diff --git a/AGENTS.md b/AGENTS.md index 48bc212f..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,8 +178,10 @@ 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). - `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..357f998f 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`. 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 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..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. +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. diff --git a/docs/specs/file-manager.md b/docs/specs/file-manager.md index ce389244..b32b57bf 100644 --- a/docs/specs/file-manager.md +++ b/docs/specs/file-manager.md @@ -54,10 +54,21 @@ 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. +- 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 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 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 checks that the folder is the same before removing. ## Done when 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 90835229..c2a0cbb7 100644 --- a/packages/server-core/src/fs/fs-service.ts +++ b/packages/server-core/src/fs/fs-service.ts @@ -1,8 +1,23 @@ 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 { basename, dirname, join } from 'node:path'; +import { constants, existsSync, realpathSync } from 'node:fs'; +import { + chmod, + copyFile, + lstat, + mkdir, + readFile, + readdir, + readlink, + realpath, + rename, + rm, + rmdir, + stat, + symlink, + writeFile, +} from 'node:fs/promises'; +import { basename, dirname, join, relative, resolve, sep } from 'node:path'; import type { FileContent, @@ -15,7 +30,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,35 +69,40 @@ 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`, 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.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) => { 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); }; +/** + * 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; - private readonly _writes = 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; @@ -90,9 +110,18 @@ 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); + this._changesKey = (() => { + try { + return realpathSync(root); + } catch { + return resolve(root); + } + })(); } /** Whether `.nfignore` hides a path (directories are tested with and without a trailing /). */ @@ -133,7 +162,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(); @@ -145,6 +182,12 @@ 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')) { + this._onSkip?.(rel, error); + return; + } return mapError(error, rel); } for (const entry of names.sort((a, b) => a.name.localeCompare(b.name))) { @@ -154,8 +197,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)) { @@ -232,15 +276,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); - const absolute = await this.jail.resolve(path); - return this._writes.run(absolute, 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), @@ -252,12 +300,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 permissions (a script stays executable), never setuid. */ + const mode = (await stat(target).catch(() => undefined))?.mode; try { await writeFile(temp, content); - await rename(temp, absolute); + if (mode !== undefined) await chmod(temp, mode & 0o777); + await rename(temp, target); } catch (error) { await rm(temp, { force: true }); return mapError(error, path); @@ -269,92 +320,147 @@ export class ProjectFileSystem { }); } - async mkdir(path: string): Promise { - assertWritable(path); - const absolute = await this.jail.resolve(path); - 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); - const target = await this.jail.resolve(to); - 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 source = await this.jail.resolve(from); - const target = await this.jail.resolve(to); - if (!existsSync(source)) throw notFound(from); - await cp(source, target, { recursive: true, force: overwrite, errorOnExist: !overwrite }).catch( - (error: unknown) => mapError(error, from), - ); - return (await this.stat(to))!; + copy(from: string, to: string, overwrite = false): Promise { + return this._serial(async () => { + assertAccessible(from); + assertWritable(to); + 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`); + /** 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); + folder = dirname(folder); + } + const madeFolders: string[] = []; + const created = !(await lstat(target).catch(() => undefined)); + const walk: CopyWalk = { + overwrite, + checkLink: (real, path) => this.jail.leadsInside(real, path, packagesReason), + links: [], + failed: false, + 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); + await copyLinks(walk); + } catch (error) { + /** A copy to a new place is all or nothing. */ + if (created) await removeMade(target); + for (const folder of madeFolders.reverse()) await removeEmptyFolder(folder); + return 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); - if (!existsSync(source)) throw notFound(path); - const trash = await this.jail.resolve(TRASH_DIR); - 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); - 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 { - if ( - !trashPath.startsWith(`${TRASH_DIR}/`) || - trashPath.slice(TRASH_DIR.length + 1).includes('/') - ) { - throw new RpcError('BAD_REQUEST', `Not in the trash: ${trashPath}`); - } - assertWritable(to); - const source = await this.jail.resolve(trashPath); - const target = await this.jail.resolve(to); - 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 CHANGES.run(this._changesKey, task); } private async _readOne(file: ReadRequest): Promise { @@ -376,12 +482,250 @@ export class ProjectFileSystem { } private async _ensureEditorGitignore(): Promise { - const file = await this.jail.resolve(`${EDITOR_DIR}/.gitignore`); - 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; + }); } } /** 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}/`); +/** 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). */ +const childPath = (path: string, name: string) => (path ? `${path}/${name}` : name); + +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 }[]; + /** 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; +} + +/** 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 + * 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 + .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)), + ); +}; + +/** 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 => { + if (walk.failed) return []; + assertCopyTarget(path); + 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 assertSameFolder(dirname(to), path); + await mkdir(to); + } else if (!existing.isDirectory()) throw inTheWay(path); + /** 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 []; + /** 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 []; +}; + +/** + * Copies the links a walk met, as links, once the real path each leads to from its new folder + * 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 => { + 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'] = []; + 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; + } + /** Every link is checked, every refused one removed, then the first error is thrown. */ + const errors: unknown[] = []; + for (const { to, path } of links) { + 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 (errors.length) throw errors[0]; +}; + +/** 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, +): Promise => { + assertCopyTarget(path); + const existing = await lstat(to).catch(() => undefined); + /** 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); + 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; + }, + ); +}; + +/** + * 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`); +}; + +/** + * 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); + 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 }); +}; + +/** 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, + 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); + await rename(temp, to); + } catch (error) { + await rm(temp, { force: true }); + throw error; + } +}; + +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/src/fs/path-jail.ts b/packages/server-core/src/fs/path-jail.ts index c168707e..e20c3549 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,15 +56,33 @@ export class PathJail { private readonly _guard?: PathGuard, ) {} - async resolve(path: string): Promise { + 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); + 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 refused = this._guard?.(relative(this._realRoot, real).split(sep).join('/')); + 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; + return real; } /** Project-relative POSIX path of an absolute path inside the root. */ 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/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/git/git-service.ts b/packages/server-core/src/git/git-service.ts index cb912983..cb978c3e 100644 --- a/packages/server-core/src/git/git-service.ts +++ b/packages/server-core/src/git/git-service.ts @@ -30,6 +30,14 @@ const HOSTED_CONFIG = [ ['credential.helper', ''], ] as const; +/** + * 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; + /** Git CLI wrapper; operations on the same repository are serialized. */ export class GitService { private readonly _mutex = new KeyedMutex(); @@ -427,7 +435,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/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 + 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; @@ -56,11 +64,14 @@ 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] : [])), 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 @@ -272,8 +283,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/src/rpc/implementation/runtime.implementation.ts b/packages/server-core/src/rpc/implementation/runtime.implementation.ts index 8e56a5ef..bea48905 100644 --- a/packages/server-core/src/rpc/implementation/runtime.implementation.ts +++ b/packages/server-core/src/rpc/implementation/runtime.implementation.ts @@ -35,7 +35,7 @@ export const implementRuntimeRpc = ( }; }, manifest: ({ project, app }, { session }) => - 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/fs/copy-moved.spec.ts b/packages/server-core/test/fs/copy-moved.spec.ts new file mode 100644 index 00000000..cf026b53 --- /dev/null +++ b/packages/server-core/test/fs/copy-moved.spec.ts @@ -0,0 +1,128 @@ +import { + mkdirSync, + mkdtempSync, + readFileSync, + 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; +/** 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 { + ...real, + readdir: ((path: string, ...rest: unknown[]) => { + 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 }); +}); + +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([]); + }); + + 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'); + }); + + 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']); + }); + + 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']); + }); +}); diff --git a/packages/server-core/test/fs/fs-service.spec.ts b/packages/server-core/test/fs/fs-service.spec.ts index 2bcb4ac8..4aec3b92 100644 --- a/packages/server-core/test/fs/fs-service.spec.ts +++ b/packages/server-core/test/fs/fs-service.spec.ts @@ -3,17 +3,21 @@ import { execFileSync } from 'node:child_process'; import { chmodSync, existsSync, + lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, + readlinkSync, + realpathSync, rmSync, + statSync, symlinkSync, utimesSync, 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'; @@ -24,6 +28,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 +45,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 }); }); @@ -117,6 +131,31 @@ describe('ProjectFileSystem', () => { ]); }); + it.skipIf(asRoot)('lists past a subfolder it cannot read, not past the root', async () => { + 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 () => { + 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 }); @@ -171,6 +210,59 @@ 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('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-')); + 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-')); @@ -233,6 +325,328 @@ 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('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('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')); + /** `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')); + 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'); + }); + + 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 }); + 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('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 < 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')); + 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('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('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')); + 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')); + /** 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 as the system follows it, not 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('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); + /** 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 () => { + 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('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('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('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('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(); + 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: 'CONFLICT', + }); + /** 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')); + } + }); + + 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('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), not the 199 others. */ + 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('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'); @@ -332,4 +746,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]); + }); }); 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']]); + }); +}); 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 = [ 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/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', + }); + }); +}); 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 }); + } + }); +});