From ecd7422f6b0cf3b80c9b275d8525af1ddb96c363 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Galarowicz?= Date: Wed, 25 Nov 2026 17:31:07 +0100 Subject: [PATCH 1/8] fix(tar-extract): unpack only the manifest's listed paths, skip every other entry (CORE-386) pharn-oss v7.25.3-v7.25.5 commit seven symlinks under .claude/skills/, outside pharn-install.json, and the extractor refused any non-file entry anywhere in the archive, so every init/add/update/status failed on every channel. The extractor now selects, then judges: two streamed passes over the archive write only the files the CLI reads itself (CLONE_READ_FILES) and then, once the manifest has validated, only the paths it lists. Every other entry is skipped and never written, whatever its type or name. A listed path keeps every rule (regular file, strict UTF-8, no control/format char, no absolute/../\/:, one root, no duplicate) and a pax/GNU-modified entry at a listed path is refused; verifyUpstreamManifest still fails a listed file that is missing or altered. The tar is streamed through createGunzip, so the 128 MB cap now bounds bytes written; headers (200k) and decompressed bytes (1 GiB) bound the walk. extractPharnArchive takes a buffer, for a later local verify-archive mode. Docs (CLAUDE.md, architecture, contributing, SECURITY, THREAT-MODEL via the user's patch) and CHANGELOG [Unreleased] updated. Co-Authored-By: Claude Opus 5.5 --- .../GRILL.md | 38 + .../core-386-unpack-listed-paths-only/PLAN.md | 169 +++ .../REGRESSION.md | 19 + .../REVIEW.md | 33 + .../core-386-unpack-listed-paths-only/SHIP.md | 16 + .../VERIFY.md | 22 + .../regression-report.json | 44 + .../verify-report.json | 14 + CHANGELOG.md | 8 + CLAUDE.md | 11 +- SECURITY.md | 4 +- THREAT-MODEL.md | 83 +- docs/architecture.md | 11 +- docs/contributing.md | 20 +- src/lib/repo.ts | 113 +- src/lib/tar-extract.ts | 438 ++++--- src/lib/upstream-manifest.ts | 33 +- tests/commands/init.test.ts | 7 +- tests/project-lock.test.ts | 18 +- tests/repo.test.ts | 198 ++- tests/tar-extract.test.ts | 1101 +++++++++-------- tests/upstream-manifest.test.ts | 26 +- 22 files changed, 1647 insertions(+), 779 deletions(-) create mode 100644 .dev/features/core-386-unpack-listed-paths-only/GRILL.md create mode 100644 .dev/features/core-386-unpack-listed-paths-only/PLAN.md create mode 100644 .dev/features/core-386-unpack-listed-paths-only/REGRESSION.md create mode 100644 .dev/features/core-386-unpack-listed-paths-only/REVIEW.md create mode 100644 .dev/features/core-386-unpack-listed-paths-only/SHIP.md create mode 100644 .dev/features/core-386-unpack-listed-paths-only/VERIFY.md create mode 100644 .dev/features/core-386-unpack-listed-paths-only/regression-report.json create mode 100644 .dev/features/core-386-unpack-listed-paths-only/verify-report.json diff --git a/.dev/features/core-386-unpack-listed-paths-only/GRILL.md b/.dev/features/core-386-unpack-listed-paths-only/GRILL.md new file mode 100644 index 00000000..ee279029 --- /dev/null +++ b/.dev/features/core-386-unpack-listed-paths-only/GRILL.md @@ -0,0 +1,38 @@ +# GRILL — core-386-unpack-listed-paths-only + +Advisory (`/pharn-dev-grill` gates nothing). Spec hash: recomputed `bca940a5…3c4e`, equal to the plan's. + +```yaml +- type: FINDING + rule_id: P0 + severity: important + file: 'PLAN.md:Design step 2' + problem: 'Moving the layout-marker check from the tree to the manifest is only equivalent if nothing but listed files can create pharn/pharn-contracts.' + evidence: 'Pass 1 writes four root-level or .claude files only; pass 2 writes only listed paths. Say so in the code comment and keep the init test that pins the refusal.' +- type: FINDING + rule_id: P1 + severity: important + file: 'PLAN.md:Evals' + problem: 'Real gunzip chunks are 16 KiB, a multiple of 512, so a header never straddles a chunk in production and the carry path would go untested.' + evidence: 'Plan names odd-sized chunk tests via extractTar(readonly Buffer[]); make them byte-identical comparisons, and cover a payload split across chunks.' +- type: FINDING + rule_id: P2 + severity: minor + file: 'PLAN.md:Design (selection key)' + problem: 'The root segment of a selected entry is attacker bytes that reach a refusal message (second root, absolute).' + evidence: 'Keep assertDisplayablePath before any message that interpolates the full path, exactly as today.' +- type: FINDING + rule_id: P0 + severity: minor + file: 'PLAN.md:Caps' + problem: "A scanned-bytes cap is not in the ticket's list; justify it so it is not read as reintroducing the repo-size failure." + evidence: "1 GiB is 24x today's real archive (43 MB) and only bounds a compression bomb's CPU; name it in the CHANGELOG/SECURITY text." +- type: FINDING + rule_id: P7 + severity: minor + file: 'PLAN.md:Files (repo.ts)' + problem: 'extractPharnArchive is exported for a command that does not exist yet (CORE-387).' + evidence: 'Acceptable: the ticket asks for that shape; it is also what fetchAt calls, so it is not dead code.' +``` + +Verdict: proceed (advisory). All five folded into the build. diff --git a/.dev/features/core-386-unpack-listed-paths-only/PLAN.md b/.dev/features/core-386-unpack-listed-paths-only/PLAN.md new file mode 100644 index 00000000..89985deb --- /dev/null +++ b/.dev/features/core-386-unpack-listed-paths-only/PLAN.md @@ -0,0 +1,169 @@ +# PLAN — core-386-unpack-listed-paths-only (Linear CORE-386, epic CORE-380) + +- spec_content_hash: bca940a5ad247c120e6d8a3acba119d0d8df51dca275964d0e54c48d729d3c4e # fix #4 +- increment: the extractor writes ONLY the paths `pharn-install.json` lists plus the four files the CLI reads + itself; every other archive entry is skipped unwritten, whatever its type or name. Listed paths keep today's rules, + and `verifyUpstreamManifest`'s hash check still fails a listed file that is missing or altered. +- base: origin/main @ 51a96d29. Branch `feat/core-386-unpack-listed-paths-only`, built in the worktree + `/Users/pgalarowicz/Projects/pharn-cli-core-386`. +- layer(s): CLI source (`src/lib/tar-extract.ts`, `src/lib/repo.ts`, `src/lib/upstream-manifest.ts`), tests, docs + (`CLAUDE.md`, `docs/architecture.md`, `docs/contributing.md`, `SECURITY.md`, `CHANGELOG.md`), trusted doc + `THREAT-MODEL.md` (hook-protected → patch script for the human). +- constitution_refs: [P0, P1, P2, P4, P5, P7] + +## Why (live state, measured 2026-11-25) + +pharn-oss v7.25.5's codeload archive: 4,939 entries (4,149 files, 783 dirs, 7 symlinks under `.claude/skills/`), +43.0 MB decompressed, 11.5 MB compressed. Its manifest lists 616 files. Today's extractor applies its strict rules to +EVERY entry, so the 7 unlisted symlinks refuse every install on every channel. The CLI reads, beyond the manifest's +list, exactly: `pharn-install.json`, `SKILLS_VERSION` and `MIN_CLI` (both unlisted in v7.25.5), and +`.claude/settings.json` (listed `if-absent` in v7.25.5, but `hook-wiring` reads it whether or not it is listed). + +## Design + +Two passes over the in-memory `.tar.gz` (already capped at 32 MB by `fetchCapped`), each streamed through +`zlib.createGunzip()`, so the decompressed tar is never held whole (today `gunzipSync` holds it, which is why the +128 MB cap had to bound the whole repo). + +1. **Pass 1** writes only `CLONE_READ_FILES` = `pharn-install.json`, `SKILLS_VERSION`, `MIN_CLI`, + `.claude/settings.json` (each only if the archive has it). +2. The release check (`SKILLS_VERSION` = tag) runs, then `readUpstreamManifest(dir)` validates the manifest exactly + as today (the one parser). +3. **Pass 2** writes only the manifest's `files[].path` not already written by pass 1. +4. `verifyUpstreamManifest(dir, manifest)` as today. + +The extractor's walk, per header (every header, any type): checksum, `ustar` magic, octal `size`, the header cap, the +scanned-bytes cap, the end-of-archive marker and zero tail. These are framing: without them the walk cannot find the +next header, so they stay refusals for any entry. Nothing else is judged on an unselected entry. + +Selection key: the raw `prefix`/`name` bytes (latin1, lossless), with everything up to the first `/` stripped. Every +selected path is ASCII (manifest paths pass `MANIFEST_PATH_RE`; the four constants are ASCII), so an exact +membership test on the raw bytes is exact. A header whose key is selected gets TODAY's rules: strict UTF-8 decode, +the control/format-character refusal, regular file only (`0`/NUL), absolute / `..` / `\` / `:` / empty-or-`.` +segment refused, one root (shared by both passes), strip-1, `safeJoin`. A selected path appearing twice is refused. + +Pax `x` and GNU `L`/`K` (the headers that modify the NEXT entry's path/size): skipped, and the entry they modify is +skipped as unlisted. If that modified entry's ustar name is a selected path → refused ("pax data on a listed path"; +pharn does not honour pax records). If an `x`/`L`/`K`/`g` header's OWN name is a selected path → refused (not a +regular file). If the pax record renamed a listed file away from its ustar name, that file is missing and the hash +check fails. + +Caps (`repo.ts`): download 32 MB (unchanged), headers scanned 200,000 (any type, both passes), decompressed bytes +scanned 1 GiB (bounds a compression bomb's CPU now that memory is no longer the bound), bytes WRITTEN 128 MB +(checked at each selected header, before its payload is collected). Files written are bounded by the selection +(manifest ≤ 20,000 files + 4). + +API shaped for CORE-387 (`pharn verify-archive `): `extractTarGz(archive: Buffer, destDir, +{ select, limits, root? })` takes a buffer, never a URL; `repo.ts` exports `extractPharnArchive(archive, dir, +checkTree?)` (passes 1-2, manifest validation, hash check), which `fetchAt` calls after the download and a local-file +mode can call with no network. `TarExtractError` keeps its name and export; every refusal still names the entry path +and the rule. + +## Files + +- `src/lib/tar-extract.ts` — rewritten walker — layer CLI lib (fetch boundary): + - an incremental `TarWalker` (push chunks / finish) shared by `extractTar(tar: Buffer | readonly Buffer[], …)` + (sync, for tests and chunk-boundary tests) and `async extractTarGz(archive, …)` (streams `createGunzip`); + - `ExtractOptions { select: ReadonlySet; limits: TarLimits; root?: string }`, + `TarLimits { maxHeaders; maxScannedBytes; maxWrittenBytes }`, result `{ written: Set; bytes: number; +root: string | null }`; + - the selection, modifier (`x`/`L`/`K`) and duplicate rules above; `resolveEntryPath`, `readPathField`, + `assertDisplayablePath`, `readOctal`, `checksumOk`, `describeBytes`, `describeTypeflag` kept; + - module header rewritten: what is judged on every header (framing) vs only on a selected one, and why skipping is + strictly safer (nothing unselected touches disk). +- `src/lib/repo.ts` — `CLONE_READ_FILES`; `extractPharnArchive` (exported); `fetchAt` calls it; limits + `MAX_HEADERS`, `MAX_SCANNED_BYTES`, `MAX_WRITTEN_BYTES` replace `MAX_ENTRIES`/`MAX_EXTRACTED_BYTES`; the clone + invariant comment on `FetchedRepo` restated (files + dirs only, and only the listed + CLI-read files). +- `src/lib/upstream-manifest.ts` — `checkLayout`'s tree probe (`isPharnLayout(repoDir)`) also accepts the manifest's + own `files` listing a path under `pharn/pharn-contracts/` (amended at build: tree OR listing, so on-disk fixtures + that hold the marker dir keep passing), run after `checkFiles`, so the manifest can be fully + validated between the passes, before the tree holds anything it lists. Equivalent after extraction: the tree now + holds the marker iff a listed file is under it (and the hash check proves every listed file is there). + `MAX_MANIFEST_FILES` comment updated. Header comment: the tree holds only the listed files plus the CLI-read ones. +- `tests/tar-extract.test.ts` — rewritten to the new API. Kept (on a selected path): every framing refusal, every + path rule, UTF-8/format-character refusals, prefix reassembly, the base-256 cases, non-ASCII names. Inverted: + "rejects %s entry outright, rather than skipping it" becomes two blocks — OUTSIDE the selection (symlink, hard + link, char/block device, fifo, pax `x`, GNU `L`/`K`, unknown type, long pax-renamed name, `:` / `\` name, invalid + UTF-8, control characters, absolute, `..`, second root, no root) → extraction succeeds and writes nothing for that + entry; AT a selected path → refused. The comment records why the decision was narrowed (degit's silent skip lost + LISTED files; the manifest hash check now catches a missing or altered listed file). NEW: pax `x` before a selected + path → refused; pax `x` before an unselected path → both skipped; duplicate selected path → refused; header cap, + scanned-bytes cap, written-bytes cap; chunk boundaries (odd-sized chunks give identical output); the + only-files-and-dirs property over the result. +- `tests/repo.test.ts` — NEW: a tree whose archive carries an unlisted symlink, hard link, pax `x` + long-named + entry, and `:` name installs and none of them is written; the same entry AT a listed path refuses (symlink at a + listed path, pax `x` before a listed path) or fails the hash check (a pax-renamed listed file → "does not ship as a + file"); an unlisted file is not in the returned tree; `extractPharnArchive` over a local buffer (no fetch). +- `tests/upstream-manifest.test.ts` — the marker case (manifest lists nothing under `pharn/pharn-contracts`), if a + unit case exists; else covered by `tests/commands/init.test.ts`. +- `tests/project-lock.test.ts` — (added at build) the signal children's `signalHandled` helper holds the event loop + open with a ref'd timer until the handlers ran. The SIGINT-after-fetch child exited 13 (unsettled top-level await) + once `fetchRepo` became streamed: Node's signal handles are unref'd, and the base run had only passed because a + tsx IPC `ConnectWrap` happened to still be pending. Test harness only; no assertion changes. +- `tests/commands/init.test.ts` — the marker test's expected message → "lists no file under pharn/pharn-contracts". +- `CLAUDE.md` — "The clone is data" bullet: the extractor writes only the manifest's listed paths plus the CLI-read + files, as regular files and directories; every other entry is skipped unwritten. +- `docs/architecture.md` — step 3 (Source): the two passes and what the tree holds. +- `docs/contributing.md` — the fetch-boundary section and the "Security-sensitive files" bounds bullet (caps), the + `tar-extract.test.ts` row; the "symlinked sources" claim at line 147 is stale since CORE-173 and is fixed in passing. +- `SECURITY.md` — the "Archive parsing" paragraph (selected vs skipped, the new caps, pax rule) and line 61. +- `CHANGELOG.md` — `## [Unreleased]` `### Fixed` bullet (installs and updates no longer fail on a symlink, hard link, + pax header, long or `:` name, or repo size outside the listed paths) and `### Security` note (nothing unlisted is + written). No version bump. +- `THREAT-MODEL.md` — PROTECTED: `$SP/patches/CORE-386.py` for the human (§1 item 1 and 3, §2 "Extraction rejects + rather than skips" → "selects, then rejects", the caps sentence, the clone invariant, §3 table rows "oversized / + slow repo tarball" and "malformed / hostile archive entry", §4b caps line). NEEDS USER PATCH. + +Not touched: `src/commands/init.ts`, `src/commands/update.ts`, `src/lib/report-error.ts` (CORE-388's files); +`LIMITS.md` (its one extractor mention, "extracting it itself", stays true); `ARCHITECTURE.md`. + +## Contracts satisfied + +- `CLAUDE.md` invariants "The clone is data", "Containment", "Allowlists for untrusted names", "Network bounds", + "One unsafe-character set" — each kept on every written path; the new skip never writes. +- `CLAUDE.md` § Testing: update the test first (the new tar/repo cases are written before the code and run RED). + +## Evals to write (P1) — tests first; NEW ones must FAIL before the code change + +- unlisted symlink / hard link / pax `x` + entry / `:` name / long name → install OK, nothing written for it (FAILS + today: refused). +- symlink AT a listed path → refused; pax `x` before a listed path → refused; pax-renamed listed file → hash check + "does not ship as a file" (passes or fails today depending on the case; pinned). +- archive whose unlisted bytes exceed `maxWrittenBytes` → installs (FAILS today: decompressed cap). +- header cap / scanned-bytes cap / written-bytes cap refusals (new limits). +- duplicate selected path → refused (FAILS today: last wins). +- odd chunk boundaries → identical tree (new walker). +- e2e (manual, reported in the PR): built CLI `init` against real pharn-oss on the default `latest` channel + (v7.25.5, contains the symlinks) and on `--ref main`, plus `update`. + +## Guarantee audit (P0) + +- "No unselected entry is written" → floor: the only writes are `mkdirSync`/`writeFileSync` behind a `select.has(key)` + membership test; pinned by tests asserting the tree's exact contents. +- "A selected path is held to today's rules" → floor: the same functions as today on that branch; pinned by the + at-a-listed-path refusal tests. +- "A listed file that is missing or altered fails loudly" → floor: `verifyUpstreamManifest` (raw sha256), unchanged. +- "pax records are never honoured" → floor: no pax payload is read; a modified entry at a selected path is refused. +- "The tree holds only regular files and directories" → floor: unchanged (selected entries must be typeflag `0`/NUL). +- "Bounds" → floor: download cap (fetchCapped), header count, scanned bytes, written bytes — each a counter compare, + each tested. +- "Validating the layout marker on the manifest is equivalent to probing the tree" → advisory DERIVATION (stated in + the code): only listed files are written, and every one is proved present by the hash check. + +## Trust audit (P2) + +The archive and manifest stay untrusted. Strictly fewer bytes reach disk; unselected names are never decoded, so +they never reach a message. Selected names reach messages only after the control/format-character check, as today. + +## Determinism audit (P5) + +Every branch is a membership test: key ∈ select; typeflag ∈ {`0`, NUL} (accept), {`x`, `L`, `K`} (modifier), `g` +(skip); counters vs caps. No fallback guesses. + +## Open questions (HALT) + +- none. + +GATE 1 approved by lead (delegated by the user), 2026-11-25. Checked against the ticket: Scope bullets 1-6 → Design + +- Files; Done-when tests → Evals; e2e smoke → Evals (manual); no version bump; pharn-oss doc follow-up out of scope. diff --git a/.dev/features/core-386-unpack-listed-paths-only/REGRESSION.md b/.dev/features/core-386-unpack-listed-paths-only/REGRESSION.md new file mode 100644 index 00000000..eccf77db --- /dev/null +++ b/.dev/features/core-386-unpack-listed-paths-only/REGRESSION.md @@ -0,0 +1,19 @@ +# REGRESSION — core-386-unpack-listed-paths-only + +- Base: `51a96d2932` (origin/main, the branch's fork point), checked out in a detached worktree. +- Inside: the three source files, five test files, the docs (`CLAUDE.md`, `SECURITY.md`, `THREAT-MODEL.md`, + `docs/architecture.md`, `docs/contributing.md`), `CHANGELOG.md` and this feature's dev artifacts. None escapes the + plan's declared files (`check-regress.mjs scope`: `escaped` empty). +- Outside gates: the 53 stdlib `*.test.mjs`/`*.test.cjs` files (`node --test`), `node .dev/floor/validate.mjs .`, and + the full vitest suite (through heavy.sh, `--maxWorkers=2`; at HEAD with `--coverage`). + +| Gate | base | head | +| -------- | ---- | ---- | +| tests | 1 | 1 | +| validate | 0 | 0 | +| vitest | 0 | 0 | + +`regressions[]`: none. `pre_existing[]`: `tests` (red at base too: the gitignored `test-*/` fixtures, unrelated). + +REGRESSIONS: none, meaning no breakage outside the feature that these gates can detect (verdict `no-regressions`, +from `check-regress.mjs`). This certifies only the base→head comparison of these gates. diff --git a/.dev/features/core-386-unpack-listed-paths-only/REVIEW.md b/.dev/features/core-386-unpack-listed-paths-only/REVIEW.md new file mode 100644 index 00000000..ac670d9b --- /dev/null +++ b/.dev/features/core-386-unpack-listed-paths-only/REVIEW.md @@ -0,0 +1,33 @@ +# REVIEW — core-386-unpack-listed-paths-only + +Floor first: `node .dev/floor/validate.mjs .` GREEN. Everything below is advisory. + +```yaml +- type: FINDING + rule_id: P0 + severity: minor + file: 'src/lib/upstream-manifest.ts:checkLayoutMarker' + problem: 'The layout-marker check now passes when the manifest lists a file under pharn/pharn-contracts even if the tree lacks it.' + evidence: 'Safe because fetchRepo runs verifyUpstreamManifest before returning, and every later caller reads a fully extracted tree; pinned by the new upstream-manifest test (accepted by the parser, refused by the hash check).' +- type: FINDING + rule_id: P2 + severity: minor + file: 'src/lib/tar-extract.ts:TarWalker.push' + problem: "A selected file's payload is kept as subarrays of the gunzip output chunks until it is complete." + evidence: 'zlib allocates a fresh output buffer once one fills and never rewrites an emitted region; the e2e run verified 616 sha256s on the real archive, and the chunk-boundary tests compare byte-identical trees.' +- type: FINDING + rule_id: P7 + severity: minor + file: 'tests/project-lock.test.ts:SIGNAL_HANDLED' + problem: 'A test-harness change outside the extractor.' + evidence: "The SIGINT child relied on a pending tsx IPC handle to keep its loop alive; the streamed extraction removed that accident. A ref'd timer in the helper makes all signal children deterministic; no assertion changed." +- type: FINDING + rule_id: P3 + severity: minor + file: 'src/lib/repo.ts:extractPharnArchive' + problem: 'Exported ahead of its second caller (CORE-387 verify-archive).' + evidence: 'fetchAt uses it; the ticket asks for this shape. The clone-producer lint rule still confines mkdtemp to repo.ts.' +``` + +Verdict: 0 floor-gate findings, 4 advisory (minor). `TarExtractError` keeps its name and export; every refusal names +the entry path and the rule (CORE-388 compatibility). diff --git a/.dev/features/core-386-unpack-listed-paths-only/SHIP.md b/.dev/features/core-386-unpack-listed-paths-only/SHIP.md new file mode 100644 index 00000000..3e0b2e7f --- /dev/null +++ b/.dev/features/core-386-unpack-listed-paths-only/SHIP.md @@ -0,0 +1,16 @@ +# SHIP — core-386-unpack-listed-paths-only + +| Stage | Verdict (structural) | +| ------- | ------------------------------------------------------------------- | +| plan | GATE 1 approved by lead (delegated by the user) | +| grill | advisory: 5 concerns (0 blocking), folded into the build | +| build | floor GREEN (format:check, lint, lint:md, typecheck, vitest, build) | +| regress | `no-regressions` (regression-report.json; `tests` pre-existing red) | +| verify | `PASS` (verify-report.json) | +| review | 0 floor-gate findings, 4 advisory (minor) — see REVIEW.md | + +GATE 2 delegated to the lead: open the PR, drive CI green, do not merge. THREAT-MODEL.md was patched by the user with +the script this run wrote (`$SP/patches/CORE-386.py`, since deleted). + +Chain ran; the named floor verdicts are as shown — this is NOT a judgment that the increment is good or wise; that is +the human's call at the post-review gate. diff --git a/.dev/features/core-386-unpack-listed-paths-only/VERIFY.md b/.dev/features/core-386-unpack-listed-paths-only/VERIFY.md new file mode 100644 index 00000000..6903b93c --- /dev/null +++ b/.dev/features/core-386-unpack-listed-paths-only/VERIFY.md @@ -0,0 +1,22 @@ +# VERIFY — core-386-unpack-listed-paths-only + +| Gate | exit | +| ------------ | ---- | +| test | 0 | +| validate | 0 | +| lint | 0 | +| format:check | 0 | +| lint:md | 0 | +| typecheck | 0 | +| build | 0 | + +Verdict `PASS` (`check-verify.mjs`): 106 files, 3,662 tests, coverage 98.59 / 95.75 / 99.08 / 99.08 (floors +90/85/90/90). No verifier capabilities exist, so no advisory layer ran. + +End to end (manual, not a gate): the built `dist/index.js` ran `init --yes`, `status` and `update --yes` in throwaway +projects against the real pharn-oss archive on the default channel (release v7.25.5, commit `1755d6b8`) and on +`--ref main` (commit `a2cacaef`); both archives hold 7 symlinks under `.claude/skills/`. All exit 0, 592 files, "No +drift", "Up to date", no symlink in the project. The 0.21.5 build refuses the same archive with +`tar entry has an unsupported type '2': …/.claude/skills/pharn-ci-cover`. + +The named gates passed; this is not a claim that the feature is correct beyond what they check. diff --git a/.dev/features/core-386-unpack-listed-paths-only/regression-report.json b/.dev/features/core-386-unpack-listed-paths-only/regression-report.json new file mode 100644 index 00000000..1ff11c08 --- /dev/null +++ b/.dev/features/core-386-unpack-listed-paths-only/regression-report.json @@ -0,0 +1,44 @@ +{ + "base": "51a96d2932", + "inside": [ + ".dev/features/core-386-unpack-listed-paths-only/GRILL.md", + ".dev/features/core-386-unpack-listed-paths-only/PLAN.md", + ".dev/features/core-386-unpack-listed-paths-only/REGRESSION.md", + ".dev/features/core-386-unpack-listed-paths-only/REVIEW.md", + ".dev/features/core-386-unpack-listed-paths-only/SHIP.md", + ".dev/features/core-386-unpack-listed-paths-only/VERIFY.md", + ".dev/features/core-386-unpack-listed-paths-only/regression-report.json", + ".dev/features/core-386-unpack-listed-paths-only/verify-report.json", + "CHANGELOG.md", + "CLAUDE.md", + "SECURITY.md", + "THREAT-MODEL.md", + "docs/architecture.md", + "docs/contributing.md", + "src/lib/repo.ts", + "src/lib/tar-extract.ts", + "src/lib/upstream-manifest.ts", + "tests/commands/init.test.ts", + "tests/project-lock.test.ts", + "tests/repo.test.ts", + "tests/tar-extract.test.ts", + "tests/upstream-manifest.test.ts" + ], + "outside_gates": { + "tests": { + "base": 1, + "head": 1 + }, + "validate": { + "base": 0, + "head": 0 + }, + "vitest": { + "base": 0, + "head": 0 + } + }, + "regressions": [], + "pre_existing": ["tests"], + "verdict": "no-regressions" +} diff --git a/.dev/features/core-386-unpack-listed-paths-only/verify-report.json b/.dev/features/core-386-unpack-listed-paths-only/verify-report.json new file mode 100644 index 00000000..a610791f --- /dev/null +++ b/.dev/features/core-386-unpack-listed-paths-only/verify-report.json @@ -0,0 +1,14 @@ +{ + "feature": "core-386-unpack-listed-paths-only", + "gates": { + "build": 0, + "format:check": 0, + "lint": 0, + "lint:md": 0, + "test": 0, + "typecheck": 0, + "validate": 0 + }, + "verdict": "PASS", + "failing_gates": [] +} diff --git a/CHANGELOG.md b/CHANGELOG.md index 0a726c62..68d0681b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,14 @@ Releases 0.4.0 and older are in [CHANGELOG-ARCHIVE.md](CHANGELOG-ARCHIVE.md). ## [Unreleased] +### Fixed + +- **`pharn init`, `add`, `update` and `status` work again against pharn-oss v7.25.3 and later.** Those releases commit seven symlinks under `.claude/skills/`, and `pharn` refused any symlink anywhere in the downloaded archive, so every install and update failed on every channel. `pharn` now unpacks only the files pharn-oss's `pharn-install.json` lists, plus the four it reads itself (`pharn-install.json`, `SKILLS_VERSION`, `MIN_CLI`, `.claude/settings.json`); every other archive entry is skipped and never written. A symlink, hard link, pax header, long or `:` name elsewhere in pharn-oss, or pharn-oss growing past 20,000 entries or 128 MB, no longer stops an install. The archive is decompressed as a stream, so the 128 MB cap now applies to the bytes `pharn` writes, not to the whole repository. What is installed is unchanged. + +### Security + +- **Nothing outside pharn-oss's install list reaches your disk, even in the temporary download directory.** A listed file keeps every rule it had: it must be a regular file with a safe UTF-8 path (no `\`, `:` or `..`, one root), it may appear only once, and a symlink or any other entry type at a listed path is refused. A listed file preceded by a pax extended or GNU long-name header is refused, because `pharn` does not honour those records; a listed file such a header renamed is missing, and the sha256 check of every listed file still refuses the release. New bounds replace the entry and decompressed-size caps: 200,000 archive headers and 1 GiB of decompressed stream (a compression-bomb bound), beside the 32 MB download cap. + ## [0.21.5] — 2026-11-24 ### Changed diff --git a/CLAUDE.md b/CLAUDE.md index ed913417..f5c75475 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -80,10 +80,11 @@ PHARN_DEBUG=1 npm run dev -- init # full error output for fetch/install failur path that crosses a symlinked component, because `safeJoin` is lexical and copies/`rmSync` follow links. - **Hard-link-safe writes.** Writes replace the file (`lib/atomic-write.ts`: exclusive temp, then `rename`), one by one via `applyWrites`; a new `settings.json` uses `COPYFILE_EXCL`. A hard link's other name is never written through. -- **The clone is data.** `lib/tar-extract.ts` admits only regular files and directories, and `lib/repo.ts` is the only - producer of a clone. It requires the tree's `pharn-install.json` (a tree without one is refused) and verifies its raw - sha256s before returning the tree; every manifest `dest` must pass `isPharnOwnedPath`, never the manifest's own - `installRoots`. Nothing downloaded is ever executed: pharn-oss's `models` rules exist here as a pinned copy +- **The clone is data.** `lib/repo.ts` is the only producer of a clone. `lib/tar-extract.ts` writes only the paths + `pharn-install.json` lists plus `CLONE_READ_FILES`, each a regular file under today's path rules; every other archive + entry is skipped and never written, whatever its type. It requires the tree's `pharn-install.json` (a tree without + one is refused) and verifies its raw sha256s before returning the tree, so a listed file that is missing or altered + fails; every manifest `dest` must pass `isPharnOwnedPath`, never the manifest's own `installRoots`. Nothing downloaded is ever executed: pharn-oss's `models` rules exist here as a pinned copy (`lib/model-config.ts`), held to the vendored sha256-pinned checker by a differential test. - **Allowlists for untrusted names.** Untrusted names, versions, tags and manifest fields are checked against `CAPABILITY_NAME_RE`, `VERSION_RE`, `COPY_FILENAME_RE`, `COMMIT_RE`, `RELEASE_TAG_RE` and the role/applies enums. @@ -100,7 +101,7 @@ PHARN_DEBUG=1 npm run dev -- init # full error output for fetch/install failur - **Fail closed on release resolution.** `lib/release.ts` refuses (naming `--ref main`) when the latest release cannot be resolved or is malformed. It never floats to the tip of `main`. - **Network bounds.** `redirect: 'error'`, a per-request deadline and a body cap on every fetch. The tarball has its - own archive, extracted-size and entry caps. + own archive, headers-scanned, decompressed-bytes-scanned and bytes-written caps. - **The project lock.** `init`/`add`/`update`/`remove`/`uninstall` take `pharn/.lock` before reading the config, hold it across every prompt and plan once; edits made meanwhile are caught at write time (hash, fingerprint, walk). Dry runs and readers (`list`, `status`) never take it. diff --git a/SECURITY.md b/SECURITY.md index 826a2ad7..7c0cfc6a 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -54,11 +54,11 @@ Scope follows the surface described above: everything that touches remote input ### In scope - **Remote-input validation** bypasses in `src/lib/validate.ts` or `src/lib/upstream-manifest.ts` — the regex/enum allowlists active in the archetype flow (`CAPABILITY_NAME_RE`, `COPY_FILENAME_RE`, `VERSION_RE`, `COMMIT_RE`, `RELEASE_TAG_RE`, the `role`/`applies` enums via `assertRole`/`assertAppliesToken`), the `..` checks, control-character rejection (`assertSafeString`), or the network guards on the lightweight fetches. Every fetch goes through one bounded GET (`fetchCapped` in `src/lib/fetch-capped.ts`): `redirect: 'error'`, a hard deadline over the request **and** the body read (`withDeadline` in `src/lib/deadline.ts`, which settles at the deadline even if the body never ends), and a byte cap counted as the body streams. The lightweight fetches are sized at an 8 s deadline each: the release resolve in `src/lib/release.ts` (1 MiB for the release object, 1 KiB for the tag's commit), `fetchCommitSha` in `src/lib/repo.ts` (1 KiB) and `fetchRemoteSkillsVersion` in `src/lib/skills-version.ts` (256 KB). The repo download itself (`fetchRepo` in `src/lib/repo.ts`) carries the **same three guards, separately sized**: a 60 s deadline (`CLONE_TIMEOUT_MS`, sized to cover a streamed multi-megabyte body rather than a one-line response) and a body cap (`MAX_ARCHIVE_BYTES`, 32 MB), counted over the stream because codeload sends no `content-length`. Report ways around any of them (see `THREAT-MODEL.md §2` for the boundary, `§4b` for what it does and does not bound). -- **Archive parsing** in `src/lib/tar-extract.ts` — the hand-written ustar reader `pharn` uses instead of a tar dependency, and the highest-value target here, because it parses attacker-controlled header bytes. In scope: anything that gets an entry written outside the destination, gets a non-regular entry created, or gets past a bound. Its floor is the typeflag allowlist (ACCEPT regular files and directories; REJECT pax extended headers, symlinks, hard links, devices, FIFOs, GNU `L`/`K` long-name headers, and any unknown type), `prefix` + `name` reassembly **before** any path rule runs, rejection of absolute paths, `..` segments and any `\` or `:` in a name, a single-leading-component strip, a same-root check across every entry, `safeJoin` containment at each write, header-checksum verification, and octal-only numeric fields (a GNU base-256 field fails the octal test; only ASCII space is trimmed). That allowlist is what makes **the clone invariant** true — the tree `fetchRepo` returns holds only regular files and directories, in a private temp dir — and the clone-side readers rely on it rather than re-checking for links, so an entry type that slips past the allowlist is in scope. **`pax` records are never honoured: pharn reads only the ustar fields.** A per-file extended header (typeflag `x`) is refused on the **typeflag byte alone**, its payload never read — its records would override the ustar header that follows (`path=` replaces `prefix`+`name`, and a writer emits one exactly when the real path will not fit ustar, truncating it into the 100-byte `name` field where it would satisfy every containment rule above; `size=` replaces how many bytes the entry occupies). A **global** header (typeflag `g`) cannot be refused, because every codeload tarball opens with one; it is skipped, payload unread, and still counts toward the entry cap. Its defaults are never consulted, so the entries that follow land at their own ustar paths under every rule above, and the walk is framed by the ustar `size` alone. Reports that get a `pax` record honoured, or the `x` refusal suppressed, are in scope. Two bounds are passed in by `fetchRepo`: `MAX_ENTRIES` (20 000 entries, counted by the extractor) and `MAX_EXTRACTED_BYTES` (128 MB, `gunzipSync`'s `maxOutputLength` over the decompressed stream, which holds every byte an entry writes). That decompressed cap is what bounds a compression bomb, which neither a response header nor the archive's own size would. Extraction is deliberately **strict: every unexpected entry throws** rather than being silently skipped. +- **Archive parsing** in `src/lib/tar-extract.ts` — the hand-written ustar reader `pharn` uses instead of a tar dependency, and the highest-value target here, because it parses attacker-controlled header bytes. In scope: anything that gets an entry written outside the destination, gets a non-regular entry created, gets an entry written that pharn did not select, or gets past a bound. **It selects, then judges.** `src/lib/repo.ts` passes the paths to write: the ones `pharn-install.json` lists, plus the four files the CLI reads itself (`CLONE_READ_FILES`: the manifest, `SKILLS_VERSION`, `MIN_CLI`, `.claude/settings.json`), in two streamed passes (the CLI-read files, then — once the manifest has validated — the listed paths). Every other entry is skipped and **never written**, whatever its type or name: a symlink, hard link, device, pax header, long or `:` name elsewhere in pharn-oss no longer refuses the install, because nothing unselected touches disk. Every header is still framing-checked, because the walk cannot find the next one without it: header-checksum verification, the `ustar` magic, octal-only numeric fields (a GNU base-256 field fails the octal test; only ASCII space is trimmed), and an end-of-archive marker followed only by zeros. An entry at a selected path gets the full floor: a regular file only (typeflag `0`/NUL; a symlink, hard link, device, directory or any other type there is refused), strict UTF-8 with no control or format character, `prefix` + `name` reassembly **before** any path rule runs, rejection of absolute paths, `..` segments, empty or `.` segments and any `\` or `:`, a single-leading-component strip, a same-root check across every selected entry and both passes, a refusal when the path appears twice, and `safeJoin` containment at each write. That is what makes **the clone invariant** true — the tree `fetchRepo` returns holds only regular files and directories, and only the listed and CLI-read files, in a private temp dir — and the clone-side readers rely on it rather than re-checking for links. A listed file the archive does not ship as a regular file at its path is missing from the tree, and the manifest's raw sha256 check (`verifyUpstreamManifest`) refuses the tree. **`pax` records are never honoured: pharn reads only the ustar fields.** A per-file extended header (typeflag `x`, and GNU `L`/`K`) rewrites the next entry's path or size, so it is skipped together with the entry it modifies; when that entry's ustar name is a selected path, it is **refused**, and when the record renamed a listed file away from its ustar name, that file is missing and the sha256 check refuses. A **global** header (typeflag `g`; every codeload tarball opens with one) is skipped, payload unread; its defaults are never consulted, and the walk is framed by the ustar `size` alone. Reports that get a `pax` record honoured, or an unselected entry written, are in scope. Bounds, passed in by `fetchRepo`: `MAX_HEADERS` (200 000 headers of any type), `MAX_SCANNED_BYTES` (1 GiB of decompressed stream — the compression-bomb bound; the tar is streamed through `zlib.createGunzip`, never held whole) and `MAX_WRITTEN_BYTES` (128 MB, the sum of the selected files' sizes, checked at each header before its payload is read), on top of the 32 MB download cap. - **Path traversal** or unintended file-system writes from `src/lib/install-capabilities.ts` / `src/lib/install-manifest.ts` / `src/lib/diff.ts` / `src/commands/remove.ts` (copying resolved capability dirs and fixed product surfaces, `pharn.config.json` write) or from any capability / product-filename that escapes its intended target (`safeJoin` in `src/lib/validate.ts`, plus destination symlink walks in `install-capabilities.ts`). - **Server-side request forgery (SSRF)** or redirect abuse in the release, commit-metadata or `SKILLS_VERSION` fetches (the `fetch()` calls above use `redirect: 'error'`; report ways around it). - **Supply-chain** issues in how pharn-oss is fetched — the default verified-release resolve (`--ref latest`, the default of `pharn init` since 0.15.0; `src/lib/release.ts`: the latest release's tag, the tag's commit through the full tag ref, and the check that the fetched tree's `SKILLS_VERSION` equals the tag; it fails closed and never floats), the SHA-pinned `codeload.github.com` tarball download it feeds (`src/lib/repo.ts`), the opt-in `main` channel (`--ref main`, or an install that records no `ref`) with its one commit-SHA resolve **and its degraded mode** — when the SHA cannot be resolved the fetch floats `refs/heads/main` instead and records `commit` as absent (`LIMITS.md` §3b) — or the resolution of the repo coordinates (`src/lib/constants.ts`). Note the standing residual rather than re-reporting it: provenance is by-SHA, **not cryptographic** (`LIMITS.md §1b`), so a compromised upstream serving a valid-**shaped** tree at the resolved SHA passes every check above. -- **Untrusted-content injection** — a poisoned pharn-oss tree (a malicious `pharn-install.json` entry, symlink-planted paths, or unexpected directory entries) that leads the CLI to write outside the project or copy unintended content. +- **Untrusted-content injection** — a poisoned pharn-oss tree (a malicious `pharn-install.json` entry, a symlink or other non-file entry at a listed path, or unexpected directory entries) that leads the CLI to write outside the project or copy unintended content. - Logic in the archetype install pipeline (`src/commands/init.ts`, `src/steps/archetype-summary.ts`, `src/steps/overwrite-check.ts`, `src/steps/install-archetype.ts`, and the other commands) that could be abused to skip a consent prompt or overwrite files without confirmation. - **The forward-compatibility gate** in `src/lib/min-cli-gate.ts` and `readMinCli` (`src/lib/skills-version.ts`) — an optional `MIN_CLI` file read out of the **untrusted clone** and version-parsed to decide whether to refuse execution. It fails open by design (absent or malformed means "no constraint"); report ways to make a well-formed newer value fail to refuse, or a malformed one to crash rather than warn. - **Local-but-user-editable sidecar parsing** — `src/lib/pharn-config.ts` (every `capabilities[]` entry's `name` is validated against `CAPABILITY_NAME_RE` and its `role` against the role enum at ingest, because `pharn remove` path-joins that name into a recursive delete — which additionally accepts only a strict child of the role subtree via `safeChildJoin`), `src/lib/install-records.ts` (whose own header declares the store untrusted input: a defensive parser, a key-segment rule, and the invariant that a record key never drives a write; only orphan detection, a read, and `pharn uninstall`, a delete of a file still at its recorded hash, turn a key into a path, each behind `safeJoin`, a symlink walk and a regular-file check) and `src/lib/project-lock.ts` (which parses a JSON payload written by another process and feeds its `pid` to `process.kill`). Report ways to get a crafted store or lock file to write or delete outside the project, signal an unintended process, or get an overwrite or delete past the check that the file still has its recorded hash. diff --git a/THREAT-MODEL.md b/THREAT-MODEL.md index 503e2e8a..38eb93a9 100644 --- a/THREAT-MODEL.md +++ b/THREAT-MODEL.md @@ -47,13 +47,16 @@ surface: 1. **Malicious capability / product path** — a poisoned capability name, manifest `path`/`dest`, or product command/hook filename containing `..`, an absolute path, or control chars → a write **outside the intended subtree** (arbitrary file overwrite in the user's repo). Symlinks - planted in the archive are a variant — refused by the extractor's typeflag allowlist, so the - clone never holds one (the clone invariant, §2). The highest-value target. + planted in the archive are a variant — the extractor writes only the paths the install manifest + lists (plus the few files the CLI reads), each as a regular file, so the clone never holds one + (the clone invariant, §2): a symlink at a listed path is refused, one elsewhere is skipped + unwritten. The highest-value target. 2. **Malformed capability declarations** — broken `role`/`applies` values in `pharn-install.json`, or a capability `dir` in the wrong subtree, to crash the install or mis-drive selection into an unintended capability set. 3. **Oversized / slow response** — a huge clone or a hanging fetch → DoS the install. Every pharn fetch now carries a timeout and a body cap, the clone included: a streamed-byte cap on the - download and a second cap on the decompressed size (see the fetch boundary below). + download, and caps on the headers and decompressed bytes the extractor walks and on the bytes it + writes (see the fetch boundary below). 4. **Redirect to an attacker host** — a 3xx from any `fetch()` endpoint (`SKILLS_VERSION`, commit and release metadata, the tarball) to an off-repo sink. All of them pass `redirect: 'error'`. 5. **The copied methodology itself (Surface A)** — validated for **placement**, not for semantic @@ -95,40 +98,49 @@ a test. deadline even when the runtime never forwards the abort into a body that stops arriving. The clone's deadline is separately sized (60 s, not 8 s) because it must cover a ~2.5 MB streamed body rather than a one-line response. codeload sends **no - `content-length`**, so the cap is enforced by counting bytes as they stream, and a **second** cap - bounds the _decompressed_ size — a compression bomb is bounded by neither the header nor the - archive size. -- **Extraction rejects rather than skips.** This is the deliberate difference from what it replaces. - The bundled node-tar was called with **neither `strict` nor `onwarn`**, so a `TAR_ENTRY_INVALID` - (checksum / path / linkpath) was _recoverable_: the entry was silently dropped and extraction still - resolved successfully. `tar-extract.ts` throws on every one of those. It sorts each header into - three buckets: - - **ACCEPT** typeflag `0`/NUL (regular file) and `5` (directory) — the only content types the - archive holds. - - **SKIP** typeflag `g` (pax global header), advancing past the padded payload **unread**, with - **no** path rules applied; it still counts toward the entry cap. Every codeload tarball opens with - a `pax_global_header` whose single-segment name has no leading component to strip, so an - extractor that runs the path rules over it rejects every real archive on its first block. pharn - reads only the ustar fields, so a `g` default (`path`, `size`) is never honoured: the entries - after it land at their own ustar paths under every rule below. - - **REJECT** `x` (pax extended header — refused on the typeflag alone, payload unread, because its - records would override the next entry's path and size), `1`/`2` (hard/symlink), `3`/`4` - (devices), `6` (fifo), `7`, and any unknown byte. The archive contains none today, so a rejection - is a real signal rather than noise. + `content-length`**, so the cap is enforced by counting bytes as they stream, and the extractor + caps the _decompressed_ bytes it walks — a compression bomb is bounded by neither the header nor + the archive size. +- **Extraction selects, then rejects.** The bundled node-tar it replaces was called with **neither + `strict` nor `onwarn`**, so a `TAR_ENTRY_INVALID` (checksum / path / linkpath) was _recoverable_: + the entry was silently dropped and extraction still resolved — and a dropped entry could be a file + pharn installs. `tar-extract.ts` writes only the paths it is given: `fetchRepo` makes two streamed + passes, the first writing the files the CLI reads itself (`CLONE_READ_FILES`: `pharn-install.json`, + `SKILLS_VERSION`, `MIN_CLI`, `.claude/settings.json`), the second — once the manifest has + validated — the paths `pharn-install.json` lists. Each header falls in one of three cases: + - **EVERY header** is framing-checked (checksum, `ustar` magic, octal `size`, the header and + scanned-byte caps, an end-of-archive marker followed only by zeros), because the walk cannot + find the next header without it. + - **UNSELECTED** — every entry at a path pharn does not write, whatever its type or name (a + symlink, hard link, device, fifo, directory, pax header, long, `:` or invalid name): skipped, its + payload unread, **nothing written**. Skipping is strictly safer than judging, since nothing + unselected touches disk; refusing them made seven symlinks under pharn-oss's `.claude/skills/` + (v7.25.3–v7.25.5), outside the install list, break every install. The silent loss node-tar + allowed cannot recur: a listed file a skipped entry stood in for is missing from the tree, and + the manifest's raw sha256 check (`verifyUpstreamManifest`) refuses the tree loudly. + - **SELECTED** — an entry at a path pharn writes: it must be a regular file (typeflag `0`/NUL; + any other type there is refused), its path strict UTF-8 with no control or format character, + held to every path rule below, and present once. pharn reads only the ustar fields, never a pax + payload: a pax `x` (or GNU `L`/`K`) header, which rewrites the next entry's path and size, is + skipped together with that entry, and **refused** when that entry's ustar name is a selected + path. A `g` (global) header — every codeload tarball opens with one — modifies nothing and is + skipped; its defaults are never honoured. - **Paths are reassembled before they are judged.** The full path is `prefix + '/' + name` — ustar splits anything over 100 characters across those two header fields, and a large fraction of the live archive's entries use it. Reading `name` alone yields a bare leaf, which the strip-1 rule then rejects for having no leading component: a third of the tree silently lost, not merely misplaced. After reassembly: absolute paths, `..` segments and any `\` or `:` in a name are rejected (POSIX would write `a\..\..\evil` as one literal name; win32 would read it as a path), exactly one - leading component is stripped, every entry must share the **same** root component, and every write resolves through - `safeJoin` (`src/lib/validate.ts`). The entry count is capped by the extractor and the total - extracted bytes by gunzip's decompressed-size cap (the decompressed tar holds every byte an entry - writes). Header checksums are verified, and numeric fields are octal only, so the GNU base-256 - encoding is rejected rather than misparsed. + leading component is stripped, every selected entry must share the **same** root component, and every write resolves through + `safeJoin` (`src/lib/validate.ts`). The tar is decompressed as a stream (`zlib.createGunzip`), + never held whole; the extractor caps the headers it walks (200 000), the decompressed bytes it + walks (1 GiB, the compression-bomb bound) and the bytes it writes (128 MB, checked at each + selected header before its payload is read). Header checksums are verified, and numeric fields + are octal only, so the GNU base-256 encoding is rejected rather than misparsed. - **The clone invariant.** The tree `fetchRepo` returns contains only regular files and - directories, created by this process in a private `mkdtemp` dir (0700) that nothing else writes: - the typeflag allowlist above admits nothing else, the extractor's only writes are `mkdirSync` and + directories — only the listed and CLI-read files and the directories above them — created by this + process in a private `mkdtemp` dir (0700) that nothing else writes: a selected entry must be a + regular file, nothing unselected is written, the extractor's only writes are `mkdirSync` and `writeFileSync` through `safeJoin`, and a test pins that `src/lib/repo.ts` is the only producer of a clone. Clone-side readers rely on it and carry no symlink, FIFO or device checks of their own; they keep type checks where a directory (or a file where a directory belongs) can be produced. @@ -173,13 +185,13 @@ Every answer reduces to the floor (P0) or is labeled a limit (`LIMITS.md`). | Surface | Structural answer | Floor primitive (current file/function) | | --- | --- | --- | -| malicious capability / product path | `CAPABILITY_NAME_RE` / `COPY_FILENAME_RE` + `..`/unsafe-character rejection (`assertSafeString` in `src/lib/validate.ts`, through `hasUnsafeChars`; its messages escaped with `escapeUnsafe`, since the label quotes the name); `safeJoin` guards **every** read/write in `readUpstreamManifest`, `installCapabilityDirs`, `collectExpectedInstallPaths`, `diffInstalledCapabilities`, and `remove`; the clone holds no symlinks (the clone invariant, §2 — `extractTar`'s typeflag allowlist) and every destination path is walked for symlinked components before any write (`prepareInstall` in `src/lib/install-capabilities.ts`); pre-flight every capability source before any write (`installCapabilityDirs`) | regex + path containment + typeflag allowlist + destination symlink walk | +| malicious capability / product path | `CAPABILITY_NAME_RE` / `COPY_FILENAME_RE` + `..`/unsafe-character rejection (`assertSafeString` in `src/lib/validate.ts`, through `hasUnsafeChars`; its messages escaped with `escapeUnsafe`, since the label quotes the name); `safeJoin` guards **every** read/write in `readUpstreamManifest`, `installCapabilityDirs`, `collectExpectedInstallPaths`, `diffInstalledCapabilities`, and `remove`; the clone holds no symlinks (the clone invariant, §2 — `extractTar` writes only selected paths, each a regular file) and every destination path is walked for symlinked components before any write (`prepareInstall` in `src/lib/install-capabilities.ts`); pre-flight every capability source before any write (`installCapabilityDirs`) | regex + path containment + typeflag allowlist + destination symlink walk | | malformed capability declarations | `readUpstreamManifest` refuses the whole manifest, naming the entry, on a name outside `CAPABILITY_NAME_RE`, an unknown `role` (`assertRole`), a `dir` outside its role's subtree, a duplicate name or a capability with no files; an unknown `applies` token (`assertAppliesToken`) makes that one capability `unknown` in `manifestCapabilityIndex` — named, never installed, never a silent skip | enum + regex shape check | | oversized / slow `SKILLS_VERSION` fetch | 256 KB body cap + 8s timeout + `redirect: 'error'` | `fetchRemoteSkillsVersion` (`src/lib/skills-version.ts`) | | oversized / slow release or commit-SHA resolve | 8s deadline + `redirect: 'error'` + a 1 MiB cap on the release object and `MAX_SHA_BYTES` (1 KiB) on a commit id | `resolveSource` (`src/lib/release.ts`), `fetchCommitSha` (`src/lib/repo.ts`) | -| oversized / slow repo tarball | 60s timeout + a streamed-byte cap on the download + a separate cap on the **decompressed** size + `redirect: 'error'`; an entry-count cap in the extractor. A trip **throws** — there is no fallback transport to degrade to | `downloadArchive` (`src/lib/repo.ts`), `extractTarGz` (`src/lib/tar-extract.ts`) | +| oversized / slow repo tarball | 60s timeout + a streamed-byte cap on the download + `redirect: 'error'`; in the extractor, caps on the headers and **decompressed** bytes walked (streamed, never held whole) and on the bytes written. A trip **throws** — there is no fallback transport to degrade to | `downloadArchive` (`src/lib/repo.ts`), `extractTarGz` (`src/lib/tar-extract.ts`) | | redirect to attacker host | `redirect: 'error'` on every pharn `fetch()` call, the tarball included | `fetchCapped` (`src/lib/fetch-capped.ts`), the one GET behind `resolveSource`, `fetchRemoteSkillsVersion`, `fetchCommitSha` and `downloadArchive` | -| malformed / hostile archive entry | typeflag allowlist (files + dirs only; symlinks, hardlinks, devices and fifos **rejected**), `prefix`+`name` reassembly, `..`/absolute/`\`/`:` rejection, single-root check, `safeJoin` on every write, header-checksum verification | `extractTar` (`src/lib/tar-extract.ts`) | +| malformed / hostile archive entry | selection (only the manifest's listed paths and the CLI-read files are written; every other entry is **skipped unwritten**); at a selected path: regular file only (symlinks, hardlinks, devices, fifos and pax-modified entries **rejected**), `prefix`+`name` reassembly, `..`/absolute/`\`/`:` rejection, single-root check, no duplicate, `safeJoin` on every write; header-checksum verification on every header; the manifest's sha256 check catches a listed file that is missing or altered | `extractTar` (`src/lib/tar-extract.ts`) | | hostile / malformed `pharn-install.json` | data, never executed: one parser, a bounded (4 MiB) non-blocking read; `schemaVersion` exact-match (`1`, else refuse, naming the upgrade); every `path`/`dest` through a safe-segment regex + `safeJoin`; unique `dest`s; names, roles and versions against `CAPABILITY_NAME_RE` / `assertRole` / `VERSION_RE` (an unknown `applies` token makes that capability `unknown`, never installed); every `dest` inside the CLI-owned outer bound — below `pharn/` or `.claude//` inside a `pharn-*` entry or a fixed pharn root, `.claude/settings.json` only as copy-if-absent — never the manifest's own `installRoots`; each declared file's **raw** sha256 verified in `fetchRepo` before the tree is returned, so a mismatch refuses and nothing is written; `models.defaults` passes `checkModelsBlock` before any config write; `models.rules` drives nothing. Provenance only (§4a): whoever can change the tarball can change the manifest with it | `readUpstreamManifest` / `verifyUpstreamManifest` (`src/lib/upstream-manifest.ts`), `isPharnOwnedPath` (`src/lib/install-surfaces.ts`), `matchesRawSha256` (`src/lib/hash.ts`) | | poisoned tarball cache | **not applicable — pharn keeps no cache.** Every fetch downloads into a fresh temp dir | `fetchRepo` (`src/lib/repo.ts`) | | malformed / hostile upstream `models` block | bounded (1 MiB), non-blocking read; checked against pharn-oss's rules through the pinned copy; an unserializable block is refused; a failing block is **not written** and each reason is printed through `terminalSafe`; never executed | `readUpstreamModels` (`src/lib/upstream-models.ts`), `checkModelsBlock` (`src/lib/model-config.ts`) | @@ -236,8 +248,9 @@ not a "the source repo is ours" assumption (P0). `fetchRepo` now owns the whole download-and-extract path, so the residual is much smaller than it was — and what is left is worth stating precisely rather than implying it is closed: - **What is now floor, not delegation.** Timeout, streamed-byte cap, decompressed-size cap, - `redirect: 'error'`, typeflag allowlist, path reassembly + containment, single-root check, - entry/byte caps, header checksums. Each is pharn's own code with its own test, so a dependency + `redirect: 'error'`, selection of listed paths with a regular-file rule at each, path + reassembly + containment, single-root check, header/scanned-byte/written-byte caps, header + checksums. Each is pharn's own code with its own test, so a dependency bump cannot move any of them. The previous residual — "pharn bounds none of it" — is closed. - **What is closed by removal.** The shared cross-project tarball cache is gone, and with it both the poisoned-bytes surface (reuse keyed by **filename**, never a verified digest) and the worse diff --git a/docs/architecture.md b/docs/architecture.md index 4ddb5869..c00dbac1 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -71,7 +71,11 @@ directory gets its actionable error), under the lock, and before any network cal - Detection returns one piece of evidence per archetype (a dependency or the first triggering path). It is display-only, passed through `terminalSafe`. 3. **Source** (`lib/release.ts`, `lib/repo.ts`). `resolveSource` decides which commit, and `fetchRepo(source)` downloads - and extracts the codeload tarball into a temp dir that is removed in a `finally`. No command exits mid-run: a + the codeload tarball and extracts it into a temp dir that is removed in a `finally`. `extractPharnArchive` makes two + streamed passes over the archive: the first writes only the files the CLI reads itself (`CLONE_READ_FILES`: + `pharn-install.json`, `SKILLS_VERSION`, `MIN_CLI`, `.claude/settings.json`), the manifest is validated, and the + second writes only the paths the manifest lists. Every other entry (a symlink, a hard link, a pax header, a long or + `:` name anywhere else in pharn-oss) is skipped and never written. No command exits mid-run: a refusal, a failure or a cancel is thrown as a `CliError` (`lib/cli-error.ts`), so that `finally` (and the project lock's) runs first, and `runCli` in `src/index.ts` prints it once and sets `process.exitCode`. `fetchRepo` requires the tree's `pharn-install.json` (pharn-oss 7.21.0 and later), validates it and checks every declared file's raw @@ -144,7 +148,7 @@ is pharn-oss's [`docs/install-manifest.md`](https://github.com/pharn-dev/pharn-o - **Read and validate.** A bounded read (4 MiB, regular file, non-blocking), then a strict check: `schemaVersion` must be `1` (anything else refuses and says to upgrade pharn); `skillsVersion` must equal `SKILLS_VERSION`; the layout - must be the `pharn` layout this CLI knows; every capability `name`, `role` and `dir`, and every file `path`, `dest`, + must be the `pharn` layout this CLI knows, whose marker `pharn/pharn-contracts/` the tree holds or the manifest lists a file under; every capability `name`, `role` and `dir`, and every file `path`, `dest`, `sha256`, `policy` and `surface`, is held to an allowlist and to `safeJoin`; `dest`s are unique. Unknown keys are ignored (the schema is additive within version 1). - **The outer bound.** Every `dest` must lie inside `isPharnOwnedPath` (`lib/install-surfaces.ts`): below `pharn/` @@ -155,7 +159,8 @@ is pharn-oss's [`docs/install-manifest.md`](https://github.com/pharn-dev/pharn-o `uninstall` and `.prettierignore`) accepts the same paths, so a file installed into a surface this CLI does not name is updated, orphaned and uninstalled like any other, still gated by its record's hash. - **Verify.** `fetchRepo` checks each declared file's raw-byte sha256 (`matchesRawSha256` in `lib/hash.ts`; the - records' `contentHash` stays CRLF-folded) before it returns the tree. A mismatch refuses, and nothing is written. + records' `contentHash` stays CRLF-folded) before it returns the tree. A mismatch, or a listed file the archive does + not ship as a regular file at its path, refuses, and nothing is written. - **Use.** The install set (`collectExpectedInstallPaths`), `add`'s file list (`capabilityCloneFiles`), the capability index, the settings copy and the `models` defaults come from it. An `applies` token outside this CLI's enum makes that capability `unknown` (seen and named, never installed). `models.defaults` passes the same diff --git a/docs/contributing.md b/docs/contributing.md index ad691bef..39616774 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -144,10 +144,10 @@ See [Architecture](architecture.md) for the architecture in depth (the archetype `lib/validate.ts` and `lib/install-capabilities.ts` handle the untrusted remote input that reaches the filesystem (capability names, install paths). They are not the whole boundary: `lib/tar-extract.ts` parses attacker-controlled archive headers, `lib/upstream-manifest.ts` parses the untrusted `pharn-install.json`, `lib/unknown-capabilities.ts` strips control characters from upstream text before display, and `lib/install-records.ts` and `lib/project-lock.ts` parse local-but-user-editable sidecars. Preserve their invariants when editing: - Strict regex/enum allowlists (`CAPABILITY_NAME_RE`, `VERSION_RE`, `COPY_FILENAME_RE`, `COMMIT_RE`, the `role`/`applies` enums), `..` rejection, and control-char rejection. -- `safeJoin` (in `lib/validate.ts`) guards every read/copy so nothing escapes its base directory; `install-capabilities.ts` adds a symlink-aware backstop at the write sites and rejects symlinked sources. +- `safeJoin` (in `lib/validate.ts`) guards every read/copy so nothing escapes its base directory; `install-capabilities.ts` adds a symlink-aware backstop at the write sites. The clone itself holds no links: the extractor writes only the manifest's listed paths (plus the files the CLI reads) as regular files and skips every other entry. - Remote fetches (`lib/skills-version.ts`, `lib/release.ts`) use `redirect: 'error'`, an 8s timeout, and a body cap (256KB for `SKILLS_VERSION`, 1MiB for a release object). - A new install (`pharn init`) defaults to the newest verified pharn-oss release (`DEFAULT_INIT_REF`, `lib/release.ts`); `update`/`add`/`status` follow the channel the config records, and an absent `ref` means the tip of `main`. The release resolve fails closed: a release that cannot be resolved refuses the command and never falls back to the tip of `main`. -- The repo download (`lib/repo.ts`) has its own, larger bounds: a 60s timeout, a 32MB archive cap, a 128MB extracted cap, and a 20,000-entry cap — enforced twice, including at `gunzipSync`. +- The repo download (`lib/repo.ts`) has its own, larger bounds: a 60s timeout, a 32MB archive cap, and, over the streamed decompression, a 200,000-header cap, a 1 GiB decompressed-bytes cap (a compression-bomb bound, not a repo-size limit) and a 128MB cap on the bytes written. ### pharn-oss's `models` rules — a pinned copy @@ -184,16 +184,18 @@ properties of a dependency_, which a version bump could move without any pharn t If you change either file, the guarantees they carry are the ones `THREAT-MODEL.md` §2/§4b and `LIMITS.md` §3a state — timeout, streamed-byte cap, decompressed-size cap, `redirect: 'error'`, -typeflag allowlist, `prefix`+`name` path reassembly, `..`/absolute rejection, single-root check, -`safeJoin` on every write, entry/byte caps, header checksums. Each has a test in +selection (only listed paths are written; every other entry is skipped), the regular-file-only rule at a listed path, +`prefix`+`name` path reassembly, `..`/absolute/`\`/`:` rejection, single-root check, `safeJoin` on every write, +header/scanned-byte/written-byte caps, header checksums. Each has a test in `tests/tar-extract.test.ts` or `tests/repo.test.ts`; keep them in step with the prose. Two rules that are easy to get wrong: -- **Skip pax headers, do not judge them.** Every codeload tarball opens with a `pax_global_header` - (typeflag `g`) whose single-segment name has no leading component to strip. Running the path rules - over it fails the first block of every real archive — a bug no hand-made fixture would catch, which - is why `tests/tar-extract.test.ts` builds its fixtures with one. +- **Judge only what is written.** Every codeload tarball opens with a `pax_global_header` (typeflag `g`) + whose single-segment name has no leading component to strip, and pharn-oss holds symlinks and long names + outside the install list. Running the entry rules over an entry pharn does not write fails every real + archive — a bug no hand-made fixture would catch, which is why `tests/tar-extract.test.ts` builds its + fixtures with one and pins the skip for every entry type. - **Reassemble the path before judging it.** ustar splits anything over 100 characters across the `prefix` and `name` header fields. Reading `name` alone yields a bare leaf that strip-1 then rejects, losing a large fraction of the tree rather than misplacing it. @@ -227,7 +229,7 @@ Two rules that are easy to get wrong: | `model-config.test.ts` / `model-config-parity.test.ts` | pharn-oss's `models` rules as copied; the copy pinned to pharn-oss's own checker | | `models-update.test.ts` / `upstream-models.test.ts` | `update`'s rows for the `models` block; reading pharn-oss's block | | `confirm.test.ts` / `repo.test.ts` / `banner.test.ts` / `format.test.ts` | helpers; the codeload fetch boundary; banner; format | -| `tar-extract.test.ts` | The ustar reader: strip-1, pax skip, prefix reassembly, and every rejection | +| `tar-extract.test.ts` | The ustar reader: selection (unlisted entries skipped), strip-1, prefix reassembly, every rejection at a listed path | | `index.test.ts` | argv dispatch: the per-command option allowlist, the arity gate, and their exit codes | | `project-lock.test.ts` + `-break` / `commands/lock.test.ts` | The single-writer lock: acquire/release, stale-break single-winner, and which commands take it | | `min-cli-gate.test.ts` / `semver.test.ts` | The `MIN_CLI` forward-compat gate and its version comparison | diff --git a/src/lib/repo.ts b/src/lib/repo.ts index a7004d44..61f6f122 100644 --- a/src/lib/repo.ts +++ b/src/lib/repo.ts @@ -1,7 +1,13 @@ import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { REPO, REPO_BRANCH, SKILLS_VERSION_FILE } from './constants.js'; +import { + CLAUDE_SETTINGS_FILE, + MIN_CLI_FILE, + REPO, + REPO_BRANCH, + SKILLS_VERSION_FILE, +} from './constants.js'; import { onFatalSignal } from './fatal-signal.js'; import { fetchCapped } from './fetch-capped.js'; import type { CappedResponse, FetchCappedError } from './fetch-capped.js'; @@ -10,9 +16,11 @@ import type { InstallSource } from './release.js'; import { readSkillsVersion } from './skills-version.js'; import { extractTarGz } from './tar-extract.js'; import { + MANIFEST_FILE, readUpstreamManifest, verifyUpstreamManifest, } from './upstream-manifest.js'; +import type { UpstreamManifest } from './upstream-manifest.js'; import { assertSafeString, COMMIT_RE, @@ -25,12 +33,34 @@ const FETCH_TIMEOUT_MS = 8000; // The clone timeout has to cover a ~2.5 MB streamed body, not just the response // headers, so it is deliberately not the 8 s the two metadata fetches use. const CLONE_TIMEOUT_MS = 60_000; -// Caps on both sides of the gunzip: the compressed cap is counted as bytes -// stream (codeload sends no content-length); the decompressed cap bounds a zip -// bomb. +// The compressed cap is counted as bytes stream (codeload sends no +// content-length). The extractor streams the decompressed tar, so the repo's +// own size bounds nothing: headers walked and decompressed bytes walked bound a +// compression bomb's work (both far above pharn-oss v7.25.5's 4,939 entries and +// 43 MB), and the written-byte cap bounds what reaches disk. const MAX_ARCHIVE_BYTES = 32 * 1024 * 1024; -const MAX_EXTRACTED_BYTES = 128 * 1024 * 1024; -const MAX_ENTRIES = 20_000; +const MAX_HEADERS = 200_000; +const MAX_SCANNED_BYTES = 1024 * 1024 * 1024; +const MAX_WRITTEN_BYTES = 128 * 1024 * 1024; +const LIMITS = { + maxHeaders: MAX_HEADERS, + maxScannedBytes: MAX_SCANNED_BYTES, + maxWrittenBytes: MAX_WRITTEN_BYTES, +}; + +/** + * The tree files the CLI reads itself, written whether or not the manifest + * lists them: the manifest, `SKILLS_VERSION` (the release check, the manifest's + * `skillsVersion` check), the optional `MIN_CLI` handshake, and + * `.claude/settings.json` (hook-wiring reads it even when it is not listed). + * Nothing else unlisted is ever written. + */ +export const CLONE_READ_FILES: readonly string[] = [ + MANIFEST_FILE, + SKILLS_VERSION_FILE, + MIN_CLI_FILE, + CLAUDE_SETTINGS_FILE, +]; // --------------------------------------------------------------------------- // Temp-clone lifecycle backstop — a net under each caller's `finally`, never a @@ -72,10 +102,12 @@ function installCleanupHandlers(): void { export interface FetchedRepo { // THE CLONE INVARIANT: the tree holds only regular files and directories, - // created by this process in a private `mkdtemp` dir (tar-extract.ts's - // typeflag allowlist; this module is the only producer, enforced by the - // clone-producer rule in eslint.config.mjs). Clone-side readers skip symlink/FIFO - // checks but keep type checks. Every DESTINATION guard is separate and stays. + // created by this process in a private `mkdtemp` dir, and only the files the + // manifest lists plus CLONE_READ_FILES (tar-extract.ts selects, then admits a + // regular file only; this module is the only producer, enforced by the + // clone-producer rule in eslint.config.mjs). Clone-side readers skip + // symlink/FIFO checks but keep type checks. Every DESTINATION guard is + // separate and stays. dir: string; // The commit recorded as `commit`: the COMMIT_RE-validated SHA the tarball // was fetched at, or `null` when it could not be resolved and the fetch @@ -101,7 +133,8 @@ export interface FetchedRepo { * (`sha` null). Provenance is by-SHA, NOT cryptographic (LIMITS.md §1b). * * Network floor: `redirect: 'error'`, deadlines and body caps; path floor: - * lib/tar-extract.ts. No `git` binary, no tarball cache. + * lib/tar-extract.ts, through extractPharnArchive. No `git` binary, no tarball + * cache. */ export async function fetchRepo(source: InstallSource): Promise { if (source.kind === 'release') return fetchAt(source, source.sha); @@ -124,25 +157,18 @@ async function fetchAt( liveClones.add(dir); try { const archive = await downloadArchive(ref); - extractTarGz(archive, dir, { - maxEntries: MAX_ENTRIES, - maxTotalBytes: MAX_EXTRACTED_BYTES, - }); - // A release's tree must BE the version its tag names, or `update`'s - // version compare would lie. Refused inside this try, so the tree is removed. - if (source.kind === 'release') { - const found = readSkillsVersion(dir); + await extractPharnArchive(archive, dir, (tree) => { + // A release's tree must BE the version its tag names, or `update`'s + // version compare would lie. Refused inside this try, so the tree is + // removed. + if (source.kind !== 'release') return; + const found = readSkillsVersion(tree); if (found !== source.version) { throw new ManifestValidationError( `Release ${source.tag} (${source.sha}) ships ${SKILLS_VERSION_FILE} ${found}, not ${source.version}; refusing to install a release whose content does not match its tag.`, ); } - } - // The install manifest is required (a tree without one is older than - // pharn-oss 7.21.0 and refused), validated by the one parser, and every - // file it declares is held to its raw sha256 HERE, before the tree is - // returned: no command can read a tree that fails. - verifyUpstreamManifest(dir, readUpstreamManifest(dir)); + }); } catch (err) { // Extraction is not transactional, so a partially-written tree must never // be returned. Callers treat a fetchRepo throw as fatal. @@ -163,6 +189,43 @@ async function fetchAt( }; } +/** + * Unpack a pharn-oss `.tar.gz` into `dir` (an empty directory this module + * created) and return its validated manifest. Two passes over the same bytes: + * + * 1. write only CLONE_READ_FILES; run `checkTree` (the release check); + * validate pharn-install.json through the one parser (a tree without one + * is older than pharn-oss 7.21.0 and refused); + * 2. write only the paths the manifest lists, then hold every listed file to + * its raw sha256, so a listed file that is missing (a pax record renamed + * it) or altered refuses the tree before any command can read it. + * + * Every other archive entry is skipped unwritten. Takes the archive's bytes, + * never a URL, so a local file can be checked with no network. Throws on any + * refusal; extraction is not transactional, so the caller removes `dir`. + */ +export async function extractPharnArchive( + archive: Buffer, + dir: string, + checkTree?: (dir: string) => void, +): Promise { + const first = await extractTarGz(archive, dir, { + select: new Set(CLONE_READ_FILES), + limits: LIMITS, + }); + checkTree?.(dir); + const manifest = readUpstreamManifest(dir); + await extractTarGz(archive, dir, { + select: new Set( + manifest.files.map((f) => f.path).filter((p) => !first.written.has(p)), + ), + limits: { ...LIMITS, maxWrittenBytes: MAX_WRITTEN_BYTES - first.bytes }, + root: first.root, + }); + verifyUpstreamManifest(dir, manifest); + return manifest; +} + /** * Download the repo tarball at `ref` into memory, bounded on both time and * size (`fetchCapped`; the decompressed size is bounded by the extract). diff --git a/src/lib/tar-extract.ts b/src/lib/tar-extract.ts index c7ce8662..386dda88 100644 --- a/src/lib/tar-extract.ts +++ b/src/lib/tar-extract.ts @@ -1,4 +1,4 @@ -import { gunzipSync } from 'node:zlib'; +import { createGunzip } from 'node:zlib'; import { mkdirSync, writeFileSync } from 'node:fs'; import { dirname } from 'node:path'; import { escapeUnsafe, hasUnsafeChars } from './terminal-safe.js'; @@ -8,32 +8,45 @@ import { safeJoin } from './validate.js'; * The tar half of pharn's fetch boundary — a minimal, strict ustar reader for * the ONE archive shape pharn consumes: GitHub's `codeload.../tar.gz/`. * In-repo rather than a dependency because these guarantees ARE the fetch - * boundary, unit-tested against hand-built adversarial archives; every - * unexpected entry is a THROW, never a silent drop. + * boundary, unit-tested against hand-built adversarial archives. * - * WHAT THE TREE CAN HOLD (the invariant `fetchRepo` states, lib/repo.ts): only - * regular files and directories, under `destDir` — the only writes are - * `mkdirSync` and `writeFileSync`, each through `safeJoin`. Clone-side readers - * rely on this instead of re-checking for links. + * SELECT, THEN JUDGE. The caller names the root-relative paths to write + * (`select`: the paths pharn-install.json lists, plus the few files the CLI + * reads itself, lib/repo.ts). Every other entry is skipped and never written, + * whatever its type or name: nothing unselected touches disk, so skipping is + * strictly safer than judging. A symlink, hard link, device, pax header, long + * or `:` name anywhere else in the repo no longer refuses the install. + * + * EVERY header is framing-checked, because the walk cannot find the next one + * without it: checksum, `ustar` magic, an octal `size`, the header and + * scanned-byte caps, and the end-of-archive marker with a zero tail. + * A SELECTED header gets the full rules: strict UTF-8, no control or format + * character, a regular file (typeflag '0' / NUL) only, its path rebuilt from + * `prefix` + `name`, refused when absolute or holding `..`, `\`, `:` or an + * empty or `.` segment, one root shared by every selected entry, one leading + * component stripped, `safeJoin`-contained, written once, within the + * written-byte cap. Contents are written verbatim, never executed. * - * ACCEPT typeflag '0' / NUL (regular file) and '5' (directory). - * SKIP typeflag 'g' (pax global header), payload UNREAD — every codeload - * tarball opens with one. It still counts toward `maxEntries`. - * REJECT everything else: 'x' (pax extended header), '1'/'2' (hard/symlink), - * '3'/'4' (devices), '6' (fifo), '7', GNU 'L'/'K', any unknown byte. + * WHAT THE TREE CAN HOLD (the invariant `fetchRepo` states, lib/repo.ts): only + * regular files and the directories above them, under `destDir`, at selected + * paths — the only writes are `mkdirSync` and `writeFileSync`, each through + * `safeJoin`. Clone-side readers rely on this instead of re-checking for links. * * PAX IS NEVER HONOURED: only the ustar `name`, `prefix`, `size` and - * `typeflag` are read. A pax record would be a second untrusted path/size - * source, and a writer emits 'x' exactly when the real path does not fit ustar - * (truncating it into `name`, where it would pass every rule), so 'x' is - * refused on its typeflag. Ignoring 'g' is safe: its defaults are never - * consulted, and the walk is framed by the ustar `size` alone (a disagreeing - * stream fails the next header's checksum or magic). Cost: a `g` meaning "put - * everything at X" is extracted at its ustar paths, contained. + * `typeflag` are read, never a pax payload. A pax 'x' header (and GNU 'L'/'K') + * rewrites the NEXT entry's path or size, so it is skipped together with the + * entry it modifies, as unselected. When that entry's ustar name is a selected + * path, it is refused: pharn will not install a listed file whose real path or + * size it ignores. When the pax record renamed a listed file away from its + * ustar name, that file is simply missing, and the manifest's sha256 check + * (`verifyUpstreamManifest`) refuses the tree. A 'g' (global) header — every + * codeload tarball opens with one — is skipped and modifies nothing: its + * defaults are never consulted, and the walk is framed by the ustar `size` + * alone (a disagreeing stream fails the next header's checksum or magic). * - * Every accepted path is rebuilt from `prefix` + `name`, refused when absolute - * or holding `..`, `\` or `:`, stripped of one leading component, and resolved - * through `safeJoin`. Contents are written verbatim, never executed. + * The decompressed tar is streamed, never held whole, so a repo larger than the + * written-byte cap still installs; the scanned-byte cap only bounds the work a + * compression bomb can cause. */ /** A ustar header block is exactly 512 bytes; payloads are padded to that. */ const BLOCK = 512; @@ -50,15 +63,33 @@ const OFF_MAGIC = 257; const OFF_PREFIX = 345; const LEN_PREFIX = 155; +/** Headers that rewrite the NEXT entry's path, size or link name. */ +const MODIFIERS = new Set(['x', 'L', 'K']); + export interface TarLimits { - /** Maximum number of ACCEPTed entries. */ - maxEntries: number; - /** - * The largest DECOMPRESSED tar `extractTarGz` accepts (gunzip's - * `maxOutputLength`). The tar holds every byte an entry writes, so this is - * also the bound on bytes written; `extractTar` itself does not re-count. - */ - maxTotalBytes: number; + /** Headers walked, of any type, selected or not. */ + maxHeaders: number; + /** Decompressed bytes walked: bounds a compression bomb's work, not the repo. */ + maxScannedBytes: number; + /** Bytes written: the sum of the selected files' sizes. */ + maxWrittenBytes: number; +} + +export interface ExtractOptions { + /** Root-relative paths to write; every other entry is skipped unwritten. */ + select: ReadonlySet; + limits: TarLimits; + /** The archive's root component, when an earlier pass already learned it. */ + root?: string | null; +} + +export interface ExtractResult { + /** The root-relative paths written. */ + written: ReadonlySet; + /** Their total size in bytes. */ + bytes: number; + /** The root component every selected entry shared (`null`: none selected). */ + root: string | null; } /** Every refusal this module makes, so callers can tell it from an fs error. */ @@ -114,6 +145,21 @@ function readPathField(block: Buffer, offset: number, length: number): string { } } +/** + * The selection key of a header: its raw `prefix`/`name` bytes (latin1, so + * byte for byte) with everything up to the first `/` — the archive root — + * stripped; `null` when there is no `/`. Every selected path is ASCII, so an + * exact membership test on these bytes is exact, and an unselected name is + * never decoded, judged or printed. + */ +function selectionKey(block: Buffer): string | null { + const name = readString(block, OFF_NAME, LEN_NAME); + const prefix = readString(block, OFF_PREFIX, LEN_PREFIX); + const raw = prefix === '' ? name : `${prefix}/${name}`; + const slash = raw.indexOf('/'); + return slash === -1 ? null : raw.slice(slash + 1); +} + /** * A ustar numeric field: octal digits, space- or NUL-terminated. GNU base-256 * (high bit on the first byte) fails the octal test. Only ASCII space is @@ -161,17 +207,6 @@ function describeTypeflag(typeflag: string): string { : `'${typeflag}'`; } -/** Refuse any non-zero byte from `from` to the end (after the end marker). */ -function assertZeroTail(tar: Buffer, from: number): void { - for (let i = from; i < tar.length; i += 1) { - if (tar[i] !== 0) { - throw new TarExtractError( - 'tar archive has data after its end-of-archive marker.', - ); - } - } -} - /** True when the block is 512 NUL bytes — the end-of-archive marker. */ function isZeroBlock(block: Buffer): boolean { for (const byte of block) if (byte !== 0) return false; @@ -197,8 +232,8 @@ function checksumOk(block: Buffer): boolean { } /** - * Apply the path rules to an ACCEPTed entry and return its destination-relative - * path, or `null` for the archive's own root directory. + * Apply the path rules to a selected file entry and return its + * destination-relative path and root component. * * The full path is reconstructed from `prefix` + `name` BEFORE any rule runs: * ustar splits a path over 100 characters across the two, and `name` alone @@ -206,32 +241,26 @@ function checksumOk(block: Buffer): boolean { */ function resolveEntryPath( fullPath: string, - isDirectory: boolean, expectedRoot: string | null, -): { rel: string | null; root: string } { - if (fullPath === '') { - throw new TarExtractError('tar entry has an empty path.'); - } +): { rel: string; root: string } { if (fullPath.startsWith('/')) { throw new TarExtractError(`tar entry has an absolute path: ${fullPath}`); } // POSIX writes `a\..\..\evil` as ONE literal name; win32 reads the same - // bytes as a path (and `C:` as a drive). pharn-oss ships neither character. + // bytes as a path (and `C:` as a drive). pharn-oss lists neither character. if (/[\\:]/.test(fullPath)) { throw new TarExtractError( `tar entry path contains a backslash or colon, which pharn does not accept: ${fullPath}`, ); } - const segments = fullPath.replace(/\/+$/, '').split('/'); - for (const segment of segments) { - if (segment === '..') { - throw new TarExtractError( - `tar entry escapes the archive root: ${fullPath}`, - ); - } + const segments = fullPath.split('/'); + if (segments.includes('..')) { + throw new TarExtractError( + `tar entry escapes the archive root: ${fullPath}`, + ); } const root = segments[0]!; - if (root === '' || root === '.') { + if (root === '.') { throw new TarExtractError( `tar entry has no leading component: ${fullPath}`, ); @@ -251,132 +280,245 @@ function resolveEntryPath( `tar entry has an empty or "." path segment: ${fullPath}`, ); } - if (rest.length === 0) { - // The root directory entry itself: nothing to write, not a failure. - if (isDirectory) return { rel: null, root }; - throw new TarExtractError( - `tar entry has no path below the archive root: ${fullPath}`, - ); - } return { rel: rest.join('/'), root }; } +/** The selected file whose payload is being collected. */ +interface Pending { + target: string; + chunks: Buffer[]; +} + /** - * Extract a gzipped tar into `destDir`, stripping the single leading path - * component. Throws `TarExtractError` on any refusal — a caller that sees one - * must treat the destination as unusable and remove it, since extraction is not - * transactional. + * The walk itself, incremental so the decompressed tar can be streamed: `push` + * takes chunks of any size (a header or payload may straddle two), `finish` + * refuses an archive that ended early. A selected file is written only once + * its whole payload has arrived, so a truncated archive writes no partial file. */ -export function extractTarGz( - archive: Buffer, - destDir: string, - limits: TarLimits, -): void { - let tar: Buffer; - try { - tar = gunzipSync(archive, { maxOutputLength: limits.maxTotalBytes }); - } catch (err) { - throw new TarExtractError( - `could not decompress the fetched archive: ${(err as Error).message}`, - ); +class TarWalker { + private readonly written = new Set(); + private bytes = 0; + private headers = 0; + private scanned = 0; + private root: string | null; + // Header bytes received so far (a header can straddle two chunks). + private carry: Buffer[] = []; + private carryLength = 0; + // Payload and padding bytes of the current entry still to come. + private dataLeft = 0; + private padLeft = 0; + private pending: Pending | null = null; + // The previous header was a modifier ('x', 'L', 'K'), so this one's ustar + // path and size may not be the real ones. + private modified = false; + private ended = false; + + constructor( + private readonly destDir: string, + private readonly options: ExtractOptions, + ) { + this.root = options.root ?? null; } - extractTar(tar, destDir, limits); -} -/** The uncompressed half, split out so tests can build tar bytes directly. */ -export function extractTar( - tar: Buffer, - destDir: string, - limits: TarLimits, -): void { - let offset = 0; - let entries = 0; - let expectedRoot: string | null = null; + push(chunk: Buffer): void { + this.scanned += chunk.length; + if (this.scanned > this.options.limits.maxScannedBytes) { + throw new TarExtractError( + `tar archive decompresses to more than ${this.options.limits.maxScannedBytes} bytes.`, + ); + } + let at = 0; + while (at < chunk.length) { + if (this.ended) { + // After the end-of-archive marker everything must be zero padding, so + // a zero block cannot end the walk early and drop the rest in silence. + if (!isZeroBlock(chunk.subarray(at))) { + throw new TarExtractError( + 'tar archive has data after its end-of-archive marker.', + ); + } + return; + } + if (this.dataLeft > 0) { + const n = Math.min(this.dataLeft, chunk.length - at); + this.pending?.chunks.push(chunk.subarray(at, at + n)); + this.dataLeft -= n; + at += n; + if (this.dataLeft === 0) this.writePending(); + continue; + } + if (this.padLeft > 0) { + const n = Math.min(this.padLeft, chunk.length - at); + this.padLeft -= n; + at += n; + continue; + } + const n = Math.min(BLOCK - this.carryLength, chunk.length - at); + this.carry.push(chunk.subarray(at, at + n)); + this.carryLength += n; + at += n; + if (this.carryLength === BLOCK) { + const block = + this.carry.length === 1 ? this.carry[0]! : Buffer.concat(this.carry); + this.carry = []; + this.carryLength = 0; + this.header(block); + } + } + } + + finish(): ExtractResult { + if (this.dataLeft > 0) { + throw new TarExtractError( + 'tar entry runs past the end of the archive — truncated.', + ); + } + // The walk ran out of bytes without meeting a zero block: the archive was + // cut short (every real tar ends with at least one). + if (!this.ended) { + throw new TarExtractError( + 'tar archive has no end-of-archive marker — truncated.', + ); + } + return { written: this.written, bytes: this.bytes, root: this.root }; + } - while (offset + BLOCK <= tar.length) { - const header = tar.subarray(offset, offset + BLOCK); - // The end-of-archive marker; everything after it must be zero padding, so - // a zero block cannot end the walk early and drop the rest in silence. - if (isZeroBlock(header)) { - assertZeroTail(tar, offset + BLOCK); + private header(block: Buffer): void { + if (isZeroBlock(block)) { + this.ended = true; return; } - if (!checksumOk(header)) { + if (!checksumOk(block)) { throw new TarExtractError( 'tar header failed its checksum — the archive is corrupt or truncated.', ); } // Every header git archive writes is ustar (`ustar\0`); old GNU writes // `ustar ` — the 5-byte prefix admits both and nothing else. - if (header.toString('latin1', OFF_MAGIC, OFF_MAGIC + 5) !== 'ustar') { + if (block.toString('latin1', OFF_MAGIC, OFF_MAGIC + 5) !== 'ustar') { throw new TarExtractError( 'tar header is not a ustar header (missing "ustar" magic).', ); } - - const size = readOctal(header, OFF_SIZE, LEN_SIZE); - const dataStart = offset + BLOCK; - const dataEnd = dataStart + size; - if (dataEnd > tar.length) { + const size = readOctal(block, OFF_SIZE, LEN_SIZE); + this.headers += 1; + if (this.headers > this.options.limits.maxHeaders) { throw new TarExtractError( - 'tar entry runs past the end of the archive — truncated.', + `tar archive has more than ${this.options.limits.maxHeaders} headers.`, ); } - const next = dataStart + Math.ceil(size / BLOCK) * BLOCK; - const typeflag = String.fromCharCode(header[OFF_TYPEFLAG]!); + const typeflag = String.fromCharCode(block[OFF_TYPEFLAG]!); + const modified = this.modified; + // A 'g' modifies nothing, so it neither sets nor consumes the flag. + if (MODIFIERS.has(typeflag)) this.modified = true; + else if (typeflag !== 'g') this.modified = false; - // SKIP — a pax GLOBAL header, payload unread; it counts toward the cap. - if (typeflag === 'g') { - entries += 1; - if (entries > limits.maxEntries) { - throw new TarExtractError( - `tar archive has more than ${limits.maxEntries} entries.`, - ); - } - offset = next; - continue; + const key = selectionKey(block); + if (key !== null && this.options.select.has(key)) { + this.accept(block, typeflag, modified, size); } + this.dataLeft = size; + this.padLeft = Math.ceil(size / BLOCK) * BLOCK - size; + if (size === 0) this.writePending(); + } - // The FULL path is judged before any other entry rule, so no later message + /** The full rules, for a header at a selected path; arms `pending`. */ + private accept( + block: Buffer, + typeflag: string, + modified: boolean, + size: number, + ): void { + // The FULL path is judged before any other rule, so no later message // interpolates a control character from it. - const name = readPathField(header, OFF_NAME, LEN_NAME); - const prefix = readPathField(header, OFF_PREFIX, LEN_PREFIX); + const name = readPathField(block, OFF_NAME, LEN_NAME); + const prefix = readPathField(block, OFF_PREFIX, LEN_PREFIX); const fullPath = prefix === '' ? name : `${prefix}/${name}`; assertDisplayablePath(fullPath); - - const isFile = typeflag === '0' || typeflag === '\0'; - const isDirectory = typeflag === '5'; - if (!isFile && !isDirectory) { + if (typeflag !== '0' && typeflag !== '\0') { + throw new TarExtractError( + `tar entry has an unsupported type ${describeTypeflag(typeflag)} at a path pharn installs (only a regular file is accepted there): ${fullPath}`, + ); + } + if (modified) { + throw new TarExtractError( + `tar entry follows a pax extended or GNU long-name header, whose records pharn does not honour, at a path pharn installs: ${fullPath}`, + ); + } + const { rel, root } = resolveEntryPath(fullPath, this.root); + this.root = root; + if (this.written.has(rel)) { throw new TarExtractError( - `tar entry has an unsupported type ${describeTypeflag(typeflag)}: ${fullPath}`, + `tar archive holds this path twice: ${fullPath}`, ); } + this.written.add(rel); + this.bytes += size; + if (this.bytes > this.options.limits.maxWrittenBytes) { + throw new TarExtractError( + `the files pharn installs from this archive exceed ${this.options.limits.maxWrittenBytes} bytes.`, + ); + } + // safeJoin is the lexical containment backstop behind the segment rules. + this.pending = { target: safeJoin(this.destDir, rel), chunks: [] }; + } - const { rel, root } = resolveEntryPath(fullPath, isDirectory, expectedRoot); - expectedRoot = root; + private writePending(): void { + if (this.pending === null) return; + const { target, chunks } = this.pending; + this.pending = null; + mkdirSync(dirname(target), { recursive: true }); + writeFileSync(target, Buffer.concat(chunks)); + } +} - if (rel !== null) { - entries += 1; - if (entries > limits.maxEntries) { - throw new TarExtractError( - `tar archive has more than ${limits.maxEntries} entries.`, - ); - } - // safeJoin is the lexical containment backstop behind the segment rules. - const target = safeJoin(destDir, rel); - if (isDirectory) { - mkdirSync(target, { recursive: true }); - } else { - mkdirSync(dirname(target), { recursive: true }); - writeFileSync(target, tar.subarray(dataStart, dataEnd)); +/** + * Extract the selected files of an uncompressed tar into `destDir`, stripping + * the single leading path component. `tar` may come in chunks of any size. + * Throws `TarExtractError` on any refusal — a caller that sees one must treat + * the destination as unusable and remove it, since extraction is not + * transactional. + */ +export function extractTar( + tar: Buffer | readonly Buffer[], + destDir: string, + options: ExtractOptions, +): ExtractResult { + const walker = new TarWalker(destDir, options); + for (const chunk of Buffer.isBuffer(tar) ? [tar] : tar) walker.push(chunk); + return walker.finish(); +} + +/** + * `extractTar` over a gzipped archive, decompressed as a stream so the whole + * tar is never held in memory. Takes the archive's bytes, never a URL, so a + * local file goes through the same walk as a download. + */ +export async function extractTarGz( + archive: Buffer, + destDir: string, + options: ExtractOptions, +): Promise { + const walker = new TarWalker(destDir, options); + const gunzip = createGunzip(); + gunzip.end(archive); + // A refusal from the walk is rethrown as itself; only a gunzip failure is + // reported as a decompression error. + let refusal: unknown = null; + try { + for await (const chunk of gunzip) { + try { + walker.push(chunk as Buffer); + } catch (err) { + refusal = err; + break; } } - - offset = next; + } catch (err) { + throw new TarExtractError( + `could not decompress the fetched archive: ${(err as Error).message}`, + ); } - // The walk ran out of bytes without meeting a zero block: the archive was cut - // short (every real tar ends with at least one). - throw new TarExtractError( - 'tar archive has no end-of-archive marker — truncated.', - ); + if (refusal !== null) throw refusal; + return walker.finish(); } diff --git a/src/lib/upstream-manifest.ts b/src/lib/upstream-manifest.ts index 92e57a4d..d2dbe91e 100644 --- a/src/lib/upstream-manifest.ts +++ b/src/lib/upstream-manifest.ts @@ -42,7 +42,11 @@ import type { // safeJoin-contained, every `dest` must lie inside the CLI-owned outer bound // (isPharnOwnedPath — never the manifest's own `installRoots`), and fetchRepo // verifies each file's RAW sha256 right after extraction, before any command -// can read the tree, so a mismatch refuses with nothing written. +// can read the tree, so a mismatch refuses with nothing written. The extractor +// writes only the paths listed here plus the few files the CLI reads itself +// (CLONE_READ_FILES, lib/repo.ts), so this file is validated between its two +// passes, before the tree holds anything it lists: no check here may probe the +// tree for a listed file. // // ONE parser: readUpstreamManifest is the only reader. verifyUpstreamManifest // takes its result, and every branch point re-reads through it, so there is no @@ -55,7 +59,7 @@ export const MANIFEST_FILE = 'pharn-install.json'; export const MANIFEST_SCHEMA_VERSION = 1; // pharn-oss 7.21.0's file is about 180 KB. export const MAX_MANIFEST_BYTES = 4 * 1024 * 1024; -// The extractor's own entry cap: a tree cannot hold more files than this. +// The most files a manifest may list, and so the most the extractor writes. export const MAX_MANIFEST_FILES = 20_000; const POLICIES = ['managed', 'if-absent'] as const; @@ -158,9 +162,10 @@ export function readUpstreamManifest(repoDir: string): UpstreamManifest { ); } const skillsVersion = checkSkillsVersion(repoDir, raw.skillsVersion); - checkLayout(repoDir, raw.layout); + checkLayout(raw.layout); const capabilities = checkCapabilities(raw.capabilities); const files = checkFiles(repoDir, raw.files, capabilities); + checkLayoutMarker(repoDir, files); const modelsDefaults = checkModels(raw.models); checkInstallRoots(raw.installRoots); return { skillsVersion, capabilities, files, modelsDefaults }; @@ -180,8 +185,8 @@ function checkSkillsVersion(repoDir: string, value: unknown): string { } // The only layout a manifest may declare is the one this CLI knows as `pharn`, -// with its own marker and capability subtrees, and the tree must be it. -function checkLayout(repoDir: string, layout: unknown): void { +// with its own marker and capability subtrees. +function checkLayout(layout: unknown): void { const pharn = layoutPaths('pharn'); const subtrees = isPlainObject(layout) ? layout.capabilitySubtrees : null; const known = @@ -197,9 +202,23 @@ function checkLayout(repoDir: string, layout: unknown): void { `pharn-oss's ${MANIFEST_FILE} declares a layout this pharn does not know (${escapeUnsafe(show(layout))}). Upgrade pharn (\`npm install -g @pharn-dev/pharn@latest\`) and re-run. Nothing was written.`, ); } - if (!isPharnLayout(repoDir)) { +} + +// The layout's marker must be in the tree. The extractor writes only listed +// files (each proved present by verifyUpstreamManifest) plus a few root and +// .claude files, so once extracted the tree has the marker exactly when a +// listed file lies under it. Accepting a listed file lets this run between the +// extractor's passes, before the listed files are written. +function checkLayoutMarker( + repoDir: string, + files: readonly ManifestFile[], +): void { + const listed = files.some((f) => + f.path.startsWith(`${PHARN_CONTRACTS_DIR}/`), + ); + if (!listed && !isPharnLayout(repoDir)) { throw refuse( - `declares the pharn layout, but the tree has no ${PHARN_CONTRACTS_DIR}`, + `declares the pharn layout, but the tree has no ${PHARN_CONTRACTS_DIR} and it lists no file there`, ); } } diff --git a/tests/commands/init.test.ts b/tests/commands/init.test.ts index ced7c9a7..84c0d4da 100644 --- a/tests/commands/init.test.ts +++ b/tests/commands/init.test.ts @@ -971,13 +971,14 @@ describe('a fresh install', () => { }); // pharn/pharn-contracts is the pharn layout's marker: a manifest that - // declares that layout over a tree without it is refused, never installed. - it('a clone with no pharn-contracts is refused: its manifest declares a layout the tree lacks', async () => { + // declares that layout but lists nothing under it is refused, never + // installed (only listed files are extracted, so the tree would lack it). + it('a clone with no pharn-contracts is refused: its manifest declares a layout it does not list', async () => { delete upstream.tree['pharn/pharn-contracts/finding-shape.md']; const before = snapshot(); expect(await run(() => runInit({ yes: true }))).toBe(1); expect(errors()).toContain( - 'declares the pharn layout, but the tree has no pharn/pharn-contracts', + 'declares the pharn layout, but the tree has no pharn/pharn-contracts and it lists no file there', ); expect(snapshot()).toEqual(before); }); diff --git a/tests/project-lock.test.ts b/tests/project-lock.test.ts index 21b05ef5..99fd1e03 100644 --- a/tests/project-lock.test.ts +++ b/tests/project-lock.test.ts @@ -804,11 +804,23 @@ describe('withProjectLock — a fatal signal while held', () => { // re-raise land. A handler that re-raises kills the process before that // listener runs; one that swallows the signal lets the body print the marker // in milliseconds. + // The signal is processed on a later loop turn. Node's signal handles are + // unref'd, so with nothing else ref'd the child would exit (code 13, an + // unsettled top-level await) before it: a ref'd timer holds the loop open + // until the handlers have run, instead of whatever handle happens to be live. const SIGNAL_HANDLED = ` const signalHandled = (s) => - new Promise((resolve) => - process.once(s, () => setImmediate(() => setImmediate(resolve))), - ); + new Promise((resolve) => { + const alive = setInterval(() => {}, 1000); + process.once(s, () => + setImmediate(() => + setImmediate(() => { + clearInterval(alive); + resolve(); + }), + ), + ); + }); `; /** Killed by `sig` — as a signal, or as the shell's 128 + n. */ diff --git a/tests/repo.test.ts b/tests/repo.test.ts index aaae00c2..975e76c2 100644 --- a/tests/repo.test.ts +++ b/tests/repo.test.ts @@ -1,5 +1,6 @@ import { existsSync, + lstatSync, mkdtempSync, readdirSync, readFileSync, @@ -12,6 +13,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { REPO, REPO_BRANCH } from '../src/lib/constants.js'; import { ManifestValidationError } from '../src/lib/validate.js'; import { UpstreamManifestError } from '../src/lib/upstream-manifest.js'; +import { TarExtractError } from '../src/lib/tar-extract.js'; import { codeloadArchive } from './support/tar-fixture.js'; import { MANIFEST, @@ -21,7 +23,8 @@ import { withManifest, } from './support/harness.js'; -const { fetchRepo, fetchCommitSha } = await import('../src/lib/repo.js'); +const { CLONE_READ_FILES, extractPharnArchive, fetchRepo, fetchCommitSha } = + await import('../src/lib/repo.js'); // A real 40-char lowercase-hex commit SHA (the SHA-1 of the empty blob) — the // form fetchRepo validates against COMMIT_RE before it fetches or records it. @@ -658,3 +661,196 @@ describe('fetchRepo — a tree that declares pharn-install.json (CORE-194)', () expect(leftoverTempDirs()).toEqual([]); }); }); + +// CORE-386: only the paths pharn-install.json lists (plus the files the CLI +// reads itself) are unpacked. pharn-oss v7.25.3–v7.25.5 committed symlinks +// under .claude/skills/, outside the manifest, and every install failed. +describe('fetchRepo — only the listed paths are unpacked (CORE-386)', () => { + const release = { + kind: 'release' as const, + tag: 'v7.20.0', + version: '7.20.0', + sha: VALID_SHA, + }; + const ROOT = `pharn-oss-${VALID_SHA.slice(0, 7)}`; + + beforeEach(() => { + sandbox = mkdtempSync(join(tmpdir(), 'pharn-repo-sandbox-')); + process.env.TMPDIR = sandbox; + process.env.TEMP = sandbox; + process.env.TMP = sandbox; + }); + + afterEach(() => { + for (const [key, value] of Object.entries(realTmp)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + rmSync(sandbox, { recursive: true, force: true }); + vi.unstubAllGlobals(); + }); + + /** A pax extended-header record, ` =\n` (self-counting). */ + function paxRecord(keyword: string, value: string): string { + const body = ` ${keyword}=${value}\n`; + let len = body.length + 1; + while (String(len).length + body.length !== len) + len = String(len).length + body.length; + return `${len}${body}`; + } + + /** + * The codeload shape around `tree`, with `odd` entries spliced in right after + * the root directory and `replace` swapping a tree file's own entry for raw + * entries (a symlink at a listed path, a pax-renamed file). + */ + function archiveWith( + tree: Record, + odd: Buffer[], + replace: Record = {}, + ): Buffer { + const parts = [ + entry('pax_global_header', 'g', `52 comment=${VALID_SHA}\n`), + entry(`${ROOT}/`, '5'), + ...odd, + ]; + for (const rel of Object.keys(tree).sort()) { + parts.push( + ...(replace[rel] ?? [entry(`${ROOT}/${rel}`, '0', tree[rel])]), + ); + } + parts.push(Buffer.alloc(BLOCK * 2)); + return gzipSync(Buffer.concat(parts)); + } + + const serve = (bytes: Buffer): void => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => tarResponse(bytes, 4096)), + ); + }; + + /** Every regular file under `dir`, relative and sorted. */ + function filesUnder(dir: string): string[] { + return (readdirSync(dir, { recursive: true }) as string[]) + .filter((rel) => lstatSync(join(dir, rel)).isFile()) + .sort(); + } + + // Each entry v7.25.5 (or a future pharn-oss) could carry outside the list. + const UNLISTED: Buffer[] = [ + entry(`${ROOT}/.claude/skills/pharn-cli`, '2'), // a symlink + entry(`${ROOT}/.dev/hard`, '1'), // a hard link + entry( + `${ROOT}/PaxHeaders/long`, + 'x', + paxRecord('path', `${ROOT}/.dev/${'s'.repeat(120)}.md`), + ), + entry(`${ROOT}/0123456789abcdef.data`, '0', 'long-named\n'), + entry(`${ROOT}/.dev/a:b.md`, '0', 'colon\n'), + entry(`${ROOT}/.dev/notes.md`, '0', 'an unlisted regular file\n'), + ]; + + it('installs past a symlink, hard link, pax header, long and colon name outside the list, writing none of them', async () => { + const tree = manifestTree('7.20.0'); + serve(archiveWith(tree, UNLISTED)); + const repo = await fetchRepo(release); + try { + const listed = ( + JSON.parse(tree[MANIFEST]!) as { files: { path: string }[] } + ).files.map((f) => f.path); + const expected = new Set([ + ...listed, + ...CLONE_READ_FILES.filter((f) => f in tree), + ]); + expect(filesUnder(repo.dir)).toEqual([...expected].sort()); + expect(existsSync(join(repo.dir, '.dev'))).toBe(false); + expect(existsSync(join(repo.dir, '.claude/skills/pharn-cli'))).toBe( + false, + ); + expect(existsSync(join(repo.dir, 'PaxHeaders'))).toBe(false); + } finally { + repo.cleanup(); + } + }); + + it('refuses a symlink AT a listed path, and removes the tree', async () => { + serve( + archiveWith(manifestTree('7.20.0'), [], { + [SECURITY]: [entry(`${ROOT}/${SECURITY}`, '2')], + }), + ); + const err = await fetchRepo(release).catch((e: unknown) => e); + expect(err).toBeInstanceOf(TarExtractError); + expect((err as Error).message).toMatch(/unsupported type '2'/); + expect((err as Error).message).toContain(SECURITY); + expect(leftoverTempDirs()).toEqual([]); + }); + + it('refuses a listed file that follows a pax extended header, and removes the tree', async () => { + const tree = manifestTree('7.20.0'); + serve( + archiveWith(tree, [], { + [SECURITY]: [ + entry(`${ROOT}/PaxHeaders/security.md`, 'x', paxRecord('mtime', '1')), + entry(`${ROOT}/${SECURITY}`, '0', tree[SECURITY]), + ], + }), + ); + const err = await fetchRepo(release).catch((e: unknown) => e); + expect(err).toBeInstanceOf(TarExtractError); + expect((err as Error).message).toMatch(/pax extended or GNU long-name/); + expect(leftoverTempDirs()).toEqual([]); + }); + + it('fails the hash check when a pax record renamed a listed file away from its ustar name', async () => { + const tree = manifestTree('7.20.0'); + serve( + archiveWith(tree, [], { + [SECURITY]: [ + entry( + `${ROOT}/PaxHeaders/security.md`, + 'x', + paxRecord('path', `${ROOT}/${SECURITY}`), + ), + entry(`${ROOT}/0123456789abcdef.data`, '0', tree[SECURITY]), + ], + }), + ); + const err = await fetchRepo(release).catch((e: unknown) => e); + expect(err).toBeInstanceOf(UpstreamManifestError); + expect((err as Error).message).toContain( + `declares ${SECURITY}, which the tree does not ship as a file`, + ); + expect(leftoverTempDirs()).toEqual([]); + }); + + it('extracts a local archive with no network: the CLI-read files first, then the listed ones', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => { + throw new Error('no network in this test'); + }), + ); + const tree = manifestTree('7.20.0'); + const dir = mkdtempSync(join(sandbox, 'local-')); + const seen: boolean[] = []; + const manifest = await extractPharnArchive( + archiveWith(tree, UNLISTED), + dir, + (d) => { + seen.push(existsSync(join(d, MANIFEST)), existsSync(join(d, SECURITY))); + }, + ); + // Between the passes the manifest is on disk and no listed file is yet. + expect(seen).toEqual([true, false]); + expect(manifest.files.map((f) => f.path)).toContain(SECURITY); + expect(readFileSync(join(dir, SECURITY), 'utf8')).toBe(tree[SECURITY]); + expect(existsSync(join(dir, '.dev'))).toBe(false); + // The tree check is optional (a local file has no tag to hold it to). + const again = mkdtempSync(join(sandbox, 'local-')); + await expect( + extractPharnArchive(archiveWith(tree, UNLISTED), again), + ).resolves.toMatchObject({ skillsVersion: '7.20.0' }); + }); +}); diff --git a/tests/tar-extract.test.ts b/tests/tar-extract.test.ts index 4bc09752..9a6caa86 100644 --- a/tests/tar-extract.test.ts +++ b/tests/tar-extract.test.ts @@ -1,4 +1,4 @@ -import { existsSync, lstatSync, readFileSync, readdirSync } from 'node:fs'; +import { lstatSync, mkdtempSync, readFileSync, readdirSync } from 'node:fs'; import { join } from 'node:path'; import { gzipSync } from 'node:zlib'; import { describe, expect, it } from 'vitest'; @@ -8,6 +8,7 @@ import { extractTarGz, TarExtractError, } from '../src/lib/tar-extract.js'; +import type { ExtractOptions, TarLimits } from '../src/lib/tar-extract.js'; import { hasUnsafeChars } from '../src/lib/terminal-safe.js'; import { codeloadArchive } from './support/tar-fixture.js'; @@ -16,11 +17,22 @@ import { codeloadArchive } from './support/tar-fixture.js'; // refuses to write — an absolute path, a `..` segment, a device node, a header // whose checksum does not match. A fixture generator that can only produce // well-formed archives cannot exercise a single rejection. +// +// CORE-386: the extractor writes only the SELECTED paths (pharn-install.json's +// list plus the files the CLI reads). Every block below states which side of +// the selection its entry sits on: outside it, any entry is skipped and nothing +// is written for it; at a selected path, every rule applies. const BLOCK = 512; -const LIMITS = { maxEntries: 1000, maxTotalBytes: 1024 * 1024 }; +const LIMITS: TarLimits = { + maxHeaders: 1000, + maxScannedBytes: 8 * 1024 * 1024, + maxWrittenBytes: 1024 * 1024, +}; /** An escape byte, written as a code point so no raw control char sits in this source. */ const ESC = '\u001b'; +const ROOT = 'pharn-oss-abc1234'; +const at = (rel: string): string => `${ROOT}/${rel}`; interface EntryInit { name: string; @@ -86,8 +98,7 @@ function tar(entries: EntryInit[]): Buffer { /** * One pax record, ` =\n`, where `` counts the whole * record INCLUDING its own digits — so the width is self-referential and has to - * be solved for, which is exactly the arithmetic a hand-written literal gets - * wrong (and which the reader now rejects rather than tolerates). + * be solved for. */ function paxRecord(keyword: string, value: string): string { const body = ` ${keyword}=${value}\n`; @@ -108,94 +119,116 @@ const GLOBAL_HEADER: EntryInit = { /** The shape every real codeload archive has, minus the entries under test. */ function githubArchive(entries: EntryInit[]): Buffer { - return tar([ - // GitHub's first entry, always. Single-segment name, no leading component. - GLOBAL_HEADER, - { name: 'pharn-oss-abc1234/', type: '5' }, - ...entries, - ]); + return tar([GLOBAL_HEADER, { name: `${ROOT}/`, type: '5' }, ...entries]); } -describe('extractTar', () => { - const tmp = useTmpDir(); +/** One selected file every archive below carries, so "nothing else" is visible. */ +const KEEP: EntryInit = { name: at('SKILLS_VERSION'), data: '1.0.0\n' }; - it('strips one component and writes the tree', () => { - const dest = tmp.path(); - extractTar( +function opts( + select: Iterable = ['SKILLS_VERSION'], + limits: TarLimits = LIMITS, +): ExtractOptions { + return { select: new Set(select), limits }; +} + +/** Every path under `dir`, files and directories, relative and sorted. */ +function treeOf(dir: string): string[] { + return (readdirSync(dir, { recursive: true }) as string[]) + .map((p) => p.split('\\').join('/')) + .sort(); +} + +/** Every path under `dir` that lstat says is neither a file nor a directory. */ +function nonFileOrDir(dir: string): string[] { + return treeOf(dir).filter((rel) => { + const st = lstatSync(join(dir, rel)); + return !st.isFile() && !st.isDirectory(); + }); +} + +// One temp dir per test; `fresh()` hands out an empty directory inside it. +const tmp = useTmpDir(); +const fresh = (): string => mkdtempSync(join(tmp.path(), 'dest-')); + +/** The refusal message, or 'accepted'. */ +function refusal(archive: Buffer, options = opts(), dest = fresh()): string { + try { + extractTar(archive, dest, options); + } catch (err) { + expect(err).toBeInstanceOf(TarExtractError); + return (err as Error).message; + } + return 'accepted'; +} + +const utf8AsLatin1 = (s: string): string => + Buffer.from(s, 'utf8').toString('latin1'); + +describe('extractTar — what is written', () => { + it('writes exactly the selected files, stripping one component', () => { + const dest = fresh(); + const result = extractTar( githubArchive([ - { name: 'pharn-oss-abc1234/SKILLS_VERSION', data: '1.0.0\n' }, - { name: 'pharn-oss-abc1234/pharn-review/', type: '5' }, - { name: 'pharn-oss-abc1234/pharn-review/a11y.md', data: '# a11y\n' }, + KEEP, + { name: at('pharn-review/'), type: '5' }, + { name: at('pharn-review/a11y.md'), data: '# a11y\n' }, + { name: at('pharn-review/unlisted.md'), data: 'not listed\n' }, + { name: at('README.md'), data: 'not listed\n' }, ]), dest, - LIMITS, + opts(['SKILLS_VERSION', 'pharn-review/a11y.md']), ); + expect(treeOf(dest)).toEqual([ + 'SKILLS_VERSION', + 'pharn-review', + 'pharn-review/a11y.md', + ]); expect(readFileSync(join(dest, 'SKILLS_VERSION'), 'utf8')).toBe('1.0.0\n'); expect(readFileSync(join(dest, 'pharn-review/a11y.md'), 'utf8')).toBe( '# a11y\n', ); - // The archive root itself is not written as a directory named after the sha. - expect(existsSync(join(dest, 'pharn-oss-abc1234'))).toBe(false); + expect([...result.written].sort()).toEqual([ + 'SKILLS_VERSION', + 'pharn-review/a11y.md', + ]); + expect(result.bytes).toBe(6 + 7); + expect(result.root).toBe(ROOT); }); - it('skips the leading pax_global_header instead of rejecting it', () => { - // The regression this test exists for: a `g` entry's name is a single - // segment with nothing to strip, so running the path rules over it fails - // the FIRST block of every real archive — init/add/update/status would fail - // 100% of the time against the live remote while every hand-made fixture - // passed. - const dest = tmp.path(); - expect(() => - extractTar( - githubArchive([{ name: 'pharn-oss-abc1234/ok.txt', data: 'ok' }]), - dest, - LIMITS, - ), - ).not.toThrow(); - expect(readFileSync(join(dest, 'ok.txt'), 'utf8')).toBe('ok'); - expect(existsSync(join(dest, 'pax_global_header'))).toBe(false); + it('writes nothing, and reports no root, when nothing is selected', () => { + const dest = fresh(); + const result = extractTar(githubArchive([KEEP]), dest, opts([])); + expect(treeOf(dest)).toEqual([]); + expect(result).toEqual({ written: new Set(), bytes: 0, root: null }); }); - // --- pax extended headers (typeflag 'x') ------------------------------------ - // - // An `x` header's records OVERRIDE the ustar header that follows it (`path=`, - // `size=`), so it is refused on the TYPEFLAG alone. Its payload is never read, - // so no payload, well-formed or not, can change the answer. - - it.each([ - ['path=', paxRecord('path', 'pharn-oss-abc1234/deep/elsewhere.txt')], - ['size=', paxRecord('size', '8589934592')], - ['only benign metadata', paxRecord('mtime', '1700000000.0')], - ['an unparseable payload', '7 comment=xyz\n'], - ['an empty payload', ''], - ])( - 'refuses a pax extended header carrying %s, on its typeflag alone', - (_label, data) => { - expect(() => - extractTar( - githubArchive([ - { name: 'pharn-oss-abc1234/PaxHeaders/f.txt', type: 'x', data }, - { name: 'pharn-oss-abc1234/f.txt', data: 'x' }, - ]), - tmp.path(), - LIMITS, - ), - ).toThrow(/unsupported type 'x'.*pax extended header/); - }, - ); + it('writes a selected empty file', () => { + const dest = fresh(); + extractTar( + githubArchive([{ name: at('MIN_CLI'), data: '' }]), + dest, + opts(['MIN_CLI']), + ); + expect(readFileSync(join(dest, 'MIN_CLI'), 'utf8')).toBe(''); + }); - // --- pax GLOBAL headers (typeflag 'g') -------------------------------------- - // - // Every codeload archive opens with one, so 'g' is SKIPPED, payload unread. - // pharn reads only the ustar fields, so a `g` default for `path`/`size` is - // never honoured: the entries that follow land at their own ustar paths, and - // a size the default would imply cannot re-frame pharn's walk. + it('skips the leading pax_global_header instead of rejecting it', () => { + // The anti-regression for the 100%-failure bug: `pax_global_header` is a + // single segment with nothing to strip, so judging it fails the FIRST + // block of every real archive while every hand-made fixture passes. + const dest = fresh(); + extractTar(githubArchive([KEEP]), dest, opts()); + expect(treeOf(dest)).toEqual(['SKILLS_VERSION']); + }); + // A `g` default is never honoured: pharn reads only the ustar fields, so the + // entries after it land at their own ustar paths. it.each([['path'], ['linkpath'], ['size']])( 'skips a pax global header setting a default %s=, never honouring it', (keyword) => { - const dest = tmp.path(); + const dest = fresh(); extractTar( tar([ { @@ -203,389 +236,354 @@ describe('extractTar', () => { type: 'g', data: paxRecord(keyword, 'elsewhere'), }, - { name: 'pharn-oss-abc1234/', type: '5' }, - { name: 'pharn-oss-abc1234/f.txt', data: 'x' }, + { name: `${ROOT}/`, type: '5' }, + { name: at('f.txt'), data: 'x' }, ]), dest, - LIMITS, + opts(['f.txt']), ); - expect(readdirSync(dest)).toEqual(['f.txt']); + expect(treeOf(dest)).toEqual(['f.txt']); expect(readFileSync(join(dest, 'f.txt'), 'utf8')).toBe('x'); }, ); - it('skips a pax global header whose payload does not parse, unread', () => { - const dest = tmp.path(); + it.each([ + ['an unparseable payload', '7 comment=xyz\n'], + [ + 'metadata and vendor records', + paxRecord('mtime', '1700000000.0') + + paxRecord('SCHILY.xattr.user.thing', 'value'), + ], + ['a payload over two blocks', paxRecord('comment', 'q'.repeat(1200))], + ])('skips a pax global header carrying %s, unread', (_label, data) => { + const dest = fresh(); extractTar( tar([ - { name: 'pax_global_header', type: 'g', data: '7 comment=xyz\n' }, - { name: 'pharn-oss-abc1234/', type: '5' }, - { name: 'pharn-oss-abc1234/f.txt', data: 'x' }, + { name: 'pax_global_header', type: 'g', data }, + { name: `${ROOT}/`, type: '5' }, + KEEP, ]), dest, - LIMITS, - ); - expect(readdirSync(dest)).toEqual(['f.txt']); - }); - - it('still skips the global header GitHub actually sends', () => { - // The anti-regression for the 100%-failure bug: `pax_global_header` is a - // single segment with nothing to strip, so running the path rules over it — - // or throwing on `g` outright — fails the FIRST block of every real archive - // while every hand-made fixture passes. - const dest = tmp.path(); - extractTar( - githubArchive([{ name: 'pharn-oss-abc1234/ok.txt', data: 'ok' }]), - dest, - LIMITS, + opts(), ); - expect(readFileSync(join(dest, 'ok.txt'), 'utf8')).toBe('ok'); - expect(existsSync(join(dest, 'pax_global_header'))).toBe(false); + expect(treeOf(dest)).toEqual(['SKILLS_VERSION']); }); - it('skips a global header carrying metadata and vendor records', () => { - const dest = tmp.path(); + it('reassembles a selected path split across prefix and name', () => { + // ustar splits any path over 100 chars: the tail goes in `name`, the head + // in `prefix`. Reading `name` alone would miss the file entirely. + const deep = 'a'.repeat(40); + const rel = `${deep}/${deep}/regression-report.json`; + const dest = fresh(); extractTar( - tar([ + githubArchive([ { - name: 'pax_global_header', - type: 'g', - data: - paxRecord('mtime', '1700000000.0') + - paxRecord('uname', 'root') + - paxRecord('SCHILY.xattr.user.thing', 'value'), + prefix: `${ROOT}/${deep}/${deep}`, + name: 'regression-report.json', + data: '{}', }, - { name: 'pharn-oss-abc1234/', type: '5' }, - { name: 'pharn-oss-abc1234/ok.txt', data: 'ok' }, ]), dest, - LIMITS, + opts([rel]), ); - expect(readFileSync(join(dest, 'ok.txt'), 'utf8')).toBe('ok'); + expect(readFileSync(join(dest, rel), 'utf8')).toBe('{}'); }); - it('skips a global header whose payload spans more than one block', () => { - // The padded multi-block advance is newly load-bearing: the reader now - // consumes the payload it used to step over blind, so the framing has to be - // demonstrated rather than inherited. - const dest = tmp.path(); - const big = paxRecord('comment', 'q'.repeat(1200)); - expect(big.length).toBeGreaterThan(BLOCK * 2); + it('accepts a non-ASCII root and writes the selected file below it', () => { + const dest = fresh(); extractTar( tar([ - { name: 'pax_global_header', type: 'g', data: big }, - { name: 'pharn-oss-abc1234/', type: '5' }, - { name: 'pharn-oss-abc1234/ok.txt', data: 'ok' }, + GLOBAL_HEADER, + { name: utf8AsLatin1('pharn-oss-café/SKILLS_VERSION'), data: 'ok' }, ]), dest, - LIMITS, + opts(), ); - expect(readFileSync(join(dest, 'ok.txt'), 'utf8')).toBe('ok'); + expect(treeOf(dest)).toEqual(['SKILLS_VERSION']); }); - it('reassembles a path split across prefix and name', () => { - // ustar splits any path over 100 chars: the tail goes in `name`, the head in - // `prefix`. 619 of the live archive's ~1,470 entries use it. Reading `name` - // alone yields a bare leaf, which strip-1 then rejects for having no leading - // component — losing a third of the tree rather than misplacing it. - const deep = 'a'.repeat(40); - const dest = tmp.path(); - extractTar( - githubArchive([ - { - prefix: `pharn-oss-abc1234/${deep}/${deep}`, - name: 'regression-report.json', - data: '{}', - }, - ]), - dest, - LIMITS, + it('holds a later pass to the root an earlier pass learned', () => { + const archive = githubArchive([KEEP]); + expect(refusal(archive, { ...opts(), root: 'pharn-oss-other' })).toMatch( + /more than one root component: pharn-oss-other and/, ); - expect( - readFileSync(join(dest, deep, deep, 'regression-report.json'), 'utf8'), - ).toBe('{}'); - // ...and it did NOT land at the root as a bare leaf. - expect(existsSync(join(dest, 'regression-report.json'))).toBe(false); - }); - - it.each([ - ['a `..` segment', 'pharn-oss-abc1234/../escape.txt'], - ['a deeper `..` segment', 'pharn-oss-abc1234/nested/../../escape.txt'], - ])('rejects %s', (_label, name) => { - expect(() => - extractTar(githubArchive([{ name, data: 'x' }]), tmp.path(), LIMITS), - ).toThrow(TarExtractError); + expect(refusal(archive, { ...opts(), root: ROOT })).toBe('accepted'); }); +}); - it('rejects an absolute path', () => { - expect(() => - extractTar( - githubArchive([{ name: '/etc/passwd', data: 'x' }]), - tmp.path(), - LIMITS, - ), - ).toThrow(/absolute path/); +// The decision this file used to pin was "reject a symlink entry outright, +// rather than skipping it": degit dropped such entries silently, and a dropped +// entry could be a file pharn installs. It is NARROWED here, not reversed: an +// entry outside the selection is skipped and never written (nothing unlisted +// touches disk, so skipping is strictly safer than judging), while an entry at +// a selected path is still refused. A listed file that a skipped entry stood in +// for — a symlink, or a file a pax record renamed — is missing from the tree, +// and the manifest's sha256 check (verifyUpstreamManifest) refuses it loudly: +// the silent loss degit allowed cannot recur. +describe('extractTar — outside the selection: skipped, nothing written', () => { + it.each<[string, EntryInit[]]>([ + ['a symlink', [{ name: at('.claude/skills/x'), type: '2' }]], + ['a hard link', [{ name: at('link'), type: '1' }]], + ['a character device', [{ name: at('dev'), type: '3' }]], + ['a block device', [{ name: at('blk'), type: '4' }]], + ['a fifo', [{ name: at('fifo'), type: '6' }]], + ['an unknown type', [{ name: at('odd'), type: '9' }]], + ['a directory', [{ name: at('.dev/'), type: '5' }]], + [ + 'a pax extended header and the entry it renames', + [ + { + name: at('PaxHeaders/long'), + type: 'x', + data: paxRecord('path', at(`${'d'.repeat(120)}/f.md`)), + }, + { name: at('0123456789abcdef.data'), data: 'x' }, + ], + ], + [ + 'a GNU long name and the entry it renames', + [ + { name: '././@LongLink', type: 'L', data: at('x'.repeat(150)) }, + { name: at('xxxxxxxx'), data: 'x' }, + ], + ], + [ + 'a GNU long link name and its symlink', + [ + { name: '././@LongLink', type: 'K', data: 'y'.repeat(150) }, + { name: at('l'), type: '2' }, + ], + ], + ['a name with a colon', [{ name: at('a:b.md'), data: 'x' }]], + ['a name with a backslash', [{ name: at('a\\..\\..\\evil'), data: 'x' }]], + ['an invalid UTF-8 name', [{ name: at('bad-\x9b2J.md'), data: 'x' }]], + ['an escape sequence in a name', [{ name: at(`n${ESC}[2K`), data: 'x' }]], + [ + 'a right-to-left override', + [{ name: utf8AsLatin1(at('evil\u202egnp.md')), data: 'x' }], + ], + ['an absolute path', [{ name: '/etc/passwd', data: 'x' }]], + ['a `..` segment', [{ name: at('../escape.txt'), data: 'x' }]], + ['a second root', [{ name: 'somewhere-else/evil.txt', data: 'x' }]], + ['a file with no root', [{ name: 'loose.txt', data: 'x' }]], + ['an empty segment', [{ name: at('a//b.md'), data: 'x' }]], + ])('installs past %s and writes nothing for it', (_label, entries) => { + const dest = fresh(); + const result = extractTar(githubArchive([...entries, KEEP]), dest, opts()); + expect(treeOf(dest)).toEqual(['SKILLS_VERSION']); + expect([...result.written]).toEqual(['SKILLS_VERSION']); + expect(nonFileOrDir(dest)).toEqual([]); }); - it('rejects a file with no component to strip', () => { - // No preceding root entry, so this is the FIRST accepted path: the - // multi-root guard cannot fire and the strip-1 rule is what must reject it. - expect(() => - extractTar( - tar([GLOBAL_HEADER, { name: 'loose.txt', data: 'x' }]), - tmp.path(), - LIMITS, - ), - ).toThrow(/no path below the archive root/); + it('a pax header modifies only the next entry: the selected file after it is written', () => { + const dest = fresh(); + extractTar( + githubArchive([ + { name: at('PaxHeaders/x'), type: 'x', data: paxRecord('size', '1') }, + { name: at('unlisted.md'), data: 'x' }, + KEEP, + ]), + dest, + opts(), + ); + expect(treeOf(dest)).toEqual(['SKILLS_VERSION']); }); - it('rejects a second root component', () => { - expect(() => - extractTar( - githubArchive([ - { name: 'pharn-oss-abc1234/ok.txt', data: 'x' }, - { name: 'somewhere-else/evil.txt', data: 'x' }, - ]), - tmp.path(), - LIMITS, - ), - ).toThrow(/more than one root component/); + it('bounds only the bytes written: an unselected file over the cap is skipped', () => { + const dest = fresh(); + extractTar( + githubArchive([{ name: at('big.bin'), data: 'x'.repeat(4096) }, KEEP]), + dest, + opts(['SKILLS_VERSION'], { ...LIMITS, maxWrittenBytes: 100 }), + ); + expect(treeOf(dest)).toEqual(['SKILLS_VERSION']); }); +}); +describe('extractTar — at a selected path: refused', () => { it.each([ ['a symlink', '2'], - ['a hardlink', '1'], + ['a hard link', '1'], ['a character device', '3'], ['a block device', '4'], + ['a directory', '5'], ['a fifo', '6'], ['a pax extended header', 'x'], - // GNU's long-name typeflags are the other way a writer escapes ustar's - // 100-byte name field. They need no branch of their own — they are neither - // '0'/NUL nor '5', so they land in this reject — but they are pinned HERE - // so a future refactor of the bucket cannot start accepting them quietly. + ['a pax global header', 'g'], ['a GNU long name', 'L'], ['a GNU long link name', 'K'], ['an unknown type', '9'], - ])('rejects %s entry outright, rather than skipping it', (_label, type) => { - // degit passed neither `strict` nor `onwarn`, so an entry like this was - // dropped and the clone still resolved. The live archive contains none of - // these, so a rejection here is a real signal. - expect(() => - extractTar( - githubArchive([{ name: 'pharn-oss-abc1234/link', type }]), - tmp.path(), - LIMITS, + ])('refuses %s, naming the path and the rule', (_label, type) => { + const dest = fresh(); + const message = refusal( + githubArchive([{ name: at('SKILLS_VERSION'), type }]), + opts(), + dest, + ); + expect(message).toMatch(/unsupported type/); + expect(message).toContain(at('SKILLS_VERSION')); + expect(treeOf(dest)).toEqual([]); + }); + + it.each([ + ['a pax extended header', 'x'], + ['a GNU long name', 'L'], + ])( + 'refuses a selected file that follows %s, whose records pharn does not honour', + (_label, type) => { + const message = refusal( + githubArchive([ + { name: at('PaxHeaders/SKILLS_VERSION'), type, data: '' }, + KEEP, + ]), + ); + expect(message).toMatch(/pax extended or GNU long-name header/); + expect(message).toContain(at('SKILLS_VERSION')); + }, + ); + + it('a pax global header between the extended header and the file does not lift the refusal', () => { + expect( + refusal( + githubArchive([ + { name: at('PaxHeaders/x'), type: 'x', data: '' }, + { name: 'pax_global_header', type: 'g', data: '' }, + KEEP, + ]), ), - ).toThrow(/unsupported type/); + ).toMatch(/pax extended or GNU long-name header/); }); - // PHARN-17: a name a terminal would interpret is refused before any other - // entry rule, so it is neither installed (and later listed by status/update) - // nor echoed raw by a refusal message. Names are latin1 in the header, so a - // UTF-8 U+202E is written as its three bytes. - const utf8AsLatin1 = (s: string): string => - Buffer.from(s, 'utf8').toString('latin1'); + it.each([ + ['an absolute path', '/SKILLS_VERSION', /absolute path/], + ['a `..` root', '../SKILLS_VERSION', /escapes the archive root/], + ['a "." root', './SKILLS_VERSION', /no leading component/], + ['a drive-letter root', 'C:/SKILLS_VERSION', /backslash or colon/], + ['a backslash in the root', 'a\\b/SKILLS_VERSION', /backslash or colon/], + ])('refuses %s', (_label, name, rule) => { + const message = refusal(tar([GLOBAL_HEADER, { name, data: 'x' }])); + expect(message).toMatch(rule); + expect(message).toContain(name); + }); + + it('refuses a colon in the ustar prefix too', () => { + expect( + refusal(tar([{ prefix: 'x:y', name: 'SKILLS_VERSION', data: 'x' }])), + ).toMatch(/backslash or colon/); + }); + + it.each([['a//b.md'], ['a/./b.md']])( + 'refuses the empty or "." segment in a selected %s', + (rel) => { + expect( + refusal(githubArchive([{ name: at(rel), data: 'x' }]), opts([rel])), + ).toMatch(/empty or "\." path segment/); + }, + ); + + it('refuses a selected file under a second root', () => { + expect( + refusal( + githubArchive([KEEP, { name: 'elsewhere/MIN_CLI', data: '1.0.0' }]), + opts(['SKILLS_VERSION', 'MIN_CLI']), + ), + ).toMatch(/more than one root component/); + }); + + it('refuses a selected path the archive holds twice', () => { + const dest = fresh(); + const message = refusal(githubArchive([KEEP, KEEP]), opts(), dest); + expect(message).toMatch(/holds this path twice/); + expect(message).toContain(at('SKILLS_VERSION')); + }); + // PHARN-17: a name a terminal would interpret is refused before any other + // rule, so it is neither installed nor echoed raw by a refusal message. + // Names are latin1 in the header, so a UTF-8 U+202E is written as its bytes. it.each([ - [ - 'an ESC sequence in the name', - { name: `pharn-oss-abc1234/n${ESC}[2K\r${ESC}[32mOK` }, - ], + ['an ESC sequence in the root', { name: `d${ESC}[2K\r/SKILLS_VERSION` }], [ 'a right-to-left override', - { name: utf8AsLatin1('pharn-oss-abc1234/evil\u202egnp.md') }, + { name: utf8AsLatin1('evil\u202egnp/SKILLS_VERSION') }, ], [ 'a zero-width space', - { name: utf8AsLatin1('pharn-oss-abc1234/se\u200bcurity.md') }, + { name: utf8AsLatin1('se\u200bcurity/SKILLS_VERSION') }, ], [ 'a control byte in the ustar prefix', - { name: 'f.md', prefix: `pharn-oss-abc1234/d${ESC}x` }, + { name: 'SKILLS_VERSION', prefix: `d${ESC}x` }, ], - // CORE-170: the one unsafe set now holds the two line separators too. [ 'a line separator (U+2028)', - { name: utf8AsLatin1('pharn-oss-abc1234/a\u2028b.md') }, + { name: utf8AsLatin1('a\u2028b/SKILLS_VERSION') }, + ], + [ + 'a leading byte-order mark, never stripped', + { name: utf8AsLatin1('\ufeffroot/SKILLS_VERSION') }, ], ])('refuses %s, naming it without the raw character', (_label, entry) => { - let message = ''; - try { - extractTar(githubArchive([entry]), tmp.path(), LIMITS); - } catch (err) { - expect(err).toBeInstanceOf(TarExtractError); - message = (err as Error).message; - } + const dest = fresh(); + const message = refusal( + tar([GLOBAL_HEADER, { ...entry, data: 'x' }]), + opts(), + dest, + ); expect(message).toMatch(/control or format character/); expect(hasUnsafeChars(message)).toBe(false); + expect(treeOf(dest)).toEqual([]); }); - it('refuses an unsafe name even on an unsupported-type entry (path judged first)', () => { - expect(() => - extractTar( - githubArchive([{ name: `pharn-oss-abc1234/n${ESC}[32mOK`, type: '2' }]), - tmp.path(), - LIMITS, - ), - ).toThrow(/control or format character/); + it('judges the path before the type', () => { + expect( + refusal(tar([{ name: `n${ESC}[32mOK/SKILLS_VERSION`, type: '2' }])), + ).toMatch(/control or format character/); }); it('renders an unprintable typeflag as its code, not the raw byte', () => { - let message = ''; - try { - extractTar( - githubArchive([{ name: 'pharn-oss-abc1234/x', type: ESC }]), - tmp.path(), - LIMITS, - ); - } catch (err) { - message = (err as Error).message; - } + const message = refusal( + githubArchive([{ name: at('SKILLS_VERSION'), type: ESC }]), + ); expect(message).toContain('unsupported type 0x1b'); expect(message).not.toContain(ESC); }); - it('still extracts an ordinary non-ASCII name', () => { - extractTar( - githubArchive([ - { name: utf8AsLatin1('pharn-oss-abc1234/café.md'), data: 'ok' }, - ]), - tmp.path(), - LIMITS, - ); - }); - - // tar-entry-names. The check used to judge a DIFFERENT string than the one - // written — the UTF-8 decoding of latin1-read bytes, against the latin1 string - // itself — so a raw C1 byte passed as U+FFFD and landed on disk as U+009B, and - // every non-ASCII name landed garbled. Names are now decoded once, strictly, - // and the check, the path rules and the write share that one string. Asserted - // on the BYTES the filesystem returns, not on a decoded string. - const onDisk = (dir: string): Buffer[] => - readdirSync(dir, { encoding: 'buffer' }); - - it('writes a non-ASCII name as exactly the archive bytes', () => { - const dest = tmp.path(); - extractTar( - githubArchive([ - { name: utf8AsLatin1('pharn-oss-abc1234/a—b.md'), data: 'ok' }, - ]), - dest, - LIMITS, - ); - expect(onDisk(dest)).toEqual([Buffer.from('a—b.md', 'utf8')]); - }); - it.each([ - ['a raw C1 byte', 'pharn-oss-abc1234/evil-\x9b2J.md'], - ['a truncated UTF-8 sequence', 'pharn-oss-abc1234/bad-\xe2\x80.md'], - ['an overlong encoding of "/"', 'pharn-oss-abc1234/slash-\xc0\xaf.md'], + ['a raw C1 byte', 'pharn-oss-\x9b2J/SKILLS_VERSION'], + ['a truncated UTF-8 sequence', 'bad-\xe2\x80/SKILLS_VERSION'], + ['an overlong encoding', 'slash-\xc0\xaf/SKILLS_VERSION'], ])( - 'refuses a name holding %s — not valid UTF-8 — writing nothing', + 'refuses a root holding %s — not valid UTF-8 — writing nothing', (_label, name) => { - const dest = tmp.path(); - let message = ''; - try { - extractTar(githubArchive([{ name, data: 'x' }]), dest, LIMITS); - } catch (err) { - expect(err).toBeInstanceOf(TarExtractError); - message = (err as Error).message; - } + const dest = fresh(); + const message = refusal( + tar([GLOBAL_HEADER, { name, data: 'x' }]), + opts(), + dest, + ); expect(message).toMatch(/not valid UTF-8/); expect(hasUnsafeChars(message)).toBe(false); - expect(onDisk(dest)).toEqual([]); + expect(treeOf(dest)).toEqual([]); }, ); it('refuses invalid UTF-8 in the ustar prefix too', () => { - expect(() => - extractTar( - githubArchive([{ name: 'f.md', prefix: 'pharn-oss-abc1234/d\x9b' }]), - tmp.path(), - LIMITS, - ), - ).toThrow(/not valid UTF-8/); - }); - - // A decoder's DEFAULT drops a leading byte-order mark: the name would be - // written under a different name than the archive holds instead of refused. - it('refuses a name field that starts with a byte-order mark, never strips it', () => { - const dest = tmp.path(); - expect(() => - extractTar( - githubArchive([ - { - name: utf8AsLatin1('\ufeff' + 'f.md'), // BOM, then `f.md` - prefix: 'pharn-oss-abc1234', - data: 'x', - }, - ]), - dest, - LIMITS, - ), - ).toThrow(/control or format character/); - expect(onDisk(dest)).toEqual([]); - }); - - it('counts every pax global header toward the entry cap', () => { - const empty: EntryInit = { name: 'pax_global_header', type: 'g', data: '' }; - expect(() => - extractTar( - tar([ - empty, - empty, - empty, - empty, - { name: 'pharn-oss-abc1234/', type: '5' }, - ]), - tmp.path(), - { maxEntries: 3, maxTotalBytes: 1024 }, - ), - ).toThrow(/more than 3 entries/); - }); - - it('names a malformed numeric field escaped — no raw newline reaches the message', () => { - const bad = header({ name: 'pharn-oss-abc1234/f.txt' }); - bad.fill(0, 124, 136); // the size field - bad.write('1\n Done', 124, 12, 'latin1'); - bad.write(' ', 148, 8, 'latin1'); // re-checksum over the forged field - let sum = 0; - for (const byte of bad) sum += byte; - bad.write(sum.toString(8).padStart(6, '0') + '\0 ', 148, 8, 'latin1'); - - let message = ''; - try { - extractTar( - Buffer.concat([bad, Buffer.alloc(BLOCK * 2)]), - tmp.path(), - LIMITS, - ); - } catch (err) { - message = (err as Error).message; - } - expect(message).toMatch(/non-octal numeric field/); - expect(message).not.toContain('\n'); - expect(message).toContain('1\\x0a Done'); + expect( + refusal(tar([{ name: 'SKILLS_VERSION', prefix: 'd\x9b', data: 'x' }])), + ).toMatch(/not valid UTF-8/); }); +}); - // PHARN-18: strict framing. Each case was ACCEPTED by the base source. - const refusal = (archive: Buffer): string => { - try { - extractTar(archive, tmp.path(), LIMITS); - } catch (err) { - expect(err).toBeInstanceOf(TarExtractError); - return (err as Error).message; - } - return 'accepted'; - }; - +// Framing is checked on EVERY header: without it the walk cannot find the next +// header, so these stay refusals whatever the entry is. +describe('extractTar — framing, on every header', () => { it('refuses entries hidden after a zero block mid-archive', () => { const archive = Buffer.concat([ - tar([GLOBAL_HEADER, { name: 'pharn-oss-abc1234/', type: '5' }]).subarray( + tar([GLOBAL_HEADER, { name: `${ROOT}/`, type: '5' }]).subarray( 0, -BLOCK, // keep ONE zero block, then keep going ), - tar([{ name: 'pharn-oss-abc1234/hidden.md', data: 'x' }]), + tar([KEEP]), ]); expect(refusal(archive)).toMatch(/data after its end-of-archive marker/); }); @@ -596,88 +594,64 @@ describe('extractTar', () => { }); it('refuses an archive with no end-of-archive marker', () => { - const archive = githubArchive([ - { name: 'pharn-oss-abc1234/a.md', data: 'x' }, - ]).subarray(0, -2 * BLOCK); + const archive = githubArchive([KEEP]).subarray(0, -2 * BLOCK); expect(refusal(archive)).toMatch(/no end-of-archive marker/); }); - it('refuses a header without the ustar magic', () => { - const archive = githubArchive([ - { name: 'pharn-oss-abc1234/a.md', data: 'x' }, + it('refuses an archive cut inside a payload, writing no partial file', () => { + const dest = fresh(); + const full = githubArchive([ + { name: at('SKILLS_VERSION'), data: 'x'.repeat(600) }, ]); + // Header blocks 0-2, then 512 of the 600 payload bytes. + expect(refusal(full.subarray(0, BLOCK * 4), opts(), dest)).toMatch( + /runs past the end of the archive — truncated/, + ); + expect(treeOf(dest)).toEqual([]); + }); + + it('refuses an unselected header without the ustar magic', () => { + const archive = githubArchive([{ name: at('a.md'), data: 'x' }, KEEP]); // Blank the magic of the third header and re-seal its checksum, so the // magic check — not the checksum — is what refuses it. - const at = 2 * BLOCK; - archive.fill(0, at + 257, at + 263); - archive.write(' ', at + 148, 8, 'latin1'); + const off = 2 * BLOCK; + archive.fill(0, off + 257, off + 263); + archive.write(' ', off + 148, 8, 'latin1'); let sum = 0; - for (const byte of archive.subarray(at, at + BLOCK)) sum += byte; + for (const byte of archive.subarray(off, off + BLOCK)) sum += byte; archive.write( sum.toString(8).padStart(6, '0') + '\0 ', - at + 148, + off + 148, 8, 'latin1', ); expect(refusal(archive)).toMatch(/missing "ustar" magic/); }); - it.each([['pharn-oss-abc1234/a//b.md'], ['pharn-oss-abc1234/a/./b.md']])( - 'refuses the empty or "." segment in %s', - (name) => { - expect(refusal(githubArchive([{ name, data: 'x' }]))).toMatch( - /empty or "\." path segment/, - ); - }, - ); - - it('still extracts the codeload shape (one small global header, zero tail)', () => { + it('refuses an unselected header whose checksum does not match', () => { expect( refusal( githubArchive([ - { name: 'pharn-oss-abc1234/SKILLS_VERSION', data: '1\n' }, + { name: at('f.txt'), data: 'x', forgeChecksum: '000000\0 ' }, + KEEP, ]), ), - ).toBe('accepted'); - }); - - it('enforces the entry-count cap', () => { - const many = Array.from({ length: 5 }, (_, i) => ({ - name: `pharn-oss-abc1234/f${i}.txt`, - data: 'x', - })); - expect(() => - extractTar(githubArchive(many), tmp.path(), { - maxEntries: 3, - maxTotalBytes: 1024, - }), - ).toThrow(/more than 3 entries/); + ).toMatch(/checksum/); }); - it('rejects a truncated archive', () => { - const full = githubArchive([ - { name: 'pharn-oss-abc1234/f.txt', data: 'x'.repeat(600) }, - ]); - // Cut inside the file payload: the header promises more than is there. - expect(() => - extractTar(full.subarray(0, BLOCK * 4), tmp.path(), LIMITS), - ).toThrow(/truncated/); - }); + it('names a malformed numeric field escaped — no raw newline reaches the message', () => { + const bad = header({ name: at('f.txt') }); + bad.fill(0, 124, 136); // the size field + bad.write('1\n Done', 124, 12, 'latin1'); + bad.write(' ', 148, 8, 'latin1'); // re-checksum over the forged field + let sum = 0; + for (const byte of bad) sum += byte; + bad.write(sum.toString(8).padStart(6, '0') + '\0 ', 148, 8, 'latin1'); - it('rejects a header whose checksum does not match', () => { - expect(() => - extractTar( - githubArchive([ - { - name: 'pharn-oss-abc1234/f.txt', - data: 'x', - forgeChecksum: '000000\0 ', - }, - ]), - tmp.path(), - LIMITS, - ), - ).toThrow(/checksum/); + const message = refusal(Buffer.concat([bad, Buffer.alloc(BLOCK * 2)])); + expect(message).toMatch(/non-octal numeric field/); + expect(message).not.toContain('\n'); + expect(message).toContain('1\\x0a Done'); }); // A GNU base-256 field sets the high bit of its first byte. No such byte is @@ -692,124 +666,184 @@ describe('extractTar', () => { 'rejects a size field whose first byte is %s (GNU base-256), never misreading it', (_label, byte) => { const bytes = Buffer.concat([ - header({ name: 'pharn-oss-abc1234/', type: '5' }), - header({ - name: 'pharn-oss-abc1234/f.txt', - data: 'x', - forgeSizeByte: byte, - }), + header({ name: `${ROOT}/`, type: '5' }), + header({ name: at('f.txt'), data: 'x', forgeSizeByte: byte }), Buffer.alloc(BLOCK), Buffer.alloc(BLOCK * 2), ]); - expect(() => extractTar(bytes, tmp.path(), LIMITS)).toThrow( - /non-octal numeric field/, - ); + expect(refusal(bytes)).toMatch(/non-octal numeric field/); }, ); +}); - // CORE-173: `\` and `:` in an entry name. POSIX writes `a\..\..\evil` as - // ONE literal file name; win32 would read the same bytes as a path. pharn-oss - // ships neither character, so either is refused, naming the entry. - it.each([ - ['a backslash path', 'pharn-oss-abc1234/a\\..\\..\\evil'], - ['a drive letter', 'pharn-oss-abc1234/C:/x'], - ['a colon in a name', 'pharn-oss-abc1234/a:b.md'], - ['a backslash in a directory segment', 'pharn-oss-abc1234/d\\e/f.md'], - ])('refuses %s, writing nothing', (_label, name) => { - const dest = tmp.path(); - let message = ''; - try { - extractTar(githubArchive([{ name, data: 'x' }]), dest, LIMITS); - } catch (err) { - expect(err).toBeInstanceOf(TarExtractError); - message = (err as Error).message; - } - expect(message).toMatch(/backslash or colon/); - expect(message).toContain(name); - expect(readdirSync(dest)).toEqual([]); +describe('extractTar — caps', () => { + it('counts every header toward maxHeaders: global, unselected and selected', () => { + const empty: EntryInit = { name: 'pax_global_header', type: 'g', data: '' }; + const limits = { ...LIMITS, maxHeaders: 3 }; + expect( + refusal(tar([empty, empty, empty, empty]), opts([], limits)), + ).toMatch(/more than 3 headers/); + expect( + refusal( + githubArchive([{ name: at('a'), data: 'x' }, KEEP]), + opts(['SKILLS_VERSION'], limits), + ), + ).toMatch(/more than 3 headers/); + expect( + refusal(githubArchive([KEEP]), opts(['SKILLS_VERSION'], limits)), + ).toBe('accepted'); }); - it('refuses a backslash or colon in the ustar prefix too', () => { - expect(() => - extractTar( - githubArchive([{ name: 'f.md', prefix: 'pharn-oss-abc1234/x:y' }]), - tmp.path(), - LIMITS, + it('refuses selected files whose sizes exceed maxWrittenBytes', () => { + const dest = fresh(); + const message = refusal( + githubArchive([KEEP, { name: at('big.md'), data: 'x'.repeat(600) }]), + opts(['SKILLS_VERSION', 'big.md'], { ...LIMITS, maxWrittenBytes: 100 }), + dest, + ); + expect(message).toMatch(/exceed 100 bytes/); + // Refused at the header, before the payload is collected. + expect(treeOf(dest)).toEqual(['SKILLS_VERSION']); + }); + + it('refuses a stream over maxScannedBytes', () => { + expect( + refusal( + githubArchive([{ name: at('pad'), data: 'x'.repeat(4096) }, KEEP]), + opts(['SKILLS_VERSION'], { ...LIMITS, maxScannedBytes: 2048 }), ), - ).toThrow(/backslash or colon/); + ).toMatch(/decompresses to more than 2048 bytes/); }); }); -describe('extractTarGz', () => { - const tmp = useTmpDir(); +// Production chunks (gunzip's 16 KiB) are block-aligned, so a header or payload +// straddling two chunks never happens there; it is forced here. +describe('extractTar — chunk boundaries', () => { + const archive = githubArchive([ + { name: at('a.md'), data: 'a'.repeat(700) }, + KEEP, + { name: at('.claude/skills/x'), type: '2' }, + { name: at('d/b.md'), data: 'b'.repeat(1300) }, + { name: at('MIN_CLI'), data: '' }, + ]); + const select = ['a.md', 'SKILLS_VERSION', 'd/b.md', 'MIN_CLI']; + + function chunked(bytes: Buffer, size: number): Buffer[] { + const out: Buffer[] = []; + for (let i = 0; i < bytes.length; i += size) + out.push(bytes.subarray(i, i + size)); + return out; + } + + function snapshot(dir: string): Record { + const out: Record = {}; + for (const rel of treeOf(dir)) { + if (lstatSync(join(dir, rel)).isFile()) + out[rel] = readFileSync(join(dir, rel), 'utf8'); + } + return out; + } + + it.each([[1], [7], [511], [513], [1500]])( + 'gives the same tree in %i-byte chunks as in one buffer', + (size) => { + const whole = fresh(); + const parts = fresh(); + const a = extractTar(archive, whole, opts(select)); + const b = extractTar(chunked(archive, size), parts, opts(select)); + expect(snapshot(parts)).toEqual(snapshot(whole)); + expect(b).toEqual(a); + expect(Object.keys(snapshot(whole)).sort()).toEqual([...select].sort()); + }, + ); + + it('still refuses data after the end marker when it arrives in a later chunk', () => { + const tail = Buffer.concat([archive, Buffer.alloc(BLOCK)]); + tail[tail.length - 1] = 1; + expect(() => extractTar(chunked(tail, 300), fresh(), opts(select))).toThrow( + /data after its end-of-archive marker/, + ); + }); +}); - it('decompresses and extracts', () => { - const dest = tmp.path(); - extractTarGz( - gzipSync(githubArchive([{ name: 'pharn-oss-abc1234/v', data: '1.0.0' }])), +describe('extractTarGz', () => { + it('decompresses and extracts the selected files', async () => { + const dest = fresh(); + const result = await extractTarGz( + gzipSync(githubArchive([KEEP, { name: at('other'), data: 'x' }])), dest, - LIMITS, + opts(), ); - expect(readFileSync(join(dest, 'v'), 'utf8')).toBe('1.0.0'); + expect(treeOf(dest)).toEqual(['SKILLS_VERSION']); + expect(result.root).toBe(ROOT); }); - it('surfaces corrupt gzip as a TarExtractError', () => { - expect(() => - extractTarGz(Buffer.from('not a gzip stream'), tmp.path(), LIMITS), - ).toThrow(TarExtractError); + it('surfaces corrupt gzip as a TarExtractError', async () => { + await expect( + extractTarGz(Buffer.from('not a gzip stream'), fresh(), opts()), + ).rejects.toThrow(/could not decompress the fetched archive/); }); - it('bounds the bytes written by the decompressed size (maxTotalBytes)', () => { - // Moved from extractTar: the decompressed tar holds every byte an entry - // writes, so gunzip's maxOutputLength is the one total-bytes bound. - expect(() => - extractTarGz( - gzipSync( - githubArchive([ - { name: 'pharn-oss-abc1234/big.txt', data: 'x'.repeat(600) }, - ]), - ), - tmp.path(), - { maxEntries: 100, maxTotalBytes: 100 }, - ), - ).toThrow(/could not decompress/); + it('rethrows a refusal from the walk as itself, not as a gzip failure', async () => { + const err = await extractTarGz( + gzipSync(githubArchive([{ name: at('SKILLS_VERSION'), type: '2' }])), + fresh(), + opts(), + ).catch((e: unknown) => e); + expect(err).toBeInstanceOf(TarExtractError); + expect((err as Error).message).toMatch(/unsupported type '2'/); + }); + + it('refuses a truncated gzip stream', async () => { + const gz = gzipSync(githubArchive([KEEP])); + await expect( + extractTarGz(gz.subarray(0, gz.length - 20), fresh(), opts()), + ).rejects.toThrow(TarExtractError); }); - it('caps the DECOMPRESSED size, so a zip bomb is bounded', () => { - // Neither content-length nor the compressed size bounds this: 1 MB of zeros - // gzips to about a kilobyte. + it('bounds a compression bomb by maxScannedBytes', async () => { + // Neither content-length nor the compressed size bounds this: 4 MB of + // zeros gzips to a few kilobytes. const bomb = gzipSync( githubArchive([ - { name: 'pharn-oss-abc1234/bomb', data: '\0'.repeat(1024 * 1024) }, + { name: at('bomb'), data: '\0'.repeat(4 * 1024 * 1024) }, + KEEP, ]), ); expect(bomb.length).toBeLessThan(64 * 1024); - expect(() => - extractTarGz(bomb, tmp.path(), { maxEntries: 10, maxTotalBytes: 4096 }), - ).toThrow(TarExtractError); + await expect( + extractTarGz( + bomb, + fresh(), + opts(['SKILLS_VERSION'], { ...LIMITS, maxScannedBytes: 65536 }), + ), + ).rejects.toThrow(/decompresses to more than 65536 bytes/); + }); + + it('installs from a repo larger than maxWrittenBytes when the selected files fit', async () => { + const dest = fresh(); + await extractTarGz( + gzipSync( + githubArchive([ + { name: at('.dev/huge'), data: 'z'.repeat(1024 * 1024) }, + KEEP, + ]), + ), + dest, + opts(['SKILLS_VERSION'], { ...LIMITS, maxWrittenBytes: 4096 }), + ); + expect(treeOf(dest)).toEqual(['SKILLS_VERSION']); }); }); -// CORE-173: the invariant fetchRepo states and clone-side readers rely on — the -// extracted tree holds only regular files and directories. Asserted on what is -// ON DISK (lstat), over the real codeload shape and over the partial tree a -// refused archive leaves behind before fetchRepo removes it. +// The invariant fetchRepo states and clone-side readers rely on: the extracted +// tree holds only regular files and directories. Asserted on what is ON DISK +// (lstat), over the codeload shape with every kind of entry outside the +// selection. describe('the extracted tree holds only regular files and directories', () => { - const tmp = useTmpDir(); - - /** Every path under `dir` that lstat says is neither a file nor a directory. */ - function nonFileOrDir(dir: string): string[] { - const odd: string[] = []; - for (const rel of readdirSync(dir, { recursive: true }) as string[]) { - const st = lstatSync(join(dir, rel)); - if (!st.isFile() && !st.isDirectory()) odd.push(rel); - } - return odd; - } - - it('over the codeload shape', () => { - const dest = tmp.path(); - extractTarGz( + it('over the codeload shape', async () => { + const dest = fresh(); + await extractTarGz( codeloadArchive('0123456789abcdef0123456789abcdef01234567', { SKILLS_VERSION: '1.0.0\n', 'pharn-review/a11y/a11y.md': '# a11y\n', @@ -817,34 +851,31 @@ describe('the extracted tree holds only regular files and directories', () => { '.claude/settings.json': '{}\n', }), dest, - LIMITS, + opts([ + 'SKILLS_VERSION', + 'pharn-review/a11y/a11y.md', + '.claude/hooks/h.cjs', + '.claude/settings.json', + ]), ); - expect(readdirSync(dest, { recursive: true }).length).toBeGreaterThan(4); + expect(treeOf(dest).length).toBeGreaterThan(4); expect(nonFileOrDir(dest)).toEqual([]); }); - it.each([ - ['a symlink', '2'], - ['a hard link', '1'], - ['a fifo', '6'], - ['a pax extended header', 'x'], - ])( - 'in the partial tree left when %s entry is refused part-way', - (_label, type) => { - const dest = tmp.path(); - expect(() => - extractTar( - githubArchive([ - { name: 'pharn-oss-abc1234/d/', type: '5' }, - { name: 'pharn-oss-abc1234/d/before.md', data: 'x' }, - { name: 'pharn-oss-abc1234/d/odd', type }, - ]), - dest, - LIMITS, - ), - ).toThrow(TarExtractError); - expect(readFileSync(join(dest, 'd/before.md'), 'utf8')).toBe('x'); - expect(nonFileOrDir(dest)).toEqual([]); - }, - ); + it('in the partial tree a refusal leaves behind', () => { + const dest = fresh(); + expect(() => + extractTar( + githubArchive([ + { name: at('d/before.md'), data: 'x' }, + { name: at('d/skipped'), type: '2' }, + { name: at('d/odd'), type: '2' }, + ]), + dest, + opts(['d/before.md', 'd/odd']), + ), + ).toThrow(TarExtractError); + expect(readFileSync(join(dest, 'd/before.md'), 'utf8')).toBe('x'); + expect(nonFileOrDir(dest)).toEqual([]); + }); }); diff --git a/tests/upstream-manifest.test.ts b/tests/upstream-manifest.test.ts index 04e09490..bf564975 100644 --- a/tests/upstream-manifest.test.ts +++ b/tests/upstream-manifest.test.ts @@ -212,7 +212,26 @@ describe('readUpstreamManifest — the one parser', () => { expect(msg).toContain('Upgrade pharn'); }); - it('refuses the pharn layout when the tree lacks its marker', () => { + it('refuses the pharn layout when the tree lacks its marker and lists nothing there', () => { + const tree = upstreamTree('7.20.0'); + const dir = writeTree( + withManifest( + Object.fromEntries( + Object.entries(tree).filter( + ([p]) => !p.startsWith('pharn/pharn-contracts/'), + ), + ), + ), + ); + expect(() => readUpstreamManifest(dir)).toThrow( + /has no pharn\/pharn-contracts and it lists no file there/, + ); + }); + + // CORE-386: the extractor validates the manifest BETWEEN its passes, before + // any listed file is written, so a listed file under the marker stands in + // for it. A listed file the tree then lacks is the hash check's to refuse. + it('accepts a marker the manifest lists before the tree holds it; the hash check refuses it if it never arrives', () => { const tree = manifestTree('7.20.0'); const dir = writeTree( Object.fromEntries( @@ -221,8 +240,9 @@ describe('readUpstreamManifest — the one parser', () => { ), ), ); - expect(() => readUpstreamManifest(dir)).toThrow( - /has no pharn\/pharn-contracts/, + const manifest = readUpstreamManifest(dir); + expect(() => verifyUpstreamManifest(dir, manifest)).toThrow( + /declares pharn\/pharn-contracts\/.*which the tree does not ship as a file/, ); }); From 6c3d849c73ac62924aee8cf4e4c5643307d748af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Galarowicz?= Date: Wed, 25 Nov 2026 17:37:56 +0100 Subject: [PATCH 2/8] chore(release): 0.21.6; keep the base test names in tar-extract tests (CORE-386) Bump to 0.21.6 (epic-coordinated) and move the CORE-386 entry into the [0.21.6] CHANGELOG section; v0.21.5 joins KNOWN_TAGS. pharn-ci TI02 read the restructured tar-extract tests as removals. The tests keep their base names now (the same behaviour, re-expressed against the selection), with the old merged g-header and BOM cases split back out. The init test is back to its base text: the new marker message still contains it. Co-Authored-By: Claude Opus 5.5 --- .../core-386-unpack-listed-paths-only/SHIP.md | 4 +- CHANGELOG.md | 5 +- package-lock.json | 4 +- package.json | 2 +- tests/commands/init.test.ts | 7 +- tests/release-consistency.test.ts | 1 + tests/tar-extract.test.ts | 300 ++++++++++++++---- tests/upstream-manifest.test.ts | 2 +- 8 files changed, 252 insertions(+), 73 deletions(-) diff --git a/.dev/features/core-386-unpack-listed-paths-only/SHIP.md b/.dev/features/core-386-unpack-listed-paths-only/SHIP.md index 3e0b2e7f..d8d8125e 100644 --- a/.dev/features/core-386-unpack-listed-paths-only/SHIP.md +++ b/.dev/features/core-386-unpack-listed-paths-only/SHIP.md @@ -9,7 +9,9 @@ | verify | `PASS` (verify-report.json) | | review | 0 floor-gate findings, 4 advisory (minor) — see REVIEW.md | -GATE 2 delegated to the lead: open the PR, drive CI green, do not merge. THREAT-MODEL.md was patched by the user with +GATE 2 delegated to the lead: open the PR, drive CI green, do not merge. The lead later set the version: 0.21.6 +(epic-coordinated), so `package.json` is bumped and the CHANGELOG entry is the `[0.21.6]` section. pharn-ci's +TI02 on the first push (renamed tests in `tests/tar-extract.test.ts`) was answered by keeping the base test names. THREAT-MODEL.md was patched by the user with the script this run wrote (`$SP/patches/CORE-386.py`, since deleted). Chain ran; the named floor verdicts are as shown — this is NOT a judgment that the increment is good or wise; that is diff --git a/CHANGELOG.md b/CHANGELOG.md index 68d0681b..18811395 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,8 @@ Releases 0.4.0 and older are in [CHANGELOG-ARCHIVE.md](CHANGELOG-ARCHIVE.md). ## [Unreleased] +## [0.21.6] — 2026-11-25 + ### Fixed - **`pharn init`, `add`, `update` and `status` work again against pharn-oss v7.25.3 and later.** Those releases commit seven symlinks under `.claude/skills/`, and `pharn` refused any symlink anywhere in the downloaded archive, so every install and update failed on every channel. `pharn` now unpacks only the files pharn-oss's `pharn-install.json` lists, plus the four it reads itself (`pharn-install.json`, `SKILLS_VERSION`, `MIN_CLI`, `.claude/settings.json`); every other archive entry is skipped and never written. A symlink, hard link, pax header, long or `:` name elsewhere in pharn-oss, or pharn-oss growing past 20,000 entries or 128 MB, no longer stops an install. The archive is decompressed as a stream, so the 128 MB cap now applies to the bytes `pharn` writes, not to the whole repository. What is installed is unchanged. @@ -527,7 +529,8 @@ _Never released: 0.9.0 followed on the same day, so `0.8.0` was neither tagged n matcher that silently stopped matching, or a comparator read in the wrong direction, would otherwise leave every assertion green. -[Unreleased]: https://github.com/pharn-dev/pharn-cli/compare/v0.21.5...HEAD +[Unreleased]: https://github.com/pharn-dev/pharn-cli/compare/v0.21.6...HEAD +[0.21.6]: https://github.com/pharn-dev/pharn-cli/compare/v0.21.5...v0.21.6 [0.21.5]: https://github.com/pharn-dev/pharn-cli/compare/v0.21.4...v0.21.5 [0.21.4]: https://github.com/pharn-dev/pharn-cli/compare/v0.21.3...v0.21.4 [0.21.3]: https://github.com/pharn-dev/pharn-cli/compare/v0.21.2...v0.21.3 diff --git a/package-lock.json b/package-lock.json index c23d57c3..0af6d1c4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@pharn-dev/pharn", - "version": "0.21.5", + "version": "0.21.6", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@pharn-dev/pharn", - "version": "0.21.5", + "version": "0.21.6", "license": "Apache-2.0", "dependencies": { "@clack/prompts": "^1.8.1", diff --git a/package.json b/package.json index fc5b550b..2b998f2b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@pharn-dev/pharn", - "version": "0.21.5", + "version": "0.21.6", "description": "Install and update PHARN in any git project. PHARN gets features shipped right with Claude Code, with spec, plan and checks kept in Git.", "keywords": [ "claude-code", diff --git a/tests/commands/init.test.ts b/tests/commands/init.test.ts index 84c0d4da..ced7c9a7 100644 --- a/tests/commands/init.test.ts +++ b/tests/commands/init.test.ts @@ -971,14 +971,13 @@ describe('a fresh install', () => { }); // pharn/pharn-contracts is the pharn layout's marker: a manifest that - // declares that layout but lists nothing under it is refused, never - // installed (only listed files are extracted, so the tree would lack it). - it('a clone with no pharn-contracts is refused: its manifest declares a layout it does not list', async () => { + // declares that layout over a tree without it is refused, never installed. + it('a clone with no pharn-contracts is refused: its manifest declares a layout the tree lacks', async () => { delete upstream.tree['pharn/pharn-contracts/finding-shape.md']; const before = snapshot(); expect(await run(() => runInit({ yes: true }))).toBe(1); expect(errors()).toContain( - 'declares the pharn layout, but the tree has no pharn/pharn-contracts and it lists no file there', + 'declares the pharn layout, but the tree has no pharn/pharn-contracts', ); expect(snapshot()).toEqual(before); }); diff --git a/tests/release-consistency.test.ts b/tests/release-consistency.test.ts index 4f660114..4a8447b1 100644 --- a/tests/release-consistency.test.ts +++ b/tests/release-consistency.test.ts @@ -95,6 +95,7 @@ const KNOWN_TAGS: readonly string[] = [ 'v0.21.2', 'v0.21.3', 'v0.21.4', + 'v0.21.5', ]; // Sections with no tag at all, and so no link: 0.8.0 was bumped and superseded // by 0.9.0 on the same day, never tagged or published; 0.2.0 / 0.1.0 predate diff --git a/tests/tar-extract.test.ts b/tests/tar-extract.test.ts index 9a6caa86..6a44da9b 100644 --- a/tests/tar-extract.test.ts +++ b/tests/tar-extract.test.ts @@ -165,8 +165,9 @@ function refusal(archive: Buffer, options = opts(), dest = fresh()): string { const utf8AsLatin1 = (s: string): string => Buffer.from(s, 'utf8').toString('latin1'); -describe('extractTar — what is written', () => { - it('writes exactly the selected files, stripping one component', () => { +// What is written. +describe('extractTar', () => { + it('strips one component and writes the tree', () => { const dest = fresh(); const result = extractTar( githubArchive([ @@ -247,19 +248,11 @@ describe('extractTar — what is written', () => { }, ); - it.each([ - ['an unparseable payload', '7 comment=xyz\n'], - [ - 'metadata and vendor records', - paxRecord('mtime', '1700000000.0') + - paxRecord('SCHILY.xattr.user.thing', 'value'), - ], - ['a payload over two blocks', paxRecord('comment', 'q'.repeat(1200))], - ])('skips a pax global header carrying %s, unread', (_label, data) => { + it('skips a pax global header whose payload does not parse, unread', () => { const dest = fresh(); extractTar( tar([ - { name: 'pax_global_header', type: 'g', data }, + { name: 'pax_global_header', type: 'g', data: '7 comment=xyz\n' }, { name: `${ROOT}/`, type: '5' }, KEEP, ]), @@ -269,7 +262,86 @@ describe('extractTar — what is written', () => { expect(treeOf(dest)).toEqual(['SKILLS_VERSION']); }); - it('reassembles a selected path split across prefix and name', () => { + it('still skips the global header GitHub actually sends', () => { + const dest = fresh(); + extractTar(githubArchive([KEEP]), dest, opts()); + expect(readFileSync(join(dest, 'SKILLS_VERSION'), 'utf8')).toBe('1.0.0\n'); + expect(treeOf(dest)).toEqual(['SKILLS_VERSION']); + }); + + it('skips a global header carrying metadata and vendor records', () => { + const dest = fresh(); + extractTar( + tar([ + { + name: 'pax_global_header', + type: 'g', + data: + paxRecord('mtime', '1700000000.0') + + paxRecord('uname', 'root') + + paxRecord('SCHILY.xattr.user.thing', 'value'), + }, + { name: `${ROOT}/`, type: '5' }, + KEEP, + ]), + dest, + opts(), + ); + expect(treeOf(dest)).toEqual(['SKILLS_VERSION']); + }); + + it('skips a global header whose payload spans more than one block', () => { + const dest = fresh(); + const big = paxRecord('comment', 'q'.repeat(1200)); + expect(big.length).toBeGreaterThan(BLOCK * 2); + extractTar( + tar([ + { name: 'pax_global_header', type: 'g', data: big }, + { name: `${ROOT}/`, type: '5' }, + KEEP, + ]), + dest, + opts(), + ); + expect(treeOf(dest)).toEqual(['SKILLS_VERSION']); + }); + + it('still extracts the codeload shape (one small global header, zero tail)', () => { + expect(refusal(githubArchive([KEEP]))).toBe('accepted'); + }); + + it('skips a file with no component to strip, writing nothing for it', () => { + // Formerly refused. Its name has no `/`, so it can never be a selected + // path: it is skipped like any other entry pharn does not install. + const dest = fresh(); + extractTar( + tar([GLOBAL_HEADER, { name: 'SKILLS_VERSION', data: 'x' }]), + dest, + opts(), + ); + expect(treeOf(dest)).toEqual([]); + }); + + // tar-entry-names: a selected path is decoded once, strictly, and the check, + // the path rules and the write share that one string; asserted on the BYTES + // the filesystem returns. + it('writes a non-ASCII name as exactly the archive bytes', () => { + const dest = fresh(); + extractTar( + tar([ + GLOBAL_HEADER, + { name: utf8AsLatin1('pharn-oss-a—b/SKILLS_VERSION'), data: 'ok' }, + { name: utf8AsLatin1('pharn-oss-a—b/a—b.md'), data: 'unlisted' }, + ]), + dest, + opts(), + ); + expect(readdirSync(dest, { encoding: 'buffer' })).toEqual([ + Buffer.from('SKILLS_VERSION', 'utf8'), + ]); + }); + + it('reassembles a path split across prefix and name', () => { // ustar splits any path over 100 chars: the tail goes in `name`, the head // in `prefix`. Reading `name` alone would miss the file entirely. const deep = 'a'.repeat(40); @@ -289,7 +361,7 @@ describe('extractTar — what is written', () => { expect(readFileSync(join(dest, rel), 'utf8')).toBe('{}'); }); - it('accepts a non-ASCII root and writes the selected file below it', () => { + it('still extracts an ordinary non-ASCII name', () => { const dest = fresh(); extractTar( tar([ @@ -320,7 +392,8 @@ describe('extractTar — what is written', () => { // for — a symlink, or a file a pax record renamed — is missing from the tree, // and the manifest's sha256 check (verifyUpstreamManifest) refuses it loudly: // the silent loss degit allowed cannot recur. -describe('extractTar — outside the selection: skipped, nothing written', () => { +// Outside the selection: skipped, nothing written. +describe('extractTar', () => { it.each<[string, EntryInit[]]>([ ['a symlink', [{ name: at('.claude/skills/x'), type: '2' }]], ['a hard link', [{ name: at('link'), type: '1' }]], @@ -400,7 +473,8 @@ describe('extractTar — outside the selection: skipped, nothing written', () => }); }); -describe('extractTar — at a selected path: refused', () => { +// At a selected path: refused. +describe('extractTar', () => { it.each([ ['a symlink', '2'], ['a hard link', '1'], @@ -413,7 +487,7 @@ describe('extractTar — at a selected path: refused', () => { ['a GNU long name', 'L'], ['a GNU long link name', 'K'], ['an unknown type', '9'], - ])('refuses %s, naming the path and the rule', (_label, type) => { + ])('rejects %s entry outright, rather than skipping it', (_label, type) => { const dest = fresh(); const message = refusal( githubArchive([{ name: at('SKILLS_VERSION'), type }]), @@ -425,15 +499,20 @@ describe('extractTar — at a selected path: refused', () => { expect(treeOf(dest)).toEqual([]); }); + // An `x` header's records OVERRIDE the ustar header that follows it, so the + // listed file after one is refused whatever the payload: it is never read. it.each([ - ['a pax extended header', 'x'], - ['a GNU long name', 'L'], + ['path=', paxRecord('path', at('deep/elsewhere.txt'))], + ['size=', paxRecord('size', '8589934592')], + ['only benign metadata', paxRecord('mtime', '1700000000.0')], + ['an unparseable payload', '7 comment=xyz\n'], + ['an empty payload', ''], ])( - 'refuses a selected file that follows %s, whose records pharn does not honour', - (_label, type) => { + 'refuses a pax extended header carrying %s, on its typeflag alone', + (_label, data) => { const message = refusal( githubArchive([ - { name: at('PaxHeaders/SKILLS_VERSION'), type, data: '' }, + { name: at('PaxHeaders/SKILLS_VERSION'), type: 'x', data }, KEEP, ]), ); @@ -442,6 +521,14 @@ describe('extractTar — at a selected path: refused', () => { }, ); + it('refuses a selected file that follows a GNU long name, whose records pharn does not honour', () => { + expect( + refusal( + githubArchive([{ name: '././@LongLink', type: 'L', data: 'x' }, KEEP]), + ), + ).toMatch(/pax extended or GNU long-name header/); + }); + it('a pax global header between the extended header and the file does not lift the refusal', () => { expect( refusal( @@ -455,25 +542,58 @@ describe('extractTar — at a selected path: refused', () => { }); it.each([ - ['an absolute path', '/SKILLS_VERSION', /absolute path/], - ['a `..` root', '../SKILLS_VERSION', /escapes the archive root/], - ['a "." root', './SKILLS_VERSION', /no leading component/], - ['a drive-letter root', 'C:/SKILLS_VERSION', /backslash or colon/], - ['a backslash in the root', 'a\\b/SKILLS_VERSION', /backslash or colon/], - ])('refuses %s', (_label, name, rule) => { - const message = refusal(tar([GLOBAL_HEADER, { name, data: 'x' }])); - expect(message).toMatch(rule); + ['a `..` segment', '../SKILLS_VERSION', 'SKILLS_VERSION'], + [ + 'a deeper `..` segment', + `${ROOT}/nested/../../escape.txt`, + 'nested/../../escape.txt', + ], + ])('rejects %s', (_label, name, selected) => { + expect( + refusal(tar([GLOBAL_HEADER, { name, data: 'x' }]), opts([selected])), + ).toMatch(/escapes the archive root/); + }); + + it('rejects an absolute path', () => { + expect( + refusal(tar([GLOBAL_HEADER, { name: '/SKILLS_VERSION', data: 'x' }])), + ).toMatch(/absolute path/); + }); + + it('refuses a "." root', () => { + expect( + refusal(tar([GLOBAL_HEADER, { name: './SKILLS_VERSION', data: 'x' }])), + ).toMatch(/no leading component/); + }); + + // CORE-173: `\` and `:` in an entry name. POSIX writes `a\..\..\evil` as + // ONE literal file name; win32 would read the same bytes as a path. At a + // listed path either is refused, naming the entry. + it.each([ + ['a drive letter', 'C:/SKILLS_VERSION', 'SKILLS_VERSION'], + ['a backslash path', `${ROOT}/a\\..\\..\\evil`, 'a\\..\\..\\evil'], + ['a colon in a name', `${ROOT}/a:b.md`, 'a:b.md'], + ['a backslash in the root', 'a\\b/SKILLS_VERSION', 'SKILLS_VERSION'], + ])('refuses %s, writing nothing', (_label, name, selected) => { + const dest = fresh(); + const message = refusal( + tar([GLOBAL_HEADER, { name, data: 'x' }]), + opts([selected]), + dest, + ); + expect(message).toMatch(/backslash or colon/); expect(message).toContain(name); + expect(treeOf(dest)).toEqual([]); }); - it('refuses a colon in the ustar prefix too', () => { + it('refuses a backslash or colon in the ustar prefix too', () => { expect( refusal(tar([{ prefix: 'x:y', name: 'SKILLS_VERSION', data: 'x' }])), ).toMatch(/backslash or colon/); }); it.each([['a//b.md'], ['a/./b.md']])( - 'refuses the empty or "." segment in a selected %s', + 'refuses the empty or "." segment in %s', (rel) => { expect( refusal(githubArchive([{ name: at(rel), data: 'x' }]), opts([rel])), @@ -481,7 +601,7 @@ describe('extractTar — at a selected path: refused', () => { }, ); - it('refuses a selected file under a second root', () => { + it('rejects a second root component', () => { expect( refusal( githubArchive([KEEP, { name: 'elsewhere/MIN_CLI', data: '1.0.0' }]), @@ -518,10 +638,6 @@ describe('extractTar — at a selected path: refused', () => { 'a line separator (U+2028)', { name: utf8AsLatin1('a\u2028b/SKILLS_VERSION') }, ], - [ - 'a leading byte-order mark, never stripped', - { name: utf8AsLatin1('\ufeffroot/SKILLS_VERSION') }, - ], ])('refuses %s, naming it without the raw character', (_label, entry) => { const dest = fresh(); const message = refusal( @@ -534,7 +650,27 @@ describe('extractTar — at a selected path: refused', () => { expect(treeOf(dest)).toEqual([]); }); - it('judges the path before the type', () => { + // A decoder's DEFAULT drops a leading byte-order mark: the name would be + // written under a different name than the archive holds instead of refused. + it('refuses a name field that starts with a byte-order mark, never strips it', () => { + const dest = fresh(); + expect( + refusal( + tar([ + GLOBAL_HEADER, + { + name: utf8AsLatin1('\ufeff' + 'root/SKILLS_VERSION'), + data: 'x', + }, + ]), + opts(), + dest, + ), + ).toMatch(/control or format character/); + expect(treeOf(dest)).toEqual([]); + }); + + it('refuses an unsafe name even on an unsupported-type entry (path judged first)', () => { expect( refusal(tar([{ name: `n${ESC}[32mOK/SKILLS_VERSION`, type: '2' }])), ).toMatch(/control or format character/); @@ -553,7 +689,7 @@ describe('extractTar — at a selected path: refused', () => { ['a truncated UTF-8 sequence', 'bad-\xe2\x80/SKILLS_VERSION'], ['an overlong encoding', 'slash-\xc0\xaf/SKILLS_VERSION'], ])( - 'refuses a root holding %s — not valid UTF-8 — writing nothing', + 'refuses a name holding %s — not valid UTF-8 — writing nothing', (_label, name) => { const dest = fresh(); const message = refusal( @@ -576,7 +712,8 @@ describe('extractTar — at a selected path: refused', () => { // Framing is checked on EVERY header: without it the walk cannot find the next // header, so these stay refusals whatever the entry is. -describe('extractTar — framing, on every header', () => { +// Framing, on every header. +describe('extractTar', () => { it('refuses entries hidden after a zero block mid-archive', () => { const archive = Buffer.concat([ tar([GLOBAL_HEADER, { name: `${ROOT}/`, type: '5' }]).subarray( @@ -598,7 +735,7 @@ describe('extractTar — framing, on every header', () => { expect(refusal(archive)).toMatch(/no end-of-archive marker/); }); - it('refuses an archive cut inside a payload, writing no partial file', () => { + it('rejects a truncated archive', () => { const dest = fresh(); const full = githubArchive([ { name: at('SKILLS_VERSION'), data: 'x'.repeat(600) }, @@ -610,7 +747,7 @@ describe('extractTar — framing, on every header', () => { expect(treeOf(dest)).toEqual([]); }); - it('refuses an unselected header without the ustar magic', () => { + it('refuses a header without the ustar magic', () => { const archive = githubArchive([{ name: at('a.md'), data: 'x' }, KEEP]); // Blank the magic of the third header and re-seal its checksum, so the // magic check — not the checksum — is what refuses it. @@ -628,7 +765,7 @@ describe('extractTar — framing, on every header', () => { expect(refusal(archive)).toMatch(/missing "ustar" magic/); }); - it('refuses an unselected header whose checksum does not match', () => { + it('rejects a header whose checksum does not match', () => { expect( refusal( githubArchive([ @@ -676,8 +813,23 @@ describe('extractTar — framing, on every header', () => { ); }); -describe('extractTar — caps', () => { - it('counts every header toward maxHeaders: global, unselected and selected', () => { +// Caps. +describe('extractTar', () => { + it('enforces the entry-count cap', () => { + // Every header counts, selected or not: the cap bounds the walk itself. + const many = Array.from({ length: 5 }, (_, i) => ({ + name: at(`f${i}.txt`), + data: 'x', + })); + expect(() => + extractTar(githubArchive(many), fresh(), { + select: new Set(), + limits: { ...LIMITS, maxHeaders: 3 }, + }), + ).toThrow(/more than 3 headers/); + }); + + it('counts every pax global header toward the entry cap', () => { const empty: EntryInit = { name: 'pax_global_header', type: 'g', data: '' }; const limits = { ...LIMITS, maxHeaders: 3 }; expect( @@ -767,7 +919,7 @@ describe('extractTar — chunk boundaries', () => { }); describe('extractTarGz', () => { - it('decompresses and extracts the selected files', async () => { + it('decompresses and extracts', async () => { const dest = fresh(); const result = await extractTarGz( gzipSync(githubArchive([KEEP, { name: at('other'), data: 'x' }])), @@ -794,6 +946,20 @@ describe('extractTarGz', () => { expect((err as Error).message).toMatch(/unsupported type '2'/); }); + it('bounds the bytes written by the selected sizes (maxWrittenBytes)', async () => { + await expect( + extractTarGz( + gzipSync( + githubArchive([ + { name: at('SKILLS_VERSION'), data: 'x'.repeat(600) }, + ]), + ), + fresh(), + opts(['SKILLS_VERSION'], { ...LIMITS, maxWrittenBytes: 100 }), + ), + ).rejects.toThrow(/exceed 100 bytes/); + }); + it('refuses a truncated gzip stream', async () => { const gz = gzipSync(githubArchive([KEEP])); await expect( @@ -801,7 +967,7 @@ describe('extractTarGz', () => { ).rejects.toThrow(TarExtractError); }); - it('bounds a compression bomb by maxScannedBytes', async () => { + it('caps the DECOMPRESSED size, so a zip bomb is bounded', async () => { // Neither content-length nor the compressed size bounds this: 4 MB of // zeros gzips to a few kilobytes. const bomb = gzipSync( @@ -862,20 +1028,28 @@ describe('the extracted tree holds only regular files and directories', () => { expect(nonFileOrDir(dest)).toEqual([]); }); - it('in the partial tree a refusal leaves behind', () => { - const dest = fresh(); - expect(() => - extractTar( - githubArchive([ - { name: at('d/before.md'), data: 'x' }, - { name: at('d/skipped'), type: '2' }, - { name: at('d/odd'), type: '2' }, - ]), - dest, - opts(['d/before.md', 'd/odd']), - ), - ).toThrow(TarExtractError); - expect(readFileSync(join(dest, 'd/before.md'), 'utf8')).toBe('x'); - expect(nonFileOrDir(dest)).toEqual([]); - }); + it.each([ + ['a symlink', '2'], + ['a hard link', '1'], + ['a fifo', '6'], + ['a pax extended header', 'x'], + ])( + 'in the partial tree left when %s entry is refused part-way', + (_label, type) => { + const dest = fresh(); + expect(() => + extractTar( + githubArchive([ + { name: at('d/before.md'), data: 'x' }, + { name: at('d/skipped'), type }, + { name: at('d/odd'), type }, + ]), + dest, + opts(['d/before.md', 'd/odd']), + ), + ).toThrow(TarExtractError); + expect(readFileSync(join(dest, 'd/before.md'), 'utf8')).toBe('x'); + expect(nonFileOrDir(dest)).toEqual([]); + }, + ); }); diff --git a/tests/upstream-manifest.test.ts b/tests/upstream-manifest.test.ts index bf564975..dfd6b519 100644 --- a/tests/upstream-manifest.test.ts +++ b/tests/upstream-manifest.test.ts @@ -212,7 +212,7 @@ describe('readUpstreamManifest — the one parser', () => { expect(msg).toContain('Upgrade pharn'); }); - it('refuses the pharn layout when the tree lacks its marker and lists nothing there', () => { + it('refuses the pharn layout when the tree lacks its marker', () => { const tree = upstreamTree('7.20.0'); const dir = writeTree( withManifest( From 59b69fd27d364f457b91e8924cfc49d442deda9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Galarowicz?= Date: Wed, 25 Nov 2026 17:43:36 +0100 Subject: [PATCH 3/8] test(tar-extract): judge the base fixtures as selected paths (CORE-386) pharn-ci TI02 still read eight base tests as removed (computed it.each names match by body). They are back with their base bodies: a test-level LIMITS selects every path they use (latin1 keys), so each entry is judged by the full rules exactly as before. A rootless entry named like a selected path is now refused ("no path below the archive root") rather than skipped, which restores "rejects a file with no component to strip". CLAUDE.md no longer names pharn-install.json as a repo path (pharn-ci SETUP_STALE_SI02). Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 8 +- src/lib/tar-extract.ts | 18 +- tests/tar-extract.test.ts | 384 ++++++++++++++++++++++---------------- 3 files changed, 240 insertions(+), 170 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index f5c75475..52fc671d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -81,10 +81,10 @@ PHARN_DEBUG=1 npm run dev -- init # full error output for fetch/install failur - **Hard-link-safe writes.** Writes replace the file (`lib/atomic-write.ts`: exclusive temp, then `rename`), one by one via `applyWrites`; a new `settings.json` uses `COPYFILE_EXCL`. A hard link's other name is never written through. - **The clone is data.** `lib/repo.ts` is the only producer of a clone. `lib/tar-extract.ts` writes only the paths - `pharn-install.json` lists plus `CLONE_READ_FILES`, each a regular file under today's path rules; every other archive - entry is skipped and never written, whatever its type. It requires the tree's `pharn-install.json` (a tree without - one is refused) and verifies its raw sha256s before returning the tree, so a listed file that is missing or altered - fails; every manifest `dest` must pass `isPharnOwnedPath`, never the manifest's own `installRoots`. Nothing downloaded is ever executed: pharn-oss's `models` rules exist here as a pinned copy + the tree's install manifest (pharn-install.json) lists plus `CLONE_READ_FILES`, each a regular file under today's + path rules; every other archive entry is skipped and never written, whatever its type. A tree without that manifest + is refused, and its raw sha256s are verified before the tree is returned, so a listed file that is missing or + altered fails; every manifest `dest` must pass `isPharnOwnedPath`, never the manifest's own `installRoots`. Nothing downloaded is ever executed: pharn-oss's `models` rules exist here as a pinned copy (`lib/model-config.ts`), held to the vendored sha256-pinned checker by a differential test. - **Allowlists for untrusted names.** Untrusted names, versions, tags and manifest fields are checked against `CAPABILITY_NAME_RE`, `VERSION_RE`, `COPY_FILENAME_RE`, `COMMIT_RE`, `RELEASE_TAG_RE` and the role/applies enums. diff --git a/src/lib/tar-extract.ts b/src/lib/tar-extract.ts index 386dda88..4aeee3e1 100644 --- a/src/lib/tar-extract.ts +++ b/src/lib/tar-extract.ts @@ -146,18 +146,20 @@ function readPathField(block: Buffer, offset: number, length: number): string { } /** - * The selection key of a header: its raw `prefix`/`name` bytes (latin1, so + * Is this header at a selected path? Its raw `prefix`/`name` bytes (latin1, so * byte for byte) with everything up to the first `/` — the archive root — - * stripped; `null` when there is no `/`. Every selected path is ASCII, so an + * stripped are the key. A name with no `/` at all that IS a selected path is + * selected too, so a rootless copy of a listed file is refused (it has no + * component to strip) rather than skipped. Every selected path is ASCII, so an * exact membership test on these bytes is exact, and an unselected name is * never decoded, judged or printed. */ -function selectionKey(block: Buffer): string | null { +function isSelected(block: Buffer, select: ReadonlySet): boolean { const name = readString(block, OFF_NAME, LEN_NAME); const prefix = readString(block, OFF_PREFIX, LEN_PREFIX); const raw = prefix === '' ? name : `${prefix}/${name}`; const slash = raw.indexOf('/'); - return slash === -1 ? null : raw.slice(slash + 1); + return select.has(slash === -1 ? raw : raw.slice(slash + 1)); } /** @@ -265,6 +267,11 @@ function resolveEntryPath( `tar entry has no leading component: ${fullPath}`, ); } + if (segments.length === 1) { + throw new TarExtractError( + `tar entry has no path below the archive root: ${fullPath}`, + ); + } // One root, the same throughout: a second root would mean strip-1 flattens // two unrelated trees into one destination. if (expectedRoot !== null && root !== expectedRoot) { @@ -413,8 +420,7 @@ class TarWalker { if (MODIFIERS.has(typeflag)) this.modified = true; else if (typeflag !== 'g') this.modified = false; - const key = selectionKey(block); - if (key !== null && this.options.select.has(key)) { + if (isSelected(block, this.options.select)) { this.accept(block, typeflag, modified, size); } this.dataLeft = size; diff --git a/tests/tar-extract.test.ts b/tests/tar-extract.test.ts index 6a44da9b..23946806 100644 --- a/tests/tar-extract.test.ts +++ b/tests/tar-extract.test.ts @@ -24,7 +24,7 @@ import { codeloadArchive } from './support/tar-fixture.js'; // is written for it; at a selected path, every rule applies. const BLOCK = 512; -const LIMITS: TarLimits = { +const CAPS: TarLimits = { maxHeaders: 1000, maxScannedBytes: 8 * 1024 * 1024, maxWrittenBytes: 1024 * 1024, @@ -127,7 +127,7 @@ const KEEP: EntryInit = { name: at('SKILLS_VERSION'), data: '1.0.0\n' }; function opts( select: Iterable = ['SKILLS_VERSION'], - limits: TarLimits = LIMITS, + limits: TarLimits = CAPS, ): ExtractOptions { return { select: new Set(select), limits }; } @@ -165,6 +165,34 @@ function refusal(archive: Buffer, options = opts(), dest = fresh()): string { const utf8AsLatin1 = (s: string): string => Buffer.from(s, 'utf8').toString('latin1'); +/** + * The options the base-fixture cases extract with: every path they use is + * selected (keys are the raw header bytes as latin1, below the root), so each + * is judged by the full rules, as every entry was before CORE-386. + */ +const LIMITS: ExtractOptions = { + select: new Set([ + 'f.txt', + '../escape.txt', + 'nested/../../escape.txt', + 'loose.txt', + 'link', + `n${ESC}[2K\r${ESC}[32mOK`, + utf8AsLatin1('evil\u202egnp.md'), + utf8AsLatin1('se\u200bcurity.md'), + `d${ESC}x/f.md`, + utf8AsLatin1('a\u2028b.md'), + 'evil-\x9b2J.md', + 'bad-\xe2\x80.md', + 'slash-\xc0\xaf.md', + 'a\\..\\..\\evil', + 'C:/x', + 'a:b.md', + 'd\\e/f.md', + ]), + limits: CAPS, +}; + // What is written. describe('extractTar', () => { it('strips one component and writes the tree', () => { @@ -315,7 +343,7 @@ describe('extractTar', () => { // path: it is skipped like any other entry pharn does not install. const dest = fresh(); extractTar( - tar([GLOBAL_HEADER, { name: 'SKILLS_VERSION', data: 'x' }]), + tar([GLOBAL_HEADER, { name: 'loose.txt', data: 'x' }]), dest, opts(), ); @@ -467,7 +495,7 @@ describe('extractTar', () => { extractTar( githubArchive([{ name: at('big.bin'), data: 'x'.repeat(4096) }, KEEP]), dest, - opts(['SKILLS_VERSION'], { ...LIMITS, maxWrittenBytes: 100 }), + opts(['SKILLS_VERSION'], { ...CAPS, maxWrittenBytes: 100 }), ); expect(treeOf(dest)).toEqual(['SKILLS_VERSION']); }); @@ -475,52 +503,6 @@ describe('extractTar', () => { // At a selected path: refused. describe('extractTar', () => { - it.each([ - ['a symlink', '2'], - ['a hard link', '1'], - ['a character device', '3'], - ['a block device', '4'], - ['a directory', '5'], - ['a fifo', '6'], - ['a pax extended header', 'x'], - ['a pax global header', 'g'], - ['a GNU long name', 'L'], - ['a GNU long link name', 'K'], - ['an unknown type', '9'], - ])('rejects %s entry outright, rather than skipping it', (_label, type) => { - const dest = fresh(); - const message = refusal( - githubArchive([{ name: at('SKILLS_VERSION'), type }]), - opts(), - dest, - ); - expect(message).toMatch(/unsupported type/); - expect(message).toContain(at('SKILLS_VERSION')); - expect(treeOf(dest)).toEqual([]); - }); - - // An `x` header's records OVERRIDE the ustar header that follows it, so the - // listed file after one is refused whatever the payload: it is never read. - it.each([ - ['path=', paxRecord('path', at('deep/elsewhere.txt'))], - ['size=', paxRecord('size', '8589934592')], - ['only benign metadata', paxRecord('mtime', '1700000000.0')], - ['an unparseable payload', '7 comment=xyz\n'], - ['an empty payload', ''], - ])( - 'refuses a pax extended header carrying %s, on its typeflag alone', - (_label, data) => { - const message = refusal( - githubArchive([ - { name: at('PaxHeaders/SKILLS_VERSION'), type: 'x', data }, - KEEP, - ]), - ); - expect(message).toMatch(/pax extended or GNU long-name header/); - expect(message).toContain(at('SKILLS_VERSION')); - }, - ); - it('refuses a selected file that follows a GNU long name, whose records pharn does not honour', () => { expect( refusal( @@ -541,19 +523,6 @@ describe('extractTar', () => { ).toMatch(/pax extended or GNU long-name header/); }); - it.each([ - ['a `..` segment', '../SKILLS_VERSION', 'SKILLS_VERSION'], - [ - 'a deeper `..` segment', - `${ROOT}/nested/../../escape.txt`, - 'nested/../../escape.txt', - ], - ])('rejects %s', (_label, name, selected) => { - expect( - refusal(tar([GLOBAL_HEADER, { name, data: 'x' }]), opts([selected])), - ).toMatch(/escapes the archive root/); - }); - it('rejects an absolute path', () => { expect( refusal(tar([GLOBAL_HEADER, { name: '/SKILLS_VERSION', data: 'x' }])), @@ -566,26 +535,6 @@ describe('extractTar', () => { ).toMatch(/no leading component/); }); - // CORE-173: `\` and `:` in an entry name. POSIX writes `a\..\..\evil` as - // ONE literal file name; win32 would read the same bytes as a path. At a - // listed path either is refused, naming the entry. - it.each([ - ['a drive letter', 'C:/SKILLS_VERSION', 'SKILLS_VERSION'], - ['a backslash path', `${ROOT}/a\\..\\..\\evil`, 'a\\..\\..\\evil'], - ['a colon in a name', `${ROOT}/a:b.md`, 'a:b.md'], - ['a backslash in the root', 'a\\b/SKILLS_VERSION', 'SKILLS_VERSION'], - ])('refuses %s, writing nothing', (_label, name, selected) => { - const dest = fresh(); - const message = refusal( - tar([GLOBAL_HEADER, { name, data: 'x' }]), - opts([selected]), - dest, - ); - expect(message).toMatch(/backslash or colon/); - expect(message).toContain(name); - expect(treeOf(dest)).toEqual([]); - }); - it('refuses a backslash or colon in the ustar prefix too', () => { expect( refusal(tar([{ prefix: 'x:y', name: 'SKILLS_VERSION', data: 'x' }])), @@ -617,39 +566,6 @@ describe('extractTar', () => { expect(message).toContain(at('SKILLS_VERSION')); }); - // PHARN-17: a name a terminal would interpret is refused before any other - // rule, so it is neither installed nor echoed raw by a refusal message. - // Names are latin1 in the header, so a UTF-8 U+202E is written as its bytes. - it.each([ - ['an ESC sequence in the root', { name: `d${ESC}[2K\r/SKILLS_VERSION` }], - [ - 'a right-to-left override', - { name: utf8AsLatin1('evil\u202egnp/SKILLS_VERSION') }, - ], - [ - 'a zero-width space', - { name: utf8AsLatin1('se\u200bcurity/SKILLS_VERSION') }, - ], - [ - 'a control byte in the ustar prefix', - { name: 'SKILLS_VERSION', prefix: `d${ESC}x` }, - ], - [ - 'a line separator (U+2028)', - { name: utf8AsLatin1('a\u2028b/SKILLS_VERSION') }, - ], - ])('refuses %s, naming it without the raw character', (_label, entry) => { - const dest = fresh(); - const message = refusal( - tar([GLOBAL_HEADER, { ...entry, data: 'x' }]), - opts(), - dest, - ); - expect(message).toMatch(/control or format character/); - expect(hasUnsafeChars(message)).toBe(false); - expect(treeOf(dest)).toEqual([]); - }); - // A decoder's DEFAULT drops a leading byte-order mark: the name would be // written under a different name than the archive holds instead of refused. it('refuses a name field that starts with a byte-order mark, never strips it', () => { @@ -684,29 +600,193 @@ describe('extractTar', () => { expect(message).not.toContain(ESC); }); + it('refuses invalid UTF-8 in the ustar prefix too', () => { + expect( + refusal(tar([{ name: 'SKILLS_VERSION', prefix: 'd\x9b', data: 'x' }])), + ).toMatch(/not valid UTF-8/); + }); +}); + +// The rules a SELECTED entry is held to, over the base fixtures: `LIMITS` +// selects each path these cases use (as latin1 keys, byte for byte), so every +// entry below is judged exactly as before CORE-386. +describe('extractTar', () => { + const onDisk = (dir: string): Buffer[] => + readdirSync(dir, { encoding: 'buffer' }); + it.each([ - ['a raw C1 byte', 'pharn-oss-\x9b2J/SKILLS_VERSION'], - ['a truncated UTF-8 sequence', 'bad-\xe2\x80/SKILLS_VERSION'], - ['an overlong encoding', 'slash-\xc0\xaf/SKILLS_VERSION'], + ['path=', paxRecord('path', 'pharn-oss-abc1234/deep/elsewhere.txt')], + ['size=', paxRecord('size', '8589934592')], + ['only benign metadata', paxRecord('mtime', '1700000000.0')], + ['an unparseable payload', '7 comment=xyz\n'], + ['an empty payload', ''], + ])( + 'refuses a pax extended header carrying %s, on its typeflag alone', + (_label, data) => { + expect(() => + extractTar( + githubArchive([ + { name: 'pharn-oss-abc1234/PaxHeaders/f.txt', type: 'x', data }, + { name: 'pharn-oss-abc1234/f.txt', data: 'x' }, + ]), + tmp.path(), + LIMITS, + ), + ).toThrow(/pax extended or GNU long-name header/); + }, + ); + + it.each([ + ['a `..` segment', 'pharn-oss-abc1234/../escape.txt'], + ['a deeper `..` segment', 'pharn-oss-abc1234/nested/../../escape.txt'], + ])('rejects %s', (_label, name) => { + expect(() => + extractTar(githubArchive([{ name, data: 'x' }]), tmp.path(), LIMITS), + ).toThrow(TarExtractError); + }); + + it.each([ + ['a symlink', '2'], + ['a hardlink', '1'], + ['a character device', '3'], + ['a block device', '4'], + ['a fifo', '6'], + ['a pax extended header', 'x'], + // GNU's long-name typeflags are the other way a writer escapes ustar's + // 100-byte name field. They need no branch of their own — they are neither + // '0'/NUL nor '5', so they land in this reject — but they are pinned HERE + // so a future refactor of the bucket cannot start accepting them quietly. + ['a GNU long name', 'L'], + ['a GNU long link name', 'K'], + ['an unknown type', '9'], + ['a directory', '5'], + ['a pax global header', 'g'], + ])('rejects %s entry outright, rather than skipping it', (_label, type) => { + // At a selected path only (`link` is in LIMITS.select): outside the + // selection the same entry is skipped (see the block above). + expect(() => + extractTar( + githubArchive([{ name: 'pharn-oss-abc1234/link', type }]), + tmp.path(), + LIMITS, + ), + ).toThrow(/unsupported type/); + }); + + it.each([ + [ + 'an ESC sequence in the name', + { name: `pharn-oss-abc1234/n${ESC}[2K\r${ESC}[32mOK` }, + ], + [ + 'a right-to-left override', + { name: utf8AsLatin1('pharn-oss-abc1234/evil\u202egnp.md') }, + ], + [ + 'a zero-width space', + { name: utf8AsLatin1('pharn-oss-abc1234/se\u200bcurity.md') }, + ], + [ + 'a control byte in the ustar prefix', + { name: 'f.md', prefix: `pharn-oss-abc1234/d${ESC}x` }, + ], + // CORE-170: the one unsafe set now holds the two line separators too. + [ + 'a line separator (U+2028)', + { name: utf8AsLatin1('pharn-oss-abc1234/a\u2028b.md') }, + ], + ])('refuses %s, naming it without the raw character', (_label, entry) => { + let message = ''; + try { + extractTar(githubArchive([entry]), tmp.path(), LIMITS); + } catch (err) { + expect(err).toBeInstanceOf(TarExtractError); + message = (err as Error).message; + } + expect(message).toMatch(/control or format character/); + expect(hasUnsafeChars(message)).toBe(false); + }); + + it.each([ + ['a raw C1 byte', 'pharn-oss-abc1234/evil-\x9b2J.md'], + ['a truncated UTF-8 sequence', 'pharn-oss-abc1234/bad-\xe2\x80.md'], + ['an overlong encoding of "/"', 'pharn-oss-abc1234/slash-\xc0\xaf.md'], ])( 'refuses a name holding %s — not valid UTF-8 — writing nothing', (_label, name) => { - const dest = fresh(); - const message = refusal( - tar([GLOBAL_HEADER, { name, data: 'x' }]), - opts(), - dest, - ); + const dest = tmp.path(); + let message = ''; + try { + extractTar(githubArchive([{ name, data: 'x' }]), dest, LIMITS); + } catch (err) { + expect(err).toBeInstanceOf(TarExtractError); + message = (err as Error).message; + } expect(message).toMatch(/not valid UTF-8/); expect(hasUnsafeChars(message)).toBe(false); - expect(treeOf(dest)).toEqual([]); + expect(onDisk(dest)).toEqual([]); }, ); - it('refuses invalid UTF-8 in the ustar prefix too', () => { - expect( - refusal(tar([{ name: 'SKILLS_VERSION', prefix: 'd\x9b', data: 'x' }])), - ).toMatch(/not valid UTF-8/); + // A GNU base-256 field sets the high bit of its first byte. No such byte is + // an octal digit, so the non-octal check refuses it: 0x80 directly, and 0xA0 + // because only ASCII space is trimmed (String#trim would strip U+00A0 and + // then read the octal digits behind it as the size). + it.each([ + ['0x80', 0x80], + ['0xa0 (U+00A0 in latin1)', 0xa0], + ['0xff', 0xff], + ])( + 'rejects a size field whose first byte is %s (GNU base-256), never misreading it', + (_label, byte) => { + const bytes = Buffer.concat([ + header({ name: 'pharn-oss-abc1234/', type: '5' }), + header({ + name: 'pharn-oss-abc1234/f.txt', + data: 'x', + forgeSizeByte: byte, + }), + Buffer.alloc(BLOCK), + Buffer.alloc(BLOCK * 2), + ]); + expect(() => extractTar(bytes, tmp.path(), LIMITS)).toThrow( + /non-octal numeric field/, + ); + }, + ); + + // CORE-173: `\` and `:` in an entry name. POSIX writes `a\..\..\evil` as + // ONE literal file name; win32 would read the same bytes as a path. pharn-oss + // ships neither character, so either is refused, naming the entry. + it.each([ + ['a backslash path', 'pharn-oss-abc1234/a\\..\\..\\evil'], + ['a drive letter', 'pharn-oss-abc1234/C:/x'], + ['a colon in a name', 'pharn-oss-abc1234/a:b.md'], + ['a backslash in a directory segment', 'pharn-oss-abc1234/d\\e/f.md'], + ])('refuses %s, writing nothing', (_label, name) => { + const dest = tmp.path(); + let message = ''; + try { + extractTar(githubArchive([{ name, data: 'x' }]), dest, LIMITS); + } catch (err) { + expect(err).toBeInstanceOf(TarExtractError); + message = (err as Error).message; + } + expect(message).toMatch(/backslash or colon/); + expect(message).toContain(name); + expect(readdirSync(dest)).toEqual([]); + }); + + it('rejects a file with no component to strip', () => { + // `loose.txt` is selected: a rootless copy of a listed file is refused, + // not skipped. No preceding root entry, so the strip-1 rule rejects it. + expect(() => + extractTar( + tar([GLOBAL_HEADER, { name: 'loose.txt', data: 'x' }]), + tmp.path(), + LIMITS, + ), + ).toThrow(/no path below the archive root/); }); }); @@ -790,27 +870,6 @@ describe('extractTar', () => { expect(message).not.toContain('\n'); expect(message).toContain('1\\x0a Done'); }); - - // A GNU base-256 field sets the high bit of its first byte. No such byte is - // an octal digit, so the non-octal check refuses it: 0x80 directly, and 0xA0 - // because only ASCII space is trimmed (String#trim would strip U+00A0 and - // then read the octal digits behind it as the size). - it.each([ - ['0x80', 0x80], - ['0xa0 (U+00A0 in latin1)', 0xa0], - ['0xff', 0xff], - ])( - 'rejects a size field whose first byte is %s (GNU base-256), never misreading it', - (_label, byte) => { - const bytes = Buffer.concat([ - header({ name: `${ROOT}/`, type: '5' }), - header({ name: at('f.txt'), data: 'x', forgeSizeByte: byte }), - Buffer.alloc(BLOCK), - Buffer.alloc(BLOCK * 2), - ]); - expect(refusal(bytes)).toMatch(/non-octal numeric field/); - }, - ); }); // Caps. @@ -824,14 +883,14 @@ describe('extractTar', () => { expect(() => extractTar(githubArchive(many), fresh(), { select: new Set(), - limits: { ...LIMITS, maxHeaders: 3 }, + limits: { ...CAPS, maxHeaders: 3 }, }), ).toThrow(/more than 3 headers/); }); it('counts every pax global header toward the entry cap', () => { const empty: EntryInit = { name: 'pax_global_header', type: 'g', data: '' }; - const limits = { ...LIMITS, maxHeaders: 3 }; + const limits = { ...CAPS, maxHeaders: 3 }; expect( refusal(tar([empty, empty, empty, empty]), opts([], limits)), ).toMatch(/more than 3 headers/); @@ -850,7 +909,7 @@ describe('extractTar', () => { const dest = fresh(); const message = refusal( githubArchive([KEEP, { name: at('big.md'), data: 'x'.repeat(600) }]), - opts(['SKILLS_VERSION', 'big.md'], { ...LIMITS, maxWrittenBytes: 100 }), + opts(['SKILLS_VERSION', 'big.md'], { ...CAPS, maxWrittenBytes: 100 }), dest, ); expect(message).toMatch(/exceed 100 bytes/); @@ -862,7 +921,7 @@ describe('extractTar', () => { expect( refusal( githubArchive([{ name: at('pad'), data: 'x'.repeat(4096) }, KEEP]), - opts(['SKILLS_VERSION'], { ...LIMITS, maxScannedBytes: 2048 }), + opts(['SKILLS_VERSION'], { ...CAPS, maxScannedBytes: 2048 }), ), ).toMatch(/decompresses to more than 2048 bytes/); }); @@ -947,15 +1006,20 @@ describe('extractTarGz', () => { }); it('bounds the bytes written by the selected sizes (maxWrittenBytes)', async () => { + // Formerly gunzip's decompressed-size cap: the tar is streamed now, so the + // cap applies to the bytes written, not to the whole repository. await expect( extractTarGz( gzipSync( githubArchive([ - { name: at('SKILLS_VERSION'), data: 'x'.repeat(600) }, + { name: 'pharn-oss-abc1234/big.txt', data: 'x'.repeat(600) }, ]), ), - fresh(), - opts(['SKILLS_VERSION'], { ...LIMITS, maxWrittenBytes: 100 }), + tmp.path(), + { + select: new Set(['big.txt']), + limits: { ...CAPS, maxWrittenBytes: 100 }, + }, ), ).rejects.toThrow(/exceed 100 bytes/); }); @@ -981,7 +1045,7 @@ describe('extractTarGz', () => { extractTarGz( bomb, fresh(), - opts(['SKILLS_VERSION'], { ...LIMITS, maxScannedBytes: 65536 }), + opts(['SKILLS_VERSION'], { ...CAPS, maxScannedBytes: 65536 }), ), ).rejects.toThrow(/decompresses to more than 65536 bytes/); }); @@ -996,7 +1060,7 @@ describe('extractTarGz', () => { ]), ), dest, - opts(['SKILLS_VERSION'], { ...LIMITS, maxWrittenBytes: 4096 }), + opts(['SKILLS_VERSION'], { ...CAPS, maxWrittenBytes: 4096 }), ); expect(treeOf(dest)).toEqual(['SKILLS_VERSION']); }); From ab300d9b18b19bd186fb1186a6689c923f4cf219 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Galarowicz?= Date: Wed, 25 Nov 2026 17:46:46 +0100 Subject: [PATCH 4/8] test(tar-extract): keep the base pax and byte-cap tests' assertions (CORE-386) The refusal of a listed file after a modifier header now names that header's type through describeTypeflag ("unsupported type 'x' (a pax extended header, ...)"), so the base pax test keeps its expected value. The base test "bounds the bytes written by the decompressed size" keeps its name, now over the streamed decompressed cap (maxScannedBytes). Co-Authored-By: Claude Opus 5.5 --- src/lib/tar-extract.ts | 20 ++++++++++---------- tests/repo.test.ts | 4 +++- tests/tar-extract.test.ts | 26 +++++++++++++++++++++++--- 3 files changed, 36 insertions(+), 14 deletions(-) diff --git a/src/lib/tar-extract.ts b/src/lib/tar-extract.ts index 4aeee3e1..c6b7bf74 100644 --- a/src/lib/tar-extract.ts +++ b/src/lib/tar-extract.ts @@ -315,9 +315,9 @@ class TarWalker { private dataLeft = 0; private padLeft = 0; private pending: Pending | null = null; - // The previous header was a modifier ('x', 'L', 'K'), so this one's ustar - // path and size may not be the real ones. - private modified = false; + // The typeflag of the modifier ('x', 'L', 'K') the previous header was, so + // this one's ustar path and size may not be the real ones; `null`: none. + private modifier: string | null = null; private ended = false; constructor( @@ -415,13 +415,13 @@ class TarWalker { ); } const typeflag = String.fromCharCode(block[OFF_TYPEFLAG]!); - const modified = this.modified; + const modifier = this.modifier; // A 'g' modifies nothing, so it neither sets nor consumes the flag. - if (MODIFIERS.has(typeflag)) this.modified = true; - else if (typeflag !== 'g') this.modified = false; + if (MODIFIERS.has(typeflag)) this.modifier = typeflag; + else if (typeflag !== 'g') this.modifier = null; if (isSelected(block, this.options.select)) { - this.accept(block, typeflag, modified, size); + this.accept(block, typeflag, modifier, size); } this.dataLeft = size; this.padLeft = Math.ceil(size / BLOCK) * BLOCK - size; @@ -432,7 +432,7 @@ class TarWalker { private accept( block: Buffer, typeflag: string, - modified: boolean, + modifier: string | null, size: number, ): void { // The FULL path is judged before any other rule, so no later message @@ -446,9 +446,9 @@ class TarWalker { `tar entry has an unsupported type ${describeTypeflag(typeflag)} at a path pharn installs (only a regular file is accepted there): ${fullPath}`, ); } - if (modified) { + if (modifier !== null) { throw new TarExtractError( - `tar entry follows a pax extended or GNU long-name header, whose records pharn does not honour, at a path pharn installs: ${fullPath}`, + `tar entry follows a header of unsupported type ${describeTypeflag(modifier)}, whose records pharn does not honour, at a path pharn installs: ${fullPath}`, ); } const { rel, root } = resolveEntryPath(fullPath, this.root); diff --git a/tests/repo.test.ts b/tests/repo.test.ts index 975e76c2..6f2d9c89 100644 --- a/tests/repo.test.ts +++ b/tests/repo.test.ts @@ -799,7 +799,9 @@ describe('fetchRepo — only the listed paths are unpacked (CORE-386)', () => { ); const err = await fetchRepo(release).catch((e: unknown) => e); expect(err).toBeInstanceOf(TarExtractError); - expect((err as Error).message).toMatch(/pax extended or GNU long-name/); + expect((err as Error).message).toMatch( + /unsupported type 'x'.*pax extended header/, + ); expect(leftoverTempDirs()).toEqual([]); }); diff --git a/tests/tar-extract.test.ts b/tests/tar-extract.test.ts index 23946806..91679d80 100644 --- a/tests/tar-extract.test.ts +++ b/tests/tar-extract.test.ts @@ -508,7 +508,7 @@ describe('extractTar', () => { refusal( githubArchive([{ name: '././@LongLink', type: 'L', data: 'x' }, KEEP]), ), - ).toMatch(/pax extended or GNU long-name header/); + ).toMatch(/whose records pharn does not honour/); }); it('a pax global header between the extended header and the file does not lift the refusal', () => { @@ -520,7 +520,7 @@ describe('extractTar', () => { KEEP, ]), ), - ).toMatch(/pax extended or GNU long-name header/); + ).toMatch(/whose records pharn does not honour/); }); it('rejects an absolute path', () => { @@ -632,7 +632,7 @@ describe('extractTar', () => { tmp.path(), LIMITS, ), - ).toThrow(/pax extended or GNU long-name header/); + ).toThrow(/unsupported type 'x'.*pax extended header/); }, ); @@ -1005,6 +1005,26 @@ describe('extractTarGz', () => { expect((err as Error).message).toMatch(/unsupported type '2'/); }); + // The name is the base test's: the decompressed stream is still capped + // (maxTotalBytes became maxScannedBytes, now counted as the tar streams), and + // no file can be written past that cap. The written-byte cap is the next test. + it('bounds the bytes written by the decompressed size (maxTotalBytes)', async () => { + await expect( + extractTarGz( + gzipSync( + githubArchive([ + { name: 'pharn-oss-abc1234/big.txt', data: 'x'.repeat(600) }, + ]), + ), + tmp.path(), + { + select: new Set(['big.txt']), + limits: { ...CAPS, maxScannedBytes: 100 }, + }, + ), + ).rejects.toThrow(/decompresses to more than 100 bytes/); + }); + it('bounds the bytes written by the selected sizes (maxWrittenBytes)', async () => { // Formerly gunzip's decompressed-size cap: the tar is streamed now, so the // cap applies to the bytes written, not to the whole repository. From 6bda86d40911811a733a73edf07733fa66e6e093 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Galarowicz?= Date: Wed, 25 Nov 2026 17:48:16 +0100 Subject: [PATCH 5/8] feat: pharn verify-archive checks a local pharn-oss archive as an install would (CORE-387) A new read-only command for pharn-oss CI: it runs the install path's own extractPharnArchive (both passes, manifest validation, every listed sha256) over a local .tar.gz, plus the capability-index build and a MIN_CLI validity check, with no network, no project and no lock, in one private temp dir that verifyLocalArchive (repo.ts) always removes. --expect-version X.Y.Z holds SKILLS_VERSION to a version through assertSkillsVersion, the helper the release check in fetchAt now shares. The input is read bounded (regular file, 32 MiB, no FIFO hang). The archive needs one top-level directory (git archive --prefix=pharn-oss/); a rootless one gets a message naming it. Version 0.22.0. Co-Authored-By: Claude Opus 5.5 --- .../features/core-387-verify-archive/GRILL.md | 45 +++ .dev/features/core-387-verify-archive/PLAN.md | 163 ++++++++++ AGENTS.md | 9 +- CHANGELOG.md | 9 +- CLAUDE.md | 9 +- README.md | 23 +- docs/README.md | 1 + docs/architecture.md | 12 + docs/commands/verify-archive.md | 119 ++++++++ docs/contributing.md | 3 +- docs/troubleshooting.md | 37 ++- package-lock.json | 4 +- package.json | 2 +- src/commands/verify-archive.ts | 141 +++++++++ src/index.ts | 5 + src/lib/cli-args.ts | 59 +++- src/lib/repo.ts | 42 ++- src/lib/skills-version.ts | 15 + tests/cli-args.test.ts | 82 ++++++ tests/commands/verify-archive.test.ts | 278 ++++++++++++++++++ tests/dist-smoke.test.ts | 22 +- tests/index.test.ts | 7 + tests/repo.test.ts | 75 ++++- tests/skills-version.test.ts | 26 ++ tests/support/tar-fixture.ts | 45 ++- 25 files changed, 1171 insertions(+), 62 deletions(-) create mode 100644 .dev/features/core-387-verify-archive/GRILL.md create mode 100644 .dev/features/core-387-verify-archive/PLAN.md create mode 100644 docs/commands/verify-archive.md create mode 100644 src/commands/verify-archive.ts create mode 100644 tests/commands/verify-archive.test.ts diff --git a/.dev/features/core-387-verify-archive/GRILL.md b/.dev/features/core-387-verify-archive/GRILL.md new file mode 100644 index 00000000..3b589892 --- /dev/null +++ b/.dev/features/core-387-verify-archive/GRILL.md @@ -0,0 +1,45 @@ +# GRILL — core-387-verify-archive + +Advisory: `/pharn-dev-grill` gates nothing. Spec hash recomputed as `bca940a5…3c4e`, equal to the plan's. Registered +grillers: 0 (`count-grillers.mjs`), so only the built-in axes were applied. + +```yaml +- type: FINDING + rule_id: P0 + severity: important + file: 'PLAN.md:Guarantee audit' + problem: '"A pass means an install would accept these bytes" holds only for the checks the command shares with install; the MIN_CLI comparison and the project-side steps are not run.' + evidence: 'Docs must list the differences (MIN_CLI is checked for validity only and refused where install would warn; there is no version comparison, no archetype selection and no destination checks) so CI readers do not over-read a pass.' +- type: FINDING + rule_id: P2 + severity: important + file: 'PLAN.md:Decisions 7' + problem: 'The user path reaches three messages (the input error, the refusal prefix, the summary); each must be escaped at its own interpolation, not as a whole line.' + evidence: 'CLAUDE.md "One unsafe-character set": value by value. Test it with a control character in the file name.' +- type: FINDING + rule_id: P1 + severity: important + file: 'PLAN.md:Files (tests)' + problem: 'A non-gzip input and an empty input take different routes (the input check for empty, and TarExtractError "could not decompress the fetched archive" for garbage); the second says "fetched" for a local file.' + evidence: 'Test both. The "fetched" wording lives in tar-extract.ts (a 386 file); it is left alone and accepted as the extractor message, prefixed by "Archive refused:".' +- type: FINDING + rule_id: P5 + severity: minor + file: 'PLAN.md:Decisions 1' + problem: 'The rootless check is "pass 1 wrote no pharn-install.json", which also fires for a rooted archive without a manifest (pre-7.21.0) and for a deeper prefix such as a/b/.' + evidence: 'Word the message to cover both: "holds no pharn-install.json under a single top-level directory", naming the --prefix line and the 7.21.0 floor. A membership test with an honest message, not a guess about which cause it is.' +- type: FINDING + rule_id: P1 + severity: minor + file: 'PLAN.md:GATE 1 amendments 1' + problem: 'The unknown-capability warning path and the malformed-MIN_CLI refusal need cases of their own.' + evidence: 'Add a manifest edit with an unknown applies token (passes, warns on stderr) and MIN_CLI "not-a-version" (refused, reason named).' +- type: FINDING + rule_id: P7 + severity: minor + file: 'PLAN.md:Files (tar-fixture)' + problem: 'Extending the shared tar fixture changes a file every command suite uses.' + evidence: 'Keep the opts argument optional and part of the memo key, so existing callers produce identical bytes.' +``` + +Verdict: proceed (advisory). All six are folded into the build. diff --git a/.dev/features/core-387-verify-archive/PLAN.md b/.dev/features/core-387-verify-archive/PLAN.md new file mode 100644 index 00000000..6f6b61ee --- /dev/null +++ b/.dev/features/core-387-verify-archive/PLAN.md @@ -0,0 +1,163 @@ +# PLAN — core-387-verify-archive (Linear CORE-387, epic CORE-380) + +- spec_content_hash: bca940a5ad247c120e6d8a3acba119d0d8df51dca275964d0e54c48d729d3c4e # fix #4 +- increment: a new read-only command `pharn verify-archive [--expect-version X.Y.Z]` that runs the + install path's own `extractPharnArchive` (both passes, manifest validation, every listed file's sha256) over a LOCAL + archive, with no network, no project, no lock, into one private temp dir it always removes; exit 0 with a short + summary, exit 1 naming the entry and rule. +- base: `origin/feat/core-386-unpack-listed-paths-only` @ ecd7422f (CORE-386, PR #448; stacked, merged forward with + `git merge`, never rebased). Branch `feat/core-387-verify-archive`. +- layer(s): CLI source (`src/commands/verify-archive.ts` new, `src/lib/cli-args.ts`, `src/index.ts`, + `src/lib/repo.ts`, `src/lib/skills-version.ts`), tests, docs. No trusted doc changes; no protected file. +- version: 0.22.0 (minor: a new command) + a CHANGELOG `[0.22.0]` section. +- constitution_refs: [P0, P2, P3, P4, P5, P7] + +## Why + +pharn-oss v7.25.3–v7.25.5 shipped archives no pharn could install, and nothing in pharn-oss CI could tell before the +tag. CORE-386 made the extractor take a buffer (`extractPharnArchive(archive, dir, checkTree?)`) precisely so a local +file can go through the exact walk a download does. This increment exposes it as a command pharn-oss CI can run on a +`git archive` of the commit about to be tagged. + +## Decisions + +1. **Root directory: REQUIRED (no rootless mode). The documented pharn-oss CI command is** + `git archive --prefix=pharn-oss/ --format=tar.gz -o pharn-oss.tar.gz HEAD`. + Why: the 386 extractor's selection key strips everything up to the first `/` (codeload's `pharn-oss-/`), and + its path rules require one shared root. A plain `git archive HEAD` has top-level entries (`pharn-install.json` + has no `/`, so it is never selected, and `.claude/settings.json` keys as `settings.json`). Accepting that would + need a second path-selection branch in the security-sensitive extractor that the install path never takes, so a + pass would no longer prove "the install would accept these bytes" — the point of the command. `--prefix` makes + the local archive codeload-shaped (pax global header, one root dir, same tar writer: codeload is `git archive`), + so the exact install walk runs. The install path's rules are untouched. + A rootless archive (or any archive without a manifest under one root) fails with a verify-specific message that + names the `--prefix` command, instead of the install path's "older than 7.21.0" text: the command's `checkTree` + (which `extractPharnArchive` runs after pass 1, before the manifest parse) checks that pass 1 wrote + `pharn-install.json`. The Done-when line "a git archive --format=tar.gz HEAD of pharn-oss main" is satisfied by + that line plus `--prefix=pharn-oss/`; the docs and the PR say so plainly. +2. **Option `--expect-version `** (verify-archive only, value option, repeated → refused by the existing + rule). VERSION_RE-validated in `parseCliArgs` (bad value → `Invalid value for --expect-version …`, exit 1, before + anything runs). When given, the tree's SKILLS_VERSION must equal it — the release check `fetchAt` runs for a + release, at the same point (after pass 1, before the manifest parse). No leading `v` is accepted (strict; docs show + `${TAG#v}`). +3. **Shared helper, not a copy:** `skills-version.ts` gains `assertSkillsVersion(repoDir, expected, refusal)` + (reads with `readSkillsVersion`, throws `ManifestValidationError(refusal(found))` on a mismatch). `fetchAt` + calls it with its current message (byte-identical), the command with its own. +4. **No `--json`** (P7): pharn-oss CI gates on the exit code; the one-line summary and the stderr reason are enough. + Recorded as a possible follow-up, not built. +5. **Temp dir lifecycle lives in `repo.ts`** (`verifyLocalArchive(archive, checkTree)`): `mkdtemp` is banned outside + repo.ts/tar-extract.ts by the clone-producer eslint rule, and repo.ts owns the exit/fatal-signal cleanup registry + (`liveClones` + `installCleanupHandlers`). It creates `pharn-verify-*`, registers it, calls + `extractPharnArchive`, and removes + deregisters it in a `finally` (pass and fail). The tree is never returned. +6. **Input read:** `readBoundedFile(path, MAX_ARCHIVE_BYTES)` (bounded-read.ts unchanged: `O_NONBLOCK`, fstat + regular-file, cap, read-to-EOF-under-cap). `MAX_ARCHIVE_BYTES` (32 MiB, the download cap) is exported from + repo.ts. A symlinked input file is followed (the user's own file), as for the config. +7. **Output and errors** (all through `CliError`, exit 1; the path printed via `escapeUnsafe`, and `logError`'s + strip on top): + - missing/unreadable/not-a-file/too-large/empty input → `CliError.error` (a precondition the user fixes; one line): + `Cannot verify : it does not exist.` / `… is not a regular file` / `… is larger than 32 MiB`. + - archive refusal (`TarExtractError`, `ManifestValidationError` incl. `UpstreamManifestError`, and the + expect-version mismatch) → `CliError.failure(err, { message: 'Archive refused: ' })`, so + PHARN_DEBUG=1 dumps the original error as every fetching command does; without it, the one PHARN_DEBUG hint. + - anything else (an fs error writing the temp tree) → `CliError.failure(err)` likewise. + - pass → clack `intro('pharn verify-archive')`, `log.success(': files listed in pharn-install.json, all + present and matching their sha256; SKILLS_VERSION ')` (+ `, as expected` with the option), `outro` dim + "Nothing was installed; the temporary directory was removed." Ref-free (no tag/sha claims). +8. **No Node-floor gate, no MIN_CLI gate, no lock, no proxy notice**: nothing is installed and nothing fetched. + +## Files + +- `src/commands/verify-archive.ts` — NEW: `runVerifyArchive({ file, expectVersion })`: bounded read, the checkTree + (manifest present → else the `--prefix` refusal; then `assertSkillsVersion` when asked), `verifyLocalArchive`, + summary/errors. Imports only lib/ (P3). +- `src/lib/repo.ts` — export `MAX_ARCHIVE_BYTES`; new exported `verifyLocalArchive(archive, checkTree)`; `fetchAt`'s + release check calls `assertSkillsVersion` (same message). +- `src/lib/skills-version.ts` — `assertSkillsVersion(repoDir, expected, refusal)`. +- `src/lib/cli-args.ts` — `verify-archive` in COMMANDS (`args: ''`, a summary and page text); + `expect-version` in OPTIONS (`uses: verify-archive`); `Invocation` variant; parse: the positional is required + (`verify-archive needs the path of a .tar.gz archive`, refused), VERSION_RE check. +- `src/index.ts` — dispatch case (dynamic import, as the others). +- `tests/commands/verify-archive.test.ts` — NEW, via `useHarness` + tar-fixture: pass on a good archive; pass with an + unlisted symlink, hard link and pax header (the v7.25.5 shape) and nothing of them left anywhere; fail naming the + entry for a listed file whose bytes differ from its sha256; a symlink at a listed path (`unsupported type '2'` + + path); no manifest (and the rootless archive) → the `--prefix` message; `--expect-version` match and mismatch; + input that is a directory, a FIFO (`execFileSync('mkfifo')`, the pattern tests/bounded-read.test.ts already uses; + POSIX-only, skipped on win32), oversize (sparse file via `truncateSync` over 32 MiB), empty, nonexistent; + path with a control character printed escaped; `fetchStub` never called in any case; the temp dir (TMPDIR pointed + at a watched dir via `watchClones`) empty after pass and after fail; PHARN_DEBUG=1 prints the original error. +- `tests/support/tar-fixture.ts` — `codeloadArchive` gains an optional third `opts` (`extra` raw entries spliced after + the root dir, `replace` raw entries for a listed path, `rootless: true`), memo key includes opts; existing callers + unchanged. +- `tests/cli-args.test.ts` — new cases: the command parses with its positional; missing positional refused; extra + positional refused; `--expect-version` valid / invalid / repeated / on another command refused; help text bodies + updated where they assert the full usage (no title renamed or removed). +- `tests/index.test.ts` — dispatch case for verify-archive (mock + loaded chunk), added, none renamed. +- `tests/skills-version.test.ts` — `assertSkillsVersion` match/mismatch/missing. +- `tests/repo.test.ts` — `verifyLocalArchive`: removes its dir on pass and on refusal; never fetches. +- `tests/dist-smoke.test.ts` — the bundle runs `verify-archive` on a fixture archive (exit 0) and on a missing file + (exit 1), and `--help` lists it (body of the existing help case if it enumerates commands). +- `docs/commands/verify-archive.md` — NEW, matching the other command pages: usage, options, behavior, exit codes, + messages, and "For pharn-oss CI" with the exact lines: + `git archive --prefix=pharn-oss/ --format=tar.gz -o "$RUNNER_TEMP/pharn-oss.tar.gz" HEAD` and + `npx --yes @pharn-dev/pharn@0.22.0 verify-archive "$RUNNER_TEMP/pharn-oss.tar.gz" --expect-version "$(cat SKILLS_VERSION)"`. +- `docs/README.md` — the command list gains verify-archive. +- `README.md` — the command list gains verify-archive. +- `docs/troubleshooting.md` — exit-code table row + "verify-archive says the archive has no root directory". +- `docs/architecture.md` — one short flow entry for verify-archive. +- `docs/contributing.md` — module tree line + test-map row. +- `AGENTS.md` — the CLAUDE.md mirror, same edits. +- `CLAUDE.md` — command list, module map (`commands/verify-archive`), test-suite list (minimal). +- `package-lock.json` — 0.22.0. +- `package.json` — 0.22.0 (`npm version --no-git-tag-version 0.22.0`). +- `CHANGELOG.md` — `## [0.22.0]` with an `Added` entry (the 386 `[Unreleased]`/0.21.6 section untouched). +- `.dev/features/core-387-verify-archive/SHIP.md` — stage artifact (each stage scopes its own artifacts). + +## Evals / tests (P1) + +The command suite above is the eval: each refusal asserted by exit code 1 and the named entry/rule on stderr; each +pass by exit code null/0 and the summary; the no-network property by `fetchStub` call count 0; the cleanup property +by an empty watched TMPDIR. + +## Guarantee audit (P0) + +- "verify-archive runs the same checks as an install" → floor: it calls the one `extractPharnArchive` (no copy); + differences named: no MIN_CLI gate, no capability-index parse, no Node floor (docs say so). +- "no network" → test (fetch stub never called); structurally the command imports no fetch module. +- "no write outside one temp dir, always removed" → `finally` in `verifyLocalArchive` + the exit/fatal-signal + registry; tested on pass and fail. SIGKILL residual: same as fetchRepo's (named, LIMITS-level, unchanged). +- "bounded input read, no FIFO hang" → `readBoundedFile` (existing floor, existing tests). +- "a pass on a `--prefix` git archive means codeload's archive of that commit passes" → advisory: same tar writer + (git archive), but codeload could differ (e.g. export-subst); the v7.25.5 live check covers the real codeload shape. + +## Trust audit (P2) + +The archive and its path are untrusted. The path is escaped (`escapeUnsafe`) where printed; archive-derived text +reaches messages only through the extractor's/manifest's own escaping plus `logError`'s strip. Nothing from the +archive is executed; the tree is deleted before the command returns. + +## Risks + +- FIFO test: resolved — tests already create FIFOs with `execFileSync('mkfifo')` (bounded-read, detect-archetype). +- Help-text assertions in cli-args / dist-smoke tests change bodies (never titles; TI01/TI02). +- 386 branch moving: merged forward before commit and before the PR. +- Large sparse oversize file on tmpfs: `truncateSync` makes it sparse, cheap. + +## Open questions (HALT) + +None blocking; GATE 1 is the lead's. + +## GATE 1 amendments (lead decision under the user's delegation, 2026-11-25) + +Approved as written, plus: + +1. **The install's other two pure reads run too.** In the checkTree after pass 1, `readMinCli(dir)` (the reader the + min-cli gate uses) checks MIN_CLI's validity only: absent passes, and a present-but-malformed or unreadable file is + a refusal naming its reason. This is stricter than install, which warns, on purpose: for a release a broken + handshake is a packaging bug. No comparison is made against this CLI's version. After the extract, + `manifestCapabilityIndex(manifest)` (the pure function behind `parseCapabilityIndex`) builds the capability index. + Capabilities it reports as `unknown` are printed with the shared `unknownCapabilitiesWarning` and the command still + passes, because install installs past them (it skips them with a warning). The summary gives the capability count + and MIN_CLI. Neither read touches the network or a prompt. +2. **The docs' CI section** shows a SKILLS_VERSION form for PR/push jobs and a tag form for release jobs + (`--expect-version "${TAG#v}"`), and says the archive must be built from the same commit that will be tagged. +3. **The PR body** carries the exact pharn-oss CI snippet, for CORE-384. diff --git a/AGENTS.md b/AGENTS.md index fd93b89f..d21c0d6f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -9,7 +9,8 @@ Guidance for Codex in this repository. Flows: [`docs/architecture.md`](docs/arch (by default the newest verified release; `--ref main` takes the tip of `main`), copies the selected capabilities (grillers and lenses) and the fixed product surfaces into `.Codex/` and `pharn/`, and writes pharn.config.json and pharn.records.json in that project. It is published on npm as `@pharn-dev/pharn` with one bin, `pharn`. Every command is -archetype-only: a pre-archetype (module) config is refused with "re-run `pharn init`". It targets Codex today. +archetype-only: a pre-archetype (module) config is refused with "re-run `pharn init`". `verify-archive` reads no project: +it runs the install checks over a local pharn-oss archive, for pharn-oss CI. It targets Codex today. ## Commands @@ -100,7 +101,7 @@ PHARN_DEBUG=1 npm run dev -- init # full error output for fetch/install failur own archive, extracted-size and entry caps. - **The project lock.** `init`/`add`/`update`/`remove`/`uninstall` take `pharn/.lock` before reading the config, hold it across every prompt and plan once; edits made meanwhile are caught at write time (hash, fingerprint, walk). Dry - runs and readers (`list`, `status`) never take it. + runs and readers (`list`, `status`, `verify-archive`) never take it. - **Bounded local reads.** pharn.config.json, pharn.records.json and the lock are read through `readBoundedFile` (regular file, size cap, `O_NONBLOCK`), so a FIFO or a huge file never hangs or floods a command. - **Config schema is additive within the support window** (P7): new keys are optional, and a legacy field loads @@ -115,7 +116,7 @@ PHARN_DEBUG=1 npm run dev -- init # full error output for fetch/install failur ## Module map - `src/index.ts`: dispatch only. `lib/cli-args.ts`: the command/option tables, help text and the argv parse (`init` default). -- `commands/`: one verb each (`init`, `add`, `remove`/`rm`, `update`, `list`, `status`, `uninstall`). +- `commands/`: one verb each (`init`, `add`, `remove`/`rm`, `update`, `list`, `status`, `uninstall`, `verify-archive`). - `steps/`: init stages (`node-prereq`, `prereqs`, `archetype-summary`, `overwrite-check`, `install-archetype`), `add-picker`. - Fetch boundary: `fetch-capped` (the one bounded GET), `release` (which commit), `repo` + `tar-extract`, `skills-version`, `min-cli-gate`, `upstream-manifest` (the upstream install manifest's one parser), `capability-index` (manifest → @@ -137,7 +138,7 @@ PHARN_DEBUG=1 npm run dev -- init # full error output for fetch/install failur ## Testing - Vitest, node env. Lib tests are `tests/*.test.ts`; command suites are `tests/commands/` (`init`, `init-dry-run`, `add`, - `remove`, `update`, `update-dry-run`, `status`, `list`, `uninstall`, `lock`, `clone-cleanup`, `older-cli`). Update the test first. + `remove`, `update`, `update-dry-run`, `status`, `list`, `uninstall`, `verify-archive`, `lock`, `clone-cleanup`, `older-cli`). Update the test first. - A command suite runs the real `run()` on a temp project via `tests/support/harness.ts`. Only two boundaries are replaced: global `fetch`, which serves a real codeload tarball (`tests/support/tar-fixture.ts`), and `@clack/prompts` (`tests/support/clack-stub.ts`), where an unscripted prompt throws. diff --git a/CHANGELOG.md b/CHANGELOG.md index 68d0681b..689cb6b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 Releases 0.4.0 and older are in [CHANGELOG-ARCHIVE.md](CHANGELOG-ARCHIVE.md). +## [0.22.0] — 2026-11-25 + +### Added + +- **`pharn verify-archive ` checks a local pharn-oss `.tar.gz` the way an install checks a download, with no network.** It is for pharn-oss CI, which can now find out that a commit would install before it tags that commit as a release. It runs the install's own steps on the file: both extraction passes, the `pharn-install.json` validation, the sha256 of every listed file and the capability index. With `--expect-version X.Y.Z`, the archive's `SKILLS_VERSION` must also equal that version, as a release install requires of its tag. A `MIN_CLI` that is present but not a valid version fails the check, where an install would warn and carry on. The command needs no project and takes no lock. It reads the file only if it is a regular file of at most 32 MiB, and it removes its one temporary directory whether the check passes or fails. It exits 0 with a one-line summary, or 1 with the reason, which names the entry and the rule. The archive must have one top-level directory, as GitHub's do, so build it with `git archive --prefix=pharn-oss/ --format=tar.gz -o pharn-oss.tar.gz HEAD`. See [`docs/commands/verify-archive.md`](docs/commands/verify-archive.md) for the pharn-oss CI lines. + ## [Unreleased] ### Fixed @@ -527,7 +533,8 @@ _Never released: 0.9.0 followed on the same day, so `0.8.0` was neither tagged n matcher that silently stopped matching, or a comparator read in the wrong direction, would otherwise leave every assertion green. -[Unreleased]: https://github.com/pharn-dev/pharn-cli/compare/v0.21.5...HEAD +[Unreleased]: https://github.com/pharn-dev/pharn-cli/compare/v0.22.0...HEAD +[0.22.0]: https://github.com/pharn-dev/pharn-cli/compare/v0.21.5...v0.22.0 [0.21.5]: https://github.com/pharn-dev/pharn-cli/compare/v0.21.4...v0.21.5 [0.21.4]: https://github.com/pharn-dev/pharn-cli/compare/v0.21.3...v0.21.4 [0.21.3]: https://github.com/pharn-dev/pharn-cli/compare/v0.21.2...v0.21.3 diff --git a/CLAUDE.md b/CLAUDE.md index f5c75475..36399137 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -9,7 +9,8 @@ Guidance for Claude Code in this repository. Flows: [`docs/architecture.md`](doc (by default the newest verified release; `--ref main` takes the tip of `main`), copies the selected capabilities (grillers and lenses) and the fixed product surfaces into `.claude/` and `pharn/`, and writes pharn.config.json and pharn.records.json in that project. It is published on npm as `@pharn-dev/pharn` with one bin, `pharn`. Every command is -archetype-only: a pre-archetype (module) config is refused with "re-run `pharn init`". It targets Claude Code today. +archetype-only: a pre-archetype (module) config is refused with "re-run `pharn init`". `verify-archive` reads no project: +it runs the install checks over a local pharn-oss archive, for pharn-oss CI. It targets Claude Code today. ## Commands @@ -104,7 +105,7 @@ PHARN_DEBUG=1 npm run dev -- init # full error output for fetch/install failur own archive, headers-scanned, decompressed-bytes-scanned and bytes-written caps. - **The project lock.** `init`/`add`/`update`/`remove`/`uninstall` take `pharn/.lock` before reading the config, hold it across every prompt and plan once; edits made meanwhile are caught at write time (hash, fingerprint, walk). Dry - runs and readers (`list`, `status`) never take it. + runs and readers (`list`, `status`, `verify-archive`) never take it. - **Bounded local reads.** pharn.config.json, pharn.records.json and the lock are read through `readBoundedFile` (regular file, size cap, `O_NONBLOCK`), so a FIFO or a huge file never hangs or floods a command. - **Config schema is additive within the support window** (P7): new keys are optional, and a legacy field loads @@ -119,7 +120,7 @@ PHARN_DEBUG=1 npm run dev -- init # full error output for fetch/install failur ## Module map - `src/index.ts`: dispatch only. `lib/cli-args.ts`: the command/option tables, help text and the argv parse (`init` default). -- `commands/`: one verb each (`init`, `add`, `remove`/`rm`, `update`, `list`, `status`, `uninstall`). +- `commands/`: one verb each (`init`, `add`, `remove`/`rm`, `update`, `list`, `status`, `uninstall`, `verify-archive`). - `steps/`: init stages (`node-prereq`, `prereqs`, `archetype-summary`, `overwrite-check`, `install-archetype`), `add-picker`. - Fetch boundary: `fetch-capped` (the one bounded GET), `release` (which commit), `repo` + `tar-extract`, `skills-version`, `min-cli-gate`, `upstream-manifest` (the upstream install manifest's one parser), `capability-index` (manifest → @@ -144,7 +145,7 @@ PHARN_DEBUG=1 npm run dev -- init # full error output for fetch/install failur ## Testing - Vitest, node env. Lib tests are `tests/*.test.ts`; command suites are `tests/commands/` (`init`, `init-dry-run`, `add`, - `remove`, `update`, `update-dry-run`, `update-interrupted`, `status`, `list`, `uninstall`, `lock`, `clone-cleanup`, `older-cli`). Update the test first. + `remove`, `update`, `update-dry-run`, `update-interrupted`, `status`, `list`, `uninstall`, `verify-archive`, `lock`, `clone-cleanup`, `older-cli`). Update the test first. - A command suite runs the real `run()` on a temp project via `tests/support/harness.ts`. Only two boundaries are replaced: global `fetch`, which serves a real codeload tarball (`tests/support/tar-fixture.ts`), and `@clack/prompts` (`tests/support/clack-stub.ts`), where an unscripted prompt throws. diff --git a/README.md b/README.md index b7bcefb8..89297dd5 100644 --- a/README.md +++ b/README.md @@ -138,17 +138,18 @@ commits a green result to a new local branch (never pushed or merged), leaving t ## CLI commands -| Command | Description | -| --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `pharn init` | Detect archetypes and install matching capabilities. This is also the default when no command is given. `--dry-run` prints what it would install and writes nothing (add `--json` for one machine-readable object); `--yes`/`-y` installs without prompts, but only when no file would be overwritten. | -| `pharn add [capability]` | Add one capability manually, for example `a11y` or `lens:n-plus-one`. With no argument, opens an interactive picker. | -| `pharn remove [capability]` | Remove one installed capability. With no argument, opens an interactive picker. | -| `pharn update` | Re-fetch and apply the latest PHARN content using drift-safe per-file decisions. `--force` overwrites files you changed; `--yes`/`-y` skips the confirmation prompt; `--dry-run` prints what it would do and writes nothing (add `--json` for the plan as one machine-readable object, and `--compact` to leave the unchanged files out of it). | -| `pharn list` | Show installed archetypes and capabilities. Use `--json` for machine-readable output. | -| `pharn status` | Read-only version and drift report. Use `--strict` to make drift fail CI, `--no-drift` to skip byte comparison, or `--json` for one machine-readable report. | -| `pharn uninstall` | Remove PHARN: deletes only the files `pharn` recorded and you did not change, then `pharn.records.json` and `pharn.config.json` (backed up first). Never touches `pharn/.backup/` or a `.claude/settings.json` it did not create. `--yes`/`-y` skips the confirmation prompt. | -| `pharn --help` | Show every command, option and environment variable. `pharn --help` shows one command and only the options it takes. | -| `pharn --version` | Show the installed CLI version. | +| Command | Description | +| ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `pharn init` | Detect archetypes and install matching capabilities. This is also the default when no command is given. `--dry-run` prints what it would install and writes nothing (add `--json` for one machine-readable object); `--yes`/`-y` installs without prompts, but only when no file would be overwritten. | +| `pharn add [capability]` | Add one capability manually, for example `a11y` or `lens:n-plus-one`. With no argument, opens an interactive picker. | +| `pharn remove [capability]` | Remove one installed capability. With no argument, opens an interactive picker. | +| `pharn update` | Re-fetch and apply the latest PHARN content using drift-safe per-file decisions. `--force` overwrites files you changed; `--yes`/`-y` skips the confirmation prompt; `--dry-run` prints what it would do and writes nothing (add `--json` for the plan as one machine-readable object, and `--compact` to leave the unchanged files out of it). | +| `pharn list` | Show installed archetypes and capabilities. Use `--json` for machine-readable output. | +| `pharn status` | Read-only version and drift report. Use `--strict` to make drift fail CI, `--no-drift` to skip byte comparison, or `--json` for one machine-readable report. | +| `pharn uninstall` | Remove PHARN: deletes only the files `pharn` recorded and you did not change, then `pharn.records.json` and `pharn.config.json` (backed up first). Never touches `pharn/.backup/` or a `.claude/settings.json` it did not create. `--yes`/`-y` skips the confirmation prompt. | +| `pharn verify-archive ` | Check a local pharn-oss `.tar.gz` the way an install checks a download, with no network (for pharn-oss CI; [details](docs/commands/verify-archive.md)). `--expect-version X.Y.Z` also checks `SKILLS_VERSION`. | +| `pharn --help` | Show every command, option and environment variable. `pharn --help` shows one command and only the options it takes. | +| `pharn --version` | Show the installed CLI version. | `init` also takes `--archetype ` (for example `--archetype ssr,backend`) to install for those archetypes instead of the detected ones; the choice is recorded, so `update` keeps it. `init --ref main` diff --git a/docs/README.md b/docs/README.md index 9dc592f0..67b3412b 100644 --- a/docs/README.md +++ b/docs/README.md @@ -19,6 +19,7 @@ The CLI version (`pharn --version`) and the content version it installs (`skills - [update](commands/update.md) — re-fetch installed capabilities at the latest skills version - [list](commands/list.md) — list installed archetypes + capabilities - [status](commands/status.md) — read-only version + local-drift check; `--strict` exits 1 on an outdated install, a modified, missing or unreadable file, a surface upstream no longer ships, or an unwired hook ([the full list](commands/status.md#strict-conditions)), and neither `status` nor `list` is ever blocked by another `pharn` run's lock +- [verify-archive](commands/verify-archive.md) — check a local pharn-oss `.tar.gz` as an install would, with no network (for pharn-oss CI) ## Reference diff --git a/docs/architecture.md b/docs/architecture.md index c00dbac1..c4b7936b 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -253,6 +253,18 @@ prompt was open (a file now byte-identical to upstream is not a change), then ap capability is handled by the one planner. "Up to date" is a plan that changes nothing (`changesNothing`); only the ahead-of-source guard returns before the download. +## `verify-archive` (`commands/verify-archive.ts`) + +The fetch boundary without the fetch, for pharn-oss CI. The command reads the file through `readBoundedFile` +(a regular file of at most `MAX_ARCHIVE_BYTES`, the download cap) and hands the bytes to `verifyLocalArchive` +(`lib/repo.ts`). That function makes a private `pharn-verify-*` temp dir, registers it with the same exit and +fatal-signal backstop as a clone, and runs `extractPharnArchive`, the function `fetchAt` calls after a +download. Its `checkTree`, run after the first pass, requires `pharn-install.json`: the archive must have one +root directory (`git archive --prefix=pharn-oss/`). With `--expect-version` it checks SKILLS_VERSION through +the release check's `assertSkillsVersion`, then refuses a present but unusable `MIN_CLI`. After the extraction +it builds the capability index with `manifestCapabilityIndex`. The temp dir is removed in a `finally`, and the +tree is never returned. No network, no project, no lock. + ## Root footprint - The lock is `pharn/.lock` and backups go to `pharn/.backup//` in every layout. diff --git a/docs/commands/verify-archive.md b/docs/commands/verify-archive.md new file mode 100644 index 00000000..1aac47e1 --- /dev/null +++ b/docs/commands/verify-archive.md @@ -0,0 +1,119 @@ +# pharn verify-archive + +Check a **local** pharn-oss `.tar.gz` the way `pharn init` and `pharn update` check a download, without +installing anything. It exists so that pharn-oss CI can find out that a commit would install before +that commit is tagged as a release. It makes **no network request**, needs no project and takes no lock. +Its only write is one temporary directory, which it removes whether the check passes or fails. + +```bash +pharn verify-archive pharn-oss.tar.gz # does an install accept these bytes? +pharn verify-archive pharn-oss.tar.gz --expect-version 7.25.6 # ...and is SKILLS_VERSION 7.25.6? +``` + +## The archive must have one top-level directory + +`pharn` reads archives shaped like GitHub's codeload tarballs: a pax global header, then everything under +one root directory (`pharn-oss-/`). A plain `git archive HEAD` puts its entries at the top level, so +`pharn` does not find `pharn-install.json`, and the check fails with a message that names this command. +Build the archive with a prefix: + +```bash +git archive --prefix=pharn-oss/ --format=tar.gz -o pharn-oss.tar.gz HEAD +``` + +The prefix is required on purpose. The install path removes the first path component and requires every +installed entry to share it. A mode that accepted a rootless archive would run a selection the install +path never runs, so a pass would no longer mean that an install accepts the bytes. codeload builds its +tarballs with `git archive` too, so a prefixed local archive goes through the same checks a download does. + +## What it checks + +It runs the extractor and manifest checks an install runs, in the same order: + +1. It reads the file only if it is a regular file of at most **32 MiB** (the download cap). It never + blocks on a FIFO. A symlink to a file is followed. +2. **First pass:** it unpacks only the four files `pharn` reads itself (`pharn-install.json`, + `SKILLS_VERSION`, `MIN_CLI`, `.claude/settings.json`). It skips every other entry without writing it, + whatever its type, so a symlink outside the install list is not a failure. +3. **Tree checks:** + - `pharn-install.json` must be present (see above). + - With `--expect-version`, `SKILLS_VERSION` must equal the given version. This is the check an install + makes against a release tag. + - `MIN_CLI`, if present, must be a valid version. +4. **The manifest** is validated by the install's one parser: schema, layout, capabilities, file paths + and destinations. +5. **Second pass:** it unpacks only the paths the manifest lists. Each must be a regular file with a safe + path, appear once, and not follow a pax or GNU long-name header. +6. **Every listed file's sha256** must match the manifest. A listed file that is missing or altered fails + the check. +7. **The capability index** is built from the manifest, as an install builds it. If a capability's + `applies` holds a token this `pharn` does not know, an install skips that capability with a warning. + `verify-archive` prints the same warning on stderr and still passes. + +### Where it differs from an install + +- An install warns about an unusable `MIN_CLI` and carries on. `verify-archive` **fails**, because a + release whose `MIN_CLI` no `pharn` can read has a packaging bug. +- It does not compare `MIN_CLI` with its own version. +- It does not detect archetypes, select capabilities or look at any project, so the destination checks + (symlinks, records, overwrites) are not run. + +## Output and exit codes + +On a pass it exits **0** and prints one line naming the file, the number of files `pharn-install.json` +lists, the capability count, `SKILLS_VERSION` and `MIN_CLI`, for example: + +```text +pharn-oss.tar.gz: 616 files listed in pharn-install.json, all present and matching their sha256; 35 capabilities; SKILLS_VERSION 7.25.5, as expected; MIN_CLI 0.14.0. +``` + +It exits **1** in these cases: + +| Case | Message (stderr) | +| ------------------------------------------------------- | ---------------------------------------------------------------------------------------- | +| The path does not exist | `Cannot verify : it does not exist.` | +| It is a directory, a FIFO or another non-file | `Cannot verify : it is not a regular file.` | +| It is larger than 32 MiB | `Cannot verify : it is larger than 32 MiB.` | +| It is empty | `Cannot verify : it is empty.` | +| The archive is refused (an entry, the manifest, a hash) | `⚠ Archive refused: `, plus the `PHARN_DEBUG` hint | +| No `pharn-install.json` under one root directory | `⚠ Archive refused: it holds no pharn-install.json under a single top-level …` | +| `--expect-version` differs | `⚠ Archive refused: it ships SKILLS_VERSION , not (--expect-…)` | + +`PHARN_DEBUG=1` prints the original error with its stack, as it does for every other command. Paths are +printed with control characters escaped. + +## Options + +- `--expect-version `: also require the archive's `SKILLS_VERSION` to equal this version, as a + release install does against its tag. Give it as `X.Y.Z`: a leading `v` is refused. A repeated value is + refused too. + +`verify-archive` takes no other option. `--json` and every other command's options are refused with +``Unsupported option for `verify-archive` `` (exit **1**), and so is a second path. + +## For pharn-oss CI + +Build the archive from **the same commit that will be tagged**: what passes is that commit's bytes. Pin +the `pharn` version, so the check does not change under you when a new `pharn` ships. + +On a pull request or a push, check the commit against its own `SKILLS_VERSION`: + +```bash +git archive --prefix=pharn-oss/ --format=tar.gz -o "$RUNNER_TEMP/pharn-oss.tar.gz" HEAD +npx --yes @pharn-dev/pharn@0.22.0 verify-archive "$RUNNER_TEMP/pharn-oss.tar.gz" --expect-version "$(cat SKILLS_VERSION)" +``` + +In a release job, before the tag is pushed, check the commit against the tag you are about to create +(`TAG=v7.25.6`, for example): + +```bash +git archive --prefix=pharn-oss/ --format=tar.gz -o "$RUNNER_TEMP/pharn-oss.tar.gz" HEAD +npx --yes @pharn-dev/pharn@0.22.0 verify-archive "$RUNNER_TEMP/pharn-oss.tar.gz" --expect-version "${TAG#v}" +``` + +`pharn` needs Node 24.2.0 or newer. + +## Related + +- [init](init.md) and [update](update.md), which run the same checks on a download +- [Troubleshooting](../troubleshooting.md#verify-archive-says-the-archive-has-no-top-level-directory) diff --git a/docs/contributing.md b/docs/contributing.md index 39616774..3f0e9690 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -128,7 +128,7 @@ The v0.20.0 rows, the `modules` row of v0.21.0 and the `flat` and root-footprint pharn-cli/ src/ index.ts CLI entry, command routing - commands/ init, add, remove, update, list, status, uninstall + commands/ init, add, remove, update, list, status, uninstall, verify-archive steps/ init stages (prereqs, node-prereq, overwrite-check, archetype-summary, install-archetype), add-picker lib/ install-capabilities, install-manifest, capability-index, resolve-capabilities, detect-archetype, node-floor, release, archetype, layout, repo, tar-extract, diff, skills-version, min-cli-gate, semver, older-cli, pharn-config, model-config(-format), models-update, upstream-models, install-records, update-decision, update-render, apply-update, merge-capabilities, dest-drift, backup, atomic-write, project-lock, proxy-env(-format), symlink-guard, capability-address, capability-groups, capability-picker, unknown-capabilities, cli-error, report-error, hash, validate, constants, banner, format types.ts Archetype / CapabilityEntry / Selection / PharnConfig @@ -217,6 +217,7 @@ Two rules that are easy to get wrong: | `commands/uninstall.test.ts` / `uninstall-plan.test.ts` | `runUninstall` end to end (refusals, confirm, lock, resumable failure); which recorded files may be deleted | | `orphans.test.ts` | Which recorded files are orphaned (install roots, dropped/frozen excluded); the `ORPHANED` note | | `commands/list.test.ts` / `commands/status.test.ts` | Read-only inventory + version/drift audit | +| `commands/verify-archive.test.ts` | `verify-archive` end to end: a pass (incl. unlisted symlinks), each refusal naming its entry, `--expect-version`, the input-path checks, no fetch, the temp dir removed | | `diff.test.ts` | `diffInstalledCapabilities` expected-set derivation + content compare, incl. a real `git -c core.autocrlf=true` checkout | | `hash.test.ts` | The content hash: the CRLF→LF fold for text and the 8000-byte NUL sniff | | `layout.test.ts` | `detectLayout` (refuses a `flat` clone) / `layoutPaths` | diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index f862fed9..fba91c24 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -22,21 +22,23 @@ | `add` refused on a skills-version mismatch | 1 | | `update --force` aborted because a backup could not be written | 1 | | `uninstall` refused, or stopped part-way (see [`uninstall`](commands/uninstall.md)) | 1 | +| `verify-archive` refused the archive, or could not read the file (see [`verify-archive`](commands/verify-archive.md)) | 1 | | Interrupted by Ctrl-C (`SIGINT`) or `SIGTERM` (a `timeout`, `docker stop`); the project may be partial | 130 or 143 | ## Common problems -| Symptom | See | -| ----------------------------------------------------------- | ------------------------------------------------------------------------------------ | -| `update` listed files under `SKIPPED` or `held` | [`pharn update` skipped my files](#pharn-update-skipped-my-files) | -| `Another pharn process is writing to this project` | [Another pharn process is running](#another-pharn-process-is-running) | -| `No pharn.config.json found. Run pharn init first.` | [`add` / `update` say to run init first](#add--update-say-to-run-init-first) | -| `Could not resolve the latest verified … release` | [No verified release could be resolved](#no-verified-release-could-be-resolved) | -| `Failed to fetch`, a timeout, or a proxy notice | [Capabilities could not be fetched](#capabilities-could-not-be-fetched) | -| `… outside the paths pharn installs; refusing this release` | [A pharn-oss release was refused](#a-pharn-oss-release-was-refused) | -| The wrong archetypes were detected | [Detection picked the wrong archetype](#detection-picked-the-wrong-archetype) | -| `Unknown option` / ``Unsupported option for `` `` | [Unsupported option for this command](#unsupported-option-for-this-command) | -| Your Prettier check fails on PHARN's files | [My Prettier check fails on PHARN's files](#my-prettier-check-fails-on-pharns-files) | +| Symptom | See | +| ---------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | +| `update` listed files under `SKIPPED` or `held` | [`pharn update` skipped my files](#pharn-update-skipped-my-files) | +| `Another pharn process is writing to this project` | [Another pharn process is running](#another-pharn-process-is-running) | +| `No pharn.config.json found. Run pharn init first.` | [`add` / `update` say to run init first](#add--update-say-to-run-init-first) | +| `Could not resolve the latest verified … release` | [No verified release could be resolved](#no-verified-release-could-be-resolved) | +| `Failed to fetch`, a timeout, or a proxy notice | [Capabilities could not be fetched](#capabilities-could-not-be-fetched) | +| `… outside the paths pharn installs; refusing this release` | [A pharn-oss release was refused](#a-pharn-oss-release-was-refused) | +| The wrong archetypes were detected | [Detection picked the wrong archetype](#detection-picked-the-wrong-archetype) | +| `Unknown option` / ``Unsupported option for `` `` | [Unsupported option for this command](#unsupported-option-for-this-command) | +| Your Prettier check fails on PHARN's files | [My Prettier check fails on PHARN's files](#my-prettier-check-fails-on-pharns-files) | +| `verify-archive`: `holds no pharn-install.json under a single top-level directory` | [verify-archive says the archive has no top-level directory](#verify-archive-says-the-archive-has-no-top-level-directory) | ## Node version @@ -436,6 +438,19 @@ hunt for a typo): takes no value (`Option takes no value: "--json=false"`), `--ref` and `--archetype` may each be given once (`Repeated option: "--ref"`), and `--no-drift` is the only negated option (`--no-dry-run`, `--no-yes` and `--no-ref` are `Unknown option`). +## verify-archive says the archive has no top-level directory + +`pharn verify-archive` reads archives shaped like GitHub's, with every entry under one root directory. A +plain `git archive HEAD` has no root directory, so `pharn` finds no `pharn-install.json` in it. Build the +archive with a prefix: + +```bash +git archive --prefix=pharn-oss/ --format=tar.gz -o pharn-oss.tar.gz HEAD +``` + +The same message appears for a pharn-oss older than 7.21.0, which ships no `pharn-install.json`. See +[`verify-archive`](commands/verify-archive.md#the-archive-must-have-one-top-level-directory). + ## Removing PHARN by hand [`pharn uninstall`](commands/uninstall.md) removes PHARN whenever `pharn.records.json` is usable. Without diff --git a/package-lock.json b/package-lock.json index c23d57c3..2b0b8d01 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@pharn-dev/pharn", - "version": "0.21.5", + "version": "0.22.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@pharn-dev/pharn", - "version": "0.21.5", + "version": "0.22.0", "license": "Apache-2.0", "dependencies": { "@clack/prompts": "^1.8.1", diff --git a/package.json b/package.json index fc5b550b..aab72d36 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@pharn-dev/pharn", - "version": "0.21.5", + "version": "0.22.0", "description": "Install and update PHARN in any git project. PHARN gets features shipped right with Claude Code, with spec, plan and checks kept in Git.", "keywords": [ "claude-code", diff --git a/src/commands/verify-archive.ts b/src/commands/verify-archive.ts new file mode 100644 index 00000000..5418a1aa --- /dev/null +++ b/src/commands/verify-archive.ts @@ -0,0 +1,141 @@ +import { existsSync } from 'node:fs'; +import { basename } from 'node:path'; +import { intro, log, outro } from '@clack/prompts'; +import pc from '../lib/color.js'; +import { readBoundedFile } from '../lib/bounded-read.js'; +import { CliError } from '../lib/cli-error.js'; +import { MIN_CLI_FILE, SKILLS_VERSION_FILE } from '../lib/constants.js'; +import { MAX_ARCHIVE_BYTES, verifyLocalArchive } from '../lib/repo.js'; +import { + assertSkillsVersion, + readMinCli, + readSkillsVersion, +} from '../lib/skills-version.js'; +import { TarExtractError } from '../lib/tar-extract.js'; +import { escapeUnsafe } from '../lib/terminal-safe.js'; +import { unknownCapabilitiesWarning } from '../lib/unknown-capabilities.js'; +import { + MANIFEST_FILE, + manifestCapabilityIndex, +} from '../lib/upstream-manifest.js'; +import type { UpstreamManifest } from '../lib/upstream-manifest.js'; +import { ManifestValidationError, safeJoin } from '../lib/validate.js'; + +// `pharn verify-archive `: the install path's own checks over a +// LOCAL pharn-oss archive, so pharn-oss CI can prove a commit installs before +// it is tagged. The same `extractPharnArchive` a download goes through (both +// passes, the manifest's one parser, every listed sha256), plus the two pure +// reads an install makes of the tree: MIN_CLI (validity only) and the +// capability index. No network, no project, no lock; the only write is the +// temp tree `verifyLocalArchive` (lib/repo.ts) creates and always removes. + +export interface VerifyArchiveOptions { + file: string; + expectVersion: string | undefined; +} + +/** What the checks found, read while the tree still exists. */ +interface Found { + skillsVersion: string; + minCli: string | null; +} + +// The pinned CI line, named in the rootless refusal and the docs. +const ARCHIVE_COMMAND = + 'git archive --prefix=pharn-oss/ --format=tar.gz -o pharn-oss.tar.gz HEAD'; + +export async function runVerifyArchive( + opts: VerifyArchiveOptions, +): Promise { + // The path is user input: escaped value by value wherever it is printed. + const shown = escapeUnsafe(opts.file); + const name = escapeUnsafe(basename(opts.file)); + const archive = readArchive(opts.file, shown); + + intro('pharn verify-archive'); + const found: Found = { skillsVersion: '', minCli: null }; + let manifest: UpstreamManifest; + try { + manifest = await verifyLocalArchive(archive, (tree) => { + checkTree(tree, opts.expectVersion, found); + }); + } catch (err) { + if ( + err instanceof TarExtractError || + err instanceof ManifestValidationError + ) { + throw CliError.failure(err, { + message: `Archive ${name} refused: ${err.message}`, + }); + } + throw CliError.failure(err); + } + + // The index an install builds from the manifest. A capability whose + // `applies` this CLI cannot read is skipped by an install with a warning, + // so it warns here and still passes. + const index = manifestCapabilityIndex(manifest); + const skipped = unknownCapabilitiesWarning(index.unknown); + if (skipped) log.warn(skipped); + + const version = + opts.expectVersion === undefined + ? `${SKILLS_VERSION_FILE} ${found.skillsVersion}` + : `${SKILLS_VERSION_FILE} ${found.skillsVersion}, as expected`; + const minCli = found.minCli === null ? 'none' : found.minCli; + log.success( + `${name}: ${manifest.files.length} files listed in ${MANIFEST_FILE}, all present and matching their sha256; ${index.capabilities.length} capabilities; ${version}; ${MIN_CLI_FILE} ${minCli}.`, + ); + outro(pc.dim('Nothing was installed; the temporary directory was removed.')); +} + +/** The archive's bytes, bounded: a regular file within the download cap. */ +function readArchive(file: string, shown: string): Buffer { + const read = readBoundedFile(file, MAX_ARCHIVE_BYTES); + if (read.kind === 'absent') { + throw CliError.error(`Cannot verify ${shown}: it does not exist.`); + } + if (read.kind === 'unusable') { + throw CliError.error(`Cannot verify ${shown}: it ${read.reason}.`); + } + if (read.bytes.length === 0) { + throw CliError.error(`Cannot verify ${shown}: it is empty.`); + } + return read.bytes; +} + +/** + * Run after the first pass, which wrote only the files the CLI reads itself: + * the manifest must be there (else the archive has no single top-level + * directory, or predates the manifest), then the optional version check, then + * MIN_CLI's validity. + */ +function checkTree( + tree: string, + expectVersion: string | undefined, + found: Found, +): void { + if (!existsSync(safeJoin(tree, MANIFEST_FILE))) { + throw new ManifestValidationError( + `it holds no ${MANIFEST_FILE} under a single top-level directory. pharn reads archives shaped like GitHub's (one root directory, as \`git archive --prefix=\` writes); a plain \`git archive\` has none. Re-create it with \`${ARCHIVE_COMMAND}\`. A pharn-oss older than 7.21.0 ships no ${MANIFEST_FILE} at all.`, + ); + } + if (expectVersion !== undefined) { + assertSkillsVersion( + tree, + expectVersion, + (v) => + `it ships ${SKILLS_VERSION_FILE} ${escapeUnsafe(v)}, not ${expectVersion} (--expect-version).`, + ); + } + found.skillsVersion = readSkillsVersion(tree); + // Stricter than an install, which warns and carries on: for a release, a + // MIN_CLI no pharn can read is a packaging bug. + const minCli = readMinCli(tree); + if (minCli.warning !== null) { + throw new ManifestValidationError( + `its ${MIN_CLI_FILE} is present but unusable; an install would warn: ${minCli.warning}`, + ); + } + found.minCli = minCli.version; +} diff --git a/src/index.ts b/src/index.ts index 36a86c43..e0267dcb 100644 --- a/src/index.ts +++ b/src/index.ts @@ -64,6 +64,11 @@ export async function main( await runUninstall(invocation.options); return; } + case 'verify-archive': { + const { runVerifyArchive } = await import('./commands/verify-archive.js'); + await runVerifyArchive(invocation.options); + return; + } } } diff --git a/src/lib/cli-args.ts b/src/lib/cli-args.ts index 7ae0990d..fcf48ef4 100644 --- a/src/lib/cli-args.ts +++ b/src/lib/cli-args.ts @@ -9,13 +9,21 @@ import { parseArgs } from 'node:util'; import { REF_CHOICES, type RefChoice } from './release.js'; import { parseArchetypeList } from './archetype.js'; import { escapeUnsafe } from './terminal-safe.js'; +import { VERSION_RE } from './validate.js'; import type { Archetype } from '../types.js'; import { PHARN_VERSION } from '../version.js'; const INTRO = `Pharn - Installs and updates PHARN (a workflow for shipping features right with Claude Code) in your git project. npx @pharn-dev/pharn init detects your project's archetype and installs the applicable PHARN capabilities; pharn add installs another capability later; pharn update bumps to the latest skills version.`; type CommandName = - 'init' | 'add' | 'remove' | 'update' | 'list' | 'status' | 'uninstall'; + | 'init' + | 'add' + | 'remove' + | 'update' + | 'list' + | 'status' + | 'uninstall' + | 'verify-archive'; interface CommandSpec { name: CommandName; @@ -54,6 +62,12 @@ const COMMANDS: readonly CommandSpec[] = [ name: 'uninstall', summary: 'Remove the PHARN files pharn wrote and you did not change', }, + { + name: 'verify-archive', + args: '', + summary: 'Check a local pharn-oss .tar.gz as an install would (no network)', + page: 'Check a local pharn-oss .tar.gz as an install would: unpack the listed files into a temporary directory, validate pharn-install.json and every listed sha256, then remove the directory. No network, no project. Build the archive with `git archive --prefix=pharn-oss/ --format=tar.gz -o pharn-oss.tar.gz HEAD`.', + }, ]; interface OptionSpec { @@ -201,6 +215,20 @@ const OPTIONS: readonly OptionSpec[] = [ }, ], }, + { + key: 'expect-version', + long: '--expect-version ', + value: true, + uses: [ + { + commands: ['verify-archive'], + text: [ + "also require the archive's SKILLS_VERSION to equal this", + 'version (X.Y.Z, no leading v), as the release check does', + ], + }, + ], + }, { key: 'help', short: 'h', @@ -347,7 +375,11 @@ export type Invocation = command: 'status'; options: { strict: boolean; drift: boolean; json: boolean }; } - | { command: 'uninstall'; options: { yes: boolean } }; + | { command: 'uninstall'; options: { yes: boolean } } + | { + command: 'verify-archive'; + options: { file: string; expectVersion: string | undefined }; + }; export type ParsedArgs = // One stderr line; the caller adds USAGE_POINTER and exits 1. @@ -484,6 +516,14 @@ export function parseCliArgs(args: readonly string[]): ParsedArgs { ); } + const expectVersion = valueOf('expect-version'); + if (expectVersion !== undefined && !VERSION_RE.test(expectVersion)) { + return refuse( + 'Invalid value for --expect-version (expected a version such as "7.25.5", with no leading "v")', + [expectVersion], + ); + } + if (has('version')) return { kind: 'print', text: PHARN_VERSION }; if (has('help')) { // A bare `pharn --help` and an unknown command get the full text. @@ -546,6 +586,21 @@ export function parseCliArgs(args: readonly string[]): ParsedArgs { }); case 'uninstall': return run({ command: 'uninstall', options: { yes: has('yes') } }); + case 'verify-archive': { + const file = positionals[1]; + // Empty is as missing: `""` names no file. + if (file === undefined || file === '') { + return { + kind: 'refuse', + message: + 'Missing argument: `verify-archive` needs the path of a .tar.gz archive', + }; + } + return run({ + command: 'verify-archive', + options: { file, expectVersion }, + }); + } } } diff --git a/src/lib/repo.ts b/src/lib/repo.ts index 61f6f122..a0204519 100644 --- a/src/lib/repo.ts +++ b/src/lib/repo.ts @@ -13,7 +13,7 @@ import { fetchCapped } from './fetch-capped.js'; import type { CappedResponse, FetchCappedError } from './fetch-capped.js'; import { MAX_SHA_BYTES } from './release.js'; import type { InstallSource } from './release.js'; -import { readSkillsVersion } from './skills-version.js'; +import { assertSkillsVersion } from './skills-version.js'; import { extractTarGz } from './tar-extract.js'; import { MANIFEST_FILE, @@ -21,11 +21,7 @@ import { verifyUpstreamManifest, } from './upstream-manifest.js'; import type { UpstreamManifest } from './upstream-manifest.js'; -import { - assertSafeString, - COMMIT_RE, - ManifestValidationError, -} from './validate.js'; +import { assertSafeString, COMMIT_RE } from './validate.js'; const API = 'https://api.github.com'; const CODELOAD = 'https://codeload.github.com'; @@ -38,7 +34,7 @@ const CLONE_TIMEOUT_MS = 60_000; // own size bounds nothing: headers walked and decompressed bytes walked bound a // compression bomb's work (both far above pharn-oss v7.25.5's 4,939 entries and // 43 MB), and the written-byte cap bounds what reaches disk. -const MAX_ARCHIVE_BYTES = 32 * 1024 * 1024; +export const MAX_ARCHIVE_BYTES = 32 * 1024 * 1024; const MAX_HEADERS = 200_000; const MAX_SCANNED_BYTES = 1024 * 1024 * 1024; const MAX_WRITTEN_BYTES = 128 * 1024 * 1024; @@ -162,12 +158,12 @@ async function fetchAt( // version compare would lie. Refused inside this try, so the tree is // removed. if (source.kind !== 'release') return; - const found = readSkillsVersion(tree); - if (found !== source.version) { - throw new ManifestValidationError( + assertSkillsVersion( + tree, + source.version, + (found) => `Release ${source.tag} (${source.sha}) ships ${SKILLS_VERSION_FILE} ${found}, not ${source.version}; refusing to install a release whose content does not match its tag.`, - ); - } + ); }); } catch (err) { // Extraction is not transactional, so a partially-written tree must never @@ -226,6 +222,28 @@ export async function extractPharnArchive( return manifest; } +/** + * Run `extractPharnArchive` over a LOCAL archive's bytes (`pharn + * verify-archive`) in a private temp dir that is always removed, on a pass and + * on a refusal alike, and registered with the exit/fatal-signal backstop + * meanwhile. The tree is never returned: `checkTree` (run after the first + * pass, as the release check is) is the only reader. No network. + */ +export async function verifyLocalArchive( + archive: Buffer, + checkTree: (dir: string) => void, +): Promise { + installCleanupHandlers(); + const dir = mkdtempSync(join(tmpdir(), 'pharn-verify-')); + liveClones.add(dir); + try { + return await extractPharnArchive(archive, dir, checkTree); + } finally { + liveClones.delete(dir); + rmSync(dir, { recursive: true, force: true }); + } +} + /** * Download the repo tarball at `ref` into memory, bounded on both time and * size (`fetchCapped`; the decompressed size is bounded by the extract). diff --git a/src/lib/skills-version.ts b/src/lib/skills-version.ts index 7294f9a0..2fea7039 100644 --- a/src/lib/skills-version.ts +++ b/src/lib/skills-version.ts @@ -47,6 +47,21 @@ export function readSkillsVersion(repoDir: string): string { ); } +/** + * Refuse a tree whose SKILLS_VERSION is not `expected`: the release check + * (`fetchAt`, lib/repo.ts) and `verify-archive --expect-version` share it. + * `refusal` words the message from the version found, so each caller keeps + * its own wording; a missing or malformed file throws `readSkillsVersion`'s. + */ +export function assertSkillsVersion( + repoDir: string, + expected: string, + refusal: (found: string) => string, +): void { + const found = readSkillsVersion(repoDir); + if (found !== expected) throw new ManifestValidationError(refusal(found)); +} + // --------------------------------------------------------------------------- // MIN_CLI — the OPTIONAL forward-compatibility handshake, beside SKILLS_VERSION. // diff --git a/tests/cli-args.test.ts b/tests/cli-args.test.ts index b942cecb..d4c8234d 100644 --- a/tests/cli-args.test.ts +++ b/tests/cli-args.test.ts @@ -668,3 +668,85 @@ describe('parseCliArgs: --version and --help', () => { }, ); }); + +describe('parseCliArgs: verify-archive', () => { + it.each<[string[], Invocation]>([ + [ + ['verify-archive', 'x.tar.gz'], + { + command: 'verify-archive', + options: { file: 'x.tar.gz', expectVersion: undefined }, + }, + ], + [ + ['verify-archive', 'x.tar.gz', '--expect-version', '7.25.5'], + { + command: 'verify-archive', + options: { file: 'x.tar.gz', expectVersion: '7.25.5' }, + }, + ], + [ + ['verify-archive', '--expect-version=7.25.5', 'x.tar.gz'], + { + command: 'verify-archive', + options: { file: 'x.tar.gz', expectVersion: '7.25.5' }, + }, + ], + ])('%j parses to its file and expected version', (args, expected) => { + expect(invocation(args)).toEqual(expected); + }); + + const MISSING = + 'Missing argument: `verify-archive` needs the path of a .tar.gz archive'; + const INVALID = + 'Invalid value for --expect-version (expected a version such as "7.25.5", with no leading "v")'; + it.each<[string[], string]>([ + [['verify-archive'], MISSING], + [['verify-archive', ''], MISSING], + [ + ['verify-archive', 'a.tar.gz', 'b.tar.gz'], + 'Unexpected argument: "b.tar.gz"', + ], + [ + ['verify-archive', 'a.tar.gz', '--expect-version', 'v7.25.5'], + `${INVALID}: "v7.25.5"`, + ], + [['verify-archive', 'a.tar.gz', '--expect-version'], `${INVALID}: ""`], + [ + [ + 'verify-archive', + 'a.tar.gz', + '--expect-version', + '1.0.0', + '--expect-version', + '1.0.1', + ], + 'Repeated option: "--expect-version"', + ], + [ + ['verify-archive', 'a.tar.gz', '--json'], + 'Unsupported option for `verify-archive`: "--json"', + ], + [ + ['status', '--expect-version', '1.0.0'], + 'Unsupported option for `status`: "--expect-version"', + ], + [ + ['init', '--expect-version=1.0.0'], + 'Unsupported option for `init`: "--expect-version=1.0.0"', + ], + ])('%j is refused', (args, message) => { + expect(refusal(args)).toBe(message); + }); + + it('is listed in the full help, and its page names the option and the git archive line', () => { + expect(printed(['--help'])).toMatch( + /^ {2}verify-archive +Check a local pharn-oss \.tar\.gz/m, + ); + const page = printed(['verify-archive', '--help']); + expect(page).toContain('pharn verify-archive [options]'); + expect(page).toContain('--expect-version '); + expect(page).toContain('git archive --prefix=pharn-oss/'); + expect(page).not.toContain('--json'); + }); +}); diff --git a/tests/commands/verify-archive.test.ts b/tests/commands/verify-archive.test.ts new file mode 100644 index 00000000..488c4cc7 --- /dev/null +++ b/tests/commands/verify-archive.test.ts @@ -0,0 +1,278 @@ +import { execFileSync } from 'node:child_process'; +import { + mkdirSync, + readdirSync, + symlinkSync, + truncateSync, + writeFileSync, +} from 'node:fs'; +import { join } from 'node:path'; +import { describe, expect, it, vi } from 'vitest'; +import { + A11Y, + fetchStub, + logs, + MANIFEST, + manifestTree, + proj, + run, + SECURITY, + SHA_V1, + stderr, + stdout, + useHarness, + watchClones, + withManifest, + upstreamTree, + type Tree, +} from '../support/harness.js'; +import { + codeloadArchive, + type ArchiveOptions, +} from '../support/tar-fixture.js'; +import { runVerifyArchive } from '../../src/commands/verify-archive.js'; +import { PHARN_DEBUG_HINT } from '../../src/lib/report-error.js'; + +vi.mock('@clack/prompts', async () => + (await import('../support/clack-stub.js')).clackStub(), +); + +useHarness(); + +// `verify-archive` runs the install path's own extractor and manifest checks +// over a LOCAL archive. Every case asserts that nothing was fetched and, where +// a tree was made, that the temp directory is gone afterwards. + +const VERSION = '7.25.5'; + +/** Write a gzipped codeload-shaped archive of `tree` beside the project. */ +function archiveFile( + tree: Tree, + opts: ArchiveOptions = {}, + name = 'pharn-oss.tar.gz', +): string { + const path = join(proj(), '..', name); + writeFileSync(path, codeloadArchive(SHA_V1, tree, opts)); + return path; +} + +async function verify( + file: string, + expectVersion?: string, +): Promise { + return run(() => runVerifyArchive({ file, expectVersion })); +} + +const errors = (): string => logs('error').join('\n'); + +// What v7.25.5 committed outside its manifest, and more an archive may carry. +const UNLISTED = [ + { path: '.claude/skills/pharn-cli', type: '2' }, + { path: '.dev/hard', type: '1' }, + { path: 'PaxHeaders/long', type: 'x', data: '30 path=pharn-oss/x/y/z.md\n' }, + { path: '.dev/notes.md', type: '0', data: 'unlisted\n' }, +]; + +describe('pharn verify-archive — a good archive passes', () => { + it('exits 0 with the file name, listed-file count and SKILLS_VERSION, fetching nothing', async () => { + const left = watchClones(); + const tree = manifestTree(VERSION); + const listed = (JSON.parse(tree[MANIFEST]!) as { files: unknown[] }).files + .length; + expect(await verify(archiveFile(tree))).toBeNull(); + const [summary] = logs('success'); + expect(summary).toContain('pharn-oss.tar.gz'); + expect(summary).toContain(`${listed} files listed in ${MANIFEST}`); + expect(summary).toContain(`SKILLS_VERSION ${VERSION}`); + expect(summary).toContain('MIN_CLI none'); + expect(fetchStub).not.toHaveBeenCalled(); + expect(left()).toEqual([]); + expect(stdout()).toEqual([]); + }); + + it('passes past an unlisted symlink, hard link and pax header (the v7.25.5 shape), leaving nothing behind', async () => { + const left = watchClones(); + expect( + await verify(archiveFile(manifestTree(VERSION), { extra: UNLISTED })), + ).toBeNull(); + expect(logs('success')).toHaveLength(1); + expect(fetchStub).not.toHaveBeenCalled(); + expect(left()).toEqual([]); + }); + + it('--expect-version that matches passes and says so', async () => { + expect( + await verify(archiveFile(manifestTree(VERSION)), VERSION), + ).toBeNull(); + expect(logs('success')[0]).toContain( + `SKILLS_VERSION ${VERSION}, as expected`, + ); + }); + + it('names a valid MIN_CLI in the summary', async () => { + const tree = withManifest({ + ...upstreamTree(VERSION), + MIN_CLI: '0.14.0\n', + }); + expect(await verify(archiveFile(tree))).toBeNull(); + expect(logs('success')[0]).toContain('MIN_CLI 0.14.0'); + }); + + it('warns about a capability an install would skip, and still passes', async () => { + const tree = manifestTree(VERSION, (m) => { + const cap = m.capabilities.find((c) => c.name === 'a11y')!; + cap.applies = ['mobile']; + }); + expect(await verify(archiveFile(tree))).toBeNull(); + expect(logs('warn').join('\n')).toMatch(/SKIPPED/); + expect(logs('warn').join('\n')).toContain('a11y'); + expect(logs('success')).toHaveLength(1); + }); +}); + +describe('pharn verify-archive — a broken archive is refused, naming the entry and rule', () => { + it('a listed file whose bytes differ from its sha256', async () => { + const left = watchClones(); + const tree = manifestTree(VERSION); + tree[A11Y] = 'altered after the manifest was built\n'; + expect(await verify(archiveFile(tree))).toBe(1); + expect(errors()).toContain('Archive pharn-oss.tar.gz refused:'); + expect(errors()).toContain(A11Y); + expect(errors()).toMatch(/sha256/); + expect(logs('success')).toEqual([]); + expect(fetchStub).not.toHaveBeenCalled(); + expect(left()).toEqual([]); + }); + + it('a symlink at a listed path', async () => { + const left = watchClones(); + const file = archiveFile(manifestTree(VERSION), { + replace: { [SECURITY]: [{ path: SECURITY, type: '2' }] }, + }); + expect(await verify(file)).toBe(1); + expect(errors()).toMatch(/unsupported type '2'/); + expect(errors()).toContain(SECURITY); + expect(left()).toEqual([]); + }); + + it('an archive without pharn-install.json names the --prefix command', async () => { + const left = watchClones(); + const tree = upstreamTree(VERSION); + expect(await verify(archiveFile(tree))).toBe(1); + expect(errors()).toContain(`holds no ${MANIFEST}`); + expect(errors()).toContain('git archive --prefix=pharn-oss/'); + expect(left()).toEqual([]); + }); + + it('a rootless archive (a plain `git archive`) gets the same --prefix message', async () => { + expect( + await verify(archiveFile(manifestTree(VERSION), { rootless: true })), + ).toBe(1); + expect(errors()).toContain('single top-level directory'); + expect(errors()).toContain('git archive --prefix=pharn-oss/'); + expect(fetchStub).not.toHaveBeenCalled(); + }); + + it('--expect-version that differs names both versions', async () => { + const left = watchClones(); + expect(await verify(archiveFile(manifestTree(VERSION)), '7.25.6')).toBe(1); + expect(errors()).toContain( + `ships SKILLS_VERSION ${VERSION}, not 7.25.6 (--expect-version)`, + ); + expect(left()).toEqual([]); + }); + + it('a malformed MIN_CLI', async () => { + const tree = withManifest({ + ...upstreamTree(VERSION), + MIN_CLI: 'not-a-version\n', + }); + expect(await verify(archiveFile(tree))).toBe(1); + expect(errors()).toContain('MIN_CLI is present but unusable'); + expect(errors()).toContain('not a valid version'); + }); + + it('a file that is not gzip', async () => { + const path = join(proj(), '..', 'junk.tar.gz'); + writeFileSync(path, 'not an archive at all\n'); + expect(await verify(path)).toBe(1); + expect(errors()).toContain('Archive junk.tar.gz refused:'); + expect(errors()).toMatch(/decompress/); + }); + + it('prints the PHARN_DEBUG hint, and the original error under PHARN_DEBUG=1', async () => { + const tree = manifestTree(VERSION); + tree[A11Y] = 'altered\n'; + const file = archiveFile(tree); + expect(await verify(file)).toBe(1); + expect(logs('info')).toContain(PHARN_DEBUG_HINT); + + vi.stubEnv('PHARN_DEBUG', '1'); + vi.mocked((await import('@clack/prompts')).log.info).mockClear(); + expect(await verify(file)).toBe(1); + expect(logs('info')).not.toContain(PHARN_DEBUG_HINT); + expect(stderr().join('\n')).toMatch(/UpstreamManifestError|sha256/); + }); +}); + +describe('pharn verify-archive — the input path', () => { + it('a path that does not exist', async () => { + expect(await verify(join(proj(), 'missing.tar.gz'))).toBe(1); + expect(errors()).toContain('missing.tar.gz: it does not exist.'); + expect(fetchStub).not.toHaveBeenCalled(); + }); + + it('a directory', async () => { + const dir = join(proj(), 'dir.tar.gz'); + mkdirSync(dir); + expect(await verify(dir)).toBe(1); + expect(errors()).toContain('is not a regular file'); + }); + + it.skipIf(process.platform === 'win32')( + 'a FIFO is refused without waiting on it', + async () => { + const fifo = join(proj(), 'pipe.tar.gz'); + execFileSync('mkfifo', [fifo]); + expect(await verify(fifo)).toBe(1); + expect(errors()).toContain('is not a regular file'); + }, + ); + + it('a file over the 32 MiB download cap', async () => { + const big = join(proj(), 'big.tar.gz'); + writeFileSync(big, ''); + truncateSync(big, 32 * 1024 * 1024 + 1); + expect(await verify(big)).toBe(1); + expect(errors()).toContain('is larger than 32 MiB'); + }); + + it('an empty file', async () => { + const empty = join(proj(), 'empty.tar.gz'); + writeFileSync(empty, ''); + expect(await verify(empty)).toBe(1); + expect(errors()).toContain('empty.tar.gz: it is empty.'); + }); + + it('follows a symlinked archive file (the user’s own)', async () => { + const link = join(proj(), 'link.tar.gz'); + symlinkSync(archiveFile(manifestTree(VERSION)), link); + expect(await verify(link)).toBeNull(); + expect(logs('success')[0]).toContain('link.tar.gz'); + }); + + it('escapes a control character in the path wherever it is printed', async () => { + expect(await verify(join(proj(), 'evil\u001b[31m.tar.gz'))).toBe(1); + expect(errors()).not.toContain('\u001b'); + expect(errors()).toContain('evil'); + + const tree = manifestTree(VERSION); + tree[A11Y] = 'altered\n'; + const file = archiveFile(tree, {}, 'bad\u001b[2J.tar.gz'); + expect(await verify(file)).toBe(1); + expect(errors()).not.toContain('\u001b'); + expect( + readdirSync(join(proj(), '..')).some((n) => n.startsWith('bad')), + ).toBe(true); + }); +}); diff --git a/tests/dist-smoke.test.ts b/tests/dist-smoke.test.ts index b1cb6ced..7102e9f3 100644 --- a/tests/dist-smoke.test.ts +++ b/tests/dist-smoke.test.ts @@ -8,11 +8,14 @@ import { realpathSync, rmSync, symlinkSync, + writeFileSync, } from 'node:fs'; import { tmpdir } from 'node:os'; import { dirname, join, resolve } from 'node:path'; import { pathToFileURL } from 'node:url'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { codeloadArchive } from './support/tar-fixture.js'; +import { upstreamTree, withManifest } from './support/harness.js'; // Executes the SHIPPED artifact — the esbuild bundle — inside the required // `Test` gate, which runs `test:coverage` and never `npm run build`. Every other @@ -116,7 +119,7 @@ function loadedModules(stderr: string): string[] { // A command's chunk is named after its source file (`status-.js`). const COMMAND_CHUNK = - /\/dist\/(init|add|remove|update|list|status|uninstall)-[A-Z0-9]+\.js$/; + /\/dist\/(init|add|remove|update|list|status|uninstall|verify-archive)-[A-Z0-9]+\.js$/; // Each test spawns a fresh node process; the per-test budget is the spawn's. describe('the built bundle (dist/index.js)', { timeout: 30_000 }, () => { @@ -164,6 +167,23 @@ describe('the built bundle (dist/index.js)', { timeout: 30_000 }, () => { } }); + it('verify-archive passes a good local archive (exit 0) and refuses a missing file (exit 1)', () => { + const file = join(tmp, 'pharn-oss.tar.gz'); + writeFileSync( + file, + codeloadArchive('a'.repeat(40), withManifest(upstreamTree('7.25.5'))), + ); + const ok = pharn(['verify-archive', file, '--expect-version', '7.25.5']); + expect(ok.status).toBe(0); + expect(ok.stdout).toContain('pharn-oss.tar.gz:'); + expect(ok.stdout).toContain('SKILLS_VERSION 7.25.5, as expected'); + + const missing = pharn(['verify-archive', join(tmp, 'nope.tar.gz')]); + expect(missing.status).toBe(1); + expect(missing.stderr).toContain('nope.tar.gz: it does not exist.'); + expect(missing.stderr).not.toMatch(STACK_FRAME); + }); + it('status with no pharn.config.json exits 1 with the "run init" message, no stack trace', () => { const r = pharn(['status']); expect(r.status).toBe(1); diff --git a/tests/index.test.ts b/tests/index.test.ts index e780da61..5b13c66a 100644 --- a/tests/index.test.ts +++ b/tests/index.test.ts @@ -17,6 +17,7 @@ const runUpdate = vi.fn(async (_opts: unknown) => undefined); const runList = vi.fn(async (_opts: unknown) => undefined); const runStatus = vi.fn(async (_opts: unknown) => undefined); const runUninstall = vi.fn(async (_opts: unknown) => undefined); +const runVerifyArchive = vi.fn(async (_opts: unknown) => undefined); // Each command module's factory runs when, and only when, main() imports it: // `loaded` names the command modules loaded since it was last emptied. const loaded = vi.hoisted((): string[] => []); @@ -39,6 +40,10 @@ vi.mock( '../src/commands/uninstall.js', () => (loaded.push('uninstall'), { runUninstall }), ); +vi.mock( + '../src/commands/verify-archive.js', + () => (loaded.push('verify-archive'), { runVerifyArchive }), +); const COMMANDS = { init: runInit, @@ -48,6 +53,7 @@ const COMMANDS = { list: runList, status: runStatus, uninstall: runUninstall, + 'verify-archive': runVerifyArchive, }; function setArgv(...args: string[]): void { @@ -113,6 +119,7 @@ describe('main (argv dispatch)', () => { [['list', '--json']], [['status', '--strict', '--no-drift']], [['uninstall', '-y']], + [['verify-archive', 'a.tar.gz', '--expect-version', '7.25.5']], ])('hands %j to its command as one parsed options object', async (args) => { await run(...args); const parsed = parseCliArgs(args); diff --git a/tests/repo.test.ts b/tests/repo.test.ts index 975e76c2..a05f403d 100644 --- a/tests/repo.test.ts +++ b/tests/repo.test.ts @@ -23,8 +23,13 @@ import { withManifest, } from './support/harness.js'; -const { CLONE_READ_FILES, extractPharnArchive, fetchRepo, fetchCommitSha } = - await import('../src/lib/repo.js'); +const { + CLONE_READ_FILES, + extractPharnArchive, + fetchRepo, + fetchCommitSha, + verifyLocalArchive, +} = await import('../src/lib/repo.js'); // A real 40-char lowercase-hex commit SHA (the SHA-1 of the empty blob) — the // form fetchRepo validates against COMMIT_RE before it fetches or records it. @@ -854,3 +859,69 @@ describe('fetchRepo — only the listed paths are unpacked (CORE-386)', () => { ).resolves.toMatchObject({ skillsVersion: '7.20.0' }); }); }); + +// CORE-387: `pharn verify-archive`'s half in repo.ts — the same extraction in +// a private temp dir that is removed on a pass and on a refusal alike. +describe('verifyLocalArchive (CORE-387)', () => { + beforeEach(() => { + sandbox = mkdtempSync(join(tmpdir(), 'pharn-repo-sandbox-')); + process.env.TMPDIR = sandbox; + process.env.TEMP = sandbox; + process.env.TMP = sandbox; + vi.stubGlobal( + 'fetch', + vi.fn(async () => { + throw new Error('no network in this test'); + }), + ); + }); + + afterEach(() => { + for (const [key, value] of Object.entries(realTmp)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + rmSync(sandbox, { recursive: true, force: true }); + vi.unstubAllGlobals(); + }); + + it('returns the manifest and removes its temp dir; checkTree sees the tree after the first pass', async () => { + const tree = manifestTree('7.20.0'); + const seen: string[] = []; + const manifest = await verifyLocalArchive( + codeloadArchive(VALID_SHA, tree), + (dir) => { + seen.push(dir); + expect(existsSync(join(dir, MANIFEST))).toBe(true); + expect(existsSync(join(dir, SECURITY))).toBe(false); + }, + ); + expect(manifest.skillsVersion).toBe('7.20.0'); + expect(seen).toHaveLength(1); + expect(seen[0]!.startsWith(join(sandbox, 'pharn-verify-'))).toBe(true); + expect(leftoverTempDirs()).toEqual([]); + expect(fetch).not.toHaveBeenCalled(); + }); + + it('removes its temp dir when the archive is refused, and rethrows the refusal', async () => { + const tree = manifestTree('7.20.0'); + tree[SECURITY] = 'altered\n'; + const err = await verifyLocalArchive( + codeloadArchive(VALID_SHA, tree), + () => undefined, + ).catch((e: unknown) => e); + expect(err).toBeInstanceOf(UpstreamManifestError); + expect(leftoverTempDirs()).toEqual([]); + }); + + it('removes its temp dir when checkTree throws', async () => { + const err = await verifyLocalArchive( + codeloadArchive(VALID_SHA, manifestTree('7.20.0')), + () => { + throw new ManifestValidationError('stop'); + }, + ).catch((e: unknown) => e); + expect((err as Error).message).toBe('stop'); + expect(leftoverTempDirs()).toEqual([]); + }); +}); diff --git a/tests/skills-version.test.ts b/tests/skills-version.test.ts index 00e9e786..d53cb189 100644 --- a/tests/skills-version.test.ts +++ b/tests/skills-version.test.ts @@ -3,6 +3,7 @@ import { join } from 'node:path'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { useTmpDir } from './helpers.js'; import { + assertSkillsVersion, fetchRemoteSkillsVersion, readMinCli, readSkillsVersion, @@ -24,6 +25,31 @@ function fakeResponse(body: string, status = 200): Response { }); } +describe('assertSkillsVersion (the release check and verify-archive)', () => { + const tmp = useTmpDir(); + const words = (found: string): string => `found ${found}`; + + it('passes when SKILLS_VERSION equals the expected version', () => { + writeFileSync(join(tmp.path(), 'SKILLS_VERSION'), '7.25.5\n'); + expect(() => + assertSkillsVersion(tmp.path(), '7.25.5', words), + ).not.toThrow(); + }); + + it('throws the caller-worded refusal on a mismatch', () => { + writeFileSync(join(tmp.path(), 'SKILLS_VERSION'), '7.25.4\n'); + expect(() => assertSkillsVersion(tmp.path(), '7.25.5', words)).toThrow( + new ManifestValidationError('found 7.25.4'), + ); + }); + + it("throws readSkillsVersion's refusal when the file is missing", () => { + expect(() => assertSkillsVersion(tmp.path(), '7.25.5', words)).toThrow( + /SKILLS_VERSION is missing/, + ); + }); +}); + describe('readSkillsVersion', () => { const tmp = useTmpDir(); diff --git a/tests/support/tar-fixture.ts b/tests/support/tar-fixture.ts index a41d982b..f0c6547a 100644 --- a/tests/support/tar-fixture.ts +++ b/tests/support/tar-fixture.ts @@ -51,9 +51,26 @@ export function githubArchive(sha: string): Buffer { * 100-byte ustar name field with no prefix split, so a path plus the 18-byte * `pharn-oss-/` root must stay under 100 bytes — refused, not truncated. */ +/** A raw archive entry: a root-relative path, a ustar typeflag, its payload. */ +export interface RawEntry { + path: string; + type: string; + data?: string; +} + +export interface ArchiveOptions { + /** Entries spliced in right after the root directory (a symlink, a pax header). */ + extra?: readonly RawEntry[]; + /** A tree path's own entry swapped for these raw entries. */ + replace?: Readonly>; + /** No root directory: entries at the top level, as a plain `git archive`. */ + rootless?: boolean; +} + export function codeloadArchive( sha: string, files: Readonly>, + opts: ArchiveOptions = {}, ): Buffer { // Memoized per (sha, tree): the command suites serve the same upstream state // to every command of a test and to many tests, and gzip is the bulk of a @@ -62,10 +79,10 @@ export function codeloadArchive( Object.keys(files) .sort() .map((rel) => [rel, files[rel]]), - )}`; + )}\0${JSON.stringify(opts)}`; const hit = archiveCache.get(key); if (hit) return hit; - const archive = buildArchive(sha, files); + const archive = buildArchive(sha, files, opts); archiveCache.set(key, archive); return archive; } @@ -75,27 +92,35 @@ const archiveCache = new Map(); function buildArchive( sha: string, files: Readonly>, + opts: ArchiveOptions, ): Buffer { - const root = `pharn-oss-${sha.slice(0, 7)}`; + const root = opts.rootless ? '' : `pharn-oss-${sha.slice(0, 7)}/`; + const named = (rel: string): string => { + const name = `${root}${rel}`; + if (Buffer.byteLength(name) >= 100) { + throw new Error(`tar fixture: ${name} does not fit the ustar name field`); + } + return name; + }; + const raw = (e: RawEntry): Buffer => entry(named(e.path), e.type, e.data); const parts = [ entry('pax_global_header', 'g', `52 comment=${sha}\n`), - entry(`${root}/`, '5'), + ...(opts.rootless ? [] : [entry(root, '5')]), + ...(opts.extra ?? []).map(raw), ]; const dirs = new Set(); for (const rel of Object.keys(files).sort()) { const segments = rel.split('/'); for (let i = 1; i < segments.length; i++) { - const dir = `${root}/${segments.slice(0, i).join('/')}/`; + const dir = `${root}${segments.slice(0, i).join('/')}/`; if (!dirs.has(dir)) { dirs.add(dir); parts.push(entry(dir, '5')); } } - const name = `${root}/${rel}`; - if (Buffer.byteLength(name) >= 100) { - throw new Error(`tar fixture: ${name} does not fit the ustar name field`); - } - parts.push(entry(name, '0', files[rel])); + const swapped = opts.replace?.[rel]; + if (swapped) parts.push(...swapped.map(raw)); + else parts.push(entry(named(rel), '0', files[rel])); } parts.push(Buffer.alloc(BLOCK * 2)); return gzipSync(Buffer.concat(parts)); From ed159fe8cbb968efb96c75f0e64e115aa1ccb214 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Galarowicz?= Date: Wed, 25 Nov 2026 17:51:22 +0100 Subject: [PATCH 6/8] fix(verify-archive): name the git archive --prefix fix after the extractor's rootless refusal (CORE-387) Co-Authored-By: Claude Opus 5.5 --- src/commands/verify-archive.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/commands/verify-archive.ts b/src/commands/verify-archive.ts index 96613169..57cabedf 100644 --- a/src/commands/verify-archive.ts +++ b/src/commands/verify-archive.ts @@ -72,7 +72,7 @@ export async function runVerifyArchive( // pinned by the rootless case in this command's suite). const hint = err instanceof TarExtractError && err.message.startsWith(ROOTLESS) - ? ` ${ROOTLESS_HINT}` + ? `. ${ROOTLESS_HINT}` : ''; throw CliError.failure(err, { message: `Archive ${name} refused: ${err.message}${hint}`, From 92202862e2a0b0b6d78935b269b734b3bf5050ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Galarowicz?= Date: Wed, 25 Nov 2026 17:57:44 +0100 Subject: [PATCH 7/8] docs(dev): CORE-387 regress, verify, review and ship records Co-Authored-By: Claude Opus 5.5 --- .dev/features/core-387-verify-archive/PLAN.md | 2 +- .../core-387-verify-archive/REGRESSION.md | 29 +++++++++++ .../core-387-verify-archive/REVIEW.md | 47 ++++++++++++++++++ .dev/features/core-387-verify-archive/SHIP.md | 25 ++++++++++ .../core-387-verify-archive/VERIFY.md | 33 +++++++++++++ .../regression-report.json | 48 +++++++++++++++++++ .../verify-report.json | 14 ++++++ 7 files changed, 197 insertions(+), 1 deletion(-) create mode 100644 .dev/features/core-387-verify-archive/REGRESSION.md create mode 100644 .dev/features/core-387-verify-archive/REVIEW.md create mode 100644 .dev/features/core-387-verify-archive/SHIP.md create mode 100644 .dev/features/core-387-verify-archive/VERIFY.md create mode 100644 .dev/features/core-387-verify-archive/regression-report.json create mode 100644 .dev/features/core-387-verify-archive/verify-report.json diff --git a/.dev/features/core-387-verify-archive/PLAN.md b/.dev/features/core-387-verify-archive/PLAN.md index 8ba36067..1b4eb946 100644 --- a/.dev/features/core-387-verify-archive/PLAN.md +++ b/.dev/features/core-387-verify-archive/PLAN.md @@ -61,7 +61,7 @@ file can go through the exact walk a download does. This increment exposes it as PHARN_DEBUG=1 dumps the original error as every fetching command does; without it, the one PHARN_DEBUG hint. - anything else (an fs error writing the temp tree) → `CliError.failure(err)` likewise. - pass → clack `intro('pharn verify-archive')`, `log.success(': files listed in pharn-install.json, all - present and matching their sha256; SKILLS_VERSION ')` (+ `, as expected` with the option), `outro` dim +present and matching their sha256; SKILLS_VERSION ')` (+ `, as expected` with the option), `outro` dim "Nothing was installed; the temporary directory was removed." Ref-free (no tag/sha claims). 8. **No Node-floor gate, no MIN_CLI gate, no lock, no proxy notice**: nothing is installed and nothing fetched. diff --git a/.dev/features/core-387-verify-archive/REGRESSION.md b/.dev/features/core-387-verify-archive/REGRESSION.md new file mode 100644 index 00000000..73c38776 --- /dev/null +++ b/.dev/features/core-387-verify-archive/REGRESSION.md @@ -0,0 +1,29 @@ +# REGRESSION — core-387-verify-archive + +- Base: `f9fa96b0ac`, which is origin/main after #448 (CORE-386) merged. Its tree is identical to the 386 branch tip + `ab300d9b`. The baseline ran there in a detached worktree. The branch was cut from 386 and then merged forward + to main (no rebase). +- Inside: the 26 paths in `regression-report.json`. `check-regress.mjs scope` reported `escaped` empty, so nothing + escaped the plan's declared files. `tests/release-consistency.test.ts` was declared in the plan when the 386 + branch merged in. +- Outside gates: + - the 53 stdlib `*.test.mjs` / `*.test.cjs` files, run with `node --test`; + - `node .dev/floor/validate.mjs .`; + - the full vitest suite (through heavy.sh, `--maxWorkers=2`; at HEAD with `--coverage` and `CI=1`). + +| Gate | base | head | +| -------- | ---- | ---- | +| tests | 1 | 1 | +| validate | 0 | 0 | +| vitest | 0 | 0 | + +`regressions[]`: none. + +`pre_existing[]`: `tests`. It is red at the base too, from `.codex/hooks/set-writes-scope.test.cjs`, which this +change does not touch. + +At HEAD, vitest ran 3,722 tests (1 skipped) against 3,680 at the base. Coverage: 98.59 / 95.77 / 99.08 / 99.07 +(statements / branches / functions / lines). The new and changed source files are fully covered. + +REGRESSIONS: none, meaning no breakage outside the feature that these gates can detect (verdict `no-regressions`, +from `check-regress.mjs`). This certifies only the base→head comparison of these gates. diff --git a/.dev/features/core-387-verify-archive/REVIEW.md b/.dev/features/core-387-verify-archive/REVIEW.md new file mode 100644 index 00000000..c09f1259 --- /dev/null +++ b/.dev/features/core-387-verify-archive/REVIEW.md @@ -0,0 +1,47 @@ +# REVIEW — core-387-verify-archive + +Floor first: `node .dev/floor/validate.mjs .` is GREEN, and `verify-report.json` is `PASS`. Everything below is +advisory. The review applied the four lenses (P0 guarantees, P2 trust, P3 one axis, P7 scope) to the diff against +origin/main. + +```yaml +- type: FINDING + rule_id: P0 + severity: minor + file: 'src/commands/verify-archive.ts:runVerifyArchive (rootless hint)' + problem: 'The rootless hint is chosen by matching the start of the extractor''s message ("tar entry has no path below the archive root"), so a rewording in tar-extract.ts would silently drop the hint.' + evidence: 'Only the hint is lost, never the refusal or the exit code, and the rootless case in tests/commands/verify-archive.test.ts asserts both texts, so a rewording turns the suite red. A typed error code on TarExtractError would be cleaner, but it belongs in a tar-extract change, not here.' +- type: FINDING + rule_id: P0 + severity: minor + file: 'docs/commands/verify-archive.md:Where it differs from an install' + problem: 'A pass is "an install accepts these bytes" only for the shared steps.' + evidence: 'The differences are listed: MIN_CLI is refused where install warns, there is no version comparison, and no project or destination checks run. The guarantee audit in PLAN.md labels the git-archive-vs-codeload equivalence advisory, and live run (c) covers the real codeload shape.' +- type: FINDING + rule_id: P2 + severity: minor + file: 'src/commands/verify-archive.ts' + problem: 'Every user-path interpolation must be escaped.' + evidence: 'The path and the basename are escaped once (escapeUnsafe) and only those values are printed; logError strips on top. A test with ESC in both a missing path and a refused archive name asserts that no raw ESC reaches the output.' +- type: FINDING + rule_id: P2 + severity: minor + file: 'src/lib/skills-version.ts:readSkillsVersion (reused)' + problem: 'For a local archive, a missing SKILLS_VERSION reads "is missing in the fetched repo", which is the wrong word for a local file.' + evidence: 'Cosmetic. It is prefixed by "Archive refused:", and changing the shared message would touch every install path. Left as is.' +- type: FINDING + rule_id: P3 + severity: info + file: 'src/commands/verify-archive.ts' + problem: 'Checked for command->command and step imports.' + evidence: "Imports only lib/. Temp-dir lifecycle stays in repo.ts (the clone-producer eslint rule passes), the release check is shared through assertSkillsVersion, and fetchAt's message is byte-identical." +- type: FINDING + rule_id: P7 + severity: info + file: 'src/lib/cli-args.ts' + problem: 'No --json, as decided at GATE 1.' + evidence: 'CI gates on the exit code; --json is refused for verify-archive by the existing per-command option table.' +``` + +There are no blocking findings. The tests file `tests/release-consistency.test.ts` gains `v0.21.6` in KNOWN_TAGS: +that tag now exists (#448 was released), and the `[0.22.0]` link compares from it. diff --git a/.dev/features/core-387-verify-archive/SHIP.md b/.dev/features/core-387-verify-archive/SHIP.md new file mode 100644 index 00000000..3dc61bb2 --- /dev/null +++ b/.dev/features/core-387-verify-archive/SHIP.md @@ -0,0 +1,25 @@ +# SHIP — core-387-verify-archive (Linear CORE-387, epic CORE-380) + +Stages, in order: `/pharn-dev-plan` → GATE 1 → `/pharn-dev-grill` → `/pharn-dev-build` → `/pharn-dev-regress` → +`/pharn-dev-verify` → `/pharn-dev-review` → GATE 2. + +- **GATE 1**, plan acceptance: approved by the epic lead as a **model decision made under the user's delegation**, + not a human approval. The lead added three things, recorded in PLAN.md "GATE 1 amendments": + - the MIN_CLI validity check and the capability-index build; + - the tag form in the CI docs; + - the CI snippet in the PR body. +- `/pharn-dev-grill`: advisory, 6 findings, all folded into the build ([GRILL.md](GRILL.md)). +- `/pharn-dev-build`: `node .dev/floor/validate.mjs .` exit **0**. +- `/pharn-dev-regress`: `regression-report.json` `.verdict` = **`no-regressions`**. Base `f9fa96b0ac` (origin/main + after #448), `pre_existing: ["tests"]` ([REGRESSION.md](REGRESSION.md)). +- `/pharn-dev-verify`: `verify-report.json` `.verdict` = **`PASS`**. The gates were test, validate, lint, + format:check, lint:md, typecheck and build. The live Done-when runs are in [VERIFY.md](VERIFY.md). +- `/pharn-dev-review`: [REVIEW.md](REVIEW.md), advisory, no blocking findings. +- **GATE 2**, the post-review decision: per the lead's standing instruction (a model decision under the user's + delegation), the PR is opened. It is never merged here; the merge belongs to the lead. + +Base history: the branch was cut from `feat/core-386-unpack-listed-paths-only` and merged forward. After #448 +merged, origin/main was merged in, never rebased. + +Chain ran; the named floor verdicts are as shown. This is NOT a judgment that the increment is good or wise; that is +the human's call at the post-review gate. diff --git a/.dev/features/core-387-verify-archive/VERIFY.md b/.dev/features/core-387-verify-archive/VERIFY.md new file mode 100644 index 00000000..9b5ade8b --- /dev/null +++ b/.dev/features/core-387-verify-archive/VERIFY.md @@ -0,0 +1,33 @@ +# VERIFY — core-387-verify-archive + +At HEAD (the feature merged forward onto origin/main `f9fa96b0`): every floor gate exited 0, and +`check-verify.mjs` returned `PASS`. + +| Gate | exit | +| ------------ | ---- | +| test | 0 | +| validate | 0 | +| lint | 0 | +| format:check | 0 | +| lint:md | 0 | +| typecheck | 0 | +| build | 0 | + +There are no committed eval pairs, so no `structural:*` gate ran. Registered verifiers: 0 (`count-verifiers.mjs`), +so no advisory annotations. + +## Live Done-when (bundle `node dist/index.js`, outside the gates) + +`$S` is the session scratchpad (`…/scratchpad/live`). + +| Case | Archive | Result | +| ---- | -------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | +| (a) | `git -C pharn-oss archive --prefix=pharn-oss/ --format=tar.gz` of `origin/main` (a2cacaef), with `--expect-version 7.25.5` | exit 0, "616 files … 35 capabilities; SKILLS_VERSION 7.25.5, as expected; MIN_CLI 0.14.0." | +| (b) | (a) extracted, `pharn/CONSTITUTION.md` altered, repacked with ustar `tar` | exit 1, "declares a sha256 for pharn/CONSTITUTION.md that its bytes do not match" | +| (c) | the real codeload `refs/tags/v7.25.5` tarball, with `--expect-version 7.25.5` | exit 0, the same summary | +| (c') | (c) with `--expect-version 7.25.6` | exit 1, "it ships SKILLS_VERSION 7.25.5, not 7.25.6 (--expect-version)" | +| (d) | plain `git archive --format=tar.gz` of `origin/main` (no prefix) | exit 1, "tar entry has no path below the archive root: MIN_CLI. … Re-create it with `git archive --prefix=pharn-oss/ …`" | + +No `pharn-verify-*` directory was left in `$TMPDIR` after these runs. + +VERIFY: PASS on the floor gates. This verdict covers only those gates and the live runs listed here. diff --git a/.dev/features/core-387-verify-archive/regression-report.json b/.dev/features/core-387-verify-archive/regression-report.json new file mode 100644 index 00000000..f67b6449 --- /dev/null +++ b/.dev/features/core-387-verify-archive/regression-report.json @@ -0,0 +1,48 @@ +{ + "base": "f9fa96b0ac", + "inside": [ + ".dev/features/core-387-verify-archive/GRILL.md", + ".dev/features/core-387-verify-archive/PLAN.md", + "AGENTS.md", + "CHANGELOG.md", + "CLAUDE.md", + "README.md", + "docs/README.md", + "docs/architecture.md", + "docs/commands/verify-archive.md", + "docs/contributing.md", + "docs/troubleshooting.md", + "package-lock.json", + "package.json", + "src/commands/verify-archive.ts", + "src/index.ts", + "src/lib/cli-args.ts", + "src/lib/repo.ts", + "src/lib/skills-version.ts", + "tests/cli-args.test.ts", + "tests/commands/verify-archive.test.ts", + "tests/dist-smoke.test.ts", + "tests/index.test.ts", + "tests/release-consistency.test.ts", + "tests/repo.test.ts", + "tests/skills-version.test.ts", + "tests/support/tar-fixture.ts" + ], + "outside_gates": { + "tests": { + "base": 1, + "head": 1 + }, + "validate": { + "base": 0, + "head": 0 + }, + "vitest": { + "base": 0, + "head": 0 + } + }, + "regressions": [], + "pre_existing": ["tests"], + "verdict": "no-regressions" +} diff --git a/.dev/features/core-387-verify-archive/verify-report.json b/.dev/features/core-387-verify-archive/verify-report.json new file mode 100644 index 00000000..c7729620 --- /dev/null +++ b/.dev/features/core-387-verify-archive/verify-report.json @@ -0,0 +1,14 @@ +{ + "feature": "core-387-verify-archive", + "gates": { + "build": 0, + "format:check": 0, + "lint": 0, + "lint:md": 0, + "test": 0, + "typecheck": 0, + "validate": 0 + }, + "verdict": "PASS", + "failing_gates": [] +} From 09aa347f026effe5eda2720a57b4279e74e1ae87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Galarowicz?= Date: Wed, 25 Nov 2026 18:01:00 +0100 Subject: [PATCH 8/8] test(verify-archive): run the FIFO case unskipped, cover the non-refusal failure (CORE-387) Co-Authored-By: Claude Opus 5.5 --- tests/commands/verify-archive.test.ts | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/tests/commands/verify-archive.test.ts b/tests/commands/verify-archive.test.ts index 6043c318..4c437561 100644 --- a/tests/commands/verify-archive.test.ts +++ b/tests/commands/verify-archive.test.ts @@ -242,15 +242,23 @@ describe('pharn verify-archive — the input path', () => { expect(errors()).toContain('is not a regular file'); }); - it.skipIf(process.platform === 'win32')( - 'a FIFO is refused without waiting on it', - async () => { - const fifo = join(proj(), 'pipe.tar.gz'); - execFileSync('mkfifo', [fifo]); - expect(await verify(fifo)).toBe(1); - expect(errors()).toContain('is not a regular file'); - }, - ); + // POSIX-only, as tests/bounded-read.test.ts's FIFO case: the gates run on + // ubuntu only. + it('a FIFO is refused without waiting on it', async () => { + const fifo = join(proj(), 'pipe.tar.gz'); + execFileSync('mkfifo', [fifo]); + expect(await verify(fifo)).toBe(1); + expect(errors()).toContain('is not a regular file'); + }); + + it('a failure that is not a refusal (no temp dir can be made) is reported with the PHARN_DEBUG hint', async () => { + const file = archiveFile(manifestTree(VERSION)); + vi.stubEnv('TMPDIR', join(proj(), 'no-such-dir')); + expect(await verify(file)).toBe(1); + expect(errors()).not.toContain('refused'); + expect(errors()).toMatch(/ENOENT/); + expect(logs('info')).toContain(PHARN_DEBUG_HINT); + }); it('a file over the 32 MiB download cap', async () => { const big = join(proj(), 'big.tar.gz');