From dd495d1b9de7823758f5659a12b5463814c318d1 Mon Sep 17 00:00:00 2001 From: ienaga Date: Sat, 28 Nov 2026 18:54:55 +0900 Subject: [PATCH 1/6] electron: refuse to serve game files that were modified after the build The desktop package ships the game's HTML/JS/assets as plain files next to the ASAR, so they could be edited in place. The builder now records the SHA-256 of every shipped game file (integrity.json, inside the ASAR) and the host checks each file against it before serving it. A file that was changed or added shows an error and quits. The bytes that were checked are the bytes that are served, so a file cannot be swapped between the check and the read. --- src/electron-host.ts | 5 +++ src/integrity.ts | 30 +++++++++++++++ templates/electron/index.js | 23 +++++++++-- templates/electron/local-assets.cjs | 11 +++++- tests/integrity.test.ts | 59 +++++++++++++++++++++++++++++ 5 files changed, 124 insertions(+), 4 deletions(-) create mode 100644 src/integrity.ts create mode 100644 tests/integrity.test.ts diff --git a/src/electron-host.ts b/src/electron-host.ts index 17c8493..7b4401c 100644 --- a/src/electron-host.ts +++ b/src/electron-host.ts @@ -4,6 +4,7 @@ import path from "node:path"; import { getTemplateDir } from "./utils.js"; import type { IElectronConfig } from "./electron-config.js"; import { stageNativeBridge } from "./electron-native.js"; +import { createIntegrityManifest } from "./integrity.js"; /** Packager cleans its temporary root; never share that root with concurrent builds. */ export const withElectronPackagerTemp = async (use: (directory: string) => Promise): Promise => { @@ -51,6 +52,10 @@ export const withElectronHost = async ( runtime.icon = "desktop-icon.png"; } fs.writeFileSync(path.join(dir, "runtime-config.json"), `${JSON.stringify(runtime, null, 2)}\n`); + // The game files ship outside the ASAR as plain files. The host keeps their hashes inside the + // ASAR and refuses to serve a file that no longer matches (see templates/electron/index.js). + fs.writeFileSync(path.join(dir, "integrity.json"), + `${JSON.stringify(createIntegrityManifest(path.join(dir, "resources")))}\n`); return await use(dir); } finally { fs.rmSync(dir, { "recursive": true, "force": true }); diff --git a/src/integrity.ts b/src/integrity.ts new file mode 100644 index 0000000..fff99b7 --- /dev/null +++ b/src/integrity.ts @@ -0,0 +1,30 @@ +// ビルドしたゲームのファイルが、配布後に書き換えられていないかを確かめるための一覧を作る。 +// 一覧 (ファイルごとの SHA-256) は、各プラットフォームのホストに組み込み、ホストが読み込むたびに照合する。 +import crypto from "node:crypto"; +import fs from "node:fs"; +import path from "node:path"; + +export interface IIntegrityManifest { + algorithm: "sha256"; + files: Record; +} + +export const hashFile = (file: string): string => + crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex"); + +const walk = (directory: string): string[] => + fs.readdirSync(directory, { "withFileTypes": true }) + .flatMap((entry) => entry.isDirectory() + ? walk(path.join(directory, entry.name)) + : entry.isFile() ? [path.join(directory, entry.name)] : []); + +/** + * directory 以下の全ファイルの一覧を作る。キーは directory からの相対パス (区切りは "/")。 + */ +export const createIntegrityManifest = (directory: string): IIntegrityManifest => { + const files: Record = {}; + for (const file of walk(directory).sort()) { + files[path.relative(directory, file).split(path.sep).join("/")] = hashFile(file); + } + return { "algorithm": "sha256", files }; +}; diff --git a/templates/electron/index.js b/templates/electron/index.js index 9a29af4..09722f7 100644 --- a/templates/electron/index.js +++ b/templates/electron/index.js @@ -1,9 +1,13 @@ -const { app, BrowserWindow, Menu, net, powerMonitor, protocol, screen, session, ipcMain } = require("electron"); +const { app, BrowserWindow, Menu, dialog, net, powerMonitor, protocol, screen, session, ipcMain } = require("electron"); const path = require("node:path"); const fs = require("node:fs"); const { pathToFileURL } = require("node:url"); -const { resolveAssetPath, CSP } = require("./local-assets.cjs"); +const { resolveAssetPath, verifyAsset, CSP } = require("./local-assets.cjs"); const config = require("./runtime-config.json"); +// Hashes of the game files, recorded by the builder. Absent only when the host is run without the builder. +const integrityFile = path.join(__dirname, "integrity.json"); +const integrity = fs.existsSync(integrityFile) ? JSON.parse(fs.readFileSync(integrityFile, "utf8")) : null; +let tampered = false; const { NativeBridge, isTrustedSender } = require("./native-bridge.cjs"); let nativeBridge; const closeNativeBridge = () => nativeBridge?.close(); @@ -409,7 +413,20 @@ app.whenReady().then(async () => { const response = await net.fetch(pathToFileURL(asset).href); const headers = new Headers(response.headers); headers.set("Content-Security-Policy", CSP); - return new Response(response.body, { status: response.status, headers }); + if (!integrity) { + return new Response(response.body, { status: response.status, headers }); + } + // Serve exactly the bytes that were checked, so a file cannot be swapped between the check and the read. + const data = Buffer.from(await response.arrayBuffer()); + if (!verifyAsset(integrity, assetRoot, asset, data)) { + if (!tampered) { + tampered = true; + dialog.showErrorBox(config.appName, "The game files have been modified or are damaged. Please reinstall the game."); + setImmediate(() => app.quit()); + } + return new Response("Forbidden", { status: 403 }); + } + return new Response(data, { status: response.status, headers }); } catch { return new Response("Not found", { status: 404 }); } diff --git a/templates/electron/local-assets.cjs b/templates/electron/local-assets.cjs index 4ad8810..a497d35 100644 --- a/templates/electron/local-assets.cjs +++ b/templates/electron/local-assets.cjs @@ -1,4 +1,5 @@ const path = require("node:path"); +const crypto = require("node:crypto"); const CSP = "default-src 'self' data: blob:; script-src 'self' 'wasm-unsafe-eval'; worker-src 'self' blob: data:; style-src 'self' 'unsafe-inline'; object-src 'none'; base-uri 'none'"; const resolveAssetPath = (root, requestURL) => { @@ -21,4 +22,12 @@ const resolveAssetPath = (root, requestURL) => { return null; } }; -module.exports = { CSP, resolveAssetPath }; +// The builder records the SHA-256 of every game file at build time (integrity.json, inside the ASAR). +// A file that was changed, added or replaced after the build does not match and must not be served. +const verifyAsset = (manifest, root, file, data) => { + const name = path.relative(root, file).split(path.sep).join("/"); + const expected = Object.prototype.hasOwnProperty.call(manifest.files, name) ? manifest.files[name] : null; + return typeof expected === "string" + && crypto.createHash("sha256").update(data).digest("hex") === expected; +}; +module.exports = { CSP, resolveAssetPath, verifyAsset }; diff --git a/tests/integrity.test.ts b/tests/integrity.test.ts new file mode 100644 index 0000000..85fb874 --- /dev/null +++ b/tests/integrity.test.ts @@ -0,0 +1,59 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import crypto from "node:crypto"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { createRequire } from "node:module"; +import { createIntegrityManifest } from "../dist/integrity.js"; +import { withElectronHost } from "../dist/electron-host.js"; +import { readElectronConfig } from "../dist/electron-config.js"; +const require = createRequire(import.meta.url); +const { verifyAsset } = require("../templates/electron/local-assets.cjs"); + +const fixture = (t) => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "next2d integrity ")); + t.after(() => fs.rmSync(root, { recursive: true, force: true })); + fs.mkdirSync(path.join(root, "web/assets/js"), { recursive: true }); + fs.writeFileSync(path.join(root, "web/index.html"), ""); + fs.writeFileSync(path.join(root, "web/assets/js/app.js"), "console.log(1);"); + fs.writeFileSync(path.join(root, "package.json"), JSON.stringify({ name: "test-game", version: "1.0.0" })); + return root; +}; + +test("the manifest lists every file with its SHA-256, keyed by a forward-slash relative path", (t) => { + const root = fixture(t); + const manifest = createIntegrityManifest(path.join(root, "web")); + assert.equal(manifest.algorithm, "sha256"); + assert.deepEqual(Object.keys(manifest.files), ["assets/js/app.js", "index.html"]); + assert.equal(manifest.files["assets/js/app.js"], + crypto.createHash("sha256").update("console.log(1);").digest("hex")); +}); + +test("the Electron host accepts only files that match the manifest", (t) => { + const root = fixture(t); + const web = path.join(root, "web"); + const manifest = createIntegrityManifest(web); + const file = path.join(web, "assets/js/app.js"); + assert.equal(verifyAsset(manifest, web, file, Buffer.from("console.log(1);")), true); + // changed content + assert.equal(verifyAsset(manifest, web, file, Buffer.from("console.log(2);")), false); + // a file added after the build + assert.equal(verifyAsset(manifest, web, path.join(web, "assets/js/extra.js"), Buffer.from("x")), false); + // names that exist on Object.prototype are not files + assert.equal(verifyAsset(manifest, web, path.join(web, "constructor"), Buffer.from("")), false); +}); + +test("the generated Electron host carries the manifest of the game files it ships", async (t) => { + const root = fixture(t); + const web = path.join(root, "web"); + await withElectronHost(root, web, readElectronConfig(root), async (dir) => { + const manifest = JSON.parse(fs.readFileSync(path.join(dir, "integrity.json"), "utf8")); + assert.deepEqual(manifest, createIntegrityManifest(path.join(dir, "resources"))); + // every shipped file is listed, including the ones the builder adds + assert.ok(manifest.files["index.html"]); + assert.ok(manifest.files["assets/js/app.js"]); + assert.ok(manifest.files["desktop-icon.png"]); + assert.match(fs.readFileSync(path.join(dir, "index.js"), "utf8"), /verifyAsset\(integrity, assetRoot, asset, data\)/); + }); +}); From e0ee3b1f16fbfb4187bbfe87bac744aea94ce2cd Mon Sep 17 00:00:00 2001 From: ienaga Date: Sat, 28 Nov 2026 20:48:30 +0900 Subject: [PATCH 2/6] electron: lock the packaged runtime so the ASAR cannot be replaced or bypassed The check of the game files lives inside the ASAR, so the ASAR has to be protected too. Flip the Electron fuses on the packaged runtime: - validate the ASAR against the hash the packager embeds in the executable (macOS and Windows; Electron has no such validation on Linux) - load the app only from the ASAR - ignore ELECTRON_RUN_AS_NODE, NODE_OPTIONS and the inspect switches Verified on Windows: a patched ASAR does not start, a modified game file shows the error, the original package runs. Not yet run on macOS (the fuses are flipped before signing, with the ad-hoc signature reset on Apple silicon). --- src/electron-config.ts | 19 +++++++++++++++++++ src/electron.ts | 17 ++++++++++++++++- src/tool-packages.ts | 2 +- tests/integrity.test.ts | 19 +++++++++++++++++++ 4 files changed, 55 insertions(+), 2 deletions(-) diff --git a/src/electron-config.ts b/src/electron-config.ts index 66229f3..b39ee7f 100644 --- a/src/electron-config.ts +++ b/src/electron-config.ts @@ -161,6 +161,25 @@ export const readElectronConfig = (root: string): IElectronConfig => { }; /** JSON is the source of game metadata; secrets stay in the environment/keychain. */ +/** + * Electron fuses for a packaged game (names of @electron/fuses FuseV1Options). + * ASAR integrity validation exists on macOS and Windows only. + */ +export const createElectronFuses = (platform: string, arch: string): { + resetAdHocDarwinSignature: boolean; + options: Record; +} => ({ + // Changing the binary invalidates the ad-hoc signature Apple silicon requires; a real signature replaces it later. + "resetAdHocDarwinSignature": platform === "darwin" && arch === "arm64", + "options": { + "RunAsNode": false, + "EnableNodeOptionsEnvironmentVariable": false, + "EnableNodeCliInspectArguments": false, + "EnableEmbeddedAsarIntegrityValidation": platform === "darwin" || platform === "win32", + "OnlyLoadAppFromAsar": true + } +}); + export const createElectronPackagerOptions = ( root: string, config: IElectronConfig, os: ElectronOS, resources: string ) => { diff --git a/src/electron.ts b/src/electron.ts index 95d12e9..aac7702 100644 --- a/src/electron.ts +++ b/src/electron.ts @@ -4,7 +4,7 @@ import fs from "node:fs"; import path from "node:path"; import { createRequire } from "node:module"; import { pathToFileURL } from "node:url"; -import { createElectronPackagerOptions, readElectronConfig } from "./electron-config.js"; +import { createElectronFuses, createElectronPackagerOptions, readElectronConfig } from "./electron-config.js"; import type { ElectronOS } from "./electron-config.js"; import { ctx } from "./context.js"; import { $spawn } from "./utils.js"; @@ -73,10 +73,25 @@ export const buildElectron = async (): Promise => { const packages = await resolveToolPackages("electron"); const require = createRequire(packages["@electron/packager"]); const { packager } = await import(pathToFileURL(require.resolve("@electron/packager")).href); + const fusesRequire = createRequire(packages["@electron/fuses"]); + const { flipFuses, FuseVersion, FuseV1Options } = await import(pathToFileURL(fusesRequire.resolve("@electron/fuses")).href); + // The host inside the ASAR checks the game files (integrity.json). The fuses keep the ASAR itself + // from being replaced or bypassed: Electron validates it against the hash the packager embeds in + // the executable, loads the app only from it, and ignores the switches that run other code. + const lockRuntime = async ({ buildPath, platform, arch }: { buildPath: string; platform: string; arch: string }): Promise => { + const fuses = createElectronFuses(platform, arch); + const electron = path.join(buildPath, platform === "darwin" ? "Electron.app" : platform === "win32" ? "electron.exe" : "electron"); + await flipFuses(electron, { + "version": FuseVersion.V1, + "resetAdHocDarwinSignature": fuses.resetAdHocDarwinSignature, + ...Object.fromEntries(Object.entries(fuses.options).map(([name, value]) => [FuseV1Options[name], value])) + }); + }; // The generated host has no npm dependencies or native addons. Packager downloads // the pinned Electron runtime directly and uses its normal download cache. return await withElectronPackagerTemp(async (tmpdir) => await packager({ ...options, dir, ...target, + "afterExtract": [lockRuntime], tmpdir, "out": outDir, "electronVersion": getElectronVersion(), diff --git a/src/tool-packages.ts b/src/tool-packages.ts index 3e65f88..c6fba2d 100644 --- a/src/tool-packages.ts +++ b/src/tool-packages.ts @@ -5,7 +5,7 @@ import { spawn } from "node:child_process"; // Keep native SDKs together and pin tools independently of the game's dependencies. const packages = { - "electron": { "@electron/packager": "20.3.0" }, + "electron": { "@electron/packager": "20.3.0", "@electron/fuses": "2.1.3" }, "capacitor": { "@capacitor/cli": "8.5.2", "@capacitor/core": "8.5.2", "@capacitor/ios": "8.5.2", "@capacitor/android": "8.5.2" diff --git a/tests/integrity.test.ts b/tests/integrity.test.ts index 85fb874..803f267 100644 --- a/tests/integrity.test.ts +++ b/tests/integrity.test.ts @@ -57,3 +57,22 @@ test("the generated Electron host carries the manifest of the game files it ship assert.match(fs.readFileSync(path.join(dir, "index.js"), "utf8"), /verifyAsset\(integrity, assetRoot, asset, data\)/); }); }); + +test("packaged Electron runtimes load only the validated ASAR and ignore switches that run other code", async () => { + const { createElectronFuses } = await import("../dist/electron-config.js"); + for (const [platform, arch, validated, adHoc] of [ + ["win32", "x64", true, false], ["darwin", "arm64", true, true], + ["darwin", "x64", true, false], ["linux", "x64", false, false] + ]) { + const fuses = createElectronFuses(platform, arch); + assert.equal(fuses.resetAdHocDarwinSignature, adHoc); + assert.deepEqual(fuses.options, { + RunAsNode: false, + EnableNodeOptionsEnvironmentVariable: false, + EnableNodeCliInspectArguments: false, + // Electron validates the ASAR on macOS and Windows only + EnableEmbeddedAsarIntegrityValidation: validated, + OnlyLoadAppFromAsar: true + }); + } +}); From 57a98363239543a08e319e0f232046d417111bb6 Mon Sep 17 00:00:00 2001 From: ienaga Date: Sat, 28 Nov 2026 20:50:42 +0900 Subject: [PATCH 3/6] electron: developer tools are off by default (electron.config.json devTools) The developer tools let anyone read and change the running game. They are now disabled in the window unless electron.config.json sets "devTools": true, which also adds the usual shortcut (F12 or Ctrl/Cmd+Shift+I; there is no application menu to carry it). Meant for a development config file (NEXT2D_ELECTRON_CONFIG_FILE), not for builds that are distributed. --- docs/steam.md | 2 ++ src/electron-config.ts | 6 ++++++ src/electron-host.ts | 2 +- templates/electron/index.js | 11 +++++++++++ tests/integrity.test.ts | 17 +++++++++++++++++ 5 files changed, 37 insertions(+), 1 deletion(-) diff --git a/docs/steam.md b/docs/steam.md index 158df39..12ccb69 100644 --- a/docs/steam.md +++ b/docs/steam.md @@ -76,6 +76,7 @@ Steamは複数Depotに対応。builderは各OSに1 IDまでで、一部OSだけ | `steam.appId` / `steam.depots` | 配布時は `null` を実際のApp ID・Depot IDへ変更する。Depot IDをApp IDから推測しない。未設定のOSはアップロード対象外。 | | `steam.branch` | 反映先。既定は `internal`。 | | `macos.sign` / `macos.notarize` | ローカル検証は `false`、配布時は両方 `true`。 | +| `devTools` | 開発者ツール(コンソールなど)を開けるようにするか。既定は `false`(開けない)。`true` にすると F12 または Ctrl/Cmd+Shift+I で開閉できる。開発用の設定ファイル(`NEXT2D_ELECTRON_CONFIG_FILE`)でだけ `true` にし、配布するビルドでは指定しない。 | | `macos.localNetworkUsageDescription` | LAN通信の利用目的。指定時のみ、メインアプリとElectron HelperのInfo.plistへ`NSLocalNetworkUsageDescription`を設定する。macOSの許可操作はユーザーが行う。 | #### オーバーレイウィンドウ @@ -353,6 +354,7 @@ Edit the configuration at the game root. The version comes from the root `packag | `steam.appId` / `steam.depots` | For distribution, replace `null` with actual App/Depot IDs. Do not infer Depot IDs from the App ID. Operating systems without a Depot ID are excluded from uploading. | | `steam.branch` | Target branch; defaults to `internal`. | | `macos.sign` / `macos.notarize` | Both `false` for local testing; both `true` for distribution. | +| `devTools` | Whether the developer tools (console, etc.) can be opened. Defaults to `false` (they cannot). With `true`, F12 or Ctrl/Cmd+Shift+I toggles them. Set it only in a development config file (`NEXT2D_ELECTRON_CONFIG_FILE`); leave it out of builds you distribute. | #### Overlay window diff --git a/src/electron-config.ts b/src/electron-config.ts index b39ee7f..45cb2ac 100644 --- a/src/electron-config.ts +++ b/src/electron-config.ts @@ -23,6 +23,7 @@ export interface IElectronConfig { window: { width: number; height: number; fullscreen: boolean; overlay?: IElectronOverlayConfig; mini?: IElectronMiniConfig }; steam?: { appId: string | null; depots: Partial>; branch?: string }; macos: { sign: boolean; notarize: boolean; localNetworkUsageDescription?: string }; + devTools: boolean; } export const validateSteamId = (value: unknown): string => { @@ -55,6 +56,8 @@ export const readElectronConfig = (root: string): IElectronConfig => { "architectures": input.architectures ?? {}, "window": { "width": 1280, "height": 720, "fullscreen": false, ...input.window }, "macos": { "sign": false, "notarize": false, ...input.macos }, + // Developer tools let anyone inspect and change the running game; off unless a development config asks for them. + "devTools": input.devTools ?? false, "steam": input.steam, "nativeBridge": input.nativeBridge }; @@ -79,6 +82,9 @@ export const readElectronConfig = (root: string): IElectronConfig => { throw new Error("Electron fullscreen/sign/notarize options must be booleans."); } } + if (typeof config.devTools !== "boolean") { + throw new Error("electron.config.json devTools must be a boolean."); + } const overlay: Partial | undefined = config.window.overlay; if (overlay !== undefined) { if (!overlay || typeof overlay !== "object" || Array.isArray(overlay)) { diff --git a/src/electron-host.ts b/src/electron-host.ts index 7b4401c..b2f6ff5 100644 --- a/src/electron-host.ts +++ b/src/electron-host.ts @@ -46,7 +46,7 @@ export const withElectronHost = async ( fs.writeFileSync(path.join(dir, "package.json"), `${JSON.stringify(pkg, null, 2)}\n`); fs.cpSync(resources, path.join(dir, "resources"), { "recursive": true }); const nativeBridge = config.nativeBridge ? stageNativeBridge(root, dir, config.nativeBridge, target ?? "") : undefined; - const runtime = { "appId": config.appId, "appName": config.appName, "window": config.window, "icon": "", nativeBridge }; + const runtime = { "appId": config.appId, "appName": config.appName, "window": config.window, "icon": "", "devTools": config.devTools, nativeBridge }; if (config.icons.linux) { fs.copyFileSync(path.resolve(root, config.icons.linux), path.join(dir, "resources/desktop-icon.png")); runtime.icon = "desktop-icon.png"; diff --git a/templates/electron/index.js b/templates/electron/index.js index 09722f7..ccdec86 100644 --- a/templates/electron/index.js +++ b/templates/electron/index.js @@ -304,6 +304,8 @@ const createWindow = async () => { } : {}), webPreferences: { nodeIntegration: false, contextIsolation: true, sandbox: true, + // Developer tools can read and change the running game. Off unless electron.config.json sets devTools. + devTools: config.devTools === true, ...(preloadFlags.length ? { preload: path.join(__dirname, "preload.cjs"), additionalArguments: preloadFlags } : {}), ...(config.nativeBridge ? { backgroundThrottling: config.nativeBridge.backgroundThrottling ?? false } : {}) } @@ -362,6 +364,15 @@ const createWindow = async () => { } } mainWindow.webContents.setWindowOpenHandler(() => ({ action: "deny" })); + if (config.devTools === true) { + // No application menu carries the usual shortcut, so offer it here: F12 or Ctrl/Cmd+Shift+I. + mainWindow.webContents.on("before-input-event", (event, input) => { + if (input.type === "keyDown" && (input.key === "F12" || ((input.control || input.meta) && input.shift && input.key.toLowerCase() === "i"))) { + event.preventDefault(); + mainWindow.webContents.toggleDevTools(); + } + }); + } mainWindow.webContents.on("will-navigate", (event, url) => { if (!resolveAssetPath(assetRoot, url)) { event.preventDefault(); diff --git a/tests/integrity.test.ts b/tests/integrity.test.ts index 803f267..12043ac 100644 --- a/tests/integrity.test.ts +++ b/tests/integrity.test.ts @@ -76,3 +76,20 @@ test("packaged Electron runtimes load only the validated ASAR and ignore switche }); } }); + +test("developer tools are off unless the Electron config turns them on", async (t) => { + const root = fixture(t); + const web = path.join(root, "web"); + assert.equal(readElectronConfig(root).devTools, false); + await withElectronHost(root, web, readElectronConfig(root), async (dir) => { + assert.equal(JSON.parse(fs.readFileSync(path.join(dir, "runtime-config.json"), "utf8")).devTools, false); + assert.match(fs.readFileSync(path.join(dir, "index.js"), "utf8"), /devTools: config\.devTools === true/); + }); + fs.writeFileSync(path.join(root, "electron.config.json"), JSON.stringify({ devTools: true })); + assert.equal(readElectronConfig(root).devTools, true); + await withElectronHost(root, web, readElectronConfig(root), async (dir) => { + assert.equal(JSON.parse(fs.readFileSync(path.join(dir, "runtime-config.json"), "utf8")).devTools, true); + }); + fs.writeFileSync(path.join(root, "electron.config.json"), JSON.stringify({ devTools: "yes" })); + assert.throws(() => readElectronConfig(root), /devTools must be a boolean/); +}); From ea3bcd17cedfb3d0b2abfe0e0e07c130e0207e89 Mon Sep 17 00:00:00 2001 From: ienaga Date: Sat, 28 Nov 2026 20:56:08 +0900 Subject: [PATCH 4/6] host core / xbox: refuse script files that were modified after the build The native host now checks the game's script files (.js .mjs .html .json .wasm) against SHA-256 hashes recorded at build time: - platform/AssetIntegrity.h (header only): SHA-256, the list of hashes and the check. A listed file must match; a script that is not listed is not read. Media files are not checked, so nothing is hashed on their load path. - AssetLoader (ReadBinary / ReadText / OpenStream / entry module), V8Runtime::LoadModule and the host scripts (bootstrap.js) go through it. - Host core API: next2d_host_set_asset_integrity(manifest), called before next2d_host_create. Without it nothing is checked (as before). - Xbox: the builder writes the hashes of the embedded scripts into src/AssetIntegrityManifest.h, so they are compiled into the executable. Unit test: tests/integrity_test.cpp (SHA-256 test vectors and the rules), added to CI and check_local.sh. The Xbox executable itself (main.cpp) is not built here; it is covered by the Xbox CI build. --- .github/workflows/xbox-host-ci.yml | 8 + src/integrity.ts | 54 ++++- src/xbox.ts | 7 + templates/xbox/src/AssetIntegrityManifest.h | 14 ++ templates/xbox/src/AssetLoader.cpp | 32 ++- templates/xbox/src/core/HostCore.cpp | 10 + templates/xbox/src/core/next2d_host_core.h | 10 + templates/xbox/src/main.cpp | 25 +- templates/xbox/src/platform/AssetIntegrity.h | 235 +++++++++++++++++++ templates/xbox/src/v8/V8Runtime.cpp | 13 + templates/xbox/tests/check_local.sh | 5 + templates/xbox/tests/integrity_test.cpp | 97 ++++++++ tests/integrity.test.ts | 18 ++ 13 files changed, 520 insertions(+), 8 deletions(-) create mode 100644 templates/xbox/src/AssetIntegrityManifest.h create mode 100644 templates/xbox/src/platform/AssetIntegrity.h create mode 100644 templates/xbox/tests/integrity_test.cpp diff --git a/.github/workflows/xbox-host-ci.yml b/.github/workflows/xbox-host-ci.yml index 746450f..f98a06f 100644 --- a/.github/workflows/xbox-host-ci.yml +++ b/.github/workflows/xbox-host-ci.yml @@ -111,6 +111,14 @@ jobs: if errorlevel 1 exit /b 1 raster_test.exe + - name: Build & run asset integrity tests + shell: cmd + working-directory: templates/xbox + run: | + cl /nologo /utf-8 /std:c++17 /EHsc /W3 /O1 /Isrc tests\integrity_test.cpp /Fe:integrity_test.exe + if errorlevel 1 exit /b 1 + integrity_test.exe + - name: Build & run stb safety regression tests shell: cmd working-directory: templates/xbox diff --git a/src/integrity.ts b/src/integrity.ts index fff99b7..c9b572b 100644 --- a/src/integrity.ts +++ b/src/integrity.ts @@ -9,8 +9,10 @@ export interface IIntegrityManifest { files: Record; } -export const hashFile = (file: string): string => - crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex"); +export const hashData = (data: Buffer | string): string => + crypto.createHash("sha256").update(data).digest("hex"); + +export const hashFile = (file: string): string => hashData(fs.readFileSync(file)); const walk = (directory: string): string[] => fs.readdirSync(directory, { "withFileTypes": true }) @@ -28,3 +30,51 @@ export const createIntegrityManifest = (directory: string): IIntegrityManifest = } return { "algorithm": "sha256", files }; }; + +/** + * 動作を決めるファイル (スクリプト類) かどうか。ネイティブのホスト (templates/xbox の + * platform/AssetIntegrity.h) は、この種類のファイルを一覧と照合し、一覧に無いものは読まない。 + * 画像や音声は対象にしない (読み込みのたびに全体のハッシュを取る時間をかけないため)。 + */ +export const isCodeFile = (key: string): boolean => + [".js", ".mjs", ".html", ".json", ".wasm"].includes(path.posix.extname(key).toLowerCase()); + +/** + * ネイティブのホストに渡す一覧の行。1 行 1 ファイルで "<空白 2 つ><キー>" (sha256sum と同じ)。 + * 対象はスクリプト類だけ。 + */ +export const createIntegrityLines = (entries: [string, Buffer][]): string[] => + entries + .filter(([key]) => isCodeFile(key)) + .map(([key, data]) => { + if (/[\r\n]/.test(key)) { + throw new Error(`A file name with a line break cannot be listed for the integrity check: ${JSON.stringify(key)}`); + } + return `${hashData(data)} ${key}`; + }) + .sort(); + +/** + * 一覧を C++ のヘッダにする (templates/xbox/src/AssetIntegrityManifest.h を置き換える内容)。 + * 1 ファイルを 1 つの文字列リテラルにして、コンパイラの文字列リテラルの長さの上限に当たらないようにする。 + */ +export const renderIntegrityHeader = (lines: string[]): string => { + const literal = (line: string): string => + ` "${line.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}",`; + return [ + "#pragma once", + "", + "// Generated by @next2d/builder. SHA-256 of the game's script files at build time.", + "// The host refuses to load a listed file whose content differs, and any script that is not listed.", + "", + "namespace next2d {", + "", + "inline const char* const kAssetIntegrityLines[] = {", + ...lines.map(literal), + " nullptr", + "};", + "", + "} // namespace next2d", + "" + ].join("\n"); +}; diff --git a/src/xbox.ts b/src/xbox.ts index 8b1580b..359a296 100644 --- a/src/xbox.ts +++ b/src/xbox.ts @@ -9,6 +9,7 @@ import cp from "child_process"; import { loadProjectVite } from "./project-vite.js"; import { ctx } from "./context.js"; import { getTemplateDir } from "./utils.js"; +import { createIntegrityLines, renderIntegrityHeader } from "./integrity.js"; import { XBOX_DIR_NAME, XBOX_CONFIG_NAME, @@ -292,6 +293,12 @@ const embedXboxAssets = async (): Promise => } fs.writeFileSync(pakPath, pak); + // 埋め込んだスクリプト類の SHA-256 を、ホストの実行コードへ組み込む (ヘッダを置き換える)。 + // ホストは読み込むたびに照合し、書き換えられたものや一覧に無いスクリプトを実行しない。 + const integrityLines: string[] = createIntegrityLines(pakEntries); + fs.writeFileSync(`${xboxDir}/src/AssetIntegrityManifest.h`, renderIntegrityHeader(integrityLines), "utf8"); + console.log(pc.green(`Recorded the integrity of ${integrityLines.length} script file(s) in the host.`)); + // rc.exe が assets.pak を RCDATA "N2DASSETS" として取り込む .rc を生成する。 fs.writeFileSync(rcPath, renderAssetsRc(path.resolve(pakPath)), "utf8"); diff --git a/templates/xbox/src/AssetIntegrityManifest.h b/templates/xbox/src/AssetIntegrityManifest.h new file mode 100644 index 0000000..7472df8 --- /dev/null +++ b/templates/xbox/src/AssetIntegrityManifest.h @@ -0,0 +1,14 @@ +#pragma once + +// ゲームのファイルの照合に使う一覧 (platform/AssetIntegrity.h)。 +// builder が書き出すときに、このファイルを実際の一覧で置き換える。 +// ここにあるのは、builder を通さずにホストだけをビルドするときの空の一覧 (照合しない)。 +// 1 要素が 1 ファイルで "<空白 2 つ><キー>"。最後は nullptr。 + +namespace next2d { + +inline const char* const kAssetIntegrityLines[] = { + nullptr +}; + +} // namespace next2d diff --git a/templates/xbox/src/AssetLoader.cpp b/templates/xbox/src/AssetLoader.cpp index 7b2126c..57ffd8b 100644 --- a/templates/xbox/src/AssetLoader.cpp +++ b/templates/xbox/src/AssetLoader.cpp @@ -1,4 +1,5 @@ #include "AssetLoader.h" +#include "platform/AssetIntegrity.h" #include "EmbeddedAssets.h" #include @@ -135,7 +136,12 @@ std::optional> AssetLoader::ReadBinary(const std::string& u } // 埋め込みモード優先: exe 内 pak に同じ相対キーがあれば実ファイルより先に返す。 - if (const auto* embedded = GetEmbeddedAsset(RelativeKey(url))) { + const std::string key = RelativeKey(url); + if (const auto* embedded = GetEmbeddedAsset(key)) { + // ビルドの後に書き換えられたファイルは使わない (platform/AssetIntegrity.h) + if (!integrity::Verify(key, embedded->data(), embedded->size())) { + return std::nullopt; + } return *embedded; } @@ -158,7 +164,10 @@ std::optional> AssetLoader::ReadBinary(const std::string& u std::chrono::steady_clock::now() - started).count(); if (perf && ms >= 10) { std::cerr << "[HostCore] slow read: " << ms << " ms, " << size << " bytes, " - << RelativeKey(url) << std::endl; + << key << std::endl; + } + if (!integrity::Verify(key, buffer.data(), buffer.size())) { + return std::nullopt; } return buffer; } @@ -221,6 +230,10 @@ std::unique_ptr AssetLoader::OpenStream(const std::string& url) co if (url.rfind("data:", 0) == 0) { return nullptr; } + // 照合が要るファイルは、全体を読んでからでないと使えない (呼び出し側は ReadBinary へ回る) + if (integrity::NeedsCheck(RelativeKey(url))) { + return nullptr; + } // 埋め込みモード優先 (ReadBinary と同じ順)。埋め込み資材は終了まで解放されない。 if (const auto* embedded = GetEmbeddedAsset(RelativeKey(url))) { return std::make_unique(embedded->data(), embedded->size()); @@ -234,7 +247,11 @@ std::unique_ptr AssetLoader::OpenStream(const std::string& url) co std::optional AssetLoader::ReadText(const std::string& url) const { - if (const auto* embedded = GetEmbeddedAsset(RelativeKey(url))) { + const std::string key = RelativeKey(url); + if (const auto* embedded = GetEmbeddedAsset(key)) { + if (!integrity::Verify(key, embedded->data(), embedded->size())) { + return std::nullopt; + } return std::string(embedded->begin(), embedded->end()); } @@ -245,7 +262,11 @@ std::optional AssetLoader::ReadText(const std::string& url) const } std::ostringstream oss; oss << ifs.rdbuf(); - return oss.str(); + std::string text = oss.str(); + if (!integrity::Verify(key, text)) { + return std::nullopt; + } + return text; } std::optional AssetLoader::ResolveEntryModule() const @@ -265,6 +286,9 @@ std::optional AssetLoader::ResolveEntryModule() const oss << ifs.rdbuf(); html = oss.str(); } + if (!integrity::Verify("index.html", html)) { + return std::nullopt; + } // type="module" を含む