Safe defaults for the main process of an Electron app
An Electron page can get Node.js, open new windows, go to any site and ask for the camera. @mark1russell7/desktop closes each of these doors with one function call. Each demo on this page runs the real functions of the package in your browser.
- One origin. The window stays on its page.
- No Node.js. A sandbox and context isolation.
- No path tricks.
app://serves one folder. - No permissions. No camera, microphone or download.
pnpm add @mark1russell7/desktop
1. Where can a window go?
The window of the app shows app://page/index.html. A link or a script tries to go to another address. restrictNavigation sends the address to a rule, and stops the navigation when the rule says no. Type an address, or pick one.
restrictNavigation(contents, (url) => allowsNavigation(page, url))
2. Which file does app://page/ serve?
The main process serves the folder /opt/notes/page under app://page/. The file /opt/notes/package.json is one folder up. pageHandler serves only the files in the folder, each with the content security policy. Try to get out of the folder.
protocol.handle("app", pageHandler(folder, { contentType }))
3. The content security policy
Each file of the page gets this policy. The page loads only its own scripts and styles. It has no inline script, no connection to a server and no frame.
4. The options of a window
The caller sets the size, the title and the other options. The web preferences are not the caller's choice: the page has no Node.js, a sandbox and context isolation. Try to turn on Node.js.
new BrowserWindow(windowOptions(preload, options))
5. Why did the load fail?
The event did-fail-load gives a Chromium net error code. failureOf gives the reason, so the app knows if another try can help.
6. Can the main process trust this message?
A message from the page is data that the main process does not trust. The handler checks the type of the message with isMessage, and the frame that sent it with allowsSender.
7. Give the keys back to the app
A click on the view of a site gives the keys to the site. returnsKeys tells when a key press gives them back: Escape with no modifier key. Click the box and press keys, or use the buttons.
8. No permission, no download
refusePermissions and refuseDownloads set the handlers of a session. The demo applies them to a fake session. Ask for a permission or start a download.
Use it
Call the rules one time, when the app starts. The README tells each function.
app.on("web-contents-created", (_event, contents) => {
refuseWebviews(contents);
denyWindows(contents);
restrictNavigation(contents, (url) => allowsNavigation(page, url));
});
refusePermissions(session.defaultSession);
refuseDownloads(session.defaultSession);
Releases shows each version, and Status shows the open work. The demos use the POSIX rules for paths, as Linux and macOS do.