Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: keep chiptune publication inside the managed app through symlinked paths (#10894)

Adam Eivyc180bf7f7af7
diff --git a/server/lib/README.md b/server/lib/README.md
index 50b5744dc2..a70ff473c3 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -374,6 +374,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `mimeTypes.js` | MIME tables and extension allowlists (incl. `UPLOAD_AUDIO_EXTENSIONS`, the playable-audio subset of `/api/uploads`), image/video format detection (`detectImageFormat`, `detectVideoFormat`), and filename sanitization. |
| `paths.js` | Canonical source/install `PATHS`, `dataPath`, and home-directory expansion. |
| `pathContainment.js` | Dependency-free leaf holding `isPathAtOrInsideDir(dir, path)` (containment where the root itself counts as inside — what a guard policing a whole tree wants, as opposed to `pathSafety.js`'s strict `isPathInsideDir`; case-folded on Windows/macOS) and `canonicalizePath(path)` (realpath of the deepest EXISTING ancestor plus the not-yet-created tail, so a target that does not exist yet still resolves through symlinked ancestors). Split out so `fileCore.js`'s #6176 guard can reach them without dragging `errorHandler.js`/`paths.js` into the closure of every server suite — see the budget in `importScoping.test.js`. Keep it free of non-builtin imports. |
+| `repoPublishPath.js` | `isSymlinkFreeRepoPath(realRepoRoot, absPath, { leaf: 'dir' \| 'file' })` — symlink-aware containment for publishing generated files into a managed app's repo. `lstat`-walks every existing component below the real root and refuses any symlink (dangling or contained), a wrong-kind leaf, or a realpath outside the root; a missing tail is allowed below a verified ancestor. The lexical `isPathInsideDir` cannot see a redirecting directory link (#10894, after #9668). Shared by the chiptune and sprite publishers. |
| `pathSafety.js` | Filename/traversal validation, path containment, and approved image-asset resolvers. |
| `uploads.js` | Upload staging/import, base64/image persistence, and safe local-file serving. |
| `icloudFile.js` | Guards against blocking reads of **evicted (dataless) cloud files**. macOS Optimize-Mac-Storage offloads a file in an iCloud ubiquity container (or a `~/Library/CloudStorage` File Provider mount); the path and `size` remain but no blocks are local, and the first **data access** BLOCKS in the kernel until materialization completes — indefinitely and uncancellably when iCloud is wedged. Four such reads exhaust libuv's 4-thread fs pool and every later `fs` call in the process queues forever, including the `express.static` read that serves the UI bundle (the whole UI hangs while memory-only routes still answer). Retry-on-error can't help: the read doesn't fail, it hangs. `readIfMaterialized(path, {encoding, label})` screens with a `stat()` (safe — never materializes) and rejects with `err.code === ICLOUD_NOT_MATERIALIZED` instead of issuing the read, kicking a background `brctl download` so the next cycle succeeds; concurrent callers for one path+encoding share a single read. `isUbiquityPath(path)` resolves the containing directory's real path (memoized) rather than substring-matching, so a **symlinked** route into iCloud — `~/Documents/...` under "Desktop & Documents Folders" sync — is still recognized. `isDatalessStats(stats)` is the raw predicate (`size > 0 && blocks === 0`) and is **not safe alone** (a sparse or `decmpfs`-compressed ordinary file matches it); pair it with the platform + cloud-root scoping via `isEvictedStats(path, stats)`, which is what a caller holding a `Stats` should use, or `isSuspectedDataless(path)` which does the `stat` itself. `requestMaterialization(path, {label, retryAfterExit, onFailure})` is the fire-and-forget `brctl download` every brctl caller shares — read paths kick it (default `retryAfterExit: true`) to heal an evicted file, per-path-deduped in a shared in-flight map capped at 4 concurrent children (an evicted vault walk would otherwise fork one per note) and each killed at `DOWNLOAD_DEADLINE_MS` so a wedged `brctl` can't hold every slot for the life of the process; the boot/settings pin in `mortalLoomStore` passes `retryAfterExit: false` so it is NOT tracked in that shared map (it owns a single-sticky-path dedupe at its call site) plus an `onFailure` hook to clear that sticky path on a failed/killed download. `claimBrctlMissingWarning()` returns `true` on the first call only, so the "brctl not found on PATH" warning fires at most once per process across every brctl caller (the fire-and-forget path here and the awaited `materializeAndWait`). `materializeAndWait(path, {label, timeoutMs})` is the **awaited, bounded** counterpart used by WRITE paths (`mortalLoomStore` before overwriting its store, `obsidian.updateNote` before overwriting a note): a write must not silently skip, so it materializes and waits rather than firing and forgetting, bounded by `MATERIALIZE_TIMEOUT_MS` (20s — much tighter than the background `DOWNLOAD_DEADLINE_MS` because a caller is blocked on it) and run in a child process, which is what makes the wait cancellable when the kernel write it replaces would not be. It resolves `true` only on brctl exit-0, which means the download was **accepted, not completed** — always re-screen before trusting the file. Measured (#3706, #3713), and recorded in the module docblock's syscall table: `stat`/`open`/`rename`/`unlink` never materialize, while `read`, `write` (including after `O_TRUNC` — truncating does NOT skip the download), `link`, and `clonefile` all do. `unlink` being free is a measurement, not the POSIX inference — `link` is pure metadata too and it *does* materialize — so delete paths need no screen. The docblock also carries the reproduction recipe: `brctl evict <path>` works (undocumented, like `brctl download`), which is what makes the evict/measure/heal loop scriptable. Consumed by `services/mortalLoomStore.js` and `services/obsidian.js`. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 540f9e243e..5125cdce14 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -322,6 +322,7 @@ export * from './settingsStore.js';
export * from './mimeTypes.js';
export * from './motionSkills.js';
export * from './pathContainment.js';
+export * from './repoPublishPath.js';
export * from './paths.js';
export * from './pathSafety.js';
export * from './uploads.js';
diff --git a/server/lib/repoPublishPath.js b/server/lib/repoPublishPath.js
new file mode 100644
index 0000000000..285f43fafd
--- /dev/null
+++ b/server/lib/repoPublishPath.js
@@ -0,0 +1,51 @@
+/**
+ * Symlink-aware containment for writing generated files into a managed app's
+ * repository. The lexical `isPathInsideDir` guard cannot see that
+ * `<repo>/linked-assets` is a symlink to a directory elsewhere, so a publish
+ * that only checks the string path can be redirected out of the repo (#10894,
+ * after the Sprite equivalent #9668). Shared by the chiptune and sprite
+ * publishers.
+ */
+
+import { lstat, realpath } from 'fs/promises';
+import { join, relative, resolve, sep } from 'path';
+import { isPathAtOrInsideDir } from './pathContainment.js';
+
+/**
+ * True when `absPath` can be written below `repoRoot` without crossing a
+ * symlink. Walks every EXISTING component from the root with `lstat`, so
+ * dangling and still-contained symlinks are refused rather than mistaken for a
+ * missing destination or silently followed. A missing tail is fine — the first
+ * absent component ends the walk and everything below it will be created under
+ * the verified ancestor.
+ *
+ * `leaf` says what the final component may be when it already exists:
+ * `'dir'` for a directory a publish will populate, `'file'` for a destination
+ * file (a directory or link there would redirect or block the write). Every
+ * intermediate component must be a plain directory.
+ *
+ * Pass the REAL repo root (`realpath`); a root that is itself a symlink is
+ * refused.
+ */
+export async function isSymlinkFreeRepoPath(repoRoot, absPath, { leaf }) {
+ const root = resolve(repoRoot);
+ const target = resolve(absPath);
+ if (!isPathAtOrInsideDir(root, target)) return false;
+ const rootStat = await lstat(root);
+ if (rootStat.isSymbolicLink() || !rootStat.isDirectory()) return false;
+ let existing = root;
+ const parts = relative(root, target).split(sep).filter(Boolean);
+ for (const [index, part] of parts.entries()) {
+ const next = join(existing, part);
+ const info = await lstat(next).catch((err) => {
+ if (err.code === 'ENOENT') return null;
+ throw err;
+ });
+ if (!info) break;
+ const isLeaf = index === parts.length - 1;
+ const wantedKind = isLeaf && leaf === 'file' ? info.isFile() : info.isDirectory();
+ if (info.isSymbolicLink() || !wantedKind) return false;
+ existing = next;
+ }
+ return isPathAtOrInsideDir(root, await realpath(existing));
+}
diff --git a/server/lib/wavAudioFile.js b/server/lib/wavAudioFile.js
index f7adde970e..ff8b4bf498 100644
--- a/server/lib/wavAudioFile.js
+++ b/server/lib/wavAudioFile.js
@@ -6,6 +6,8 @@
* the Music Designer code engine's browser-recorded takes.
*/
+import { randomUUID } from 'crypto';
+import { rename } from 'fs/promises';
import { join } from 'path';
import { atomicWrite, unlinkGuarded } from './fileUtils.js';
import { findFfmpeg, runFfmpegProcess } from './ffmpeg.js';
@@ -23,10 +25,19 @@ export async function writeWavAudioFile(wav, dir, basename) {
await unlinkGuarded(oggPath).catch(() => {});
return `${basename}.wav`;
}
- const result = await runFfmpegProcess({ bin, args: ['-y', '-i', wavPath, '-c:a', 'libvorbis', '-q:a', '5', oggPath] });
- if (!result.ok) {
- console.error(`❌ OGG encode failed (keeping WAV): ${result.reason}`);
- await unlinkGuarded(oggPath).catch(() => {}); // stale or partial encode output
+ // Encode to a sibling temp file and rename over the destination: ffmpeg
+ // truncates and writes THROUGH a leaf symlink at `oggPath`, a rename replaces
+ // the link itself (#10894).
+ const stagedOgg = `${oggPath}.${randomUUID()}.tmp`;
+ const result = await runFfmpegProcess({ bin, args: ['-y', '-i', wavPath, '-c:a', 'libvorbis', '-q:a', '5', '-f', 'ogg', stagedOgg] });
+ const landed = result.ok && await rename(stagedOgg, oggPath).then(() => true, (err) => {
+ console.error(`❌ OGG rename failed (keeping WAV): ${err.message}`);
+ return false;
+ });
+ if (!landed) {
+ if (!result.ok) console.error(`❌ OGG encode failed (keeping WAV): ${result.reason}`);
+ await unlinkGuarded(stagedOgg).catch(() => {}); // partial encode output
+ await unlinkGuarded(oggPath).catch(() => {}); // stale output from an earlier write
return `${basename}.wav`;
}
await unlinkGuarded(wavPath).catch(() => {});
diff --git a/server/lib/wavAudioFile.test.js b/server/lib/wavAudioFile.test.js
index 13b94c47c4..017f375790 100644
--- a/server/lib/wavAudioFile.test.js
+++ b/server/lib/wavAudioFile.test.js
@@ -1,5 +1,24 @@
-import { describe, expect, it } from 'vitest';
-import { measureWavAudio, wavDurationMs } from './wavAudioFile.js';
+import { lstat, mkdir, mkdtemp, readFile, readdir, rm, symlink, writeFile } from 'fs/promises';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { afterAll, describe, expect, it, vi } from 'vitest';
+
+// ffmpeg double: like the real binary it opens its output path and writes
+// THROUGH a symlink there; the last argument is the output file.
+vi.mock('./ffmpeg.js', () => ({
+ findFfmpeg: vi.fn().mockResolvedValue('/fake/ffmpeg'),
+ runFfmpegProcess: vi.fn(async ({ args }) => {
+ await writeFile(args.at(-1), 'encoded-ogg');
+ return { ok: true };
+ }),
+}));
+
+const { measureWavAudio, wavDurationMs, writeWavAudioFile } = await import('./wavAudioFile.js');
+
+const tmpRoots = [];
+afterAll(async () => {
+ await Promise.all(tmpRoots.map((dir) => rm(dir, { recursive: true, force: true })));
+});
// Minimal RIFF/WAVE writer: `samples` is interleaved, already in [-1, 1].
function wav({ samples, channels = 2, sampleRate = 48000, format = 'int16', extensible = false, leadingChunk = false }) {
@@ -57,3 +76,23 @@ describe('measureWavAudio', () => {
expect(measureWavAudio(null)).toBeNull();
});
});
+
+describe('writeWavAudioFile OGG staging (#10894)', () => {
+ it('replaces a leaf symlink at the OGG destination instead of encoding through it', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'wav-ogg-'));
+ tmpRoots.push(root);
+ const dir = join(root, 'out');
+ await mkdir(dir);
+ const victim = join(root, 'victim.ogg');
+ await writeFile(victim, 'victim-bytes');
+ await symlink(victim, join(dir, 'loop.ogg'));
+
+ const name = await writeWavAudioFile(wav({ samples: stereoTone(480, 0.25) }), dir, 'loop');
+
+ expect(name).toBe('loop.ogg');
+ expect(await readFile(victim, 'utf8')).toBe('victim-bytes');
+ expect((await lstat(join(dir, 'loop.ogg'))).isFile()).toBe(true);
+ expect(await readFile(join(dir, 'loop.ogg'), 'utf8')).toBe('encoded-ogg');
+ expect(await readdir(dir)).toEqual(['loop.ogg']); // no staged temp or WAV left behind
+ });
+});
diff --git a/server/services/chiptune.js b/server/services/chiptune.js
index b3642eb28e..e827a549d4 100644
--- a/server/services/chiptune.js
+++ b/server/services/chiptune.js
@@ -14,10 +14,11 @@
* repo owns its own git — we only write files.
*/
-import { stat } from 'fs/promises';
+import { mkdir, realpath, stat } from 'fs/promises';
import { join, resolve, isAbsolute } from 'path';
import { ServerError } from '../lib/errorHandler.js';
import { atomicWrite, isPathInsideDir } from '../lib/fileUtils.js';
+import { isSymlinkFreeRepoPath } from '../lib/repoPublishPath.js';
import { writeWavAudioFile } from '../lib/wavAudioFile.js';
import { chiptuneScoreSchema, CHIPTUNE_LIMITS, CHIPTUNE_NOISE_PRESETS, scoreDurationSec } from '../lib/chiptuneScore.js';
import { renderScoreToWav } from '../lib/chiptuneRender.js';
@@ -137,13 +138,13 @@ export async function renderChiptuneTrack({ trackId }) {
const SLUG_RE = /[^a-z0-9-]+/g;
const slugify = (s) => String(s || '').toLowerCase().trim().replace(SLUG_RE, '-').replace(/^-+|-+$/g, '').slice(0, 64);
+const badSubdir = (message) => new ServerError(message, { status: 400, code: 'CHIPTUNE_BAD_SUBDIR' });
+
// A publish subdir must stay inside the app repo: relative, no traversal, no
// backslashes (Windows-style separators would dodge the segment check).
function assertSafeSubdir(subdir) {
- if (isAbsolute(subdir) || subdir.includes('\\') || subdir.split('/').some((seg) => seg === '..')) {
- throw new ServerError('Publish subdir must be a relative path inside the app repo', {
- status: 400, code: 'CHIPTUNE_BAD_SUBDIR',
- });
+ if (isAbsolute(subdir) || subdir.includes('\\') || subdir.includes('\0') || subdir.split('/').some((seg) => seg === '..')) {
+ throw badSubdir('Publish subdir must be a relative path inside the app repo');
}
}
@@ -166,11 +167,13 @@ export async function publishChiptuneTrack({ trackId, appId, subdir, slug }) {
if (app.id === PORTOS_APP_ID || app.archived) {
throw new ServerError('That app is not a publishable target', { status: 400, code: 'CHIPTUNE_APP_NOT_PUBLISHABLE' });
}
- const repoRoot = resolve(app.repoPath);
- const repoStat = await stat(repoRoot).catch(() => null);
+ const repoStat = await stat(app.repoPath).catch(() => null);
if (!repoStat?.isDirectory()) {
throw new ServerError(`App repo path does not exist: ${app.repoPath}`, { status: 400, code: 'CHIPTUNE_APP_REPO_MISSING' });
}
+ // Anchor on the REAL root: a lexical check cannot see a directory symlink
+ // inside the checkout that points elsewhere (#10894).
+ const repoRoot = await realpath(app.repoPath);
// Validate the RAW subdir before any normalization — stripping a leading
// slash first would launder an absolute path into a relative-looking one.
@@ -179,12 +182,27 @@ export async function publishChiptuneTrack({ trackId, appId, subdir, slug }) {
const cleanSubdir = rawSubdir.replace(/\/+$/g, '');
const targetDir = resolve(repoRoot, cleanSubdir);
if (targetDir !== repoRoot && !isPathInsideDir(repoRoot, targetDir)) {
- throw new ServerError('Publish target escapes the app repo', { status: 400, code: 'CHIPTUNE_BAD_SUBDIR' });
+ throw badSubdir('Publish target escapes the app repo');
}
const name = slugify(slug) || slugify(track.title) || 'track';
- const audioFilename = await renderScoreToFile(score, targetDir, name);
const scoreFilename = `${name}.score.json`;
+ // Preflight EVERY destination (WAV fallback, OGG, score sidecar) before the
+ // first mutation so a bad one can't leave a partial publish behind.
+ const assertDestinationsContained = async () => {
+ const targetOk = await isSymlinkFreeRepoPath(repoRoot, targetDir, { leaf: 'dir' });
+ const leavesOk = targetOk && (await Promise.all(
+ [`${name}.wav`, `${name}.ogg`, scoreFilename].map((f) => isSymlinkFreeRepoPath(repoRoot, join(targetDir, f), { leaf: 'file' })),
+ )).every(Boolean);
+ if (!leavesOk) throw badSubdir('Publish target must stay inside the app repo without symlinks');
+ };
+ await assertDestinationsContained();
+ // Create the directory ourselves and re-check the completed parent, so a
+ // link planted after the preflight (or created mid-path) is still caught.
+ await mkdir(targetDir, { recursive: true });
+ await assertDestinationsContained();
+
+ const audioFilename = await renderScoreToFile(score, targetDir, name);
await atomicWrite(join(targetDir, scoreFilename), `${JSON.stringify(score, null, 2)}\n`);
const rel = (f) => (cleanSubdir ? `${cleanSubdir}/${f}` : f);
diff --git a/server/services/chiptune.test.js b/server/services/chiptune.test.js
index 38adba2581..4a32b7e07a 100644
--- a/server/services/chiptune.test.js
+++ b/server/services/chiptune.test.js
@@ -1,4 +1,4 @@
-import { mkdtemp, readFile, readdir, rm } from 'fs/promises';
+import { lstat, mkdir, mkdtemp, readFile, readdir, realpath, rm, symlink, writeFile } from 'fs/promises';
import { tmpdir } from 'os';
import { join } from 'path';
import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -217,4 +217,84 @@ describe('publishChiptuneTrack', () => {
const result = await publishChiptuneTrack({ trackId: 'track-1', appId: 'app-1', subdir: 'assets/bgm', slug: 'Overworld Theme!' });
expect(result.files[0]).toBe('assets/bgm/overworld-theme.wav');
});
+
+ describe('symlink containment (#10894)', () => {
+ // Disposable synthetic roots: <root>/app is the managed repo, <root>/outside is
+ // an unrelated directory holding pre-existing files a publish must not touch.
+ const setup = async () => {
+ const root = await makeTmp('chiptune-symlink-');
+ const repo = join(root, 'app');
+ const outside = join(root, 'outside');
+ await mkdir(repo);
+ await mkdir(outside);
+ await writeFile(join(outside, 'example.wav'), 'outside-wav');
+ await writeFile(join(outside, 'example.score.json'), 'outside-score');
+ tracks.getTrack.mockResolvedValue(baseTrack({ chiptuneScore: validScore() }));
+ apps.getAppById.mockResolvedValue({ id: 'app-1', name: 'Game', repoPath: repo });
+ return { repo, outside };
+ };
+ const publish = (subdir) => publishChiptuneTrack({ trackId: 'track-1', appId: 'app-1', subdir, slug: 'example' });
+ const expectOutsideUntouched = async (outside) => {
+ expect(await readFile(join(outside, 'example.wav'), 'utf8')).toBe('outside-wav');
+ expect(await readFile(join(outside, 'example.score.json'), 'utf8')).toBe('outside-score');
+ expect((await readdir(outside)).sort()).toEqual(['example.score.json', 'example.wav']);
+ };
+
+ it('refuses a subdir that is a directory symlink out of the app, leaving outside files unchanged', async () => {
+ const { repo, outside } = await setup();
+ await symlink(outside, join(repo, 'linked-assets'));
+ await expect(publish('linked-assets')).rejects.toMatchObject({ code: 'CHIPTUNE_BAD_SUBDIR' });
+ await expectOutsideUntouched(outside);
+ });
+
+ it('refuses a symlink in the middle of a nested subdir and a dangling directory link', async () => {
+ const { repo, outside } = await setup();
+ await symlink(outside, join(repo, 'shared'));
+ await expect(publish('shared/music')).rejects.toMatchObject({ code: 'CHIPTUNE_BAD_SUBDIR' });
+ await symlink(join(outside, 'nope'), join(repo, 'dangling'));
+ await expect(publish('dangling')).rejects.toMatchObject({ code: 'CHIPTUNE_BAD_SUBDIR' });
+ await expectOutsideUntouched(outside);
+ await expect(readdir(join(outside, 'nope'))).rejects.toMatchObject({ code: 'ENOENT' });
+ });
+
+ it('refuses a symlinked destination leaf before any write, so there is no partial publish', async () => {
+ const { repo, outside } = await setup();
+ const dir = join(repo, 'assets');
+ await mkdir(dir);
+ // Only the LAST destination (the score sidecar) is invalid: the WAV must not be written first.
+ await symlink(join(outside, 'example.score.json'), join(dir, 'example.score.json'));
+ await expect(publish('assets')).rejects.toMatchObject({ code: 'CHIPTUNE_BAD_SUBDIR' });
+ expect(await readdir(dir)).toEqual(['example.score.json']);
+ expect(await readFile(join(outside, 'example.score.json'), 'utf8')).toBe('outside-score');
+
+ await rm(join(dir, 'example.score.json'));
+ await symlink(join(outside, 'missing.ogg'), join(dir, 'example.ogg')); // dangling OGG link
+ await expect(publish('assets')).rejects.toMatchObject({ code: 'CHIPTUNE_BAD_SUBDIR' });
+ expect(await readdir(dir)).toEqual(['example.ogg']);
+ await expectOutsideUntouched(outside);
+ });
+
+ it('refuses a link substituted between two requests', async () => {
+ const { repo, outside } = await setup();
+ await publish('assets');
+ expect((await lstat(join(repo, 'assets/example.wav'))).isFile()).toBe(true);
+ await rm(join(repo, 'assets'), { recursive: true });
+ await symlink(outside, join(repo, 'assets'));
+ await expect(publish('assets')).rejects.toMatchObject({ code: 'CHIPTUNE_BAD_SUBDIR' });
+ await expectOutsideUntouched(outside);
+ });
+
+ it('still creates missing nested directories and publishes through a symlinked repo root', async () => {
+ const { repo, outside } = await setup();
+ const alias = join(await makeTmp('chiptune-alias-'), 'repo-link');
+ await symlink(repo, alias); // the checkout path itself may legitimately be a link
+ apps.getAppById.mockResolvedValue({ id: 'app-1', name: 'Game', repoPath: alias });
+ const result = await publish('a/b/music/');
+ expect(result.files).toEqual(['a/b/music/example.wav', 'a/b/music/example.score.json']);
+ const realRepo = await realpath(repo);
+ expect((await lstat(join(realRepo, 'a/b/music/example.wav'))).isFile()).toBe(true);
+ expect((await lstat(join(realRepo, 'a/b/music/example.score.json'))).isFile()).toBe(true);
+ await expectOutsideUntouched(outside);
+ });
+ });
});
diff --git a/server/services/sprites/publish.js b/server/services/sprites/publish.js
index c13acfbf60..e3290db6bb 100644
--- a/server/services/sprites/publish.js
+++ b/server/services/sprites/publish.js
@@ -31,12 +31,13 @@
* posture) nested inside the record's walk write tail.
*/
-import { dirname, join, relative, resolve, sep } from 'path';
-import { lstat, mkdir, readFile, realpath, stat } from 'fs/promises';
+import { dirname, join, resolve } from 'path';
+import { mkdir, readFile, realpath, stat } from 'fs/promises';
import {
atomicWrite, isPathInsideDir, readJSONFile, safeJSONParse, sha256File, pathExists,
} from '../../lib/fileUtils.js';
import { isPathAtOrInsideDir } from '../../lib/pathContainment.js';
+import { isSymlinkFreeRepoPath } from '../../lib/repoPublishPath.js';
import { ServerError } from '../../lib/errorHandler.js';
import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';
import { getAppById } from '../apps.js';
@@ -79,25 +80,9 @@ async function anchorRepoPath(repoRoot, relPath, label) {
if (abs === resolve(repoRoot) || !isPathInsideDir(repoRoot, abs)) {
throw bindingError(`${label} escapes the app repository: ${relPath}`, 'INVALID_PUBLISH_PATH');
}
- const invalid = () => bindingError(`${label} must stay inside the app repository without symlinks: ${relPath}`, 'INVALID_PUBLISH_PATH');
- // Walk from the real root so even dangling or contained symlinks are refused,
- // rather than mistaken for a missing destination or silently followed.
- const rootStat = await lstat(repoRoot);
- if (rootStat.isSymbolicLink() || !rootStat.isDirectory()) throw invalid();
- let existing = repoRoot;
- const parts = relative(repoRoot, abs).split(sep);
- for (const [index, part] of parts.entries()) {
- const next = join(existing, part);
- const info = await lstat(next).catch((err) => {
- if (err.code === 'ENOENT') return null;
- throw err;
- });
- if (!info) break;
- if (info.isSymbolicLink()
- || (index < parts.length - 1 ? !info.isDirectory() : !info.isFile())) throw invalid();
- existing = next;
+ if (!(await isSymlinkFreeRepoPath(repoRoot, abs, { leaf: 'file' }))) {
+ throw bindingError(`${label} must stay inside the app repository without symlinks: ${relPath}`, 'INVALID_PUBLISH_PATH');
}
- if (!isPathAtOrInsideDir(repoRoot, await realpath(existing))) throw invalid();
return abs;
}