diff --git a/.changeset/strict-containment-answers.md b/.changeset/strict-containment-answers.md new file mode 100644 index 0000000000..f969c5399b --- /dev/null +++ b/.changeset/strict-containment-answers.md @@ -0,0 +1,26 @@ +--- +"@schlessera/brain": minor +"@schlessera/brain-ui-sdk": patch +"@schlessera/brain-ui-server": patch +"@schlessera/brain-module-diagrams": patch +"@schlessera/brain-module-travel": patch +"@schlessera/brain-module-images": patch +--- + +**Breaking: `safeResolve` and `resolveWritable` from `@schlessera/brain/module` now give the strictest containment answer in every row (#3422).** They return `null` for: + +- an absolute path, even one inside the brain root; +- any `..` segment, even when the result stays inside; +- `:` or `\` in a segment; +- a dangling symlink, even one whose target is inside; +- a path that leaves the root through one symlink and comes back through another, since every existing component must now stay inside, not only the final path. + +A root whose realpath fails was already refused, and still is. The answer is still the canonical path. + +The CLI still accepts an absolute path argument inside the brain. Before resolving one, it converts it to a brain-relative path with the new `brainRelativeArgument(root, arg)`, which `@schlessera/brain/module` also exports for module commands. This covers `--out`, document paths and the other CLI path flags. An absolute path outside the brain is still refused, and so is one that reaches the outside through a symlink inside the brain or has a `..` segment. + +Migration for module authors: pass paths relative to the brain root. A module command that takes a path argument from the user passes it through `brainRelativeArgument(ctx.root, arg)` first, as the first-party commands do. To re-check an absolute path you already hold, such as an earlier answer from `safeResolve`, pass it relative to the root's realpath (`relative(safeResolve(root, ".")!, path)`). Normalise a link target before resolving it (`join(dirname(path), target)`) instead of sending its `..`. Do not rely on a dangling link to name a file you are about to create. + +The ui-sdk's `resolveInRepo` and the server's file `safeResolve` give the same answers. The SDK newly refuses `..`, `:` and `\`, dangling links and out-and-back links. The server newly refuses a missing brain root instead of falling back to the lexical path. + +The deny-direction containment checks now treat `/` as holding every absolute path. Before, a `/` source passed the worker launcher's refusal of "the brain or its ancestors" for a transport bind, a managed worktree generation and a reference source view, and the server's sync transport mounted a local remote of `/`. A host credential state directory of `/` was also accepted. All of these are now refused. diff --git a/api-report/core.txt b/api-report/core.txt index 65165c36d7..e6c3bd4605 100644 --- a/api-report/core.txt +++ b/api-report/core.txt @@ -159,6 +159,7 @@ export "./module" (./src/module.ts) type WriteFileSafelyOptions WriteRefusedError assertScratchWritable + brainRelativeArgument buildTaxonomy configurationRoot geminiCompletions @@ -1425,6 +1426,8 @@ signatures (every public export and the types it is made of) }, z.core.$strict>>>; }, z.core.$strict>>; }, z.core.$strict>; + brainRelativeArgument (packages/core/src/lib/safe-path.ts) + export function brainRelativeArgument(root: string, arg: string): string; buildPathMatcher (packages/core/src/lib/reranker.ts) export function buildPathMatcher(patterns: readonly string[] | undefined): ((path: string) => boolean) | undefined; buildTaxonomy (packages/core/src/lib/taxonomy.ts) @@ -1578,7 +1581,7 @@ signatures (every public export and the types it is made of) resolveReranker (packages/core/src/lib/registry.ts) export function resolveReranker(config?: RerankerSettings): Reranker | undefined; resolveWritable (packages/core/src/lib/safe-path.ts) - export function resolveWritable(root: string, relOrAbs: string): string | null; + export function resolveWritable(root: string, relPath: string): string | null; restoreStorageAttachment (packages/core/src/lib/storage-attachments.ts) export function restoreStorageAttachment(root: string, path: string, expected: StorageAttachmentVersion, copy: (fd: number) => void, assertCurrent?: () => void): void; rewriteGeneratedRegion (packages/core/src/lib/generated-regions.ts) diff --git a/docs/decisions/container-fresh-proc.md b/docs/decisions/container-fresh-proc.md index 1c35d6245c..d7196c7de5 100644 --- a/docs/decisions/container-fresh-proc.md +++ b/docs/decisions/container-fresh-proc.md @@ -1,7 +1,7 @@ # A fresh /proc for agent workers in a container The agent worker launcher gives every worker its own user and PID namespaces -and a fresh procfs (`workerCommand`, `packages/ui-sdk/src/server/worker-launcher.ts:510-690`). +and a fresh procfs (`workerCommand`, `packages/ui-sdk/src/server/worker-launcher.ts:514-694`). Under Docker's default masked `/proc` paths the kernel refuses that procfs mount, so every turn on such a host refuses with `bwrap: Can't mount proc on /newroot/proc: Operation not permitted` (#1622, @@ -22,7 +22,7 @@ does not change. /proc because the parent /proc has masked or covered paths; in Docker, run the container with --security-opt systempaths=unconfined", followed by bubblewrap's own line. Every other launch failure keeps the generic list - (`FRESH_PROC_REFUSED`, `packages/ui-sdk/src/server/worker-launcher.ts:1637`). + (`FRESH_PROC_REFUSED`, `packages/ui-sdk/src/server/worker-launcher.ts:1646`). The match is on bubblewrap's literal message, not a guess from the environment: a host that refuses for another reason is not told to change Docker options. diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 23e8f86629..11b55f56d0 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -543,7 +543,7 @@ maintenance worker no longer receives the keys the provider relay carries (`GEMINI_API_KEY`, `ANTHROPIC_API_KEY`, `OPENAI_API_KEY` and keys the operator lists for it), and the brain's `.env*` files are masked as they are for a credential-free worker. Its `brain` CLI reaches those providers through its own -relay (`providerRelayFor`, `packages/ui-server/src/brain/host-boundary.ts:421-428`). +relay (`providerRelayFor`, `packages/ui-server/src/brain/host-boundary.ts:422-429`). What remains is narrower and stated in the status: keys the relay does not carry (the `jev` reranker's, a `brain sync` agent runner's login) and every key on a host without managed native storage, where there is no relay. @@ -596,7 +596,7 @@ lists the keys each first-party command reads. The launcher withholds every provider credential in the subprocess descriptor from a governed or strict turn worker, except what its backend declares for its own inference and what an operator admits (`const turnProfile`, -`packages/ui-sdk/src/server/worker-launcher.ts:681-691`). A relayed turn keeps no +`packages/ui-sdk/src/server/worker-launcher.ts:684-694`). A relayed turn keeps no key. An unrelayed one keeps only its runtime's own inference credential, under the 2026-10-22 ruling that hosts without managed native storage keep today's inference credentials; pi resolves its own credentials there, so it keeps all @@ -1029,7 +1029,7 @@ worker's command starts, the server opens that tmpfs from outside through the sandbox's `/proc//root`. It waits until the path is a tmpfs of exactly the allowance on another device than the server's own `/tmp`, and keeps the descriptor -(`function* openPrivateTurnTempSteps`, `packages/ui-sdk/src/server/worker-launcher.ts:1137-1165`). +(`function* openPrivateTurnTempSteps`, `packages/ui-sdk/src/server/worker-launcher.ts:1146-1174`). Every later read goes through that descriptor, after the worker's namespace is gone as well, and never enters another mount, so runtime state below `/tmp` is never read as turn temp. The allowance (256 MiB by default, @@ -2208,7 +2208,7 @@ The worker's private `/tmp` and the other host masks remain in place. After the masks, the launcher re-binds only the explicit runtime inputs the worker needs, read-only, with the same resolution the restricted envelope uses -(`export function restrictedReadPaths`, `packages/ui-sdk/src/server/worker-launcher.ts:1912`): +(`export function restrictedReadPaths`, `packages/ui-sdk/src/server/worker-launcher.ts:1921`): - the Bun executable; - the backend entry's package, its `node_modules` chains and linked workspace @@ -2308,9 +2308,9 @@ and subdirectories through retained aliases. It does not restore unrelated host-temp siblings or make runtime bytes writable. The concrete checks and mounts are in (`validateRuntimePlacement`, -`packages/ui-sdk/src/server/worker-launcher.ts:610-616`), -(`temporaryRuntimeMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:637-676`) -and (`runtimeMaskOverlays`, `packages/ui-sdk/src/server/worker-launcher.ts:792-810`). +`packages/ui-sdk/src/server/worker-launcher.ts:613-619`), +(`temporaryRuntimeMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:640-679`) +and (`runtimeMaskOverlays`, `packages/ui-sdk/src/server/worker-launcher.ts:801-819`). Alias restoration recognizes names already supplied by a read-only bind or an explicit system-view symlink. It does not mount a canonical executable over an existing alias such as `/bin/sh`; missing owned temporary paths still receive @@ -3479,11 +3479,11 @@ An ordinary group-shared directory was accessible, but the worker's private mount and namespace links through `/proc/` were denied. Changing the private directory to `0770` did not remove that process-access barrier. The current launcher opens mounts directly (`function openPrivateState`, -`packages/ui-sdk/src/server/worker-launcher.ts:1100-1128`; +`packages/ui-sdk/src/server/worker-launcher.ts:1109-1137`; `function* openPrivateTurnTempSteps`, -`packages/ui-sdk/src/server/worker-launcher.ts:1137-1163`) before population and +`packages/ui-sdk/src/server/worker-launcher.ts:1146-1172`) before population and start-gate release (`function* launchAgentWorkerSteps`, -`packages/ui-sdk/src/server/worker-launcher.ts:1326-1414`). Group modes and a uid +`packages/ui-sdk/src/server/worker-launcher.ts:1335-1423`). Group modes and a uid switch alone therefore cannot implement the selected cross-uid lifecycle. **Authority and launch.** One trusted external supervisor owns each worker @@ -3918,7 +3918,7 @@ files, `.claude/`, `.agents/`, `.pi/`, `.mcp.json`, and - The core CLI loads `brain.config.ts` or `brain.config.json` at the canonical brain cwd (`loadUserConfig`, `packages/core/src/lib/config.ts:594-628`). Host commands bind that cwd to the selected brain (`function hostSpawn`, - `packages/ui-server/src/brain/host-boundary.ts:512-523`). + `packages/ui-server/src/brain/host-boundary.ts:513-524`). - Bun startup uses root `bunfig.toml` and `package.json`; retained literal preload/module inputs can identify a nested module's nearest package scope. The inventory walks parent directories only within the originating journal diff --git a/docs/decisions/managed-worktrees.md b/docs/decisions/managed-worktrees.md index c1265b08e3..7dfc992e81 100644 --- a/docs/decisions/managed-worktrees.md +++ b/docs/decisions/managed-worktrees.md @@ -98,7 +98,7 @@ Each governed or strict turn whose journal is recording opens one worker generation, and every worker of that turn binds the generation's root-owned directory whole at `/tmp/brain-worktrees`, inside the turn's own `/tmp` (`// Managed worktrees (#2430): a journaled turn's workers bind one empty generation.`, `packages/ui-server/src/ws/run-session.ts:570-582`; -`// Managed worktrees (#2430): the whole access generation`, `packages/ui-sdk/src/server/worker-launcher.ts:853-864`). +`// Managed worktrees (#2430): the whole access generation`, `packages/ui-sdk/src/server/worker-launcher.ts:862-873`). A granted worktree appears there as `/tmp/brain-worktrees//` on the worker's next path lookup; the worker cannot create entries beside it, and a restricted worker never binds a generation. Nothing returns a host path to the @@ -212,7 +212,7 @@ nothing. **Shared source is read through views.** Each such turn's workers bind the public view and their principal's private view whole and read-only at `/tmp/brain-reference/public` and `/tmp/brain-reference/private` -(`// Shared reference source (#2432)`, `packages/ui-sdk/src/server/worker-launcher.ts:865-876`). +(`// Shared reference source (#2432)`, `packages/ui-sdk/src/server/worker-launcher.ts:874-885`). A view the domain has not published to yet is opened empty first, so the turn sees its own first acquisition (`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:741-753`). diff --git a/docs/decisions/policy-write-boundary.md b/docs/decisions/policy-write-boundary.md index cec19f1f42..07392791dc 100644 --- a/docs/decisions/policy-write-boundary.md +++ b/docs/decisions/policy-write-boundary.md @@ -497,13 +497,13 @@ sessions. before the runtime starts and read it after the worker is gone, while the tmpfs is reachable only inside the worker. The launcher does both from the host (`function* launchAgentWorkerSteps`, -`packages/ui-sdk/src/server/worker-launcher.ts:1326-1581`): +`packages/ui-sdk/src/server/worker-launcher.ts:1335-1590`): 1. It finds the sandbox's first process from the kernel's record of bubblewrap's only child, then opens the tmpfs root through `/proc//root` and keeps that directory descriptor (`function openPrivateState`, - `packages/ui-sdk/src/server/worker-launcher.ts:1100-1124`). bubblewrap's + `packages/ui-sdk/src/server/worker-launcher.ts:1109-1133`). bubblewrap's process exists before its mounts do, so the open is accepted only once the path is its own mount (a device other than its parent's), a tmpfs of exactly the allowance, and empty; until then it would name the host's diff --git a/docs/decisions/worker-writable-areas.md b/docs/decisions/worker-writable-areas.md index 118fd68354..8301dd2660 100644 --- a/docs/decisions/worker-writable-areas.md +++ b/docs/decisions/worker-writable-areas.md @@ -81,7 +81,7 @@ on the transcript persist path and is not part of this record. **One resolution, two consumers.** `prepareWorkerSandbox` resolves the areas and per-turn XDG layout once per worker -(`export function prepareWorkerSandbox`, `packages/ui-sdk/src/server/worker-launcher.ts:902-943`). +(`export function prepareWorkerSandbox`, `packages/ui-sdk/src/server/worker-launcher.ts:911-952`). The backend passes the result both to the launcher, which turns it into bubblewrap arguments, and to `workerSandboxNote`, which renders the agent's note (`export function workerSandboxNote`, `packages/ui-sdk/src/server/worker-sandbox.ts:592-657`). @@ -89,7 +89,7 @@ The launcher re-checks the resolved layout against the actual launch: the same brain and envelope, each writable area still a real directory at its own path in the brain. The backend selects runtime HOME separately. A mismatch refuses the launch instead of binding something the note does not -describe (`function sandboxMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:824-854`). +describe (`function sandboxMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:833-863`). A launch without a resolved layout keeps the 0.41 view: only the per-turn scratch is writable. @@ -153,7 +153,7 @@ through the roadblock path. This is a worker write boundary, not an immutable view: host-side changes to that directory remain visible. A backend may select a different runtime HOME as described below; it does not make the host home writable. `prepareWorkerSandbox` resolves this same XDG mode on every eligible host (`export function prepareWorkerSandbox`, -`packages/ui-sdk/src/server/worker-launcher.ts:902-943`). Host-backed overlay +`packages/ui-sdk/src/server/worker-launcher.ts:911-952`). Host-backed overlay uppers cannot live on the worker's private tmpfs; keeping them would leave an unbounded write area. Tools reading XDG config see the per-turn directory, while direct reads of real HOME retain the read-only host view. @@ -267,14 +267,14 @@ The `read_only_brain` code and its **Serving.** The file routes refuse any symlink at or below `.brain` for a scratch path, and a scratch listing omits links -(`const policy: ContainmentPolicy = isScratchPath(rel)`, `packages/ui-server/src/files/walker.ts:97-99`). +(`const policy: ContainmentPolicy = isScratchPath(rel)`, `packages/ui-server/src/files/walker.ts:96-98`). Elsewhere in the brain an in-brain link resolves as before. Those checks run before the open, so a file whose requested or resolved path lies in `.brain/scratch/` or `workspaces/` is then read once, from its resolved path, through descriptors that never follow a link (each directory from the brain root opened with `O_NOFOLLOW | O_DIRECTORY` through the previous one, the file with `O_NOFOLLOW`), and the route serves that snapshot; the size cap bounds it -(`export function readAnchoredSnapshot`, `packages/ui-server/src/files/walker.ts:116-152`). +(`export function readAnchoredSnapshot`, `packages/ui-server/src/files/walker.ts:115-151`). Core's prune reads every entry with `lstat`, and on Linux removes each file and emptied directory through its parent's descriptor in the same way (`function anchored`, `packages/core/src/lib/scratch.ts:517-547`), because a diff --git a/docs/hosting/agent-workers.md b/docs/hosting/agent-workers.md index 25f573a775..bfa8bb5ad4 100644 --- a/docs/hosting/agent-workers.md +++ b/docs/hosting/agent-workers.md @@ -91,7 +91,7 @@ owner-only `0700`/`0600` modes. Before mounting the proxy, the launcher checks canonical paths, server ownership, the expected helper group, exact modes and socket type. Missing entries, symlinks and widened permissions refuse before the payload starts (`if (input.egress)`, -`packages/ui-sdk/src/server/worker-launcher.ts:553-568`). This does not select +`packages/ui-sdk/src/server/worker-launcher.ts:556-571`). This does not select the ordinary inference route or enable the proxy by default. Native output stages use the existing manager's active stage identity. The diff --git a/docs/hosting/paid-cli-provider-qualification.md b/docs/hosting/paid-cli-provider-qualification.md index 03457678c2..8278505999 100644 --- a/docs/hosting/paid-cli-provider-qualification.md +++ b/docs/hosting/paid-cli-provider-qualification.md @@ -56,7 +56,7 @@ SDK conversion without adding a public embedding-provider seam. The image CLI preserves `bytes`, `costIsEstimate`, `costUsd`, `model`, `note`, `output`, `outputs`, `provider`, `reason` and `renamed` -(`const payload`, `packages/module-images/src/cli.ts:407-419`). Its help example +(`const payload`, `packages/module-images/src/cli.ts:408-420`). Its help example is abbreviated; it is not the complete machine contract. Internal image raw usage does not imply that this envelope exposes it. diff --git a/docs/integration-contract.md b/docs/integration-contract.md index 6ab59be06a..28eda3a530 100644 --- a/docs/integration-contract.md +++ b/docs/integration-contract.md @@ -20,6 +20,27 @@ same-commit update of the index or relevant authoritative component. How they ar The reasoning is in [decisions/contract-versioning.md](decisions/contract-versioning.md). +## Strictest path containment answers (breaking before 1.0, 0.45.0, #3422) + +`safeResolve` and `resolveWritable` from `@schlessera/brain/module` now return +`null` in these cases: + +- an absolute path, even inside the root; +- any `..` segment; +- `:` or `\` in a segment; +- a dangling symlink; +- a path any existing component of which leaves the root. + +The CLI is not affected for paths inside the brain. Before calling them, it +converts an absolute path argument inside the brain (`--out`, document paths +and the other CLI path flags) to a brain-relative path, through the additive +`brainRelativeArgument` export. An absolute argument outside the brain is still +refused, and so is one through a symlink that leaves it. The maintainer rulings +are recorded [on the issue](https://github.com/schlessera/brain-kit/issues/3422#issuecomment-6599244174) +and, for the CLI, [on the PR](https://github.com/schlessera/brain-kit/pull/3465#issuecomment-6602766385). See [the package API component](integration-contract/package-api.md#strictest-path-containment-answers-breaking-before-10-0450-3422). +This ships in the 0.45.0 minor with the `breaking` label and a changeset that +names the break. + ## Explicit local chat deletion (additive, #3230) An authenticated owner can delete its own chat's local history with diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index b3fc1c3de3..7f7731e1d1 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -437,6 +437,45 @@ process context. First-party modules import this entry and never `@schlessera/brain/queries`. The `/internal` entry keeps the same names for the first-party packages that still import them. + +**Breaking before 1.0: strictest path containment answers (0.45.0, #3422).** +`safeResolve(root, rel)` and `resolveWritable(root, rel)` take a path relative +to the brain root. They return its canonical path, or `null` for any of these: + +- an absolute `rel`, even one inside the root; +- a `..` segment, even one whose result would stay inside; +- `:` or `\` in a segment, or a NUL; +- a dangling symlink, wherever it points; +- a path whose existing components do not all stay inside, such as one that + leaves through one link and comes back through another; +- a root whose realpath fails. + +Before 0.45.0, core accepted an absolute path inside the root and a `..` that +stayed inside. It also followed a dangling link to an inside target and checked +only the final path. A caller holding an absolute path passes it relative to +the root's realpath. + +The CLI keeps accepting absolute path arguments inside the brain +([maintainer ruling](https://github.com/schlessera/brain-kit/pull/3465#issuecomment-6602766385)). +Before resolving one, it converts it with the new, additive +`brainRelativeArgument(root, arg): string`, also exported from +`@schlessera/brain/module` for module commands. An absolute argument lexically +under the root as given or under its realpath becomes repo-relative (`.` for +the root itself). Any other argument comes back unchanged, so `safeResolve` +still refuses an absolute path outside the brain and one with a `..` segment. +The converted path still goes through `safeResolve`, so an absolute path +through a symlink that leaves the brain is refused. The arguments it covers: + +- `brain read`, `archive` and `process` ``; +- `import --stamp`; +- `render` `` and `--out`; +- `eval --out`; +- `geo` track paths, `--compare`, `--along` and `map --out`; +- `okf export --out`; +- `image --out`, `--ref` and `--mask`; +- `diagram export|build` `` and `--out`; +- `travel photo --to`, and `travel route` `` and `--to`. + **Additive frozen configuration root (#2848).** `@schlessera/brain/module` exports `configurationRoot(root: string): string`. When `root` equals the trusted worker's `BRAIN_WORKER_DATA_ROOT` and `BRAIN_WORKER_CONFIG_ROOT` is @@ -1827,6 +1866,9 @@ unload a module or cancel running sessions. document paths are repo-relative (no absolute, `~`, `..`, or control characters) and resolved through a symlink-aware canonicalizer, so neither a symlinked directory nor a dangling symlink redirects a write out of the repo. + A CLI path argument may also be absolute: one inside the brain root is + converted to a repo-relative path first, and one outside it is refused + (0.45.0, #3422). - **Mutating commands require an initialized brain.** `add`, `import`, `index`, `archive`, `accept-mtime`, `process`, `maintain`, `sync`, `skills sync`, and `setup`, plus `okf export`, exit 1 when no `brain.config` is found rather than initializing a diff --git a/docs/modules.md b/docs/modules.md index b18b3e0437..30f4b37199 100644 --- a/docs/modules.md +++ b/docs/modules.md @@ -600,7 +600,7 @@ first-party modules do not use it either. | Need | `@schlessera/brain/module` exports | | --- | --- | | Read configuration from a worker's frozen view | `configurationRoot(root)`; other roots pass through unchanged | -| Keep a path inside the brain | `safeResolve`, `resolveWritable` | +| Keep a path inside the brain | `safeResolve`, `resolveWritable`: a path relative to the root, never absolute and without `..`; dangling and out-and-back links are refused ([0.45.0](integration-contract/package-api.md#strictest-path-containment-answers-breaking-before-10-0450-3422)). A path argument from the command line goes through `brainRelativeArgument(root, arg)` first, which makes an absolute path inside the brain brain-relative | | Write a document atomically | `writeFileSafely` (`replace: false` refuses an existing name with `WriteRefusedError`, `code: "EEXIST"`) | | Intermediate files that are never canonical | `SCRATCH_DIR`, `scratchName`, `writeScratchFile`, `assertScratchWritable`, `isInScratch`, `isWriteRefusal`, `pruneScratch` | | Rewrite a generated region, keeping the rest of the file | `splitFrontmatterBlock`, `rewriteGeneratedRegion`, `inertGeneratedText` | diff --git a/docs/plans/module-renderers.md b/docs/plans/module-renderers.md index 6ed484352b..ce8f6ac204 100644 --- a/docs/plans/module-renderers.md +++ b/docs/plans/module-renderers.md @@ -181,7 +181,7 @@ reach the app through `![](x.svg)`: - **An `.svg` file must open as an image.** Today it opens as source, because the byte sniff in `export function classifyKind`, - `packages/ui-server/src/files/walker.ts:303` classifies UTF-8 SVG as text. + `packages/ui-server/src/files/walker.ts:302` classifies UTF-8 SVG as text. - **SVG images must print light.** Measured: a host `@media print { :root { color-scheme: light } }` makes an `` SVG take its light palette. diff --git a/docs/plans/storage-accounting.md b/docs/plans/storage-accounting.md index 213e6d8076..dfac46edbf 100644 --- a/docs/plans/storage-accounting.md +++ b/docs/plans/storage-accounting.md @@ -69,7 +69,7 @@ Source anchors, checked against the reviewed commit: thinning (`thin`, `packages/core/src/lib/stats-history.ts:232-244`). - D: effective path/journal resolution (`createApp`, `packages/ui-server/src/app.ts:303-339`), WAL store (`createUiDb`, `packages/ui-server/src/db/client.ts:27-44`), and - private locations (`statePaths`, `packages/ui-server/src/brain/operational-state.ts:114-120`). + private locations (`statePaths`, `packages/ui-server/src/brain/operational-state.ts:113-119`). - E: live/archive paths (`transcriptPaths`, `packages/ui-backend-claude/src/transcript-archive.ts:31-40`). - F: session location (`piSessionDirectory`, `packages/ui-backend-pi/src/session-storage.ts:10-30`). - G: staging location (`shareStagingRoot`, `packages/ui-server/src/share/staging.ts:143-145`) diff --git a/packages/core/src/cli/commands/archive.ts b/packages/core/src/cli/commands/archive.ts index 2bfd1ac418..30c8eb8ad2 100644 --- a/packages/core/src/cli/commands/archive.ts +++ b/packages/core/src/cli/commands/archive.ts @@ -1,6 +1,7 @@ import type { Database } from "bun:sqlite"; import { archiveDocument } from "../../lib/archiver.js"; +import { brainRelativeArgument } from "../../lib/safe-path.js"; import { indexAll } from "../../lib/indexer.js"; import type { CoreCommand } from "../types.js"; import { emit, embeddingDims, parseArgs, UsageError } from "../io.js"; @@ -14,7 +15,7 @@ export const archiveCommand: CoreCommand = { helpBlock: HELP, async run(args, cli) { const { args: pos, flags } = parseArgs(args); - const relPath = pos[0]; + const relPath = pos[0] && brainRelativeArgument(cli.brain.root, pos[0]); if (!relPath) { throw new UsageError("Usage: brain archive [--dry-run]"); } diff --git a/packages/core/src/cli/commands/eval.ts b/packages/core/src/cli/commands/eval.ts index b5b1b674fc..6daf1104f7 100644 --- a/packages/core/src/cli/commands/eval.ts +++ b/packages/core/src/cli/commands/eval.ts @@ -36,7 +36,7 @@ import type { ScoreRow, SetHeader, } from "../../lib/retrieval-eval.js"; -import { resolveWritable, safeResolve, writeFileSafely } from "../../lib/safe-path.js"; +import { brainRelativeArgument, resolveWritable, safeResolve, writeFileSafely } from "../../lib/safe-path.js"; import { isInScratch, isWriteRefusal, writeScratchFile } from "../../lib/scratch.js"; import { hybridSearch, type SearchDeps } from "../../lib/search-engine.js"; import type { EmbeddingProvider } from "../../lib/seams.js"; @@ -631,7 +631,7 @@ async function runEval(args: string[], cli: CliContext): Promise { if (flags.lint === true) return lintSet(cli.json, root, setPath, redact); // Everything the CLI writes stays inside the brain (integration contract, // "Containment"): checked before any search runs, and again at the write. - const outRel = typeof flags.out === "string" ? flags.out : undefined; + const outRel = typeof flags.out === "string" ? brainRelativeArgument(root, flags.out) : undefined; if (outRel !== undefined && !resolveWritable(root, outRel)) { throw new UsageError(`Output path is not inside the brain: ${outRel}`); } diff --git a/packages/core/src/cli/commands/geo.ts b/packages/core/src/cli/commands/geo.ts index 1eabc3f064..fcbfe9b815 100644 --- a/packages/core/src/cli/commands/geo.ts +++ b/packages/core/src/cli/commands/geo.ts @@ -6,7 +6,7 @@ import { nearestTrackPoint, parseTrackGpx, routePoint, summarizeTrack, trackCove import { GeoClient, type GeoResult, type GeocodeCandidate, type PoiResult, type RoutingResult, type StaticMapInput, type StaticMapPin, type StaticMapResult } from "@schlessera/brain-geo/server"; import { resolveGeoConfig } from "../../lib/geo-config.js"; -import { safeResolve, resolveWritable, writeFileSafely } from "../../lib/safe-path.js"; +import { brainRelativeArgument, safeResolve, resolveWritable, writeFileSafely } from "../../lib/safe-path.js"; import { assertScratchWritable, isInScratch, isWriteRefusal, pruneScratch, writeScratchFile } from "../../lib/scratch.js"; import { parseArgs, UsageError, type Flags } from "../io.js"; import type { CliContext, CoreCommand } from "../types.js"; @@ -97,7 +97,7 @@ function usage(fn: () => T): T { try { return fn(); } catch (error) { throw new UsageError((error as Error).message); } } async function readTrack(root: string, path: string): Promise<{ track: ParsedTrack; summary: TrackSummary }> { - const absolute = safeResolve(root, path); + const absolute = safeResolve(root, brainRelativeArgument(root, path)); if (!absolute) throw new UsageError(`Track path must remain inside the brain: ${path}`); const file = Bun.file(absolute); if (!await file.exists()) throw new UsageError(`Track file does not exist: ${path}`); @@ -207,7 +207,7 @@ export const geoCommand: CoreCommand = { async function runMap(args: string[], argv: string[], flags: Flags, cli: CliContext, geo: GeoClient): Promise { if (cli.brain.configPath === null) throw new UsageError("Map refuses to write in an uninitialized directory; run brain init first."); - const root = realpathSync(cli.brain.root), out = option(flags, "out", true)!; + const root = realpathSync(cli.brain.root), out = brainRelativeArgument(cli.brain.root, option(flags, "out", true)!); if (extname(out).toLowerCase() !== ".png") throw new UsageError("Map --out must name a PNG file."); const absolute = resolveWritable(root, out); if (!absolute) throw new UsageError("Map output must remain inside the brain."); diff --git a/packages/core/src/cli/commands/import.ts b/packages/core/src/cli/commands/import.ts index a6f8bf8f55..ead82fde31 100644 --- a/packages/core/src/cli/commands/import.ts +++ b/packages/core/src/cli/commands/import.ts @@ -5,7 +5,7 @@ import { Glob } from "bun"; import { frontmatterBlock } from "@schlessera/brain-common/internal/frontmatter-block"; import { stringifyDocument } from "../../lib/frontmatter.js"; -import { safeResolve, writeFileSafely } from "../../lib/safe-path.js"; +import { brainRelativeArgument, safeResolve, writeFileSafely } from "../../lib/safe-path.js"; import type { CoreCommand } from "../types.js"; import { emit, parseArgs, UsageError } from "../io.js"; @@ -35,7 +35,7 @@ export const importCommand: CoreCommand = { throw new UsageError("Usage: brain import --stamp "); } - const base = safeResolve(cli.brain.root, dir); + const base = safeResolve(cli.brain.root, brainRelativeArgument(cli.brain.root, dir)); if (base === null) { throw new UsageError(`--stamp directory escapes the brain root: ${dir}`); } diff --git a/packages/core/src/cli/commands/okf.ts b/packages/core/src/cli/commands/okf.ts index bd211ab44a..716bbcccd5 100644 --- a/packages/core/src/cli/commands/okf.ts +++ b/packages/core/src/cli/commands/okf.ts @@ -8,6 +8,7 @@ import { type OkfExportReport, } from "../../lib/okf-exporter.js"; import type { CoreCommand } from "../types.js"; +import { brainRelativeArgument } from "../../lib/safe-path.js"; import { emit, parseArgs, UsageError } from "../io.js"; const HELP = `brain okf — export and validate Open Knowledge Format v0.1 bundles @@ -81,7 +82,7 @@ export const okfCommand: CoreCommand = { const report = await exportOkfBundle({ root: cli.brain.root, taxonomy: cli.brain.taxonomy, - outDir: typeof flags.out === "string" ? flags.out : undefined, + outDir: typeof flags.out === "string" ? brainRelativeArgument(cli.brain.root, flags.out) : undefined, include: repeatedValues(argv, "include"), exclude: repeatedValues(argv, "exclude"), copyAssets: flags["no-assets"] !== true, diff --git a/packages/core/src/cli/commands/process.ts b/packages/core/src/cli/commands/process.ts index d0e8e36a8c..9c0686d7ce 100644 --- a/packages/core/src/cli/commands/process.ts +++ b/packages/core/src/cli/commands/process.ts @@ -7,7 +7,7 @@ import { parseFrontmatter } from "@schlessera/brain-common/internal/frontmatter" import type { CompletionProvider } from "../../lib/seams.js"; import { hybridSearch, type SearchDeps } from "../../lib/search-engine.js"; -import { safeResolve } from "../../lib/safe-path.js"; +import { brainRelativeArgument, safeResolve } from "../../lib/safe-path.js"; import { openDatabase } from "../../lib/db.js"; import type { CliContext, CoreCommand } from "../types.js"; import type { SearchOptions } from "../../lib/types.js"; @@ -188,7 +188,7 @@ export const processCommand: CoreCommand = { return; } - const notePath = pos[0]; + const notePath = pos[0] && brainRelativeArgument(cli.brain.root, pos[0]); if (!notePath) { throw new UsageError("Usage: brain process [--keep-note] [--all]"); } diff --git a/packages/core/src/cli/commands/read.ts b/packages/core/src/cli/commands/read.ts index d5a2d6aadc..5d310f97ec 100644 --- a/packages/core/src/cli/commands/read.ts +++ b/packages/core/src/cli/commands/read.ts @@ -1,7 +1,7 @@ import { existsSync, readFileSync } from "fs"; import { readDocumentPart, SectionNotFoundError } from "../../lib/document-parts.js"; -import { safeResolve } from "../../lib/safe-path.js"; +import { brainRelativeArgument, safeResolve } from "../../lib/safe-path.js"; import type { CoreCommand } from "../types.js"; import { parseArgs, UsageError } from "../io.js"; @@ -23,7 +23,7 @@ export const readCommand: CoreCommand = { helpBlock: HELP, async run(args, cli) { const { args: pos, flags } = parseArgs(args); - const relPath = pos[0]; + const relPath = pos[0] && brainRelativeArgument(cli.brain.root, pos[0]); if (!relPath) { throw new UsageError("Usage: brain read "); } diff --git a/packages/core/src/cli/commands/render.ts b/packages/core/src/cli/commands/render.ts index d27b5d1fdc..c0864e2454 100644 --- a/packages/core/src/cli/commands/render.ts +++ b/packages/core/src/cli/commands/render.ts @@ -11,7 +11,7 @@ import { documentTitle, isFullDocument, prepareStaticDocument } from "@schlesser import { DOCUMENT_KINDS, readSkeleton, resolveKind } from "@schlessera/brain-render-template/kinds"; import { collectModuleRenderers } from "../../lib/module-renderers.js"; -import { resolveWritable, writeFileSafely } from "../../lib/safe-path.js"; +import { brainRelativeArgument, resolveWritable, writeFileSafely } from "../../lib/safe-path.js"; import { assertScratchWritable, isInScratch, @@ -195,7 +195,7 @@ function runReference(pos: string[], flags: Record, js export function validateRenderInput(args: string[], root: string): void { const { args: pos, flags } = parseArgs(args); if (flags.kind !== undefined || flags.blocks === true) return; - const input = pos[0]; + const input = pos[0] && brainRelativeArgument(root, pos[0]); if (!input) throw new UsageError("Usage: brain render [--format pdf|png|html] [--out ]"); if (input === "-") return; const abs = resolveWritable(root, input); @@ -213,7 +213,7 @@ export const renderCommand: CoreCommand = { return; } if (flags.scaffold === true) throw new UsageError("--scaffold needs --kind "); - const input = pos[0]; + const input = pos[0] && brainRelativeArgument(cli.brain.root, pos[0]); if (!input) { throw new UsageError("Usage: brain render [--format pdf|png|html] [--out ]"); } @@ -257,7 +257,7 @@ export const renderCommand: CoreCommand = { (fromStdin ? undefined : sourceLabel); // --- resolve the output path - const outFlag = typeof flags.out === "string" ? flags.out : undefined; + const outFlag = typeof flags.out === "string" ? brainRelativeArgument(root, flags.out) : undefined; if (outFlag && flags.scratch === true) { throw new UsageError("--out and --scratch are exclusive"); } diff --git a/packages/core/src/lib/module-settings.ts b/packages/core/src/lib/module-settings.ts index c8151e362c..d7b397d31e 100644 --- a/packages/core/src/lib/module-settings.ts +++ b/packages/core/src/lib/module-settings.ts @@ -7,7 +7,7 @@ import type { LoadedModule } from "./module-types.js"; import type { ModuleSettingsMigrationPlan } from "./module-settings-types.js"; import { isRecord, mergeModuleSettings, moduleSettingsPath, readModuleSettings } from "./module-settings-source.js"; import { equalSettings, rewriteSettingsJson } from "./module-settings-json.js"; -import { safeResolve, writeFileSafely } from "./safe-path.js"; +import { safeResolve, safeResolveHeld, writeFileSafely } from "./safe-path.js"; import { git, gitPath } from "./sync/git.js"; export class ModuleSettingsError extends Error { @@ -121,7 +121,7 @@ function commitChanges(brain: BrainContext, name: string, changes: Array<{ path: if (git(brain.root, ["rev-parse", "--verify", "HEAD"]).code) throw new ModuleSettingsError("Commit the initial brain before saving module settings", 422); const paths = actual.map((c) => relative(safeResolve(brain.root, ".")!, c.path)); for (const change of actual) { - if (safeResolve(brain.root, change.path) !== change.path || lstatSync(change.path, { throwIfNoEntry: false })?.isSymbolicLink()) throw new ModuleSettingsError("A settings target is unsafe; no changes made", 422); + if (safeResolveHeld(brain.root, change.path) !== change.path || lstatSync(change.path, { throwIfNoEntry: false })?.isSymbolicLink()) throw new ModuleSettingsError("A settings target is unsafe; no changes made", 422); const present = existsSync(change.path) ? readFileSync(change.path, "utf8") : null; if (present !== change.before) throw new ModuleSettingsError("Settings changed; review the saved values", 409); } diff --git a/packages/core/src/lib/module-toggle.ts b/packages/core/src/lib/module-toggle.ts index 104fc2198f..f4647292a8 100644 --- a/packages/core/src/lib/module-toggle.ts +++ b/packages/core/src/lib/module-toggle.ts @@ -6,7 +6,7 @@ import { planModuleFlag } from "./module-config-edit.js"; import { planModuleInstructions } from "./module-instructions.js"; import { discoverSkills } from "./skills/discover.js"; import { syncSkills } from "./skills/sync.js"; -import { safeResolve, writeFileSafely } from "./safe-path.js"; +import { safeResolveHeld, writeFileSafely } from "./safe-path.js"; import type { LoadedModule } from "./module-types.js"; import { readGeneratedRegion } from "./generated-regions.js"; @@ -25,7 +25,7 @@ export function toggleModule(cli: CliContext, name: string, enabled: boolean): { } const state = enabled ? "active" : "dormant"; const modules: LoadedModule[] = brain.modules.map((m) => m === mod ? { ...m, state } : m); - const path = safeResolve(brain.root, brain.configPath); + const path = safeResolveHeld(brain.root, brain.configPath); if (!path) throw new UsageError("Config resolves outside the brain root; no changes made"); const original = readFileSync(path, "utf8"); // All source, ownership, discovery and emitter checks precede every write. diff --git a/packages/core/src/lib/safe-path.ts b/packages/core/src/lib/safe-path.ts index 27e162362b..d316febefe 100644 --- a/packages/core/src/lib/safe-path.ts +++ b/packages/core/src/lib/safe-path.ts @@ -2,27 +2,93 @@ import { randomBytes } from "crypto"; import { resolveContainedSync, type ContainmentPolicy } from "@schlessera/brain-common/internal/safe-path"; import { closeSync, fchmodSync, linkSync, lstatSync, mkdirSync, openSync, realpathSync, renameSync, rmSync, writeSync } from "fs"; import type { Stats } from "fs"; -import { basename, dirname, join } from "path"; +import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "path"; -const CORE_CONTAINMENT: ContainmentPolicy = { missingRoot: "refuse", danglingLinks: "follow", components: "final" }; +const CORE_CONTAINMENT: ContainmentPolicy = { missingRoot: "refuse", danglingLinks: "refuse", components: "every" }; /** - * Resolve a relative path and verify it stays inside `root`, following + * Whether a request is refused before it is resolved: anything but a string, + * an absolute path, and a segment that is `..` or holds `:` or `\\` (#3422). + * A NUL is refused by the shared resolver. + */ +function refusedRequest(relPath: string): boolean { + if (typeof relPath !== "string") return true; + if (relPath.startsWith("/") || relPath.startsWith("\\")) return true; + return relPath.split("/").some((segment) => segment === ".." || segment.includes(":") || segment.includes("\\")); +} + +/** + * Resolve a repo-relative path and verify it stays inside `root`, following * symlinks (realpath) so a symlink inside the repo can't escape it. - * Returns the canonical absolute path, or null if the path escapes (or the - * root itself does not exist). + * Returns the canonical absolute path, or null if the path is refused, + * escapes, or the root itself does not exist. * * core's row of the shared resolver (`@schlessera/brain-common/internal/safe-path`, - * #2506): synchronous, `null` for every refusal, an absolute path accepted - * when it lies inside the root, `..` accepted while the result stays inside, - * a dangling link followed to a target that must stay inside, and only the - * final path checked, not each component on the way. + * #2506), with the strictest answer in every row since #3422: synchronous, + * `null` for every refusal; an absolute request is refused even inside the + * root, and so is any `..` segment, even one whose result would stay inside, + * and `:` or `\\` in a segment; a dangling link is refused wherever it points; + * and every existing component on the way must stay inside, not only the + * final path. A caller holding an absolute path passes it relative to the + * root (`relative(root, abs)`), which a path outside the root turns into a + * refused `..`. */ export function safeResolve(root: string, relPath: string): string | null { + if (refusedRequest(relPath)) return null; const contained = resolveContainedSync(root, relPath, CORE_CONTAINMENT); return contained.ok ? contained.canonical : null; } +/** + * Re-check a path the caller already holds as absolute: a canonical answer + * `safeResolve` gave earlier, or a file core located itself (the brain's + * config). It is `safeResolve` of the same path taken relative to the root's + * realpath, or to the root as given, whichever holds it lexically; a path + * under neither is refused. Not for requests: a request is relative, and + * `safeResolve` refuses an absolute one (#3422). + */ +export function safeResolveHeld(root: string, path: string): string | null { + if (typeof path !== "string" || !isAbsolute(path)) return null; + const canonicalRoot = safeResolve(root, "."); + if (!canonicalRoot) return null; + for (const base of [canonicalRoot, resolve(root)]) { + const rel = relative(base, path); + if (rel === "" || (!isAbsolute(rel) && rel.split(sep)[0] !== "..")) return safeResolve(root, rel || "."); + } + return null; +} + +/** + * A CLI path argument as the request `safeResolve` takes (#3422). An absolute + * argument lexically inside the brain (under the root as given or under its + * realpath) becomes brain-relative, `.` for the root itself. Anything else is + * returned unchanged, so the resolver gives its own answer: a relative + * argument is resolved as before, and an absolute one outside the brain, or + * one with a `..` segment, stays absolute and is refused. Only the spelling + * changes here: the relative result still goes through `safeResolve`, so a + * symlink on the way that leaves the brain is refused there. + * + * Every CLI argument that names a brain path goes through this before it + * reaches `safeResolve` or `resolveWritable`. Requests from anywhere else (MCP + * tools, settings, files) do not: they are repo-relative by contract. + */ +export function brainRelativeArgument(root: string, arg: string): string { + if (typeof arg !== "string" || !isAbsolute(arg)) return arg; + if (arg.split(/[\\/]/).includes("..")) return arg; + const bases = [resolve(root)]; + try { + bases.push(realpathSync(root)); + } catch { + // A root that does not resolve is refused by the resolver anyway. + } + for (const base of bases) { + const rel = relative(base, arg); + if (rel === "") return "."; + if (!isAbsolute(rel) && rel.split(sep)[0] !== "..") return rel.split(sep).join("/"); + } + return arg; +} + /** * Resolve a path the caller may read or write: inside the brain root only. * @@ -33,8 +99,8 @@ export function safeResolve(root: string, relPath: string): string | null { * what lands there, and gitignored and pruned, so it is never canonical. A * write into it goes through `ensureScratch`. */ -export function resolveWritable(root: string, relOrAbs: string): string | null { - return safeResolve(root, relOrAbs); +export function resolveWritable(root: string, relPath: string): string | null { + return safeResolve(root, relPath); } /** diff --git a/packages/core/src/module.ts b/packages/core/src/module.ts index 211d8a8d05..4fd703778f 100644 --- a/packages/core/src/module.ts +++ b/packages/core/src/module.ts @@ -17,7 +17,7 @@ export { configurationRoot } from "./lib/config.js"; // Path containment and atomic writes -export { safeResolve, resolveWritable, writeFileSafely, WriteRefusedError } from "./lib/safe-path.js"; +export { safeResolve, resolveWritable, brainRelativeArgument, writeFileSafely, WriteRefusedError } from "./lib/safe-path.js"; export type { WriteFileSafelyOptions } from "./lib/safe-path.js"; // The scratch area (.brain/scratch) diff --git a/packages/core/tests/cli-path-arguments.test.ts b/packages/core/tests/cli-path-arguments.test.ts new file mode 100644 index 0000000000..684dd74be4 --- /dev/null +++ b/packages/core/tests/cli-path-arguments.test.ts @@ -0,0 +1,87 @@ +/** + * CLI path arguments (#3422, maintainer ruling of 2026-11-03): an absolute + * argument inside the brain is converted to a brain-relative path before it + * reaches `safeResolve`, which itself stays strict. An absolute argument + * outside the brain is still refused, and so is one that only reaches the + * outside through a symlink inside the brain. `brain eval --out` and + * `brain image --out` carry the same rows in their own suites. + */ + +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { existsSync, mkdtempSync, symlinkSync, writeFileSync } from "fs"; +import { tmpdir } from "os"; +import { join } from "path"; + +import { cleanup, makeTempBrain, runCli } from "./cli-harness"; + +let root: string; +let outside: string; + +beforeAll(() => { + root = makeTempBrain(); + outside = mkdtempSync(join(tmpdir(), "brain-cli-path-outside-")); + writeFileSync(join(outside, "secret.md"), "---\ntitle: Secret\ntype: note\n---\n\nOutside the brain.\n"); + symlinkSync(outside, join(root, "notes", "link-out")); +}); + +afterAll(() => { + cleanup(root); + cleanup(outside); +}); + +describe("brain read ", () => { + test("an absolute path inside the brain is read", async () => { + const { code, stdout } = await runCli(root, ["read", join(root, "health", "knee-injury.md")]); + expect(code).toBe(0); + expect(stdout).toContain("Left Knee"); + }); + + test("an absolute path outside the brain is refused", async () => { + const { code, stdout, stderr } = await runCli(root, ["read", join(outside, "secret.md")]); + expect(code).not.toBe(0); + expect(stdout).not.toContain("Outside the brain"); + expect(stderr).toContain("File not found"); + }); + + test("an absolute path through a symlink that leaves the brain is refused", async () => { + const { code, stdout, stderr } = await runCli(root, ["read", join(root, "notes", "link-out", "secret.md")]); + expect(code).not.toBe(0); + expect(stdout).not.toContain("Outside the brain"); + expect(stderr).toContain("File not found"); + }); +}); + +describe("brain archive ", () => { + test("an absolute path inside the brain is archived, reported brain-relative", async () => { + const { code, stdout } = await runCli(root, ["archive", join(root, "notes", "loose-idea.md"), "--dry-run", "--json"]); + expect(code).toBe(0); + expect(JSON.parse(stdout).path).toBe("notes/loose-idea.md"); + }); + + test("an absolute path outside the brain, or through a link out of it, is refused", async () => { + for (const path of [join(outside, "secret.md"), join(root, "notes", "link-out", "secret.md")]) { + const { code, stderr } = await runCli(root, ["archive", path, "--dry-run", "--json"]); + expect(code).not.toBe(0); + expect(stderr).toContain("escapes the brain root"); + } + }); +}); + +describe("brain okf export --out ", () => { + test("an absolute directory inside the brain passes containment and is named brain-relative", async () => { + const { stderr } = await runCli(root, ["okf", "export", "--out", join(root, "okf-abs"), "--json"]); + // The fixture does not exclude this directory from indexing, so the export + // stops at that later check, which names the converted relative path. + expect(stderr).not.toContain("escapes the brain root"); + expect(stderr).toContain("okf-abs."); + }); + + test("an absolute directory outside the brain, or through a link out of it, is refused", async () => { + for (const out of [join(outside, "okf"), join(root, "notes", "link-out", "okf")]) { + const { code, stderr } = await runCli(root, ["okf", "export", "--out", out, "--json"]); + expect(code).not.toBe(0); + expect(stderr).toContain("escapes the brain root"); + expect(existsSync(join(outside, "okf"))).toBe(false); + } + }); +}); diff --git a/packages/core/tests/containment-rows.test.ts b/packages/core/tests/containment-rows.test.ts index df986182a6..c36ffd9054 100644 --- a/packages/core/tests/containment-rows.test.ts +++ b/packages/core/tests/containment-rows.test.ts @@ -1,11 +1,10 @@ /** * core's row of the resolver matrix (#2506): `safeResolve(root, rel)` is - * synchronous, returns the canonical path or `null`, accepts an absolute path - * that lies inside the root, accepts `..` while the result stays inside, - * follows a dangling link whose target stays inside, and refuses everything - * when the root's realpath fails. Written against the copy core carried - * before the shared `@schlessera/brain-common/internal/safe-path`, and kept - * unchanged across the move. + * synchronous and returns the canonical path or `null`. Since #3422 it gives + * the strictest answer in every row: it refuses an absolute request even + * inside the root, any `..` segment, `:` or `\\` in a segment, a dangling + * link wherever it points, a path that leaves through one link and comes back + * through another, and everything when the root's realpath fails. */ import { afterAll, describe, expect, test } from "bun:test"; import { mkdirSync, mkdtempSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync } from "fs"; @@ -13,7 +12,7 @@ import { tmpdir } from "os"; import { join, relative } from "path"; import { SCRATCH_DIR } from "../src/lib/scratch"; -import { safeResolve } from "../src/lib/safe-path"; +import { brainRelativeArgument, safeResolve, safeResolveHeld } from "../src/lib/safe-path"; const base = realpathSync(mkdtempSync(join(tmpdir(), "brain-kit-containment-rows-"))); afterAll(() => rmSync(base, { recursive: true, force: true })); @@ -55,17 +54,21 @@ describe("core safeResolve(root, rel): its resolver row", () => { ["notes//a.md", "brain/notes/a.md"], ["notes/a.md/", "brain/notes/a.md"], ["file.md/x", "brain/file.md/x"], - // `..` is accepted while the result stays inside. - ["notes/../notes/a.md", "brain/notes/a.md"], + // `..` is refused even when the result stays inside (#3422). + ["notes/../notes/a.md", "refused"], + ["notes/sub/..", "refused"], ["notes/../../x", "refused"], // Sibling prefix: `brain-other` starts with `brain`. ["../brain-other/secret.md", "refused"], - // Absolute: accepted only inside the root. - [join(root, "notes/a.md"), "brain/notes/a.md"], + // Absolute: refused even inside the root (#3422). + [join(root, "notes/a.md"), "refused"], + [root, "refused"], ["/etc/passwd", "refused"], - // Windows syntax is not checked. - ["a:b", "brain/a:b"], - ["a\\b", "brain/a\\b"], + // Windows syntax is refused in any segment (#3422). + ["a:b", "refused"], + ["notes/a:b.md", "refused"], + ["a\\b", "refused"], + ["\\notes", "refused"], ["a\0b", "refused"], // Links: canonical answers, escapes refused, including for a file that // does not exist yet under a symlinked parent. @@ -73,18 +76,19 @@ describe("core safeResolve(root, rel): its resolver row", () => { ["link-in/new.md", "brain/notes/new.md"], ["link-out/secret.md", "refused"], ["link-out/new.md", "refused"], - // A dangling link is followed to its target, which must stay inside. - ["dangling-in", "brain/notes/missing"], - ["dangling-in/x", "brain/notes/missing/x"], + // A dangling link is refused wherever it points (#3422). + ["dangling-in", "refused"], + ["dangling-in/x", "refused"], ["dangling-out", "refused"], // A dangling chain is refused as soon as it leaves the root, even when it // ends inside. ["dangling-bounce", "refused"], ["cycle-a", "refused"], ["cycle-a/x", "refused"], - // Only the final path must be inside: out through one link and back - // through another is accepted. - ["bounce/back/a.md", "brain/notes/a.md"], + // Every component must stay inside, not only the final path: out through + // one link and back through another is refused (#3422). + ["bounce/back/a.md", "refused"], + ["bounce/back", "refused"], // Scratch is not special to the resolver. [".brain", "brain/.brain"], [".brain/scratch/s.txt", "brain/.brain/scratch/s.txt"], @@ -120,6 +124,66 @@ describe("core safeResolve(root, rel): its resolver row", () => { }); }); +describe("core safeResolveHeld(root, abs): re-checking a path the caller holds (#3422)", () => { + test("an absolute path under the root's realpath or the root as given gets safeResolve's answer", () => { + expect(answer(safeResolveHeld(root, join(root, "notes/a.md")))).toBe("brain/notes/a.md"); + expect(answer(safeResolveHeld(root, root))).toBe("brain"); + expect(answer(safeResolveHeld(join(base, "root-link"), join(base, "root-link/notes/a.md")))).toBe("brain/notes/a.md"); + expect(answer(safeResolveHeld(join(base, "root-link"), join(root, "notes/a.md")))).toBe("brain/notes/a.md"); + }); + + test("a relative path, a path outside the root and a path through a refused link are refused", () => { + expect(safeResolveHeld(root, "notes/a.md")).toBeNull(); + expect(safeResolveHeld(root, join(outside, "secret.md"))).toBeNull(); + expect(safeResolveHeld(root, `${root}-other/secret.md`)).toBeNull(); + expect(safeResolveHeld(root, join(root, "bounce/back/a.md"))).toBeNull(); + expect(safeResolveHeld(root, join(root, "dangling-in"))).toBeNull(); + expect(safeResolveHeld(join(base, "nope"), join(base, "nope/x"))).toBeNull(); + }); +}); + +describe("core brainRelativeArgument(root, arg): CLI path arguments (#3422 ruling of 2026-11-03)", () => { + /** The argument after conversion, then `safeResolve`'s answer to it. */ + const cli = (r: string, arg: string) => answer(safeResolve(r, brainRelativeArgument(r, arg))); + + test("an absolute argument inside the brain becomes brain-relative and is accepted", () => { + expect(brainRelativeArgument(root, join(root, "notes/a.md"))).toBe("notes/a.md"); + expect(brainRelativeArgument(root, root)).toBe("."); + expect(brainRelativeArgument(root, `${root}/`)).toBe("."); + expect(cli(root, join(root, "notes/a.md"))).toBe("brain/notes/a.md"); + expect(cli(root, join(root, "notes/new.md"))).toBe("brain/notes/new.md"); + // The root as given or its realpath: either spelling is inside the brain. + expect(cli(join(base, "root-link"), join(base, "root-link/notes/a.md"))).toBe("brain/notes/a.md"); + expect(cli(join(base, "root-link"), join(root, "notes/a.md"))).toBe("brain/notes/a.md"); + }); + + test("a relative argument is passed through unchanged", () => { + expect(brainRelativeArgument(root, "notes/a.md")).toBe("notes/a.md"); + expect(brainRelativeArgument(root, "notes/../x")).toBe("notes/../x"); + }); + + test("an absolute argument outside the brain stays absolute and is refused", () => { + for (const arg of [join(outside, "secret.md"), `${root}-other/secret.md`, "/", join(root, "notes/../../brain-other/secret.md")]) { + expect(brainRelativeArgument(root, arg)).toBe(arg); + expect(cli(root, arg)).toBe("refused"); + } + }); + + test("a `..` segment keeps the argument absolute, even when its result would stay inside", () => { + const arg = join(root, "notes") + "/../file.md"; + expect(brainRelativeArgument(root, arg)).toBe(arg); + expect(cli(root, arg)).toBe("refused"); + }); + + test("an absolute argument through a link that leaves the brain is refused", () => { + expect(brainRelativeArgument(root, join(root, "link-out/secret.md"))).toBe("link-out/secret.md"); + expect(cli(root, join(root, "link-out/secret.md"))).toBe("refused"); + expect(cli(root, join(root, "link-out/new.md"))).toBe("refused"); + expect(cli(root, join(root, "bounce/back/a.md"))).toBe("refused"); + expect(cli(root, join(root, "dangling-in"))).toBe("refused"); + }); +}); + test("core's scratch area is .brain/scratch", () => { expect(SCRATCH_DIR).toBe(".brain/scratch"); }); diff --git a/packages/core/tests/eval-cli.test.ts b/packages/core/tests/eval-cli.test.ts index 6a8463ef89..de66f85069 100644 --- a/packages/core/tests/eval-cli.test.ts +++ b/packages/core/tests/eval-cli.test.ts @@ -278,6 +278,14 @@ describe("--out stays inside the brain", () => { expect(existsSync(join(outside, "through-dir.json"))).toBe(false); }); + test("an absolute path through a symlinked directory that leaves the brain is refused (#3422)", async () => { + symlinkSync(outside, join(root, "evals", "abs-linked-dir")); + const { code, stderr } = await refusedOut(join(root, "evals", "abs-linked-dir", "through-abs.json")); + expect(code).toBe(2); + expect(stderr).toContain("Output path is not inside the brain"); + expect(existsSync(join(outside, "through-abs.json"))).toBe(false); + }); + test("a symlinked file inside the brain does not redirect the write", async () => { const target = join(outside, "through-file.json"); writeFileSync(target, "untouched"); diff --git a/packages/core/tests/safe-path.test.ts b/packages/core/tests/safe-path.test.ts index ba31bb76cc..b8a436078d 100644 --- a/packages/core/tests/safe-path.test.ts +++ b/packages/core/tests/safe-path.test.ts @@ -94,10 +94,10 @@ describe("safeResolve — dangling and cyclic symlinks", () => { expect(safeResolve(root, "sneakydir/new.md")).toBeNull(); }); - test("accepts a dangling symlink whose target stays inside the root", () => { + test("refuses a dangling symlink even when its target stays inside the root (#3422)", () => { const root = makeRoot(); symlinkSync(join(root, "not-yet.md"), join(root, "link.md")); - expect(safeResolve(root, "link.md")).toBe(join(realpathSync(root), "not-yet.md")); + expect(safeResolve(root, "link.md")).toBeNull(); }); test("rejects a dangling symlink cycle instead of looping", () => { diff --git a/packages/module-diagrams/src/export-cli.ts b/packages/module-diagrams/src/export-cli.ts index 7d50a7cfbc..1861b13ae0 100644 --- a/packages/module-diagrams/src/export-cli.ts +++ b/packages/module-diagrams/src/export-cli.ts @@ -1,6 +1,6 @@ import { existsSync,lstatSync } from "node:fs"; import { basename,dirname,extname,join,relative } from "node:path"; -import { markdownFences,resolveWritable,writeFileSafely,renderHtmlArtifact,SCRATCH_DIR,scratchName,assertScratchWritable,writeScratchFile,isInScratch } from "@schlessera/brain/module"; +import { brainRelativeArgument,markdownFences,resolveWritable,writeFileSafely,renderHtmlArtifact,SCRATCH_DIR,scratchName,assertScratchWritable,writeScratchFile,isInScratch } from "@schlessera/brain/module"; import {readRegularText} from "./regular-text.js"; import { parseDiagram } from "./svg-model.js"; import { embedDiagramFonts } from "./fonts.js"; @@ -15,12 +15,12 @@ const themes=new Set(["light","dark","print"]),formats=new Set(["svg","png","pdf const finding=(code:string,path:string,error:unknown):ArtifactFinding=>({code,path,message:error instanceof Error?error.message:String(error)}); /** Bounded UTF-8 input, before a complete allocation, for files and stdin. */ export async function readDiagramInput(root:string,input:string):Promise<{source:string;path:string;absolute:string|null}>{ - const absolute=input==="-"?null:resolveWritable(root,input);if(input!=="-"&&!absolute)throw Error("Input path must remain inside the brain");if(absolute&&!lstatSync(absolute).isFile())throw Error("Input must be a regular file"); + const absolute=input==="-"?null:resolveWritable(root,brainRelativeArgument(root,input));if(input!=="-"&&!absolute)throw Error("Input path must remain inside the brain");if(absolute&&!lstatSync(absolute).isFile())throw Error("Input must be a regular file"); const file=absolute?Bun.file(absolute):Bun.stdin,reader=file.stream().getReader(),chunks:Uint8Array[]=[];let size=0; try{for(;;){const item=await reader.read();if(item.done)break;size+=item.value.byteLength;if(size>1024*1024)throw Error("Diagram input exceeds the 1 MiB parse bound");chunks.push(item.value);}}finally{await reader.cancel();} return {source:new TextDecoder("utf-8",{fatal:true}).decode(Buffer.concat(chunks,size)),path:absolute?relative(root,absolute):"-",absolute}; } -function target(root:string,path:string):string {const parent=resolveWritable(root,dirname(path));if(!parent)throw Error("Output path must remain inside the brain");const result=join(parent,basename(path)),entry=lstatSync(result,{throwIfNoEntry:false});if(entry?.isSymbolicLink()||entry&&!entry.isFile())throw Error("Output must be an unlinked regular file name");if(!resolveWritable(root,result))throw Error("Output path must remain inside the brain");return result;} +function target(root:string,path:string):string {const parent=resolveWritable(root,dirname(path));if(!parent)throw Error("Output path must remain inside the brain");const result=join(parent,basename(path)),entry=lstatSync(result,{throwIfNoEntry:false});if(entry?.isSymbolicLink()||entry&&!entry.isFile())throw Error("Output must be an unlinked regular file name");if(resolveWritable(root,path)!==result)throw Error("Output path must remain inside the brain");return result;} function ownedTarget(root:string,path:string,id:string,document:string):boolean { const absolute=target(root,path);if(!existsSync(absolute))return false; const identity=derivedIdentity(readRegularText(absolute,8*1024*1024));if(!identity||identity.id!==id||identity.document!==document)throw Error(`Refusing to replace an unrelated SVG: ${path}`);return true; @@ -31,7 +31,7 @@ export async function exportDiagram(argv:string[],root:string):Promise --theme light|dark|print --format svg|png|pdf [--out path]");const theme=parsed.flags["--theme"]??"print",format=parsed.flags["--format"]??"svg";if(!themes.has(theme)||!formats.has(format))throw Error("Unknown diagram theme or artifact format");result.theme=theme as DiagramTheme;result.format=format as DiagramExportResult["format"]; const input=await readDiagramInput(root,parsed.position[0]!);result.input=input.path;const checked=checkDiagram(input.source);result.warnings=checked.warnings.map(w=>finding(w.code,w.path,w.message));if(!checked.valid){result.errors=checked.errors.map(e=>finding(e.code,e.path,e.message));return result;} - const svg=embedDiagramFonts(toFlatSvg(input.source,result.theme)),defaultName=input.path==="-"?join(SCRATCH_DIR,scratchName(`diagram-${theme}`,format)):input.path.replace(/(?:\.diagram\.ya?ml|\.[^./\\]+)$/i,"")+`.${theme}.${format}`,output=parsed.flags["--out"]??defaultName; + const svg=embedDiagramFonts(toFlatSvg(input.source,result.theme)),defaultName=input.path==="-"?join(SCRATCH_DIR,scratchName(`diagram-${theme}`,format)):input.path.replace(/(?:\.diagram\.ya?ml|\.[^./\\]+)$/i,"")+`.${theme}.${format}`,output=parsed.flags["--out"]===undefined?defaultName:brainRelativeArgument(root,parsed.flags["--out"]); if(extname(output).toLowerCase()!==`.${format}`)throw Error("Output extension must match the artifact format");const destination=target(root,output);if(destination===input.absolute)throw Error("The source cannot be replaced by its derived artifact");if(isInScratch(root,output))assertScratchWritable(root,destination); let data:string|Uint8Array=svg;if(format!=="svg"){const box=/viewBox="[-0-9.]+ [-0-9.]+ ([0-9.]+) ([0-9.]+)"/.exec(svg)!;const width=Number(box[1]),height=Number(box[2]);data=await renderHtmlArtifact({html:`${svg}`,format:format as "png"|"pdf",width:Math.max(320,width)});} result.output=write(root,output,data,input.path!=="-"||!!parsed.flags["--out"]);result.bytes=typeof data==="string"?Buffer.byteLength(data):data.byteLength;result.ok=true; diff --git a/packages/module-diagrams/tests/export.test.ts b/packages/module-diagrams/tests/export.test.ts index 8c34f3c076..cd213f0efc 100644 --- a/packages/module-diagrams/tests/export.test.ts +++ b/packages/module-diagrams/tests/export.test.ts @@ -78,3 +78,18 @@ test("FIFO and directory leaves cannot block diagram source or derived inspectio writeFileSync(join(root,"brain.config.ts"),'import {defineConfig} from "@schlessera/brain";export default defineConfig({});\n');expect((await boundedAudit(root)).map((issue:{category:string})=>issue.category)).toEqual(["diagram-source"]); }finally{cleanup(root);} }); + +test("absolute CLI paths inside the brain are converted to brain-relative; outside, or through a link out, they are refused (#3422)",async()=>{ + const root=makeTempBrain({empty:true}),outside=makeTempBrain({empty:true}); + try{ + configure(root);writeFileSync(join(root,"release.diagram.yaml"),source);symlinkSync(outside,join(root,"escape"),"dir"); + const inside=await command(root,["diagram","export",join(root,"release.diagram.yaml"),"--out",join(root,"release.abs.svg"),"--json"]); + expect(inside.code,inside.stderr).toBe(0);expect(inside.value.input).toBe("release.diagram.yaml");expect(inside.value.output).toBe("release.abs.svg"); + expect(existsSync(join(root,"release.abs.svg"))).toBe(true); + for(const out of [join(outside,"result.svg"),join(root,"escape","result.svg")]){ + const refused=await command(root,["diagram","export","release.diagram.yaml","--out",out,"--json"]); + expect(refused.code).toBe(1);expect(refused.value.output).toBeNull();expect(refused.value.errors[0].message).toContain("must remain inside the brain"); + } + expect(existsSync(join(outside,"result.svg"))).toBe(false); + }finally{cleanup(root);cleanup(outside);} +}); diff --git a/packages/module-images/src/cli.ts b/packages/module-images/src/cli.ts index 0bdd93ca7c..4717452c5a 100644 --- a/packages/module-images/src/cli.ts +++ b/packages/module-images/src/cli.ts @@ -8,6 +8,7 @@ import { isInScratch, isWriteRefusal, pruneScratch, + brainRelativeArgument, resolveWritable, safeResolve, scratchName, @@ -130,7 +131,7 @@ function slugify(prompt: string): string { } function loadImage(root: string, rel: string): ImageInput { - const abs = safeResolve(root, rel); + const abs = safeResolve(root, brainRelativeArgument(root, rel)); if (!abs) throw new Error(`Path escapes the brain root: ${rel}`); if (!existsSync(abs)) throw new Error(`No such file: ${rel}`); const ext = extname(abs).toLowerCase(); @@ -282,7 +283,7 @@ export const imageCommand: CommandModule = { // earlier draft must keep showing that draft. const toScratch = parsed.flags.scratch === true; const outRel = - (parsed.flags.out as string | undefined) ?? + (parsed.flags.out === undefined ? undefined : brainRelativeArgument(ctx.root, parsed.flags.out as string)) ?? (toScratch ? `${SCRATCH_DIR}/${scratchName(slugify(prompt), ext)}` : `${cfg.imagesDir}/${slugify(prompt)}-${new Date().toISOString().slice(0, 10)}.${ext}`); diff --git a/packages/module-images/tests/scratch.test.ts b/packages/module-images/tests/scratch.test.ts index db46d6eec4..a0415247bd 100644 --- a/packages/module-images/tests/scratch.test.ts +++ b/packages/module-images/tests/scratch.test.ts @@ -216,6 +216,20 @@ describe("brain image --scratch", () => { expect(readFileSync(join(root, "assets", "draft.png"), "utf8")).toBe(PNG_BYTES); }); + test("an absolute --out outside the brain, or through a link out of it, is refused and nothing lands outside (#3422)", async () => { + const outside = mkdtempSync(join(tmpdir(), "brain-outside-")); + mkdirSync(join(root, "assets"), { recursive: true }); + symlinkSync(outside, join(root, "assets", "link-out")); + stubProvider(); + for (const target of [join(outside, "draft.png"), join(root, "assets", "link-out", "draft.png")]) { + out.length = 0; + expect(await run(["a lighthouse", "--draft", "--out", target])).toBe(1); + expect(out.join("\n")).toContain("Output path is not inside the brain"); + } + expect(readdirSync(outside)).toEqual([]); + rmSync(outside, { recursive: true, force: true }); + }); + test("the ignore rule is checked again after the provider call, so a rule lost in flight refuses the write", async () => { ignoreScratch(root); // The rule disappears while the request is out: the pre-flight check diff --git a/packages/module-travel/src/cli.ts b/packages/module-travel/src/cli.ts index 59efdec92c..d92af04896 100644 --- a/packages/module-travel/src/cli.ts +++ b/packages/module-travel/src/cli.ts @@ -1,6 +1,6 @@ import { existsSync, lstatSync, readFileSync } from "fs"; import { join } from "path"; -import { safeResolve, writeFileSafely } from "@schlessera/brain/module"; +import { brainRelativeArgument, safeResolve, writeFileSafely } from "@schlessera/brain/module"; import type { CommandContext, CommandModule } from "@schlessera/brain"; import { readTravelCorpus } from "./content.js"; import type { TravelConfig } from "./module.js"; @@ -97,7 +97,7 @@ const command: CommandModule = { } if (!files.length || to === undefined) throw new Error("Usage: brain travel photo --to [--name ] [--date YYYY-MM-DD] [--force-date] [--json]"); const { preparePhotos } = await import("./photo.js"); - const photo = await preparePhotos(ctx.root, files, to, { name, date, forceDate }); + const photo = await preparePhotos(ctx.root, files, brainRelativeArgument(ctx.root, to), { name, date, forceDate }); if (ctx.json) console.log(JSON.stringify({ photo }, null, 2)); else { for (const file of photo.files) console.log(file.source + " → " + file.output + " (" + file.width + "×" + file.height + ")"); diff --git a/packages/module-travel/src/route.ts b/packages/module-travel/src/route.ts index c1b1b47cc6..cbba76035b 100644 --- a/packages/module-travel/src/route.ts +++ b/packages/module-travel/src/route.ts @@ -1,6 +1,6 @@ import { readFileSync, lstatSync } from "node:fs"; import { basename, extname, join, relative } from "node:path"; -import { safeResolve, writeFileSafely, WriteRefusedError } from "@schlessera/brain/module"; +import { brainRelativeArgument, safeResolve, writeFileSafely, WriteRefusedError } from "@schlessera/brain/module"; import { parseHtml, ScrapeClient } from "@schlessera/brain-scrape"; import { MAX_ROUTE_BYTES, parseGpx, quantizeRoute, routeMetrics, routePoint, trimRoute, writeGpx } from "./route-gpx.js"; import type { RouteGeometry, RouteMetrics } from "./route-gpx.js"; @@ -125,10 +125,11 @@ export async function importRoute(root: string, source: string, to: string, star if (metrics.recorded_duration_s === null) warnings.push("Incomplete or non-monotonic timestamps: recorded duration remains unknown."); if (startM || endM) warnings.push("Trim boundaries interpolate position, elevation and timestamps along each edge."); for (let suffix = 1; suffix <= 10_000; suffix++) { - const candidate = join(directory, `${stem}${suffix === 1 ? "" : `-${suffix}`}.gpx`); - if (lstatSync(candidate, { throwIfNoEntry: false })) continue; - const output = safeResolve(root, candidate); - if (!output || safeResolve(root, directory) !== directory) throw new Error("Route output directory changed or escapes the brain root."); + const file = `${stem}${suffix === 1 ? "" : `-${suffix}`}.gpx`; + if (lstatSync(join(directory, file), { throwIfNoEntry: false })) continue; + // Requests stay root-relative: `safeResolve` refuses an absolute path (#3422). + const output = safeResolve(root, join(to, file)); + if (!output || safeResolve(root, to) !== directory) throw new Error("Route output directory changed or escapes the brain root."); try { writeFileSafely(output, gpx, { replace: false }); } catch (error) { if (error instanceof WriteRefusedError && error.message.startsWith("EEXIST:")) continue; throw error; } return { source_kind: kind, gpx: relative(canonicalRoot, output).replaceAll("\\", "/"), ...metrics, trim: { start_m: startM, end_m: endM }, warnings, @@ -159,7 +160,7 @@ export async function runRoute(args: string[], root: string, json: boolean): Pro else source = arg; } if (!source || !to) throw new Error("Usage: brain travel route --to [--name