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/docs/capacitor.md b/docs/capacitor.md index f463ecb..c04fe27 100644 --- a/docs/capacitor.md +++ b/docs/capacitor.md @@ -90,6 +90,20 @@ Capacitorの `cap run` を使う場合は `--build` を `--preview` に置き換 テンプレートのnpmスクリプト `open:ios` / `open:android` / `build:ios` / `build:android` も使用できる。 環境指定は `npm run build:ios -- --env prd` のように渡す。 +### 補足:書き換えの検知 + +`sync` / `open` / `build` は、アプリに入れたスクリプト類(`.js` `.mjs` `.html` `.json` `.wasm`)と Capacitor の設定ファイルの SHA-256 を記録し、起動時に照合するコードをネイティブプロジェクトへ入れる。ビルドの後に書き換えられたファイルや、後から足されたスクリプトがあると、アプリは起動しない。画像や音声は対象外。 + +| OS | 入るもの | ゲームのリポジトリに残る変更 | +|---|---|---| +| Android | `app/src/main/java/app/next2d/integrity/` に照合のクラスと一覧(一覧は同じ場所の `.gitignore` で除外)。`AndroidManifest.xml` に `` を 1 つ | `AndroidManifest.xml` と照合のクラス(どちらも初回だけ) | +| iOS | `AppDelegate.swift` の末尾に照合の処理と、起動時の呼び出し 1 行。一覧は `App/App/public/next2d-integrity.txt` | `AppDelegate.swift`(初回だけ) | + +- 一覧は `sync` のたびに、Capacitor がコピーした後のファイルから作り直す。IDE から Web 資材だけを入れ替えた(`cap copy` など)場合は一覧と合わなくなり、起動しなくなる。builder の `sync` / `build` をやり直すこと。 +- `preview`(`cap run`)は照合しない一覧を書く。開発中に起動できなくならないようにするため。 +- Android は、一覧をアプリのコードに持たせている。別の鍵で署名し直した APK でも、スクリプトを書き換えただけでは動かない。コードごと書き換える相手までは防げないので、配布経路での検証(Play Integrity など)と併用する。 +- iOS は、アプリ全体が署名で封印されていて、書き換えたものは通常の端末では起動しない。この照合が効くのは、署名の検証が働かない端末でスクリプトだけを差し替えられた場合。一覧はバンドルの中にあるので、署名し直せる相手には効かない。 + ### 補足:既存プロジェクトの移行とSDKキャッシュ 1. ゲームから不要になった `@capacitor/cli`・`@capacitor/ios`・`@capacitor/android` の直接依存を外す。 @@ -189,6 +203,20 @@ If any command fails, the builder fails as well. Template npm scripts `open:ios` / `open:android` / `build:ios` / `build:android` are also available. Pass the environment as in `npm run build:ios -- --env prd`. +### Reference: Detecting modified files + +`sync` / `open` / `build` record the SHA-256 of the scripts packaged in the app (`.js` `.mjs` `.html` `.json` `.wasm`) and of the Capacitor config files, and add native code that checks them at launch. If a file was changed after the build, or a script was added, the app does not start. Images and audio are not checked. + +| OS | What is added | Changes left in the game repository | +|---|---|---| +| Android | The check class and the list under `app/src/main/java/app/next2d/integrity/` (the list is excluded by a `.gitignore` in that folder). One `` in `AndroidManifest.xml` | `AndroidManifest.xml` and the check class (first time only) | +| iOS | The check and one call at launch, appended to `AppDelegate.swift`. The list is `App/App/public/next2d-integrity.txt` | `AppDelegate.swift` (first time only) | + +- The list is rebuilt on every `sync` from the files Capacitor has just copied. If you replace only the web files from the IDE (`cap copy`, etc.) they no longer match the list and the app does not start; run the builder's `sync` / `build` again. +- `preview` (`cap run`) writes a list that checks nothing, so development runs are never blocked. +- Android keeps the list in the app's code. An APK re-signed with another key does not run if only its scripts were changed. It cannot stop someone who also patches the code, so combine it with verification on the distribution side (Play Integrity, etc.). +- On iOS the whole app is sealed by its signature and a modified app does not start on a normal device. This check matters only where signature validation is not enforced and just the scripts are swapped. The list is inside the bundle, so it does not stop someone who can re-sign the app. + ### Reference: Existing project migration and SDK cache 1. Remove direct dependencies on `@capacitor/cli`, `@capacitor/ios` and `@capacitor/android` that are no longer needed by the game. 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/package-lock.json b/package-lock.json index 03240e9..bb66bd2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@next2d/builder", - "version": "0.5.24", + "version": "0.5.25", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@next2d/builder", - "version": "0.5.24", + "version": "0.5.25", "license": "MIT", "bin": { "builder": "dist/index.js" diff --git a/package.json b/package.json index 20e67e4..b7947e6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@next2d/builder", - "version": "0.5.24", + "version": "0.5.25", "description": "A multiplatform builder for the Next2d Framework. It supports exporting to a variety of platforms, including Steam, macOS, Windows, Linux, iOS, Android, Xbox, Nintendo Switch, and the web (HTML).", "author": "Toshiyuki Ienaga ", "license": "MIT", diff --git a/src/electron-config.ts b/src/electron-config.ts index 66229f3..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)) { @@ -161,6 +167,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-host.ts b/src/electron-host.ts index 17c8493..b2f6ff5 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 => { @@ -45,12 +46,16 @@ 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"; } 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/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/integrity.ts b/src/integrity.ts new file mode 100644 index 0000000..c9b572b --- /dev/null +++ b/src/integrity.ts @@ -0,0 +1,80 @@ +// ビルドしたゲームのファイルが、配布後に書き換えられていないかを確かめるための一覧を作る。 +// 一覧 (ファイルごとの 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 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 }) + .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 }; +}; + +/** + * 動作を決めるファイル (スクリプト類) かどうか。ネイティブのホスト (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/native-integrity.ts b/src/native-integrity.ts new file mode 100644 index 0000000..97706ab --- /dev/null +++ b/src/native-integrity.ts @@ -0,0 +1,355 @@ +// iOS / Android (Capacitor): アプリに入れたスクリプト類が、ビルドの後に書き換えられていないかを +// 起動時に確かめるネイティブコードを、Capacitor のプロジェクトへ入れる。 +// +// Android: 別の鍵で署名し直した APK を配れるので、スクリプト類の SHA-256 をアプリのコード (dex) に持たせ、 +// 起動時 (ContentProvider) に assets と照合する。合わなければ起動しない。 +// iOS: アプリ全体が署名で封印されていて、書き換えたものは通常の端末では起動しない。ここで足すのは、 +// 署名の検証が働かない端末でスクリプトだけ差し替えられるのを止めるための照合。一覧は +// バンドルの中 (public/) に置くので、署名し直せる相手には効かない。 +import fs from "node:fs"; +import path from "node:path"; +import { hashData, isCodeFile } from "./integrity.js"; + +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)] : []); + +/** 一覧のファイル名 (public/ の直下に置く。iOS だけが使う)。 */ +export const IOS_MANIFEST_NAME = "next2d-integrity.txt"; + +/** + * 同期済みの資材ディレクトリから、照合の一覧の行を作る。1 行 1 ファイルで "<空白 2 つ><キー>"。 + * キーは base からの相対パス (区切りは "/")。対象は public/ 以下のスクリプト類と、extra に挙げた設定ファイル。 + */ +export const createNativeIntegrityLines = (base: string, extra: string[] = []): string[] => { + const publicDir = path.join(base, "public"); + const files = fs.existsSync(publicDir) ? walk(publicDir) : []; + const keys = files + .map((file) => path.relative(base, file).split(path.sep).join("/")) + .filter((key) => isCodeFile(key)) + .concat(extra.filter((name) => fs.existsSync(path.join(base, name)))); + return keys.map((key) => { + 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(fs.readFileSync(path.join(base, key)))} ${key}`; + }).sort(); +}; + +const BEGIN = "next2d-integrity:begin"; +const END = "next2d-integrity:end"; + +// --------------------------------------------------------------------------------------------- +// Android +// --------------------------------------------------------------------------------------------- + +const ANDROID_PACKAGE = "app.next2d.integrity"; + +/** 照合の処理。内容はビルドによらず同じなので、ゲームのリポジトリに入れておける。 */ +export const ANDROID_CHECK_SOURCE = `package ${ANDROID_PACKAGE}; + +import android.content.ContentProvider; +import android.content.ContentValues; +import android.content.res.AssetManager; +import android.database.Cursor; +import android.net.Uri; + +import java.io.IOException; +import java.io.InputStream; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + +/** + * Generated by @next2d/builder. Do not edit. + * + * Checks, before anything else in the app runs, that the game's script files in the APK are the ones + * that were built. The expected SHA-256 hashes are compiled into Next2DAssetIntegrityManifest + * (generated on every build). A changed or added script stops the app from starting. + */ +public final class Next2DAssetIntegrity extends ContentProvider { + + private static final String[] CODE_EXTENSIONS = { ".js", ".mjs", ".html", ".json", ".wasm" }; + + @Override + public boolean onCreate() { + final String[] lines = manifestLines(); + if (lines.length == 0 || getContext() == null) { + return true; + } + try { + verify(getContext().getAssets(), lines); + } catch (IOException | NoSuchAlgorithmException error) { + throw new IllegalStateException("The game files could not be verified.", error); + } + return true; + } + + /** The manifest class is generated by the builder; without it (a build that skipped the builder) nothing is checked. */ + private static String[] manifestLines() { + try { + final Object lines = Class.forName("${ANDROID_PACKAGE}.Next2DAssetIntegrityManifest").getField("LINES").get(null); + return lines instanceof String[] ? (String[]) lines : new String[0]; + } catch (ReflectiveOperationException error) { + return new String[0]; + } + } + + private static void verify(AssetManager assets, String[] lines) throws IOException, NoSuchAlgorithmException { + final Map expected = new HashMap<>(); + for (String line : lines) { + // "<64 hex digits>" + expected.put(line.substring(66), line.substring(0, 64)); + } + for (Map.Entry entry : expected.entrySet()) { + if (!entry.getValue().equals(hash(assets, entry.getKey()))) { + throw new IllegalStateException("The game files have been modified: " + entry.getKey()); + } + } + rejectUnlistedScripts(assets, "public", expected); + } + + /** A script that was added after the build is not in the list. */ + private static void rejectUnlistedScripts(AssetManager assets, String directory, Map expected) throws IOException { + final String[] names = assets.list(directory); + if (names == null) { + return; + } + for (String name : names) { + final String path = directory + "/" + name; + final String[] children = assets.list(path); + if (children != null && children.length > 0) { + rejectUnlistedScripts(assets, path, expected); + } else if (isCode(name) && !expected.containsKey(path)) { + throw new IllegalStateException("The game files have been modified: " + path); + } + } + } + + private static boolean isCode(String name) { + final String lower = name.toLowerCase(Locale.ROOT); + for (String extension : CODE_EXTENSIONS) { + if (lower.endsWith(extension)) { + return true; + } + } + return false; + } + + private static String hash(AssetManager assets, String path) throws IOException, NoSuchAlgorithmException { + final MessageDigest digest = MessageDigest.getInstance("SHA-256"); + try (InputStream input = assets.open(path)) { + final byte[] buffer = new byte[65536]; + int read; + while ((read = input.read(buffer)) > 0) { + digest.update(buffer, 0, read); + } + } + final StringBuilder hex = new StringBuilder(64); + for (byte value : digest.digest()) { + hex.append(Character.forDigit((value >> 4) & 0xF, 16)).append(Character.forDigit(value & 0xF, 16)); + } + return hex.toString(); + } + + @Override + public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { + return null; + } + + @Override + public String getType(Uri uri) { + return null; + } + + @Override + public Uri insert(Uri uri, ContentValues values) { + return null; + } + + @Override + public int delete(Uri uri, String selection, String[] selectionArgs) { + return 0; + } + + @Override + public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { + return 0; + } +} +`; + +const javaString = (value: string): string => + `"${value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`; + +/** ビルドごとに変わる一覧。ゲームのリポジトリには入れない (同じ場所の .gitignore で外す)。 */ +export const renderAndroidManifestSource = (lines: string[]): string => [ + `package ${ANDROID_PACKAGE};`, + "", + "/** Generated by @next2d/builder on every build. SHA-256 of the game's script files in the APK. */", + "public final class Next2DAssetIntegrityManifest {", + " public static final String[] LINES = {", + ...lines.map((line) => ` ${javaString(line)},`), + " };", + "", + " private Next2DAssetIntegrityManifest() {}", + "}", + "" +].join("\n"); + +const ANDROID_PROVIDER = [ + ` `, + " ", + ` ` +].join("\n"); + +/** AndroidManifest.xml に、照合を行う provider を 1 度だけ足す。 */ +export const addAndroidProvider = (manifest: string): string => { + if (manifest.includes(BEGIN)) { + return manifest; + } + const close = manifest.lastIndexOf(""); + if (close < 0) { + throw new Error("AndroidManifest.xml has no ; the integrity check cannot be registered."); + } + const newline = manifest.includes("\r\n") ? "\r\n" : "\n"; + const lineStart = manifest.lastIndexOf("\n", close) + 1; + return manifest.slice(0, lineStart) + ANDROID_PROVIDER.split("\n").join(newline) + newline + manifest.slice(lineStart); +}; + +/** + * Android のプロジェクトに照合を入れる。lines が null のときは照合しない一覧 (空) を書く + * (開発用の実行では資材が入れ替わるので、古い一覧で起動できなくならないように)。 + */ +export const applyAndroidIntegrity = (platformDir: string, lines: string[] | null): void => { + const manifestFile = path.join(platformDir, "app/src/main/AndroidManifest.xml"); + if (!fs.existsSync(manifestFile)) { + throw new Error(`AndroidManifest.xml was not found: ${manifestFile}`); + } + const sourceDir = path.join(platformDir, "app/src/main/java", ...ANDROID_PACKAGE.split(".")); + fs.mkdirSync(sourceDir, { "recursive": true }); + fs.writeFileSync(path.join(sourceDir, "Next2DAssetIntegrity.java"), ANDROID_CHECK_SOURCE); + fs.writeFileSync(path.join(sourceDir, "Next2DAssetIntegrityManifest.java"), renderAndroidManifestSource(lines ?? [])); + fs.writeFileSync(path.join(sourceDir, ".gitignore"), "# Generated on every build by @next2d/builder\nNext2DAssetIntegrityManifest.java\n"); + + const manifest = fs.readFileSync(manifestFile, "utf8"); + const patched = addAndroidProvider(manifest); + if (patched !== manifest) { + fs.writeFileSync(manifestFile, patched); + } +}; + +// --------------------------------------------------------------------------------------------- +// iOS +// --------------------------------------------------------------------------------------------- + +const IOS_CALL = " Next2DAssetIntegrity.verify() // next2d-integrity:call (generated by @next2d/builder)"; + +/** AppDelegate.swift に足す照合の処理。内容はビルドによらず同じ。 */ +export const IOS_CHECK_SOURCE = `// ${BEGIN} (generated by @next2d/builder; do not edit) +import CryptoKit + +/// Checks at launch that the game's script files in the app bundle are the ones that were built. +/// The expected SHA-256 hashes are listed in public/${IOS_MANIFEST_NAME}, written on every build. +/// A changed or added script stops the app. Without the list (a build that skipped the builder) nothing is checked. +enum Next2DAssetIntegrity { + private static let codeExtensions: Set = ["js", "mjs", "html", "json", "wasm"] + + static func verify() { + guard let base = Bundle.main.resourceURL?.resolvingSymlinksInPath(), + let text = try? String(contentsOf: base.appendingPathComponent("public/${IOS_MANIFEST_NAME}"), encoding: .utf8) else { + return + } + var expected: [String: String] = [:] + for line in text.split(whereSeparator: { $0 == "\\n" || $0 == "\\r" }) where line.count > 66 { + // "<64 hex digits>" + expected[String(line.dropFirst(66))] = String(line.prefix(64)) + } + if expected.isEmpty { + return + } + for (key, hash) in expected { + guard let data = try? Data(contentsOf: base.appendingPathComponent(key)), + SHA256.hash(data: data).map({ String(format: "%02x", $0) }).joined() == hash else { + fatalError("The game files have been modified: \\(key)") + } + } + // A script that was added after the build is not in the list. + let publicURL = base.appendingPathComponent("public") + let prefix = base.pathComponents.count + guard let enumerator = FileManager.default.enumerator(at: publicURL, includingPropertiesForKeys: nil) else { + return + } + for case let url as URL in enumerator where codeExtensions.contains(url.pathExtension.lowercased()) { + let key = url.resolvingSymlinksInPath().pathComponents.dropFirst(prefix).joined(separator: "/") + if expected[key] == nil { + fatalError("The game files have been modified: \\(key)") + } + } + } +} +// ${END} +`; + +/** AppDelegate.swift に、照合の処理と、起動時の呼び出しを 1 度だけ足す (処理のほうは常に最新へ置き換える)。 */ +export const addIosCheck = (source: string): string => { + const newline = source.includes("\r\n") ? "\r\n" : "\n"; + const block = IOS_CHECK_SOURCE.split("\n").join(newline); + const begin = source.indexOf(`// ${BEGIN}`); + let result = source; + if (begin >= 0) { + const endMarker = `// ${END}`; + const end = source.indexOf(endMarker, begin); + if (end < 0) { + throw new Error("AppDelegate.swift has an unterminated next2d-integrity block; remove it and build again."); + } + let after = end + endMarker.length; + if (source.startsWith(newline, after)) { + after += newline.length; + } + result = source.slice(0, begin) + block + source.slice(after); + } else { + result = source + (source.endsWith(newline) ? "" : newline) + newline + block; + } + if (!result.includes("next2d-integrity:call")) { + const launch = /didFinishLaunchingWithOptions[^{]*\{[ \t]*\r?\n/.exec(result); + if (!launch) { + throw new Error("AppDelegate.swift has no application(_:didFinishLaunchingWithOptions:); the integrity check cannot be called."); + } + const at = launch.index + launch[0].length; + result = result.slice(0, at) + IOS_CALL + newline + result.slice(at); + } + return result; +}; + +/** + * iOS のプロジェクトに照合を入れる。lines が null のときは一覧を消す (照合しない)。 + * 一覧は public/ に置くので、アプリのバンドルに入り、ゲームのリポジトリには残らない。 + */ +export const applyIosIntegrity = (platformDir: string, lines: string[] | null): void => { + const appDir = path.join(platformDir, "App/App"); + const delegate = path.join(appDir, "AppDelegate.swift"); + if (!fs.existsSync(delegate)) { + throw new Error(`AppDelegate.swift was not found: ${delegate}`); + } + const source = fs.readFileSync(delegate, "utf8"); + const patched = addIosCheck(source); + if (patched !== source) { + fs.writeFileSync(delegate, patched); + } + const list = path.join(appDir, "public", IOS_MANIFEST_NAME); + if (lines && lines.length) { + fs.mkdirSync(path.dirname(list), { "recursive": true }); + fs.writeFileSync(list, `${lines.join("\n")}\n`); + } else { + fs.rmSync(list, { "force": true }); + } +}; diff --git a/src/native.ts b/src/native.ts index 4d5fb6c..cb58bc1 100644 --- a/src/native.ts +++ b/src/native.ts @@ -5,6 +5,7 @@ import { ctx } from "./context.js"; import { $spawn } from "./utils.js"; import { CAPACITOR_CONFIG_NAME } from "./constants.js"; import { resolveToolPackages } from "./tool-packages.js"; +import { applyAndroidIntegrity, applyIosIntegrity, createNativeIntegrityLines } from "./native-integrity.js"; /** Resolve from npm's persistent tool cache without installing into the game. */ export const getCapacitorCommand = async (): Promise<{ cli: string; env: NodeJS.ProcessEnv }> => { @@ -52,13 +53,40 @@ const prepareNativeProject = async (): Promise => { }; /** Keep native customizations and update web assets/dependency paths in place. */ +const nativePlatformDir = (): string => { + const root = process.cwd(); + const config = JSON.parse(fs.readFileSync(path.join(root, CAPACITOR_CONFIG_NAME), "utf8")); + return path.resolve(root, config[ctx.platform]?.path ?? ctx.platform); +}; + +/** + * Put the check of the game's script files into the native project (see native-integrity.ts). + * `check` false writes an empty list: a development run replaces the web files itself, and a list + * left over from an earlier build would stop the app from starting. + */ +export const applyNativeIntegrity = (check: boolean): void => { + const platformDir = nativePlatformDir(); + if (ctx.platform === "android") { + const assets = path.join(platformDir, "app/src/main/assets"); + applyAndroidIntegrity(platformDir, check + ? createNativeIntegrityLines(assets, ["capacitor.config.json", "capacitor.plugins.json"]) : null); + } else { + const bundle = path.join(platformDir, "App/App"); + applyIosIntegrity(platformDir, check + ? createNativeIntegrityLines(bundle, ["capacitor.config.json"]) : null); + } +}; + export const syncNative = async (): Promise => { await prepareNativeProject(); await runCapacitor(["sync", ctx.platform]); + // The list is made from the files Capacitor has just copied into the native project. + applyNativeIntegrity(true); }; export const runNative = async (): Promise => { await prepareNativeProject(); + applyNativeIntegrity(false); await runCapacitor(["run", ctx.platform]); }; 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/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/electron/index.js b/templates/electron/index.js index 9a29af4..ccdec86 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(); @@ -300,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 } : {}) } @@ -358,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(); @@ -409,7 +424,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/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" を含む