A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
refactor(editor): one path sandbox, asked of once
yhh014ffc324302
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex d7b27112b..67ebf57bb 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -106,6 +106,12 @@ We follow a strict commit message format:- **C++**: See naming conventions and formatting rules in [`docs/CODING_STYLE.md`](docs/CODING_STYLE.md)- **TypeScript**: Strict mode, use `defineComponent()` and `defineSystem()`- **Comments**: Code should be self-documenting. Only add comments for non-obvious logic.+- **One path sandbox**: "is this path inside that root?" is `isInsideRoot` /+ `resolveInside` from `desktop/electron/pathSandbox.ts`. Do not open-code+ `path.relative(...).startsWith('..')` — lexical containment is not containment,+ because a symlink or junction inside the root holds no `..`. Enforced by+ `node tools/check-path-sandbox.mjs` (in `pnpm verify`); a use that is genuinely+ not a boundary opts out with a `path-sandbox: <why>` comment above it.- **No prose in comments**: state the fact, not the story. One or two lines. No narratingthe bug that led here, no "previously X, now Y", no essay paragraphs — that belongs inthe commit message. A comment that needs a paragraph is a sign the code needs a name.diff --git a/desktop/electron/exportGame.ts b/desktop/electron/exportGame.tsindex 782fe7a7e..ea570589e 100644--- a/desktop/electron/exportGame.ts+++ b/desktop/electron/exportGame.ts@@ -314,6 +314,9 @@ app.whenReady().then(() => {let rel = decodeURIComponent(new URL(req.url).pathname).replace(/^\\/+/, '') || 'index.html';const filePath = path.join(ROOT, rel);// Contain within ROOT (no path traversal out of the bundled payload).+ // path-sandbox: this is emitted into the shipped game and cannot import the+ // editor's module. Lexical is enough because the payload is BUILT file by file+ // (the cook writes bytes, esbuild writes outputs) — no link can be in it.if (filePath !== ROOT && !filePath.startsWith(ROOT + path.sep)) {return new Response('forbidden', { status: 403 });}diff --git a/desktop/electron/importAssets.ts b/desktop/electron/importAssets.tsindex a4ebce634..df2cac51c 100644--- a/desktop/electron/importAssets.ts+++ b/desktop/electron/importAssets.ts@@ -10,6 +10,7 @@import { copyFile, mkdir, writeFile } from 'node:fs/promises';import { existsSync } from 'node:fs';import path from 'node:path';+import { isInsideRoot } from './pathSandbox';import { resolveInRoot, META_EXT } from './projectFs';import { EXT_TO_TYPE, metaTypeFor, metaTypeForFile, mintMeta, writeMeta, adoptOrphan } from './assetMeta';import { CONTENT_TYPED_EXTENSIONS } from '../../tools/assetMetaTable.js';@@ -34,9 +35,9 @@ function uniqueName(absDir: string, name: string): string {/** The project-relative (forward-slashed) path of `abs` under `root`, or null* when `abs` lives outside the project. */function relInRoot(root: string, abs: string): string | null {+ if (!isInsideRoot(root, abs)) return null;const rel = path.relative(path.resolve(root), path.resolve(abs));- if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return null;- return rel.replace(/\\/g, '/');+ return rel ? rel.replace(/\\/g, '/') : null;}/** Canonical creation extension per meta type — the inverse of {@link EXT_TO_TYPE},diff --git a/desktop/electron/loopbackServer.ts b/desktop/electron/loopbackServer.tsindex ac6d82780..831699ebb 100644--- a/desktop/electron/loopbackServer.ts+++ b/desktop/electron/loopbackServer.ts@@ -25,6 +25,7 @@ import http from 'node:http';import { readFile } from 'node:fs/promises';import { existsSync } from 'node:fs';import path from 'node:path';+import { isInsideRoot } from './pathSandbox';import { httpContentType } from './mimeTypes';/** Served root (absolute) → its running loopback server + URL. */@@ -47,8 +48,7 @@ export async function loopbackServer(rootDir: string): Promise<string> {try {const rel = decodeURIComponent(new URL(req.url ?? '/', 'http://x').pathname).replace(/^\/+/, '') || 'index.html';const abs = path.join(root, rel);- // Contain within the served root (no traversal out of the build).- if (abs !== root && !abs.startsWith(root + path.sep)) {+ if (!isInsideRoot(root, abs)) {res.writeHead(403).end('forbidden');return;}diff --git a/desktop/electron/main.ts b/desktop/electron/main.tsindex ee9923fa0..fb655b97e 100644--- a/desktop/electron/main.ts+++ b/desktop/electron/main.ts@@ -23,6 +23,7 @@ import {resolveInRoot,META_EXT,} from './projectFs';+import { isInsideRoot } from './pathSandbox';import { syncAutosave, listAutosave, restoreAutosave, clearAutosave, type AutosaveEntry } from './autosave';import { listRecents, addRecent, removeRecent, listTemplates, createFromTemplate } from './launcher';import { buildProjectScripts } from './buildScripts';@@ -1432,11 +1433,10 @@ ipcMain.handle('project:saveDialog', async (_e, defaultRel?: string) => {filters: [{ name: 'Estella Scene', extensions: ['esscene'] }],});if (res.canceled || !res.filePath) return null;- const rel = path.relative(root, res.filePath);- if (rel.startsWith('..') || path.isAbsolute(rel)) {+ if (!isInsideRoot(root, res.filePath)) {throw new Error('scene must be saved inside the project');}- return rel;+ return path.relative(root, res.filePath);});// Serve a project file, honoring an HTTP Range request (206) when present so@@ -1527,7 +1527,7 @@ async function handleApp(request: Request): Promise<Response> {return await serveProjectFile(abs, request);}const abs = path.join(RENDERER_DIST, rel);- if (abs !== RENDERER_DIST && !abs.startsWith(RENDERER_DIST + path.sep)) {+ if (!isInsideRoot(RENDERER_DIST, abs)) {return new Response('forbidden', { status: 403 });}const bytes = await readFile(abs);diff --git a/desktop/electron/pathSandbox.ts b/desktop/electron/pathSandbox.tsnew file mode 100644index 000000000..201ec4c71--- /dev/null+++ b/desktop/electron/pathSandbox.ts@@ -0,0 +1,83 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The one answer to "is this path inside that root?".+ *+ * Every door that takes a caller-named path and turns it into an fs call needs+ * this, and each one that spells it out itself gets a different amount of it+ * right. `check-path-sandbox.mjs` keeps the idiom from being written a seventh+ * time; a use that is NOT a boundary opts out by saying so in a comment.+ */+import { realpathSync } from 'node:fs';+import path from 'node:path';++/** Lexical containment: `abs` is `base`, or sits under it. */+export function containsPath(base: string, abs: string): boolean {+ const rel = path.relative(base, abs);+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));+}++// A root is resolved once per open; the candidate side is always resolved live.+const realRootCache = new Map<string, string>();++/** `root` with links resolved — a root may itself live under one (/tmp on macOS). */+export function realRootOf(root: string): string {+ const key = path.resolve(root);+ const hit = realRootCache.get(key);+ if (hit !== undefined) return hit;+ let real = key;+ try {+ real = realpathSync.native(key);+ } catch {+ // Not created yet (a project being made) — the lexical form is all there is.+ }+ realRootCache.set(key, real);+ return real;+}++/**+ * `abs` with links resolved. The leaf often does not exist yet (a write, a mkdir,+ * a rename target), so resolve the deepest ancestor that does and re-attach the+ * rest — that is the part someone can have made a link.+ */+export function realPathOf(abs: string): string {+ const tail: string[] = [];+ let head = path.resolve(abs);+ for (;;) {+ try {+ return path.join(realpathSync.native(head), ...tail);+ } catch {+ const parent = path.dirname(head);+ if (parent === head) return path.resolve(abs);+ tail.unshift(path.basename(head));+ head = parent;+ }+ }+}++/**+ * Whether `abs` is really inside `root`. Lexical containment is not containment:+ * a link inside the root holds no `..` and points wherever it likes, so both+ * sides are compared with links resolved as well.+ *+ * Racing a link swapped between this and the call that follows needs O_NOFOLLOW,+ * which node does not expose portably — this raises the bar, it is not a seal.+ */+export function isInsideRoot(root: string, abs: string): boolean {+ const resolved = path.resolve(abs);+ return containsPath(path.resolve(root), resolved)+ && containsPath(realRootOf(root), realPathOf(resolved));+}++/** {@link isInsideRoot} for a relative path, throwing rather than returning false.+ * `label` names the root in the message ("project root", "build output"). */+export function resolveInside(root: string, relPath: string, label: string): string {+ const resolved = path.resolve(root, relPath);+ if (!containsPath(path.resolve(root), resolved)) {+ throw new Error(`path "${relPath}" escapes the ${label}`);+ }+ if (!containsPath(realRootOf(root), realPathOf(resolved))) {+ throw new Error(`path "${relPath}" escapes the ${label} through a link`);+ }+ return resolved;+}diff --git a/desktop/electron/projectFs.ts b/desktop/electron/projectFs.tsindex 2764c8c26..03b06a3d6 100644--- a/desktop/electron/projectFs.ts+++ b/desktop/electron/projectFs.ts@@ -9,7 +9,7 @@* project someone else authored can read or write arbitrary files.*/import { readFile, writeFile, readdir, mkdir, rename, cp, stat, rm } from 'node:fs/promises';-import { existsSync, realpathSync } from 'node:fs';+import { existsSync } from 'node:fs';import { randomUUID } from 'node:crypto';import { tmpdir } from 'node:os';import path from 'node:path';@@ -24,68 +24,14 @@ import {type DirEntry,} from '../src/project/format';import { META_EXT, isContentDir, isContentFile } from './contentPolicy';+import { resolveInside } from './pathSandbox';export { META_EXT };-/** Whether `abs` is `base` or sits under it, lexically. */-function contains(base: string, abs: string): boolean {- const rel = path.relative(base, abs);- return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));-}--// Roots change once per project open; the candidate side is still resolved live.-const realRootCache = new Map<string, string>();--/** `root` with links resolved — a project may itself live under one (/tmp on macOS). */-function realRoot(root: string): string {- const key = path.resolve(root);- const hit = realRootCache.get(key);- if (hit !== undefined) return hit;- let real = key;- try {- real = realpathSync.native(key);- } catch {- // Not created yet (a project being made) — the lexical form is all there is.- }- realRootCache.set(key, real);- return real;-}--/**- * `abs` with links resolved. The leaf often does not exist yet (a write, a mkdir,- * a rename target), so resolve the deepest ancestor that does and re-attach the- * rest — that is the part an attacker can have made a link.- */-function realResolve(abs: string): string {- const tail: string[] = [];- let head = abs;- for (;;) {- try {- return path.join(realpathSync.native(head), ...tail);- } catch {- const parent = path.dirname(head);- if (parent === head) return abs;- tail.unshift(path.basename(head));- head = parent;- }- }-}--/**- * Resolve a project-relative path, refusing anything that escapes `root` — the- * security boundary for every fs op below. A link inside the project holds no- * `..` and points wherever it likes, so both sides are compared with links- * resolved; racing a swap after the check needs O_NOFOLLOW, which node lacks.- */+/** Resolve a project-relative path, refusing anything that escapes `root` — the+ * security boundary for every fs op below (see pathSandbox). */export function resolveInRoot(root: string, relPath: string): string {- const resolved = path.resolve(root, relPath);- if (!contains(root, resolved)) {- throw new Error(`path "${relPath}" escapes the project root`);- }- if (!contains(realRoot(root), realResolve(resolved))) {- throw new Error(`path "${relPath}" escapes the project root through a link`);- }- return resolved;+ return resolveInside(root, relPath, 'project root');}/**diff --git a/desktop/electron/sizeReport.ts b/desktop/electron/sizeReport.tsindex 2998c002f..623c37540 100644--- a/desktop/electron/sizeReport.ts+++ b/desktop/electron/sizeReport.ts@@ -286,6 +286,7 @@ export async function measureBuild(opts: {const excluded = new Set<string>();for (const file of [...(opts.packages ?? []), ...(opts.deliverable ? [opts.deliverable] : [])]) {const rel = path.relative(opts.root, file);+ // path-sandbox: not a boundary — classifying which built files a report counts.if (rel && !rel.startsWith('..') && !path.isAbsolute(rel)) excluded.add(normalizeRel(rel));}const files = (await collectBuildFiles(opts.root)).filter((f) => !excluded.has(normalizeRel(f.path)));diff --git a/desktop/tests/loopback-server.test.ts b/desktop/tests/loopback-server.test.tsindex 0cd874679..9db2fcc36 100644--- a/desktop/tests/loopback-server.test.ts+++ b/desktop/tests/loopback-server.test.ts@@ -8,7 +8,7 @@* server per root, and fails fast without an index.html.*/import { describe, it, expect, afterAll } from 'vitest';-import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';+import { mkdtempSync, mkdirSync, writeFileSync, rmSync, symlinkSync } from 'node:fs';import { tmpdir } from 'node:os';import path from 'node:path';import { loopbackServer, closeAllLoopbackServers } from '../electron/loopbackServer';@@ -63,6 +63,27 @@ describe('loopback server', () => {}});+ it('refuses a link out of the served root', async () => {+ const dir = buildDir();+ const outside = mkdtempSync(path.join(tmpdir(), 'estella-loopback-outside-'));+ writeFileSync(path.join(outside, 'secret.txt'), 'PRIVATE');+ try {+ if (process.platform === 'win32') symlinkSync(outside, path.join(dir, 'escape'), 'junction');+ else symlinkSync(outside, path.join(dir, 'escape'), 'dir');+ } catch {+ return; // no permission to make one here+ }+ try {+ const url = await loopbackServer(dir);+ const res = await fetch(`${url}escape/secret.txt`);+ expect([403, 404]).toContain(res.status);+ expect(await res.text()).not.toContain('PRIVATE');+ } finally {+ rmSync(outside, { recursive: true, force: true });+ rmSync(dir, { recursive: true, force: true });+ }+ });+it('fails fast when the dir has no index.html', async () => {const empty = mkdtempSync(path.join(tmpdir(), 'estella-loopback-empty-'));mkdirSync(path.join(empty, 'sub'), { recursive: true });diff --git a/package.json b/package.jsonindex b4127986f..5e385d407 100644--- a/package.json+++ b/package.json@@ -17,7 +17,7 @@"emsdk:setup": "node build-tools/toolchain/setup-emsdk.js","asset-meta": "node tools/asset-meta.js","migrate-asset-refs": "node tools/migrate-asset-refs.js",- "verify": "pnpm --filter ./sdk exec tsc --noEmit && node tools/api-surface.mjs --check && node tools/check-cycles.mjs && node tools/check-layers.mjs && node tools/check-project-settings.mjs && node tools/check-workflows.mjs && node tools/check-tool-calls.mjs && node tools/check-inspector-door.mjs && node tools/check-dirty-source.mjs && node tools/check-comment-style.mjs && node tools/component-reference.mjs --check",+ "verify": "pnpm --filter ./sdk exec tsc --noEmit && node tools/api-surface.mjs --check && node tools/check-cycles.mjs && node tools/check-layers.mjs && node tools/check-project-settings.mjs && node tools/check-workflows.mjs && node tools/check-tool-calls.mjs && node tools/check-inspector-door.mjs && node tools/check-dirty-source.mjs && node tools/check-path-sandbox.mjs && node tools/check-comment-style.mjs && node tools/component-reference.mjs --check","perf": "node tools/perf-guard.mjs --check","prepare": "git config core.hooksPath .githooks || true"},diff --git a/tools/check-path-sandbox.mjs b/tools/check-path-sandbox.mjsnew file mode 100644index 000000000..0a117808a--- /dev/null+++ b/tools/check-path-sandbox.mjs@@ -0,0 +1,61 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file check-path-sandbox.mjs — one containment check, not six.+ *+ * "Is this path inside that root?" was written out by hand at six doors, each+ * with a different amount of it right; the project one was lexical, so a symlink+ * inside a project walked out of the sandbox. They now share `pathSandbox.ts`,+ * and this keeps the idiom from being open-coded again.+ *+ * A use that is NOT a boundary — classifying paths for a report, say — opts out+ * on the line above with `path-sandbox: <why>`.+ */+import { execFileSync } from 'node:child_process';+import { readFileSync } from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const HOME = 'desktop/electron/pathSandbox.ts';+const SCOPE = /^desktop\/(electron|src)\/.*\.tsx?$/;++// The two spellings of lexical containment, which is the check that is not one.+const IDIOMS = [+ { id: 'dotdot', re: /\.startsWith\(\s*['"]\.\.['"]\s*\)/ },+ { id: 'sep', re: /\.startsWith\(\s*\w[\w.]*\s*\+\s*path\.sep\s*\)/ },+];+const OPT_OUT = /path-sandbox:/;++const files = execFileSync('git', ['ls-files'], { cwd: ROOT, encoding: 'utf8' })+ .split('\n')+ .filter((f) => SCOPE.test(f) && f !== HOME);++const findings = [];+for (const file of files) {+ const lines = readFileSync(path.join(ROOT, file), 'utf8').split('\n');+ for (let i = 0; i < lines.length; i++) {+ const hit = IDIOMS.find((r) => r.re.test(lines[i]));+ if (!hit) continue;+ // The opt-out sits on the line itself or anywhere in the comment block above+ // it — a justification worth reading is usually more than one line.+ let j = i - 1;+ while (j >= 0 && /^\s*(\/\/|\*|\/\*)/.test(lines[j])) j--;+ if (OPT_OUT.test(lines[i]) || lines.slice(j + 1, i).some((l) => OPT_OUT.test(l))) continue;+ findings.push({ file, line: i + 1, text: lines[i].trim() });+ }+}++if (findings.length === 0) {+ console.log(`check-path-sandbox: ${files.length} file(s) — containment is asked of ${HOME}, not open-coded.`);+ process.exit(0);+}+for (const f of findings) {+ console.error(`\n${f.file}:${f.line} hand-rolled containment check`);+ console.error(` ${f.text}`);+}+console.error(+ `\ncheck-path-sandbox: ${findings.length} finding(s). Use isInsideRoot/resolveInside from `+ + `${HOME}, or mark a non-boundary use with a "path-sandbox: <why>" comment.`,+);+process.exit(1);