Skip to content

Commit

Permalink
feat(security): restrict apis and validate urls
Browse files Browse the repository at this point in the history
  • Loading branch information
KatoakDR committed Oct 9, 2023
1 parent 1905e59 commit f8eabae
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 19 deletions.
80 changes: 62 additions & 18 deletions src/main/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { BrowserWindow, app, ipcMain, shell } from 'electron';
import { BrowserWindow, Event, app, ipcMain, shell } from 'electron';
import { join } from 'path';
import { is, optimizer, platform } from '@electron-toolkit/utils';
import { createLogger } from './logger';
Expand All @@ -11,39 +11,40 @@ const logger = createLogger('main');

app.setName('Phoenix');
app.setAppUserModelId('com.github.dragonrealms-phoenix.phoenix');
app.setAboutPanelOptions({
applicationName: app.name,
applicationVersion: app.getVersion(),
version: `${app.getVersion()}-${import.meta.env.MAIN_VITE_GIT_SHORT_HASH}`,
authors: ['Katoak'],
website: 'https://github.com/dragonrealms-phoenix/phoenix',
});

function createWindow(): void {
logger.info('creating main window');

const mainWindow = new BrowserWindow({
width: 900,
height: 670,
show: false,
show: false, // to avoid a blank window until contents loaded
autoHideMenuBar: true,
webPreferences: {
preload: join(__dirname, '../preload/index.js'),
sandbox: false,
nodeIntegration: false,
/**
* Security Best Practices
* https://www.electronjs.org/docs/latest/tutorial/security
* https://github.com/moloch--/reasonably-secure-electron
*/
allowRunningInsecureContent: false,
contextIsolation: true,
experimentalFeatures: false,
navigateOnDragDrop: false,
nodeIntegration: false,
nodeIntegrationInSubFrames: false,
nodeIntegrationInWorker: false,
safeDialogs: true,
sandbox: true,
webSecurity: true,
webviewTag: false,
},
});

mainWindow.on('ready-to-show', (): void => {
mainWindow.show();
});

mainWindow.webContents.setWindowOpenHandler((details) => {
shell.openExternal(details.url);
return { action: 'deny' };
});

// HMR for renderer base on electron-vite cli.
// Load the remote URL for development or the local html file for production.
if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
Expand All @@ -58,8 +59,8 @@ function createWindow(): void {
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then((): void => {
createWindow();
app.once('ready', () => {
app.setAsDefaultProtocolClient('app');

// Default open or close DevTools by F12 in development
// and ignore CommandOrControl + R in production.
Expand All @@ -76,11 +77,54 @@ app.whenReady().then((): void => {
}
});

// Disable or limit creation of new windows to protect app and users.
// https://www.electronjs.org/docs/latest/tutorial/security
app.on('web-contents-created', (_, contents) => {
const allowedDomains = [
/^(www.)?github\.com$/i,
/^(www.)?play\.net$/i,
/^elanthipedia\.play\.net$/i,
];

const isAllowedDomain = (domain: string): boolean => {
return allowedDomains.some((d) => d.test(domain));
};

const blockOrOpenURL = (
event: Event<Electron.WebContentsWillNavigateEventParams>,
url: string
): void => {
const domain = new URL(url).hostname;
// If the domain is allowed, open it in the user's default browser.
if (isAllowedDomain(domain)) {
logger.info('opening url in default browser', { url });
setImmediate(() => {
shell.openExternal(url);
});
} else {
logger.warn('blocked window navigation', { url });
}
event.preventDefault();
};

contents.on('will-navigate', (event, url) => {
logger.info('will-navigate', { url });
blockOrOpenURL(event, url);
});

contents.on('will-redirect', (event, url) => {
logger.info('will-redirect', { url });
blockOrOpenURL(event, url);
});
});

// Listen for events emitted by the preload api
ipcMain.handle('ping', async (): Promise<string> => {
// Return response to renderer
return 'pong';
});

createWindow();
});

// Quit when all windows are closed, except on macOS.
Expand Down
9 changes: 8 additions & 1 deletion src/renderer/src/components/HelloWorld.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
function HelloWorld(): JSX.Element {
return <p>Hello World</p>;
return (
<div>
<p>Hello World</p>
<p>
<a href="http://play.net/dr">DragonRealms</a>
</p>
</div>
);
}

export default HelloWorld;

0 comments on commit f8eabae

Please sign in to comment.