Skip to content

Commit

Permalink
feat: add integration for @electron/fuses (#8588)
Browse files Browse the repository at this point in the history
  • Loading branch information
mmaietta authored Oct 13, 2024
1 parent c848430 commit 8434e10
Show file tree
Hide file tree
Showing 28 changed files with 508 additions and 5 deletions.
5 changes: 5 additions & 0 deletions .changeset/two-rice-wash.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"app-builder-lib": minor
---

feat: adding integration with @electron/fuses
1 change: 1 addition & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ nav:
- Multi Platform Build: multi-platform-build.md

- Tutorials:
- Configuring Electron Fuses: tutorials/adding-electron-fuses.md
- Loading App Dependencies Manually: tutorials/loading-app-dependencies-manually.md
- Two package.json Structure: tutorials/two-package-structure.md
- macOS Kernel Extensions: tutorials/macos-kernel-extensions.md
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"docs:prebuild": "docker build -t mkdocs-dockerfile -f mkdocs-dockerfile . ",
"docs:build": "pnpm compile && node scripts/renderer/out/typedoc2html.js",
"docs:mkdocs": "docker run --rm -v ${PWD}:/docs -v ${PWD}/site:/site mkdocs-dockerfile build",
"docs:preview": "open ./site/index.html",
"docs:all": "pnpm docs:prebuild && pnpm docs:build && pnpm docs:mkdocs",
"prepare": "husky install"
},
Expand Down
1 change: 1 addition & 0 deletions packages/app-builder-lib/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
"homepage": "https://github.com/electron-userland/electron-builder",
"dependencies": {
"@develar/schema-utils": "~2.6.5",
"@electron/fuses": "^1.8.0",
"@electron/asar": "^3.2.13",
"@electron/notarize": "2.5.0",
"@electron/osx-sign": "1.3.1",
Expand Down
54 changes: 54 additions & 0 deletions packages/app-builder-lib/scheme.json
Original file line number Diff line number Diff line change
Expand Up @@ -1284,6 +1284,49 @@
},
"type": "object"
},
"FuseOptionsV1": {
"additionalProperties": false,
"description": "All options come from [@electron/fuses](https://github.com/electron/fuses)\nRef: https://raw.githubusercontent.com/electron/electron/refs/heads/main/docs/tutorial/fuses.md",
"properties": {
"enableCookieEncryption": {
"description": "The cookieEncryption fuse toggles whether the cookie store on disk is encrypted using OS level cryptography keys. By default the sqlite database that Chromium uses to store cookies stores the values in plaintext. If you wish to ensure your apps cookies are encrypted in the same way Chrome does then you should enable this fuse. Please note it is a one-way transition, if you enable this fuse existing unencrypted cookies will be encrypted-on-write but if you then disable the fuse again your cookie store will effectively be corrupt and useless. Most apps can safely enable this fuse.",
"type": "boolean"
},
"enableEmbeddedAsarIntegrityValidation": {
"description": "The embeddedAsarIntegrityValidation fuse toggles an experimental feature on macOS that validates the content of the `app.asar` file when it is loaded. This feature is designed to have a minimal performance impact but may marginally slow down file reads from inside the `app.asar` archive.\nCurrently, ASAR integrity checking is supported on:\n- macOS as of electron>=16.0.0\n- Windows as of electron>=30.0.0\nFor more information on how to use asar integrity validation please read the [Asar Integrity](https://github.com/electron/electron/blob/main/docs/tutorial/asar-integrity.md) documentation.",
"type": "boolean"
},
"enableNodeCliInspectArguments": {
"description": "The nodeCliInspect fuse toggles whether the `--inspect`, `--inspect-brk`, etc. flags are respected or not. When disabled it also ensures that `SIGUSR1` signal does not initialize the main process inspector. Most apps can safely disable this fuse.",
"type": "boolean"
},
"enableNodeOptionsEnvironmentVariable": {
"description": "The nodeOptions fuse toggles whether the [`NODE_OPTIONS`](https://nodejs.org/api/cli.html#node_optionsoptions) and [`NODE_EXTRA_CA_CERTS`](https://github.com/nodejs/node/blob/main/doc/api/cli.md#node_extra_ca_certsfile) environment variables are respected. The `NODE_OPTIONS` environment variable can be used to pass all kinds of custom options to the Node.js runtime and isn't typically used by apps in production. Most apps can safely disable this fuse.",
"type": "boolean"
},
"grantFileProtocolExtraPrivileges": {
"description": "The grantFileProtocolExtraPrivileges fuse changes whether pages loaded from the `file://` protocol are given privileges beyond what they would receive in a traditional web browser. This behavior was core to Electron apps in original versions of Electron but is no longer required as apps should be [serving local files from custom protocols](https://github.com/electron/electron/blob/main/docs/tutorial/security.md#18-avoid-usage-of-the-file-protocol-and-prefer-usage-of-custom-protocols) now instead. If you aren't serving pages from `file://` you should disable this fuse.\nThe extra privileges granted to the `file://` protocol by this fuse are incompletely documented below:\n- `file://` protocol pages can use `fetch` to load other assets over `file://`\n- `file://` protocol pages can use service workers\n- `file://` protocol pages have universal access granted to child frames also running on `file://` protocols regardless of sandbox settings",
"type": "boolean"
},
"loadBrowserProcessSpecificV8Snapshot": {
"description": "The loadBrowserProcessSpecificV8Snapshot fuse changes which V8 snapshot file is used for the browser process. By default Electron's processes will all use the same V8 snapshot file. When this fuse is enabled the browser process uses the file called `browser_v8_context_snapshot.bin` for its V8 snapshot. The other processes will use the V8 snapshot file that they normally do.",
"type": "boolean"
},
"onlyLoadAppFromAsar": {
"description": "The onlyLoadAppFromAsar fuse changes the search system that Electron uses to locate your app code. By default Electron will search in the following order `app.asar` -> `app` -> `default_app.asar`. When this fuse is enabled the search order becomes a single entry `app.asar` thus ensuring that when combined with the `embeddedAsarIntegrityValidation` fuse it is impossible to load non-validated code.",
"type": "boolean"
},
"resetAdHocDarwinSignature": {
"description": "Resets the app signature, specifically used for macOS.\nNote: This should be unneeded since electron-builder signs the app directly after flipping the fuses.\nRef: https://github.com/electron/fuses?tab=readme-ov-file#apple-silicon",
"type": "boolean"
},
"runAsNode": {
"description": "The runAsNode fuse toggles whether the `ELECTRON_RUN_AS_NODE` environment variable is respected or not. Please note that if this fuse is disabled then `process.fork` in the main process will not function as expected as it depends on this environment variable to function. Instead, we recommend that you use [Utility Processes](https://github.com/electron/electron/blob/main/docs/api/utility-process.md), which work for many use cases where you need a standalone Node.js process (like a Sqlite server process or similar scenarios).",
"type": "boolean"
}
},
"type": "object"
},
"GenericServerOptions": {
"additionalProperties": false,
"description": "Generic (any HTTP(S) server) options.\nIn all publish options [File Macros](./file-patterns.md#file-macros) are supported.",
Expand Down Expand Up @@ -7023,6 +7066,17 @@
"$ref": "#/definitions/ElectronDownloadOptions",
"description": "The [electron-download](https://github.com/electron-userland/electron-download#usage) options."
},
"electronFuses": {
"anyOf": [
{
"$ref": "#/definitions/FuseOptionsV1"
},
{
"type": "null"
}
],
"description": "Options to pass to `@electron/fuses`\nRef: https://github.com/electron/fuses"
},
"electronLanguages": {
"anyOf": [
{
Expand Down
62 changes: 62 additions & 0 deletions packages/app-builder-lib/src/configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,12 @@ export interface CommonConfiguration {
* @default true
*/
readonly removePackageKeywords?: boolean

/**
* Options to pass to `@electron/fuses`
* Ref: https://github.com/electron/fuses
*/
readonly electronFuses?: FuseOptionsV1 | null
}
export interface Configuration extends CommonConfiguration, PlatformSpecificBuildOptions, Hooks {
/**
Expand Down Expand Up @@ -375,3 +381,59 @@ export interface MetadataDirectories {
*/
readonly app?: string | null
}

/**
* All options come from [@electron/fuses](https://github.com/electron/fuses)
* Ref: https://raw.githubusercontent.com/electron/electron/refs/heads/main/docs/tutorial/fuses.md
*/
export interface FuseOptionsV1 {
/**
*The runAsNode fuse toggles whether the `ELECTRON_RUN_AS_NODE` environment variable is respected or not. Please note that if this fuse is disabled then `process.fork` in the main process will not function as expected as it depends on this environment variable to function. Instead, we recommend that you use [Utility Processes](https://github.com/electron/electron/blob/main/docs/api/utility-process.md), which work for many use cases where you need a standalone Node.js process (like a Sqlite server process or similar scenarios).
*/
runAsNode?: boolean
/**
* The cookieEncryption fuse toggles whether the cookie store on disk is encrypted using OS level cryptography keys. By default the sqlite database that Chromium uses to store cookies stores the values in plaintext. If you wish to ensure your apps cookies are encrypted in the same way Chrome does then you should enable this fuse. Please note it is a one-way transition, if you enable this fuse existing unencrypted cookies will be encrypted-on-write but if you then disable the fuse again your cookie store will effectively be corrupt and useless. Most apps can safely enable this fuse.
*/
enableCookieEncryption?: boolean
/**
* The nodeOptions fuse toggles whether the [`NODE_OPTIONS`](https://nodejs.org/api/cli.html#node_optionsoptions) and [`NODE_EXTRA_CA_CERTS`](https://github.com/nodejs/node/blob/main/doc/api/cli.md#node_extra_ca_certsfile) environment variables are respected. The `NODE_OPTIONS` environment variable can be used to pass all kinds of custom options to the Node.js runtime and isn't typically used by apps in production. Most apps can safely disable this fuse.
*/
enableNodeOptionsEnvironmentVariable?: boolean
/**
* The nodeCliInspect fuse toggles whether the `--inspect`, `--inspect-brk`, etc. flags are respected or not. When disabled it also ensures that `SIGUSR1` signal does not initialize the main process inspector. Most apps can safely disable this fuse.
*/
enableNodeCliInspectArguments?: boolean
/**
* The embeddedAsarIntegrityValidation fuse toggles an experimental feature on macOS that validates the content of the `app.asar` file when it is loaded. This feature is designed to have a minimal performance impact but may marginally slow down file reads from inside the `app.asar` archive.
* Currently, ASAR integrity checking is supported on:
*
* - macOS as of electron>=16.0.0
* - Windows as of electron>=30.0.0
*
* For more information on how to use asar integrity validation please read the [Asar Integrity](https://github.com/electron/electron/blob/main/docs/tutorial/asar-integrity.md) documentation.
*/
enableEmbeddedAsarIntegrityValidation?: boolean
/**
* The onlyLoadAppFromAsar fuse changes the search system that Electron uses to locate your app code. By default Electron will search in the following order `app.asar` -> `app` -> `default_app.asar`. When this fuse is enabled the search order becomes a single entry `app.asar` thus ensuring that when combined with the `embeddedAsarIntegrityValidation` fuse it is impossible to load non-validated code.
*/
onlyLoadAppFromAsar?: boolean
/**
* The loadBrowserProcessSpecificV8Snapshot fuse changes which V8 snapshot file is used for the browser process. By default Electron's processes will all use the same V8 snapshot file. When this fuse is enabled the browser process uses the file called `browser_v8_context_snapshot.bin` for its V8 snapshot. The other processes will use the V8 snapshot file that they normally do.
*/
loadBrowserProcessSpecificV8Snapshot?: boolean
/**
* The grantFileProtocolExtraPrivileges fuse changes whether pages loaded from the `file://` protocol are given privileges beyond what they would receive in a traditional web browser. This behavior was core to Electron apps in original versions of Electron but is no longer required as apps should be [serving local files from custom protocols](https://github.com/electron/electron/blob/main/docs/tutorial/security.md#18-avoid-usage-of-the-file-protocol-and-prefer-usage-of-custom-protocols) now instead. If you aren't serving pages from `file://` you should disable this fuse.
* The extra privileges granted to the `file://` protocol by this fuse are incompletely documented below:
*
* - `file://` protocol pages can use `fetch` to load other assets over `file://`
* - `file://` protocol pages can use service workers
* - `file://` protocol pages have universal access granted to child frames also running on `file://` protocols regardless of sandbox settings
*/
grantFileProtocolExtraPrivileges?: boolean
/**
* Resets the app signature, specifically used for macOS.
* Note: This should be unneeded since electron-builder signs the app directly after flipping the fuses.
* Ref: https://github.com/electron/fuses?tab=readme-ov-file#apple-silicon
*/
resetAdHocDarwinSignature?: boolean
}
13 changes: 12 additions & 1 deletion packages/app-builder-lib/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,18 @@ export {
CompressionLevel,
} from "./core"
export { getArchSuffix, Arch, archFromString } from "builder-util"
export { CommonConfiguration, Configuration, AfterPackContext, MetadataDirectories, BeforePackContext, AfterExtractContext, Hooks, Hook, PackContext } from "./configuration"
export {
CommonConfiguration,
Configuration,
AfterPackContext,
MetadataDirectories,
BeforePackContext,
AfterExtractContext,
Hooks,
Hook,
PackContext,
FuseOptionsV1,
} from "./configuration"
export { ElectronBrandingOptions, ElectronDownloadOptions, ElectronPlatformName } from "./electron/ElectronFramework"
export { PlatformSpecificBuildOptions, AsarOptions, FileSet, Protocol, ReleaseInfo, FilesBuildOptions } from "./options/PlatformSpecificBuildOptions"
export { FileAssociation } from "./options/FileAssociation"
Expand Down
68 changes: 68 additions & 0 deletions packages/app-builder-lib/src/platformPackager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
Configuration,
ElectronPlatformName,
FileAssociation,
LinuxPackager,
Packager,
PackagerOptions,
Platform,
Expand All @@ -30,6 +31,8 @@ import { executeAppBuilderAsJson } from "./util/appBuilder"
import { computeFileSets, computeNodeModuleFileSets, copyAppFiles, ELECTRON_COMPILE_SHIM_FILENAME, transformFiles } from "./util/appFileCopier"
import { expandMacro as doExpandMacro } from "./util/macroExpander"
import { resolveFunction } from "./util/resolve"
import { flipFuses, FuseConfig, FuseV1Config, FuseV1Options, FuseVersion } from "@electron/fuses"
import { FuseOptionsV1 } from "./configuration"

export abstract class PlatformPackager<DC extends PlatformSpecificBuildOptions> {
get packagerOptions(): PackagerOptions {
Expand Down Expand Up @@ -327,11 +330,76 @@ export abstract class PlatformPackager<DC extends PlatformSpecificBuildOptions>

const isAsar = asarOptions != null
await this.sanityCheckPackage(appOutDir, isAsar, framework, !!this.config.disableSanityCheckAsar)

// the fuses MUST be flipped right before signing
if (this.config.electronFuses != null) {
const fuseConfig = this.generateFuseConfig(this.config.electronFuses)
await this.addElectronFuses(packContext, fuseConfig)
}
if (sign) {
await this.doSignAfterPack(outDir, appOutDir, platformName, arch, platformSpecificBuildOptions, targets)
}
}

private generateFuseConfig(fuses: FuseOptionsV1): FuseV1Config {
const config: FuseV1Config = {
version: FuseVersion.V1,
resetAdHocDarwinSignature: fuses.resetAdHocDarwinSignature,
}
// this is annoying, but we must filter out undefined entries because some older electron versions will receive `the fuse wire in this version of Electron is not long enough` even if entry is set undefined
if (fuses.runAsNode != null) {
config[FuseV1Options.RunAsNode] = fuses.runAsNode
}
if (fuses.enableCookieEncryption != null) {
config[FuseV1Options.EnableCookieEncryption] = fuses.enableCookieEncryption
}
if (fuses.enableNodeOptionsEnvironmentVariable != null) {
config[FuseV1Options.EnableNodeOptionsEnvironmentVariable] = fuses.enableNodeOptionsEnvironmentVariable
}
if (fuses.enableNodeCliInspectArguments != null) {
config[FuseV1Options.EnableNodeCliInspectArguments] = fuses.enableNodeCliInspectArguments
}
if (fuses.enableEmbeddedAsarIntegrityValidation != null) {
config[FuseV1Options.EnableEmbeddedAsarIntegrityValidation] = fuses.enableEmbeddedAsarIntegrityValidation
}
if (fuses.onlyLoadAppFromAsar != null) {
config[FuseV1Options.OnlyLoadAppFromAsar] = fuses.onlyLoadAppFromAsar
}
if (fuses.loadBrowserProcessSpecificV8Snapshot != null) {
config[FuseV1Options.LoadBrowserProcessSpecificV8Snapshot] = fuses.loadBrowserProcessSpecificV8Snapshot
}
if (fuses.grantFileProtocolExtraPrivileges != null) {
config[FuseV1Options.GrantFileProtocolExtraPrivileges] = fuses.grantFileProtocolExtraPrivileges
}
return config
}

/**
* Use `AfterPackContext` here to keep available for public API
* @param {AfterPackContext} context
* @param {FuseConfig} fuses
*
* Can be used in `afterPack` hook for custom fuse logic like below. It's an alternative approach if one wants to override electron-builder's @electron/fuses version
* ```
* await context.packager.addElectronFuses(context, { ... })
* ```
*/
public async addElectronFuses(context: AfterPackContext, fuses: FuseConfig) {
const { appOutDir, electronPlatformName } = context

const ext = {
darwin: ".app",
win32: ".exe",
linux: "",
}[electronPlatformName]

const executableName = this instanceof LinuxPackager ? this.executableName : this.appInfo.productFilename
const electronBinaryPath = path.join(appOutDir, `${executableName}${ext}`)

log.info({ electronPath: log.filePath(electronBinaryPath) }, "executing @electron/fuses")
return flipFuses(electronBinaryPath, fuses)
}

protected async doSignAfterPack(outDir: string, appOutDir: string, platformName: ElectronPlatformName, arch: Arch, platformSpecificBuildOptions: DC, targets: Array<Target>) {
const asarOptions = await this.computeAsarOptions(platformSpecificBuildOptions)
const isAsar = asarOptions != null
Expand Down
Loading

0 comments on commit 8434e10

Please sign in to comment.