From 1d60fe00b599afe99cbd4cb31cb1253b0cae29a4 Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 02:02:42 +0100 Subject: [PATCH 01/39] fix(server-core): keep the server running when the watcher cannot read a folder --- packages/server-core/src/fs/watcher.ts | 10 ++++++- .../src/project/project-registry.ts | 1 + .../server-core/test/fs/fs-service.spec.ts | 28 +++++++++++++++++++ 3 files changed, 38 insertions(+), 1 deletion(-) diff --git a/packages/server-core/src/fs/watcher.ts b/packages/server-core/src/fs/watcher.ts index 1941498c..916cf41f 100644 --- a/packages/server-core/src/fs/watcher.ts +++ b/packages/server-core/src/fs/watcher.ts @@ -33,6 +33,11 @@ export interface WatcherOptions { /** Paths hidden from the editor (`.nfignore`), checked for each change. */ isIgnored?: (path: string, directory: boolean) => boolean; batchMs?: number; + /** + * A folder that can't be watched (unreadable, or past the inotify limit: `ENOSPC`, `EMFILE`). + * The rest of the project is still watched. + */ + onError?: (error: unknown) => void; } /** @@ -103,6 +108,7 @@ export class ProjectWatcher { ignored: this._ignored, awaitWriteFinish: false, atomic: true, + ignorePermissionErrors: true, }); this._watcher = watcher; this._ready = new Promise((resolve) => watcher.once('ready', () => resolve())); @@ -113,7 +119,9 @@ export class ProjectWatcher { .on('addDir', push('created', 'directory')) .on('change', push('changed', 'file')) .on('unlink', push('deleted', 'file')) - .on('unlinkDir', push('deleted', 'directory')); + .on('unlinkDir', push('deleted', 'directory')) + /** Without a listener, an `error` event throws and ends the server. */ + .on('error', (error) => this._options.onError?.(error)); } private async _stop(): Promise { diff --git a/packages/server-core/src/project/project-registry.ts b/packages/server-core/src/project/project-registry.ts index 7674d099..5b95be79 100644 --- a/packages/server-core/src/project/project-registry.ts +++ b/packages/server-core/src/project/project-registry.ts @@ -61,6 +61,7 @@ export class OpenProject implements Disposable { this.watcher = new ProjectWatcher(this.fs.jail, { ignoredPaths: () => this._model.get().apps.flatMap((app) => (app.outDir ? [app.outDir] : [])), isIgnored: (path, directory) => this.fs.isIgnored(path, directory), + onError: (error) => this._logger.warn(`Could not watch part of ${location}`, error), }); void this.fs.refreshIgnore(); void this.fs diff --git a/packages/server-core/test/fs/fs-service.spec.ts b/packages/server-core/test/fs/fs-service.spec.ts index 2bcb4ac8..095e6565 100644 --- a/packages/server-core/test/fs/fs-service.spec.ts +++ b/packages/server-core/test/fs/fs-service.spec.ts @@ -24,6 +24,15 @@ import { ProjectWatcher } from '../../src/fs/watcher'; import { sha1 } from '../../src/util/hash'; const roots: string[] = []; +/** Folders made unreadable by a test: given back their mode so they can be removed. */ +const locked: string[] = []; +/** Root reads every folder whatever its mode. */ +const asRoot = process.getuid?.() === 0; +const lock = (path: string) => { + mkdirSync(path, { recursive: true }); + chmodSync(path, 0o000); + locked.push(path); +}; const project = () => { const root = mkdtempSync(join(tmpdir(), 'nf-fs-')); roots.push(root); @@ -32,6 +41,7 @@ const project = () => { return { root, fs: new ProjectFileSystem(root) }; }; afterEach(() => { + for (const path of locked.splice(0)) chmodSync(path, 0o755); for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); }); @@ -332,4 +342,22 @@ describe('ProjectWatcher', () => { subscription.dispose(); expect(batches.flat().map((change) => change.path)).toEqual(['src/new.ts']); }); + + it.skipIf(asRoot)('keeps watching past a folder it cannot read', async () => { + const { root, fs } = project(); + lock(join(root, 'pgdata')); + const errors: unknown[] = []; + const watcher = new ProjectWatcher(fs.jail, { onError: (error) => errors.push(error) }); + const batches: FileChange[][] = []; + const subscription = watcher.onDidChange((changes) => batches.push(changes)); + await watcher.ready; + writeFileSync(join(root, 'src/new.ts'), 'x'); + const start = Date.now(); + while (!batches.length && Date.now() - start < 1000) await new Promise((r) => setTimeout(r, 5)); + const limit = Object.assign(new Error('watch limit'), { code: 'ENOSPC' }); + watcher['_watcher']?.emit('error', limit); + subscription.dispose(); + expect(batches.flat().map((change) => change.path)).toEqual(['src/new.ts']); + expect(errors).toEqual([limit]); + }); }); From b0c31eb2dd4f8b307934afac65ef350cd566f576 Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 02:03:09 +0100 Subject: [PATCH 02/39] fix(server-core): skip an unreadable subfolder in a recursive listing --- packages/server-core/src/fs/fs-service.ts | 3 +++ packages/server-core/test/fs/fs-service.spec.ts | 11 +++++++++++ 2 files changed, 14 insertions(+) diff --git a/packages/server-core/src/fs/fs-service.ts b/packages/server-core/src/fs/fs-service.ts index 90835229..6ce488f5 100644 --- a/packages/server-core/src/fs/fs-service.ts +++ b/packages/server-core/src/fs/fs-service.ts @@ -145,6 +145,9 @@ export class ProjectFileSystem { try { names = await readdir(dir, { withFileTypes: true }); } catch (error) { + /** One unreadable subfolder (a root-owned `pgdata/`) must not hide the whole project. */ + const code = errno(error); + if (dir !== absolute && (code === 'EACCES' || code === 'EPERM')) return; return mapError(error, rel); } for (const entry of names.sort((a, b) => a.name.localeCompare(b.name))) { diff --git a/packages/server-core/test/fs/fs-service.spec.ts b/packages/server-core/test/fs/fs-service.spec.ts index 095e6565..514c8123 100644 --- a/packages/server-core/test/fs/fs-service.spec.ts +++ b/packages/server-core/test/fs/fs-service.spec.ts @@ -127,6 +127,17 @@ describe('ProjectFileSystem', () => { ]); }); + it.skipIf(asRoot)('lists past a subfolder it cannot read, not past the root', async () => { + const { root, fs } = project(); + lock(join(root, 'pgdata')); + expect((await fs.list('', true)).map((e) => [e.path, e.kind])).toEqual([ + ['pgdata', 'directory'], + ['src', 'directory'], + ['src/main.ts', 'file'], + ]); + await expect(fs.list('pgdata', true)).rejects.toMatchObject({ code: 'FORBIDDEN' }); + }); + it('never reaches a .git folder', async () => { const { root, fs } = project(); mkdirSync(join(root, '.git/hooks'), { recursive: true }); From 608da40fed6a14cd1fa4a7f3ebf021d276313db2 Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 02:03:55 +0100 Subject: [PATCH 03/39] fix(server-core): stream a folder zip without hashing its files first --- packages/server-core/src/fs/archive.ts | 8 +++----- packages/server-core/src/fs/fs-service.ts | 17 ++++++++++++++--- packages/server-core/test/fs/fs-service.spec.ts | 11 +++++++++++ 3 files changed, 28 insertions(+), 8 deletions(-) diff --git a/packages/server-core/src/fs/archive.ts b/packages/server-core/src/fs/archive.ts index ce5e697f..5b7d2bb5 100644 --- a/packages/server-core/src/fs/archive.ts +++ b/packages/server-core/src/fs/archive.ts @@ -13,9 +13,6 @@ const LEFT_OUT = [TRASH_DIR, PACKAGES_DIR]; /** From this size on, a file is compressed in a worker (as fflate's `zip()` does). */ const ASYNC_FROM_BYTES = 160_000; -const leftOut = (path: string) => - LEFT_OUT.some((folder) => path === folder || path.startsWith(`${folder}/`)); - /** * Zips a folder of the project as a stream: one file read at a time, as the reader asks for * more (the next once the last is zipped), so a large folder is never held in memory. A file @@ -28,8 +25,9 @@ export const archiveFolder = async ( maxBytes = MAX_ARCHIVE_BYTES, ): Promise> => { const prefix = path ? `${path}/` : ''; - const files = (await fs.list(path, true)).filter( - (entry) => entry.kind === 'file' && !leftOut(entry.path), + /** Sizes only: the zip never uses the hashes, and its first byte would wait for them. */ + const files = (await fs.list(path, true, { hash: false, leaveOut: LEFT_OUT })).filter( + (entry) => entry.kind === 'file', ); const total = files.reduce((sum, entry) => sum + entry.size, 0); if (total > maxBytes) diff --git a/packages/server-core/src/fs/fs-service.ts b/packages/server-core/src/fs/fs-service.ts index 6ce488f5..181b32e0 100644 --- a/packages/server-core/src/fs/fs-service.ts +++ b/packages/server-core/src/fs/fs-service.ts @@ -133,7 +133,15 @@ export class ProjectFileSystem { } } - async list(path: string, recursive = false): Promise { + /** + * Entries of a folder, sorted by name. `hash: false` skips the content hashes (sizes only); + * `leaveOut` folders (project-relative) are neither listed nor walked. + */ + async list( + path: string, + recursive = false, + options: { hash?: boolean; leaveOut?: readonly string[] } = {}, + ): Promise { assertAccessible(path); const absolute = await this.jail.resolve(path); await this.refreshIgnore(); @@ -157,8 +165,9 @@ export class ProjectFileSystem { if (!info) continue; const kind = info.isDirectory() ? 'directory' : 'file'; if (this.isIgnored(childRel, kind === 'directory')) continue; + if (options.leaveOut?.some((folder) => isUnder(childRel, folder))) continue; /** Pipes would block the read; the trash is never read, so its files cost nothing. */ - if (info.isFile() && !inTrash(childRel)) + if (options.hash !== false && info.isFile() && !inTrash(childRel)) files.push({ index: entries.length, absolute: join(dir, entry.name), info }); entries.push({ path: childRel, kind, size: info.size, mtime: info.mtimeMs }); if (recursive && kind === 'directory' && !SKIPPED_IN_RECURSIVE_LIST.has(entry.name)) { @@ -387,4 +396,6 @@ export class ProjectFileSystem { /** Heavy folders a recursive listing does not descend into. */ const SKIPPED_IN_RECURSIVE_LIST = new Set(['node_modules']); -const inTrash = (path: string) => path === TRASH_DIR || path.startsWith(`${TRASH_DIR}/`); +const isUnder = (path: string, folder: string) => path === folder || path.startsWith(`${folder}/`); + +const inTrash = (path: string) => isUnder(path, TRASH_DIR); diff --git a/packages/server-core/test/fs/fs-service.spec.ts b/packages/server-core/test/fs/fs-service.spec.ts index 514c8123..7a0d04e2 100644 --- a/packages/server-core/test/fs/fs-service.spec.ts +++ b/packages/server-core/test/fs/fs-service.spec.ts @@ -138,6 +138,17 @@ describe('ProjectFileSystem', () => { await expect(fs.list('pgdata', true)).rejects.toMatchObject({ code: 'FORBIDDEN' }); }); + it('lists without hashes and without the folders left out, when asked', async () => { + const { root, fs } = project(); + mkdirSync(join(root, 'nf_modules/@a/b'), { recursive: true }); + writeFileSync(join(root, 'nf_modules/@a/b/index.ts'), 'x'); + const entries = await fs.list('', true, { hash: false, leaveOut: ['nf_modules'] }); + expect(entries.map((e) => [e.path, e.hash])).toEqual([ + ['src', undefined], + ['src/main.ts', undefined], + ]); + }); + it('never reaches a .git folder', async () => { const { root, fs } = project(); mkdirSync(join(root, '.git/hooks'), { recursive: true }); From fee7cbdd2ce03d8ad91cddff04173bfe33d3e5e6 Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 02:04:57 +0100 Subject: [PATCH 04/39] fix(server-core): check nf_modules on the real path so a link cannot change it --- packages/server-core/src/fs/fs-service.ts | 46 ++++++++----------- packages/server-core/src/fs/path-jail.ts | 17 ++++++- .../server-core/test/fs/fs-service.spec.ts | 33 +++++++++++++ 3 files changed, 67 insertions(+), 29 deletions(-) diff --git a/packages/server-core/src/fs/fs-service.ts b/packages/server-core/src/fs/fs-service.ts index 181b32e0..9b95810d 100644 --- a/packages/server-core/src/fs/fs-service.ts +++ b/packages/server-core/src/fs/fs-service.ts @@ -15,7 +15,7 @@ import { RpcError } from '@nanoforge-dev/editor-rpc'; import { sha1 } from '../util/hash'; import { KeyedMutex } from '../util/keyed-mutex'; import { FileHashes, type FileVersion } from './file-hashes'; -import { PathJail } from './path-jail'; +import { type PathGuard, PathJail, gitReason, isGitPath } from './path-jail'; export const EDITOR_DIR = '.nanoforge/editor'; export const TRASH_DIR = `${EDITOR_DIR}/trash`; @@ -54,29 +54,21 @@ const mapError = (error: unknown, path: string): never => { } }; -/** - * A repository's own folder is never reached through the file API: writing hooks or config there - * runs code on the next git command, and its config may hold credentials. - */ -const isGitPath = (path: string) => - path.split(/[\\/]/).some((part) => part.toLowerCase() === '.git'); - -const gitReason = (path: string) => - isGitPath(path) ? `${path} is inside a .git folder` : undefined; - const assertAccessible = (path: string) => { const refused = gitReason(path); if (refused) throw new RpcError('FORBIDDEN', refused); }; +/** {@link PathGuard} refusing a path inside `nf_modules`: installing is the only way to change it. */ +const packagesReason: PathGuard = (path) => + path === PACKAGES_DIR || path.startsWith(`${PACKAGES_DIR}/`) + ? `${path} is part of an installed package (nf_modules), which cannot be changed. Copy it into your project to modify it.` + : undefined; + const assertWritable = (path: string) => { assertAccessible(path); - if (path === PACKAGES_DIR || path.startsWith(`${PACKAGES_DIR}/`)) { - throw new RpcError( - 'FORBIDDEN', - `${path} is part of an installed package (nf_modules), which cannot be changed. Copy it into your project to modify it.`, - ); - } + const refused = packagesReason(path); + if (refused) throw new RpcError('FORBIDDEN', refused); }; /** File operations of one project, jailed to its root. */ @@ -251,7 +243,7 @@ export class ProjectFileSystem { ): Promise { if (path === '') throw new RpcError('BAD_REQUEST', 'Cannot write the project root'); assertWritable(path); - const absolute = await this.jail.resolve(path); + const absolute = await this.jail.resolve(path, packagesReason); return this._writes.run(absolute, async () => { if (options.expectedHash !== undefined) { const current = await readFile(absolute).then( @@ -283,7 +275,7 @@ export class ProjectFileSystem { async mkdir(path: string): Promise { assertWritable(path); - const absolute = await this.jail.resolve(path); + const absolute = await this.jail.resolve(path, packagesReason); await mkdir(absolute, { recursive: true }).catch((error: unknown) => mapError(error, path)); return (await this.stat(path))!; } @@ -291,8 +283,8 @@ export class ProjectFileSystem { async rename(from: string, to: string, overwrite = false): Promise { assertWritable(from); assertWritable(to); - const source = await this.jail.resolve(from); - const target = await this.jail.resolve(to); + const source = await this.jail.resolve(from, packagesReason); + const target = await this.jail.resolve(to, packagesReason); if (!existsSync(source)) throw notFound(from); if (!overwrite && existsSync(target)) throw new RpcError('CONFLICT', `Already exists: ${to}`); await mkdir(dirname(target), { recursive: true }); @@ -304,7 +296,7 @@ export class ProjectFileSystem { assertAccessible(from); assertWritable(to); const source = await this.jail.resolve(from); - const target = await this.jail.resolve(to); + const target = await this.jail.resolve(to, packagesReason); if (!existsSync(source)) throw notFound(from); await cp(source, target, { recursive: true, force: overwrite, errorOnExist: !overwrite }).catch( (error: unknown) => mapError(error, from), @@ -321,9 +313,9 @@ export class ProjectFileSystem { throw new RpcError('BAD_REQUEST', `Cannot delete ${path || 'the project root'}`); } assertWritable(path); - const source = await this.jail.resolve(path); + const source = await this.jail.resolve(path, packagesReason); if (!existsSync(source)) throw notFound(path); - const trash = await this.jail.resolve(TRASH_DIR); + const trash = await this.jail.resolve(TRASH_DIR, packagesReason); await mkdir(trash, { recursive: true }); await this._ensureEditorGitignore(); const target = join( @@ -339,7 +331,7 @@ export class ProjectFileSystem { * bring them back). Returns how many went. */ async purgeTrash(now = Date.now()): Promise { - const trash = await this.jail.resolve(TRASH_DIR); + const trash = await this.jail.resolve(TRASH_DIR, packagesReason); const names = await readdir(trash).catch(() => [] as string[]); let purged = 0; for (const name of names) { @@ -361,7 +353,7 @@ export class ProjectFileSystem { } assertWritable(to); const source = await this.jail.resolve(trashPath); - const target = await this.jail.resolve(to); + const target = await this.jail.resolve(to, packagesReason); if (!existsSync(source)) throw notFound(trashPath); if (existsSync(target)) throw new RpcError('CONFLICT', `Already exists: ${to}`); await mkdir(dirname(target), { recursive: true }); @@ -388,7 +380,7 @@ export class ProjectFileSystem { } private async _ensureEditorGitignore(): Promise { - const file = await this.jail.resolve(`${EDITOR_DIR}/.gitignore`); + const file = await this.jail.resolve(`${EDITOR_DIR}/.gitignore`, packagesReason); if (!existsSync(file)) await writeFile(file, EDITOR_GITIGNORE); } } diff --git a/packages/server-core/src/fs/path-jail.ts b/packages/server-core/src/fs/path-jail.ts index c168707e..90a3f25b 100644 --- a/packages/server-core/src/fs/path-jail.ts +++ b/packages/server-core/src/fs/path-jail.ts @@ -31,10 +31,22 @@ const realpathLenient = async (target: string): Promise => { */ export type PathGuard = (real: string) => string | undefined; +/** + * A repository's own folder is never reached through the file API: writing hooks or config there + * runs code on the next git command, and its config may hold credentials. + */ +export const isGitPath = (path: string): boolean => + path.split(/[\\/]/).some((part) => part.toLowerCase() === '.git'); + +/** {@link PathGuard} refusing a path inside a `.git` folder. */ +export const gitReason: PathGuard = (path) => + isGitPath(path) ? `${path} is inside a .git folder` : undefined; + /** * Resolves project-relative paths to absolute ones inside `root`, rejecting `..` escapes and * symlinks pointing outside of the project. `guard` also sees where a path really leads, so a * link inside the project cannot reach a folder the requested path does not name (`.git`). + * A `guard` given to {@link PathJail.resolve} also applies, to that call only (writes). */ export class PathJail { private _realRoot: string | undefined; @@ -44,13 +56,14 @@ export class PathJail { private readonly _guard?: PathGuard, ) {} - async resolve(path: string): Promise { + async resolve(path: string, guard?: PathGuard): Promise { const target = resolve(this.root, path); if (!isInside(this.root, target)) throw this._escape(path); this._realRoot ??= await realpath(this.root); const real = await realpathLenient(target); if (!isInside(this._realRoot, real)) throw this._escape(path); - const refused = this._guard?.(relative(this._realRoot, real).split(sep).join('/')); + const rel = relative(this._realRoot, real).split(sep).join('/'); + const refused = this._guard?.(rel) ?? guard?.(rel); if (refused) throw new RpcError('FORBIDDEN', refused); return target; } diff --git a/packages/server-core/test/fs/fs-service.spec.ts b/packages/server-core/test/fs/fs-service.spec.ts index 7a0d04e2..0de10846 100644 --- a/packages/server-core/test/fs/fs-service.spec.ts +++ b/packages/server-core/test/fs/fs-service.spec.ts @@ -265,6 +265,39 @@ describe('ProjectFileSystem packages, ignore and trash', () => { expect(readFileSync(join(root, 'src/body.ts'), 'utf8')).toBe('export {};\n'); }); + it('never changes installed packages through a link inside the project', async () => { + const { root, fs } = project(); + mkdirSync(join(root, 'nf_modules/@a/b'), { recursive: true }); + writeFileSync(join(root, 'nf_modules/@a/b/index.ts'), 'export {};\n'); + symlinkSync('nf_modules', join(root, 'mods')); + symlinkSync('../nf_modules/@a/b/index.ts', join(root, 'src/index.ts')); + const { trashPath } = await fs.delete('src/main.ts'); + const refused = { code: 'FORBIDDEN' }; + await expect(fs.write('mods/@a/b/index.ts', 'tampered')).rejects.toMatchObject(refused); + await expect(fs.write('mods/@a/b/new.ts', 'x')).rejects.toMatchObject(refused); + await expect(fs.write('src/index.ts', 'tampered')).rejects.toMatchObject(refused); + await expect(fs.mkdir('mods/@a/c')).rejects.toMatchObject(refused); + await expect(fs.delete('mods/@a/b/index.ts')).rejects.toMatchObject(refused); + await expect(fs.rename('mods/@a/b/index.ts', 'src/moved.ts')).rejects.toMatchObject(refused); + await expect(fs.copy('src/index.ts', 'mods/@a/b/copy.ts')).rejects.toMatchObject(refused); + await expect(fs.restore(trashPath, 'mods/@a/b/main.ts')).rejects.toMatchObject(refused); + expect(readdirSync(join(root, 'nf_modules/@a'))).toEqual(['b']); + expect(readdirSync(join(root, 'nf_modules/@a/b'))).toEqual(['index.ts']); + expect(readFileSync(join(root, 'nf_modules/@a/b/index.ts'), 'utf8')).toBe('export {};\n'); + expect(new TextDecoder().decode((await fs.read('mods/@a/b/index.ts')).content)).toBe( + 'export {};\n', + ); + }); + + it('never moves deleted entries into nf_modules through a linked trash', async () => { + const { root, fs } = project(); + mkdirSync(join(root, 'nf_modules')); + mkdirSync(join(root, '.nanoforge/editor'), { recursive: true }); + symlinkSync('../../nf_modules', join(root, '.nanoforge/editor/trash')); + await expect(fs.delete('src/main.ts')).rejects.toMatchObject({ code: 'FORBIDDEN' }); + expect(readdirSync(join(root, 'nf_modules'))).toEqual([]); + }); + it('restores deleted entries from the trash', async () => { const { root, fs } = project(); const { trashPath } = await fs.delete('src/main.ts'); From ecd0ee4d13d421b2660e1190a8d324d1a2d7f775 Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 02:05:34 +0100 Subject: [PATCH 05/39] fix(server-core): keep the mode of a saved file and save through a link to its target --- packages/server-core/src/fs/fs-service.ts | 19 +++++--- packages/server-core/src/fs/path-jail.ts | 11 ++++- .../server-core/test/fs/fs-service.spec.ts | 47 +++++++++++++++++++ 3 files changed, 70 insertions(+), 7 deletions(-) diff --git a/packages/server-core/src/fs/fs-service.ts b/packages/server-core/src/fs/fs-service.ts index 9b95810d..93ca2719 100644 --- a/packages/server-core/src/fs/fs-service.ts +++ b/packages/server-core/src/fs/fs-service.ts @@ -1,7 +1,7 @@ import ignore, { type Ignore } from 'ignore'; import { randomBytes } from 'node:crypto'; import { existsSync } from 'node:fs'; -import { cp, mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises'; +import { chmod, cp, mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises'; import { basename, dirname, join } from 'node:path'; import type { @@ -243,8 +243,12 @@ export class ProjectFileSystem { ): Promise { if (path === '') throw new RpcError('BAD_REQUEST', 'Cannot write the project root'); assertWritable(path); - const absolute = await this.jail.resolve(path, packagesReason); - return this._writes.run(absolute, async () => { + /** + * A link is saved through to its target: the very path the jail checked, never looked up + * again (a dangling link is replaced, even if its target appears meanwhile). + */ + const { target: absolute, real: target } = await this.jail.locate(path, packagesReason); + return this._writes.run(target, async () => { if (options.expectedHash !== undefined) { const current = await readFile(absolute).then( (buffer) => sha1(buffer), @@ -256,12 +260,15 @@ export class ProjectFileSystem { } if (options.createParents !== false) await mkdir(dirname(absolute), { recursive: true }); const temp = join( - dirname(absolute), - `.${basename(absolute)}.nf-${randomBytes(4).toString('hex')}`, + dirname(target), + `.${basename(target)}.nf-${randomBytes(4).toString('hex')}`, ); + /** The new file keeps the old one's mode (an executable script or hook stays one). */ + const mode = (await stat(target).catch(() => undefined))?.mode; try { await writeFile(temp, content); - await rename(temp, absolute); + if (mode !== undefined) await chmod(temp, mode & 0o7777); + await rename(temp, target); } catch (error) { await rm(temp, { force: true }); return mapError(error, path); diff --git a/packages/server-core/src/fs/path-jail.ts b/packages/server-core/src/fs/path-jail.ts index 90a3f25b..9c91b115 100644 --- a/packages/server-core/src/fs/path-jail.ts +++ b/packages/server-core/src/fs/path-jail.ts @@ -57,6 +57,15 @@ export class PathJail { ) {} async resolve(path: string, guard?: PathGuard): Promise { + return (await this.locate(path, guard)).target; + } + + /** + * {@link resolve}, plus where the path really leads (`real`, links followed, the path the + * checks saw): write there, so that what is written is what was checked. A dangling link + * leads to itself (it has no target to check). + */ + async locate(path: string, guard?: PathGuard): Promise<{ target: string; real: string }> { const target = resolve(this.root, path); if (!isInside(this.root, target)) throw this._escape(path); this._realRoot ??= await realpath(this.root); @@ -65,7 +74,7 @@ export class PathJail { const rel = relative(this._realRoot, real).split(sep).join('/'); const refused = this._guard?.(rel) ?? guard?.(rel); if (refused) throw new RpcError('FORBIDDEN', refused); - return target; + return { target, real }; } /** Project-relative POSIX path of an absolute path inside the root. */ diff --git a/packages/server-core/test/fs/fs-service.spec.ts b/packages/server-core/test/fs/fs-service.spec.ts index 0de10846..6aa2b109 100644 --- a/packages/server-core/test/fs/fs-service.spec.ts +++ b/packages/server-core/test/fs/fs-service.spec.ts @@ -3,11 +3,13 @@ import { execFileSync } from 'node:child_process'; import { chmodSync, existsSync, + lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, + statSync, symlinkSync, utimesSync, writeFileSync, @@ -203,6 +205,51 @@ describe('ProjectFileSystem', () => { expect(readdirSync(join(root, 'src')).some((name) => name.includes('.nf-'))).toBe(false); }); + it('keeps the mode of a saved file, and saves through a link to its target', async () => { + const { root, fs } = project(); + writeFileSync(join(root, 'run.sh'), '#!/bin/sh\n', { mode: 0o755 }); + chmodSync(join(root, 'run.sh'), 0o755); + mkdirSync(join(root, 'real')); + writeFileSync(join(root, 'real/target.txt'), 'orig'); + symlinkSync('real/target.txt', join(root, 'link.txt')); + await fs.write('run.sh', '#!/bin/sh\nexit 0\n'); + await fs.write('link.txt', 'edited'); + expect(statSync(join(root, 'run.sh')).mode & 0o777).toBe(0o755); + expect(lstatSync(join(root, 'link.txt')).isSymbolicLink()).toBe(true); + expect(readFileSync(join(root, 'real/target.txt'), 'utf8')).toBe('edited'); + }); + + it('never saves through a link to outside, to nf_modules or to .git', async () => { + const { root, fs } = project(); + const outside = mkdtempSync(join(tmpdir(), 'nf-outside-')); + roots.push(outside); + writeFileSync(join(outside, 'host.txt'), 'host'); + mkdirSync(join(root, 'nf_modules/@a/b'), { recursive: true }); + writeFileSync(join(root, 'nf_modules/@a/b/index.ts'), 'pkg'); + mkdirSync(join(root, '.git')); + writeFileSync(join(root, '.git/config'), 'cfg'); + symlinkSync(join(outside, 'host.txt'), join(root, 'out.txt')); + symlinkSync('nf_modules/@a/b/index.ts', join(root, 'pkg.ts')); + symlinkSync('.git/config', join(root, 'config')); + for (const path of ['out.txt', 'pkg.ts', 'config']) + await expect(fs.write(path, 'tampered'), path).rejects.toMatchObject({ code: 'FORBIDDEN' }); + expect(readFileSync(join(outside, 'host.txt'), 'utf8')).toBe('host'); + expect(readFileSync(join(root, 'nf_modules/@a/b/index.ts'), 'utf8')).toBe('pkg'); + expect(readFileSync(join(root, '.git/config'), 'utf8')).toBe('cfg'); + for (const link of ['out.txt', 'pkg.ts', 'config']) + expect(lstatSync(join(root, link)).isSymbolicLink()).toBe(true); + }); + + it('replaces a dangling link rather than writing outside the project', async () => { + const { root, fs } = project(); + const outside = mkdtempSync(join(tmpdir(), 'nf-outside-')); + roots.push(outside); + symlinkSync(join(outside, 'planted.txt'), join(root, 'dangling.txt')); + await fs.write('dangling.txt', 'x'); + expect(readdirSync(outside)).toEqual([]); + expect(lstatSync(join(root, 'dangling.txt')).isSymbolicLink()).toBe(false); + }); + it('jails paths, including through symlinks', async () => { const { root, fs } = project(); const outside = mkdtempSync(join(tmpdir(), 'nf-outside-')); From 45433cb47533507179e080d6303f653eaf006aca Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 02:06:14 +0100 Subject: [PATCH 06/39] fix(server-core): never root a gateway project in the clone's .git folder --- .../src/project/project-registry.ts | 16 +++++++-- .../test/project/project-registry.spec.ts | 36 +++++++++++++++++++ 2 files changed, 49 insertions(+), 3 deletions(-) create mode 100644 packages/server-core/test/project/project-registry.spec.ts diff --git a/packages/server-core/src/project/project-registry.ts b/packages/server-core/src/project/project-registry.ts index 5b95be79..b7cb6507 100644 --- a/packages/server-core/src/project/project-registry.ts +++ b/packages/server-core/src/project/project-registry.ts @@ -19,7 +19,7 @@ import type { ApiClient } from '../api/api-client'; import type { EditorEnv } from '../env/editor-env.type'; import { FileHashes } from '../fs/file-hashes'; import { MAX_READ_BYTES, NFIGNORE_FILE, ProjectFileSystem } from '../fs/fs-service'; -import { PathJail } from '../fs/path-jail'; +import { PathJail, gitReason } from '../fs/path-jail'; import { ProjectWatcher } from '../fs/watcher'; import type { GitService } from '../git/git-service'; import type { Session } from '../session/session-store'; @@ -33,6 +33,14 @@ const MAX_RECENT = 20; const GATEWAY_ID = /^[\w-]{1,60}$/; const CONFIG_CHANGE = /(^|\/)(nanoforge\.config\.[mc]?[jt]s|package\.json)$/; +/** + * Root of a gateway project: the `dir` its metadata names inside the clone (the clone itself + * without one). The metadata comes from the API, so it is jailed like any path, and never + * leads into `.git` (a project there could write the repository's config: code on the next pull). + */ +export const gatewayProjectRoot = (clone: string, dir: string | null | undefined) => + dir ? new PathJail(clone, gitReason).resolve(dir) : Promise.resolve(clone); + /** An opened project: its files, watcher and live model. */ export class OpenProject implements Disposable { readonly fs: ProjectFileSystem; @@ -273,8 +281,10 @@ export class ProjectRegistry implements Disposable { } else if (!this._projects.has(id)) { await this._git.pull(root, url, gateway.token); } - const subdir = gateway.gatewayProjectRegistryMetadata.dir; - const projectRoot = subdir ? await new PathJail(root).resolve(subdir) : root; + const projectRoot = await gatewayProjectRoot( + root, + gateway.gatewayProjectRegistryMetadata.dir, + ); return this._getOrCreate(id, projectRoot, { gatewayId }, gateway.name, false); }); } diff --git a/packages/server-core/test/project/project-registry.spec.ts b/packages/server-core/test/project/project-registry.spec.ts new file mode 100644 index 00000000..28daf85a --- /dev/null +++ b/packages/server-core/test/project/project-registry.spec.ts @@ -0,0 +1,36 @@ +import { mkdirSync, mkdtempSync, rmSync, symlinkSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, describe, expect, it } from 'vitest'; + +import { gatewayProjectRoot } from '../../src/project/project-registry'; + +const roots: string[] = []; +afterEach(() => { + for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); +}); + +const clone = () => { + const root = mkdtempSync(join(tmpdir(), 'nf-gateway-')); + roots.push(root); + mkdirSync(join(root, '.git/hooks'), { recursive: true }); + mkdirSync(join(root, 'game')); + symlinkSync('.git', join(root, 'sub')); + return root; +}; + +describe('gatewayProjectRoot', () => { + it('takes the clone, or the folder its dir names inside it', async () => { + const root = clone(); + expect(await gatewayProjectRoot(root, null)).toBe(root); + expect(await gatewayProjectRoot(root, 'game')).toBe(join(root, 'game')); + }); + + it('never roots a project in the clone .git folder, nor outside the clone', async () => { + const root = clone(); + for (const dir of ['.git', '.git/hooks', '.GIT', 'game/../.git', 'sub', '..', '/etc']) + await expect(gatewayProjectRoot(root, dir), dir).rejects.toMatchObject({ + code: 'FORBIDDEN', + }); + }); +}); From ab9c7dd63bbebca36fb0916bfa10ba79bae614c1 Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 02:07:55 +0100 Subject: [PATCH 07/39] fix(server-core): keep config paths in the project and serve runtime output of trusted projects only --- packages/server-core/src/project/discovery.ts | 103 +++++++++++------- .../implementation/runtime.implementation.ts | 2 +- .../src/server/create-editor-server.ts | 10 +- .../test/project/discovery.spec.ts | 31 ++++++ .../test/runtime/project-runtime.spec.ts | 54 ++++++++- 5 files changed, 158 insertions(+), 42 deletions(-) diff --git a/packages/server-core/src/project/discovery.ts b/packages/server-core/src/project/discovery.ts index 9750c142..74117f78 100644 --- a/packages/server-core/src/project/discovery.ts +++ b/packages/server-core/src/project/discovery.ts @@ -1,6 +1,6 @@ import { existsSync } from 'node:fs'; import { readFile, readdir } from 'node:fs/promises'; -import { basename, dirname, join, relative, resolve, sep } from 'node:path'; +import { basename, dirname, join, posix, relative, resolve, sep } from 'node:path'; import type { AppModel, ProjectModel } from '@nanoforge-dev/editor-protocol'; import { joinPath } from '@nanoforge-dev/editor-protocol'; @@ -202,17 +202,35 @@ export const resolveLibraries = ( return diagnostics; }; +/** + * A config path of the app at `root` as a normalized project path, or nothing when it leaves the + * project: an untrusted folder's config chooses it, and the build output is served (`/runtime/`). + */ +const inProject = (root: string, path: string): string | undefined => { + const slashed = path.replaceAll('\\', '/'); + if (slashed.startsWith('/') || /^[a-z]:/i.test(slashed)) return undefined; + const joined = posix.normalize(joinPath(root, slashed)); + if (joined === '..' || joined.startsWith('../')) return undefined; + return joined === '.' ? '' : joined; +}; + const toApp = async ( projectRoot: string, appRoot: string, config: ResolvedConfig, uses: Map, + diagnostics: Diagnostic[], ): Promise => { if (config.type === 'workspace') return undefined; const root = toPosix(relative(projectRoot, appRoot)); const pkg = await readJson(join(appRoot, 'package.json')); const name = pkg?.name ?? (basename(appRoot) || 'app'); - const at = (path: string) => joinPath(root, path); + const escaping: string[] = []; + const at = (path: string) => { + const inside = inProject(root, path); + if (inside === undefined) escaping.push(path); + return inside ?? ''; + }; const configFile = toPosix(relative(projectRoot, findConfigFile(appRoot) ?? appRoot)); uses.set(root, { configFile, @@ -225,41 +243,50 @@ const toApp = async ( }), }); - if (config.type === 'lib') { - return { - id: root, - name, - type: 'lib', - root, - language: 'ts', - dirs: { - assets: at(config.dir.assets), - components: at(config.dir.components), - systems: at(config.dir.systems), - scenes: at(config.dir.scenes), - }, - ...(await engineLibsOf(appRoot, projectRoot, pkg)), - libraries: [], - }; + const app: AppModel = + config.type === 'lib' + ? { + id: root, + name, + type: 'lib', + root, + language: 'ts', + dirs: { + assets: at(config.dir.assets), + components: at(config.dir.components), + systems: at(config.dir.systems), + scenes: at(config.dir.scenes), + }, + ...(await engineLibsOf(appRoot, projectRoot, pkg)), + libraries: [], + } + : { + id: root, + name, + type: config.type, + root, + language: config.language, + dirs: { + assets: at(config.dir.assets), + components: at(config.dir.components), + systems: at(config.dir.systems), + scenes: at(config.dir.scenes), + }, + entryFile: at(config.entryFile), + editorEntryFile: at(config.editor.entryFile), + outDir: at(config.out.dir), + ...(await engineLibsOf(appRoot, projectRoot, pkg)), + libraries: [], + }; + if (escaping.length) { + diagnostics.push({ + path: configFile, + message: `${escaping.join(', ')} leaves the project: config paths stay inside it`, + severity: 'error', + }); + return undefined; } - return { - id: root, - name, - type: config.type, - root, - language: config.language, - dirs: { - assets: at(config.dir.assets), - components: at(config.dir.components), - systems: at(config.dir.systems), - scenes: at(config.dir.scenes), - }, - entryFile: at(config.entryFile), - editorEntryFile: at(config.editor.entryFile), - outDir: at(config.out.dir), - ...(await engineLibsOf(appRoot, projectRoot, pkg)), - libraries: [], - }; + return app; }; /** @@ -308,7 +335,7 @@ export const discoverProject = async (input: DiscoveryInput): Promise - runtimeOf(projects.get(session, project)).manifest(app), + runnable(projects.get(session, project), 'Playing').manifest(app), env: ({ project, app, overrides }, { session }) => runtimeOf(projects.get(session, project)).env(app, overrides), startServer: async ({ project, app, overrides }, { session }) => { diff --git a/packages/server-core/src/server/create-editor-server.ts b/packages/server-core/src/server/create-editor-server.ts index feca4dad..94f0bccf 100644 --- a/packages/server-core/src/server/create-editor-server.ts +++ b/packages/server-core/src/server/create-editor-server.ts @@ -191,7 +191,8 @@ export const createEditorServer = (options: EditorServerOptions): EditorServer = /** * Build outputs of running games: `/runtime///`. Local editors only, like - * the runtime RPC: a hosted editor never builds nor runs a project's code. + * the runtime RPC: a hosted editor never builds nor runs a project's code. Trusted projects only, + * and only files inside the project. */ const handleRuntime = async (request: Request, url: URL): Promise => { const [projectId, appSegment, ...rest] = url.pathname.slice('/runtime/'.length).split('/'); @@ -201,9 +202,14 @@ export const createEditorServer = (options: EditorServerOptions): EditorServer = let file: string | undefined; let output: BuildOutput; try { - const projectRuntime = runtime.get(projects.get(session, projectId)); + const project = projects.get(session, projectId); + /** Only a game that may run is served: its output holds what the project's code wrote. */ + if (!project.trusted) throw new RpcError('FORBIDDEN', 'Not a trusted project'); + const projectRuntime = runtime.get(project); output = projectRuntime.builds.output(projectRuntime.app(decodeRuntimeApp(appSegment))); file = await new PathJail(output.dir).resolve(rest.map(decodeURIComponent).join('/')); + /** The output folder may itself be a link out of the project (`dist -> /`). */ + await project.fs.jail.resolve(project.fs.jail.relative(file)); } catch { return json(404, { error: 'Not found' }); } diff --git a/packages/server-core/test/project/discovery.spec.ts b/packages/server-core/test/project/discovery.spec.ts index 9915d231..e6f6bd33 100644 --- a/packages/server-core/test/project/discovery.spec.ts +++ b/packages/server-core/test/project/discovery.spec.ts @@ -167,6 +167,37 @@ describe('discoverProject diagnostics', () => { expect(model.apps).toMatchObject([{ type: 'server', language: 'ts' }]); }); + it('refuses config paths that leave the project, and keeps the ones inside it', async () => { + const root = mkdtempSync(join(tmpdir(), 'nf-escape-')); + temporary.push(root); + writeFileSync(join(root, 'package.json'), '{"name":"escape"}'); + const discover = (config: string) => { + writeFileSync(join(root, 'nanoforge.config.ts'), `export default ${config};`); + return discoverProject({ id: 'escape', root, location: root, loader: staticConfigLoader }); + }; + for (const config of [ + "{ type: 'client', out: { dir: '../../../../../../../../..' } }", + "{ type: 'client', out: { dir: 'dist/../..' } }", + "{ type: 'client', out: { dir: '/etc' } }", + "{ type: 'client', out: { dir: '..\\\\..' } }", + "{ type: 'client', dir: { assets: 'C:/Windows' } }", + "{ type: 'lib', dir: { components: '../other' } }", + ]) { + const model = await discover(config); + expect(model.apps, config).toEqual([]); + expect(model.diagnostics, config).toMatchObject([ + { + path: 'nanoforge.config.ts', + severity: 'error', + message: expect.stringContaining('leaves'), + }, + ]); + } + const model = await discover("{ type: 'client', out: { dir: './build/../out' } }"); + expect(model.diagnostics).toEqual([]); + expect(model.apps).toMatchObject([{ outDir: 'out' }]); + }); + it('supports single app projects', async () => { const root = mkdtempSync(join(tmpdir(), 'nf-single-')); temporary.push(root); diff --git a/packages/server-core/test/runtime/project-runtime.spec.ts b/packages/server-core/test/runtime/project-runtime.spec.ts index 2f8df0ca..2e35b08b 100644 --- a/packages/server-core/test/runtime/project-runtime.spec.ts +++ b/packages/server-core/test/runtime/project-runtime.spec.ts @@ -1,9 +1,19 @@ -import { chmodSync, cpSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { + chmodSync, + cpSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + symlinkSync, + writeFileSync, +} from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { + ProjectsContract, RuntimeContract, type RuntimeEvent, runtimeOutputPath, @@ -257,3 +267,45 @@ describe('runtime', () => { expect(events.at(-1)).toMatchObject({ type: 'server', state: 'exited' }); }); }); + +describe('runtime of a folder that is not trusted', () => { + /** A pong copy with a built client output, opened without trust. */ + const untrusted = async (name: string) => { + const root = join(workspace, name); + cpSync(join(import.meta.dirname, '../fixtures/pong-network'), root, { recursive: true }); + mkdirSync(join(root, 'apps/client/dist')); + writeFileSync(join(root, 'apps/client/dist/main.js'), 'export const main = async () => {};\n'); + const opened = await client.api(ProjectsContract).open({ path: name }); + expect(opened.trusted).toBe(false); + return opened.id; + }; + const get = async (path: string) => + (await editor.fetch(new Request(`${TEST_ORIGIN}${path}`)))!.status; + + it('serves no build output and gives no manifest', async () => { + const id = await untrusted('untrusted'); + expect(await get(`${runtimeOutputPath(id, 'apps/client')}main.js`)).toBe(404); + await expect( + client.api(RuntimeContract).manifest({ project: id, app: 'apps/client' }), + ).rejects.toMatchObject({ code: 'FORBIDDEN' }); + }); +}); + +describe('runtime output that leaves the project', () => { + it('serves nothing through an output folder linked outside of the project', async () => { + const outside = mkdtempSync(join(tmpdir(), 'nf-outside-')); + writeFileSync(join(outside, 'secret.txt'), 'secret'); + const root = join(workspace, 'linked'); + cpSync(join(import.meta.dirname, '../fixtures/pong-network'), root, { recursive: true }); + symlinkSync(outside, join(root, 'apps/client/dist')); + try { + const id = await openTrustedProject(client, 'linked'); + const response = (await editor.fetch( + new Request(`${TEST_ORIGIN}${runtimeOutputPath(id, 'apps/client')}secret.txt`), + ))!; + expect(response.status).toBe(404); + } finally { + rmSync(outside, { recursive: true, force: true }); + } + }); +}); From 757a196fd6c1e15b07c932985ff0901236689806 Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 02:09:19 +0100 Subject: [PATCH 08/39] fix(server-core): reveal a folder in finder without opening it --- packages/server-core/src/fs/reveal.ts | 21 ++++++++++++++------- packages/server-core/test/fs/reveal.spec.ts | 20 ++++++++++++++++++++ 2 files changed, 34 insertions(+), 7 deletions(-) create mode 100644 packages/server-core/test/fs/reveal.spec.ts diff --git a/packages/server-core/src/fs/reveal.ts b/packages/server-core/src/fs/reveal.ts index 1101a30b..ed0ac6e1 100644 --- a/packages/server-core/src/fs/reveal.ts +++ b/packages/server-core/src/fs/reveal.ts @@ -2,15 +2,22 @@ import { spawn } from 'node:child_process'; import { stat } from 'node:fs/promises'; import { dirname } from 'node:path'; +/** The command that shows an entry in the file manager of `platform`. */ +export const revealCommand = ( + absolute: string, + directory: boolean, + platform: NodeJS.Platform = process.platform, +): [string, string[]] => + platform === 'darwin' + ? /** Always `-R`: `open` on a folder named `x.app` launches the bundle in it. */ + ['open', ['-R', absolute]] + : platform === 'win32' + ? ['explorer', directory ? [absolute] : [`/select,${absolute}`]] + : ['xdg-open', [directory ? absolute : dirname(absolute)]]; + /** Opens the OS file manager on an entry (its folder for files; selected where supported). */ export const revealInFileManager = async (absolute: string): Promise => { - const directory = (await stat(absolute)).isDirectory(); - const [command, args] = - process.platform === 'darwin' - ? ['open', directory ? [absolute] : ['-R', absolute]] - : process.platform === 'win32' - ? ['explorer', directory ? [absolute] : [`/select,${absolute}`]] - : ['xdg-open', [directory ? absolute : dirname(absolute)]]; + const [command, args] = revealCommand(absolute, (await stat(absolute)).isDirectory()); await new Promise((resolve, reject) => { const child = spawn(command, args, { detached: true, stdio: 'ignore' }); child.once('error', reject); diff --git a/packages/server-core/test/fs/reveal.spec.ts b/packages/server-core/test/fs/reveal.spec.ts new file mode 100644 index 00000000..30816de3 --- /dev/null +++ b/packages/server-core/test/fs/reveal.spec.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from 'vitest'; + +import { revealCommand } from '../../src/fs/reveal'; + +describe('revealCommand', () => { + it('selects the entry in Finder, a folder too, so a .app bundle is never launched', () => { + expect(revealCommand('/p/x.app', true, 'darwin')).toEqual(['open', ['-R', '/p/x.app']]); + expect(revealCommand('/p/a.ts', false, 'darwin')).toEqual(['open', ['-R', '/p/a.ts']]); + }); + + it('opens Explorer on Windows and the folder elsewhere', () => { + expect(revealCommand('C:\\p\\a.ts', false, 'win32')).toEqual([ + 'explorer', + ['/select,C:\\p\\a.ts'], + ]); + expect(revealCommand('C:\\p', true, 'win32')).toEqual(['explorer', ['C:\\p']]); + expect(revealCommand('/p/a.ts', false, 'linux')).toEqual(['xdg-open', ['/p']]); + expect(revealCommand('/p/src', true, 'linux')).toEqual(['xdg-open', ['/p/src']]); + }); +}); From 6598720bf93d0ba64ad9e295b364569d65580bd0 Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 02:16:49 +0100 Subject: [PATCH 09/39] fix(server-core): never write the editor gitignore through a dangling link --- packages/server-core/src/fs/fs-service.ts | 10 ++++++++-- packages/server-core/test/fs/fs-service.spec.ts | 10 ++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/packages/server-core/src/fs/fs-service.ts b/packages/server-core/src/fs/fs-service.ts index 93ca2719..09ece21f 100644 --- a/packages/server-core/src/fs/fs-service.ts +++ b/packages/server-core/src/fs/fs-service.ts @@ -387,8 +387,14 @@ export class ProjectFileSystem { } private async _ensureEditorGitignore(): Promise { - const file = await this.jail.resolve(`${EDITOR_DIR}/.gitignore`, packagesReason); - if (!existsSync(file)) await writeFile(file, EDITOR_GITIGNORE); + const { real } = await this.jail.locate(`${EDITOR_DIR}/.gitignore`, packagesReason); + /** + * Created only where nothing is (`wx` never follows a link, even a dangling one, whose + * target the jail could not check): an existing file or link is left as it is. + */ + await writeFile(real, EDITOR_GITIGNORE, { flag: 'wx' }).catch((error: unknown) => { + if (errno(error) !== 'EEXIST') throw error; + }); } } diff --git a/packages/server-core/test/fs/fs-service.spec.ts b/packages/server-core/test/fs/fs-service.spec.ts index 6aa2b109..3475a19a 100644 --- a/packages/server-core/test/fs/fs-service.spec.ts +++ b/packages/server-core/test/fs/fs-service.spec.ts @@ -345,6 +345,16 @@ describe('ProjectFileSystem packages, ignore and trash', () => { expect(readdirSync(join(root, 'nf_modules'))).toEqual([]); }); + it('never writes the editor .gitignore through a dangling link', async () => { + const { root, fs } = project(); + const outside = mkdtempSync(join(tmpdir(), 'nf-outside-')); + roots.push(outside); + mkdirSync(join(root, '.nanoforge/editor'), { recursive: true }); + symlinkSync(join(outside, 'planted'), join(root, '.nanoforge/editor/.gitignore')); + await fs.delete('src/main.ts'); + expect(readdirSync(outside)).toEqual([]); + }); + it('restores deleted entries from the trash', async () => { const { root, fs } = project(); const { trashPath } = await fs.delete('src/main.ts'); From bd1364557751ffc60eff7e139334f6ceeb500730 Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 02:18:00 +0100 Subject: [PATCH 10/39] docs(server-core): document the path, link and runtime limits of the file API --- AGENTS.md | 4 +++- docs/adr/0002-editor-server.md | 3 ++- docs/adr/0005-package-installs.md | 2 +- docs/specs/file-manager.md | 6 ++++-- 4 files changed, 10 insertions(+), 5 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 48bc212f..ea9a0df8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -180,6 +180,8 @@ Everything in our registry has a `nanoforge.manifest.json` and a name `@scope/na - A local project's code runs only in a **trusted folder** (`TrustStore`, `DATA_DIR/trusted-folders.json`, by real path; seeded with the recent projects when first created). Trusted: `nanoforge.config.ts` is executed, project plugins load and their server entries run, builds, games, dependency installs, the project's Prettier and its git hooks run. - An untrusted folder opens in **restricted mode**: the config is read statically (as in a hosted editor), project plugins stay out, Play explains why, git runs with the hosted hardening, formatting uses the bundled Prettier. A sticky notification and `project.trust` offer **Trust this folder** (`projects.trust`, then the project reopens). - Server gates go through `ProjectRegistry.assertTrusted(project, what)`; `OpenProject.trusted` and `ClientProject.trusted` carry the state. A new code path that runs project code needs the gate. +- `/runtime//…` (the build output) is served to trusted projects only, and only files that really lie inside the project (the output folder may be a link out of it). +- A `nanoforge.config` path (`dir.*`, `entryFile`, `editor.entryFile`, `out.dir`) must stay inside the project: an absolute path or one that leaves it drops that app, with an error diagnostic (the config of an untrusted folder chooses these). - `plugins.list` never runs anything: the client calls `plugins.runProjectServers` with the project plugins that loaded. - The editor shell is served with `frame-ancestors 'self'` / `X-Frame-Options: SAMEORIGIN`, so another site cannot frame it and get a click on **Trust and open**. @@ -315,6 +317,6 @@ Everything in our registry has a `nanoforge.manifest.json` and a name `@scope/na 1. **Items (decided, ADR 0003).** See "Manifests: packages and plugins" above. Still open there: engine libs shipping items, inspector value hints, headless meta generation (imports, collisions, the packages list and sub-packages were settled by ADR 0004 and 0005). 2. **`nf_modules` / install (decided, ADR 0005).** The editor server installs packages read-only into `nf_modules/@scope/name`, side by side, one version each, from `nanoforge.packages.json` and its lock; plugins go to `~/.nanoforge/editor/plugins` or `/.nanoforge/plugins`. To change a package, the user copies it into their own components. - - The editor treats `nf_modules` as read-only (server, file manager, code editor): installing is the only way to change it. + - The editor treats `nf_modules` as read-only (server, file manager, code editor): installing is the only way to change it. The rule follows links: a link to `nf_modules` (or to `.git`) cannot be written, renamed or deleted through the file API either. - Discovery goes through a catalog with providers (project packages and apps, `nf_modules`), never folder scans. - Still open: the real registry (contract handed off in `docs/api/registry.md`; the editor runs on a folder with `REGISTRY_DIR`, and calls the API's only with `API_FEATURES=registry`), whether engine libs stay on npm. The registry package moved to the CLI repository (`libs/registry`): the editor, `nf install` and `nf publish` use the same one. diff --git a/docs/adr/0002-editor-server.md b/docs/adr/0002-editor-server.md index 62e6b6b7..ba75489e 100644 --- a/docs/adr/0002-editor-server.md +++ b/docs/adr/0002-editor-server.md @@ -34,7 +34,8 @@ The previous editor ran all server logic through SvelteKit form actions and hook - Every RPC call and WebSocket upgrade is checked against the `Origin` header, so a web page on another origin cannot drive a local editor. OFFLINE editors bind to `127.0.0.1` by default. - Project paths are jailed to `FS_ROOT`, and file paths to the project root, including through - symlinks. Deletes go to `.nanoforge/editor/trash`. + symlinks. Deletes go to `.nanoforge/editor/trash`. Config paths (`dir.*`, entry files, `out.dir`) must + stay inside the project, and `/runtime/` serves only trusted projects' files that lie inside it. - **Config loading**: - OFFLINE executes `nanoforge.config.*` with `unrun`, like the CLI does. Everything but Node built-ins is bundled (unrun imports from `/node_modules/.unrun`), and diff --git a/docs/adr/0005-package-installs.md b/docs/adr/0005-package-installs.md index 00c97c75..ebe0e4d7 100644 --- a/docs/adr/0005-package-installs.md +++ b/docs/adr/0005-package-installs.md @@ -5,7 +5,7 @@ Date: 2026-10-01. Status: accepted. It settles the install questions ADR 0003 le ## Decisions 1. **Who installs.** The editor server, with a package that has no editor dependency (`@nanoforge-dev/registry`). It is meant to move to the CLI repository, where `nf install` will use it too. Update 2026-11-08: done, it is `libs/registry` in the CLI repository, used by the editor, `nf install` and `nf publish`. -2. **The project's list.** `nanoforge.packages.json` holds the packages a project asks for, with version ranges. `nanoforge.packages.lock.json` holds what is installed: exact versions, archive hashes, and each package's own dependencies. `nf_modules` can be restored from the lock, so it may be left out of git. The editor does not edit the project's `.gitignore`: that choice is the project's. +2. **The project's list.** `nanoforge.packages.json` holds the packages a project asks for, with version ranges. `nanoforge.packages.lock.json` holds what is installed: exact versions, archive hashes, and each package's own dependencies. `nf_modules` can be restored from the lock, so it may be left out of git. The editor does not edit the project's `.gitignore`: that choice is the project's (it only writes its own `.nanoforge/editor/.gitignore`, and never through a link). 3. **Sub-packages.** Each package is published on its own and can be installed alone. A package that needs others lists them in `dependencies` (`{ "@scope/name": "^1.0.0" }`); they are installed side by side in `nf_modules/@scope/name`, one version each. `include` stays for folders inside one published package. 4. **Version conflicts.** One version of a package per project. When two ranges have no version in common, the install is refused and names both. 5. **Name collisions of items.** Plain names stay. The app's own item wins over a package's and the editor warns. Refusing installs on collisions between two packages is left for when the registry knows item names. diff --git a/docs/specs/file-manager.md b/docs/specs/file-manager.md index ce389244..3ec4611c 100644 --- a/docs/specs/file-manager.md +++ b/docs/specs/file-manager.md @@ -54,10 +54,12 @@ Browse and organize a game's files: a folder tree, plus a grid of the selected f ## Core and server additions - `fs.delete` returns the trash location, and `fs.restore` brings it back (undo). -- `fs.reveal` (local only) opens the OS file manager. +- `fs.reveal` (local only) opens the OS file manager (`open -R` on macOS, which selects the file). - `GET /files//` serves a project file (thumbnails, downloads); on a folder with `?download` it serves a `.zip`. - `.nfignore` is read by the server: listings and watch events skip it. -- `nf_modules/**` is read-only for every write. +- `nf_modules/**` is read-only for every write, and so is a link that leads there (the check uses where a path really leads; `.git` is refused the same way). +- A write through a link goes to the link's real target and keeps the file's mode. +- A subfolder the server cannot read (permission denied) is skipped in listings and does not stop the watcher; the rest of the project still shows. ## Done when From 7e3f29d04a7061be7581edde13aacbae118ac799 Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 02:24:40 +0100 Subject: [PATCH 11/39] fix(server-core): never copy through a link in the destination --- packages/server-core/src/fs/fs-service.ts | 24 ++++++++++++++++++- .../server-core/test/fs/fs-service.spec.ts | 22 +++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/packages/server-core/src/fs/fs-service.ts b/packages/server-core/src/fs/fs-service.ts index 09ece21f..dae3a908 100644 --- a/packages/server-core/src/fs/fs-service.ts +++ b/packages/server-core/src/fs/fs-service.ts @@ -1,7 +1,18 @@ import ignore, { type Ignore } from 'ignore'; import { randomBytes } from 'node:crypto'; import { existsSync } from 'node:fs'; -import { chmod, cp, mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises'; +import { + chmod, + cp, + lstat, + mkdir, + readFile, + readdir, + rename, + rm, + stat, + writeFile, +} from 'node:fs/promises'; import { basename, dirname, join } from 'node:path'; import type { @@ -305,6 +316,9 @@ export class ProjectFileSystem { const source = await this.jail.resolve(from); const target = await this.jail.resolve(to, packagesReason); if (!existsSync(source)) throw notFound(from); + /** Bun's `cp` writes through a link it meets in the destination (out of the project). */ + if (await holdsLink(target)) + throw new RpcError('FORBIDDEN', `${to} holds a link: copy somewhere else`); await cp(source, target, { recursive: true, force: overwrite, errorOnExist: !overwrite }).catch( (error: unknown) => mapError(error, from), ); @@ -401,6 +415,14 @@ export class ProjectFileSystem { /** Heavy folders a recursive listing does not descend into. */ const SKIPPED_IN_RECURSIVE_LIST = new Set(['node_modules']); +/** Whether `path` is a link or a folder with a link anywhere inside. */ +const holdsLink = async (path: string): Promise => { + const info = await lstat(path).catch(() => undefined); + if (!info?.isDirectory()) return info?.isSymbolicLink() ?? false; + for (const name of await readdir(path)) if (await holdsLink(join(path, name))) return true; + return false; +}; + const isUnder = (path: string, folder: string) => path === folder || path.startsWith(`${folder}/`); const inTrash = (path: string) => isUnder(path, TRASH_DIR); diff --git a/packages/server-core/test/fs/fs-service.spec.ts b/packages/server-core/test/fs/fs-service.spec.ts index 3475a19a..b51de5bc 100644 --- a/packages/server-core/test/fs/fs-service.spec.ts +++ b/packages/server-core/test/fs/fs-service.spec.ts @@ -355,6 +355,28 @@ describe('ProjectFileSystem packages, ignore and trash', () => { expect(readdirSync(outside)).toEqual([]); }); + it('never copies through a link in the destination, with or without overwrite', async () => { + const { root, fs } = project(); + const outside = mkdtempSync(join(tmpdir(), 'nf-outside-')); + roots.push(outside); + writeFileSync(join(outside, 'f'), 'OLD'); + mkdirSync(join(root, 'nf_modules/pkg'), { recursive: true }); + mkdirSync(join(root, 'from/sub'), { recursive: true }); + writeFileSync(join(root, 'from/f'), 'NEW'); + writeFileSync(join(root, 'from/sub/h'), 'NEW'); + mkdirSync(join(root, 'dst')); + symlinkSync(join(outside, 'f'), join(root, 'dst/f')); + symlinkSync('../nf_modules/pkg', join(root, 'dst/sub')); + for (const overwrite of [true, false]) + await expect(fs.copy('from', 'dst', overwrite), String(overwrite)).rejects.toMatchObject({ + code: 'FORBIDDEN', + }); + expect(readFileSync(join(outside, 'f'), 'utf8')).toBe('OLD'); + expect(readdirSync(join(root, 'nf_modules/pkg'))).toEqual([]); + await fs.copy('from', 'fresh'); + expect(readFileSync(join(root, 'fresh/sub/h'), 'utf8')).toBe('NEW'); + }); + it('restores deleted entries from the trash', async () => { const { root, fs } = project(); const { trashPath } = await fs.delete('src/main.ts'); From d3b0fb88867f0187b878e59f68fa218635655322 Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 02:25:06 +0100 Subject: [PATCH 12/39] fix(server-core): restore only plain trash entries and never out of nf_modules --- packages/server-core/src/fs/fs-service.ts | 10 +++++----- packages/server-core/test/fs/fs-service.spec.ts | 15 +++++++++++++++ 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/packages/server-core/src/fs/fs-service.ts b/packages/server-core/src/fs/fs-service.ts index dae3a908..dddbb5b5 100644 --- a/packages/server-core/src/fs/fs-service.ts +++ b/packages/server-core/src/fs/fs-service.ts @@ -366,14 +366,14 @@ export class ProjectFileSystem { /** Brings a deleted entry back from the trash (undo of `delete`). */ async restore(trashPath: string, to: string): Promise { - if ( - !trashPath.startsWith(`${TRASH_DIR}/`) || - trashPath.slice(TRASH_DIR.length + 1).includes('/') - ) { + /** One entry of the trash: a plain name, no separator of any platform, never `.` or `..`. */ + const name = trashPath.slice(TRASH_DIR.length + 1); + if (!trashPath.startsWith(`${TRASH_DIR}/`) || !name || /[\\/]|^\.\.?$/.test(name)) { throw new RpcError('BAD_REQUEST', `Not in the trash: ${trashPath}`); } assertWritable(to); - const source = await this.jail.resolve(trashPath); + /** The trash may be a link: what leaves it must not come out of nf_modules. */ + const source = await this.jail.resolve(trashPath, packagesReason); const target = await this.jail.resolve(to, packagesReason); if (!existsSync(source)) throw notFound(trashPath); if (existsSync(target)) throw new RpcError('CONFLICT', `Already exists: ${to}`); diff --git a/packages/server-core/test/fs/fs-service.spec.ts b/packages/server-core/test/fs/fs-service.spec.ts index b51de5bc..40a65dd9 100644 --- a/packages/server-core/test/fs/fs-service.spec.ts +++ b/packages/server-core/test/fs/fs-service.spec.ts @@ -377,6 +377,21 @@ describe('ProjectFileSystem packages, ignore and trash', () => { expect(readFileSync(join(root, 'fresh/sub/h'), 'utf8')).toBe('NEW'); }); + it('never restores out of nf_modules through a linked trash, nor a name that leaves it', async () => { + const { root, fs } = project(); + mkdirSync(join(root, 'nf_modules/pkg'), { recursive: true }); + mkdirSync(join(root, '.nanoforge/editor'), { recursive: true }); + symlinkSync('../../nf_modules', join(root, '.nanoforge/editor/trash')); + await expect(fs.restore('.nanoforge/editor/trash/pkg', 'moved')).rejects.toMatchObject({ + code: 'FORBIDDEN', + }); + expect(existsSync(join(root, 'nf_modules/pkg'))).toBe(true); + for (const name of ['..', '.', '', '..\\..\\src', 'a\\b']) + await expect(fs.restore(`.nanoforge/editor/trash/${name}`, 'x'), name).rejects.toMatchObject({ + code: 'BAD_REQUEST', + }); + }); + it('restores deleted entries from the trash', async () => { const { root, fs } = project(); const { trashPath } = await fs.delete('src/main.ts'); From e4f153b549ddb7a9e126c9e12b81d2819dcb787c Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 02:25:26 +0100 Subject: [PATCH 13/39] fix(server-core): never keep the setuid or setgid bit of a saved file --- packages/server-core/src/fs/fs-service.ts | 4 ++-- packages/server-core/test/fs/fs-service.spec.ts | 8 ++++++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/packages/server-core/src/fs/fs-service.ts b/packages/server-core/src/fs/fs-service.ts index dddbb5b5..a9b87a3c 100644 --- a/packages/server-core/src/fs/fs-service.ts +++ b/packages/server-core/src/fs/fs-service.ts @@ -274,11 +274,11 @@ export class ProjectFileSystem { dirname(target), `.${basename(target)}.nf-${randomBytes(4).toString('hex')}`, ); - /** The new file keeps the old one's mode (an executable script or hook stays one). */ + /** The new file keeps the old one's permissions (a script stays executable), never setuid. */ const mode = (await stat(target).catch(() => undefined))?.mode; try { await writeFile(temp, content); - if (mode !== undefined) await chmod(temp, mode & 0o7777); + if (mode !== undefined) await chmod(temp, mode & 0o777); await rename(temp, target); } catch (error) { await rm(temp, { force: true }); diff --git a/packages/server-core/test/fs/fs-service.spec.ts b/packages/server-core/test/fs/fs-service.spec.ts index 40a65dd9..3540ad82 100644 --- a/packages/server-core/test/fs/fs-service.spec.ts +++ b/packages/server-core/test/fs/fs-service.spec.ts @@ -240,6 +240,14 @@ describe('ProjectFileSystem', () => { expect(lstatSync(join(root, link)).isSymbolicLink()).toBe(true); }); + it('never gives a saved file the setuid or setgid bit', async () => { + const { root, fs } = project(); + writeFileSync(join(root, 'tool'), 'x'); + chmodSync(join(root, 'tool'), 0o6755); + await fs.write('tool', 'y'); + expect(statSync(join(root, 'tool')).mode & 0o7777).toBe(0o755); + }); + it('replaces a dangling link rather than writing outside the project', async () => { const { root, fs } = project(); const outside = mkdtempSync(join(tmpdir(), 'nf-outside-')); From 4e67158b255de03c56348c3cbebff1ae1ae0a195 Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 02:26:25 +0100 Subject: [PATCH 14/39] fix(server-core): log the subfolders a recursive listing skips --- packages/server-core/src/fs/fs-service.ts | 7 ++++++- packages/server-core/src/project/project-registry.ts | 4 +++- packages/server-core/test/fs/fs-service.spec.ts | 5 ++++- 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/packages/server-core/src/fs/fs-service.ts b/packages/server-core/src/fs/fs-service.ts index a9b87a3c..f6e27030 100644 --- a/packages/server-core/src/fs/fs-service.ts +++ b/packages/server-core/src/fs/fs-service.ts @@ -93,6 +93,8 @@ export class ProjectFileSystem { readonly root: string, /** Hashes shared by the server's projects (kept between runs); its own otherwise. */ hashes?: FileHashes, + /** Told of a subfolder a recursive listing skips because it can't be read. */ + private readonly _onSkip?: (path: string, error: unknown) => void, ) { this._hashes = hashes ?? new FileHashes({ maxBytes: MAX_READ_BYTES }); this.jail = new PathJail(root, gitReason); @@ -158,7 +160,10 @@ export class ProjectFileSystem { } catch (error) { /** One unreadable subfolder (a root-owned `pgdata/`) must not hide the whole project. */ const code = errno(error); - if (dir !== absolute && (code === 'EACCES' || code === 'EPERM')) return; + if (dir !== absolute && (code === 'EACCES' || code === 'EPERM')) { + this._onSkip?.(rel, error); + return; + } return mapError(error, rel); } for (const entry of names.sort((a, b) => a.name.localeCompare(b.name))) { diff --git a/packages/server-core/src/project/project-registry.ts b/packages/server-core/src/project/project-registry.ts index b7cb6507..d5e4207a 100644 --- a/packages/server-core/src/project/project-registry.ts +++ b/packages/server-core/src/project/project-registry.ts @@ -64,7 +64,9 @@ export class OpenProject implements Disposable { private readonly _logger: Logger, hashes?: FileHashes, ) { - this.fs = new ProjectFileSystem(root, hashes); + this.fs = new ProjectFileSystem(root, hashes, (path, error) => + this._logger.warn(`Skipped ${path}, which cannot be read, in ${location}`, error), + ); this._model = new ObservableValue(initial); this.watcher = new ProjectWatcher(this.fs.jail, { ignoredPaths: () => this._model.get().apps.flatMap((app) => (app.outDir ? [app.outDir] : [])), diff --git a/packages/server-core/test/fs/fs-service.spec.ts b/packages/server-core/test/fs/fs-service.spec.ts index 3540ad82..6f0f21c8 100644 --- a/packages/server-core/test/fs/fs-service.spec.ts +++ b/packages/server-core/test/fs/fs-service.spec.ts @@ -130,14 +130,17 @@ describe('ProjectFileSystem', () => { }); it.skipIf(asRoot)('lists past a subfolder it cannot read, not past the root', async () => { - const { root, fs } = project(); + const { root } = project(); lock(join(root, 'pgdata')); + const skipped: string[] = []; + const fs = new ProjectFileSystem(root, undefined, (path) => skipped.push(path)); expect((await fs.list('', true)).map((e) => [e.path, e.kind])).toEqual([ ['pgdata', 'directory'], ['src', 'directory'], ['src/main.ts', 'file'], ]); await expect(fs.list('pgdata', true)).rejects.toMatchObject({ code: 'FORBIDDEN' }); + expect(skipped).toEqual(['pgdata']); }); it('lists without hashes and without the folders left out, when asked', async () => { From 0a1616ed583911f3f6d0fbe87bba71cefcc9aaec Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 02:30:16 +0100 Subject: [PATCH 15/39] docs(server-core): date the adr notes on project path checks --- docs/adr/0002-editor-server.md | 2 +- docs/adr/0005-package-installs.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/adr/0002-editor-server.md b/docs/adr/0002-editor-server.md index ba75489e..357f998f 100644 --- a/docs/adr/0002-editor-server.md +++ b/docs/adr/0002-editor-server.md @@ -34,7 +34,7 @@ The previous editor ran all server logic through SvelteKit form actions and hook - Every RPC call and WebSocket upgrade is checked against the `Origin` header, so a web page on another origin cannot drive a local editor. OFFLINE editors bind to `127.0.0.1` by default. - Project paths are jailed to `FS_ROOT`, and file paths to the project root, including through - symlinks. Deletes go to `.nanoforge/editor/trash`. Config paths (`dir.*`, entry files, `out.dir`) must + symlinks. Deletes go to `.nanoforge/editor/trash`. Update 2026-11-23: config paths (`dir.*`, entry files, `out.dir`) must stay inside the project, and `/runtime/` serves only trusted projects' files that lie inside it. - **Config loading**: - OFFLINE executes `nanoforge.config.*` with `unrun`, like the CLI does. Everything but Node diff --git a/docs/adr/0005-package-installs.md b/docs/adr/0005-package-installs.md index ebe0e4d7..caaa8d84 100644 --- a/docs/adr/0005-package-installs.md +++ b/docs/adr/0005-package-installs.md @@ -5,7 +5,7 @@ Date: 2026-10-01. Status: accepted. It settles the install questions ADR 0003 le ## Decisions 1. **Who installs.** The editor server, with a package that has no editor dependency (`@nanoforge-dev/registry`). It is meant to move to the CLI repository, where `nf install` will use it too. Update 2026-11-08: done, it is `libs/registry` in the CLI repository, used by the editor, `nf install` and `nf publish`. -2. **The project's list.** `nanoforge.packages.json` holds the packages a project asks for, with version ranges. `nanoforge.packages.lock.json` holds what is installed: exact versions, archive hashes, and each package's own dependencies. `nf_modules` can be restored from the lock, so it may be left out of git. The editor does not edit the project's `.gitignore`: that choice is the project's (it only writes its own `.nanoforge/editor/.gitignore`, and never through a link). +2. **The project's list.** `nanoforge.packages.json` holds the packages a project asks for, with version ranges. `nanoforge.packages.lock.json` holds what is installed: exact versions, archive hashes, and each package's own dependencies. `nf_modules` can be restored from the lock, so it may be left out of git. The editor does not edit the project's `.gitignore`: that choice is the project's. Update 2026-11-23: it only writes its own `.nanoforge/editor/.gitignore`, and never through a link. 3. **Sub-packages.** Each package is published on its own and can be installed alone. A package that needs others lists them in `dependencies` (`{ "@scope/name": "^1.0.0" }`); they are installed side by side in `nf_modules/@scope/name`, one version each. `include` stays for folders inside one published package. 4. **Version conflicts.** One version of a package per project. When two ranges have no version in common, the install is refused and names both. 5. **Name collisions of items.** Plain names stay. The app's own item wins over a package's and the editor warns. Refusing installs on collisions between two packages is left for when the registry knows item names. From 0bede59f4f1fde918bc25d112e68557df718806d Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 09:03:46 +0100 Subject: [PATCH 16/39] fix(server-core): copy entry by entry without following links in the destination --- packages/server-core/src/fs/fs-service.ts | 67 ++++++++++++++----- .../server-core/test/fs/fs-service.spec.ts | 31 +++++++-- 2 files changed, 77 insertions(+), 21 deletions(-) diff --git a/packages/server-core/src/fs/fs-service.ts b/packages/server-core/src/fs/fs-service.ts index f6e27030..3b104af9 100644 --- a/packages/server-core/src/fs/fs-service.ts +++ b/packages/server-core/src/fs/fs-service.ts @@ -1,19 +1,21 @@ import ignore, { type Ignore } from 'ignore'; import { randomBytes } from 'node:crypto'; -import { existsSync } from 'node:fs'; +import { constants, existsSync } from 'node:fs'; import { chmod, - cp, + copyFile, lstat, mkdir, readFile, readdir, + readlink, rename, rm, stat, + symlink, writeFile, } from 'node:fs/promises'; -import { basename, dirname, join } from 'node:path'; +import { basename, dirname, join, sep } from 'node:path'; import type { FileContent, @@ -318,15 +320,13 @@ export class ProjectFileSystem { async copy(from: string, to: string, overwrite = false): Promise { assertAccessible(from); assertWritable(to); - const source = await this.jail.resolve(from); - const target = await this.jail.resolve(to, packagesReason); + const { real: source } = await this.jail.locate(from); + const { real: target } = await this.jail.locate(to, packagesReason); if (!existsSync(source)) throw notFound(from); - /** Bun's `cp` writes through a link it meets in the destination (out of the project). */ - if (await holdsLink(target)) - throw new RpcError('FORBIDDEN', `${to} holds a link: copy somewhere else`); - await cp(source, target, { recursive: true, force: overwrite, errorOnExist: !overwrite }).catch( - (error: unknown) => mapError(error, from), - ); + if (target === source || target.startsWith(`${source}${sep}`)) + throw new RpcError('BAD_REQUEST', `Cannot copy ${from} into itself`); + await mkdir(dirname(target), { recursive: true }); + await copyTree(source, target, to, overwrite).catch((error: unknown) => mapError(error, to)); return (await this.stat(to))!; } @@ -420,12 +420,45 @@ export class ProjectFileSystem { /** Heavy folders a recursive listing does not descend into. */ const SKIPPED_IN_RECURSIVE_LIST = new Set(['node_modules']); -/** Whether `path` is a link or a folder with a link anywhere inside. */ -const holdsLink = async (path: string): Promise => { - const info = await lstat(path).catch(() => undefined); - if (!info?.isDirectory()) return info?.isSymbolicLink() ?? false; - for (const name of await readdir(path)) if (await holdsLink(join(path, name))) return true; - return false; +const exists = (path: string) => Object.assign(new Error(path), { code: 'EEXIST' }); + +/** + * Copies `from` to `to` entry by entry, never through a link at the destination (Bun's `cp` + * writes through one, out of the project): a folder is made by a plain `mkdir` or must already + * be a real folder, a file or link goes to a temp name renamed over the old entry (a link there + * is replaced, not followed). Links of the source are copied as links; pipes, sockets and `.git` + * are left out. `path` (project-relative) names the destination in errors. + */ +const copyTree = async ( + from: string, + to: string, + path: string, + overwrite: boolean, +): Promise => { + const info = await lstat(from); + const existing = await lstat(to).catch(() => undefined); + if (info.isDirectory()) { + if (existing?.isSymbolicLink()) + throw new RpcError('FORBIDDEN', `${path} is a link: copy somewhere else`); + if (!existing) await mkdir(to); + else if (!existing.isDirectory()) throw exists(to); + for (const name of await readdir(from)) { + if (!isGitPath(name)) + await copyTree(join(from, name), join(to, name), `${path}/${name}`, overwrite); + } + return; + } + if (!info.isFile() && !info.isSymbolicLink()) return; + if (existing && (!overwrite || existing.isDirectory())) throw exists(to); + const temp = join(dirname(to), `.${basename(to)}.nf-${randomBytes(4).toString('hex')}`); + try { + if (info.isSymbolicLink()) await symlink(await readlink(from), temp); + else await copyFile(from, temp, constants.COPYFILE_EXCL); + await rename(temp, to); + } catch (error) { + await rm(temp, { force: true }); + throw error; + } }; const isUnder = (path: string, folder: string) => path === folder || path.startsWith(`${folder}/`); diff --git a/packages/server-core/test/fs/fs-service.spec.ts b/packages/server-core/test/fs/fs-service.spec.ts index 6f0f21c8..dac13dc0 100644 --- a/packages/server-core/test/fs/fs-service.spec.ts +++ b/packages/server-core/test/fs/fs-service.spec.ts @@ -378,12 +378,16 @@ describe('ProjectFileSystem packages, ignore and trash', () => { mkdirSync(join(root, 'dst')); symlinkSync(join(outside, 'f'), join(root, 'dst/f')); symlinkSync('../nf_modules/pkg', join(root, 'dst/sub')); - for (const overwrite of [true, false]) - await expect(fs.copy('from', 'dst', overwrite), String(overwrite)).rejects.toMatchObject({ - code: 'FORBIDDEN', - }); + await expect(fs.copy('from', 'dst', true)).rejects.toMatchObject({ code: 'FORBIDDEN' }); + await expect(fs.copy('from', 'dst')).rejects.toMatchObject({ code: 'CONFLICT' }); + /** Only new names: nothing in the way but the linked folder. */ + mkdirSync(join(root, 'dst2')); + symlinkSync('../nf_modules/pkg', join(root, 'dst2/sub')); + rmSync(join(root, 'from/f')); + await expect(fs.copy('from', 'dst2')).rejects.toMatchObject({ code: 'FORBIDDEN' }); expect(readFileSync(join(outside, 'f'), 'utf8')).toBe('OLD'); expect(readdirSync(join(root, 'nf_modules/pkg'))).toEqual([]); + writeFileSync(join(root, 'from/f'), 'NEW'); await fs.copy('from', 'fresh'); expect(readFileSync(join(root, 'fresh/sub/h'), 'utf8')).toBe('NEW'); }); @@ -403,6 +407,25 @@ describe('ProjectFileSystem packages, ignore and trash', () => { }); }); + it('never copies through a link moved into the destination while it copies', async () => { + const outside = mkdtempSync(join(tmpdir(), 'nf-outside-')); + roots.push(outside); + for (let run = 0; run < 60; run++) { + const { root, fs } = project(); + mkdirSync(join(root, 'from/t/sub'), { recursive: true }); + for (let i = 0; i < 20; i++) writeFileSync(join(root, `from/a${i}`), 'x'); + writeFileSync(join(root, 'from/t/sub/planted'), 'x'); + mkdirSync(join(root, 'dst')); + mkdirSync(join(root, 'evil')); + symlinkSync(outside, join(root, 'evil/sub')); + const copied = fs.copy('from', 'dst', true).catch(() => undefined); + for (let tick = 0; tick < (run % 5) + 1; tick++) await new Promise(setImmediate); + await fs.rename('evil', 'dst/t').catch(() => undefined); + await copied; + expect(readdirSync(outside), `run ${run}`).toEqual([]); + } + }); + it('restores deleted entries from the trash', async () => { const { root, fs } = project(); const { trashPath } = await fs.delete('src/main.ts'); From 591c8911f1e4a9fd9414b31e1c8d9534d2eac7b2 Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 09:04:31 +0100 Subject: [PATCH 17/39] fix(server-core): run the changes of a project one at a time --- packages/server-core/src/fs/fs-service.ts | 176 ++++++++++-------- .../server-core/test/fs/fs-service.spec.ts | 12 ++ 2 files changed, 110 insertions(+), 78 deletions(-) diff --git a/packages/server-core/src/fs/fs-service.ts b/packages/server-core/src/fs/fs-service.ts index 3b104af9..3cef2642 100644 --- a/packages/server-core/src/fs/fs-service.ts +++ b/packages/server-core/src/fs/fs-service.ts @@ -87,7 +87,11 @@ const assertWritable = (path: string) => { /** File operations of one project, jailed to its root. */ export class ProjectFileSystem { readonly jail: PathJail; - private readonly _writes = new KeyedMutex(); + /** + * Every change of the project runs alone, checks then act: another change can't move a link + * into a path between its check and its write. + */ + private readonly _changes = new KeyedMutex(); private readonly _hashes: FileHashes; private _ignore: { mtime: number; rules: Ignore } | undefined; @@ -254,19 +258,19 @@ export class ProjectFileSystem { * Atomic write (temp file + rename). With `expectedHash`, fails with CONFLICT when the file * changed since it was read (`null` means "must not exist"). */ - async write( + write( path: string, content: Uint8Array | string, options: { expectedHash?: string | null; createParents?: boolean } = {}, ): Promise { - if (path === '') throw new RpcError('BAD_REQUEST', 'Cannot write the project root'); - assertWritable(path); - /** - * A link is saved through to its target: the very path the jail checked, never looked up - * again (a dangling link is replaced, even if its target appears meanwhile). - */ - const { target: absolute, real: target } = await this.jail.locate(path, packagesReason); - return this._writes.run(target, async () => { + return this._serial(async () => { + if (path === '') throw new RpcError('BAD_REQUEST', 'Cannot write the project root'); + assertWritable(path); + /** + * A link is saved through to its target: the very path the jail checked, never looked up + * again (a dangling link is replaced, even if its target appears meanwhile). + */ + const { target: absolute, real: target } = await this.jail.locate(path, packagesReason); if (options.expectedHash !== undefined) { const current = await readFile(absolute).then( (buffer) => sha1(buffer), @@ -298,93 +302,109 @@ export class ProjectFileSystem { }); } - async mkdir(path: string): Promise { - assertWritable(path); - const absolute = await this.jail.resolve(path, packagesReason); - await mkdir(absolute, { recursive: true }).catch((error: unknown) => mapError(error, path)); - return (await this.stat(path))!; + mkdir(path: string): Promise { + return this._serial(async () => { + assertWritable(path); + const absolute = await this.jail.resolve(path, packagesReason); + await mkdir(absolute, { recursive: true }).catch((error: unknown) => mapError(error, path)); + return (await this.stat(path))!; + }); } - async rename(from: string, to: string, overwrite = false): Promise { - assertWritable(from); - assertWritable(to); - const source = await this.jail.resolve(from, packagesReason); - const target = await this.jail.resolve(to, packagesReason); - if (!existsSync(source)) throw notFound(from); - if (!overwrite && existsSync(target)) throw new RpcError('CONFLICT', `Already exists: ${to}`); - await mkdir(dirname(target), { recursive: true }); - await rename(source, target).catch((error: unknown) => mapError(error, from)); - return (await this.stat(to))!; + rename(from: string, to: string, overwrite = false): Promise { + return this._serial(async () => { + assertWritable(from); + assertWritable(to); + const source = await this.jail.resolve(from, packagesReason); + const target = await this.jail.resolve(to, packagesReason); + if (!existsSync(source)) throw notFound(from); + if (!overwrite && existsSync(target)) throw new RpcError('CONFLICT', `Already exists: ${to}`); + await mkdir(dirname(target), { recursive: true }); + await rename(source, target).catch((error: unknown) => mapError(error, from)); + return (await this.stat(to))!; + }); } - async copy(from: string, to: string, overwrite = false): Promise { - assertAccessible(from); - assertWritable(to); - const { real: source } = await this.jail.locate(from); - const { real: target } = await this.jail.locate(to, packagesReason); - if (!existsSync(source)) throw notFound(from); - if (target === source || target.startsWith(`${source}${sep}`)) - throw new RpcError('BAD_REQUEST', `Cannot copy ${from} into itself`); - await mkdir(dirname(target), { recursive: true }); - await copyTree(source, target, to, overwrite).catch((error: unknown) => mapError(error, to)); - return (await this.stat(to))!; + copy(from: string, to: string, overwrite = false): Promise { + return this._serial(async () => { + assertAccessible(from); + assertWritable(to); + const { real: source } = await this.jail.locate(from); + const { real: target } = await this.jail.locate(to, packagesReason); + if (!existsSync(source)) throw notFound(from); + if (target === source || target.startsWith(`${source}${sep}`)) + throw new RpcError('BAD_REQUEST', `Cannot copy ${from} into itself`); + await mkdir(dirname(target), { recursive: true }); + await copyTree(source, target, to, overwrite).catch((error: unknown) => mapError(error, to)); + return (await this.stat(to))!; + }); } /** * Moves the entry into the project trash (recoverable), never deletes directly. Returns its * place in the trash, for `restore`. */ - async delete(path: string): Promise<{ trashPath: string }> { - if (path === '' || inTrash(path)) { - throw new RpcError('BAD_REQUEST', `Cannot delete ${path || 'the project root'}`); - } - assertWritable(path); - const source = await this.jail.resolve(path, packagesReason); - if (!existsSync(source)) throw notFound(path); - const trash = await this.jail.resolve(TRASH_DIR, packagesReason); - await mkdir(trash, { recursive: true }); - await this._ensureEditorGitignore(); - const target = join( - trash, - `${Date.now()}-${randomBytes(3).toString('hex')}-${basename(source)}`, - ); - await rename(source, target).catch((error: unknown) => mapError(error, path)); - return { trashPath: `${TRASH_DIR}/${basename(target)}` }; + delete(path: string): Promise<{ trashPath: string }> { + return this._serial(async () => { + if (path === '' || inTrash(path)) { + throw new RpcError('BAD_REQUEST', `Cannot delete ${path || 'the project root'}`); + } + assertWritable(path); + const source = await this.jail.resolve(path, packagesReason); + if (!existsSync(source)) throw notFound(path); + const trash = await this.jail.resolve(TRASH_DIR, packagesReason); + await mkdir(trash, { recursive: true }); + await this._ensureEditorGitignore(); + const target = join( + trash, + `${Date.now()}-${randomBytes(3).toString('hex')}-${basename(source)}`, + ); + await rename(source, target).catch((error: unknown) => mapError(error, path)); + return { trashPath: `${TRASH_DIR}/${basename(target)}` }; + }); } /** * Empties the trash of entries deleted more than `TRASH_TTL_MS` ago (their undo can no longer * bring them back). Returns how many went. */ - async purgeTrash(now = Date.now()): Promise { - const trash = await this.jail.resolve(TRASH_DIR, packagesReason); - const names = await readdir(trash).catch(() => [] as string[]); - let purged = 0; - for (const name of names) { - const deletedAt = Number(/^(\d+)-/.exec(name)?.[1]); - if (!Number.isFinite(deletedAt) || now - deletedAt <= TRASH_TTL_MS) continue; - await rm(join(trash, name), { recursive: true, force: true }); - purged++; - } - return purged; + purgeTrash(now = Date.now()): Promise { + return this._serial(async () => { + const trash = await this.jail.resolve(TRASH_DIR, packagesReason); + const names = await readdir(trash).catch(() => [] as string[]); + let purged = 0; + for (const name of names) { + const deletedAt = Number(/^(\d+)-/.exec(name)?.[1]); + if (!Number.isFinite(deletedAt) || now - deletedAt <= TRASH_TTL_MS) continue; + await rm(join(trash, name), { recursive: true, force: true }); + purged++; + } + return purged; + }); } /** Brings a deleted entry back from the trash (undo of `delete`). */ - async restore(trashPath: string, to: string): Promise { - /** One entry of the trash: a plain name, no separator of any platform, never `.` or `..`. */ - const name = trashPath.slice(TRASH_DIR.length + 1); - if (!trashPath.startsWith(`${TRASH_DIR}/`) || !name || /[\\/]|^\.\.?$/.test(name)) { - throw new RpcError('BAD_REQUEST', `Not in the trash: ${trashPath}`); - } - assertWritable(to); - /** The trash may be a link: what leaves it must not come out of nf_modules. */ - const source = await this.jail.resolve(trashPath, packagesReason); - const target = await this.jail.resolve(to, packagesReason); - if (!existsSync(source)) throw notFound(trashPath); - if (existsSync(target)) throw new RpcError('CONFLICT', `Already exists: ${to}`); - await mkdir(dirname(target), { recursive: true }); - await rename(source, target).catch((error: unknown) => mapError(error, to)); - return (await this.stat(to))!; + restore(trashPath: string, to: string): Promise { + return this._serial(async () => { + /** One entry of the trash: a plain name, no separator of any platform, never `.` or `..`. */ + const name = trashPath.slice(TRASH_DIR.length + 1); + if (!trashPath.startsWith(`${TRASH_DIR}/`) || !name || /[\\/]|^\.\.?$/.test(name)) { + throw new RpcError('BAD_REQUEST', `Not in the trash: ${trashPath}`); + } + assertWritable(to); + /** The trash may be a link: what leaves it must not come out of nf_modules. */ + const source = await this.jail.resolve(trashPath, packagesReason); + const target = await this.jail.resolve(to, packagesReason); + if (!existsSync(source)) throw notFound(trashPath); + if (existsSync(target)) throw new RpcError('CONFLICT', `Already exists: ${to}`); + await mkdir(dirname(target), { recursive: true }); + await rename(source, target).catch((error: unknown) => mapError(error, to)); + return (await this.stat(to))!; + }); + } + + private _serial(task: () => Promise): Promise { + return this._changes.run(this.root, task); } private async _readOne(file: ReadRequest): Promise { diff --git a/packages/server-core/test/fs/fs-service.spec.ts b/packages/server-core/test/fs/fs-service.spec.ts index dac13dc0..18be5aed 100644 --- a/packages/server-core/test/fs/fs-service.spec.ts +++ b/packages/server-core/test/fs/fs-service.spec.ts @@ -426,6 +426,18 @@ describe('ProjectFileSystem packages, ignore and trash', () => { } }); + it('runs one change of the project at a time, in the order they came', async () => { + const { root, fs } = project(); + mkdirSync(join(root, 'from')); + for (let i = 0; i < 50; i++) writeFileSync(join(root, `from/a${i}`), 'x'); + const done: string[] = []; + const copy = fs.copy('from', 'dst').then(() => done.push('copy')); + const rename = fs.rename('src/main.ts', 'src/moved.ts').then(() => done.push('rename')); + const write = fs.write('src/new.ts', 'x').then(() => done.push('write')); + await Promise.all([copy, rename, write]); + expect(done).toEqual(['copy', 'rename', 'write']); + }); + it('restores deleted entries from the trash', async () => { const { root, fs } = project(); const { trashPath } = await fs.delete('src/main.ts'); From e595bb7feabbc514b8bf5a0e818be655fd8625a2 Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 09:05:14 +0100 Subject: [PATCH 18/39] fix(server-core): check out links as plain files in a hosted editor --- packages/server-core/src/git/git-service.ts | 11 ++++++++- .../server-core/test/git/git-service.spec.ts | 23 +++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/packages/server-core/src/git/git-service.ts b/packages/server-core/src/git/git-service.ts index cb912983..e195058b 100644 --- a/packages/server-core/src/git/git-service.ts +++ b/packages/server-core/src/git/git-service.ts @@ -30,6 +30,13 @@ const HOSTED_CONFIG = [ ['credential.helper', ''], ] as const; +/** + * A hosted editor's checkouts also hold no link: git writes a committed `link -> /` as a plain + * file, so no later file operation can be led out of the tenant's folder. An untrusted local + * folder keeps its links (the user's own checkout; the file API checks where they lead). + */ +const SERVER_CONFIG = [...HOSTED_CONFIG, ['core.symlinks', 'false']] as const; + /** Git CLI wrapper; operations on the same repository are serialized. */ export class GitService { private readonly _mutex = new KeyedMutex(); @@ -427,7 +434,9 @@ export class GitService { GIT_OPTIONAL_LOCKS: '0', LC_ALL: 'C', ...(batchSsh && { GIT_SSH_COMMAND: 'ssh -o BatchMode=yes' }), - ...(hosted ? withGitConfig(extraEnv, HOSTED_CONFIG) : extraEnv), + ...(hosted + ? withGitConfig(extraEnv, this._env.mode === 'ONLINE' ? SERVER_CONFIG : HOSTED_CONFIG) + : extraEnv), }, ...(network && { signal: AbortSignal.timeout(this._networkTimeoutMs) }), }).done; diff --git a/packages/server-core/test/git/git-service.spec.ts b/packages/server-core/test/git/git-service.spec.ts index 04d96a14..43007ba2 100644 --- a/packages/server-core/test/git/git-service.spec.ts +++ b/packages/server-core/test/git/git-service.spec.ts @@ -2,10 +2,12 @@ import { execFileSync } from 'node:child_process'; import { chmodSync, existsSync, + lstatSync, mkdirSync, mkdtempSync, readFileSync, rmSync, + symlinkSync, writeFileSync, } from 'node:fs'; import { tmpdir } from 'node:os'; @@ -123,6 +125,27 @@ describe('repository settings that run commands', () => { }); }); +describe('links in a repository', () => { + it('are checked out as plain files by a hosted editor, in a clone and a pull', async () => { + const hosted = new GitService( + loadEnv( + { NODE_ENV: 'test', PUBLIC_MODE: 'ONLINE', API_KEY: 'k', FS_ROOT: workspace }, + workspace, + ), + ); + const source = await repository('linked-source'); + symlinkSync('/etc', join(source, 'host')); + await git.commit(source, 'a link', { all: true }); + const target = join(workspace, 'linked-clone'); + await hosted.clone(source, target); + symlinkSync('/', join(source, 'root')); + await git.commit(source, 'another link', { all: true }); + await hosted.pull(target, source); + for (const name of ['host', 'root']) + expect(lstatSync(join(target, name)).isSymbolicLink(), name).toBe(false); + }); +}); + describe('parseStatus', () => { it('reads the branch, the upstream counts and every kind of entry', () => { const output = [ From ea23d2c2b9036fa0a20da70f52091be93f156a83 Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 09:07:49 +0100 Subject: [PATCH 19/39] fix(server-core): copy a link only when it still leads inside the project --- packages/server-core/src/fs/fs-service.ts | 24 +++++++++++++------ packages/server-core/src/fs/path-jail.ts | 14 ++++++++--- .../server-core/test/fs/fs-service.spec.ts | 18 ++++++++++++++ 3 files changed, 46 insertions(+), 10 deletions(-) diff --git a/packages/server-core/src/fs/fs-service.ts b/packages/server-core/src/fs/fs-service.ts index 3cef2642..c687fc62 100644 --- a/packages/server-core/src/fs/fs-service.ts +++ b/packages/server-core/src/fs/fs-service.ts @@ -15,7 +15,7 @@ import { symlink, writeFile, } from 'node:fs/promises'; -import { basename, dirname, join, sep } from 'node:path'; +import { basename, dirname, join, resolve, sep } from 'node:path'; import type { FileContent, @@ -335,7 +335,12 @@ export class ProjectFileSystem { if (target === source || target.startsWith(`${source}${sep}`)) throw new RpcError('BAD_REQUEST', `Cannot copy ${from} into itself`); await mkdir(dirname(target), { recursive: true }); - await copyTree(source, target, to, overwrite).catch((error: unknown) => mapError(error, to)); + /** A copied link is read from its new folder: it must still lead inside, never to nf_modules. */ + const checkLink = (link: string, path: string) => + this.jail.leadsInside(link, path, packagesReason); + await copyTree(source, target, to, overwrite, checkLink).catch((error: unknown) => + mapError(error, to), + ); return (await this.stat(to))!; }); } @@ -446,14 +451,16 @@ const exists = (path: string) => Object.assign(new Error(path), { code: 'EEXIST' * Copies `from` to `to` entry by entry, never through a link at the destination (Bun's `cp` * writes through one, out of the project): a folder is made by a plain `mkdir` or must already * be a real folder, a file or link goes to a temp name renamed over the old entry (a link there - * is replaced, not followed). Links of the source are copied as links; pipes, sockets and `.git` - * are left out. `path` (project-relative) names the destination in errors. + * is replaced, not followed). Links of the source are copied as links, once `checkLink` accepts + * where they lead from their new folder (a relative `../../x` may leave the project there); pipes, + * sockets and `.git` are left out. `path` (project-relative) names the destination in errors. */ const copyTree = async ( from: string, to: string, path: string, overwrite: boolean, + checkLink: (target: string, path: string) => Promise, ): Promise => { const info = await lstat(from); const existing = await lstat(to).catch(() => undefined); @@ -464,7 +471,7 @@ const copyTree = async ( else if (!existing.isDirectory()) throw exists(to); for (const name of await readdir(from)) { if (!isGitPath(name)) - await copyTree(join(from, name), join(to, name), `${path}/${name}`, overwrite); + await copyTree(join(from, name), join(to, name), `${path}/${name}`, overwrite, checkLink); } return; } @@ -472,8 +479,11 @@ const copyTree = async ( if (existing && (!overwrite || existing.isDirectory())) throw exists(to); const temp = join(dirname(to), `.${basename(to)}.nf-${randomBytes(4).toString('hex')}`); try { - if (info.isSymbolicLink()) await symlink(await readlink(from), temp); - else await copyFile(from, temp, constants.COPYFILE_EXCL); + if (info.isSymbolicLink()) { + const link = await readlink(from); + await checkLink(resolve(dirname(to), link), path); + await symlink(link, temp); + } else await copyFile(from, temp, constants.COPYFILE_EXCL); await rename(temp, to); } catch (error) { await rm(temp, { force: true }); diff --git a/packages/server-core/src/fs/path-jail.ts b/packages/server-core/src/fs/path-jail.ts index 9c91b115..e20c3549 100644 --- a/packages/server-core/src/fs/path-jail.ts +++ b/packages/server-core/src/fs/path-jail.ts @@ -68,13 +68,21 @@ export class PathJail { async locate(path: string, guard?: PathGuard): Promise<{ target: string; real: string }> { const target = resolve(this.root, path); if (!isInside(this.root, target)) throw this._escape(path); + return { target, real: await this.leadsInside(target, path, guard) }; + } + + /** + * Checks where an absolute path really leads (links followed): inside the root, and accepted + * by the guards. Returns that real path; `name` is the path shown in the error. + */ + async leadsInside(absolute: string, name: string, guard?: PathGuard): Promise { this._realRoot ??= await realpath(this.root); - const real = await realpathLenient(target); - if (!isInside(this._realRoot, real)) throw this._escape(path); + const real = await realpathLenient(absolute); + if (!isInside(this._realRoot, real)) throw this._escape(name); const rel = relative(this._realRoot, real).split(sep).join('/'); const refused = this._guard?.(rel) ?? guard?.(rel); if (refused) throw new RpcError('FORBIDDEN', refused); - return { target, real }; + return real; } /** Project-relative POSIX path of an absolute path inside the root. */ diff --git a/packages/server-core/test/fs/fs-service.spec.ts b/packages/server-core/test/fs/fs-service.spec.ts index 18be5aed..43c002d8 100644 --- a/packages/server-core/test/fs/fs-service.spec.ts +++ b/packages/server-core/test/fs/fs-service.spec.ts @@ -438,6 +438,24 @@ describe('ProjectFileSystem packages, ignore and trash', () => { expect(done).toEqual(['copy', 'rename', 'write']); }); + it('never copies a relative link that would leave the project, or reach nf_modules, from its new place', async () => { + const { root, fs } = project(); + mkdirSync(join(root, 'p/q/from/deep'), { recursive: true }); + symlinkSync('../../../../src/main.ts', join(root, 'p/q/from/deep/l')); + await expect(fs.copy('p/q/from', 'to')).rejects.toMatchObject({ code: 'FORBIDDEN' }); + expect(lstatSync(join(root, 'to/deep/l'), { throwIfNoEntry: false })).toBeUndefined(); + mkdirSync(join(root, 'nf_modules/pkg'), { recursive: true }); + mkdirSync(join(root, 'a/b/from'), { recursive: true }); + symlinkSync('../nf_modules/pkg', join(root, 'a/b/from/m')); + await expect(fs.copy('a/b/from', 'from')).rejects.toMatchObject({ code: 'FORBIDDEN' }); + expect(lstatSync(join(root, 'from/m'), { throwIfNoEntry: false })).toBeUndefined(); + /** A link that still leads inside from its new folder is copied as a link. */ + mkdirSync(join(root, 'src/links')); + symlinkSync('../main.ts', join(root, 'src/links/self')); + await fs.copy('src/links', 'src/copied'); + expect(lstatSync(join(root, 'src/copied/self')).isSymbolicLink()).toBe(true); + }); + it('restores deleted entries from the trash', async () => { const { root, fs } = project(); const { trashPath } = await fs.delete('src/main.ts'); From 507978bae1e91048162f10bf656bda9a137b37b3 Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 09:11:02 +0100 Subject: [PATCH 20/39] fix(server-core): check a copied link by the real path it leads to --- packages/server-core/src/fs/fs-service.ts | 23 ++++++++++++---- .../server-core/test/fs/fs-service.spec.ts | 26 ++++++++++++++++++- 2 files changed, 43 insertions(+), 6 deletions(-) diff --git a/packages/server-core/src/fs/fs-service.ts b/packages/server-core/src/fs/fs-service.ts index c687fc62..fcacfc0f 100644 --- a/packages/server-core/src/fs/fs-service.ts +++ b/packages/server-core/src/fs/fs-service.ts @@ -9,13 +9,14 @@ import { readFile, readdir, readlink, + realpath, rename, rm, stat, symlink, writeFile, } from 'node:fs/promises'; -import { basename, dirname, join, resolve, sep } from 'node:path'; +import { basename, dirname, isAbsolute, join, sep } from 'node:path'; import type { FileContent, @@ -452,8 +453,9 @@ const exists = (path: string) => Object.assign(new Error(path), { code: 'EEXIST' * writes through one, out of the project): a folder is made by a plain `mkdir` or must already * be a real folder, a file or link goes to a temp name renamed over the old entry (a link there * is replaced, not followed). Links of the source are copied as links, once `checkLink` accepts - * where they lead from their new folder (a relative `../../x` may leave the project there); pipes, - * sockets and `.git` are left out. `path` (project-relative) names the destination in errors. + * the real path they lead to from their new folder (a relative `../../x` may leave the project + * there; one that leads nowhere is refused); pipes, sockets and `.git` are left out. `path` + * (project-relative) names the destination in errors. */ const copyTree = async ( from: string, @@ -469,7 +471,13 @@ const copyTree = async ( throw new RpcError('FORBIDDEN', `${path} is a link: copy somewhere else`); if (!existing) await mkdir(to); else if (!existing.isDirectory()) throw exists(to); - for (const name of await readdir(from)) { + /** Links last: one may lead to an entry of the same folder, which must be there to check. */ + const entries = await readdir(from, { withFileTypes: true }); + const ordered = [ + ...entries.filter((entry) => !entry.isSymbolicLink()), + ...entries.filter((entry) => entry.isSymbolicLink()), + ]; + for (const { name } of ordered) { if (!isGitPath(name)) await copyTree(join(from, name), join(to, name), `${path}/${name}`, overwrite, checkLink); } @@ -481,7 +489,12 @@ const copyTree = async ( try { if (info.isSymbolicLink()) { const link = await readlink(from); - await checkLink(resolve(dirname(to), link), path); + /** Followed as the system does: `..` is never collapsed as text (`hop/..` is above `hop`). */ + const real = await realpath(isAbsolute(link) ? link : `${dirname(to)}${sep}${link}`).catch( + () => undefined, + ); + if (!real) throw new RpcError('FORBIDDEN', `${path} is a link that leads nowhere`); + await checkLink(real, path); await symlink(link, temp); } else await copyFile(from, temp, constants.COPYFILE_EXCL); await rename(temp, to); diff --git a/packages/server-core/test/fs/fs-service.spec.ts b/packages/server-core/test/fs/fs-service.spec.ts index 43c002d8..2b8a64d0 100644 --- a/packages/server-core/test/fs/fs-service.spec.ts +++ b/packages/server-core/test/fs/fs-service.spec.ts @@ -15,7 +15,7 @@ import { writeFileSync, } from 'node:fs'; import { tmpdir } from 'node:os'; -import { join } from 'node:path'; +import { basename, join } from 'node:path'; import { afterEach, describe, expect, it } from 'vitest'; import type { FileChange } from '@nanoforge-dev/editor-protocol'; @@ -452,8 +452,32 @@ describe('ProjectFileSystem packages, ignore and trash', () => { /** A link that still leads inside from its new folder is copied as a link. */ mkdirSync(join(root, 'src/links')); symlinkSync('../main.ts', join(root, 'src/links/self')); + /** And one to an entry of its own folder, whatever order the folder lists them in. */ + symlinkSync('z-target', join(root, 'src/links/a-link')); + writeFileSync(join(root, 'src/links/z-target'), 'x'); await fs.copy('src/links', 'src/copied'); expect(lstatSync(join(root, 'src/copied/self')).isSymbolicLink()).toBe(true); + expect(lstatSync(join(root, 'src/copied/a-link')).isSymbolicLink()).toBe(true); + }); + + it('checks a copied link the way the system follows it, not by collapsing .. as text', async () => { + const { root, fs } = project(); + const outside = mkdtempSync(join(tmpdir(), 'nf-outside-')); + roots.push(outside); + writeFileSync(join(outside, 'f'), 'secret'); + mkdirSync(join(root, 'from')); + /** Copied to p/q/r/to, `hop` leads to the project root, so `hop/..` is above it. */ + symlinkSync('../../../..', join(root, 'from/hop')); + symlinkSync(`hop/../${basename(outside)}/f`, join(root, 'from/l')); + await expect(fs.copy('from', 'p/q/r/to')).rejects.toMatchObject({ code: 'FORBIDDEN' }); + expect(lstatSync(join(root, 'p/q/r/to/l'), { throwIfNoEntry: false })).toBeUndefined(); + }); + + it('never copies a link that leads nowhere', async () => { + const { root, fs } = project(); + mkdirSync(join(root, 'from')); + symlinkSync('missing', join(root, 'from/l')); + await expect(fs.copy('from', 'to')).rejects.toMatchObject({ code: 'FORBIDDEN' }); }); it('restores deleted entries from the trash', async () => { From c77ea7c861f25b451c5a38738ad9d73e06d4f825 Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 09:41:27 +0100 Subject: [PATCH 21/39] fix(server-core): copy links once the tree is copied and undo a failed copy to a new place --- packages/server-core/src/fs/fs-service.ts | 113 ++++++++++++------ .../server-core/test/fs/fs-service.spec.ts | 42 +++++++ 2 files changed, 117 insertions(+), 38 deletions(-) diff --git a/packages/server-core/src/fs/fs-service.ts b/packages/server-core/src/fs/fs-service.ts index fcacfc0f..f00c7d97 100644 --- a/packages/server-core/src/fs/fs-service.ts +++ b/packages/server-core/src/fs/fs-service.ts @@ -336,12 +336,20 @@ export class ProjectFileSystem { if (target === source || target.startsWith(`${source}${sep}`)) throw new RpcError('BAD_REQUEST', `Cannot copy ${from} into itself`); await mkdir(dirname(target), { recursive: true }); - /** A copied link is read from its new folder: it must still lead inside, never to nf_modules. */ - const checkLink = (link: string, path: string) => - this.jail.leadsInside(link, path, packagesReason); - await copyTree(source, target, to, overwrite, checkLink).catch((error: unknown) => - mapError(error, to), - ); + const walk: CopyWalk = { + overwrite, + checkLink: (real, path) => this.jail.leadsInside(real, path, packagesReason), + links: [], + }; + const created = !(await lstat(target).catch(() => undefined)); + try { + await copyTree(source, target, to, walk); + await copyLinks(walk); + } catch (error) { + /** A copy to a new place is all or nothing. */ + if (created) await rm(target, { recursive: true, force: true }); + return mapError(error, to); + } return (await this.stat(to))!; }); } @@ -448,55 +456,84 @@ const SKIPPED_IN_RECURSIVE_LIST = new Set(['node_modules']); const exists = (path: string) => Object.assign(new Error(path), { code: 'EEXIST' }); +interface CopyWalk { + readonly overwrite: boolean; + /** Where a copied link really leads must still be inside the project (and not nf_modules). */ + readonly checkLink: (real: string, path: string) => Promise; + /** Links met by the walk: made once the whole tree is there, so any target they have exists. */ + readonly links: { from: string; to: string; path: string }[]; +} + /** * Copies `from` to `to` entry by entry, never through a link at the destination (Bun's `cp` * writes through one, out of the project): a folder is made by a plain `mkdir` or must already - * be a real folder, a file or link goes to a temp name renamed over the old entry (a link there - * is replaced, not followed). Links of the source are copied as links, once `checkLink` accepts - * the real path they lead to from their new folder (a relative `../../x` may leave the project - * there; one that leads nowhere is refused); pipes, sockets and `.git` are left out. `path` - * (project-relative) names the destination in errors. + * be a real folder, a file goes to a temp name renamed over the old entry (a link there is + * replaced, not followed). Links are only collected (see {@link copyLink}); pipes, sockets and + * `.git` are left out. `path` (project-relative) names the destination in errors. */ -const copyTree = async ( - from: string, - to: string, - path: string, - overwrite: boolean, - checkLink: (target: string, path: string) => Promise, -): Promise => { +const copyTree = async (from: string, to: string, path: string, walk: CopyWalk): Promise => { const info = await lstat(from); + if (info.isSymbolicLink()) { + walk.links.push({ from, to, path }); + return; + } const existing = await lstat(to).catch(() => undefined); if (info.isDirectory()) { if (existing?.isSymbolicLink()) throw new RpcError('FORBIDDEN', `${path} is a link: copy somewhere else`); if (!existing) await mkdir(to); else if (!existing.isDirectory()) throw exists(to); - /** Links last: one may lead to an entry of the same folder, which must be there to check. */ - const entries = await readdir(from, { withFileTypes: true }); - const ordered = [ - ...entries.filter((entry) => !entry.isSymbolicLink()), - ...entries.filter((entry) => entry.isSymbolicLink()), - ]; - for (const { name } of ordered) { + for (const name of await readdir(from)) { if (!isGitPath(name)) - await copyTree(join(from, name), join(to, name), `${path}/${name}`, overwrite, checkLink); + await copyTree(join(from, name), join(to, name), `${path}/${name}`, walk); } return; } - if (!info.isFile() && !info.isSymbolicLink()) return; - if (existing && (!overwrite || existing.isDirectory())) throw exists(to); + if (!info.isFile()) return; + if (existing && (!walk.overwrite || existing.isDirectory())) throw exists(to); + await replaceWith(to, (temp) => copyFile(from, temp, constants.COPYFILE_EXCL)); +}; + +/** + * Copies the links a walk met, as links, once the real path each leads to from its new folder + * passes `checkLink`: followed as the system does (`..` is never collapsed as text, `hop/..` is + * above where `hop` leads), so a relative `../../x` that leaves the project there is refused. A + * link may lead through another one (`.bin/x -> ../x/bin`, `x` a link): those that lead nowhere + * yet wait for the others, and are refused once a round makes none. + */ +const copyLinks = async (walk: CopyWalk): Promise => { + let pending = walk.links; + while (pending.length) { + const waiting: CopyWalk['links'] = []; + for (const link of pending) if (!(await copyLink(link, walk))) waiting.push(link); + if (waiting.length === pending.length) + throw new RpcError('FORBIDDEN', `${waiting[0]!.path} is a link that leads nowhere`); + pending = waiting; + } +}; + +/** One link of {@link copyLinks}: false when it leads nowhere (yet). */ +const copyLink = async ( + { from, to, path }: CopyWalk['links'][number], + walk: CopyWalk, +): Promise => { + const existing = await lstat(to).catch(() => undefined); + if (existing && (!walk.overwrite || existing.isDirectory())) throw exists(to); + const link = await readlink(from); + const real = await realpath(isAbsolute(link) ? link : `${dirname(to)}${sep}${link}`).catch( + () => undefined, + ); + if (!real) return false; + await walk.checkLink(real, path); + await replaceWith(to, (temp) => symlink(link, temp)); + return true; +}; + +/** Makes `to` through a temp name next to it, renamed over what was there (never followed). */ +const replaceWith = async (to: string, make: (temp: string) => Promise): Promise => { const temp = join(dirname(to), `.${basename(to)}.nf-${randomBytes(4).toString('hex')}`); try { - if (info.isSymbolicLink()) { - const link = await readlink(from); - /** Followed as the system does: `..` is never collapsed as text (`hop/..` is above `hop`). */ - const real = await realpath(isAbsolute(link) ? link : `${dirname(to)}${sep}${link}`).catch( - () => undefined, - ); - if (!real) throw new RpcError('FORBIDDEN', `${path} is a link that leads nowhere`); - await checkLink(real, path); - await symlink(link, temp); - } else await copyFile(from, temp, constants.COPYFILE_EXCL); + await make(temp); await rename(temp, to); } catch (error) { await rm(temp, { force: true }); diff --git a/packages/server-core/test/fs/fs-service.spec.ts b/packages/server-core/test/fs/fs-service.spec.ts index 2b8a64d0..9b7f4ecb 100644 --- a/packages/server-core/test/fs/fs-service.spec.ts +++ b/packages/server-core/test/fs/fs-service.spec.ts @@ -480,6 +480,48 @@ describe('ProjectFileSystem packages, ignore and trash', () => { await expect(fs.copy('from', 'to')).rejects.toMatchObject({ code: 'FORBIDDEN' }); }); + it('copies links into a sibling folder, whatever order the folders are listed in', async () => { + const { root, fs } = project(); + /** Each way round, so one of them lists the link's folder first. */ + for (const [linked, target] of [ + ['A', 'B'], + ['B', 'A'], + ] as const) { + mkdirSync(join(root, `x${linked}/${linked}`), { recursive: true }); + mkdirSync(join(root, `x${linked}/${target}`), { recursive: true }); + writeFileSync(join(root, `x${linked}/${target}/f`), 'x'); + symlinkSync(`../${target}/f`, join(root, `x${linked}/${linked}/l`)); + await fs.copy(`x${linked}`, `y${linked}`); + expect(lstatSync(join(root, `y${linked}/${linked}/l`)).isSymbolicLink()).toBe(true); + } + }); + + it('copies an npm-style node_modules, its .bin and .pnpm links included', async () => { + const { root, fs } = project(); + const nm = join(root, 'app/node_modules'); + mkdirSync(join(nm, '.bin'), { recursive: true }); + mkdirSync(join(nm, '.pnpm/x@1.0.0/node_modules/x/bin'), { recursive: true }); + mkdirSync(join(nm, '.pnpm/node_modules'), { recursive: true }); + writeFileSync(join(nm, '.pnpm/x@1.0.0/node_modules/x/bin/x.js'), 'x'); + symlinkSync('../x@1.0.0/node_modules/x', join(nm, '.pnpm/node_modules/x')); + symlinkSync('.pnpm/x@1.0.0/node_modules/x', join(nm, 'x')); + symlinkSync('../x/bin/x.js', join(nm, '.bin/x')); + await fs.copy('app', 'copy'); + expect(readFileSync(join(root, 'copy/node_modules/.bin/x'), 'utf8')).toBe('x'); + expect( + readFileSync(join(root, 'copy/node_modules/.pnpm/node_modules/x/bin/x.js'), 'utf8'), + ).toBe('x'); + }); + + it('leaves nothing behind when a copy to a new place fails', async () => { + const { root, fs } = project(); + mkdirSync(join(root, 'from/sub'), { recursive: true }); + writeFileSync(join(root, 'from/sub/f'), 'x'); + symlinkSync('missing', join(root, 'from/l')); + await expect(fs.copy('from', 'to')).rejects.toMatchObject({ code: 'FORBIDDEN' }); + expect(existsSync(join(root, 'to'))).toBe(false); + }); + it('restores deleted entries from the trash', async () => { const { root, fs } = project(); const { trashPath } = await fs.delete('src/main.ts'); From c59626dd9cc562a49823d474f29d3303cffa66e8 Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 09:42:12 +0100 Subject: [PATCH 22/39] fix(server-core): copy a named link as a link and never copy into a link --- packages/server-core/src/fs/fs-service.ts | 13 +++++++++---- packages/server-core/test/fs/fs-service.spec.ts | 12 ++++++++++++ 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/packages/server-core/src/fs/fs-service.ts b/packages/server-core/src/fs/fs-service.ts index f00c7d97..79b77855 100644 --- a/packages/server-core/src/fs/fs-service.ts +++ b/packages/server-core/src/fs/fs-service.ts @@ -330,10 +330,15 @@ export class ProjectFileSystem { return this._serial(async () => { assertAccessible(from); assertWritable(to); - const { real: source } = await this.jail.locate(from); - const { real: target } = await this.jail.locate(to, packagesReason); - if (!existsSync(source)) throw notFound(from); - if (target === source || target.startsWith(`${source}${sep}`)) + const named = await this.jail.locate(from); + const { target: destination, real: target } = await this.jail.locate(to, packagesReason); + if (!existsSync(named.real)) throw notFound(from); + if ((await lstat(destination).catch(() => undefined))?.isSymbolicLink()) + throw new RpcError('FORBIDDEN', `${to} is a link: copy somewhere else`); + /** A link the copy names is copied as a link (see `copyLink`), not what it leads to. */ + const isLink = (await lstat(named.target)).isSymbolicLink(); + const source = isLink ? named.target : named.real; + if (!isLink && (target === source || target.startsWith(`${source}${sep}`))) throw new RpcError('BAD_REQUEST', `Cannot copy ${from} into itself`); await mkdir(dirname(target), { recursive: true }); const walk: CopyWalk = { diff --git a/packages/server-core/test/fs/fs-service.spec.ts b/packages/server-core/test/fs/fs-service.spec.ts index 9b7f4ecb..81e7d884 100644 --- a/packages/server-core/test/fs/fs-service.spec.ts +++ b/packages/server-core/test/fs/fs-service.spec.ts @@ -522,6 +522,18 @@ describe('ProjectFileSystem packages, ignore and trash', () => { expect(existsSync(join(root, 'to'))).toBe(false); }); + it('copies a link named by the copy as a link, and never copies into a link', async () => { + const { root, fs } = project(); + symlinkSync('main.ts', join(root, 'src/alias.ts')); + await fs.copy('src/alias.ts', 'src/alias-copy.ts'); + expect(lstatSync(join(root, 'src/alias-copy.ts')).isSymbolicLink()).toBe(true); + mkdirSync(join(root, 'from')); + writeFileSync(join(root, 'from/new.ts'), 'x'); + symlinkSync('src', join(root, 'linked')); + await expect(fs.copy('from', 'linked', true)).rejects.toMatchObject({ code: 'FORBIDDEN' }); + expect(existsSync(join(root, 'src/new.ts'))).toBe(false); + }); + it('restores deleted entries from the trash', async () => { const { root, fs } = project(); const { trashPath } = await fs.delete('src/main.ts'); From 274d97730627005c0f4073d0b6d1235db5bc5140 Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 09:42:42 +0100 Subject: [PATCH 23/39] fix(server-core): name the entry in the way when a copy meets one --- packages/server-core/src/fs/fs-service.ts | 13 ++++++++----- packages/server-core/test/fs/fs-service.spec.ts | 12 ++++++++++++ 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/packages/server-core/src/fs/fs-service.ts b/packages/server-core/src/fs/fs-service.ts index 79b77855..ab08b232 100644 --- a/packages/server-core/src/fs/fs-service.ts +++ b/packages/server-core/src/fs/fs-service.ts @@ -459,7 +459,10 @@ export class ProjectFileSystem { /** Heavy folders a recursive listing does not descend into. */ const SKIPPED_IN_RECURSIVE_LIST = new Set(['node_modules']); -const exists = (path: string) => Object.assign(new Error(path), { code: 'EEXIST' }); +const inTheWay = (path: string) => new RpcError('CONFLICT', `Already exists: ${path}`); + +/** Project-relative path of `name` in the folder `path` (`''` is the project root). */ +const childPath = (path: string, name: string) => (path ? `${path}/${name}` : name); interface CopyWalk { readonly overwrite: boolean; @@ -487,15 +490,15 @@ const copyTree = async (from: string, to: string, path: string, walk: CopyWalk): if (existing?.isSymbolicLink()) throw new RpcError('FORBIDDEN', `${path} is a link: copy somewhere else`); if (!existing) await mkdir(to); - else if (!existing.isDirectory()) throw exists(to); + else if (!existing.isDirectory()) throw inTheWay(path); for (const name of await readdir(from)) { if (!isGitPath(name)) - await copyTree(join(from, name), join(to, name), `${path}/${name}`, walk); + await copyTree(join(from, name), join(to, name), childPath(path, name), walk); } return; } if (!info.isFile()) return; - if (existing && (!walk.overwrite || existing.isDirectory())) throw exists(to); + if (existing && (!walk.overwrite || existing.isDirectory())) throw inTheWay(path); await replaceWith(to, (temp) => copyFile(from, temp, constants.COPYFILE_EXCL)); }; @@ -523,7 +526,7 @@ const copyLink = async ( walk: CopyWalk, ): Promise => { const existing = await lstat(to).catch(() => undefined); - if (existing && (!walk.overwrite || existing.isDirectory())) throw exists(to); + if (existing && (!walk.overwrite || existing.isDirectory())) throw inTheWay(path); const link = await readlink(from); const real = await realpath(isAbsolute(link) ? link : `${dirname(to)}${sep}${link}`).catch( () => undefined, diff --git a/packages/server-core/test/fs/fs-service.spec.ts b/packages/server-core/test/fs/fs-service.spec.ts index 81e7d884..4b25e048 100644 --- a/packages/server-core/test/fs/fs-service.spec.ts +++ b/packages/server-core/test/fs/fs-service.spec.ts @@ -534,6 +534,18 @@ describe('ProjectFileSystem packages, ignore and trash', () => { expect(existsSync(join(root, 'src/new.ts'))).toBe(false); }); + it('names the entry in the way when a copy meets one', async () => { + const { root, fs } = project(); + mkdirSync(join(root, 'from/sub'), { recursive: true }); + writeFileSync(join(root, 'from/sub/f'), 'x'); + mkdirSync(join(root, 'dst/sub'), { recursive: true }); + writeFileSync(join(root, 'dst/sub/f'), 'old'); + await expect(fs.copy('from', 'dst')).rejects.toMatchObject({ + code: 'CONFLICT', + message: 'Already exists: dst/sub/f', + }); + }); + it('restores deleted entries from the trash', async () => { const { root, fs } = project(); const { trashPath } = await fs.delete('src/main.ts'); From 6120dcc9217cb7aa133f641a0acf6376fc75084d Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 09:43:28 +0100 Subject: [PATCH 24/39] fix(server-core): check every entry a copy makes against nf_modules and .git --- packages/server-core/src/fs/fs-service.ts | 14 ++++++++++++-- packages/server-core/test/fs/fs-service.spec.ts | 10 ++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/packages/server-core/src/fs/fs-service.ts b/packages/server-core/src/fs/fs-service.ts index ab08b232..6a402f2e 100644 --- a/packages/server-core/src/fs/fs-service.ts +++ b/packages/server-core/src/fs/fs-service.ts @@ -16,7 +16,7 @@ import { symlink, writeFile, } from 'node:fs/promises'; -import { basename, dirname, isAbsolute, join, sep } from 'node:path'; +import { basename, dirname, isAbsolute, join, relative, sep } from 'node:path'; import type { FileContent, @@ -348,7 +348,9 @@ export class ProjectFileSystem { }; const created = !(await lstat(target).catch(() => undefined)); try { - await copyTree(source, target, to, walk); + /** Paths of the walk are where the entries really go (`target`), as the guards read them. */ + const realRoot = await realpath(this.root); + await copyTree(source, target, relative(realRoot, target).split(sep).join('/'), walk); await copyLinks(walk); } catch (error) { /** A copy to a new place is all or nothing. */ @@ -459,6 +461,12 @@ export class ProjectFileSystem { /** Heavy folders a recursive listing does not descend into. */ const SKIPPED_IN_RECURSIVE_LIST = new Set(['node_modules']); +/** Each entry a copy makes, by its real project path: a copy into the root holds `nf_modules`. */ +const assertCopyTarget = (path: string) => { + const refused = path ? (gitReason(path) ?? packagesReason(path)) : undefined; + if (refused) throw new RpcError('FORBIDDEN', refused); +}; + const inTheWay = (path: string) => new RpcError('CONFLICT', `Already exists: ${path}`); /** Project-relative path of `name` in the folder `path` (`''` is the project root). */ @@ -480,6 +488,7 @@ interface CopyWalk { * `.git` are left out. `path` (project-relative) names the destination in errors. */ const copyTree = async (from: string, to: string, path: string, walk: CopyWalk): Promise => { + assertCopyTarget(path); const info = await lstat(from); if (info.isSymbolicLink()) { walk.links.push({ from, to, path }); @@ -525,6 +534,7 @@ const copyLink = async ( { from, to, path }: CopyWalk['links'][number], walk: CopyWalk, ): Promise => { + assertCopyTarget(path); const existing = await lstat(to).catch(() => undefined); if (existing && (!walk.overwrite || existing.isDirectory())) throw inTheWay(path); const link = await readlink(from); diff --git a/packages/server-core/test/fs/fs-service.spec.ts b/packages/server-core/test/fs/fs-service.spec.ts index 4b25e048..c335338f 100644 --- a/packages/server-core/test/fs/fs-service.spec.ts +++ b/packages/server-core/test/fs/fs-service.spec.ts @@ -546,6 +546,16 @@ describe('ProjectFileSystem packages, ignore and trash', () => { }); }); + it('never copies into nf_modules or .git, even from a copy into the project root', async () => { + const { root, fs } = project(); + mkdirSync(join(root, 'nf_modules/pkg'), { recursive: true }); + writeFileSync(join(root, 'nf_modules/pkg/index.js'), 'original'); + mkdirSync(join(root, 'a/nf_modules/pkg'), { recursive: true }); + writeFileSync(join(root, 'a/nf_modules/pkg/index.js'), 'tampered'); + await expect(fs.copy('a', '', true)).rejects.toMatchObject({ code: 'FORBIDDEN' }); + expect(readFileSync(join(root, 'nf_modules/pkg/index.js'), 'utf8')).toBe('original'); + }); + it('restores deleted entries from the trash', async () => { const { root, fs } = project(); const { trashPath } = await fs.delete('src/main.ts'); From 58505e163668092b937ab38491863b727b4c9f3c Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 09:44:04 +0100 Subject: [PATCH 25/39] fix(server-core): share the change lock of a folder between its instances --- packages/server-core/src/fs/fs-service.ts | 28 +++++++++++++------ .../server-core/test/fs/fs-service.spec.ts | 12 ++++++++ 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/packages/server-core/src/fs/fs-service.ts b/packages/server-core/src/fs/fs-service.ts index 6a402f2e..b553a19e 100644 --- a/packages/server-core/src/fs/fs-service.ts +++ b/packages/server-core/src/fs/fs-service.ts @@ -1,6 +1,6 @@ import ignore, { type Ignore } from 'ignore'; import { randomBytes } from 'node:crypto'; -import { constants, existsSync } from 'node:fs'; +import { constants, existsSync, realpathSync } from 'node:fs'; import { chmod, copyFile, @@ -16,7 +16,7 @@ import { symlink, writeFile, } from 'node:fs/promises'; -import { basename, dirname, isAbsolute, join, relative, sep } from 'node:path'; +import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'; import type { FileContent, @@ -85,14 +85,19 @@ const assertWritable = (path: string) => { if (refused) throw new RpcError('FORBIDDEN', refused); }; +/** + * Every change of a project through the file API runs alone, checks then act, so another change + * can't move a link into a path between its check and its write. One lock per real root, shared by + * every instance on it (a project closed and opened again during a long copy gets a new one). It + * does not cover anything outside the file API (a game, git, the user's tools): see `copyTree`. + */ +const CHANGES = new KeyedMutex(); + /** File operations of one project, jailed to its root. */ export class ProjectFileSystem { readonly jail: PathJail; - /** - * Every change of the project runs alone, checks then act: another change can't move a link - * into a path between its check and its write. - */ - private readonly _changes = new KeyedMutex(); + /** Key of the project in {@link CHANGES}: its real root, the same for every instance on it. */ + private readonly _changesKey: string; private readonly _hashes: FileHashes; private _ignore: { mtime: number; rules: Ignore } | undefined; @@ -105,6 +110,13 @@ export class ProjectFileSystem { ) { this._hashes = hashes ?? new FileHashes({ maxBytes: MAX_READ_BYTES }); this.jail = new PathJail(root, gitReason); + this._changesKey = (() => { + try { + return realpathSync(root); + } catch { + return resolve(root); + } + })(); } /** Whether `.nfignore` hides a path (directories are tested with and without a trailing /). */ @@ -425,7 +437,7 @@ export class ProjectFileSystem { } private _serial(task: () => Promise): Promise { - return this._changes.run(this.root, task); + return CHANGES.run(this._changesKey, task); } private async _readOne(file: ReadRequest): Promise { diff --git a/packages/server-core/test/fs/fs-service.spec.ts b/packages/server-core/test/fs/fs-service.spec.ts index c335338f..00d5ecfb 100644 --- a/packages/server-core/test/fs/fs-service.spec.ts +++ b/packages/server-core/test/fs/fs-service.spec.ts @@ -556,6 +556,18 @@ describe('ProjectFileSystem packages, ignore and trash', () => { expect(readFileSync(join(root, 'nf_modules/pkg/index.js'), 'utf8')).toBe('original'); }); + it('runs the changes of two instances on one folder one at a time', async () => { + const { root, fs } = project(); + const other = new ProjectFileSystem(root); + mkdirSync(join(root, 'from')); + for (let i = 0; i < 50; i++) writeFileSync(join(root, `from/a${i}`), 'x'); + const done: string[] = []; + const copy = fs.copy('from', 'dst').then(() => done.push('copy')); + const write = other.write('src/new.ts', 'x').then(() => done.push('write')); + await Promise.all([copy, write]); + expect(done).toEqual(['copy', 'write']); + }); + it('restores deleted entries from the trash', async () => { const { root, fs } = project(); const { trashPath } = await fs.delete('src/main.ts'); From c0e381833de5aeb59cdfed3159acf34700e5ae00 Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 09:45:19 +0100 Subject: [PATCH 26/39] fix(server-core): stop a copy when a folder it writes into is swapped for a link --- packages/server-core/src/fs/fs-service.ts | 28 ++++++++-- .../server-core/test/fs/copy-moved.spec.ts | 56 +++++++++++++++++++ 2 files changed, 79 insertions(+), 5 deletions(-) create mode 100644 packages/server-core/test/fs/copy-moved.spec.ts diff --git a/packages/server-core/src/fs/fs-service.ts b/packages/server-core/src/fs/fs-service.ts index b553a19e..663c56f3 100644 --- a/packages/server-core/src/fs/fs-service.ts +++ b/packages/server-core/src/fs/fs-service.ts @@ -510,8 +510,10 @@ const copyTree = async (from: string, to: string, path: string, walk: CopyWalk): if (info.isDirectory()) { if (existing?.isSymbolicLink()) throw new RpcError('FORBIDDEN', `${path} is a link: copy somewhere else`); - if (!existing) await mkdir(to); - else if (!existing.isDirectory()) throw inTheWay(path); + if (!existing) { + await assertSameFolder(dirname(to), path); + await mkdir(to); + } else if (!existing.isDirectory()) throw inTheWay(path); for (const name of await readdir(from)) { if (!isGitPath(name)) await copyTree(join(from, name), join(to, name), childPath(path, name), walk); @@ -520,7 +522,7 @@ const copyTree = async (from: string, to: string, path: string, walk: CopyWalk): } if (!info.isFile()) return; if (existing && (!walk.overwrite || existing.isDirectory())) throw inTheWay(path); - await replaceWith(to, (temp) => copyFile(from, temp, constants.COPYFILE_EXCL)); + await replaceWith(to, path, (temp) => copyFile(from, temp, constants.COPYFILE_EXCL)); }; /** @@ -555,12 +557,28 @@ const copyLink = async ( ); if (!real) return false; await walk.checkLink(real, path); - await replaceWith(to, (temp) => symlink(link, temp)); + await replaceWith(to, path, (temp) => symlink(link, temp)); return true; }; +/** + * Refuses to write into `folder` unless it still really is that path. The walk only makes real + * folders, but something outside the file API (a game, git, the user's tools) can swap one for a + * link while it copies; the file API's lock can't stop that. shortcut: this narrows the window to + * the time between this check and the write, Node has no `openat` to close it. + */ +const assertSameFolder = async (folder: string, path: string): Promise => { + if ((await realpath(folder).catch(() => undefined)) !== folder) + throw new RpcError('FORBIDDEN', `${path} was moved while it was copied`); +}; + /** Makes `to` through a temp name next to it, renamed over what was there (never followed). */ -const replaceWith = async (to: string, make: (temp: string) => Promise): Promise => { +const replaceWith = async ( + to: string, + path: string, + make: (temp: string) => Promise, +): Promise => { + await assertSameFolder(dirname(to), path); const temp = join(dirname(to), `.${basename(to)}.nf-${randomBytes(4).toString('hex')}`); try { await make(temp); diff --git a/packages/server-core/test/fs/copy-moved.spec.ts b/packages/server-core/test/fs/copy-moved.spec.ts new file mode 100644 index 00000000..69e06f46 --- /dev/null +++ b/packages/server-core/test/fs/copy-moved.spec.ts @@ -0,0 +1,56 @@ +import { + mkdirSync, + mkdtempSync, + readdirSync, + renameSync, + rmSync, + symlinkSync, + writeFileSync, +} from 'node:fs'; +import type * as FsPromises from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { ProjectFileSystem } from '../../src/fs/fs-service'; + +/** Runs before the walk reads a source folder: where a test moves things outside the file API. */ +let beforeRead: ((path: string) => void) | undefined; +vi.mock('node:fs/promises', async (original) => { + const real = await original(); + return { + ...real, + readdir: ((path: string, ...rest: unknown[]) => { + beforeRead?.(String(path)); + return (real.readdir as (...args: unknown[]) => unknown)(path, ...rest); + }) as typeof real.readdir, + }; +}); + +const roots: string[] = []; +afterEach(() => { + beforeRead = undefined; + for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); +}); + +describe('copy and changes outside the file API', () => { + it('stops when a folder it copies into is swapped for a link during the copy', async () => { + const root = mkdtempSync(join(tmpdir(), 'nf-moved-')); + const outside = mkdtempSync(join(tmpdir(), 'nf-outside-')); + roots.push(root, outside); + mkdirSync(join(root, 'from/t/sub'), { recursive: true }); + writeFileSync(join(root, 'from/t/sub/f'), 'x'); + mkdirSync(join(root, 'evil')); + symlinkSync(outside, join(root, 'evil/sub')); + beforeRead = (path) => { + if (!path.endsWith(join('from', 't', 'sub'))) return; + beforeRead = undefined; + renameSync(join(root, 'dst/t'), join(root, 'moved')); + renameSync(join(root, 'evil'), join(root, 'dst/t')); + }; + await expect(new ProjectFileSystem(root).copy('from', 'dst')).rejects.toMatchObject({ + code: 'FORBIDDEN', + }); + expect(readdirSync(outside)).toEqual([]); + }); +}); From 01b3694be6fa73cb7a319c01ec8c1b943207ca1e Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 09:46:49 +0100 Subject: [PATCH 27/39] perf(server-core): copy sixteen entries at a time --- packages/server-core/src/fs/fs-service.ts | 54 ++++++++++++++++++++--- 1 file changed, 47 insertions(+), 7 deletions(-) diff --git a/packages/server-core/src/fs/fs-service.ts b/packages/server-core/src/fs/fs-service.ts index 663c56f3..74e28555 100644 --- a/packages/server-core/src/fs/fs-service.ts +++ b/packages/server-core/src/fs/fs-service.ts @@ -357,6 +357,7 @@ export class ProjectFileSystem { overwrite, checkLink: (real, path) => this.jail.leadsInside(real, path, packagesReason), links: [], + limit: limiter(COPY_CONCURRENCY), }; const created = !(await lstat(target).catch(() => undefined)); try { @@ -490,8 +491,37 @@ interface CopyWalk { readonly checkLink: (real: string, path: string) => Promise; /** Links met by the walk: made once the whole tree is there, so any target they have exists. */ readonly links: { from: string; to: string; path: string }[]; + /** Runs one entry's file operations, {@link COPY_CONCURRENCY} at a time over the whole walk. */ + readonly limit: (task: () => Promise) => Promise; } +/** Entries a copy works on at once (one at a time made a 10k-file copy take about a second). */ +const COPY_CONCURRENCY = 16; + +/** Runs tasks at most `max` at a time. */ +const limiter = (max: number): CopyWalk['limit'] => { + let active = 0; + const waiting: (() => void)[] = []; + return async (task) => { + if (active >= max) await new Promise((resolve) => waiting.push(resolve)); + active++; + try { + return await task(); + } finally { + active--; + waiting.shift()?.(); + } + }; +}; + +/** Waits for every task, then throws the first failure (none still runs once it throws). */ +const settleAll = async (tasks: Promise[]): Promise => { + const failed = (await Promise.allSettled(tasks)).find( + (result): result is PromiseRejectedResult => result.status === 'rejected', + ); + if (failed) throw failed.reason; +}; + /** * Copies `from` to `to` entry by entry, never through a link at the destination (Bun's `cp` * writes through one, out of the project): a folder is made by a plain `mkdir` or must already @@ -500,11 +530,24 @@ interface CopyWalk { * `.git` are left out. `path` (project-relative) names the destination in errors. */ const copyTree = async (from: string, to: string, path: string, walk: CopyWalk): Promise => { + const children = await walk.limit(() => copyEntry(from, to, path, walk)); + await settleAll( + children.map((name) => copyTree(join(from, name), join(to, name), childPath(path, name), walk)), + ); +}; + +/** One entry of {@link copyTree}: returns the names to copy inside it (a folder's). */ +const copyEntry = async ( + from: string, + to: string, + path: string, + walk: CopyWalk, +): Promise => { assertCopyTarget(path); const info = await lstat(from); if (info.isSymbolicLink()) { walk.links.push({ from, to, path }); - return; + return []; } const existing = await lstat(to).catch(() => undefined); if (info.isDirectory()) { @@ -514,15 +557,12 @@ const copyTree = async (from: string, to: string, path: string, walk: CopyWalk): await assertSameFolder(dirname(to), path); await mkdir(to); } else if (!existing.isDirectory()) throw inTheWay(path); - for (const name of await readdir(from)) { - if (!isGitPath(name)) - await copyTree(join(from, name), join(to, name), childPath(path, name), walk); - } - return; + return (await readdir(from)).filter((name) => !isGitPath(name)); } - if (!info.isFile()) return; + if (!info.isFile()) return []; if (existing && (!walk.overwrite || existing.isDirectory())) throw inTheWay(path); await replaceWith(to, path, (temp) => copyFile(from, temp, constants.COPYFILE_EXCL)); + return []; }; /** From 2705d735b569f8c7a8b5e7781fff1403a574af81 Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 09:47:20 +0100 Subject: [PATCH 28/39] docs(server-core): describe how a copy treats links and how hosted git checks them out --- AGENTS.md | 4 ++-- docs/specs/file-manager.md | 8 ++++++++ packages/server-core/src/git/git-service.ts | 7 ++++--- 3 files changed, 14 insertions(+), 5 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index ea9a0df8..e008ed88 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -84,7 +84,7 @@ pnpm e2e:last-failure # error-context.md of the last failed test, its last fra - The editor server answers only to loopback host names and `ALLOWED_HOSTS` (DNS rebinding guard): a dev server reached by another name needs it. - `EDITOR_TOKEN` (off by default; `random` makes one per start): a local editor then answers only to a browser that opened the link it prints (`?token=`, which sets an HttpOnly cookie). Dev server and e2e run without it. - The editor's page has a Content Security Policy (`packages/server-core/src/http/shell-csp.ts`; inline scripts by hash, read from `index.html`). A local editor allows `'unsafe-eval'` (the engine's ECS is Emscripten WebAssembly, whose bindings compile strings); a hosted one does not. The e2e fixture fails a test on any CSP violation: a new kind of resource (another origin, a worker type) needs the policy changed with it. -- Hosted sessions: project grants belong to the user who opened the project (a new user or a sign-out drops them); refused tokens are not re-checked for a minute; API calls time out after 15 s; over the session cap, anonymous sessions go first. `/rpc` bodies are capped at 100 MiB, folder zips are streamed (no trash, no `nf_modules`, 1 GiB at most), and trash entries older than 30 days go when a project opens. +- Hosted sessions: project grants belong to the user who opened the project (a new user or a sign-out drops them); refused tokens are not re-checked for a minute; API calls time out after 15 s; over the session cap, anonymous sessions go first. `/rpc` bodies are capped at 100 MiB, folder zips are streamed (no trash, no `nf_modules`, 1 GiB at most), and trash entries older than 30 days go when a project opens. A hosted editor's git runs with `core.symlinks=false`: what it clones or pulls holds no link (a committed link becomes a plain file; a clone made before keeps its links). - To debug a failed e2e test, `pnpm e2e:last-failure` (or read `test-results//error-context.md`, and the last frame of `trace.zip`). A minified Monaco stack: rebuild code-editor with `npx vite build --sourcemap --outDir ` (same file hashes) and map the frames with `@jridgewell/trace-mapping`. - The CLI repo needs `pnpm --filter @nanoforge-dev/config build` before `pnpm build`, and `pnpm --filter @nanoforge-dev/schematics build` for `nf new` (its root build leaves the schematics out). @@ -178,7 +178,7 @@ Everything in our registry has a `nanoforge.manifest.json` and a name `@scope/na ### Folder trust (local editors) - A local project's code runs only in a **trusted folder** (`TrustStore`, `DATA_DIR/trusted-folders.json`, by real path; seeded with the recent projects when first created). Trusted: `nanoforge.config.ts` is executed, project plugins load and their server entries run, builds, games, dependency installs, the project's Prettier and its git hooks run. -- An untrusted folder opens in **restricted mode**: the config is read statically (as in a hosted editor), project plugins stay out, Play explains why, git runs with the hosted hardening, formatting uses the bundled Prettier. A sticky notification and `project.trust` offer **Trust this folder** (`projects.trust`, then the project reopens). +- An untrusted folder opens in **restricted mode**: the config is read statically (as in a hosted editor), project plugins stay out, Play explains why, git runs with the hosted hardening (without `core.symlinks=false`: the user's own checkout keeps its links), formatting uses the bundled Prettier. A sticky notification and `project.trust` offer **Trust this folder** (`projects.trust`, then the project reopens). - Server gates go through `ProjectRegistry.assertTrusted(project, what)`; `OpenProject.trusted` and `ClientProject.trusted` carry the state. A new code path that runs project code needs the gate. - `/runtime//…` (the build output) is served to trusted projects only, and only files that really lie inside the project (the output folder may be a link out of it). - A `nanoforge.config` path (`dir.*`, `entryFile`, `editor.entryFile`, `out.dir`) must stay inside the project: an absolute path or one that leaves it drops that app, with an error diagnostic (the config of an untrusted folder chooses these). diff --git a/docs/specs/file-manager.md b/docs/specs/file-manager.md index 3ec4611c..ef51d510 100644 --- a/docs/specs/file-manager.md +++ b/docs/specs/file-manager.md @@ -60,6 +60,14 @@ Browse and organize a game's files: a folder tree, plus a grid of the selected f - `nf_modules/**` is read-only for every write, and so is a link that leads there (the check uses where a path really leads; `.git` is refused the same way). - A write through a link goes to the link's real target and keeps the file's mode. - A subfolder the server cannot read (permission denied) is skipped in listings and does not stop the watcher; the rest of the project still shows. +- Changes through the file API (write, create a folder, rename, copy, delete, restore, empty the trash) run one at a time per project folder. +- `fs.copy` never writes through a link: + - a link in the destination where a folder goes is refused, and a destination that is a link is refused; + - a file or link already there is replaced (with `overwrite`) or is a conflict that names that entry; + - no entry goes into `nf_modules` or `.git`, even from a copy into the project root, and `.git` folders of the source are left out; + - links are copied as links, after the rest of the tree, and only when they still lead inside the project from their new place (a link that leads nowhere is refused); a copied link named by the copy stays a link; + - a copy to a new place that fails leaves nothing behind; one into an existing folder keeps what it had copied; + - a folder swapped for a link by another program during the copy stops it. ## Done when diff --git a/packages/server-core/src/git/git-service.ts b/packages/server-core/src/git/git-service.ts index e195058b..cb978c3e 100644 --- a/packages/server-core/src/git/git-service.ts +++ b/packages/server-core/src/git/git-service.ts @@ -31,9 +31,10 @@ const HOSTED_CONFIG = [ ] as const; /** - * A hosted editor's checkouts also hold no link: git writes a committed `link -> /` as a plain - * file, so no later file operation can be led out of the tenant's folder. An untrusted local - * folder keeps its links (the user's own checkout; the file API checks where they lead). + * A hosted editor's git also writes a committed link (`link -> /`) as a plain file, in what it + * clones, pulls or checks out from now on. A clone made before keeps the links it has: the file + * API still checks where every path leads. An untrusted local folder keeps its links (the user's + * own checkout). */ const SERVER_CONFIG = [...HOSTED_CONFIG, ['core.symlinks', 'false']] as const; From 5099de03ccbbe6bb4ecf88b628a3558b65a37a0b Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 10:16:20 +0100 Subject: [PATCH 29/39] fix(server-core): never clean up a failed copy through a folder swapped for a link --- packages/server-core/src/fs/fs-service.ts | 20 ++++++++++++++++- .../server-core/test/fs/copy-moved.spec.ts | 22 +++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/packages/server-core/src/fs/fs-service.ts b/packages/server-core/src/fs/fs-service.ts index 74e28555..ec0aaa0e 100644 --- a/packages/server-core/src/fs/fs-service.ts +++ b/packages/server-core/src/fs/fs-service.ts @@ -367,7 +367,7 @@ export class ProjectFileSystem { await copyLinks(walk); } catch (error) { /** A copy to a new place is all or nothing. */ - if (created) await rm(target, { recursive: true, force: true }); + if (created) await removeMade(target); return mapError(error, to); } return (await this.stat(to))!; @@ -612,6 +612,24 @@ const assertSameFolder = async (folder: string, path: string): Promise => throw new RpcError('FORBIDDEN', `${path} was moved while it was copied`); }; +/** + * Removes what a failed copy made, only while its folder still really is that path (swapped for a + * link, the removal would reach outside). It is moved to a temp name in that folder first, so + * what is removed is what was checked; a link moved in is removed, never followed. + */ +const removeMade = async (made: string): Promise => { + const folder = dirname(made); + if ((await realpath(folder).catch(() => undefined)) !== folder) return; + const temp = join(folder, `.${basename(made)}.nf-${randomBytes(4).toString('hex')}`); + if ( + await rename(made, temp).then( + () => true, + () => false, + ) + ) + await rm(temp, { recursive: true, force: true }); +}; + /** Makes `to` through a temp name next to it, renamed over what was there (never followed). */ const replaceWith = async ( to: string, diff --git a/packages/server-core/test/fs/copy-moved.spec.ts b/packages/server-core/test/fs/copy-moved.spec.ts index 69e06f46..d3dc84e0 100644 --- a/packages/server-core/test/fs/copy-moved.spec.ts +++ b/packages/server-core/test/fs/copy-moved.spec.ts @@ -1,6 +1,7 @@ import { mkdirSync, mkdtempSync, + readFileSync, readdirSync, renameSync, rmSync, @@ -53,4 +54,25 @@ describe('copy and changes outside the file API', () => { }); expect(readdirSync(outside)).toEqual([]); }); + + it('never cleans up through a parent swapped for a link when the copy fails', async () => { + const root = mkdtempSync(join(tmpdir(), 'nf-moved-')); + const victim = mkdtempSync(join(tmpdir(), 'nf-victim-')); + roots.push(root, victim); + mkdirSync(join(victim, 't/keep'), { recursive: true }); + writeFileSync(join(victim, 't/keep/precious'), 'data'); + mkdirSync(join(root, 'from/sub'), { recursive: true }); + writeFileSync(join(root, 'from/sub/f'), 'x'); + mkdirSync(join(root, 'dst')); + beforeRead = (path) => { + if (!path.endsWith(join('from', 'sub'))) return; + beforeRead = undefined; + renameSync(join(root, 'dst'), join(root, 'dst-moved')); + symlinkSync(victim, join(root, 'dst')); + }; + await expect(new ProjectFileSystem(root).copy('from', 'dst/t')).rejects.toMatchObject({ + code: 'FORBIDDEN', + }); + expect(readFileSync(join(victim, 't/keep/precious'), 'utf8')).toBe('data'); + }); }); From ddcef84fb12d1e3623f11c4ade95bd3e21425e12 Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 10:17:51 +0100 Subject: [PATCH 30/39] fix(server-core): check a copied link where the system really leads it, once all are made --- packages/server-core/src/fs/fs-service.ts | 53 ++++++++++++++----- .../server-core/test/fs/fs-service.spec.ts | 28 ++++++++++ 2 files changed, 68 insertions(+), 13 deletions(-) diff --git a/packages/server-core/src/fs/fs-service.ts b/packages/server-core/src/fs/fs-service.ts index ec0aaa0e..6bd5b8e6 100644 --- a/packages/server-core/src/fs/fs-service.ts +++ b/packages/server-core/src/fs/fs-service.ts @@ -16,7 +16,7 @@ import { symlink, writeFile, } from 'node:fs/promises'; -import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'; +import { basename, dirname, join, relative, resolve, sep } from 'node:path'; import type { FileContent, @@ -567,13 +567,14 @@ const copyEntry = async ( /** * Copies the links a walk met, as links, once the real path each leads to from its new folder - * passes `checkLink`: followed as the system does (`..` is never collapsed as text, `hop/..` is - * above where `hop` leads), so a relative `../../x` that leaves the project there is refused. A - * link may lead through another one (`.bin/x -> ../x/bin`, `x` a link): those that lead nowhere - * yet wait for the others, and are refused once a round makes none. + * passes `checkLink`. A link may lead through another one (`.bin/x -> ../x/bin`, `x` a link): + * those that lead nowhere yet wait for the others, and are refused once a round makes none. A + * link the copy replaces can change where an earlier one leads, so every link made is checked + * again at the end. In path order, so what is refused does not depend on timing. */ const copyLinks = async (walk: CopyWalk): Promise => { - let pending = walk.links; + const links = walk.links.sort((a, b) => a.path.localeCompare(b.path)); + let pending = links; while (pending.length) { const waiting: CopyWalk['links'] = []; for (const link of pending) if (!(await copyLink(link, walk))) waiting.push(link); @@ -581,9 +582,30 @@ const copyLinks = async (walk: CopyWalk): Promise => { throw new RpcError('FORBIDDEN', `${waiting[0]!.path} is a link that leads nowhere`); pending = waiting; } + for (const { to, path } of links) { + const real = await realpath(to).catch(() => undefined); + const refused = real + ? await walk.checkLink(real, path).then( + () => undefined, + (error: unknown) => error, + ) + : new RpcError('FORBIDDEN', `${path} is a link that leads nowhere`); + if (refused) { + if ((await lstat(to).catch(() => undefined))?.isSymbolicLink()) await rm(to); + throw refused; + } + } }; -/** One link of {@link copyLinks}: false when it leads nowhere (yet). */ +/** Thrown inside {@link copyLink} for a link that leads nowhere (yet). */ +const NOWHERE = new Error('leads nowhere'); + +/** + * One link of {@link copyLinks}: false when it leads nowhere (yet). It is made at a temp name + * next to where it goes and checked there by `realpath`: the system follows it as it will follow + * the copy (a link's text is never joined to a path, where `..` would be collapsed as text: Bun's + * `realpath` does that, and `hop/..` is above where `hop` leads). + */ const copyLink = async ( { from, to, path }: CopyWalk['links'][number], walk: CopyWalk, @@ -592,13 +614,18 @@ const copyLink = async ( const existing = await lstat(to).catch(() => undefined); if (existing && (!walk.overwrite || existing.isDirectory())) throw inTheWay(path); const link = await readlink(from); - const real = await realpath(isAbsolute(link) ? link : `${dirname(to)}${sep}${link}`).catch( - () => undefined, + return replaceWith(to, path, async (temp) => { + await symlink(link, temp); + const real = await realpath(temp).catch(() => undefined); + if (!real) throw NOWHERE; + await walk.checkLink(real, path); + }).then( + () => true, + (error: unknown) => { + if (error === NOWHERE) return false; + throw error; + }, ); - if (!real) return false; - await walk.checkLink(real, path); - await replaceWith(to, path, (temp) => symlink(link, temp)); - return true; }; /** diff --git a/packages/server-core/test/fs/fs-service.spec.ts b/packages/server-core/test/fs/fs-service.spec.ts index 00d5ecfb..21c4d59e 100644 --- a/packages/server-core/test/fs/fs-service.spec.ts +++ b/packages/server-core/test/fs/fs-service.spec.ts @@ -568,6 +568,34 @@ describe('ProjectFileSystem packages, ignore and trash', () => { expect(done).toEqual(['copy', 'write']); }); + it('checks copied links once they are all made, whatever their names', async () => { + /** `a` sorts before `b`, `z` after: either way `b` is replaced by the copy. */ + for (const name of ['a', 'z']) { + const { root, fs } = project(); + mkdirSync(join(root, 'deep/from'), { recursive: true }); + mkdirSync(join(root, 'dst/deep1/deep2'), { recursive: true }); + writeFileSync(join(root, 'dst/x'), 'in'); + symlinkSync('deep1/deep2', join(root, 'dst/b')); + symlinkSync('b/../../x', join(root, `deep/from/${name}`)); + symlinkSync('.', join(root, 'deep/from/b')); + await expect(fs.copy('deep/from', 'dst', true), name).rejects.toMatchObject({ + code: 'FORBIDDEN', + }); + expect(lstatSync(join(root, `dst/${name}`), { throwIfNoEntry: false }), name).toBeUndefined(); + } + }); + + it('checks a copied link through what it really leads through (hop -> ..)', async () => { + const { root, fs } = project(); + writeFileSync(join(root, 'x'), 'in'); + mkdirSync(join(root, 'deep/from'), { recursive: true }); + writeFileSync(join(root, 'deep/from/x'), 'in'); + symlinkSync('..', join(root, 'deep/from/hop')); + symlinkSync('hop/../x', join(root, 'deep/from/a')); + await expect(fs.copy('deep/from', 'dst')).rejects.toMatchObject({ code: 'FORBIDDEN' }); + expect(existsSync(join(root, 'dst'))).toBe(false); + }); + it('restores deleted entries from the trash', async () => { const { root, fs } = project(); const { trashPath } = await fs.delete('src/main.ts'); From 4e5f970c4c9c5865a5568f64993f0a3dd2bf17aa Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 10:18:20 +0100 Subject: [PATCH 31/39] fix(server-core): remove the folders a failed copy made to hold its destination --- packages/server-core/src/fs/fs-service.ts | 9 +++++++-- packages/server-core/test/fs/fs-service.spec.ts | 3 +++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/packages/server-core/src/fs/fs-service.ts b/packages/server-core/src/fs/fs-service.ts index 6bd5b8e6..d4bbe6dc 100644 --- a/packages/server-core/src/fs/fs-service.ts +++ b/packages/server-core/src/fs/fs-service.ts @@ -352,6 +352,12 @@ export class ProjectFileSystem { const source = isLink ? named.target : named.real; if (!isLink && (target === source || target.startsWith(`${source}${sep}`))) throw new RpcError('BAD_REQUEST', `Cannot copy ${from} into itself`); + /** What a failed copy to a new place removes: the first folder it had to make, or `target`. */ + let made: string | undefined; + for (let folder = target; !(await lstat(folder).catch(() => undefined));) { + made = folder; + folder = dirname(folder); + } await mkdir(dirname(target), { recursive: true }); const walk: CopyWalk = { overwrite, @@ -359,7 +365,6 @@ export class ProjectFileSystem { links: [], limit: limiter(COPY_CONCURRENCY), }; - const created = !(await lstat(target).catch(() => undefined)); try { /** Paths of the walk are where the entries really go (`target`), as the guards read them. */ const realRoot = await realpath(this.root); @@ -367,7 +372,7 @@ export class ProjectFileSystem { await copyLinks(walk); } catch (error) { /** A copy to a new place is all or nothing. */ - if (created) await removeMade(target); + if (made) await removeMade(made); return mapError(error, to); } return (await this.stat(to))!; diff --git a/packages/server-core/test/fs/fs-service.spec.ts b/packages/server-core/test/fs/fs-service.spec.ts index 21c4d59e..0a98de31 100644 --- a/packages/server-core/test/fs/fs-service.spec.ts +++ b/packages/server-core/test/fs/fs-service.spec.ts @@ -520,6 +520,9 @@ describe('ProjectFileSystem packages, ignore and trash', () => { symlinkSync('missing', join(root, 'from/l')); await expect(fs.copy('from', 'to')).rejects.toMatchObject({ code: 'FORBIDDEN' }); expect(existsSync(join(root, 'to'))).toBe(false); + /** Nor the folders made to hold it. */ + await expect(fs.copy('from', 'new/deep/to')).rejects.toMatchObject({ code: 'FORBIDDEN' }); + expect(existsSync(join(root, 'new'))).toBe(false); }); it('copies a link named by the copy as a link, and never copies into a link', async () => { From e2a2a619817721406b958d0ee2319f0f22ba24fa Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 10:19:45 +0100 Subject: [PATCH 32/39] fix(server-core): stop a copy at its first failure, in name order --- packages/server-core/src/fs/fs-service.ts | 15 +++++++++++++-- packages/server-core/test/fs/fs-service.spec.ts | 11 +++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/packages/server-core/src/fs/fs-service.ts b/packages/server-core/src/fs/fs-service.ts index d4bbe6dc..9e14c0eb 100644 --- a/packages/server-core/src/fs/fs-service.ts +++ b/packages/server-core/src/fs/fs-service.ts @@ -363,6 +363,7 @@ export class ProjectFileSystem { overwrite, checkLink: (real, path) => this.jail.leadsInside(real, path, packagesReason), links: [], + failed: false, limit: limiter(COPY_CONCURRENCY), }; try { @@ -496,6 +497,8 @@ interface CopyWalk { readonly checkLink: (real: string, path: string) => Promise; /** Links met by the walk: made once the whole tree is there, so any target they have exists. */ readonly links: { from: string; to: string; path: string }[]; + /** Set once an entry failed: the entries not started yet are skipped. */ + failed: boolean; /** Runs one entry's file operations, {@link COPY_CONCURRENCY} at a time over the whole walk. */ readonly limit: (task: () => Promise) => Promise; } @@ -535,7 +538,12 @@ const settleAll = async (tasks: Promise[]): Promise => { * `.git` are left out. `path` (project-relative) names the destination in errors. */ const copyTree = async (from: string, to: string, path: string, walk: CopyWalk): Promise => { - const children = await walk.limit(() => copyEntry(from, to, path, walk)); + const children = await walk + .limit(() => copyEntry(from, to, path, walk)) + .catch((error: unknown) => { + walk.failed = true; + throw error; + }); await settleAll( children.map((name) => copyTree(join(from, name), join(to, name), childPath(path, name), walk)), ); @@ -548,6 +556,7 @@ const copyEntry = async ( path: string, walk: CopyWalk, ): Promise => { + if (walk.failed) return []; assertCopyTarget(path); const info = await lstat(from); if (info.isSymbolicLink()) { @@ -562,10 +571,12 @@ const copyEntry = async ( await assertSameFolder(dirname(to), path); await mkdir(to); } else if (!existing.isDirectory()) throw inTheWay(path); - return (await readdir(from)).filter((name) => !isGitPath(name)); + /** In name order, the same on every runtime: what is copied before a failure is predictable. */ + return (await readdir(from)).filter((name) => !isGitPath(name)).sort(); } if (!info.isFile()) return []; if (existing && (!walk.overwrite || existing.isDirectory())) throw inTheWay(path); + if (walk.failed) return []; await replaceWith(to, path, (temp) => copyFile(from, temp, constants.COPYFILE_EXCL)); return []; }; diff --git a/packages/server-core/test/fs/fs-service.spec.ts b/packages/server-core/test/fs/fs-service.spec.ts index 0a98de31..a0caa6b6 100644 --- a/packages/server-core/test/fs/fs-service.spec.ts +++ b/packages/server-core/test/fs/fs-service.spec.ts @@ -599,6 +599,17 @@ describe('ProjectFileSystem packages, ignore and trash', () => { expect(existsSync(join(root, 'dst'))).toBe(false); }); + it('stops copying once an entry fails', async () => { + const { root, fs } = project(); + mkdirSync(join(root, 'from')); + for (let i = 0; i < 20; i++) writeFileSync(join(root, `from/a${i}`), 'x'); + mkdirSync(join(root, 'ex')); + writeFileSync(join(root, 'ex/a0'), 'old'); + await expect(fs.copy('from', 'ex')).rejects.toMatchObject({ code: 'CONFLICT' }); + /** `a0` and at most the 15 entries copied with it (16 at a time, in name order), not 19 more. */ + expect(readdirSync(join(root, 'ex')).length).toBeLessThanOrEqual(16); + }); + it('restores deleted entries from the trash', async () => { const { root, fs } = project(); const { trashPath } = await fs.delete('src/main.ts'); From 1f7d2e4f7e26c8da0d1fdb1abd488723e72bd81d Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 10:20:44 +0100 Subject: [PATCH 33/39] fix(server-core): remove only the empty folders a failed copy made --- packages/server-core/src/fs/fs-service.ts | 28 +++++++++++++++---- .../server-core/test/fs/copy-moved.spec.ts | 18 ++++++++++++ 2 files changed, 40 insertions(+), 6 deletions(-) diff --git a/packages/server-core/src/fs/fs-service.ts b/packages/server-core/src/fs/fs-service.ts index 9e14c0eb..a2dbbefd 100644 --- a/packages/server-core/src/fs/fs-service.ts +++ b/packages/server-core/src/fs/fs-service.ts @@ -12,6 +12,7 @@ import { realpath, rename, rm, + rmdir, stat, symlink, writeFile, @@ -352,13 +353,21 @@ export class ProjectFileSystem { const source = isLink ? named.target : named.real; if (!isLink && (target === source || target.startsWith(`${source}${sep}`))) throw new RpcError('BAD_REQUEST', `Cannot copy ${from} into itself`); - /** What a failed copy to a new place removes: the first folder it had to make, or `target`. */ - let made: string | undefined; - for (let folder = target; !(await lstat(folder).catch(() => undefined));) { - made = folder; + /** Folders made here to hold `target`, one by one: a failed copy removes those still empty. */ + const missing: string[] = []; + for (let folder = dirname(target); !(await lstat(folder).catch(() => undefined));) { + missing.unshift(folder); folder = dirname(folder); } - await mkdir(dirname(target), { recursive: true }); + const madeFolders: string[] = []; + for (const folder of missing) { + const made = await mkdir(folder).then( + () => true, + (error: unknown) => (errno(error) === 'EEXIST' ? false : mapError(error, to)), + ); + if (made) madeFolders.push(folder); + } + const created = !(await lstat(target).catch(() => undefined)); const walk: CopyWalk = { overwrite, checkLink: (real, path) => this.jail.leadsInside(real, path, packagesReason), @@ -373,7 +382,8 @@ export class ProjectFileSystem { await copyLinks(walk); } catch (error) { /** A copy to a new place is all or nothing. */ - if (made) await removeMade(made); + if (created) await removeMade(target); + for (const folder of madeFolders.reverse()) await removeEmptyFolder(folder); return mapError(error, to); } return (await this.stat(to))!; @@ -673,6 +683,12 @@ const removeMade = async (made: string): Promise => { await rm(temp, { recursive: true, force: true }); }; +/** Removes a folder a failed copy made, if it is still empty and still really that folder. */ +const removeEmptyFolder = async (folder: string): Promise => { + if ((await realpath(folder).catch(() => undefined)) === folder) + await rmdir(folder).catch(() => {}); +}; + /** Makes `to` through a temp name next to it, renamed over what was there (never followed). */ const replaceWith = async ( to: string, diff --git a/packages/server-core/test/fs/copy-moved.spec.ts b/packages/server-core/test/fs/copy-moved.spec.ts index d3dc84e0..45cf5387 100644 --- a/packages/server-core/test/fs/copy-moved.spec.ts +++ b/packages/server-core/test/fs/copy-moved.spec.ts @@ -75,4 +75,22 @@ describe('copy and changes outside the file API', () => { }); expect(readFileSync(join(victim, 't/keep/precious'), 'utf8')).toBe('data'); }); + + it('keeps what another writer adds to a folder a failing copy made', async () => { + const root = mkdtempSync(join(tmpdir(), 'nf-moved-')); + roots.push(root); + mkdirSync(join(root, 'from')); + writeFileSync(join(root, 'from/f'), 'x'); + symlinkSync('missing', join(root, 'from/l')); + beforeRead = (path) => { + if (!path.endsWith('from')) return; + beforeRead = undefined; + writeFileSync(join(root, 'new/deep/other.txt'), 'theirs'); + }; + await expect(new ProjectFileSystem(root).copy('from', 'new/deep/to')).rejects.toMatchObject({ + code: 'FORBIDDEN', + }); + expect(readFileSync(join(root, 'new/deep/other.txt'), 'utf8')).toBe('theirs'); + expect(readdirSync(join(root, 'new/deep'))).toEqual(['other.txt']); + }); }); From 51ddb1101aaed7714b358e895aefd3dee9b71c6d Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 10:22:09 +0100 Subject: [PATCH 34/39] fix(server-core): never replace a link already in a copy's destination --- packages/server-core/src/fs/fs-service.ts | 8 +++-- .../server-core/test/fs/fs-service.spec.ts | 35 ++++++++++++++++--- 2 files changed, 37 insertions(+), 6 deletions(-) diff --git a/packages/server-core/src/fs/fs-service.ts b/packages/server-core/src/fs/fs-service.ts index a2dbbefd..1bf89080 100644 --- a/packages/server-core/src/fs/fs-service.ts +++ b/packages/server-core/src/fs/fs-service.ts @@ -585,7 +585,9 @@ const copyEntry = async ( return (await readdir(from)).filter((name) => !isGitPath(name)).sort(); } if (!info.isFile()) return []; - if (existing && (!walk.overwrite || existing.isDirectory())) throw inTheWay(path); + /** A link already there is never replaced: it could change where other links lead. */ + if (existing && (!walk.overwrite || existing.isDirectory() || existing.isSymbolicLink())) + throw inTheWay(path); if (walk.failed) return []; await replaceWith(to, path, (temp) => copyFile(from, temp, constants.COPYFILE_EXCL)); return []; @@ -638,7 +640,9 @@ const copyLink = async ( ): Promise => { assertCopyTarget(path); const existing = await lstat(to).catch(() => undefined); - if (existing && (!walk.overwrite || existing.isDirectory())) throw inTheWay(path); + /** A link already there is never replaced: it could change where other links lead. */ + if (existing && (!walk.overwrite || existing.isDirectory() || existing.isSymbolicLink())) + throw inTheWay(path); const link = await readlink(from); return replaceWith(to, path, async (temp) => { await symlink(link, temp); diff --git a/packages/server-core/test/fs/fs-service.spec.ts b/packages/server-core/test/fs/fs-service.spec.ts index a0caa6b6..301c44fd 100644 --- a/packages/server-core/test/fs/fs-service.spec.ts +++ b/packages/server-core/test/fs/fs-service.spec.ts @@ -8,6 +8,8 @@ import { mkdtempSync, readFileSync, readdirSync, + readlinkSync, + realpathSync, rmSync, statSync, symlinkSync, @@ -378,7 +380,8 @@ describe('ProjectFileSystem packages, ignore and trash', () => { mkdirSync(join(root, 'dst')); symlinkSync(join(outside, 'f'), join(root, 'dst/f')); symlinkSync('../nf_modules/pkg', join(root, 'dst/sub')); - await expect(fs.copy('from', 'dst', true)).rejects.toMatchObject({ code: 'FORBIDDEN' }); + /** `dst/f` (a link) is in the way, with or without overwrite. */ + await expect(fs.copy('from', 'dst', true)).rejects.toMatchObject({ code: 'CONFLICT' }); await expect(fs.copy('from', 'dst')).rejects.toMatchObject({ code: 'CONFLICT' }); /** Only new names: nothing in the way but the linked folder. */ mkdirSync(join(root, 'dst2')); @@ -572,7 +575,7 @@ describe('ProjectFileSystem packages, ignore and trash', () => { }); it('checks copied links once they are all made, whatever their names', async () => { - /** `a` sorts before `b`, `z` after: either way `b` is replaced by the copy. */ + /** `a` sorts before `b`, `z` after: `b`, a link already there, is in the way either way. */ for (const name of ['a', 'z']) { const { root, fs } = project(); mkdirSync(join(root, 'deep/from'), { recursive: true }); @@ -582,9 +585,12 @@ describe('ProjectFileSystem packages, ignore and trash', () => { symlinkSync('b/../../x', join(root, `deep/from/${name}`)); symlinkSync('.', join(root, 'deep/from/b')); await expect(fs.copy('deep/from', 'dst', true), name).rejects.toMatchObject({ - code: 'FORBIDDEN', + code: 'CONFLICT', }); - expect(lstatSync(join(root, `dst/${name}`), { throwIfNoEntry: false }), name).toBeUndefined(); + /** What it made before stopping still leads inside (`b` was never replaced). */ + const made = join(root, `dst/${name}`); + if (existsSync(made)) + expect(realpathSync.native(made), name).toBe(join(realpathSync.native(root), 'dst/x')); } }); @@ -610,6 +616,27 @@ describe('ProjectFileSystem packages, ignore and trash', () => { expect(readdirSync(join(root, 'ex')).length).toBeLessThanOrEqual(16); }); + it('never replaces a link already in the destination, even with overwrite', async () => { + const { root, fs } = project(); + mkdirSync(join(root, 'dst')); + symlinkSync('../src', join(root, 'dst/b')); + symlinkSync('../src/main.ts', join(root, 'dst/f')); + mkdirSync(join(root, 'from')); + writeFileSync(join(root, 'from/f'), 'new'); + await expect(fs.copy('from', 'dst', true)).rejects.toMatchObject({ + code: 'CONFLICT', + message: 'Already exists: dst/f', + }); + rmSync(join(root, 'from/f')); + symlinkSync('.', join(root, 'from/b')); + await expect(fs.copy('from', 'dst', true)).rejects.toMatchObject({ + code: 'CONFLICT', + message: 'Already exists: dst/b', + }); + expect(lstatSync(join(root, 'dst/f')).isSymbolicLink()).toBe(true); + expect(readlinkSync(join(root, 'dst/b'))).toBe('../src'); + }); + it('restores deleted entries from the trash', async () => { const { root, fs } = project(); const { trashPath } = await fs.delete('src/main.ts'); From 9d1fb3f1c2bc178bd261a1a2b5062529dd6ed702 Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 10:22:40 +0100 Subject: [PATCH 35/39] fix(server-core): remove every copied link that leads outside, not only the first --- packages/server-core/src/fs/fs-service.ts | 10 +++--- .../server-core/test/fs/copy-moved.spec.ts | 32 +++++++++++++++++++ 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/packages/server-core/src/fs/fs-service.ts b/packages/server-core/src/fs/fs-service.ts index 1bf89080..25a98661 100644 --- a/packages/server-core/src/fs/fs-service.ts +++ b/packages/server-core/src/fs/fs-service.ts @@ -610,6 +610,8 @@ const copyLinks = async (walk: CopyWalk): Promise => { throw new RpcError('FORBIDDEN', `${waiting[0]!.path} is a link that leads nowhere`); pending = waiting; } + /** Every link is checked, every refused one removed, then the first refusal is thrown. */ + const refusals: unknown[] = []; for (const { to, path } of links) { const real = await realpath(to).catch(() => undefined); const refused = real @@ -618,11 +620,11 @@ const copyLinks = async (walk: CopyWalk): Promise => { (error: unknown) => error, ) : new RpcError('FORBIDDEN', `${path} is a link that leads nowhere`); - if (refused) { - if ((await lstat(to).catch(() => undefined))?.isSymbolicLink()) await rm(to); - throw refused; - } + if (!refused) continue; + refusals.push(refused); + if ((await lstat(to).catch(() => undefined))?.isSymbolicLink()) await rm(to); } + if (refusals.length) throw refusals[0]; }; /** Thrown inside {@link copyLink} for a link that leads nowhere (yet). */ diff --git a/packages/server-core/test/fs/copy-moved.spec.ts b/packages/server-core/test/fs/copy-moved.spec.ts index 45cf5387..cf026b53 100644 --- a/packages/server-core/test/fs/copy-moved.spec.ts +++ b/packages/server-core/test/fs/copy-moved.spec.ts @@ -17,6 +17,8 @@ import { ProjectFileSystem } from '../../src/fs/fs-service'; /** Runs before the walk reads a source folder: where a test moves things outside the file API. */ let beforeRead: ((path: string) => void) | undefined; +/** Runs before the copy looks up where a path really leads. */ +let beforeRealpath: ((path: string) => void) | undefined; vi.mock('node:fs/promises', async (original) => { const real = await original(); return { @@ -25,12 +27,17 @@ vi.mock('node:fs/promises', async (original) => { beforeRead?.(String(path)); return (real.readdir as (...args: unknown[]) => unknown)(path, ...rest); }) as typeof real.readdir, + realpath: ((path: string, ...rest: unknown[]) => { + beforeRealpath?.(String(path)); + return (real.realpath as (...args: unknown[]) => unknown)(path, ...rest); + }) as typeof real.realpath, }; }); const roots: string[] = []; afterEach(() => { beforeRead = undefined; + beforeRealpath = undefined; for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); }); @@ -93,4 +100,29 @@ describe('copy and changes outside the file API', () => { expect(readFileSync(join(root, 'new/deep/other.txt'), 'utf8')).toBe('theirs'); expect(readdirSync(join(root, 'new/deep'))).toEqual(['other.txt']); }); + + it('removes every link that leads outside once all are made, not only the first', async () => { + const root = mkdtempSync(join(tmpdir(), 'nf-moved-')); + const outside = mkdtempSync(join(tmpdir(), 'nf-outside-')); + roots.push(root, outside); + writeFileSync(join(outside, 'x'), 'secret'); + writeFileSync(join(outside, 'y'), 'secret'); + mkdirSync(join(root, 'dst/hop'), { recursive: true }); + writeFileSync(join(root, 'dst/hop/x'), 'in'); + writeFileSync(join(root, 'dst/hop/y'), 'in'); + mkdirSync(join(root, 'from')); + symlinkSync('hop/x', join(root, 'from/l1')); + symlinkSync('hop/y', join(root, 'from/l2')); + /** Once both links are made, `hop` is swapped for a link out of the project. */ + beforeRealpath = (path) => { + if (!path.endsWith(join('dst', 'l1'))) return; + beforeRealpath = undefined; + renameSync(join(root, 'dst/hop'), join(root, 'hop-old')); + symlinkSync(outside, join(root, 'dst/hop')); + }; + await expect(new ProjectFileSystem(root).copy('from', 'dst')).rejects.toMatchObject({ + code: 'FORBIDDEN', + }); + expect(readdirSync(join(root, 'dst')).sort()).toEqual(['hop']); + }); }); From 8167a08f069618ab408c1c28068f3b21a2677c5f Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 10:23:08 +0100 Subject: [PATCH 36/39] fix(server-core): refuse nf_modules whatever its case --- packages/server-core/src/fs/fs-service.ts | 10 +++++++--- packages/server-core/test/fs/fs-service.spec.ts | 7 +++++++ 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/packages/server-core/src/fs/fs-service.ts b/packages/server-core/src/fs/fs-service.ts index 25a98661..97d2e7a2 100644 --- a/packages/server-core/src/fs/fs-service.ts +++ b/packages/server-core/src/fs/fs-service.ts @@ -74,10 +74,14 @@ const assertAccessible = (path: string) => { if (refused) throw new RpcError('FORBIDDEN', refused); }; -/** {@link PathGuard} refusing a path inside `nf_modules`: installing is the only way to change it. */ +/** + * {@link PathGuard} refusing a path inside `nf_modules`, whatever its case (one folder on macOS and + * Windows, as `.git` is): installing is the only way to change it. + */ const packagesReason: PathGuard = (path) => - path === PACKAGES_DIR || path.startsWith(`${PACKAGES_DIR}/`) - ? `${path} is part of an installed package (nf_modules), which cannot be changed. Copy it into your project to modify it.` + path.split(/[\\/]/, 1)[0]!.toLowerCase() === PACKAGES_DIR + ? `${path} is part of an installed package (nf_modules), which cannot be changed. ` + + 'Copy it into your project to modify it.' : undefined; const assertWritable = (path: string) => { diff --git a/packages/server-core/test/fs/fs-service.spec.ts b/packages/server-core/test/fs/fs-service.spec.ts index 301c44fd..6bab9dc4 100644 --- a/packages/server-core/test/fs/fs-service.spec.ts +++ b/packages/server-core/test/fs/fs-service.spec.ts @@ -637,6 +637,13 @@ describe('ProjectFileSystem packages, ignore and trash', () => { expect(readlinkSync(join(root, 'dst/b'))).toBe('../src'); }); + it('refuses nf_modules whatever its case (one folder on macOS and Windows)', async () => { + const { fs } = project(); + for (const path of ['NF_Modules/pkg/index.js', 'Nf_modules', 'NF_MODULES/x']) + await expect(fs.write(path, 'x'), path).rejects.toMatchObject({ code: 'FORBIDDEN' }); + await fs.write('nf_modules_backup/x', 'x'); + }); + it('restores deleted entries from the trash', async () => { const { root, fs } = project(); const { trashPath } = await fs.delete('src/main.ts'); From df20e749f1cf4f8bfa3ce9723552376e50c04cdf Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 10:23:21 +0100 Subject: [PATCH 37/39] docs(server-core): describe the copy's order, cleanup and link checks --- docs/specs/file-manager.md | 11 ++++++----- packages/server-core/src/fs/fs-service.ts | 4 ++-- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/docs/specs/file-manager.md b/docs/specs/file-manager.md index ef51d510..55e20ed7 100644 --- a/docs/specs/file-manager.md +++ b/docs/specs/file-manager.md @@ -63,11 +63,12 @@ Browse and organize a game's files: a folder tree, plus a grid of the selected f - Changes through the file API (write, create a folder, rename, copy, delete, restore, empty the trash) run one at a time per project folder. - `fs.copy` never writes through a link: - a link in the destination where a folder goes is refused, and a destination that is a link is refused; - - a file or link already there is replaced (with `overwrite`) or is a conflict that names that entry; - - no entry goes into `nf_modules` or `.git`, even from a copy into the project root, and `.git` folders of the source are left out; - - links are copied as links, after the rest of the tree, and only when they still lead inside the project from their new place (a link that leads nowhere is refused); a copied link named by the copy stays a link; - - a copy to a new place that fails leaves nothing behind; one into an existing folder keeps what it had copied; - - a folder swapped for a link by another program during the copy stops it. + - a file already there is replaced (with `overwrite`) or is a conflict that names that entry; a link already there is always a conflict (replacing it could change where other links lead); + - no entry goes into `nf_modules` (in any case) or `.git`, even from a copy into the project root, and `.git` folders of the source are left out; + - entries are copied in name order, and the copy stops at the first failure (entries already under way still finish); + - links are copied as links, after the rest of the tree, and only when they lead inside the project from their new place, as the system follows them; they are all checked again at the end, and every one that no longer leads inside is removed; a link that leads nowhere is refused; a link named by the copy stays a link; + - a copy to a new place that fails removes what it made, and the folders it made to hold it if they are still empty; one into an existing folder keeps what it had copied; + - a folder swapped for a link by another program during the copy stops it, and the cleanup never goes through such a folder. ## Done when diff --git a/packages/server-core/src/fs/fs-service.ts b/packages/server-core/src/fs/fs-service.ts index 97d2e7a2..8636fda9 100644 --- a/packages/server-core/src/fs/fs-service.ts +++ b/packages/server-core/src/fs/fs-service.ts @@ -357,7 +357,7 @@ export class ProjectFileSystem { const source = isLink ? named.target : named.real; if (!isLink && (target === source || target.startsWith(`${source}${sep}`))) throw new RpcError('BAD_REQUEST', `Cannot copy ${from} into itself`); - /** Folders made here to hold `target`, one by one: a failed copy removes those still empty. */ + /** Folders made to hold `target`, one by one: a failed copy removes those still empty. */ const missing: string[] = []; for (let folder = dirname(target); !(await lstat(folder).catch(() => undefined));) { missing.unshift(folder); @@ -380,7 +380,7 @@ export class ProjectFileSystem { limit: limiter(COPY_CONCURRENCY), }; try { - /** Paths of the walk are where the entries really go (`target`), as the guards read them. */ + /** The walk's paths are where entries really go (`target`), as the guards read them. */ const realRoot = await realpath(this.root); await copyTree(source, target, relative(realRoot, target).split(sep).join('/'), walk); await copyLinks(walk); From 2af144fd0cad650b73e36f990e10d4482b3af9b1 Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 10:26:41 +0100 Subject: [PATCH 38/39] test(server-core): name the copy tests for what they check, and stop a copy of 200 files --- packages/server-core/test/fs/fs-service.spec.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/packages/server-core/test/fs/fs-service.spec.ts b/packages/server-core/test/fs/fs-service.spec.ts index 6bab9dc4..1ab2a9f2 100644 --- a/packages/server-core/test/fs/fs-service.spec.ts +++ b/packages/server-core/test/fs/fs-service.spec.ts @@ -395,7 +395,7 @@ describe('ProjectFileSystem packages, ignore and trash', () => { expect(readFileSync(join(root, 'fresh/sub/h'), 'utf8')).toBe('NEW'); }); - it('never restores out of nf_modules through a linked trash, nor a name that leaves it', async () => { + it('never restores from nf_modules via a linked trash, or a name leaving it', async () => { const { root, fs } = project(); mkdirSync(join(root, 'nf_modules/pkg'), { recursive: true }); mkdirSync(join(root, '.nanoforge/editor'), { recursive: true }); @@ -416,7 +416,7 @@ describe('ProjectFileSystem packages, ignore and trash', () => { for (let run = 0; run < 60; run++) { const { root, fs } = project(); mkdirSync(join(root, 'from/t/sub'), { recursive: true }); - for (let i = 0; i < 20; i++) writeFileSync(join(root, `from/a${i}`), 'x'); + for (let i = 0; i < 200; i++) writeFileSync(join(root, `from/a${i}`), 'x'); writeFileSync(join(root, 'from/t/sub/planted'), 'x'); mkdirSync(join(root, 'dst')); mkdirSync(join(root, 'evil')); @@ -441,7 +441,7 @@ describe('ProjectFileSystem packages, ignore and trash', () => { expect(done).toEqual(['copy', 'rename', 'write']); }); - it('never copies a relative link that would leave the project, or reach nf_modules, from its new place', async () => { + it('never copies a relative link that leaves the project or reaches nf_modules', async () => { const { root, fs } = project(); mkdirSync(join(root, 'p/q/from/deep'), { recursive: true }); symlinkSync('../../../../src/main.ts', join(root, 'p/q/from/deep/l')); @@ -463,7 +463,7 @@ describe('ProjectFileSystem packages, ignore and trash', () => { expect(lstatSync(join(root, 'src/copied/a-link')).isSymbolicLink()).toBe(true); }); - it('checks a copied link the way the system follows it, not by collapsing .. as text', async () => { + it('checks a copied link as the system follows it, not collapsing .. as text', async () => { const { root, fs } = project(); const outside = mkdtempSync(join(tmpdir(), 'nf-outside-')); roots.push(outside); @@ -574,7 +574,7 @@ describe('ProjectFileSystem packages, ignore and trash', () => { expect(done).toEqual(['copy', 'write']); }); - it('checks copied links once they are all made, whatever their names', async () => { + it('keeps copied links inside when a link is in the way, in any name order', async () => { /** `a` sorts before `b`, `z` after: `b`, a link already there, is in the way either way. */ for (const name of ['a', 'z']) { const { root, fs } = project(); @@ -612,7 +612,7 @@ describe('ProjectFileSystem packages, ignore and trash', () => { mkdirSync(join(root, 'ex')); writeFileSync(join(root, 'ex/a0'), 'old'); await expect(fs.copy('from', 'ex')).rejects.toMatchObject({ code: 'CONFLICT' }); - /** `a0` and at most the 15 entries copied with it (16 at a time, in name order), not 19 more. */ + /** `a0` and at most the 15 entries copied with it (16 at a time), not the 199 others. */ expect(readdirSync(join(root, 'ex')).length).toBeLessThanOrEqual(16); }); From f412e8ac8b449e667926967da56661fe9805fccf Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 10:36:21 +0100 Subject: [PATCH 39/39] fix(server-core): roll back a failed folder of a copy and check each refused link's folder --- docs/specs/file-manager.md | 4 +- packages/server-core/src/fs/fs-service.ts | 58 +++++++++++-------- .../server-core/test/fs/fs-service.spec.ts | 3 + 3 files changed, 39 insertions(+), 26 deletions(-) diff --git a/docs/specs/file-manager.md b/docs/specs/file-manager.md index 55e20ed7..b32b57bf 100644 --- a/docs/specs/file-manager.md +++ b/docs/specs/file-manager.md @@ -65,10 +65,10 @@ Browse and organize a game's files: a folder tree, plus a grid of the selected f - a link in the destination where a folder goes is refused, and a destination that is a link is refused; - a file already there is replaced (with `overwrite`) or is a conflict that names that entry; a link already there is always a conflict (replacing it could change where other links lead); - no entry goes into `nf_modules` (in any case) or `.git`, even from a copy into the project root, and `.git` folders of the source are left out; - - entries are copied in name order, and the copy stops at the first failure (entries already under way still finish); + - entries are started in name order, 16 at a time, and the copy stops at the first failure (entries already under way still finish); the error reported is one of the failing entries; - links are copied as links, after the rest of the tree, and only when they lead inside the project from their new place, as the system follows them; they are all checked again at the end, and every one that no longer leads inside is removed; a link that leads nowhere is refused; a link named by the copy stays a link; - a copy to a new place that fails removes what it made, and the folders it made to hold it if they are still empty; one into an existing folder keeps what it had copied; - - a folder swapped for a link by another program during the copy stops it, and the cleanup never goes through such a folder. + - a folder swapped for a link by another program during the copy stops it, and the cleanup checks that the folder is the same before removing. ## Done when diff --git a/packages/server-core/src/fs/fs-service.ts b/packages/server-core/src/fs/fs-service.ts index 8636fda9..c2a0cbb7 100644 --- a/packages/server-core/src/fs/fs-service.ts +++ b/packages/server-core/src/fs/fs-service.ts @@ -364,13 +364,6 @@ export class ProjectFileSystem { folder = dirname(folder); } const madeFolders: string[] = []; - for (const folder of missing) { - const made = await mkdir(folder).then( - () => true, - (error: unknown) => (errno(error) === 'EEXIST' ? false : mapError(error, to)), - ); - if (made) madeFolders.push(folder); - } const created = !(await lstat(target).catch(() => undefined)); const walk: CopyWalk = { overwrite, @@ -380,6 +373,15 @@ export class ProjectFileSystem { limit: limiter(COPY_CONCURRENCY), }; try { + for (const folder of missing) { + const made = await mkdir(folder).then( + () => true, + (error: unknown) => (errno(error) === 'EEXIST' ? false : Promise.reject(error)), + ); + if (made) madeFolders.push(folder); + else if (!(await lstat(folder)).isDirectory()) + throw new RpcError('FORBIDDEN', `${to}: a folder on its way is not a folder`); + } /** The walk's paths are where entries really go (`target`), as the guards read them. */ const realRoot = await realpath(this.root); await copyTree(source, target, relative(realRoot, target).split(sep).join('/'), walk); @@ -547,9 +549,10 @@ const settleAll = async (tasks: Promise[]): Promise => { /** * Copies `from` to `to` entry by entry, never through a link at the destination (Bun's `cp` * writes through one, out of the project): a folder is made by a plain `mkdir` or must already - * be a real folder, a file goes to a temp name renamed over the old entry (a link there is - * replaced, not followed). Links are only collected (see {@link copyLink}); pipes, sockets and - * `.git` are left out. `path` (project-relative) names the destination in errors. + * be a real folder, a file goes to a temp name renamed over the old entry (a link already + * there is a conflict, never followed). Links are only collected (see {@link copyLink}); + * pipes, sockets and `.git` are left out. `path` (project-relative) names the destination in + * errors. */ const copyTree = async (from: string, to: string, path: string, walk: CopyWalk): Promise => { const children = await walk @@ -605,7 +608,7 @@ const copyEntry = async ( * again at the end. In path order, so what is refused does not depend on timing. */ const copyLinks = async (walk: CopyWalk): Promise => { - const links = walk.links.sort((a, b) => a.path.localeCompare(b.path)); + const links = walk.links.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)); let pending = links; while (pending.length) { const waiting: CopyWalk['links'] = []; @@ -614,21 +617,26 @@ const copyLinks = async (walk: CopyWalk): Promise => { throw new RpcError('FORBIDDEN', `${waiting[0]!.path} is a link that leads nowhere`); pending = waiting; } - /** Every link is checked, every refused one removed, then the first refusal is thrown. */ - const refusals: unknown[] = []; + /** Every link is checked, every refused one removed, then the first error is thrown. */ + const errors: unknown[] = []; for (const { to, path } of links) { - const real = await realpath(to).catch(() => undefined); - const refused = real - ? await walk.checkLink(real, path).then( - () => undefined, - (error: unknown) => error, - ) - : new RpcError('FORBIDDEN', `${path} is a link that leads nowhere`); - if (!refused) continue; - refusals.push(refused); - if ((await lstat(to).catch(() => undefined))?.isSymbolicLink()) await rm(to); + try { + const real = await realpath(to).catch(() => undefined); + const refused = real + ? await walk.checkLink(real, path).then( + () => undefined, + (error: unknown) => error, + ) + : new RpcError('FORBIDDEN', `${path} is a link that leads nowhere`); + if (!refused) continue; + errors.push(refused); + await assertSameFolder(dirname(to), path); + if ((await lstat(to).catch(() => undefined))?.isSymbolicLink()) await rm(to); + } catch (error) { + errors.push(error); + } } - if (refusals.length) throw refusals[0]; + if (errors.length) throw errors[0]; }; /** Thrown inside {@link copyLink} for a link that leads nowhere (yet). */ @@ -679,6 +687,8 @@ const assertSameFolder = async (folder: string, path: string): Promise => * Removes what a failed copy made, only while its folder still really is that path (swapped for a * link, the removal would reach outside). It is moved to a temp name in that folder first, so * what is removed is what was checked; a link moved in is removed, never followed. + * shortcut: the folder can still be swapped between the realpath check and the rename (Node has + * no `openat`), upgrade if Node or Bun gets one. */ const removeMade = async (made: string): Promise => { const folder = dirname(made); diff --git a/packages/server-core/test/fs/fs-service.spec.ts b/packages/server-core/test/fs/fs-service.spec.ts index 1ab2a9f2..4aec3b92 100644 --- a/packages/server-core/test/fs/fs-service.spec.ts +++ b/packages/server-core/test/fs/fs-service.spec.ts @@ -526,6 +526,9 @@ describe('ProjectFileSystem packages, ignore and trash', () => { /** Nor the folders made to hold it. */ await expect(fs.copy('from', 'new/deep/to')).rejects.toMatchObject({ code: 'FORBIDDEN' }); expect(existsSync(join(root, 'new'))).toBe(false); + /** Nor when making one of those folders fails (a name too long). */ + await expect(fs.copy('from', `n1/n2/${'n'.repeat(300)}/x`)).rejects.toBeDefined(); + expect(existsSync(join(root, 'n1'))).toBe(false); }); it('copies a link named by the copy as a link, and never copies into a link', async () => {