diff --git a/.changeset/frontmatter-block-once.md b/.changeset/frontmatter-block-once.md new file mode 100644 index 0000000000..453c062ef6 --- /dev/null +++ b/.changeset/frontmatter-block-once.md @@ -0,0 +1,8 @@ +--- +"@schlessera/brain-common": patch +"@schlessera/brain": patch +"@schlessera/brain-ui-sdk": patch +"@schlessera/brain-ui-react": patch +--- + +Where a document's frontmatter block starts and ends now has one implementation, `frontmatterBlock` in the new internal entry `@schlessera/brain-common/internal/frontmatter-block` (#2507). It follows the rule `parseFrontmatter` reads by. `frontmatterLength` moved there too, and core re-exports it. Five fixes follow. `brain validate` accepts a document whose frontmatter follows a byte order mark, and reports a `----` first line as missing frontmatter. `brain import --stamp` skips a file whose frontmatter follows a byte order mark instead of stamping a second block over it. The OKF bundle check sees frontmatter after a byte order mark. `brain hygiene` reads and keeps such a log file's frontmatter instead of rewriting it as body. `brain tags --apply` and the frontmatter key editor share one bounds and scalar reader. One rule is stricter than before: hygiene now refuses a log file whose closing fence has text after the dashes (`----`, `---x`). The public `splitFrontmatter` from `@schlessera/brain-ui-react` now reads a block that follows a byte order mark, has trailing whitespace after its opening fence, or is closed by a fence at the end of the file. It still returns an unclosed block as body. `bun run lint` refuses a frontmatter fence detected by hand in package source. The new entry, and its re-export from the ui-sdk's `internal/client`, are internal and carry no compatibility promise. diff --git a/.changeset/governance-policy-read-once.md b/.changeset/governance-policy-read-once.md new file mode 100644 index 0000000000..2e481599ab --- /dev/null +++ b/.changeset/governance-policy-read-once.md @@ -0,0 +1,7 @@ +--- +"@schlessera/brain-common": patch +"@schlessera/brain-ui-server": patch +"@schlessera/brain": patch +--- + +The governance policy file is read through one descriptor-anchored reader (#2508). `brain policy`, the indexer, `brain stats`, the hosted server's policy reader and its policy writer now share `openGovernancePolicyAnchored` and `verifyGovernancePolicyAnchored` in `@schlessera/brain-common/internal/governance-policy`, so a hardening fix reaches all of them. Each keeps the stricter rule of the two former copies. The writer no longer loads a file that grows past the 1 MiB bound after its size check, and it refuses a short read as a change. `checkGovernancePolicy` now refuses an ancestor directory replaced during the read on Linux as well, and reports an ancestor removed during the read as invalid rather than missing. The writer's review states and messages are unchanged. diff --git a/.changeset/safe-path-once.md b/.changeset/safe-path-once.md new file mode 100644 index 0000000000..b7ed39f57a --- /dev/null +++ b/.changeset/safe-path-once.md @@ -0,0 +1,8 @@ +--- +"@schlessera/brain-common": patch +"@schlessera/brain": patch +"@schlessera/brain-ui-sdk": patch +"@schlessera/brain-ui-server": patch +--- + +Symlink-safe path containment now has one implementation, in the new internal entry `@schlessera/brain-common/internal/safe-path` (#2506). It holds `isWithin`, the containment primitive whose equality, separator, trailing-separator and normalisation answers are explicit parameters, and one canonicalisation algorithm with a synchronous and an asynchronous variant. core's `safeResolve`, the SDK's `resolveInRepo` and the server's `safeResolve` are thin wrappers over it, and the scratch-directory copies read the shared `BRAIN_SCRATCH_DIR`. Each caller keeps its own answers, with two exceptions: the server's `safeResolve` now refuses a path through a symlink cycle, as core and the SDK already did, instead of answering a path that resolves nowhere; and the server's check that core's query entry lies inside its package no longer refuses a directory whose name starts with `..`. `safeResolve` and `SCRATCH_DIR` stay exported from `@schlessera/brain/module` with their signatures and answers unchanged. The new entry is internal and carries no compatibility promise. 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/common.txt b/api-report/common.txt index 7e55767c9d..65a6dd5f49 100644 --- a/api-report/common.txt +++ b/api-report/common.txt @@ -159,10 +159,16 @@ export "./internal/frontmatter" (./src/frontmatter-parse.ts) type ParsedFrontmatter parseFrontmatter +export "./internal/frontmatter-block" (./src/frontmatter-block.ts) + type FrontmatterBlock + frontmatterBlock + frontmatterLength + export "./internal/governance-policy" (./src/governance-policy.ts) APIFY_LIMIT_BOUNDS APIFY_MAX_ACTOR_GRANTS APIFY_MAX_RUN_USD + type AnchoredGovernancePolicy type ApifyLimits BUILTIN_GOVERNANCE_POLICY type EffectiveGovernancePolicy @@ -170,12 +176,17 @@ export "./internal/governance-policy" (./src/governance-policy.ts) GOVERNANCE_POLICY_PATH type GovernanceCommandRuleIndices type GovernancePolicyCheck + type GovernancePolicyDirectory type GovernancePolicyInput + GovernancePolicyReadError + type GovernancePolicyReadRefusal GovernancePolicySchema checkGovernancePolicy + openGovernancePolicyAnchored parseGovernancePolicy providerAllows resolveGovernancePolicy + verifyGovernancePolicyAnchored export "./internal/index-location" (./src/index-location.ts) EMBEDDING_LOCK_FAMILY @@ -215,6 +226,15 @@ export "./internal/provider-unavailable" (./src/provider-unavailable.ts) providerUnavailableNotice withheldKeys +export "./internal/safe-path" (./src/safe-path.ts) + type ContainedPath + type ContainmentPolicy + type ContainmentRefusal + type WithinRule + isWithin + resolveContained + resolveContainedSync + export "./internal/worker-areas" (./src/worker-areas.ts) BRAIN_SCRATCH_DIR BRAIN_WORKSPACES_DIR diff --git a/api-report/core.txt b/api-report/core.txt index f6430d3ce0..8dd87c5ed7 100644 --- a/api-report/core.txt +++ b/api-report/core.txt @@ -174,6 +174,7 @@ export "./module" (./src/module.ts) type WriteFileSafelyOptions WriteRefusedError assertScratchWritable + brainRelativeArgument buildTaxonomy configurationRoot geminiCompletions @@ -1449,6 +1450,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) @@ -1606,7 +1609,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/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index 13ca93155b..3ec96bb356 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -1333,6 +1333,7 @@ export "./internal" (./src/internal.ts) workerSandboxWarnings export "./internal/client" (./src/internal-client.ts) + type FrontmatterBlock type LinkEdit type ShareTargetError askUserFormPayload @@ -1345,6 +1346,7 @@ export "./internal/client" (./src/internal-client.ts) defaultAsrClientRegistry defaultToolRendererRegistry describeRetry + frontmatterBlock handleShareTargetRequest isShareTargetRequest pruneStoredShares diff --git a/docs/decisions/frontmatter-parsing.md b/docs/decisions/frontmatter-parsing.md index 410cd3cf75..db2380ab91 100644 --- a/docs/decisions/frontmatter-parsing.md +++ b/docs/decisions/frontmatter-parsing.md @@ -54,7 +54,7 @@ maintainer chose option B on #142 on 2026-09-28. - Rule 1: gray-matter may be loaded (`import`, `import type`, `export … from`, `import x = require()`, `require()`, `import()`, subpaths) only by the files in its `ALLOWED` list (`ALLOWED`, - `scripts/check-frontmatter-parse.ts:40-62`). + `scripts/check-frontmatter-parse.ts:50-72`). - Rule 2: inside those files, the default binding may only be called with an object literal where gray-matter takes its options, or named in a type. Aliases, re-exports, `matter.read`, `matter.cache` and variable options @@ -105,6 +105,44 @@ This repairs the documented data-only input guarantee. It changes no supported YAML meaning, envelope, approval authority, descriptor read, size limit or last-valid fallback. See the [file-layer contract](../integration-contract/frontmatter.md#file-layer-contracts). +## Where the block starts and ends (#2507, 2026-11-03) + +Finding the fences without parsing the YAML has one answer too: +`frontmatterBlock` (`frontmatterBlock`, +`packages/common/src/frontmatter-block.ts:42-55`), reached through +`@schlessera/brain-common/internal/frontmatter-block`. It returns the offsets +of the opening fence, the inner YAML lines and the end of the block, plus +whether a closing fence was found, by gray-matter's rule: an optional byte +order mark, `---` not followed by a fourth `-`, the first `\n---` after it, and +one line ending after that. It imports nothing, so ui-react reaches it through +ui-sdk's browser-safe `internal/client` entry. `frontmatterLength` moved with +it; core re-exports it. A table-driven test holds it to `parseFrontmatter` on a +byte order mark, CRLF, trailing whitespace after either fence, a closing fence +at the end of the file, `----`, a leading blank line, an unclosed block, an +empty block and a `...` line. + +Nine places had their own rule. Each now asks `frontmatterBlock`, and each +default is the parser's answer, except where a stricter answer protects a +write: + +| Site | Disagreed on | Rule now | +| --- | --- | --- | +| `brain validate` | BOM (reported `frontmatter-missing`); `----` counted as a fence | the parser's | +| `brain import --stamp` | BOM (stamped a second block over the first, which became body) | the parser's | +| OKF bundle check | BOM (rejected explicitly: a marked concept "missing frontmatter", a marked `index.md` block let through) | the parser's | +| generated regions | none in effect; its search ignored the BOM offset | the parser's, still refusing an unclosed block | +| `brain tags --apply` and the key editor | two `frontmatterBounds`/`readScalar` pairs; the tags copy searched back from the block's end and took the closing fence into the block when a `---` rule followed it | one pair, in `frontmatter-edit.ts`; an unclosed block has no bounds | +| hygiene log files | BOM (frontmatter read as body and rewritten) | the parser's opening; **stricter closing**: a block not closed by a `---` line with only whitespace after it is refused, including `----`, `---x` and `...` closers the parser would end at or run past, because hygiene rewrites the body | +| ui-react `splitFrontmatter` | BOM; a closing fence at the end of the file | the parser's, except that an unclosed block is shown as body rather than swallowed, so the viewer never hides text | +| ui-server policy review `split` | accepts a `...` closer | unchanged for now; open on #2507 | + +Rule 3 of the gate (`scanFences`, `scripts/check-frontmatter-parse.ts:222-252`) +refuses a hand-written detector in package source: a non-multiline regex +anchored at a leading `---` (a BOM before it included), `startsWith("---…")` +and `indexOf`/`lastIndexOf("\n---…")`. Files that emit or post-process a fence +they wrote, and the pending policy splitter, are listed in `FENCE_ALLOWED` +with a reason each. + ## Rejected alternatives - **Pass `{}` at every call site (O1).** This was already half-done, and the @@ -158,6 +196,9 @@ file is parsed once per run. - An edit to the helper is made once, in `packages/common`. - A new entry in `ALLOWED` needs a reason that says why the file cannot reach the cache. "It only parses once" is not one: the cache is process-wide. +- A new entry in `FENCE_ALLOWED` needs a reason that says why the file is not + reading an arbitrary document's fences: it emits them, or it post-processes + text it emitted. ## Superseded: a copy per parsing package diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 441e186476..3d0feac089 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -505,11 +505,11 @@ before application-lock admission, acquires its own complete native checkpoint asynchronously and runs a credential-free, read-only Git query. It releases that input after the worker drains, without creating or publishing a writable stage (`createScratchIgnoreQuery`, -`packages/ui-server/src/brain/scratch-mask-query.ts:7-43`). Exit 1 means the +`packages/ui-server/src/brain/scratch-mask-query.ts:8-44`). Exit 1 means the directory is not ignored. Launch failure, another exit or timeout means the rule could not be verified; the mask remains refused without forwarding worker stderr or claiming that the ignore file needs repair (`assertScratchMaskAsync`, -`packages/ui-sdk/src/server/bridge-tools/mask.ts:224-235`). +`packages/ui-sdk/src/server/bridge-tools/mask.ts:228-239`). **Credentials never reach a process that evaluates repository inputs.** A read-only host does not stop sandboxed code from stealing a credential it was @@ -1074,14 +1074,14 @@ is gone as well, and never enters another mount, so runtime state below against its own budget, and a turn that cannot reserve it is refused as `worker_state_busy` (docs/hosting/agent-workers.md). The `turn_temp` tool reports usage and purges paths through the same descriptor -(`export function purgeTurnTemp`, `packages/ui-sdk/src/server/worker-turn-temp.ts:450-458`). +(`export function purgeTurnTemp`, `packages/ui-sdk/src/server/worker-turn-temp.ts:451-459`). The restricted envelope gets the same sized `/tmp` and promotes nothing. After the worker exits, the backend rewrites the answer text the turn appended to its saved transcript, and only that text. It looks at Markdown link and image destinations and reference definitions outside code. A file is promoted once per turn however often it is linked, up to 128 MiB per file, 256 MiB and 64 files per turn -(`export function createTurnTempPromoter`, `packages/ui-sdk/src/server/worker-turn-temp.ts:124-135`). +(`export function createTurnTempPromoter`, `packages/ui-sdk/src/server/worker-turn-temp.ts:125-136`). The copy goes to `.brain/scratch/turns//` under a name the reader's file links accept, so the rewritten link is brain-relative and is pinned like any other scratch link. Each result reaches the server as a `promotion` or @@ -1104,10 +1104,10 @@ Live blocks still use streamed-text offsets; the client and server share the span rebasing function and discard ambiguous overlaps as plain Markdown. **Pinning.** A link into `.brain/scratch/` pins the target. Prune skips pinned -files (`export function pruneScratch`, `packages/core/src/lib/scratch.ts:641`). +files (`export function pruneScratch`, `packages/core/src/lib/scratch.ts:645`). A pin is released when every conversation that links the file is deleted or falls out of retention. If the scratch area still exceeds its size limit -(`SCRATCH_MAX_BYTES`, `scratch.ts:58`) after unpinned files are pruned, the +(`SCRATCH_MAX_BYTES`, `scratch.ts:62`) after unpinned files are pruned, the overage is reported. Pinned files are never deleted. A writer that prunes after writing into scratch also passes the paths it just produced, protected for that one call (`pinnedPaths`), so retained pins over the cap cannot make it @@ -1409,7 +1409,7 @@ external editor throughout a native tool's execution. The parent observes the worker's resolved mount sources, including strict startup copies and writable area aliases; it does not substitute newer canonical bytes for a frozen view (`createWorkerFileObserver`, -`packages/ui-sdk/src/server/worker-file-observer.ts:13`). A failed or changing +`packages/ui-sdk/src/server/worker-file-observer.ts:15`). A failed or changing read cannot establish a new version. Claude's native `file_unchanged` response also preserves the previous observation: it supplied no new bytes (`const finishNativeFile`, diff --git a/docs/decisions/hygiene-review.md b/docs/decisions/hygiene-review.md index d01f6341f2..62c2853cbc 100644 --- a/docs/decisions/hygiene-review.md +++ b/docs/decisions/hygiene-review.md @@ -43,8 +43,8 @@ or a snooze reset by an unrelated edit, makes the owner's decision temporary. Reuse the existing markdown log and deterministic CLI operations. A candidate already carries category, path and stable evidence (`HygieneCandidate`, -`packages/core/src/lib/hygiene.ts:68-84`), and its ID derives from those fields -(`hygieneId`, `packages/core/src/lib/hygiene.ts:181-184`). Those primitives do not +`packages/core/src/lib/hygiene.ts:69-85`), and its ID derives from those fields +(`hygieneId`, `packages/core/src/lib/hygiene.ts:182-185`). Those primitives do not by themselves supply validation-to-hygiene equivalence, priority selection or review dispositions. The CLI exposes reconciliation, listing and deterministic selection (`hygieneCommand`, `packages/core/src/cli/commands/hygiene.ts:250-252`). @@ -135,11 +135,11 @@ shapes are in [the integration contract](../integration-contract/package-api.md# **Equivalence map.** Each `brain validate` rule becomes a candidate with a category and ID evidence (`VALIDATION_JOIN`, -`packages/core/src/lib/hygiene.ts:199-212`). Validation gives the join a +`packages/core/src/lib/hygiene.ts:200-213`). Validation gives the join a structured detail, so the message is never read (`export interface ValidationDetail`, -`packages/core/src/lib/validate.ts:43-51`). Candidates are one finding exactly +`packages/core/src/lib/validate.ts:44-52`). Candidates are one finding exactly when category, path and evidence agree, and the join does not depend on their -order (`canonicalFindings`, `packages/core/src/lib/hygiene.ts:283-333`). +order (`canonicalFindings`, `packages/core/src/lib/hygiene.ts:284-334`). | Validation rule | Category | ID evidence | Joins | | --- | --- | --- | --- | @@ -161,7 +161,7 @@ a source states it; otherwise it stays unknown. **Evidence fingerprints.** A fingerprint is 12 hex digits of SHA-1 over the category and a hash of each field below (`FINGERPRINT_FIELDS`, -`packages/core/src/lib/hygiene.ts:246-259`). Line numbers, messages, other +`packages/core/src/lib/hygiene.ts:247-260`). Line numbers, messages, other document content and age are never in it. | Category | Fingerprint fields | diff --git a/docs/decisions/index-query-api.md b/docs/decisions/index-query-api.md index 7d08ffc6b2..0b17a82a87 100644 --- a/docs/decisions/index-query-api.md +++ b/docs/decisions/index-query-api.md @@ -118,7 +118,7 @@ neither justified a service or configurable query-provider seam. > **2026-10-05 — Implementation context (#697).** UI-server now declares the > optional peer and resolves the entry lazily, once per app -> (`createCoreQueryAccess`, `packages/ui-server/src/core-queries.ts:192-227`). The +> (`createCoreQueryAccess`, `packages/ui-server/src/core-queries.ts:193-228`). The > source-backed range is `>=0.40.0 <1.0.0`: the published 0.40.0 manifest is the > first to export `./queries`, its declarations name all nine operations and its > query source matches the source the server was migrated against; 0.39.0 has no diff --git a/docs/decisions/mechanical-hygiene.md b/docs/decisions/mechanical-hygiene.md index d4a2078330..6433db64bd 100644 --- a/docs/decisions/mechanical-hygiene.md +++ b/docs/decisions/mechanical-hygiene.md @@ -39,7 +39,7 @@ The prototype reuses table detection (`indexTableLag`, `packages/core/src/lib/hygiene.ts:577-619`), scalar table rendering (`renderRegistry`, `packages/core/src/lib/index-registry.ts:117-185`) and the surgical frontmatter editor (`editFrontmatter`, -`packages/core/src/lib/frontmatter-edit.ts:216-224`). It intentionally refuses +`packages/core/src/lib/frontmatter-edit.ts:232-240`). It intentionally refuses wiki links and an entire index containing an unsafe row. ## Held-out quality and reliability diff --git a/docs/decisions/module-instruction-ownership.md b/docs/decisions/module-instruction-ownership.md index f2c0fb82d7..1fd0f05545 100644 --- a/docs/decisions/module-instruction-ownership.md +++ b/docs/decisions/module-instruction-ownership.md @@ -30,7 +30,7 @@ The existing module mechanism builds contributions from validated config (`ModuleContribution`, `packages/core/src/lib/module-types.ts:147-175`). The generated-region helper replaces a whole named block and preserves bytes outside it (`replaceGeneratedRegion`, -`packages/core/src/lib/generated-regions.ts:99-120`). Neither a shared block +`packages/core/src/lib/generated-regions.ts:100-121`). Neither a shared block nor its heading establishes which module owns each paragraph. The CLI needs an authoritative source and explicit ownership to remove, regenerate and measure module instructions deterministically. diff --git a/docs/decisions/public-export-boundary.md b/docs/decisions/public-export-boundary.md index 09a16600ad..2f9f8d42d7 100644 --- a/docs/decisions/public-export-boundary.md +++ b/docs/decisions/public-export-boundary.md @@ -290,15 +290,17 @@ its watch implementation and CLI remain implementation details. An internal-only package (#1396): `@schlessera/brain-common` has no root entry. Its entries, `./internal/env`, `./internal/frontmatter` and `./internal/worker-areas`, `./internal/protected-paths`, -`./internal/governance-policy` and `./internal/claude-subscription`, follow -the internal-entry rule above. +`./internal/governance-policy`, `./internal/claude-subscription` and +`./internal/safe-path`, follow the internal-entry rule above. The policy helper (#1744) serves both core and the server without requiring the server’s optional core peer; it adds no supported extension interface. The first two replace byte-identical copies of `env-core.ts` and `frontmatter-parse.ts` that the packages carried; the third (#1693) holds the worker write-area rules that the ui-sdk's sandbox note and core's CLI refusal both state. The subscription billing guard (#2493) replaces the copies core's CLI runner and -the chat backend carried. A name a +the chat backend carried. Symlink-safe containment (#2506) replaces the +resolvers core, the ui-sdk and ui-server carried and their hand-written +containment predicates. A name a public entry re-exports from it, such as core's `DynamicEnvReadSpec` and `readEnvVar`, stays part of that package's supported surface and is recorded in that package's report. diff --git a/docs/decisions/reference-pool-accounting.md b/docs/decisions/reference-pool-accounting.md index 76858e1b86..25b09c9aed 100644 --- a/docs/decisions/reference-pool-accounting.md +++ b/docs/decisions/reference-pool-accounting.md @@ -8,7 +8,7 @@ actual allocated disk. That decision left the mechanism to implementation. This record names the mechanism, the primary sources it relies on and the native observations that qualified it. The pool is managed by the existing host-only native manager -(`createNativeReferencePool`, `packages/ui-sdk/src/server/native-reference-pool.ts:270-962`). +(`createNativeReferencePool`, `packages/ui-sdk/src/server/native-reference-pool.ts:272-964`). No consumer uses it yet. ## A separate volume, not another subvolume of the brain store @@ -224,7 +224,7 @@ directory its intent records. Sealing also makes the root's top directory `roots/` and `views/` join the mandatory worker masks. A worker sees reference source only through a view bound for it, and other domains' views stay invisible. `poolView` (#2432) opens a view's directory before its first -publication (`function viewOpen`, `packages/ui-sdk/src/server/native-reference-pool.ts:938-941`), +publication (`function viewOpen`, `packages/ui-sdk/src/server/native-reference-pool.ts:940-943`), so a worker that binds it at its start sees the domain's first publication on a later lookup ([agent tools](managed-worktrees.md#agent-tools)). diff --git a/docs/decisions/worker-writable-areas.md b/docs/decisions/worker-writable-areas.md index 407602e71e..a164f6e208 100644 --- a/docs/decisions/worker-writable-areas.md +++ b/docs/decisions/worker-writable-areas.md @@ -267,17 +267,17 @@ 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 scratchRequest`, `packages/ui-server/src/files/walker.ts:115`). +(`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:157-193`). +(`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:513-543`), because a +(`function anchored`, `packages/core/src/lib/scratch.ts:517-547`), because a hosted agent can swap a scratch directory for a link while the host prunes. ## Measurements diff --git a/docs/hosting/agent-workers.md b/docs/hosting/agent-workers.md index 025e07a9e0..cc5cece6f4 100644 --- a/docs/hosting/agent-workers.md +++ b/docs/hosting/agent-workers.md @@ -1288,7 +1288,7 @@ its working directory. No first-party code reads `.env` any other way. The launcher binds `/dev/null` over every present `.env*` name at the brain root, and over the file an `.env*` link leads to, after every other mount, so no later bind can restore it (`maintenanceEnvMasks`, -`packages/ui-sdk/src/server/maintenance-env-masks.ts:66-70`). The worker cannot +`packages/ui-sdk/src/server/maintenance-env-masks.ts:67-71`). The worker cannot open them: a read fails with `EACCES`, so Bun loads nothing and `cat .env` prints nothing. A new `.env*` name is a protected tier A path, so a turn cannot create one in the brain either. diff --git a/docs/hosting/paid-cli-provider-qualification.md b/docs/hosting/paid-cli-provider-qualification.md index 51b22af5d4..f14ae1b845 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/http-api-coverage.md b/docs/http-api-coverage.md index 8a92d10772..ca09fb8b82 100644 --- a/docs/http-api-coverage.md +++ b/docs/http-api-coverage.md @@ -238,10 +238,10 @@ cover start refusal, mid-turn partial work, overlapping observations and leases. **F — Content and byte ranges.** -- `an uncompressed, all-ASCII PDF is served as binary, not as its source` ([source](../packages/ui-server/tests/files-walker.test.ts)), (`an uncompressed, all-ASCII PDF is served as binary, not as its source`, `packages/ui-server/tests/files-walker.test.ts:299-305`) -- `rejects file_too_large` ([source](../packages/ui-server/tests/files-walker.test.ts)), (`rejects file_too_large`, `packages/ui-server/tests/files-walker.test.ts:324-329`) +- `an uncompressed, all-ASCII PDF is served as binary, not as its source` ([source](../packages/ui-server/tests/files-walker.test.ts)), (`an uncompressed, all-ASCII PDF is served as binary, not as its source`, `packages/ui-server/tests/files-walker.test.ts:310-316`) +- `rejects file_too_large` ([source](../packages/ui-server/tests/files-walker.test.ts)), (`rejects file_too_large`, `packages/ui-server/tests/files-walker.test.ts:335-340`) - `rejects symlink escape` ([source](../packages/ui-server/tests/files-walker.test.ts)), (`rejects symlink escape`, `packages/ui-server/tests/files-walker.test.ts:102-104`) -- `a child of an existing file is not found without leaking its absolute path` ([source](../packages/ui-server/tests/files-walker.test.ts)), (`a child of an existing file is not found without leaking its absolute path`, `packages/ui-server/tests/files-walker.test.ts:335-348`) +- `a child of an existing file is not found without leaking its absolute path` ([source](../packages/ui-server/tests/files-walker.test.ts)), (`a child of an existing file is not found without leaking its absolute path`, `packages/ui-server/tests/files-walker.test.ts:346-359`) - `Safari's two-byte probe gets a 206 with its length, and the frame headers` ([source](../packages/ui-server/tests/files-raw-range.test.ts)), (`Safari's two-byte probe gets a 206 with its length, and the frame headers`, `packages/ui-server/tests/files-raw-range.test.ts:222-231`) - `a range that starts past the end is a 416 naming the size` ([source](../packages/ui-server/tests/files-raw-range.test.ts)), (`a range that starts past the end is a 416 naming the size`, `packages/ui-server/tests/files-raw-range.test.ts:87-92`) - `a HEAD request ignores Range, which applies to GET only` ([source](../packages/ui-server/tests/files-raw-range.test.ts)), (`a HEAD request ignores Range, which applies to GET only`, `packages/ui-server/tests/files-raw-range.test.ts:102-107`) diff --git a/docs/integration-contract.md b/docs/integration-contract.md index bbb3a951ea..d744f3759e 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. + ## Provider-relay requests and session taint (breaking before 1.0, #3246) Under the [maintainer's option C](https://github.com/schlessera/brain-kit/issues/3246), diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 6590ad01b4..78d536d26a 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -492,6 +492,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 @@ -1994,6 +2033,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/investigations/audit-capability-investigation.md b/docs/investigations/audit-capability-investigation.md index 76b61f09dc..84758d461a 100644 --- a/docs/investigations/audit-capability-investigation.md +++ b/docs/investigations/audit-capability-investigation.md @@ -74,7 +74,7 @@ Planning parses complete child metadata (`planRegistry`, `packages/core/src/lib/index-registry.ts:210-262`). Tag migration is real code (`applyTagChanges`, -`packages/core/src/lib/tags-apply.ts:435-497`): configured alias chains and +`packages/core/src/lib/tags-apply.ts:381-443`): configured alias chains and eligible variant groups determine the plan; raw tag entries are changed while other bytes, including `updated`, remain. The CLI opens its index before writes, then reindexes and accepts only the exact rewritten bytes. Literal configured @@ -150,8 +150,8 @@ Unsupported, missing, invalid and no-op cases stay manual/unavailable. Reindex after authoritative Markdown changes, then rerun the finding's actual check; partial repair or a failed check never becomes success. -Reuse (`candidateFromAudit`, `packages/core/src/lib/hygiene.ts:351-391`) and -(`hygieneId`, `packages/core/src/lib/hygiene.ts:181-184`) without inventing another +Reuse (`candidateFromAudit`, `packages/core/src/lib/hygiene.ts:352-392`) and +(`hygieneId`, `packages/core/src/lib/hygiene.ts:182-185`) without inventing another identity or disposition store. The [hygiene-review policy](../decisions/hygiene-review.md) binds #597's canonical equivalence, severity/known-urgency ordering and relevant evidence invalidation. This investigation chooses no mappings, review controls diff --git a/docs/modules.md b/docs/modules.md index 6a7358a234..2621f1fc88 100644 --- a/docs/modules.md +++ b/docs/modules.md @@ -627,7 +627,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 fc726d3f6e..741b224a58 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:347` 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 3e79e88d45..93f9895850 100644 --- a/docs/plans/storage-accounting.md +++ b/docs/plans/storage-accounting.md @@ -69,14 +69,14 @@ 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:310-346`), WAL store (`createUiDb`, `packages/ui-server/src/db/client.ts:27-44`), and - private locations (`statePaths`, `packages/ui-server/src/brain/operational-state.ts:108-114`). + 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:149-151`) and settlement-aware cleanup (`function claim`, `packages/ui-server/src/inbox/lifecycle-writes.ts:42-61`). [#807](https://github.com/schlessera/brain-kit/issues/807) supplies live-work and settlement protection for staging cleanup. -- H: scratch defaults (`SCRATCH_DIR`, `packages/core/src/lib/scratch.ts:52-61`), +- H: scratch defaults (`SCRATCH_DIR`, `packages/core/src/lib/scratch.ts:56-65`), scheduled prune (`startScratchPrune`, `packages/ui-server/src/cron/scratch-prune.ts:41-49`), and the [writable-area decision](../decisions/worker-writable-areas.md). [#1656](https://github.com/schlessera/brain-kit/issues/1656) supplies retained diff --git a/docs/plans/storage-lifecycle.md b/docs/plans/storage-lifecycle.md index 8c83fe3869..c6b9bf19ea 100644 --- a/docs/plans/storage-lifecycle.md +++ b/docs/plans/storage-lifecycle.md @@ -76,9 +76,9 @@ Source foundations for the matrix: - Staging eligibility, removal and acknowledgment are separate (`export function createInboxCleanup`, `packages/ui-server/src/inbox/cleanup.ts:15-72`). - Scratch pin loading and per-entry revalidation sit inside pruning - (`export function pruneScratch`, `packages/core/src/lib/scratch.ts:641-722`); + (`export function pruneScratch`, `packages/core/src/lib/scratch.ts:645-726`); explicit clean is different - (`export function cleanScratch`, `packages/core/src/lib/scratch.ts:725-743`). + (`export function cleanScratch`, `packages/core/src/lib/scratch.ts:729-747`). Server refresh refuses incomplete enumeration and confirms missing histories before releasing links (`function openScratchPins`, `packages/ui-server/src/cron/scratch-pins.ts:72-195`). - Claude publishes and verifies cold copies before deleting the live source @@ -90,7 +90,7 @@ Source foundations for the matrix: Object copies reserve temporary bytes before writing (`async putFileAsync`, `packages/ui-server/src/brain/journal-objects.ts:95-150`). - Turn-temp purge has its own scope and measured result - (`export function purgeTurnTemp`, `packages/ui-sdk/src/server/worker-turn-temp.ts:450-533`), + (`export function purgeTurnTemp`, `packages/ui-sdk/src/server/worker-turn-temp.ts:451-534`), and tool validation/recording (`export function handleTurnTemp`, `packages/ui-sdk/src/server/bridge-tools/turn-temp.ts:19-41`). [Operational recovery](../inbox-recovery.md) specifies backup consistency and diff --git a/packages/common/README.md b/packages/common/README.md index 0bbc577d31..3e6d19da57 100644 --- a/packages/common/README.md +++ b/packages/common/README.md @@ -11,11 +11,13 @@ one; it arrives as their dependency. | --- | --- | | `@schlessera/brain-common/internal/env` | The environment descriptor contract (`EnvVarSpec`, `DynamicEnvReadSpec`), `readEnvVar`, and the boolean parsers `envFlag` and `envPresent`. Each package keeps its own `src/config/env.ts` chokepoint on top of it. | | `@schlessera/brain-common/internal/frontmatter` | `parseFrontmatter`, the only door to gray-matter's parser. It always passes an options object, so gray-matter's process-wide cache is never read or written ([decision](../../docs/decisions/frontmatter-parsing.md)). | +| `@schlessera/brain-common/internal/frontmatter-block` | `frontmatterBlock` and `frontmatterLength`: where a frontmatter block starts and ends, by the rule `parseFrontmatter` reads by, without parsing it. It imports nothing, so browser code can use it; every package that needs only the fences asks it (#2507). | | `@schlessera/brain-common/internal/worker-areas` | The hosted worker's write-area names and the rules stated about them: turn temp is never linked, the link rule, and the read-only-brain rule. The ui-sdk's sandbox note and core's `brain` CLI refusal both render them, so the refusal repeats the note word for word (#1654, admitted by #1693). | | `@schlessera/brain-common/internal/protected-paths` | The protected worker path tiers shared by core policy validation and the sandbox. | -| `@schlessera/brain-common/internal/governance-policy` | Data-only policy schema, defaults, parsing and anchored reads shared by the core CLI and hosted server (#1744). The server can read policy without installing its optional core peer. | +| `@schlessera/brain-common/internal/governance-policy` | Data-only policy schema, defaults, parsing and anchored reads shared by the core CLI and hosted server (#1744). The server can read policy without installing its optional core peer. Its policy writer reads and re-checks the file through the same descriptor-anchored reader (#2508). | | `@schlessera/brain-common/internal/index-location` | Where the disposable search index lives: the `.brain-index/` directory holding `brain.db` and its SQLite sidecars, and the legacy root-level names a brain migrates away from by rebuilding (#1668). | | `@schlessera/brain-common/internal/claude-subscription` | The subscription billing guard both Claude runners apply: the cleared credential variables, the neutralised flag settings, the settings refusal and the account verdict. core's CLI runner and the chat backend import it, so a newly found credential or routing variable is added once (#2493). | +| `@schlessera/brain-common/internal/safe-path` | Symlink-safe path containment: `isWithin`, the containment primitive whose equality, separator, trailing-separator and normalisation answers are explicit parameters, and `resolveContained`/`resolveContainedSync`, one canonicalisation algorithm that resolves a request under the root's realpath through its nearest existing ancestor. core's `safeResolve`, the SDK's `resolveInRepo` and the server's `safeResolve` are thin wrappers that each keep their own request refusals and policy, so a hardening fix lands once (#2506). | Nothing else belongs here. A further helper needs its own issue and a reason it cannot live in the package that uses it. diff --git a/packages/common/package.json b/packages/common/package.json index 4cb744e035..6dccc10351 100644 --- a/packages/common/package.json +++ b/packages/common/package.json @@ -36,6 +36,11 @@ "types": "./dist/frontmatter-parse.d.ts", "default": "./dist/frontmatter-parse.js" }, + "./internal/frontmatter-block": { + "bun": "./src/frontmatter-block.ts", + "types": "./dist/frontmatter-block.d.ts", + "default": "./dist/frontmatter-block.js" + }, "./internal/worker-areas": { "bun": "./src/worker-areas.ts", "types": "./dist/worker-areas.d.ts", @@ -85,6 +90,11 @@ "bun": "./src/claude-subscription.ts", "types": "./dist/claude-subscription.d.ts", "default": "./dist/claude-subscription.js" + }, + "./internal/safe-path": { + "bun": "./src/safe-path.ts", + "types": "./dist/safe-path.d.ts", + "default": "./dist/safe-path.js" } }, "files": [ diff --git a/packages/common/src/frontmatter-block.ts b/packages/common/src/frontmatter-block.ts new file mode 100644 index 0000000000..13f15f5212 --- /dev/null +++ b/packages/common/src/frontmatter-block.ts @@ -0,0 +1,63 @@ +// Internal to brain-kit: reached through +// `@schlessera/brain-common/internal/frontmatter-block`, with no compatibility +// promise. Where a document's frontmatter block starts and ends, by the rule +// `parseFrontmatter` (gray-matter 4.0.3) reads it. It imports nothing, so a +// browser bundle can use it (ui-react reaches it through ui-sdk's +// `internal/client`). Every site that needs the fences, but not the YAML, +// asks this instead of writing its own regex (#2507); +// scripts/check-frontmatter-parse.ts refuses a hand-written one. + +/** + * Offsets of a frontmatter block in the original text: + * + * - `start`: where the opening `---` is (1 after a byte order mark, else 0). + * - `innerStart`: after the opening fence's line ending (the end of the text + * when that line has none). + * - `innerEnd`: up to the closing fence, its preceding line ending included, + * so `text.slice(innerStart, innerEnd)` is the block's YAML lines; the end + * of the text when the block is not closed. + * - `end`: after the closing fence and one line ending following it, which is + * where `parseFrontmatter`'s `content` starts; the end of the text when the + * block is not closed. + * - `closed`: whether a closing fence was found. gray-matter reads an + * unclosed block to the end of the file; a writer should refuse one. + */ +export interface FrontmatterBlock { + start: number; + innerStart: number; + innerEnd: number; + end: number; + closed: boolean; +} + +/** + * The frontmatter block, or null when the text has none. gray-matter's rule: + * after a byte order mark, which it strips, the text opens with `---` not + * followed by a fourth `-` (anything else on that line is a language name); + * the block runs to the first `\n---` after it, wherever on its line that + * `---` is followed by more text, and one `\r` and one `\n` after the fence + * belong to it. A leading blank line means no frontmatter; a `...` line does + * not close it. + */ +export function frontmatterBlock(text: string): FrontmatterBlock | null { + const start = text.charCodeAt(0) === 0xfeff ? 1 : 0; + if (!text.startsWith("---", start) || text.charAt(start + 3) === "-") return null; + const newline = text.indexOf("\n", start); + const close = text.indexOf("\n---", start + 3); + if (close === -1) { + return { start, innerStart: newline === -1 ? text.length : newline + 1, innerEnd: text.length, end: text.length, closed: false }; + } + let end = close + 4; + if (text[end] === "\r") end++; + if (text[end] === "\n") end++; + return { start, innerStart: newline + 1, innerEnd: close + 1, end, closed: true }; +} + +/** + * Length of the frontmatter block, `frontmatterBlock(text).end`, or 0 when + * there is none. The length counts a byte order mark, so it is an offset into + * the original text. + */ +export function frontmatterLength(text: string): number { + return frontmatterBlock(text)?.end ?? 0; +} diff --git a/packages/common/src/governance-policy.ts b/packages/common/src/governance-policy.ts index d717f419d7..f62d5117f4 100644 --- a/packages/common/src/governance-policy.ts +++ b/packages/common/src/governance-policy.ts @@ -1,6 +1,6 @@ /** Read-only, data-only governance policy input. Enforcement belongs to its owning siblings. */ import { createHash } from "node:crypto"; -import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, realpathSync } from "node:fs"; +import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readSync, realpathSync } from "node:fs"; import { join } from "node:path"; import { z } from "zod"; import { parseFrontmatter } from "./frontmatter-parse.js"; @@ -205,43 +205,150 @@ export function parseGovernancePolicy(bytes: Uint8Array): GovernancePolicyCheck } } -/** Descriptor-anchored, no links or FIFO reads; never loads brain configuration or executes code. */ -export function checkGovernancePolicy(brainPath: string): GovernancePolicyCheck { - const fds: number[] = []; - const directories: Array<{ path: string; fd: number }> = []; +/** + * Why the anchored reader refused the policy. Each has one message here; + * the policy writer maps them onto its own review states and wording. + * - `not_regular`: not an ordinary file, or a file with hardlink aliases. + * - `oversize`: the file reports more than {@link GOVERNANCE_POLICY_MAX_BYTES}. + * - `changed`: size, timestamps or the bytes read disagree within one read. + * - `ancestry`: a held directory no longer has its name, or is not a directory. + * - `mismatch`: a re-check read bytes other than the expected hash. + */ +export type GovernancePolicyReadRefusal = "not_regular" | "oversize" | "changed" | "ancestry" | "mismatch"; +const READ_REFUSALS: Record = { + not_regular: "Policy must be a regular file without hardlink aliases", + oversize: "Policy exceeds the 1 MiB input bound", + changed: "Policy changed while it was read; retry the check or repair the edit", + ancestry: "Policy ancestry changed while it was read", + mismatch: "Policy changed since it was read", +}; +export class GovernancePolicyReadError extends Error { + constructor(readonly refusal: GovernancePolicyReadRefusal) { super(READ_REFUSALS[refusal]); this.name = "GovernancePolicyReadError"; } +} + +/** One held directory of the policy's ancestry: the brain root, `context`, `context/policies`. */ +export interface GovernancePolicyDirectory { readonly fd: number; readonly path: string; readonly dev: number; readonly ino: number } +/** + * The policy as read through held directory descriptors. `at` names the file + * relative to the innermost held directory (`/proc/self/fd//governance.md` + * on Linux), so a write staged beside it lands in the directory that was checked. + * `bytes` is null when the file does not exist. Close it exactly once. + */ +export interface AnchoredGovernancePolicy { + readonly directories: readonly GovernancePolicyDirectory[]; + readonly at: string; + readonly bytes: Buffer | null; + /** Permission bits of the file read; absent when there is none. */ + readonly mode?: number; + close(): void; +} + +const DIRECTORY_FLAGS = constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW; +const anchoredName = (parent: GovernancePolicyDirectory, name: string, visible: string) => + process.platform === "linux" ? `/proc/self/fd/${parent.fd}/${name}` : visible; + +/** + * Bounded read of the file at `at`, never following a link or blocking on a + * FIFO. Null when it does not exist. Allocates at most one byte past the bound, + * so a file growing after its size check is caught without loading it. + */ +function readAnchoredFile(at: string): { bytes: Buffer | null; mode?: number } { + let fd: number; + try { fd = openSync(at, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); } + catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return { bytes: null }; throw error; } try { - let path = realpathSync(brainPath); - let fd = openSync(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW); fds.push(fd); - directories.push({ path, fd }); - const parts = GOVERNANCE_POLICY_PATH.split("/"); - for (const part of parts.slice(0, -1)) { - path = join(path, part); - fd = openSync(process.platform === "linux" ? `/proc/self/fd/${fd}/${part}` : path, - constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW); fds.push(fd); - directories.push({ path, fd }); - } - fd = openSync(process.platform === "linux" ? `/proc/self/fd/${fd}/${parts.at(-1)!}` : join(path, parts.at(-1)!), - constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); fds.push(fd); const info = fstatSync(fd); - if (!info.isFile() || info.nlink !== 1) throw new Error("Policy must be a regular file without hardlink aliases"); - if (info.size > GOVERNANCE_POLICY_MAX_BYTES) throw new Error("Policy exceeds the 1 MiB input bound"); + if (!info.isFile() || info.nlink !== 1) throw new GovernancePolicyReadError("not_regular"); + if (info.size > GOVERNANCE_POLICY_MAX_BYTES) throw new GovernancePolicyReadError("oversize"); const bytes = Buffer.alloc(GOVERNANCE_POLICY_MAX_BYTES + 1); let length = 0; while (length < bytes.length) { const read = readSync(fd, bytes, length, bytes.length - length, null); if (!read) break; length += read; } const after = fstatSync(fd); - if (after.size !== info.size || after.mtimeMs !== info.mtimeMs || after.ctimeMs !== info.ctimeMs || length !== info.size) throw new Error("Policy changed while it was read; retry the check or repair the edit"); - // Non-Linux CLI readers cannot use /proc descriptor traversal. They open - // each component without following links and reject changed ancestry. - // Hosted workers require Linux, where every open above is descriptor-relative. - if (process.platform !== "linux") for (const directory of directories) { - const named = lstatSync(directory.path), held = fstatSync(directory.fd); - if (!named.isDirectory() || named.dev !== held.dev || named.ino !== held.ino) throw new Error("Policy ancestry changed while it was read"); + // A short or long read is a change even when the timestamps did not move. + if (length !== info.size || after.size !== info.size || after.mtimeMs !== info.mtimeMs || after.ctimeMs !== info.ctimeMs) + throw new GovernancePolicyReadError("changed"); + return { bytes: Buffer.from(bytes.subarray(0, length)), mode: info.mode & 0o7777 }; + } finally { closeSync(fd); } +} + +/** Every held directory still has its name, as a directory, with the identity it was opened with. */ +function checkAncestry(directories: readonly GovernancePolicyDirectory[]) { + for (const directory of directories) { + // A removed ancestor is a change, not a missing policy: bytes were already read. + const named = lstatSync(directory.path, { throwIfNoEntry: false }); + if (!named?.isDirectory() || named.dev !== directory.dev || named.ino !== directory.ino) throw new GovernancePolicyReadError("ancestry"); + } +} + +/** + * Opens the policy's ancestry under `root` without following links, holding + * each directory, and reads the policy through the innermost one. `root` is + * used as given (callers resolve it once) and must itself not be a link. + * On Linux every open after the root is relative to the held parent + * descriptor; elsewhere each component is opened by name and the ancestry + * check below rejects a swap. + * + * With `create`, missing ancestor directories are made (mode 0755) and their + * visible paths appended to `created`, so a caller can remove them again. + * Without it, a missing ancestor throws `ENOENT`. A missing file is + * `bytes: null`. Other refusals throw {@link GovernancePolicyReadError}; + * errors of the system calls (a link: `ELOOP`/`ENOTDIR`) propagate as they are. + * The ancestry is checked after the read, so a directory swapped while the + * bytes were read is refused. + */ +export function openGovernancePolicyAnchored(root: string, options: { create?: boolean; created?: string[] } = {}): AnchoredGovernancePolicy { + const directories: GovernancePolicyDirectory[] = []; + const release = () => { for (const directory of directories.splice(0).reverse()) closeSync(directory.fd); }; + try { + const parts = GOVERNANCE_POLICY_PATH.split("/"), name = parts.pop()!; + let visible = root, at = root; + for (let i = 0; i <= parts.length; i++) { + if (i > 0) { + visible = join(visible, parts[i - 1]!); at = anchoredName(directories.at(-1)!, parts[i - 1]!, visible); + if (options.create) { + try { mkdirSync(at, { mode: 0o755 }); options.created?.push(visible); } + catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; } + } + } + const fd = openSync(at, DIRECTORY_FLAGS); + try { const info = fstatSync(fd); directories.push({ fd, path: visible, dev: info.dev, ino: info.ino }); } + catch (error) { closeSync(fd); throw error; } } - return parseGovernancePolicy(bytes.subarray(0, length)); + const file = anchoredName(directories.at(-1)!, name, join(visible, name)); + const read = readAnchoredFile(file); + checkAncestry(directories); + let closed = false; + return { directories, at: file, ...read, close() { if (!closed) { closed = true; release(); } } }; + } catch (error) { release(); throw error; } +} + +/** + * Re-checks a held policy: the ancestry still has its names, and the file + * now at `handle.at` reads (with the same bounds) to `expectedHash`, the + * SHA-256 of its bytes, or is absent when `expectedHash` is null. Returns the + * bytes read; throws {@link GovernancePolicyReadError} otherwise. + */ +export function verifyGovernancePolicyAnchored(handle: AnchoredGovernancePolicy, expectedHash: string | null): Buffer | null { + checkAncestry(handle.directories); + const current = readAnchoredFile(handle.at).bytes; + if ((current === null ? null : createHash("sha256").update(current).digest("hex")) !== expectedHash) throw new GovernancePolicyReadError("mismatch"); + return current; +} + +/** Descriptor-anchored, no links or FIFO reads; never loads brain configuration or executes code. */ +export function checkGovernancePolicy(brainPath: string): GovernancePolicyCheck { + let handle: AnchoredGovernancePolicy | undefined; + try { + handle = openGovernancePolicyAnchored(realpathSync(brainPath)); + if (handle.bytes === null) return missingGovernancePolicy(); + return parseGovernancePolicy(handle.bytes); } catch (error) { - const missing = (error as NodeJS.ErrnoException).code === "ENOENT"; - return { schema_version: 1, ok: missing, status: missing ? "missing" : "invalid", content_hash: null, - errors: missing ? [] : [error instanceof Error ? error.message : String(error)], warnings: [], effective: resolveGovernancePolicy({ schema_version: 1 }) }; - } finally { for (const fd of fds.reverse()) closeSync(fd); } + if ((error as NodeJS.ErrnoException).code === "ENOENT") return missingGovernancePolicy(); + return { schema_version: 1, ok: false, status: "invalid", content_hash: null, + errors: [error instanceof Error ? error.message : String(error)], warnings: [], effective: resolveGovernancePolicy({ schema_version: 1 }) }; + } finally { handle?.close(); } +} +function missingGovernancePolicy(): GovernancePolicyCheck { + return { schema_version: 1, ok: true, status: "missing", content_hash: null, errors: [], warnings: [], effective: resolveGovernancePolicy({ schema_version: 1 }) }; } /** Matching rules intersect their allowlists; unknown recipients never authorize a match. */ diff --git a/packages/common/src/safe-path.ts b/packages/common/src/safe-path.ts new file mode 100644 index 0000000000..f9b3fba908 --- /dev/null +++ b/packages/common/src/safe-path.ts @@ -0,0 +1,255 @@ +/** + * Symlink-safe path containment, held once for core, the ui-sdk and ui-server + * (#2506). Two parts: + * + * - {@link isWithin}, the string question "is this path the root or below + * it?". The callers' answers differ on equality, the separator, a root + * ending in a separator and normalisation, so those are parameters + * ({@link WithinRule}) rather than hidden choices. + * - {@link resolveContained} and {@link resolveContainedSync}, one + * canonicalisation algorithm: resolve the request under the root's + * realpath, canonicalise its nearest existing ancestor, and check the + * canonical result against the root. A dangling link is either followed + * to its target, which must stay inside, or refused. The algorithm is a + * generator of filesystem queries, so the synchronous and asynchronous + * variants run the same steps. + * + * What a caller accepts as a request (absolute paths, `..`, Windows syntax) + * and how it reports a refusal stay in that caller: they are its policy, and + * the resolver rows of #2506 differ on them. Everything after the request is + * accepted is decided here. + */ +import { lstatSync, readlinkSync, realpathSync } from "node:fs"; +import { lstat, readlink, realpath } from "node:fs/promises"; +import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; + +/** How {@link isWithin} answers the cases its callers disagree on. */ +export interface WithinRule { + /** Whether the root itself counts as within. Default `true`. */ + readonly includeRoot?: boolean; + /** The separator that must follow the root. Default `/`. */ + readonly separator?: string; + /** + * A root already ending in the separator: `"append"` (default) appends + * another, so `/` and `/a/` hold nothing below them; `"boundary"` takes the + * root's own separator as the boundary, so `/` holds every absolute path. + */ + readonly trailingSeparator?: "append" | "boundary"; + /** + * Resolve both paths against the working directory first, as + * `path.relative` does, so `/a/b/../c` is not within `/a/b`. Default + * `false`: the comparison is on the strings as given. + */ + readonly resolvePaths?: boolean; +} + +/** Whether `path` is `root` or below it, under `rule`. The argument order is fixed: root first. */ +export function isWithin(root: string, path: string, rule: WithinRule = {}): boolean { + if (rule.resolvePaths) { + root = resolve(root); + path = resolve(path); + } + if (path === root) return rule.includeRoot ?? true; + const separator = rule.separator ?? "/"; + const prefix = rule.trailingSeparator === "boundary" && root.endsWith(separator) ? root : root + separator; + return path.startsWith(prefix); +} + +/** The platform-separator rule the resolvers check canonical paths with. */ +const CANONICAL: WithinRule = { separator: sep }; + +/** What a caller decides about the filesystem it resolves through. */ +export interface ContainmentPolicy { + /** + * A root whose realpath fails. `"refuse"`: nothing resolves. `"lexical"`: + * a root that does not exist yet contains the lexical path; a dangling + * link in its place is refused and any other failure is an error. + */ + readonly missingRoot: "refuse" | "lexical"; + /** + * A symlink whose target cannot be resolved. `"follow"`: re-check its + * target, which must stay inside, so a write through it lands inside. + * `"refuse"`: refuse it, wherever it points. + */ + readonly danglingLinks: "follow" | "refuse"; + /** + * `"final"`: only the canonical path must stay inside, so a request may + * leave through one link and come back through another. `"every"`: each + * existing component on the way must stay inside too. + */ + readonly components: "final" | "every"; + /** + * Refuse a symlink at this lexical component without following it; `root` + * is the root's realpath. Only consulted with `components: "every"`, + * which visits each component. + */ + readonly refuseLinkAt?: (path: string, root: string) => boolean; +} + +/** Why a request was refused. */ +export type ContainmentRefusal = "nul" | "missing-root" | "escape" | "dangling" | "link-budget" | "refused-link"; + +export type ContainedPath = + | { + readonly ok: true; + /** The root's realpath (its lexical path when a missing root is allowed). */ + readonly root: string; + /** The request resolved under {@link root}, links as written. */ + readonly lexical: string; + /** The request with every existing link followed; the missing tail as written. */ + readonly canonical: string; + } + | { readonly ok: false; readonly reason: ContainmentRefusal } + /** A filesystem failure that is neither absence nor a refusal (EIO, ...). */ + | { readonly ok: false; readonly reason: "error"; readonly error: NodeJS.ErrnoException }; + +/** + * Codes that mean "this component cannot be resolved": the lookup stops + * there and what follows is treated as not existing yet. Any other code is + * an error, never an acceptance. + */ +const UNRESOLVABLE = new Set(["ENOENT", "ENOTDIR", "ENAMETOOLONG", "ELOOP", "EACCES", "EPERM"]); + +/** The kernel's symlink budget for one lookup. */ +const MAX_LINK_HOPS = 40; + +type FsQuery = + | { readonly op: "realpath" | "readlink"; readonly path: string } + | { readonly op: "lstat"; readonly path: string }; +type FsReply = + | { readonly ok: true; readonly value: string; readonly link: boolean } + | { readonly ok: false; readonly error: NodeJS.ErrnoException }; +type Steps = Generator; + +const failed = (error: unknown): FsReply => ({ ok: false, error: error as NodeJS.ErrnoException }); +const unresolvable = (reply: FsReply) => !reply.ok && UNRESOLVABLE.has(reply.error.code ?? ""); + +function querySync(query: FsQuery): FsReply { + try { + if (query.op === "lstat") return { ok: true, value: query.path, link: lstatSync(query.path).isSymbolicLink() }; + return { ok: true, value: query.op === "realpath" ? realpathSync(query.path) : readlinkSync(query.path), link: false }; + } catch (error) { + return failed(error); + } +} + +async function queryAsync(query: FsQuery): Promise { + try { + if (query.op === "lstat") return { ok: true, value: query.path, link: (await lstat(query.path)).isSymbolicLink() }; + return { ok: true, value: query.op === "realpath" ? await realpath(query.path) : await readlink(query.path), link: false }; + } catch (error) { + return failed(error); + } +} + +/** + * Canonicalise `path` (lexically inside `root`, a realpath): realpath its + * nearest existing ancestor and re-append the missing tail. A purely lexical + * fallback would let a symlinked parent smuggle a not-yet-created file + * outside the root. A dangling link is not "missing": a write through it is + * created at its target, so it is followed and re-checked, or refused. + */ +function* canonicalise(root: string, path: string, policy: ContainmentPolicy): Steps { + let existing = path; + let tail: string[] = []; + let hops = 0; + for (;;) { + const real = yield { op: "realpath", path: existing }; + if (real.ok) { + const candidate = tail.length > 0 ? join(real.value, ...tail) : real.value; + if (!isWithin(root, candidate, CANONICAL)) return { ok: false, reason: "escape" }; + return { ok: true, root, lexical: path, canonical: candidate }; + } + if (!unresolvable(real)) return { ok: false, reason: "error", error: real.error }; + const entry = yield { op: "lstat", path: existing }; + if (entry.ok && entry.link) { + // A link whose realpath fails: dangling, a cycle, or unreadable. + if (policy.danglingLinks === "refuse") return { ok: false, reason: "dangling" }; + if (++hops > MAX_LINK_HOPS) return { ok: false, reason: "link-budget" }; + const target = yield { op: "readlink", path: existing }; + if (!target.ok) return { ok: false, reason: "error", error: target.error }; + const resolved = isAbsolute(target.value) ? resolve(target.value) : resolve(dirname(existing), target.value); + const rejoined = tail.length > 0 ? join(resolved, ...tail) : resolved; + if (!isWithin(root, rejoined, CANONICAL)) return { ok: false, reason: "escape" }; + existing = rejoined; + tail = []; + continue; + } + if (!entry.ok && !unresolvable(entry)) return { ok: false, reason: "error", error: entry.error }; + // Not there (yet), or there but not resolvable as a whole: canonicalise + // what is above it. The walk ends at the root, which resolved. + tail.unshift(basename(existing)); + const parent = dirname(existing); + if (parent === existing) return { ok: false, reason: "escape" }; + existing = parent; + } +} + +function* containedSteps(root: string, rel: string, policy: ContainmentPolicy): Steps { + // A NUL would make the later fs call throw: a containment failure, not a + // deferred TypeError. + if (rel.includes("\0")) return { ok: false, reason: "nul" }; + const lexicalRoot = resolve(root); + const rootReal = yield { op: "realpath", path: lexicalRoot }; + if (!rootReal.ok) { + if (policy.missingRoot === "refuse") return { ok: false, reason: "missing-root" }; + if (rootReal.error.code !== "ENOENT") return { ok: false, reason: "error", error: rootReal.error }; + // Present but unresolvable means a dangling link stands in its place. + const entry = yield { op: "lstat", path: lexicalRoot }; + if (entry.ok) return { ok: false, reason: "dangling" }; + if (!unresolvable(entry)) return { ok: false, reason: "error", error: entry.error }; + const lexical = resolve(lexicalRoot, rel); + if (!isWithin(lexicalRoot, lexical, CANONICAL)) return { ok: false, reason: "escape" }; + // Nothing below a missing root exists to be followed. + return { ok: true, root: lexicalRoot, lexical, canonical: lexical }; + } + const absRoot = rootReal.value; + const lexical = resolve(absRoot, rel); + if (!isWithin(absRoot, lexical, CANONICAL)) return { ok: false, reason: "escape" }; + if (policy.components === "final") { + const contained = yield* canonicalise(absRoot, lexical, policy); + return contained.ok ? { ...contained, lexical } : contained; + } + // Each component in order, from the root down: a link refused here is + // refused before it is followed, and every existing prefix must canonicalise + // inside, not only the whole path. + let prefix = absRoot; + const prefixes = [absRoot]; + for (const segment of relative(absRoot, lexical).split(sep)) { + if (!segment) continue; + prefix = join(prefix, segment); + prefixes.push(prefix); + } + let canonical = absRoot; + for (const path of prefixes) { + if (policy.refuseLinkAt?.(path, absRoot)) { + const entry = yield { op: "lstat", path }; + if (entry.ok && entry.link) return { ok: false, reason: "refused-link" }; + } + const contained = yield* canonicalise(absRoot, path, policy); + if (!contained.ok) return contained; + canonical = contained.canonical; + } + return { ok: true, root: absRoot, lexical, canonical }; +} + +/** {@link resolveContained}, synchronously. */ +export function resolveContainedSync(root: string, rel: string, policy: ContainmentPolicy): ContainedPath { + const steps = containedSteps(root, rel, policy); + let step = steps.next(); + while (!step.done) step = steps.next(querySync(step.value)); + return step.value; +} + +/** + * Resolve `rel` under `root` and check that it stays inside, following + * symlinks, under the caller's {@link ContainmentPolicy}. Each call reads the + * filesystem again: the answer describes the moment of the call, so a + * caller that opens the path later still owns the race between the two. + */ +export async function resolveContained(root: string, rel: string, policy: ContainmentPolicy): Promise { + const steps = containedSteps(root, rel, policy); + let step = steps.next(); + while (!step.done) step = steps.next(await queryAsync(step.value)); + return step.value; +} diff --git a/packages/common/tests/frontmatter-block.test.ts b/packages/common/tests/frontmatter-block.test.ts new file mode 100644 index 0000000000..ee92820e7b --- /dev/null +++ b/packages/common/tests/frontmatter-block.test.ts @@ -0,0 +1,52 @@ +/** + * `frontmatterBlock` finds the fences `parseFrontmatter` reads by (#2507). + * Every row is checked against the parser itself, so a change to either side + * that makes them disagree fails here. + */ + +import { describe, expect, test } from "bun:test"; + +import { frontmatterBlock, frontmatterLength } from "../src/frontmatter-block"; +import { parseFrontmatter } from "../src/frontmatter-parse"; + +const BOM = "\uFEFF"; + +const rows: Array<{ name: string; text: string; block: ReturnType; data?: Record }> = [ + { name: "plain LF", text: "---\ntitle: a\n---\nbody\n", block: { start: 0, innerStart: 4, innerEnd: 13, end: 17, closed: true }, data: { title: "a" } }, + { name: "byte order mark", text: `${BOM}---\ntitle: a\n---\nbody\n`, block: { start: 1, innerStart: 5, innerEnd: 14, end: 18, closed: true }, data: { title: "a" } }, + { name: "CRLF", text: "---\r\ntitle: a\r\n---\r\nbody\r\n", block: { start: 0, innerStart: 5, innerEnd: 15, end: 20, closed: true }, data: { title: "a" } }, + { name: "trailing whitespace after the opening fence", text: "--- \ntitle: a\n---\nbody\n", block: { start: 0, innerStart: 5, innerEnd: 14, end: 18, closed: true }, data: { title: "a" } }, + // gray-matter ends the block at the dashes; the whitespace starts the content. + { name: "trailing whitespace after the closing fence", text: "---\ntitle: a\n--- \nbody\n", block: { start: 0, innerStart: 4, innerEnd: 13, end: 16, closed: true }, data: { title: "a" } }, + { name: "closing fence at the end of the file", text: "---\ntitle: a\n---", block: { start: 0, innerStart: 4, innerEnd: 13, end: 16, closed: true }, data: { title: "a" } }, + { name: "four dashes are not a fence", text: "----\ntitle: a\n----\nbody\n", block: null }, + { name: "a leading blank line means no frontmatter", text: "\n---\ntitle: a\n---\nbody\n", block: null }, + { name: "no frontmatter", text: "# Title\n", block: null }, + { name: "unclosed block runs to the end", text: "---\ntitle: a\n", block: { start: 0, innerStart: 4, innerEnd: 13, end: 13, closed: false }, data: { title: "a" } }, + { name: "empty block", text: "---\n---\nbody\n", block: { start: 0, innerStart: 4, innerEnd: 4, end: 8, closed: true }, data: {} }, + // The first `\n---` closes; the next `---` line is a rule in the body. + { name: "a rule right after the closing fence", text: "---\ntitle: a\n---\n---\nbody\n", block: { start: 0, innerStart: 4, innerEnd: 13, end: 17, closed: true }, data: { title: "a" } }, + // A `...` line does not close a block: everything to the end is frontmatter. + { name: "a ... line is not a closer", text: "---\ntitle: a\n...\n", block: { start: 0, innerStart: 4, innerEnd: 17, end: 17, closed: false }, data: { title: "a" } }, +]; + +describe("frontmatterBlock agrees with parseFrontmatter", () => { + for (const row of rows) { + test(row.name, () => { + const block = frontmatterBlock(row.text); + expect(block).toEqual(row.block); + expect(frontmatterLength(row.text)).toBe(block?.end ?? 0); + const parsed = parseFrontmatter(row.text, { dataOnly: true }); + if (!block) { + expect(parsed.matter).toBe(""); + expect(parsed.data).toEqual({}); + return; + } + // What the parser treats as body is exactly what follows the block. + expect(parsed.content).toBe(row.text.slice(block.end)); + // What it treats as YAML is exactly the block's inner lines. + expect(parsed.matter.trim()).toBe(row.text.slice(block.innerStart, block.innerEnd).trim()); + expect(parsed.data).toEqual(row.data!); + }); + } +}); diff --git a/packages/common/tests/governance-policy-read.test.ts b/packages/common/tests/governance-policy-read.test.ts new file mode 100644 index 0000000000..7700b4a365 --- /dev/null +++ b/packages/common/tests/governance-policy-read.test.ts @@ -0,0 +1,173 @@ +/** + * The descriptor-anchored governance policy read (#2508). `checkGovernancePolicy` + * and ui-server's policy writer both read the protected file through it; the + * writer's own characterization lives in + * `packages/ui-server/tests/policy-proposal-read.test.ts`. + * + * Races are staged through `node:fs` spies on the descriptor's `fstatSync`, so + * the same hooks drive every implementation without knowing how it reads. + */ +import { afterEach, expect, test } from "bun:test"; +import * as fs from "node:fs"; +import { linkSync, mkdirSync, mkdtempSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createHash } from "node:crypto"; +import { spyOn } from "bun:test"; +import { checkGovernancePolicy, GOVERNANCE_POLICY_MAX_BYTES, GOVERNANCE_POLICY_PATH } from "../src/governance-policy"; + +const policy = "---\nschema_version: 1\nprofiles:\n interactive: governed\n---\nPenelope keeps the policy.\n"; +const replacement = "---\nschema_version: 1\nprofiles:\n interactive: strict\n---\nThe suitors rewrote the policy.\n"; +const sha = (text: string | Uint8Array) => createHash("sha256").update(text).digest("hex"); +const cleanup: Array<() => void> = []; +afterEach(() => { for (const fn of cleanup.splice(0).reverse()) fn(); }); + +function brain(content: string | null = policy) { + const root = mkdtempSync(join(tmpdir(), "governance-read-")); + cleanup.push(() => rmSync(root, { recursive: true, force: true })); + mkdirSync(join(root, "context/policies"), { recursive: true }); + const path = join(root, GOVERNANCE_POLICY_PATH); + if (content !== null) writeFileSync(path, content); + return { root, path }; +} + +/** + * Runs `hook` once, when the reader first fstats a regular file (the policy + * descriptor before its bytes are read), and lets `size` override what every + * regular-file fstat reports. Restored in teardown. + */ +function onPolicyStat(hook?: () => void, size?: (real: number) => number) { + const original = fs.fstatSync; + let fired = false; + const spy = spyOn(fs, "fstatSync").mockImplementation(((fd: number, options?: fs.StatOptions) => { + const info = original(fd, options as never) as fs.Stats; + if (!info.isFile()) return info; + if (!fired && hook) { fired = true; hook(); } + if (size) Object.defineProperty(info, "size", { value: size(info.size) }); + return info; + }) as typeof fs.fstatSync); + cleanup.push(() => spy.mockRestore()); + return () => fired; +} + +/** Largest single result either read API handed back for a descriptor. */ +function readHighWater() { + const readSync = fs.readSync, readFileSync = fs.readFileSync; + let most = 0; + const a = spyOn(fs, "readSync").mockImplementation(((...args: Parameters) => { + const n = (readSync as (...x: unknown[]) => number)(...args); most = Math.max(most, n); return n; + }) as typeof fs.readSync); + const b = spyOn(fs, "readFileSync").mockImplementation(((...args: Parameters) => { + const out = (readFileSync as (...x: unknown[]) => Buffer | string)(...args); + if (typeof args[0] === "number") most = Math.max(most, out.length); + return out; + }) as typeof fs.readFileSync); + cleanup.push(() => { a.mockRestore(); b.mockRestore(); }); + return () => most; +} + +function withPlatform(platform: NodeJS.Platform) { + const descriptor = Object.getOwnPropertyDescriptor(process, "platform")!; + Object.defineProperty(process, "platform", { ...descriptor, value: platform }); + cleanup.push(() => Object.defineProperty(process, "platform", descriptor)); +} + +/** Moves `context` aside and puts a fresh tree holding `replacement` at the old name. */ +function replaceAncestry(root: string) { + renameSync(join(root, "context"), join(root, "old-context")); + mkdirSync(join(root, "context/policies"), { recursive: true }); + writeFileSync(join(root, GOVERNANCE_POLICY_PATH), replacement); +} + +test("a valid policy is read with the hash of its exact bytes", () => { + const { root } = brain(); + const checked = checkGovernancePolicy(root); + expect(checked.status).toBe("valid"); + expect(checked.content_hash).toBe(sha(policy)); +}); + +test("a missing file and a missing ancestor both select defaults as missing", () => { + expect(checkGovernancePolicy(brain(null).root)).toMatchObject({ ok: true, status: "missing", content_hash: null, errors: [] }); + const { root } = brain(null); + rmSync(join(root, "context"), { recursive: true }); + expect(checkGovernancePolicy(root)).toMatchObject({ ok: true, status: "missing", content_hash: null }); +}); + +test("a symlinked policy file is refused, not followed", () => { + const { root, path } = brain(null); + writeFileSync(join(root, "elsewhere.md"), policy); + symlinkSync(join(root, "elsewhere.md"), path); + const checked = checkGovernancePolicy(root); + expect(checked).toMatchObject({ ok: false, status: "invalid", content_hash: null }); + expect(checked.errors[0]).toMatch(/ELOOP|symbolic link/i); +}); + +test("a symlinked ancestor is refused, not followed", () => { + const { root } = brain(); + renameSync(join(root, "context"), join(root, "real-context")); + symlinkSync(join(root, "real-context"), join(root, "context")); + expect(checkGovernancePolicy(root)).toMatchObject({ ok: false, status: "invalid", content_hash: null }); +}); + +test("a hardlinked policy file is refused", () => { + const { root, path } = brain(); + linkSync(path, join(root, "alias.md")); + expect(checkGovernancePolicy(root)).toMatchObject({ ok: false, status: "invalid", errors: ["Policy must be a regular file without hardlink aliases"] }); +}); + +test("a FIFO at the policy name is refused without blocking", () => { + const { path, root } = brain(null); + const made = Bun.spawnSync(["mkfifo", path]); + expect(made.exitCode).toBe(0); + expect(checkGovernancePolicy(root)).toMatchObject({ ok: false, status: "invalid", errors: ["Policy must be a regular file without hardlink aliases"] }); +}); + +test("an oversized policy is refused before its bytes are read", () => { + const { root } = brain("x".repeat(GOVERNANCE_POLICY_MAX_BYTES + 1)); + expect(checkGovernancePolicy(root)).toMatchObject({ ok: false, status: "invalid", errors: ["Policy exceeds the 1 MiB input bound"] }); +}); + +test("a short read (fewer bytes than the descriptor reported) is refused as a change", () => { + const { root } = brain(); + onPolicyStat(undefined, real => real + 16); + expect(checkGovernancePolicy(root)).toMatchObject({ ok: false, status: "invalid", errors: ["Policy changed while it was read; retry the check or repair the edit"] }); +}); + +test("a file that grows during the read is refused as a change", () => { + const { root, path } = brain(); + onPolicyStat(() => fs.appendFileSync(path, "Antinous appended this.\n")); + expect(checkGovernancePolicy(root)).toMatchObject({ ok: false, status: "invalid", errors: ["Policy changed while it was read; retry the check or repair the edit"] }); +}); + +test("a file that grows past the bound after its size check never loads more than the bound", () => { + const { root, path } = brain(); + const highWater = readHighWater(); + onPolicyStat(() => fs.appendFileSync(path, "x".repeat(4 * GOVERNANCE_POLICY_MAX_BYTES)), () => policy.length); + expect(checkGovernancePolicy(root)).toMatchObject({ ok: false, status: "invalid" }); + expect(highWater()).toBeLessThanOrEqual(GOVERNANCE_POLICY_MAX_BYTES + 1); +}); + +test("an ancestor replaced while the policy is read is refused on Linux (the writer's rule)", () => { + if (process.platform !== "linux") return; + const { root } = brain(); + const fired = onPolicyStat(() => replaceAncestry(root)); + const checked = checkGovernancePolicy(root); + expect(fired()).toBe(true); + expect(checked, "GOVERNANCE_READ_LINUX_ANCESTRY_RECHECK").toMatchObject({ ok: false, status: "invalid", errors: ["Policy ancestry changed while it was read"] }); +}); + +test("an ancestor removed while the policy is read is refused, not reported missing (non-Linux traversal)", () => { + const { root } = brain(); + withPlatform("darwin"); + const fired = onPolicyStat(() => renameSync(join(root, "context"), join(root, "old-context"))); + const checked = checkGovernancePolicy(root); + expect(fired()).toBe(true); + expect(checked, "GOVERNANCE_READ_REMOVED_ANCESTOR_IS_NOT_MISSING").toMatchObject({ ok: false, status: "invalid", errors: ["Policy ancestry changed while it was read"] }); +}); + +test("an ancestor replaced while the policy is read is refused (non-Linux traversal)", () => { + const { root } = brain(); + withPlatform("darwin"); + onPolicyStat(() => replaceAncestry(root)); + expect(checkGovernancePolicy(root)).toMatchObject({ ok: false, status: "invalid", errors: ["Policy ancestry changed while it was read"] }); +}); diff --git a/packages/common/tests/safe-path.test.ts b/packages/common/tests/safe-path.test.ts new file mode 100644 index 0000000000..e6c897d33d --- /dev/null +++ b/packages/common/tests/safe-path.test.ts @@ -0,0 +1,176 @@ +import { afterAll, describe, expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, relative, sep } from "node:path"; + +import { + isWithin, + resolveContained, + resolveContainedSync, + type ContainedPath, + type ContainmentPolicy, + type WithinRule, +} from "../src/safe-path"; + +describe("isWithin(root, path, rule)", () => { + // Columns: equality, child, sibling prefix, parent, root `/` (absolute, + // itself, relative), trailing separator on the root, unnormalised paths. + const CASES: [string, string][] = [ + ["/a/b", "/a/b"], ["/a/b", "/a/b/c"], ["/a/b", "/a/bc"], ["/a/b", "/a"], + ["/", "/x"], ["/", "/"], ["/", "x"], + ["/a/b/", "/a/b/c"], ["/a/b/", "/a/b"], + ["/a/b", "/a/b/"], ["/a/b", "/a/b/../c"], ["/a/b", "/a/b/..c"], ["/a/b", "/a/b//c"], + ]; + const row = (rule?: WithinRule) => CASES.map(([root, path]) => (isWithin(root, path, rule) ? "T" : "-")).join(" "); + + // Every combination a caller uses (#2506), each written out. + test("the default: root included, `/` appended to any root, strings as given", () => { + expect(row()).toBe("T T - - - T - - - T T T T"); + expect(row({ includeRoot: true, separator: "/", trailingSeparator: "append", resolvePaths: false })).toBe(row()); + }); + + test("a trailing separator on the root is its boundary, so `/` holds every absolute path", () => { + expect(row({ trailingSeparator: "boundary" })).toBe("T T - - T T - T - T T T T"); + }); + + test("resolved first, root included (relative()-based callers)", () => { + expect(row({ resolvePaths: true, separator: sep, trailingSeparator: "boundary" })).toBe("T T - - T T T T T T - T T"); + }); + + test("resolved first, root excluded", () => { + expect(row({ includeRoot: false, resolvePaths: true, separator: sep, trailingSeparator: "boundary" })) + .toBe("- T - - T - T T - - - T T"); + }); + + test("the separator is a parameter", () => { + expect(isWithin("C:\\a", "C:\\a\\b", { separator: "\\" })).toBe(true); + expect(isWithin("C:\\a", "C:\\ab", { separator: "\\" })).toBe(false); + expect(isWithin("C:\\a", "C:\\a/b", { separator: "\\" })).toBe(false); + expect(isWithin("/a", "/a\\b", { separator: "\\" })).toBe(true); + }); + + test("the sibling prefix is never within, under any rule", () => { + for (const rule of [{}, { trailingSeparator: "boundary" }, { resolvePaths: true }, { includeRoot: false }] as WithinRule[]) { + expect(isWithin("/srv/brain", "/srv/brain-other/x", rule)).toBe(false); + expect(isWithin("/srv/brain", "/srv/brainx", rule)).toBe(false); + } + }); + + test("the argument order is root first", () => { + expect(isWithin("/a", "/a/b")).toBe(true); + expect(isWithin("/a/b", "/a")).toBe(false); + }); +}); + +const base = realpathSync(mkdtempSync(join(tmpdir(), "brain-common-safe-path-"))); +afterAll(() => rmSync(base, { recursive: true, force: true })); +const root = join(base, "brain"); +const outside = join(base, "brain-other"); +mkdirSync(join(root, "notes"), { recursive: true }); +mkdirSync(join(root, ".brain/scratch"), { recursive: true }); +mkdirSync(outside); +writeFileSync(join(root, "notes/a.md"), "a"); +writeFileSync(join(outside, "secret.md"), "s"); +symlinkSync("notes", join(root, "link-in")); +symlinkSync(outside, join(root, "link-out")); +symlinkSync("notes/missing", join(root, "dangling-in")); +symlinkSync(join(outside, "missing"), join(root, "dangling-out")); +symlinkSync("cycle-b", join(root, "cycle-a")); +symlinkSync("cycle-a", join(root, "cycle-b")); +symlinkSync(outside, join(root, "bounce")); +symlinkSync(join(root, "notes"), join(outside, "back")); +symlinkSync("../../notes", join(root, ".brain/scratch/link")); +symlinkSync(root, join(base, "root-link")); +// A dangling chain that leaves the root and comes back to a missing target inside. +symlinkSync(join(root, "notes/missing"), join(outside, "dangling-back")); +symlinkSync(join(outside, "dangling-back"), join(root, "dangling-bounce")); + +const FINAL_FOLLOW: ContainmentPolicy = { missingRoot: "refuse", danglingLinks: "follow", components: "final" }; +const EVERY_REFUSE: ContainmentPolicy = { missingRoot: "lexical", danglingLinks: "refuse", components: "every" }; + +/** `canonical` (and `lexical` when it differs) relative to the fixture base, or the refusal. */ +function show(result: ContainedPath): string { + if (!result.ok) return result.reason === "error" ? `error ${result.error.code}` : `refused ${result.reason}`; + const canonical = relative(base, result.canonical); + const lexical = relative(base, result.lexical); + return canonical === lexical ? canonical : `${canonical} (as ${lexical})`; +} + +/** Both variants, which must agree. */ +async function both(at: string, rel: string, policy: ContainmentPolicy): Promise { + const sync = show(resolveContainedSync(at, rel, policy)); + expect(show(await resolveContained(at, rel, policy))).toBe(sync); + return sync; +} + +describe("resolveContained: one algorithm, sync and async", () => { + const rows: [string, string, string][] = [ + // rel, final + follow, every + refuse + ["notes/a.md", "brain/notes/a.md", "brain/notes/a.md"], + ["notes/new.md", "brain/notes/new.md", "brain/notes/new.md"], + ["a/b/c.md", "brain/a/b/c.md", "brain/a/b/c.md"], + ["", "brain", "brain"], + ["../brain-other/secret.md", "refused escape", "refused escape"], + ["notes/../../brain-other", "refused escape", "refused escape"], + ["a\0b", "refused nul", "refused nul"], + ["link-in/a.md", "brain/notes/a.md (as brain/link-in/a.md)", "brain/notes/a.md (as brain/link-in/a.md)"], + // A symlinked parent of a file that does not exist yet. + ["link-out/new.md", "refused escape", "refused escape"], + ["link-in/new.md", "brain/notes/new.md (as brain/link-in/new.md)", "brain/notes/new.md (as brain/link-in/new.md)"], + ["dangling-in", "brain/notes/missing (as brain/dangling-in)", "refused dangling"], + ["dangling-in/x", "brain/notes/missing/x (as brain/dangling-in/x)", "refused dangling"], + ["dangling-out", "refused escape", "refused dangling"], + // Followed, the first hop already leaves the root: refused there, even + // though the chain ends inside. + ["dangling-bounce", "refused escape", "refused dangling"], + // A dangling cycle: followed, it runs out of the link budget. + ["cycle-a", "refused link-budget", "refused dangling"], + ["cycle-a/x", "refused link-budget", "refused dangling"], + // Out through one link and back through another. + ["bounce/back/a.md", "brain/notes/a.md (as brain/bounce/back/a.md)", "refused escape"], + ]; + for (const [rel, finalFollow, everyRefuse] of rows) { + test(JSON.stringify(rel), async () => { + expect(await both(root, rel, FINAL_FOLLOW)).toBe(finalFollow); + expect(await both(root, rel, EVERY_REFUSE)).toBe(everyRefuse); + }); + } + + test("an absolute request is resolved like any other: inside is accepted", async () => { + expect(await both(root, join(root, "notes/a.md"), FINAL_FOLLOW)).toBe("brain/notes/a.md"); + expect(await both(root, "/etc/passwd", FINAL_FOLLOW)).toBe("refused escape"); + }); + + test("a root that is itself a symlink resolves against its target", async () => { + expect(await both(join(base, "root-link"), "notes/a.md", FINAL_FOLLOW)).toBe("brain/notes/a.md"); + expect(await both(join(base, "root-link"), "link-out/x", EVERY_REFUSE)).toBe("refused escape"); + }); + + test("a missing root: refused, or the lexical path; never through a dangling link or a file", async () => { + expect(await both(join(base, "nope"), "notes/a.md", FINAL_FOLLOW)).toBe("refused missing-root"); + expect(await both(join(base, "nope"), "notes/a.md", EVERY_REFUSE)).toBe("nope/notes/a.md"); + expect(await both(join(base, "nope"), "../brain/notes", EVERY_REFUSE)).toBe("refused escape"); + expect(await both(join(root, "dangling-in"), "x", EVERY_REFUSE)).toBe("refused dangling"); + writeFileSync(join(base, "file"), ""); + expect(await both(join(base, "file/x"), "y", EVERY_REFUSE)).toBe("error ENOTDIR"); + }); + + test("refuseLinkAt refuses a link at a chosen component before following it", async () => { + const policy: ContainmentPolicy = { ...EVERY_REFUSE, refuseLinkAt: (path, absRoot) => isWithin(join(absRoot, ".brain"), path) }; + expect(await both(root, ".brain/scratch/link/a.md", policy)).toBe("refused refused-link"); + expect(await both(root, ".brain/scratch/link/a.md", EVERY_REFUSE)).toBe("brain/notes/a.md (as brain/.brain/scratch/link/a.md)"); + expect(await both(root, "link-in/a.md", policy)).toBe("brain/notes/a.md (as brain/link-in/a.md)"); + // Only the component walk consults it. + expect(await both(root, ".brain/scratch/link/a.md", { ...FINAL_FOLLOW, refuseLinkAt: () => true })).toBe("brain/notes/a.md (as brain/.brain/scratch/link/a.md)"); + }); + + test("each call reads the filesystem again: a directory swapped for an escaping link is refused", async () => { + const swap = join(root, "swap"); + mkdirSync(swap); + expect(await both(root, "swap/new.md", FINAL_FOLLOW)).toBe("brain/swap/new.md"); + renameSync(swap, join(base, "swapped-away")); + symlinkSync(outside, swap); + expect(await both(root, "swap/new.md", FINAL_FOLLOW)).toBe("refused escape"); + expect(await both(root, "swap/new.md", EVERY_REFUSE)).toBe("refused escape"); + }); +}); 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 64a4622294..15a40ca222 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"; @@ -627,7 +627,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 4c88a47772..ead82fde31 100644 --- a/packages/core/src/cli/commands/import.ts +++ b/packages/core/src/cli/commands/import.ts @@ -2,8 +2,10 @@ import { readFileSync, statSync } from "fs"; import { resolve } from "path"; 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"; @@ -33,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}`); } @@ -48,7 +50,9 @@ export const importCommand: CoreCommand = { const full = resolve(base, rel); try { const raw = readFileSync(full, "utf-8"); - if (raw.startsWith("---")) { + // Frontmatter as the indexer finds it (#2507): a byte order mark + // before the fence still counts, so that block is never stamped over. + if (frontmatterBlock(raw)) { skipped.push(rel); continue; } 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 31b0ddac58..3c3e09fdd5 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 { stringFlag } from "../flags.js"; import { parseArgs, UsageError } from "../io.js"; @@ -24,7 +24,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/document-parts.ts b/packages/core/src/lib/document-parts.ts index c5c96ec409..e9b1624913 100644 --- a/packages/core/src/lib/document-parts.ts +++ b/packages/core/src/lib/document-parts.ts @@ -3,6 +3,8 @@ import remarkGfm from "remark-gfm"; import remarkParse from "remark-parse"; import { unified } from "unified"; +import { frontmatterLength } from "@schlessera/brain-common/internal/frontmatter-block"; + import { caseFold } from "./case-fold.js"; import { estimateTokens } from "./chunker.js"; @@ -65,22 +67,10 @@ const parser = unified().use(remarkParse).use(remarkGfm); /** * Length of the frontmatter block, by the rule gray-matter applies when core - * reads a document: after a byte order mark, which gray-matter strips, the - * file opens with `---` not followed by a fourth `-`, and the block runs to - * the first `\n---` (to the end of the file if there is none), plus one line - * ending after it. The length counts the mark, so it is an offset into the - * original text. + * reads a document. It lives with `frontmatterBlock` next to `parseFrontmatter` + * in brain-common, so every site that finds the fences agrees (#2507). */ -export function frontmatterLength(text: string): number { - const bom = text.charCodeAt(0) === 0xfeff ? 1 : 0; - if (!text.startsWith("---", bom) || text.charAt(bom + 3) === "-") return 0; - const close = text.indexOf("\n---", bom + 3); - if (close === -1) return text.length; - let end = close + 4; - if (text[end] === "\r") end++; - if (text[end] === "\n") end++; - return end; -} +export { frontmatterLength } from "@schlessera/brain-common/internal/frontmatter-block"; interface LocatedHeading { level: number; diff --git a/packages/core/src/lib/frontmatter-edit.ts b/packages/core/src/lib/frontmatter-edit.ts index 94b370b2e4..f0e07cdfd9 100644 --- a/packages/core/src/lib/frontmatter-edit.ts +++ b/packages/core/src/lib/frontmatter-edit.ts @@ -14,48 +14,64 @@ */ import { parseFrontmatter } from "@schlessera/brain-common/internal/frontmatter"; +import { frontmatterBlock, frontmatterLength } from "@schlessera/brain-common/internal/frontmatter-block"; -import { frontmatterLength } from "./document-parts.js"; import { stringifyDocument } from "./frontmatter.js"; /** A new value: a string, a list of strings (written in flow style), or null to remove the key. */ export type FrontmatterValue = string | string[] | null; -interface Token { +/** A scalar's offsets in the block, quotes included, its quote, and its value with quotes and escapes read. */ +export interface ScalarToken { start: number; end: number; quote: '"' | "'" | null; + value: string; } -/** The frontmatter's inner text: after the opening `---` line, up to the closing `---` line. */ -function frontmatterBounds(text: string): { start: number; end: number } | null { - const length = frontmatterLength(text); - if (length === 0) return null; - // The first `\n---` after the opening fence, as frontmatterLength finds it: - // a later `---` or `----` line is a horizontal rule in the body. - const bom = text.charCodeAt(0) === 0xfeff ? 1 : 0; - const close = text.indexOf("\n---", bom + 3); - const start = text.indexOf("\n") + 1; - return close !== -1 && start > 0 && start <= close + 1 ? { start, end: close + 1 } : null; +type Token = Omit; + +/** + * The frontmatter's inner text: after the opening `---` line, up to the + * closing `---` line, by the fences `parseFrontmatter` reads (#2507). Null + * when there is no block, or when it is never closed: an edit cannot know + * where the body starts. `brain tags --apply` uses the same bounds. + */ +export function frontmatterBounds(text: string): { start: number; end: number } | null { + const block = frontmatterBlock(text); + return block?.closed ? { start: block.innerStart, end: block.innerEnd } : null; } -/** One scalar at `i`: quoted to its closing quote, or plain up to the line end or ` #`. */ -function readScalar(block: string, i: number): Token | null { - const quote = block[i]; +/** + * One scalar at `i`: quoted to its closing quote on the same line, or plain up + * to the line end, a character in `stops`, or ` #`. Null when there is none. + * Shared with `brain tags --apply`, which stops a flow entry at `,` and `]`. + */ +export function readScalar(text: string, i: number, stops = ""): ScalarToken | null { + const quote = text[i]; if (quote === '"' || quote === "'") { - for (let j = i + 1; j < block.length; j++) { - const c = block[j]; + let value = ""; + for (let j = i + 1; j < text.length; j++) { + const c = text[j]; if (c === "\n" || c === "\r") return null; - if (quote === '"' && c === "\\") j++; - else if (quote === "'" && c === "'" && block[j + 1] === "'") j++; - else if (c === quote) return { start: i, end: j + 1, quote }; + if (quote === '"' && c === "\\") { + const next = text[++j]; + value += next === "n" ? "\n" : next === "t" ? "\t" : next ?? ""; + } else if (quote === "'" && c === "'" && text[j + 1] === "'") { + value += "'"; + j++; + } else if (c === quote) { + return { start: i, end: j + 1, quote, value }; + } else { + value += c; + } } return null; } let j = i; - while (j < block.length && block[j] !== "\n" && block[j] !== "\r" && !/^[ \t]#/.test(block.slice(j, j + 2))) j++; - const raw = block.slice(i, j).replace(/[ \t]+$/, ""); - return raw ? { start: i, end: i + raw.length, quote: null } : null; + while (j < text.length && !stops.includes(text[j]!) && text[j] !== "\n" && text[j] !== "\r" && !/^[ \t]#/.test(text.slice(j, j + 2))) j++; + const raw = text.slice(i, j).replace(/[ \t]+$/, ""); + return raw ? { start: i, end: i + raw.length, quote: null, value: raw } : null; } /** A one-line flow sequence at `i`: up to its `]`, quoted entries skipped whole. */ diff --git a/packages/core/src/lib/generated-regions.ts b/packages/core/src/lib/generated-regions.ts index ae90c39ea0..75531dfee4 100644 --- a/packages/core/src/lib/generated-regions.ts +++ b/packages/core/src/lib/generated-regions.ts @@ -15,7 +15,8 @@ * and dashboard tables. */ -import { frontmatterLength } from "./document-parts.js"; +import { frontmatterBlock } from "@schlessera/brain-common/internal/frontmatter-block"; + import { codeRanges } from "./markdown-code.js"; /** A region name: lowercase letters, digits and dashes. */ @@ -124,14 +125,17 @@ export function replaceGeneratedRegion(body: string, name: string, content: stri * Split a file into its frontmatter block, kept verbatim (`---` fences * included), and its body. Frontmatter is never re-serialized: hand-written * YAML keeps its layout. Where the block starts follows the rule core reads - * documents by (`frontmatterLength`); a block that opens and never closes - * throws, since which part is the body cannot be known. + * documents by (`frontmatterBlock`, #2507); a block that opens and never + * closes throws, since which part is the body cannot be known. The + * frontmatter ends with the closing fence's three dashes; its line ending + * starts the body. */ export function splitFrontmatterBlock(raw: string): { frontmatter: string; body: string } { - if (frontmatterLength(raw) === 0) return { frontmatter: "", body: raw }; - const close = raw.indexOf("\n---", 3); - if (close === -1) throw new Error("frontmatter has no closing --- line"); - return { frontmatter: raw.slice(0, close + 4), body: raw.slice(close + 4) }; + const block = frontmatterBlock(raw); + if (!block) return { frontmatter: "", body: raw }; + if (!block.closed) throw new Error("frontmatter has no closing --- line"); + const fenceEnd = block.innerEnd + 3; + return { frontmatter: raw.slice(0, fenceEnd), body: raw.slice(fenceEnd) }; } /** diff --git a/packages/core/src/lib/hygiene.ts b/packages/core/src/lib/hygiene.ts index 029520c4db..67cb6853a9 100644 --- a/packages/core/src/lib/hygiene.ts +++ b/packages/core/src/lib/hygiene.ts @@ -17,6 +17,7 @@ import type { Database } from "bun:sqlite"; import { createHash } from "crypto"; import { closeSync, constants, existsSync, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, realpathSync } from "fs"; +import { frontmatterBlock } from "@schlessera/brain-common/internal/frontmatter-block"; import { parseFrontmatter } from "@schlessera/brain-common/internal/frontmatter"; import { join, posix, resolve } from "path"; import remarkGfm from "remark-gfm"; @@ -748,7 +749,6 @@ export class HygieneLogError extends Error {} /** An entry heading: `### ` and one token ending in the ID's `-hash4`. */ const ENTRY_HEADING = /^### +(\S+-[0-9a-f]{4})[ \t]*\r?$/; -const FRONTMATTER = /^---[ \t]*\r?\n[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$)/; /** A `## ` section of a log file, or (heading null) the text before the first one. */ interface Segment { @@ -771,14 +771,23 @@ interface LogFile { } /** - * The frontmatter and body of a log file. A file that opens a frontmatter - * block it does not close, or whose block is not a YAML mapping, is refused: - * rewriting it would mean guessing where the frontmatter ends. + * The frontmatter and body of a log file, by the fences the indexer reads + * (`frontmatterBlock`, #2507): a byte order mark before the opening fence + * still opens a block. A file that opens a block it does not close with a + * `---` line, or whose block is not a YAML mapping, is refused: rewriting it + * would mean guessing where the frontmatter ends. That is stricter than the + * indexer on purpose, because this rewrites the body. A closing fence with + * more than whitespace after its dashes (`----`, `---x`) is refused too: the + * indexer ends the block there, an author probably did not. The frontmatter + * keeps the closing line's trailing whitespace and line ending. */ function splitFrontmatter(text: string, rel: string): { frontmatter: string; body: string } { - if (!/^---[ \t]*\r?\n/.test(text)) return { frontmatter: "", body: text }; - const frontmatter = FRONTMATTER.exec(text)?.[0]; - if (!frontmatter) throw new HygieneLogError(`${rel}: the frontmatter is never closed with ---; fix it by hand, brain hygiene will not rewrite it`); + const block = frontmatterBlock(text); + if (!block) return { frontmatter: "", body: text }; + // After the closing dashes: optional whitespace, then a line ending or the end of the file. + const rest = block.closed ? /^[ \t]*(?:\r?\n|$)/.exec(text.slice(block.innerEnd + 3)) : null; + if (!rest) throw new HygieneLogError(`${rel}: the frontmatter is never closed with a --- line; fix it by hand, brain hygiene will not rewrite it`); + const frontmatter = text.slice(0, block.innerEnd + 3 + rest[0].length); let data: unknown; try { data = parseFrontmatter(frontmatter, { dataOnly: true }).data; 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/okf-exporter.ts b/packages/core/src/lib/okf-exporter.ts index a3f4128191..46b5cc8330 100644 --- a/packages/core/src/lib/okf-exporter.ts +++ b/packages/core/src/lib/okf-exporter.ts @@ -1,4 +1,5 @@ import { Glob } from "bun"; +import { frontmatterBlock } from "@schlessera/brain-common/internal/frontmatter-block"; import { parseFrontmatter, type ParsedFrontmatter } from "@schlessera/brain-common/internal/frontmatter"; import { existsSync, @@ -488,8 +489,9 @@ export async function exportOkfBundle(options: OkfExportOptions): Promise segment === ".." || segment.includes(":") || segment.includes("\\")); +} /** - * Resolve a relative path and verify it stays inside `root`, following + * Resolve a repo-relative path and verify it stays inside `root`, following * symlinks (realpath) so a symlink inside the repo can't escape it. - * The trailing-slash comparison rejects sibling-prefix paths like - * `../brain-other/x.md` that a bare startsWith(root) would accept. - * 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), 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 { - // A NUL byte would make the later fs call throw ERR_INVALID_ARG_VALUE — - // reject it as a containment failure, not a deferred TypeError. - if (relPath.includes("\0")) return 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; +} - let rootReal: string; +/** + * 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 { - rootReal = realpathSync(resolve(root)); + bases.push(realpathSync(root)); } catch { - return null; + // A root that does not resolve is refused by the resolver anyway. } - // Separator-aware containment check (backslash paths on Windows). - const contains = (p: string) => p === rootReal || p.startsWith(rootReal + sep); - const fullPath = resolve(rootReal, relPath); - if (!contains(fullPath)) return null; - // Canonicalize through symlinks. When the target (or a stretch of its - // parents) doesn't exist yet, canonicalize the nearest EXISTING ancestor and - // re-append the missing tail — a purely lexical fallback would let a - // symlinked parent directory smuggle a to-be-created file outside the root. - let existing = fullPath; - const tail: string[] = []; - // Symlink-hop budget: a dangling-link CYCLE (a→b, b→a) throws in realpath - // but resolves link-by-link here — bound it like the kernel does. - let hops = 0; - for (;;) { - let real: string; - try { - real = realpathSync(existing); - } catch { - // realpath failed: either the entry is genuinely absent, or it is a - // DANGLING symlink (exists, target missing). The two are different - // security cases — a write through a dangling link is created AT THE - // LINK TARGET, so it must be resolved and re-checked, never treated as - // "doesn't exist yet". - let linkTarget: string | null = null; - try { - if (lstatSync(existing).isSymbolicLink()) { - linkTarget = readlinkSync(existing); - } - } catch { - // lstat failed too → the entry really doesn't exist. - } - if (linkTarget !== null) { - if (++hops > 40) return null; - const resolvedTarget = isAbsolute(linkTarget) - ? resolve(linkTarget) - : resolve(dirname(existing), linkTarget); - // Re-enter containment checking with the link's target substituted in. - const rejoined = tail.length > 0 ? join(resolvedTarget, ...tail) : resolvedTarget; - if (!contains(rejoined)) return null; - existing = rejoined; - tail.length = 0; - continue; - } - tail.unshift(basename(existing)); - const parent = dirname(existing); - // The loop always terminates at rootReal (it exists), but guard the - // filesystem root anyway. - if (parent === existing) return null; - existing = parent; - continue; - } - const candidate = tail.length > 0 ? join(real, ...tail) : real; - if (!contains(candidate)) return null; - return candidate; + 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; } /** @@ -89,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/lib/scratch.ts b/packages/core/src/lib/scratch.ts index 3fff9f8cfc..02cd405c1b 100644 --- a/packages/core/src/lib/scratch.ts +++ b/packages/core/src/lib/scratch.ts @@ -46,10 +46,14 @@ import { import type { Stats } from "fs"; import { tmpdir } from "os"; import { basename, dirname, join, relative, resolve, sep } from "path"; +import { BRAIN_SCRATCH_DIR } from "@schlessera/brain-common/internal/worker-areas"; import { modeOf, WriteRefusedError, writeExclusive, writeFileSafely } from "./safe-path.js"; -/** Repo-relative scratch directory. Every mechanism that needs it reads this. */ -export const SCRATCH_DIR = ".brain/scratch"; +/** + * Repo-relative scratch directory. Every mechanism that needs it reads this; + * the value is the one the SDK and server share (`BRAIN_SCRATCH_DIR`, #2506). + */ +export const SCRATCH_DIR = BRAIN_SCRATCH_DIR; /** Files older than this are pruned. */ export const SCRATCH_TTL_MS = 7 * 24 * 60 * 60 * 1000; diff --git a/packages/core/src/lib/tags-apply.ts b/packages/core/src/lib/tags-apply.ts index bb41ee643a..900d4f41e4 100644 --- a/packages/core/src/lib/tags-apply.ts +++ b/packages/core/src/lib/tags-apply.ts @@ -16,7 +16,7 @@ import { createHash } from "crypto"; import { readFileSync } from "fs"; import { resolve } from "path"; -import { frontmatterLength } from "./document-parts.js"; +import { frontmatterBounds, readScalar, type ScalarToken as Token } from "./frontmatter-edit.js"; import { getMarkdownFiles, indexAll } from "./indexer.js"; import { inCanonicalDir, writeFileSafely } from "./safe-path.js"; import type { Database } from "bun:sqlite"; @@ -148,60 +148,6 @@ export function isRedundant(doc: { path: string; type: string | null }, tag: str // Raw frontmatter editing // --------------------------------------------------------------------------- -/** - * Where the frontmatter's inner text lies: between the opening `---` line and - * the closing `---`, by the span `frontmatterLength` measures with - * gray-matter's rule (a leading byte order mark included). - */ -function frontmatterBounds(text: string): { start: number; end: number } | null { - const length = frontmatterLength(text); - if (length === 0) return null; - const close = text.lastIndexOf("\n---", length); - const start = text.indexOf("\n") + 1; - return close !== -1 && start > 0 && start <= close + 1 ? { start, end: close + 1 } : null; -} - -interface Token { - /** Offsets of the scalar in the block text, quotes included. */ - start: number; - end: number; - value: string; -} - -/** Read one scalar at `i`: quoted, or plain up to a stop character or ` #`. */ -function readScalar(text: string, i: number, stops: string): Token | null { - const quote = text[i]; - if (quote === '"' || quote === "'") { - let j = i + 1; - let value = ""; - while (j < text.length) { - const c = text[j]; - if (quote === "'" && c === "'" && text[j + 1] === "'") { - value += "'"; - j += 2; - } else if (quote === '"' && c === "\\") { - const next = text[j + 1]; - value += next === "n" ? "\n" : next === "t" ? "\t" : next; - j += 2; - } else if (c === quote) { - return { start: i, end: j + 1, value }; - } else if (c === "\n" || c === "\r") { - return null; - } else { - value += c; - j++; - } - } - return null; - } - let j = i; - while (j < text.length && !stops.includes(text[j]) && !"\r\n".includes(text[j]) && !/^[ \t]#/.test(text.slice(j, j + 2))) { - j++; - } - const raw = text.slice(i, j).replace(/[ \t]+$/, ""); - return raw ? { start: i, end: i + raw.length, value: raw } : null; -} - /** A tag as YAML: plain when that reads back as the same string, else double-quoted. */ function yamlScalar(tag: string): string { const plain = diff --git a/packages/core/src/lib/validate.ts b/packages/core/src/lib/validate.ts index 9c531ae46e..e3504670ed 100644 --- a/packages/core/src/lib/validate.ts +++ b/packages/core/src/lib/validate.ts @@ -14,6 +14,7 @@ * the taxonomy so validation and the indexer's link graph agree exactly. */ +import { frontmatterBlock } from "@schlessera/brain-common/internal/frontmatter-block"; import { parseFrontmatter } from "@schlessera/brain-common/internal/frontmatter"; import { readFileSync, existsSync } from "fs"; import { resolve } from "path"; @@ -148,8 +149,9 @@ export function validateDetailed(root: string, taxonomy: Taxonomy): DetailedVali const fullPath = resolve(root, filePath); const raw = readFileSync(fullPath, "utf-8"); - // Check for frontmatter - if (!raw.startsWith("---")) { + // Check for frontmatter, by the fences the indexer reads (#2507): a + // byte order mark before them is fine, a `----` line is not a fence. + if (!frontmatterBlock(raw)) { issues.push({ file: filePath, level: "error", diff --git a/packages/core/src/module.ts b/packages/core/src/module.ts index 8fa334ff23..53bbc75acd 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-onboarding.test.ts b/packages/core/tests/cli-onboarding.test.ts index ce05dff43c..c944a2c5be 100644 --- a/packages/core/tests/cli-onboarding.test.ts +++ b/packages/core/tests/cli-onboarding.test.ts @@ -110,6 +110,22 @@ test("import --stamp adds frontmatter to bare markdown", async () => { expect(stamped).toContain("status: draft"); }); +test("import --stamp skips frontmatter after a byte order mark instead of stamping over it (#2507)", async () => { + const root = tempBrain(); + const importDir = join(root, "import", "vault"); + mkdirSync(importDir, { recursive: true }); + const marked = "\uFEFF---\ntype: note\ntitle: Already\n---\nbody\n"; + writeFileSync(join(importDir, "marked.md"), marked); + writeFileSync(join(importDir, "rule.md"), "----\n\nA rule, not a fence.\n"); + + const { stdout, code } = await runCli(root, ["import", "--stamp", "import/vault", "--json"]); + expect(code).toBe(0); + const out = JSON.parse(stdout); + expect(out.skipped).toEqual(["marked.md"]); + expect(out.stamped).toEqual(["rule.md"]); + expect(readFileSync(join(importDir, "marked.md"), "utf-8")).toBe(marked); +}); + test("skills lint fails on a broken fixture skill", async () => { const root = tempBrain(); const skillDir = join(root, ".agents", "skills", "broken-skill"); 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 new file mode 100644 index 0000000000..c36ffd9054 --- /dev/null +++ b/packages/core/tests/containment-rows.test.ts @@ -0,0 +1,189 @@ +/** + * core's row of the resolver matrix (#2506): `safeResolve(root, rel)` is + * 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"; +import { tmpdir } from "os"; +import { join, relative } from "path"; + +import { SCRATCH_DIR } from "../src/lib/scratch"; +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 })); +const root = join(base, "brain"); +const outside = join(base, "brain-other"); + +mkdirSync(join(root, "notes/sub"), { recursive: true }); +mkdirSync(outside); +mkdirSync(join(root, ".brain/scratch"), { recursive: true }); +writeFileSync(join(root, "notes/a.md"), "a"); +writeFileSync(join(root, "file.md"), "f"); +writeFileSync(join(outside, "secret.md"), "s"); +writeFileSync(join(root, ".brain/scratch/s.txt"), "s"); +symlinkSync("notes", join(root, "link-in")); +symlinkSync(outside, join(root, "link-out")); +symlinkSync("notes/missing", join(root, "dangling-in")); +symlinkSync(join(outside, "missing"), join(root, "dangling-out")); +symlinkSync("cycle-b", join(root, "cycle-a")); +symlinkSync("cycle-a", join(root, "cycle-b")); +symlinkSync(outside, join(root, "bounce")); +symlinkSync(join(root, "notes"), join(outside, "back")); +symlinkSync("../../notes", join(root, ".brain/scratch/link")); +symlinkSync(root, join(base, "root-link")); +// A dangling chain that leaves the root and comes back to a missing target inside. +symlinkSync(join(root, "notes/missing"), join(outside, "dangling-back")); +symlinkSync(join(outside, "dangling-back"), join(root, "dangling-bounce")); + +/** The answer relative to the fixture base, or `refused`. */ +const answer = (path: string | null) => (path === null ? "refused" : relative(base, path) || "."); + +describe("core safeResolve(root, rel): its resolver row", () => { + const rows: [string, string][] = [ + ["notes/a.md", "brain/notes/a.md"], + ["notes/new.md", "brain/notes/new.md"], + ["a/b/c.md", "brain/a/b/c.md"], + ["", "brain"], + [".", "brain"], + ["./notes/a.md", "brain/notes/a.md"], + ["notes//a.md", "brain/notes/a.md"], + ["notes/a.md/", "brain/notes/a.md"], + ["file.md/x", "brain/file.md/x"], + // `..` 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: refused even inside the root (#3422). + [join(root, "notes/a.md"), "refused"], + [root, "refused"], + ["/etc/passwd", "refused"], + // 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. + ["link-in/a.md", "brain/notes/a.md"], + ["link-in/new.md", "brain/notes/new.md"], + ["link-out/secret.md", "refused"], + ["link-out/new.md", "refused"], + // 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"], + // 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"], + [".brain/scratch/link", "brain/notes"], + [".brain/scratch/link/a.md", "brain/notes/a.md"], + ]; + for (const [rel, expected] of rows) { + test(`${JSON.stringify(rel.startsWith(base) ? "/" + relative(base, rel) : rel)} -> ${expected}`, () => { + expect(answer(safeResolve(root, rel))).toBe(expected); + }); + } + + test("a root that is itself a symlink resolves against its target", () => { + expect(answer(safeResolve(join(base, "root-link"), "notes/a.md"))).toBe("brain/notes/a.md"); + }); + + test("a root whose realpath fails refuses everything", () => { + expect(safeResolve(join(base, "nope"), "notes/a.md")).toBeNull(); + expect(safeResolve(join(root, "dangling-in"), "x")).toBeNull(); + expect(safeResolve(join(root, "file.md/x"), "x")).toBeNull(); + }); + + test("each call reads the filesystem again: a directory swapped for an escaping link is refused", () => { + const swap = join(root, "swap"); + mkdirSync(swap); + expect(answer(safeResolve(root, "swap/new.md"))).toBe("brain/swap/new.md"); + renameSync(swap, join(base, "swapped-away")); + symlinkSync(outside, swap); + expect(safeResolve(root, "swap/new.md")).toBeNull(); + rmSync(swap); + renameSync(join(base, "swapped-away"), swap); + expect(answer(safeResolve(root, "swap/new.md"))).toBe("brain/swap/new.md"); + }); +}); + +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/frontmatter-fences.test.ts b/packages/core/tests/frontmatter-fences.test.ts new file mode 100644 index 0000000000..5637c4a060 --- /dev/null +++ b/packages/core/tests/frontmatter-fences.test.ts @@ -0,0 +1,85 @@ +/** + * Core's raw frontmatter editors find the block through `frontmatterBlock`, + * the rule `parseFrontmatter` reads by (#2507): the generated-region splitter, + * the key editor and `brain tags --apply` (which share one `frontmatterBounds` + * and one `readScalar`). + */ + +import { describe, expect, test } from "bun:test"; + +import { editFrontmatter, frontmatterBounds, readScalar, type ScalarToken } from "../src/lib/frontmatter-edit"; +import { splitFrontmatterBlock } from "../src/lib/generated-regions"; +import { rewriteTags } from "../src/lib/tags-apply"; + +const BOM = "\uFEFF"; + +describe("splitFrontmatterBlock", () => { + test.each([ + ["LF", "---\ntitle: a\n---\nbody\n", "---\ntitle: a\n---", "\nbody\n"], + ["a byte order mark", `${BOM}---\ntitle: a\n---\nbody\n`, `${BOM}---\ntitle: a\n---`, "\nbody\n"], + ["CRLF", "---\r\ntitle: a\r\n---\r\nbody\r\n", "---\r\ntitle: a\r\n---", "\r\nbody\r\n"], + ["a closing fence at the end of the file", "---\ntitle: a\n---", "---\ntitle: a\n---", ""], + ["a rule right after the closing fence", "---\ntitle: a\n---\n---\nbody\n", "---\ntitle: a\n---", "\n---\nbody\n"], + ["a leading blank line", "\n---\ntitle: a\n---\n", "", "\n---\ntitle: a\n---\n"], + ["a four-dash first line", "----\ntitle: a\n", "", "----\ntitle: a\n"], + ])("%s", (_, raw, frontmatter, body) => { + expect(splitFrontmatterBlock(raw)).toEqual({ frontmatter, body }); + }); + + test("a block that is never closed is refused", () => { + expect(() => splitFrontmatterBlock("---\ntitle: a\nbody\n")).toThrow("no closing --- line"); + expect(() => splitFrontmatterBlock(`${BOM}---\ntitle: a\n`)).toThrow("no closing --- line"); + }); +}); + +describe("frontmatterBounds, shared by the key editor and brain tags --apply", () => { + test.each([ + ["LF", "---\ntitle: a\n---\nbody\n", "title: a\n"], + ["a byte order mark", `${BOM}---\ntitle: a\n---\nbody\n`, "title: a\n"], + ["CRLF", "---\r\ntitle: a\r\n---\r\nbody\r\n", "title: a\r\n"], + ["a closing fence at the end of the file", "---\ntitle: a\n---", "title: a\n"], + // The copy in tags-apply searched back from the block's end, so this one + // took the closing fence into the block. + ["a rule right after the closing fence", "---\ntitle: a\n---\n---\nbody\n", "title: a\n"], + ["an empty block", "---\n---\nbody\n", ""], + ])("%s", (_, text, inner) => { + const bounds = frontmatterBounds(text); + expect(bounds && text.slice(bounds.start, bounds.end)).toBe(inner); + }); + + test("no block, or one never closed, has no bounds", () => { + for (const text of ["\n---\ntitle: a\n---\n", "----\ntitle: a\n----\n", "---\ntitle: a\n", "---\ntitle: a\n...\n"]) { + expect(frontmatterBounds(text)).toBeNull(); + } + }); + + test("the key editor keeps a byte order mark and an end-of-file fence", () => { + expect(editFrontmatter(`${BOM}---\ntitle: a\n---\nbody\n`, { title: "b" })).toBe(`${BOM}---\ntitle: b\n---\nbody\n`); + expect(editFrontmatter("---\ntitle: a\n---", { title: "b" })).toBe("---\ntitle: b\n---"); + }); + + test("brain tags --apply rewrites the tags after a byte order mark and before a rule", () => { + expect(rewriteTags(`${BOM}---\ntitle: T\ntags: [old]\n---\nbody\n`, () => ["new"])).toEqual({ + text: `${BOM}---\ntitle: T\ntags: [new]\n---\nbody\n`, from: ["old"], to: ["new"], + }); + expect(rewriteTags("---\ntitle: T\ntags:\n - old\n---\n---\nbody\n", () => ["new"])).toEqual({ + text: "---\ntitle: T\ntags:\n - new\n---\n---\nbody\n", from: ["old"], to: ["new"], + }); + }); +}); + +describe("readScalar, the one scalar reader both editors use", () => { + test.each<[string, string, string, ScalarToken]>([ + ["a plain scalar up to a comment", "abc # note", "", { start: 0, end: 3, quote: null, value: "abc" }], + ["a plain scalar up to a stop", "abc, def", ",]", { start: 0, end: 3, quote: null, value: "abc" }], + ["a double-quoted scalar with escapes", '"a\\"b\\n"', "", { start: 0, end: 8, quote: '"', value: 'a"b\n' }], + ["a single-quoted scalar with a doubled quote", "'it''s'", "", { start: 0, end: 7, quote: "'", value: "it's" }], + ])("%s", (_, text, stops, token) => { + expect(readScalar(text, 0, stops)).toEqual(token); + }); + + test("a quote not closed on its line, or nothing to read, is null", () => { + expect(readScalar('"open\n"', 0)).toBeNull(); + expect(readScalar(" # only a comment", 0)).toBeNull(); + }); +}); diff --git a/packages/core/tests/hygiene.test.ts b/packages/core/tests/hygiene.test.ts index b318245da6..77df170415 100644 --- a/packages/core/tests/hygiene.test.ts +++ b/packages/core/tests/hygiene.test.ts @@ -710,9 +710,27 @@ describe("writing the log", () => { expect(read(root, "resolved.md")).toContain(`### ${idOf(goes)}\n${seen}\n\nAsked about this on Monday.\n- resolved-by: auto-disappeared`); }); + test("a log file whose frontmatter follows a byte order mark keeps it as frontmatter (#2507)", () => { + const root = tempRoot(); + const seen = "- **First seen**: 2026-06-01 · **Last seen**: 2026-06-01"; + const frontmatter = '\uFEFF---\ntype: context\ntitle: "Open"\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n'; + mkdirSync(join(root, "context/hygiene"), { recursive: true }); + writeFileSync(log(root, "open.md"), `${frontmatter}\n## TODO markers\n\n${entry(idOf(goes), seen)}\n`); + expect(reconcile(root, [], docs, { now: NOW })).toMatchObject({ resolved: 1 }); + // The block is read where the indexer reads it: kept, mark included, with only `updated` set. + expect(read(root, "open.md")).toStartWith(frontmatter.replace("updated: 2026-01-01", `updated: ${TODAY}`)); + expect(read(root, "open.md")).not.toContain(`### ${idOf(goes)}`); + expect(read(root, "resolved.md")).toContain(`### ${idOf(goes)}`); + }); + test.each([ ["frontmatter that is not valid YAML", '---\ntitle: "unclosed\nupdated: 2026-01-01\n---\n\n## Resolved\n', "not valid YAML"], ["frontmatter that is never closed", "---\ntitle: Resolved\n\n## Resolved\n", "never closed"], + // The indexer ends these blocks at the dashes; an author probably did not (#2507). + ["a closing fence with text after its dashes", "---\ntitle: Resolved\n---x\n\n## Resolved\n---\n", "never closed"], + ["a four-dash closing line", "---\ntitle: Resolved\n----\n\n## Resolved\n---\n", "never closed"], + ["a ... closing line", "---\ntitle: Resolved\n...\n\n## Resolved\n", "never closed"], + ["a byte order mark before a block that is never closed", "\uFEFF---\ntitle: Resolved\n\n## Resolved\n", "never closed"], ["frontmatter that is a list, not a mapping", "---\n- one\n- two\n---\n\n## Resolved\n", "not a YAML mapping"], ["a section holding entries and other text", "## Parked\n\nA note.\n\n### todo-notes-goes-abcd\n- resolved-by: manual\n", 'section "## Parked"'], ])("a log file with %s is refused, and nothing is written", (_, text, message) => { diff --git a/packages/core/tests/okf-exporter.test.ts b/packages/core/tests/okf-exporter.test.ts index a476460af1..ee0c1e81d2 100644 --- a/packages/core/tests/okf-exporter.test.ts +++ b/packages/core/tests/okf-exporter.test.ts @@ -348,4 +348,14 @@ describe("OKF checker", () => { expect(errorReport.ok).toBe(false); expect(errorReport.errors).toBeGreaterThanOrEqual(4); }); + + test("finds frontmatter after a byte order mark, as the parser reads it (#2507)", () => { + const root = makeBrain({ + "index.md": "\uFEFF---\ntitle: Not allowed\n---\n# Bundle\n\n* [Concept](concept.md)\n", + "concept.md": `\uFEFF${document("Concept", "Body.")}`, + }); + const messages = checkOkfBundle(root).issues.map((issue) => `${issue.path}: ${issue.message}`); + expect(messages).toContain("index.md: index.md must not have frontmatter (except root okf_version only)"); + expect(messages).not.toContain("concept.md: concept document is missing YAML frontmatter"); + }); }); 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/core/tests/validate.test.ts b/packages/core/tests/validate.test.ts index c5c8a73538..c5a785be05 100644 --- a/packages/core/tests/validate.test.ts +++ b/packages/core/tests/validate.test.ts @@ -62,6 +62,17 @@ describe("validate", () => { }); }); + test("accepts frontmatter after a byte order mark, as the indexer reads it (#2507)", () => { + const fields = { type: "identity", title: "Identity", created: '"2026-01-01"', updated: '"2026-01-02"', tags: "[me]" }; + const root = makeCorpus({ "me/identity.md": `\uFEFF${doc(fields)}` }); + expect(validate(root, taxonomy).filter((i) => i.level === "error")).toEqual([]); + }); + + test("a four-dash first line is not frontmatter (#2507)", () => { + const root = makeCorpus({ "notes/raw.md": "----\ntitle: x\n----\nbody\n" }); + expect(validate(root, taxonomy)).toContainEqual({ file: "notes/raw.md", level: "error", message: "Missing YAML frontmatter" }); + }); + test("reports an invalid type and lists the taxonomy's valid types", () => { const root = makeCorpus({ "notes/x.md": doc({ type: "bogus", title: "X", tags: "[a]" }), 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