Skip to content

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.

fix(assets): the cook read through links the sandbox had already refused

esengine30407729c195
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b92985784..5fe63bca7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -64,6 +64,19 @@ published separately; it ships inside the editor.
### Fixed
+- **Exporting a project could ship files from outside it.** The IPC door already
+ refused a path that left the project through a link, but the asset scanner and
+ the cook never went through that door. A file named like content with a `.meta`
+ beside it was indexed no matter what it was — and a symlink is a file. So a
+ scene referencing it made the cook `readFile` straight through the link and
+ write whatever it found into the shipped game, with no warning. A project is not
+ trusted input: it is cloned, unzipped, copied from a template, or handed over,
+ and exporting one is enough to carry files off the machine that exported it. The
+ scanner now refuses a link that leaves the project — as a file, as a sidecar's
+ content, or as a directory to walk into — and the cook refuses one again before
+ staging bytes. A link that stays inside the project still works. Only links pay
+ the extra `realpath`, so scanning is unchanged for everything else.
+
- **An additive scene unloaded during its own `setup()` came back as a ghost.**
`setup()` is user code and may await for as long as it likes; an `unload()`
during it tears the scene down completely — entities, systems, assets, its slot
diff --git a/desktop/electron/assetDb.ts b/desktop/electron/assetDb.ts
index 6d2d7f4ab..d66b0bda8 100644
--- a/desktop/electron/assetDb.ts
+++ b/desktop/electron/assetDb.ts
@@ -17,10 +17,12 @@
* extension→type table — it reads the type each meta already declares.
*/
import { readFile, writeFile, mkdir, readdir, stat } from 'node:fs/promises';
+import type { Dirent } from 'node:fs';
import { existsSync } from 'node:fs';
import { randomUUID } from 'node:crypto';
import path from 'node:path';
import { readTextInRoot } from './projectFs';
+import { isInsideRoot } from './pathSandbox';
import { META_EXT, isContentDir, isContentFile, isNonContentPath } from './contentPolicy';
import { adoptOrphan } from './assetMeta';
// The runtime's tileset-path resolver (a dependency-free leaf) — shared so the dep scan
@@ -128,6 +130,16 @@ async function resolveDuplicateUuids(
return reminted;
}
+/**
+ * A directory entry that leaves the project through a link — never indexed. The
+ * cook reads every indexed path and writes what it reads into the shipped game,
+ * and a project is not trusted input. A link that stays inside is an ordinary
+ * file here, and only links pay the realpath call.
+ */
+function leavesProject(root: string, dirent: Dirent, abs: string): boolean {
+ return dirent.isSymbolicLink() && !isInsideRoot(root, abs);
+}
+
/** Recursively yield every `<file>.meta` path (project-relative, forward-slashed). */
async function* walkMeta(root: string, rel = ''): AsyncGenerator<string> {
const abs = rel ? path.join(root, rel) : root;
@@ -137,11 +149,20 @@ async function* walkMeta(root: string, rel = ''): AsyncGenerator<string> {
} catch {
return; // unreadable dir
}
+ const escaped = new Set<string>();
+ for (const e of entries) {
+ if (leavesProject(root, e, path.join(abs, e.name))) escaped.add(e.name);
+ }
for (const e of entries) {
+ if (escaped.has(e.name)) continue;
if (e.isDirectory()) {
if (!isContentDir(e.name)) continue;
yield* walkMeta(root, rel ? `${rel}/${e.name}` : e.name);
} else if (e.name.endsWith(META_EXT)) {
+ // A sidecar is an ordinary file even when the content beside it is a link
+ // out. Indexing it would put that link's path in the registry, and the cook
+ // reads registry paths.
+ if (escaped.has(e.name.slice(0, -META_EXT.length))) continue;
yield rel ? `${rel}/${e.name}` : e.name;
}
}
@@ -165,6 +186,7 @@ async function adoptOrphans(root: string, rel = '', adopted: string[] = []): Pro
}
for (const e of entries) {
const relPath = rel ? `${rel}/${e.name}` : e.name;
+ if (leavesProject(root, e, path.join(abs, e.name))) continue;
if (e.isDirectory()) {
if (!isContentDir(e.name)) continue;
await adoptOrphans(root, relPath, adopted);
diff --git a/desktop/electron/cookAssets.ts b/desktop/electron/cookAssets.ts
index d8b65074b..0c401888a 100644
--- a/desktop/electron/cookAssets.ts
+++ b/desktop/electron/cookAssets.ts
@@ -18,6 +18,7 @@
* This is the reachability + manifest + staging core they all build on.
*/
import { writeFile, mkdir, readFile } from 'node:fs/promises';
+import { isInsideRoot } from './pathSandbox';
import path from 'node:path';
import { scanAssetDatabase, type AssetEntry } from './assetDb';
import { packAtlas, decodePngImage, encodePagePng, encodeRgbaPng, downscaleRgba, type AtlasInputImage } from './atlasPacker';
@@ -268,9 +269,17 @@ export async function cookAssets(
const transcodeVideo = opts.transcodeVideo ?? false;
const platform = opts.platform;
const { index } = await scanAssetDatabase(root, { write: false, adopt: false });
- const byUuid = new Map(index.entries.map((e) => [e.uuid, e]));
- const byPath = new Map(index.entries.map((e) => [e.path, e]));
const warnings: string[] = [];
+ // Second gate: nothing reaches it while the scanner drops these upstream, but
+ // this is where bytes become an artifact someone else runs. Warns rather than
+ // dropping silently — an asset missing from a build has to say why.
+ const shippable = index.entries.filter((e) => {
+ if (isInsideRoot(root, path.join(root, e.path))) return true;
+ warnings.push(`${e.path}: resolves outside the project through a link — not shipped`);
+ return false;
+ });
+ const byUuid = new Map(shippable.map((e) => [e.uuid, e]));
+ const byPath = new Map(shippable.map((e) => [e.path, e]));
// Asset-delivery config: which folders are remote (CDN) / subpackage groups.
const groupsConfig = await loadAssetGroups(root);
@@ -295,7 +304,7 @@ export async function cookAssets(
// scene never references them — but they (and their deps) must still ship. A
// shared dep that lives outside subpackages/ resolves to group 'main' below, so
// it lands in the always-present main package, not duplicated per subpackage.
- for (const e of index.entries) {
+ for (const e of shippable) {
const group = resolveAssetGroup(e.path, groupsConfig);
// …and every non-local (subpackage / remote-CDN) asset: never scene-
// referenced, but must be cooked + staged for its group's delivery.
@@ -310,14 +319,14 @@ export async function cookAssets(
// option (a scene never references them — Text carries KEYS, not paths), so
// reachability would always cull them, and a build missing its languages is
// strictly wrong. Text is tiny; dead tables cost nothing.
- for (const e of index.entries) {
+ for (const e of shippable) {
if (e.path.toLowerCase().endsWith('.eslocale')) seed(e.uuid);
}
// …and data assets, for the same reason one step further: a `.json` table is
// named by the code that loads it, so nothing in the scene graph points at it.
// Culling it produces the worst failure this pipeline can produce — it works in
// the editor, which serves the whole project, and 404s only in the build.
- for (const e of index.entries) {
+ for (const e of shippable) {
if (e.type === 'json') seed(e.uuid);
}
// …then take the transitive closure over the dependency graph.
diff --git a/desktop/tests/asset-symlink-escape.test.ts b/desktop/tests/asset-symlink-escape.test.ts
new file mode 100644
index 000000000..405278295
--- /dev/null
+++ b/desktop/tests/asset-symlink-escape.test.ts
@@ -0,0 +1,136 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file A project is not trusted input, and the cook reads by project-relative
+ * path. Together those mean a link inside a project is an instruction to
+ * read whatever it points at — and the cook writes what it reads into the
+ * game that gets shipped. A project cloned, unzipped or handed over could
+ * therefore carry files off the machine that exported it.
+ *
+ * The IPC door (resolveInside) already refuses links out. The scanner and
+ * the cook are a separate path: they never went through that door, so a
+ * link named like content, with a sidecar beside it, was indexed and its
+ * target's bytes were staged with no warning.
+ */
+import { describe, it, expect } from 'vitest';
+import { mkdtempSync, mkdirSync, writeFileSync, symlinkSync, rmSync, readFileSync, existsSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { scanAssetDatabase } from '../electron/assetDb';
+import { cookAssets } from '../electron/cookAssets';
+
+const SECRET = 'SECRET-BYTES-NOT-IN-THE-PROJECT';
+const LEAK_UUID = '33333333-3333-4333-8333-333333333333';
+const SCENE_UUID = 'dddddddd-dddd-4ddd-8ddd-dddddddddddd';
+
+/** Windows refuses plain symlinks without elevation but allows directory junctions. */
+function linkDir(target: string, at: string): void {
+ symlinkSync(target, at, process.platform === 'win32' ? 'junction' : 'dir');
+}
+
+interface Fixture { base: string; root: string; outsideFile: string }
+
+function makeProject(): Fixture {
+ const base = mkdtempSync(path.join(tmpdir(), 'estella-escape-'));
+ const outside = path.join(base, 'outside');
+ mkdirSync(outside, { recursive: true });
+ const outsideFile = path.join(outside, 'secret.png');
+ writeFileSync(outsideFile, SECRET);
+
+ const root = path.join(base, 'project');
+ mkdirSync(path.join(root, 'assets', 'textures'), { recursive: true });
+ mkdirSync(path.join(root, 'assets', 'scenes'), { recursive: true });
+ writeFileSync(path.join(root, 'assets', 'textures', 'ok.png'), 'legit');
+ return { base, root, outsideFile };
+}
+
+function writeMeta(abs: string, uuid: string, type: string): void {
+ writeFileSync(`${abs}.meta`, JSON.stringify({ uuid, version: '2.0', type, importer: {} }));
+}
+
+function writeScene(root: string, texUuid: string): string {
+ const rel = 'assets/scenes/main.esscene';
+ const abs = path.join(root, rel);
+ writeFileSync(abs, JSON.stringify({
+ version: 1, name: 's',
+ entities: [{
+ id: 1, name: 'S', parent: null, children: [],
+ components: [{ type: 'Sprite', data: { texture: `@uuid:${texUuid}` } }],
+ }],
+ }));
+ writeMeta(abs, SCENE_UUID, 'scene');
+ return rel;
+}
+
+describe('a link out of the project reaches neither the index nor the build', () => {
+ it('a linked content file is not indexed, with or without a sidecar', async () => {
+ const { base, root, outsideFile } = makeProject();
+ try {
+ symlinkSync(outsideFile, path.join(root, 'assets', 'textures', 'adopted.png'));
+ symlinkSync(outsideFile, path.join(root, 'assets', 'textures', 'sidecar.png'));
+ writeMeta(path.join(root, 'assets', 'textures', 'sidecar.png'), LEAK_UUID, 'texture');
+
+ const { index } = await scanAssetDatabase(root, { write: false, adopt: true });
+ const paths = index.entries.map((e) => e.path);
+ expect(paths).toContain('assets/textures/ok.png');
+ expect(paths).not.toContain('assets/textures/adopted.png');
+ expect(paths).not.toContain('assets/textures/sidecar.png');
+ } finally {
+ rmSync(base, { recursive: true, force: true });
+ }
+ });
+
+ it('a linked directory is not walked into', async () => {
+ const { base, root } = makeProject();
+ try {
+ const outsideDir = path.join(base, 'outside', 'more');
+ mkdirSync(outsideDir, { recursive: true });
+ writeFileSync(path.join(outsideDir, 'deep.png'), SECRET);
+ linkDir(outsideDir, path.join(root, 'assets', 'linked'));
+
+ const { index } = await scanAssetDatabase(root, { write: false, adopt: true });
+ expect(index.entries.map((e) => e.path).some((p) => p.includes('deep'))).toBe(false);
+ } finally {
+ rmSync(base, { recursive: true, force: true });
+ }
+ });
+
+ it('a scene referencing a linked texture ships without its bytes', async () => {
+ const { base, root, outsideFile } = makeProject();
+ try {
+ const leak = path.join(root, 'assets', 'textures', 'leak.png');
+ symlinkSync(outsideFile, leak);
+ writeMeta(leak, LEAK_UUID, 'texture');
+ const scene = writeScene(root, LEAK_UUID);
+
+ const out = path.join(base, 'out');
+ const cooked = await cookAssets(root, { entryScenes: [scene], outDir: out, contentAddressed: false });
+
+ expect(cooked.includedPaths).not.toContain('assets/textures/leak.png');
+ const staged = path.join(out, 'assets', 'textures', 'leak.png');
+ expect(existsSync(staged)).toBe(false);
+ // Nothing anywhere in the build may carry those bytes.
+ const manifest = path.join(out, 'assets.manifest.json');
+ if (existsSync(manifest)) expect(readFileSync(manifest, 'utf8')).not.toContain(SECRET);
+ } finally {
+ rmSync(base, { recursive: true, force: true });
+ }
+ });
+
+ it('a link that stays inside the project still works', async () => {
+ const { base, root } = makeProject();
+ try {
+ const real = path.join(root, 'assets', 'textures', 'real.png');
+ writeFileSync(real, 'inside-bytes');
+ writeMeta(real, LEAK_UUID, 'texture');
+ symlinkSync(real, path.join(root, 'assets', 'textures', 'alias.png'));
+
+ const { index } = await scanAssetDatabase(root, { write: false, adopt: true });
+ const paths = index.entries.map((e) => e.path);
+ expect(paths).toContain('assets/textures/real.png');
+ expect(paths).toContain('assets/textures/alias.png');
+ } finally {
+ rmSync(base, { recursive: true, force: true });
+ }
+ });
+});