From 5d288e2e83ddb33f8773ba35ecfc3145733887dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Galarowicz?= Date: Tue, 17 Nov 2026 13:14:46 +0100 Subject: [PATCH 1/2] =?UTF-8?q?docs(security,roadmap):=20match=20the=20cod?= =?UTF-8?q?e=20=E2=80=94=20release=20default,=20pharn/=20layout,=20uninsta?= =?UTF-8?q?ll=20(C4.4,=20CORE-177)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SECURITY.md: the verified release is the default channel and `main` the opt-in; everything installs under pharn/ and .claude/ (pharn/.lock, pharn/.backup/); the capability index comes from pharn-install.json, not frontmatter; every fetch is fetchCapped with a withDeadline hard deadline; a record key becomes a path only for orphan reads and uninstall. docs/roadmap.md: add the `pharn uninstall` and `--ref` rows; the lock and backup rows name uninstall (and init); the TTY row matches init/update/ uninstall --yes; the update row follows the recorded channel. THREAT-MODEL.md and LIMITS.md follow via the human-applied patch. Co-Authored-By: Claude Opus 5.5 --- SECURITY.md | 12 ++++++------ docs/roadmap.md | 10 ++++++---- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/SECURITY.md b/SECURITY.md index 62ba9b19..826a2ad7 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -4,7 +4,7 @@ Taking security seriously is part of PHARN, not an afterthought. `pharn` is the ## What `pharn` is, and its security surface -This repository **is `pharn`** — an ESM-only Node CLI (`"type": "module"`, NodeNext, `engines.node >= 24.2.0`) that detects a project's **archetype(s)**, downloads `pharn-dev/pharn-oss` as a tarball from `codeload.github.com` and extracts it into a temp directory with its own reader (`src/lib/tar-extract.ts`), derives the capability index from that tree's frontmatter, copies the resolved capabilities plus fixed product surfaces into the user's project — the `.claude/` command/hook surfaces, the mirrored capability dirs (`pharn-pipeline/grillers/`, `pharn-review/`), and the trusted docs / `pharn-contracts/` / `.dev/floor/` product surfaces at the project root — and writes `pharn.config.json` and `pharn.records.json`. Under the current `pharn` layout the capability dirs, contracts, `pharn-core`, the floor (`pharn/floor/`, **not** `pharn/.dev/floor/`), `CONSTITUTION.md` and `ARCHITECTURE.md` move under `pharn/`, while `THREAT-MODEL.md`, `LIMITS.md`, `features/README.md` and `.claude/` stay at the project root. There is **no fetch, unpack, or cache dependency**: `pharn` spawns no `git` binary and keeps no tarball cache, so every fetch is a fresh download into a fresh temp directory, removed on success, cancel and error alike. There is no module catalog, no `manifest.json` fetch, and no wizard questionnaire. It has a small, thin dependency set — **two** runtime dependencies (`@clack/prompts`, `picocolors`) — no bundled runtime services, and no telemetry. Its security-relevant surface is exactly the two things that cross a trust boundary: **remote input** (the pharn-oss tarball and its extraction, the lightweight `SKILLS_VERSION` / commit-SHA fetches, and every name read from the untrusted tree) and **file-system writes** (everything it copies into the project — the `.claude/` surfaces, the mirrored capability dirs, the root/`pharn/` product surfaces, and upstream's Apache-2.0 `LICENSE` at the one deliberate source-differs-from-destination mapping, `pharn/LICENSE` or `PHARN-LICENSE` — plus the `pharn.config.json`, `pharn.records.json`, `.pharn.lock` and `.pharn-backup//` files it writes). See `THREAT-MODEL.md` for the trust-boundary map — its §2 describes this fetch boundary in full — and `CLAUDE.md` for the command architecture. +This repository **is `pharn`** — an ESM-only Node CLI (`"type": "module"`, NodeNext, `engines.node >= 24.2.0`) that detects a project's **archetype(s)**, downloads `pharn-dev/pharn-oss` as a tarball from `codeload.github.com` and extracts it into a temp directory with its own reader (`src/lib/tar-extract.ts`), takes the install set and the capability index from that tree's `pharn-install.json` (a tree without one is refused, and every file it declares is held to its sha256 before anything is written — `src/lib/upstream-manifest.ts`), copies the resolved capabilities plus fixed product surfaces into the user's project, and writes `pharn.config.json` and `pharn.records.json`. Everything it installs lands under two roots: `pharn/` (the capability dirs `pharn/pharn-pipeline/grillers/` and `pharn/pharn-review/`, `pharn/pharn-contracts/`, `pharn/pharn-core/`, the floor at `pharn/floor/`, the trusted docs `pharn/CONSTITUTION.md`, `pharn/ARCHITECTURE.md`, `pharn/THREAT-MODEL.md` and `pharn/LIMITS.md`, and `pharn/features/README.md`) and `.claude/` (the `pharn-*` commands, hooks and agents, and `.claude/settings.json` only when the project has none). `isPharnOwnedPath` (`src/lib/install-surfaces.ts`) holds every manifest destination to those two roots. There is **no fetch, unpack, or cache dependency**: `pharn` spawns no `git` binary and keeps no tarball cache, so every fetch is a fresh download into a fresh temp directory, removed on success, cancel and error alike. There is no module catalog, no `manifest.json` fetch, and no wizard questionnaire. It has a small, thin dependency set — **two** runtime dependencies (`@clack/prompts`, `picocolors`) — no bundled runtime services, and no telemetry. Its security-relevant surface is exactly the two things that cross a trust boundary: **remote input** (the pharn-oss tarball and its extraction, the lightweight release, commit-SHA and `SKILLS_VERSION` fetches, and every name read from the untrusted tree) and **file-system writes** (everything it copies into the project — the `.claude/` surfaces, the `pharn/` capability dirs and product surfaces, and upstream's Apache-2.0 `LICENSE` at the one deliberate source-differs-from-destination mapping, `pharn/LICENSE` — plus the `pharn.config.json`, `pharn.records.json`, `pharn/.lock` and `pharn/.backup//` files it writes, and the lines it appends to the project's `.gitignore` and `.prettierignore`). See `THREAT-MODEL.md` for the trust-boundary map — its §2 describes this fetch boundary in full — and `CLAUDE.md` for the command architecture. The CLI's security model is **deterministic, not model-driven**: it never asks an AI to decide what is safe. Every value that arrives from the network or the fetched tree is validated against strict regex/enum allowlists (`src/lib/validate.ts`), rejected for `..` and control characters, and every copy is confined with a `safeJoin` guard plus symlink walks over the destination at the write sites (`src/lib/install-capabilities.ts`) so nothing can escape its intended target — checks that hold regardless of what the fetched content says. Preserve that shape: a security fix that relies on "the content will be well-behaved" is not a fix. @@ -53,15 +53,15 @@ 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/capability-index.ts` — the regex/enum allowlists active in the archetype flow (`CAPABILITY_NAME_RE`, `COPY_FILENAME_RE`, `VERSION_RE`, the `role`/`applies` enums via `assertRole`/`assertAppliesToken`), the `..` checks, control-character rejection (`assertSafeString`), or the network guards on the lightweight fetches (`fetchRemoteSkillsVersion` in `src/lib/skills-version.ts`: `redirect: 'error'`, 8s timeout, 256 KB body cap; `fetchCommitSha` in `src/lib/repo.ts`: `redirect: 'error'`, 8s timeout). The repo download itself (`fetchRepo` in `src/lib/repo.ts`) carries the **same three guards, separately sized**: `redirect: 'error'`, an `AbortController` timeout (`CLONE_TIMEOUT_MS`, 60 s — sized to cover a streamed multi-megabyte body rather than a one-line response), and a body cap (`MAX_ARCHIVE_BYTES`, 32 MB) enforced as a **running count 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). +- **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. - **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 `SKILLS_VERSION` or commit-metadata fetches (the `fetch()` calls above use `redirect: 'error'`; report ways around it). -- **Supply-chain** issues in how pharn-oss is fetched — the default `main` channel's one commit-SHA resolve and the SHA-pinned `codeload.github.com` tarball download it feeds (`src/lib/repo.ts`), **including 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 in the resolution of the repo coordinates (`src/lib/constants.ts`), or the opt-in verified-release resolve (`--ref latest`; `src/lib/release.ts`: the latest release's tag, the tag's commit, and the check that the fetched tree's `SKILLS_VERSION` equals the tag; it fails closed and never floats). 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 (malicious capability frontmatter, symlink-planted paths, or unexpected directory entries) that leads the CLI to write outside the project or copy unintended content. +- **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. - 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 is **never** path-joined) 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 outside the project, signal an unintended process, or defeat the fail-closed stamp check. +- **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. - **Control-character or escape-sequence injection** into terminal output from upstream names — `src/lib/unknown-capabilities.ts` strips them before display; report ways past it. ### Out of scope diff --git a/docs/roadmap.md b/docs/roadmap.md index 43122f5f..16d2d206 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -14,18 +14,20 @@ What the latest release does; the [CHANGELOG](../CHANGELOG.md) says which versio | Copy the canonical `CONSTITUTION.md` verbatim + the other trusted docs, upstream's `LICENSE` and `pharn/features/README.md`; write `pharn.config.json` (`pharnVersion`, `skillsVersion`, `repo`, `commit`, `installedAt`, archetypes, capabilities, layout, `models`) and `pharn.records.json` | Shipped | | `pharn add ` — add one capability to an existing project | Shipped | | `pharn remove ` — remove an installed capability (no clone, no network) | Shipped | -| `pharn update` — re-resolve recorded archetypes and re-fetch capabilities at the latest version | Shipped | +| `pharn update` — re-resolve recorded archetypes and re-fetch capabilities from the channel the install records (the newest verified release, or `main`'s tip) | Shipped | | `pharn list` — read-only inventory of installed archetypes + capabilities (`--json`) | Shipped | +| `pharn uninstall` — delete the PHARN files pharn can prove it wrote and nobody changed (offline; edited and unrecorded files are kept and listed; `--yes`) | Shipped | | `pharn status` — read-only version + capability-drift report (modified/missing/unreadable PHARN-owned files; `--strict`, `--no-drift`) | Shipped | | `pharn.records.json` — a sha256 of every installed file, so `update` can tell pharn's bytes from your edits | Shipped | | Orphaned-file detection — `update` and `status` name the files upstream stopped shipping that are still in your project (`ORPHANED` note, `orphans` in `--json`); nothing is deleted | Shipped | -| Drift-safe `update` — per-file decisions, `--force` with `pharn/.backup//` (also written by `add` and `remove`) | Shipped | -| Single-writer lock (`pharn/.lock`) for `init`/`add`/`remove`/`update`; `list`/`status` never take it | Shipped | +| Drift-safe `update` — per-file decisions, `--force` with `pharn/.backup//` (also written by `init`, `add`, `remove` and `uninstall`) | Shipped | +| Single-writer lock (`pharn/.lock`) for `init`/`add`/`remove`/`update`/`uninstall`; `list`/`status` never take it | Shipped | | `MIN_CLI` forward-compatibility gate — refuses cleanly when upstream needs a newer CLI | Shipped | | Mixed-version warning — a `pharn` older than the config's recorded `pharnVersion` (major.minor) warns on stderr before it writes, and still writes ([support policy](support-policy.md)) | Shipped | | Proxy-environment notice — Node's `fetch` reads no proxy variable unless `NODE_USE_ENV_PROXY=1`, so a configured one is reported as used or unused | Shipped | | Per-command option allowlist — an option a command does not take exits 1 instead of being ignored | Shipped | -| Interactive-only `init`/`update` (exit 1 off a TTY; `update --yes` for CI) + the capability picker for bare `add`/`remove` | Shipped | +| No prompt off a TTY — `init`, `update`, `uninstall` and the bare `add`/`remove` capability picker exit 1 instead of waiting; `update --yes` and `uninstall --yes` skip the confirmation, and `init --yes` is below | Shipped | +| `--ref latest\|main` — `init` installs from the newest verified pharn-oss release by default (refusing when it cannot be resolved) or from `main`'s tip; the channel is recorded, `update`/`add`/`status` follow it, and `update --ref` switches it | Shipped | | `init --dry-run [--json]` (a preview that writes nothing) and `init --yes` (a prompt-free install that refuses wherever it would overwrite a file) | Shipped | | `seam` block left to pharn-oss: never written or validated, carried verbatim by every command | Shipped | | pharn-oss's `models` block — copied by `init`, kept or upgraded by `update`, shown resolved per stage by `status` | Shipped | From 76a1814fee701dc78ab9be0e8f8c44121fa444b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Galarowicz?= Date: Tue, 17 Nov 2026 13:41:50 +0100 Subject: [PATCH 2/2] =?UTF-8?q?docs(threat-model,limits):=20match=20the=20?= =?UTF-8?q?code=20=E2=80=94=20release=20default,=20withDeadline,=2024.2=20?= =?UTF-8?q?floor=20(C4.4,=20CORE-177)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit THREAT-MODEL.md: the verified release is the default channel; every fetch is fetchCapped with the withDeadline hard deadline; the proxy text follows the 24.2.0 floor; the table names the release resolve; §3.1 drops `modules`; §4c cites functions instead of line numbers. LIMITS.md: §1a pharn-install.json + isPharnOwnedPath, files in pharn/ and .claude/; §1b/§3a the release resolve is the default; §1c archetypes and capabilities; §1d names instead of line numbers; §3a the 24.2.0 floor's proxy opt-in; §3e the structural break is an unreadable pharn-install.json. Applied by a maintainer from the reviewed patch script. Co-Authored-By: Claude Opus 5.5 --- LIMITS.md | 53 +++++++++++++++++++++++++------------------- THREAT-MODEL.md | 59 ++++++++++++++++++++++++++++--------------------- 2 files changed, 64 insertions(+), 48 deletions(-) diff --git a/LIMITS.md b/LIMITS.md index b3ea05f5..989a0324 100644 --- a/LIMITS.md +++ b/LIMITS.md @@ -21,18 +21,21 @@ a guarantee. ### 1a. pharn validates placement, not content The floor contains **where** fetched files land (`safeJoin`) and validates their **paths + schema** -— it does **not** vet the **semantic content** of the PHARN methodology it copies. A `module.json` -with perfectly safe paths can still install methodology whose body is whatever the upstream shipped. +— it does **not** vet the **semantic content** of the PHARN methodology it copies. A +`pharn-install.json` with perfectly safe paths and matching sha256s can still install methodology +whose body is whatever the upstream shipped. - **Struck claim:** "`pharn init` installed it, so the methodology is safe." -- **True statement:** pharn guarantees the files landed in `.claude/` without escaping; content +- **True statement:** pharn guarantees the files landed in `pharn/` and `.claude/` without escaping; content trust is **provenance** (`pharn-dev/pharn-oss`) + the **user's review**. -- **Backstop (floor):** `INSTALL_PATH_RE` + `safeJoin` bound a hostile module to content **inside** - `.claude/`, never an arbitrary-path write. +- **Backstop (floor):** `isPharnOwnedPath` (`src/lib/install-surfaces.ts`) + `safeJoin` + the + destination symlink walk bound a hostile manifest to content **inside** `pharn/` and pharn's own + `.claude/` entries, never an arbitrary-path write. ### 1b. Trust in the remote is provenance, not cryptographic -pharn records a `commit` SHA (best-effort via the GitHub API) but fetches from a mutable remote +pharn records a `commit` SHA (the release tag's commit by default; best-effort on the `main` +channel) but fetches from a mutable remote over HTTPS; it stores **no signature and no upstream-authenticating hash**. The per-file sha256s it does store ([`pharn.records.json`](docs/reference/pharn-records.md)) are taken from the **written file, never from the upstream source** — dest-side drift baselines, provenance-neutral by @@ -48,28 +51,29 @@ floor. ### 1c. `pharn.config.json` is an advisory record, not a live guarantee -`pharnVersion` / `skillsVersion` / `modules[]` / `installedSkills[]` record what a run **intended** +`pharnVersion` / `skillsVersion` / `archetypes` / `capabilities` record what a run **intended** to install. The file is plain JSON the user can edit, and it is not re-verified against the filesystem except when `status` runs. -- **Struck claim:** "the config says module X is installed, therefore its exact files are present and +- **Struck claim:** "the config says capability X is installed, therefore its exact files are present and unmodified." - **True statement:** the config is a record of **intent**; actual on-disk state is derived **live** - by `pharn status` / `diff` (against `@main` — or the newest verified release on that channel — not - the pinned `commit`). "installed per config" ≠ + by `pharn status` / `diff` (against what the install's channel offers now — the newest verified + release by default, or `@main` — not the pinned `commit`). "installed per config" ≠ "these exact bytes present" until `status` is run. - **Backstop:** `pharn status` re-derives drift live — that is the guarantee, not the config field. ### 1d. `update` / `status` resolve against the channel's current source; `remove` resolves offline -There is no manifest. `update`/`status` re-derive the expected set from a fresh clone of what the +pharn keeps no manifest of the pinned install. `update`/`status` re-derive the expected set from the +`pharn-install.json` of a fresh clone of what the install's channel offers NOW — the newest verified release for an install that records `"ref": "latest"` (what `pharn init` writes by default since 0.15.0), or `@main` for one that records no `ref` (`--ref main`, or an install made before `--ref` existed) — (not the pinned `commit`), while `remove` resolves against **nothing remote** — it is addressed entirely from `pharn.config.json` at the one `pharn` layout (`layoutPaths('pharn')` in `src/commands/remove.ts`; a config recorded at the `flat` layout, removed in v0.21.0, is refused at load). An upstream **rename** lands at two levels: a renamed **capability** surfaces in `update`'s membership report as -`dropped-gone` / `added` (`src/lib/merge-capabilities.ts:79`, `:201`), while a renamed **file inside** a +`dropped-gone` / `added` (`mergeCapabilities`, `src/lib/merge-capabilities.ts`), while a renamed **file inside** a capability is restored at its new path and the old copy is left on disk — `update` never deletes (`src/commands/update.ts:452`). @@ -77,8 +81,8 @@ capability is restored at its new path and the old copy is left on disk — `upd - **True statement:** `update`/`status` reconstruct from the **current** upstream, so a capability renamed since the pin is **reported**, never guessed; `remove` reconstructs from the **recorded config**, deleting the directory the `pharn` layout addresses for that capability - (`src/commands/remove.ts:72`) and pruning that capability's entries from `pharn.records.json` - (`:117`). + (`deleteCapabilityDir`, `src/lib/capability-dir.ts`) and pruning that capability's entries from + `pharn.records.json` (`pruneCapabilityRecords`, `src/commands/remove.ts`). - **Backstop:** every one of those paths is `safeJoin`-contained. Two residuals remain named: a file **orphaned by an upstream rename** — `update` restores the new path, leaves the old one, and reports nothing, bounded to the install subtree and visible to `pharn status`; and `remove`'s delete takes the @@ -104,17 +108,19 @@ State these honestly; do not pretend they are free. ### 3a. Network — and proxy support only through Node's opt-in `init` / `add` / `update` require a network. They require **no `git` binary at all**: pharn resolves -the branch head over the GitHub REST API and downloads the repo tarball from `codeload.github.com`, +the newest verified release (or, on the `main` channel, the branch head) over the GitHub REST API and +downloads the repo tarball from `codeload.github.com`, extracting it itself (`src/lib/tar-extract.ts`). Nothing is spawned. There is no offline or air-gapped install path today. **pharn has no proxy support of its own.** Every network call goes through Node's global `fetch`, which by default reads **no** proxy environment variable — not `https_proxy`, not `HTTPS_PROXY`, not -`no_proxy`. Node 22.21+ and 24+ can opt in with `NODE_USE_ENV_PROXY=1` (22.21+ and 24.5+ also accept -`--use-env-proxy`, for example through `NODE_OPTIONS`); Node's `fetch` then reads `https_proxy`, -`HTTPS_PROXY`, `http_proxy`, `HTTP_PROXY`, in that order, and honours `NO_PROXY`. Node 20, 21, -22.0–22.20 and 23 have no opt-in: there, in a network where direct egress is blocked, `pharn` cannot -fetch, and setting a proxy variable will not change that. The exact rules are in +`no_proxy`. Every Node at or above pharn's floor (24.2.0, `engines.node`) can opt in with +`NODE_USE_ENV_PROXY=1` (24.5+ also accepts `--use-env-proxy`, for example through `NODE_OPTIONS`); +Node's `fetch` then reads `https_proxy`, `HTTPS_PROXY`, `http_proxy`, `HTTP_PROXY`, in that order, +and honours `NO_PROXY`. `init` and `update` refuse to run below the floor; `add` and `status` still +run there, and on Node 20, 21, 22.0–22.20 or 23, which have no opt-in, they cannot fetch where +direct egress is blocked, whatever proxy variable is set. The exact rules are in `docs/troubleshooting.md` → "Proxy environment variables". This is a **regression for one group of users**, and it is named here rather than left to be @@ -165,7 +171,7 @@ waits for a verified release, and resolves its commit through the tag ref itself capability grammar it parses is closed (`src/lib/validate.ts`, frozen enums), and that is deliberate — the fail-closed posture is the security property (P2). -What is **bounded**: a per-capability grammar violation no longer aborts the parse. `parseCapabilityIndex` +What is **bounded**: an `applies` token this CLI does not know no longer aborts the parse. `parseCapabilityIndex` tolerates-and-reports — the offending capability is skipped, named at every call site, kept out of `resolveCapabilities`, out of `installCapabilities`, out of the install manifest, and therefore out of `update`'s write path; a recorded entry for it is **frozen**, not dropped. So the blast radius of a @@ -178,8 +184,9 @@ than the installed CLI ever refuses; absent / unreadable / malformed imposes no lever cannot itself become the outage. What is **NOT closed**: a **structural** break still hard-fails every released CLI until upstream -reverts or the user upgrades — a relocated or renamed capability subtree throws -(`Capability subtree "…" is missing in the fetched repo.`), because a clone whose shape the CLI cannot +reverts or the user upgrades — a `pharn-install.json` this CLI cannot read (a new `schemaVersion` or +layout, or a capability name, `role` or `dir` outside the grammar) refuses the whole tree +(`readUpstreamManifest`, `src/lib/upstream-manifest.ts`), because a clone whose shape the CLI cannot address at all is not "one unknown capability". There is no version pinning, no mirror, and no rollback lever on the consumer side (see §3c). Two coordination steps live **upstream**, not here: pharn-oss shipping a `MIN_CLI`, and gating its own merges on the **released** CLI's parser. Named, diff --git a/THREAT-MODEL.md b/THREAT-MODEL.md index bf964c0a..7e0be992 100644 --- a/THREAT-MODEL.md +++ b/THREAT-MODEL.md @@ -58,8 +58,9 @@ surface: 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 content. -6. **Stale / renamed upstream paths** — `status`/`update`/`diff` resolve against the newest verified - `@main` HEAD (or release, on the `--ref latest` channel), not the pinned `commit`, so an upstream rename can orphan or re-target a path. +6. **Stale / renamed upstream paths** — `status`/`update`/`diff` resolve against what the install's + channel offers now — the newest verified release by default, or `@main` HEAD on the `main` + channel — not the pinned `commit`, so an upstream rename can orphan or re-target a path. 7. **The archive itself** — entry paths, types, sizes and header fields are attacker-controlled bytes, read by pharn's own extractor (see the fetch boundary below). 8. **The install manifest (`pharn-install.json`)** — untrusted JSON inside the same tarball: a @@ -69,7 +70,7 @@ surface: resolution (C3.1, `src/lib/release.ts`), the same download, no second fetch path — so its `sha256` values bind the files to the manifest, never the manifest to pharn-oss (§4a). -**The fetch boundary, in pharn's own code.** The clone is one REST resolve followed by a direct +**The fetch boundary, in pharn's own code.** The clone is a REST resolve (two requests for a release, one for `main`) followed by a direct download of `https://codeload.github.com/pharn-dev/pharn-oss/tar.gz/`, extracted by `src/lib/tar-extract.ts`. There is **no fetch dependency**: pharn imports nothing to obtain, cache, or unpack the tree, spawns no `git` binary, and keeps no tarball cache. That matters for this @@ -78,16 +79,21 @@ had to describe _measured properties of a dependency_, which a version bump coul pharn test noticing. Every property below is now pharn's own code, and every one of them is pinned by a test. -- **One resolve, one download.** `fetchCommitSha` reads the branch head over the GitHub REST API through its - full ref (`commits/refs/heads/main`, so a tag named `main` cannot answer); the +- **One resolve, one download.** The default channel resolves the newest release's tag, then that + tag's commit through its full ref (`commits/refs/tags/`, so a branch named like the tag cannot + answer; `src/lib/release.ts`); the `main` channel's `fetchCommitSha` reads the branch head through + its full ref (`commits/refs/heads/main`, so a tag named `main` cannot answer). Either way the `COMMIT_RE`-validated result is the last URL segment **and** the recorded `commit`. Nothing re-resolves the ref. The previous path resolved it a second time inside the dependency and matched the result only against **current ref tips**, so an upstream push landing between the two failed the whole command. codeload serves any commit, tip or not, so a mid-fetch push now yields exactly the pinned SHA. -- **The network floor applies to the clone, not just the metadata fetches.** `redirect: 'error'`, an - `AbortController` timeout cleared in `finally`, and a body cap — the same three guards - `lib/skills-version.ts` carries. The clone's timeout is separately sized (60 s, not 8 s) because it +- **The network floor applies to the clone, not just the metadata fetches.** Every fetch goes through + one bounded GET (`fetchCapped`, `src/lib/fetch-capped.ts`): `redirect: 'error'`, a deadline over the + request and the body read, and a body cap. The deadline is `withDeadline` (`src/lib/deadline.ts`): + it aborts the request **and** rejects through a `Promise.race`, so the command returns at the + 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 @@ -145,11 +151,11 @@ a test. filename. Caches already on disk are inert but **not** removed — pharn deletes nothing outside the user's project; `docs/troubleshooting.md` says where they live and how to size them. - **No proxy support of pharn's own, stated as a limit.** Node's global `fetch` reads **no** proxy - environment variable by default. Node 22.21+ and 24+ read them once the user opts in - (`NODE_USE_ENV_PROXY=1`; `--use-env-proxy` on 22.21+ and 24.5+), and then honour `NO_PROXY`; Node - 20, 21, 22.0–22.20 and 23 have no opt-in. The previous dependency read `process.env.https_proxy` + environment variable by default. Every Node at or above pharn's floor (24.2.0, `engines.node`) + reads them once the user opts in (`NODE_USE_ENV_PROXY=1`, or `--use-env-proxy` on 24.5+), and then + honours `NO_PROXY`. The previous dependency read `process.env.https_proxy` itself — only that lowercase spelling, and never `no_proxy`. So a user behind a corporate proxy - who succeeded before now fails unless they opt in, and on a Node without the opt-in they cannot; + who succeeded before now fails unless they opt in; `pharn update` and `status --no-drift` already behaved the same, since those were always plain `fetch`. It is a named limit (`LIMITS.md` §3a), and every network-bearing command says which case applies before the fetch rather than letting it surface as an unexplained timeout. @@ -169,9 +175,9 @@ Every answer reduces to the floor (P0) or is labeled a limit (`LIMITS.md`). | 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 | | 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 commit-SHA resolve | 8s timeout + `redirect: 'error'` + `MAX_SHA_BYTES` (1 KiB) body cap | `fetchCommitSha` (`src/lib/repo.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`) | -| redirect to attacker host | `redirect: 'error'` on every pharn `fetch()` call, the tarball included | `fetchRemoteSkillsVersion`, `fetchCommitSha`, `downloadArchive` | +| 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`) | | 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`) | @@ -188,8 +194,9 @@ Beyond the copied methodology (Surface A), pharn writes one structured file of i own. `writePharnConfig` (`src/lib/pharn-config.ts`) serializes the config with `JSON.stringify` to a **fixed, non-attacker-influenced path** — `configPath(cwd)` = `resolve(cwd, 'pharn.config.json')` — so the sink location is never derived from -remote input. The record mixes local-origin fields (`pharnVersion`, `repo`, -`installedAt`, `modules`, the `seam` default) with four network-derived ones, and +remote input. The record mixes local-origin fields (`pharnVersion`, `repo`, `ref`, +`installedAt`, `updatedAt`, `archetypes`, `layout`; `seam` belongs to pharn-oss and is only carried +through from the existing file) with four network-derived ones, and **each network-derived field is validated at its ingest boundary before it can reach this write** (P0/P2): `skillsVersion` against `VERSION_RE` (`readSkillsVersion`, `src/lib/skills-version.ts`); every `capabilities[]` name @@ -244,8 +251,8 @@ not a "the source repo is ours" assumption (P0). which is why `fetchRepo` removes the temp dir on the error path rather than returning it. - **A named regression, not a hidden one.** Node's global `fetch` reads no proxy environment variable by default, so a user behind a corporate proxy who succeeded via the old dependency's - own `https_proxy` read now fails unless they opt in (`NODE_USE_ENV_PROXY=1`, Node 22.21+ and - 24+; no opt-in exists on Node 20, 21, 22.0–22.20 or 23). `LIMITS.md` §3a carries it, and every + own `https_proxy` read now fails unless they opt in (`NODE_USE_ENV_PROXY=1`, which every Node + at or above the 24.2.0 floor accepts). `LIMITS.md` §3a carries it, and every network-bearing command says which case applies before the fetch. - **4c. The stored content-hashes cover only what pharn wrote.** pharn does keep @@ -254,13 +261,15 @@ not a "the source repo is ours" assumption (P0). recorded hash holds bytes pharn wrote, whatever the stamp — CORE-161) — and `update` gates every file on it. The residual is its **coverage**, not its absence. Where the store is absent or unreadable, the two directions differ: a file **present** on disk becomes `unrecorded`/`unverifiable` and `update` **skips** it rather - than overwrite (`src/lib/update-decision.ts:64-65`), while a file **absent** from disk is **restored** - regardless of the store (row 1, `:60`). A file already byte-identical to upstream is never skipped even - with no records, and its record is refreshed — so a degraded install partially heals, but never for the - differing files an upgrade needs to touch (`:67-71`). `status` is not record-based at all: its drift is - a **live comparison against `@main` (or the newest release)** via `readDiskState` (`src/lib/diff.ts:79`, `src/lib/apply-update.ts:44`), - which classifies a symlink or non-regular path as `unreadable` rather than hashing it - (`apply-update.ts:57-61`). _Backstop:_ drift **is** detected (`pharn status`, live), and bytes pharn + than overwrite (rows 5 and 6 of the decision table in `decideFileAction`, `src/lib/update-decision.ts`), + while a file **absent** from disk is **restored** regardless of the store (row 1). A file already + byte-identical to upstream is never skipped even with no records, and its record is refreshed (row 2) + — so a degraded install partially heals, but never for the differing files an upgrade needs to touch. + `status` is not record-based at all: its drift is a **live comparison against what the install's + channel offers now (the newest verified release by default, or `@main`)** via + `diffInstalledCapabilities` (`src/lib/diff.ts`), whose project side, `readDiskState` + (`src/lib/apply-update.ts`), classifies a symlinked path or a non-regular file as `unreadable` rather + than hashing it. _Backstop:_ drift **is** detected (`pharn status`, live), and bytes pharn cannot explain are **skipped, never overwritten** without `--force`. - **4d. The single-writer lock does not exclude a pharn older than 0.14.0.** The lock is `pharn/.lock` (beside the backups in `pharn/.backup/`, `src/lib/project-lock.ts`). pharn 0.13.0 and older lock a