Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .github/workflows/xbox-host-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
28 changes: 28 additions & 0 deletions docs/capacitor.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` に `<provider>` を 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` の直接依存を外す。
Expand Down Expand Up @@ -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 `<provider>` 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.
Expand Down
2 changes: 2 additions & 0 deletions docs/steam.md
Original file line number Diff line number Diff line change
Expand Up @@ -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の許可操作はユーザーが行う。 |

#### オーバーレイウィンドウ
Expand Down Expand Up @@ -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

Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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 <ienaga@next2d.app>",
"license": "MIT",
Expand Down
25 changes: 25 additions & 0 deletions src/electron-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export interface IElectronConfig {
window: { width: number; height: number; fullscreen: boolean; overlay?: IElectronOverlayConfig; mini?: IElectronMiniConfig };
steam?: { appId: string | null; depots: Partial<Record<ElectronOS, string | null>>; branch?: string };
macos: { sign: boolean; notarize: boolean; localNetworkUsageDescription?: string };
devTools: boolean;
}

export const validateSteamId = (value: unknown): string => {
Expand Down Expand Up @@ -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
};
Expand All @@ -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<IElectronOverlayConfig> | undefined = config.window.overlay;
if (overlay !== undefined) {
if (!overlay || typeof overlay !== "object" || Array.isArray(overlay)) {
Expand Down Expand Up @@ -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<string, boolean>;
} => ({
// 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
) => {
Expand Down
7 changes: 6 additions & 1 deletion src/electron-host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 <T>(use: (directory: string) => Promise<T>): Promise<T> => {
Expand Down Expand Up @@ -45,12 +46,16 @@ export const withElectronHost = async <T>(
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 });
Expand Down
17 changes: 16 additions & 1 deletion src/electron.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -73,10 +73,25 @@ export const buildElectron = async (): Promise<void> => {
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<void> => {
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(),
Expand Down
80 changes: 80 additions & 0 deletions src/integrity.ts
Original file line number Diff line number Diff line change
@@ -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<string, string>;
}

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<string, string> = {};
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 ファイルで "<SHA-256><空白 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");
};
Loading
Loading