From 0ff574a233c9021dd9ab5eb92dd2c497b4347a18 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Wed, 29 Jul 2026 20:34:13 -0400 Subject: [PATCH 1/2] Resolve security scan findings Seven of the ten findings in docs/securityscan.md were valid and are fixed; three are disputed in the report with reasoning. Library: - `requireDetails` copies with `Object.defineProperty`, so a detail key that names an inherited accessor (`__proto__`, which `JSON.parse` produces as an own property) is stored instead of swallowed by the setter. - `requireTimestamp` requires an ISO 8601 date-time shape as well as a parsable instant, so `Date.parse`-only formats no longer enter a permanent record. - `decodeAuditEvent` requires stored fields to be non-empty strings and the stored actor kind to be exactly `principal` or `system`, rather than coercing a corrupt row into a plausible-looking event. - `sweep` validates a supplied `limit` as a positive safe integer, so `NaN` can no longer leave a permanent deletion unbounded. Release tooling: - `validateRepository` refuses a published manifest defining `preinstall`, `install`, or `postinstall`; `package.json` is always packed, so the `files` allowlist does not constrain them. - `runNpm` requires `npm_execpath` and never builds a shell command line. The removed Windows fallback passed unescaped arguments through `cmd.exe`. - The publish workflow verifies the npm CLI tarball against a reviewed sha512 before installing the tool that packs and publishes the release. Bumps @pegma/audit to 0.1.1. No public type or signature changes: validation is stricter, and every value the codec itself writes still round-trips. Co-Authored-By: Claude Fable 5 --- .github/workflows/publish.yml | 14 +++- docs/securityscan.md | 101 +++++++++++++++++++++++++---- package-lock.json | 2 +- packages/audit/package.json | 2 +- packages/audit/src/index.test.ts | 89 +++++++++++++++++++++++++ packages/audit/src/index.ts | 107 ++++++++++++++++++++++++++----- scripts/release-packages.d.mts | 12 ++++ scripts/release-packages.mjs | 91 +++++++++++++++++++++++--- tests/release-packages.test.ts | 36 +++++++++++ 9 files changed, 412 insertions(+), 42 deletions(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index ac4326c..9bd1d37 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -53,8 +53,20 @@ jobs: registry-url: https://registry.npmjs.org package-manager-cache: false + # The CLI that packs and publishes the release is fetched from the + # registry, so its bytes are verified against the reviewed integrity in + # scripts/release-packages.mjs before it is installed and trusted. - name: Use the reviewed npm release - run: npm install --global npm@11.18.0 + shell: bash + env: + REVIEWED_NPM_VERSION: 11.18.0 + run: | + tarball="${RUNNER_TEMP}/npm-${REVIEWED_NPM_VERSION}.tgz" + curl --fail --silent --show-error --location --proto '=https' --tlsv1.2 \ + --output "${tarball}" \ + "https://registry.npmjs.org/npm/-/npm-${REVIEWED_NPM_VERSION}.tgz" + node scripts/release-packages.mjs verify-npm --tarball "${tarball}" + npm install --global "${tarball}" - name: Install dependencies run: npm ci diff --git a/docs/securityscan.md b/docs/securityscan.md index b046fc1..240f887 100644 --- a/docs/securityscan.md +++ b/docs/securityscan.md @@ -13,22 +13,26 @@ Findings were appended as they were discovered during the scan. ## Summary -| # | Severity | Finding | -|---|----------|---------| -| 1 | Low | `__proto__` keys in `details` are silently dropped by the codec | -| 2 | Low | `occurredAt` accepts non-ISO-8601 strings despite the `IsoTimestamp` contract | -| 3 | Low | `decodeAuditEvent` decodes malformed records into plausible events instead of failing | -| 4 | Low | Release validation requires `prepack` but does not forbid other install-time lifecycle scripts | -| 5 | Low | Windows fallback in `runNpm` uses `shell: true` with unescaped arguments | -| 6 | Low | Release workflow installs `npm@11.18.0` without an integrity pin | -| 7 | Informational | `sweep` `limit` of `NaN` bypasses the positive-number guard | -| 8 | Informational | Smoke test installs sibling dependencies from the registry without a lockfile | -| 9 | Informational | Unbounded in-memory partition reads in `history` and `sweep`; unbounded `details` size | -| 10 | Informational | `exports` target recursion in release validation is unbounded | +| # | Severity | Finding | Disposition | +| --- | ------------- | ---------------------------------------------------------------------------------------------- | ----------- | +| 1 | Low | `__proto__` keys in `details` are silently dropped by the codec | ✅ Resolved | +| 2 | Low | `occurredAt` accepts non-ISO-8601 strings despite the `IsoTimestamp` contract | ✅ Resolved | +| 3 | Low | `decodeAuditEvent` decodes malformed records into plausible events instead of failing | ✅ Resolved | +| 4 | Low | Release validation requires `prepack` but does not forbid other install-time lifecycle scripts | ✅ Resolved | +| 5 | Low | Windows fallback in `runNpm` uses `shell: true` with unescaped arguments | ✅ Resolved | +| 6 | Low | Release workflow installs `npm@11.18.0` without an integrity pin | ✅ Resolved | +| 7 | Informational | `sweep` `limit` of `NaN` bypasses the positive-number guard | ✅ Resolved | +| 8 | Informational | Smoke test installs sibling dependencies from the registry without a lockfile | ⚠️ Disputed | +| 9 | Informational | Unbounded in-memory partition reads in `history` and `sweep`; unbounded `details` size | ⚠️ Disputed | +| 10 | Informational | `exports` target recursion in release validation is unbounded | ⚠️ Disputed | **No high, medium, or critical vulnerabilities were found.** `npm audit` reports zero known vulnerabilities across 103 dependencies. All 24 tests pass. +Every finding was re-examined against the code on 2026-07-29 and dispositioned +below: seven were fixed, three were disputed. Each disputed item says why the +observation, though accurate as a description, is not a weakness to close. + The package's central security claims were verified and held up: - Record ids derive from the event id alone; `KEY_ESCAPES` escaping is @@ -53,6 +57,10 @@ The package's central security claims were verified and held up: ### 1. Low — `__proto__` keys in `details` are silently dropped +✅ Resolved 2026-07-29 — `requireDetails` builds its copy with +`Object.defineProperty` instead of plain assignment, so a key that names an +inherited accessor is stored rather than swallowed by the setter. + **File:** `packages/audit/src/index.ts` — `requireDetails` (lines 189-209), reached from both `auditEvent` (encode path) and `decodeDetails` (decode path, lines 264-280). @@ -96,6 +104,10 @@ regardless of name. ### 2. Low — `occurredAt` accepts non-ISO-8601 strings +✅ Resolved 2026-07-29 — `requireTimestamp` now requires an ISO 8601 date-time +shape (UTC designator or numeric offset) in addition to a parsable instant, so +`March 3, 2020` and `2026-07-26` are refused. + **File:** `packages/audit/src/index.ts` — `requireTimestamp` (lines 155-161). **Evidence.** Validation is `Number.isNaN(Date.parse(text))`. `Date.parse` @@ -117,6 +129,10 @@ only compensated. ### 3. Low — `decodeAuditEvent` decodes malformed records into plausible events +✅ Resolved 2026-07-29 — stored fields must be non-empty strings and the stored +actor kind must be exactly `principal` or `system`; a malformed row now raises +`AuditError` instead of being coerced with `String(...)`. + **File:** `packages/audit/src/index.ts` — `decodeAuditEvent` (lines 283-301). **Evidence.** Two lenient coercions: @@ -140,6 +156,10 @@ id fields with `AuditError` instead of coercing. ### 4. Low — Release validation requires `prepack` but does not forbid other lifecycle scripts +✅ Resolved 2026-07-29 — `validateRepository` refuses a published manifest that +defines `preinstall`, `install`, or `postinstall`, via a `findInstallTimeScript` +helper with its own unit test. + **File:** `scripts/release-packages.mjs` — `validateRepository` (lines 177-185). @@ -165,6 +185,14 @@ script that runs at install time on consumers (`preinstall`, `install`, ### 5. Low — Windows fallback in `runNpm` uses `shell: true` with unescaped arguments +✅ Resolved 2026-07-29 — the fallback is removed rather than quoted: `runNpm` +requires `npm_execpath` (which every release entry point, being an npm script, +always sets) and never builds a shell command line. Note that the alternative +recommendation is not implementable — since the fix for CVE-2024-27980, Node +refuses to spawn `npm.cmd` without `shell: true` (`EINVAL`), and Node now +deprecates passing arguments alongside `shell: true` (DEP0190) for exactly the +reason given here. + **File:** `scripts/release-packages.mjs` — `runNpm` (lines 61-69), callers pass operator-supplied paths (`--root` → `packageDirectory`, `--output`, tarball paths). @@ -187,6 +215,13 @@ require `npm_execpath`. ### 6. Low — Release workflow installs `npm@11.18.0` without an integrity pin +✅ Resolved 2026-07-29 — the workflow downloads the npm CLI tarball over HTTPS +and verifies its `sha512` against `REVIEWED_NPM_INTEGRITY` in +`scripts/release-packages.mjs` (`release-packages.mjs verify-npm`) before +installing it, so a substituted tarball fails before it can build anything. A +test asserts the workflow uses the reviewed constants and no longer installs the +bare registry spec. + **File:** `.github/workflows/publish.yml` line 57 (`npm install --global npm@11.18.0`); `scripts/release-packages.mjs` lines 21, 157-161, 403-415. @@ -213,6 +248,10 @@ after install, or a corepack-style pinned installer). ### 7. Informational — `sweep` `limit` of `NaN` bypasses the guard +✅ Resolved 2026-07-29 — `sweep` validates a supplied `limit` as a positive safe +integer rather than by comparison, so `NaN` (and a fraction) is refused and the +bound on a permanent deletion always holds. + **File:** `packages/audit/src/index.ts` lines 493-496. `NaN <= 0` is `false`, so `limit: NaN` passes validation; `deleted >= NaN` is always `false`, so the limit never binds and one call sweeps the entire partition. Caller-supplied @@ -222,6 +261,18 @@ one call, and a caller bug silently removes the bound. A ### 8. Informational — Smoke test installs sibling dependencies without a lockfile +⚠️ Disputed 2026-07-29 — not a valid finding: the description is accurate but +there is no weakness to close, and the report itself recommends no change. The +prepare job holds no secrets and no OIDC token, `--ignore-scripts` blocks +install-time hooks, and — checked against the code — `prepareRelease` hashes the +tarball _before_ `smokeTestTarball` runs while `verifyPreparedManifest` re-hashes +it in the publish job, so code executed during the smoke test cannot alter what +is published without failing the release. A lockfile would also not add a +guarantee: the sibling versions are already exact-pinned in +`packages/audit/package.json`, and committing a second lockfile for a throwaway +temporary project would duplicate that pin without narrowing the trust in the +registry that `npm ci` already places one step earlier. + **File:** `scripts/release-packages.mjs` — `smokeTestTarball` (lines 285-319). The temp project has no lockfile; `npm install ` resolves `@pegma/spine` and `@pegma/storage-core` from the registry (exact-pinned, so @@ -233,6 +284,18 @@ awareness that the smoke test is a registry-trust point. ### 9. Informational — Unbounded in-memory reads and `details` size +⚠️ Disputed 2026-07-29 — not a valid finding: neither quantity is +attacker-amplified, and neither can be bounded here without breaking a stated +design rule. `history` and `sweep` read one partition because storage-core's +`list` is explicitly unordered with no server-side filter or pagination; +bounding a read would require a secondary index, which is a second collection +with its own atomicity problem — the one change `AGENTS.md` says the design +cannot absorb. The partition name and the `details` contents are both chosen by +the trusted caller, and `SECURITY.md` already assigns partition choice, read +authorization, and `details` hygiene to the host. `AGENTS.md` documents +one-partition-at-a-time reads as a known gap, so this is a design consequence +already written down rather than an oversight. + **File:** `packages/audit/src/index.ts` — `history` (lines 481-487) and `sweep` (lines 502-525) load an entire partition into memory; `details` has no size bound before `JSON.stringify` (line 260). Both are caller-controlled @@ -243,6 +306,14 @@ oversized `details` bags are stored and returned whole to every reader. ### 10. Informational — Unbounded recursion in `exportTargets` +⚠️ Disputed 2026-07-29 — not a valid finding: `exportTargets` only ever walks +the `exports` object of `packages/audit/package.json`, a repository-controlled +file authored by maintainers and reviewed before merge, so no untrusted input +reaches it. A stack overflow would abort validation and fail the release closed, +which is the direction a release check should fail. The report classifies this as +a robustness note rather than a vulnerability, and adding a depth cap would add a +branch guarding against a manifest nobody can supply. + **File:** `scripts/release-packages.mjs` lines 82-88. A deeply nested `exports` object could overflow the stack during validation. The manifest is repository-controlled and validated in CI, so this is a robustness note only. @@ -285,3 +356,9 @@ repository-controlled and validated in CI, so this is a robustness note only. ## Test baseline `npm test` at scan time: 24/24 passing (Node 24.18.0). + +After the 2026-07-29 fixes: 30/30 passing (Node 24.18.0). The six added tests +cover the `__proto__` detail key round trip, a timestamp only `Date.parse` would +accept, a stored row that cannot be read faithfully, a `sweep` limit that would +not bound the deletion, install-time lifecycle scripts, and the npm CLI +integrity pin. diff --git a/package-lock.json b/package-lock.json index 95b12aa..3ded0ae 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1732,7 +1732,7 @@ }, "packages/audit": { "name": "@pegma/audit", - "version": "0.1.0", + "version": "0.1.1", "license": "MIT", "dependencies": { "@pegma/spine": "0.1.1", diff --git a/packages/audit/package.json b/packages/audit/package.json index 7aac0fc..a9e5942 100644 --- a/packages/audit/package.json +++ b/packages/audit/package.json @@ -1,6 +1,6 @@ { "name": "@pegma/audit", - "version": "0.1.0", + "version": "0.1.1", "description": "Append-only audit records that commit in the caller's own transaction.", "license": "MIT", "type": "module", diff --git a/packages/audit/src/index.test.ts b/packages/audit/src/index.test.ts index 407f3e7..df94679 100644 --- a/packages/audit/src/index.test.ts +++ b/packages/audit/src/index.test.ts @@ -7,6 +7,7 @@ import { decodeAuditEvent, defineAudit, encodeAuditEvent, + type AuditDetails, type AuditEvent, } from "./index.js"; @@ -127,6 +128,66 @@ describe("the event shape", () => { event({ details: { nested: {} as unknown as string } }), ).toThrow(/details.nested/); }); + + it("rejects a timestamp only Date.parse would accept", () => { + // `Date.parse` accepts implementation-defined formats, so it cannot be the + // whole check: the value is kept forever exactly as it was submitted, and + // a consumer parsing strictly as ISO 8601 would reject it. + expect(Date.parse("March 3, 2020")).not.toBeNaN(); + expect(() => event({ occurredAt: "March 3, 2020" })).toThrow( + /ISO 8601 timestamp/, + ); + expect(() => event({ occurredAt: "2026-07-26" })).toThrow( + /ISO 8601 timestamp/, + ); + expect(() => event({ occurredAt: "2026-13-01T00:00:00Z" })).toThrow( + /ISO 8601 timestamp/, + ); + expect(event({ occurredAt: "2026-07-26T12:00:00Z" }).occurredAt).toBe( + "2026-07-26T12:00:00Z", + ); + expect(event({ occurredAt: "2026-07-26T14:00:00+02:00" }).occurredAt).toBe( + "2026-07-26T14:00:00+02:00", + ); + }); + + it("keeps a details key that names an inherited accessor", () => { + // `__proto__` is an own property when it arrives from `JSON.parse`, which + // is how a stored record comes back. Copying with plain assignment calls + // the inherited setter instead of storing it, so the key disappears and the + // event no longer round-trips as the bytes that were submitted. + const details = JSON.parse( + '{"__proto__":"inherited","safe":2}', + ) as AuditDetails; + const original = event({ details }); + + expect(Object.keys(original.details ?? {})).toEqual(["__proto__", "safe"]); + expect( + Object.keys(decodeAuditEvent(encodeAuditEvent(original)).details ?? {}), + ).toEqual(["__proto__", "safe"]); + // The transient copy never becomes anyone's prototype. + expect(Object.getPrototypeOf(original.details)).toBe(Object.prototype); + expect(({} as Record)["safe"]).toBeUndefined(); + }); + + it("refuses a stored row it cannot read faithfully", () => { + const stored = encodeAuditEvent(event()); + + // An unrecognized kind used to decode as a principal, inventing an actor. + expect(() => + decodeAuditEvent({ ...stored, auditActorKind: "operator" }), + ).toThrow(/actor kind/); + // `String(null)` used to pass the non-empty-string check as `"null"`. + expect(() => + decodeAuditEvent({ ...stored, auditActorPrincipalId: null }), + ).toThrow(/actor principal id/); + expect(() => decodeAuditEvent({ ...stored, auditSubject: null })).toThrow( + /stored audit subject/, + ); + expect(() => decodeAuditEvent({ ...stored, auditEventId: 7 })).toThrow( + /stored audit id/, + ); + }); }); describe("an audit action inside the caller's transaction", () => { @@ -371,4 +432,32 @@ describe("the retention sweep", () => { audit.sweep(collection, PARTITION, { before: "last week" }), ).rejects.toThrow(/ISO 8601 timestamp/); }); + + it("rejects a limit that would not bound the deletion", async () => { + const collection = await seed(records()); + + // `NaN` passed a `<= 0` guard and then never bound against `deleted`, so + // a caller's arithmetic mistake swept the whole partition instead of one + // page of it. This is a permanent deletion, so it fails closed. + await expect( + audit.sweep(collection, PARTITION, { + before: "2026-06-01T00:00:00.000Z", + limit: Number.NaN, + }), + ).rejects.toThrow(/positive safe integer/); + await expect( + audit.sweep(collection, PARTITION, { + before: "2026-06-01T00:00:00.000Z", + limit: 1.5, + }), + ).rejects.toThrow(/positive safe integer/); + await expect( + audit.sweep(collection, PARTITION, { + before: "2026-06-01T00:00:00.000Z", + limit: 0, + }), + ).rejects.toThrow(/positive safe integer/); + // A refused sweep deleted nothing. + expect(await audit.history(collection, PARTITION)).toHaveLength(3); + }); }); diff --git a/packages/audit/src/index.ts b/packages/audit/src/index.ts index b3a81b2..1cd892a 100644 --- a/packages/audit/src/index.ts +++ b/packages/audit/src/index.ts @@ -152,9 +152,22 @@ function requireText(value: unknown, field: string): string { return value; } +/** + * ISO 8601 calendar date and time, with a UTC designator or a numeric offset. + * + * `Date.parse` is not this check on its own: it also accepts + * implementation-defined formats such as `March 3, 2020`, which would be kept + * verbatim in a record nothing in this package can correct afterwards, and + * which a consumer parsing strictly as ISO 8601 would reject. Both checks run, + * so a value that is the right shape but not a real instant, such as + * `2026-13-01T00:00:00Z`, is still refused. + */ +const ISO_TIMESTAMP = + /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/u; + function requireTimestamp(value: unknown, field: string): IsoTimestamp { const text = requireText(value, field); - if (Number.isNaN(Date.parse(text))) { + if (!ISO_TIMESTAMP.test(text) || Number.isNaN(Date.parse(text))) { throw new AuditError(`${field} must be an ISO 8601 timestamp`); } return text; @@ -203,7 +216,18 @@ function requireDetails(details: AuditDetails): AuditDetails { if (typeof value === "number" && !Number.isFinite(value)) { throw new AuditError(`details.${key} must be a finite number`); } - copied[key] = value; + // Not `copied[key] = value`: for a key that names an inherited accessor, + // notably `__proto__`, plain assignment calls the setter instead of + // storing the detail, so the key vanishes and the event round-trips as + // different bytes than were submitted. `JSON.parse` produces exactly that + // key as an own property, so the decode path reaches this too. Defining + // the property keeps every own key, whatever it is called. + Object.defineProperty(copied, key, { + value, + enumerable: true, + writable: true, + configurable: true, + }); } return Object.freeze(copied); } @@ -279,22 +303,59 @@ function decodeDetails(value: unknown): AuditDetails | undefined { return requireDetails(parsed as AuditDetails); } +/** + * Reads a stored field that {@link encodeAuditEvent} always writes as a string. + * + * Deliberately not `String(...)`: coercion turns a missing or null field into + * the strings `"undefined"` and `"null"`, which then pass the non-empty-string + * check and produce a plausible-looking event out of a corrupt row. An audit + * record is read to establish what happened, so failing is the only honest + * answer. + */ +function requireStoredText(value: unknown, field: string): string { + if (typeof value !== "string" || value.length === 0) { + throw new AuditError(`stored audit ${field} must be a non-empty string`); + } + return value; +} + +function decodeActor(record: StoredRecord): AuditActor { + const kind = record[ACTOR_KIND_FIELD]; + if (kind === "principal") { + return { + kind: "principal", + principalId: requireStoredText( + record[ACTOR_PRINCIPAL_FIELD], + "actor principal id", + ), + }; + } + if (kind === "system") { + return { + kind: "system", + systemId: requireStoredText( + record[ACTOR_SYSTEM_FIELD], + "actor system id", + ), + }; + } + // Anything else is a row this package did not write, or one that was + // changed underneath it. Treating an unrecognized kind as a principal + // invents an actor, which is the one thing an audit reader must not be + // handed. + throw new AuditError("stored audit actor kind must be principal or system"); +} + /** Reads an event back out of a stored row written by {@link encodeAuditEvent}. */ export function decodeAuditEvent(record: StoredRecord): AuditEvent { const sequence = record[SEQUENCE_FIELD]; const details = decodeDetails(record[DETAILS_FIELD]); return auditEvent({ - id: String(record[ID_FIELD]), - occurredAt: String(record[OCCURRED_AT_FIELD]), - actor: - record[ACTOR_KIND_FIELD] === "system" - ? { kind: "system", systemId: String(record[ACTOR_SYSTEM_FIELD]) } - : { - kind: "principal", - principalId: String(record[ACTOR_PRINCIPAL_FIELD]), - }, - action: String(record[ACTION_FIELD]), - subject: String(record[SUBJECT_FIELD]), + id: requireStoredText(record[ID_FIELD], "id"), + occurredAt: requireStoredText(record[OCCURRED_AT_FIELD], "occurredAt"), + actor: decodeActor(record), + action: requireStoredText(record[ACTION_FIELD], "action"), + subject: requireStoredText(record[SUBJECT_FIELD], "subject"), ...(sequence == null ? {} : { sequence: Number(sequence) }), ...(details === undefined ? {} : { details }), }); @@ -346,7 +407,11 @@ export interface AuditSweepOptions { readonly before: IsoTimestamp; /** Sweep only events concerning this subject. */ readonly subject?: string; - /** Stop after this many deletions, so one call has a bounded cost. */ + /** + * Stop after this many deletions, so one call has a bounded cost. + * + * A positive safe integer. Omit it to sweep everything expired in one call. + */ readonly limit?: number; } @@ -490,10 +555,18 @@ export function defineAudit( const before = Date.parse( requireTimestamp(options.before, "options.before"), ); - const limit = options.limit ?? Number.POSITIVE_INFINITY; - if (limit <= 0) { - throw new AuditError("options.limit must be a positive number"); + // Validated as a count rather than by comparison: `NaN <= 0` is false, + // so a comparison guard passes `NaN` through, and `deleted >= NaN` is + // also false, so the limit would never bind and one call would delete + // the whole partition. `limit` is the only bound on a permanent + // deletion, and it has to hold against a caller's arithmetic mistake. + if ( + options.limit !== undefined && + (!Number.isSafeInteger(options.limit) || options.limit <= 0) + ) { + throw new AuditError("options.limit must be a positive safe integer"); } + const limit = options.limit ?? Number.POSITIVE_INFINITY; let examined = 0; let deleted = 0; diff --git a/scripts/release-packages.d.mts b/scripts/release-packages.d.mts index 309a4ac..cb8e11b 100644 --- a/scripts/release-packages.d.mts +++ b/scripts/release-packages.d.mts @@ -16,6 +16,7 @@ export interface ValidationOptions { export interface ReleaseCommandOptions extends ValidationOptions { readonly manifest?: string; readonly output?: string; + readonly tarball?: string; } export interface PublicPackageManifest { @@ -33,6 +34,17 @@ export interface ValidationResult { export const RELEASE_PACKAGES: readonly ReleasePackageDefinition[]; +export const REVIEWED_NPM: { + readonly version: string; + readonly integrity: string; +}; + +export function findInstallTimeScript( + scripts: unknown, +): "preinstall" | "install" | "postinstall" | null; + +export function verifyReviewedNpmTarball(bytes: Uint8Array | string): string; + export function parseArguments( arguments_: readonly string[], ): ReleaseCommandOptions; diff --git a/scripts/release-packages.mjs b/scripts/release-packages.mjs index 0cdf288..dd5ff55 100644 --- a/scripts/release-packages.mjs +++ b/scripts/release-packages.mjs @@ -19,10 +19,36 @@ const PACKAGE = { }; const REPOSITORY_URL = "git+https://github.com/pegma-dev/audit.git"; const REVIEWED_NPM_VERSION = "11.18.0"; +/** + * Subresource integrity of the reviewed npm CLI tarball. + * + * The CLI that packs and publishes the release is itself fetched from the + * registry at release time, so pinning only its version leaves the bytes to + * whatever the registry serves. Everything downstream is verified with + * metadata this same tool produced, which a trojaned CLI would produce + * consistently. Recorded from `npm view npm@11.18.0 dist.integrity`. + */ +const REVIEWED_NPM_INTEGRITY = + "sha512-T67M4L5wNm0cZ7EBLErcEkY1SmzEW/WJ+SADBzsFUY1UdAPfFHXFQtZ6SEXiK0+vzXysCvAsepbMaBTwnrAD+w=="; const STABLE_SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u; +/** + * Lifecycle scripts npm runs on a consumer's machine during `npm install`. + * + * `package.json` is always packed, so the `files` allowlist places no + * constraint on these: one of them in the published manifest is arbitrary code + * execution on every downstream host. Build-time hooks such as `prepack` run + * here instead, where they belong. + */ +const INSTALL_TIME_SCRIPTS = ["preinstall", "install", "postinstall"]; export const RELEASE_PACKAGES = [PACKAGE]; +/** What the release workflow must install, so a test can hold it to this. */ +export const REVIEWED_NPM = { + version: REVIEWED_NPM_VERSION, + integrity: REVIEWED_NPM_INTEGRITY, +}; + function fail(message) { throw new Error(message); } @@ -60,12 +86,19 @@ function run(command, arguments_, options = {}) { function runNpm(arguments_, options = {}) { const npmExecPath = process.env.npm_execpath; - return npmExecPath === undefined - ? run(process.platform === "win32" ? "npm.cmd" : "npm", arguments_, { - ...options, - shell: process.platform === "win32", - }) - : run(process.execPath, [npmExecPath, ...arguments_], options); + if (npmExecPath === undefined) { + // The removed fallback reached `npm.cmd` through `cmd.exe`, which is the + // only way to spawn it on Windows, and a shell concatenates arguments + // without escaping them, so a path containing `&`, `%`, `^`, or a quote + // became part of the command line. Nothing here needs to build a command + // line: every release entry point is an npm script, and npm always sets + // this, so requiring it removes the shell instead of trying to quote for + // one. + fail( + "release commands must be run through npm (npm_execpath is not set); use npm run release:check, release:pack, or release:publish", + ); + } + return run(process.execPath, [npmExecPath, ...arguments_], options); } function gitCommand() { @@ -79,6 +112,28 @@ function hashTarball(bytes) { }; } +/** + * Confirms a downloaded npm CLI tarball is the reviewed one, before it is + * installed and used to build the release. + */ +export function verifyReviewedNpmTarball(bytes) { + const { integrity } = hashTarball(bytes); + if (!safeEqual(integrity, REVIEWED_NPM_INTEGRITY)) { + fail( + `npm@${REVIEWED_NPM_VERSION} tarball integrity ${integrity} does not match the reviewed ${REVIEWED_NPM_INTEGRITY}`, + ); + } + return integrity; +} + +/** The install-time lifecycle script a manifest defines, or null. */ +export function findInstallTimeScript(scripts) { + if (scripts === null || typeof scripts !== "object") return null; + return ( + INSTALL_TIME_SCRIPTS.find((name) => scripts[name] !== undefined) ?? null + ); +} + function exportTargets(value) { if (typeof value === "string") return [value]; if (value !== null && typeof value === "object" && !Array.isArray(value)) { @@ -183,6 +238,12 @@ export async function validateRepository(options = {}) { ) { fail(`${PACKAGE.name} has an unsafe package allowlist or prepack`); } + const installScript = findInstallTimeScript(manifest.scripts); + if (installScript !== null) { + fail( + `${PACKAGE.name} must not define the install-time script ${installScript}`, + ); + } const targets = exportTargets(manifest.exports); if ( targets.length === 0 || @@ -542,9 +603,11 @@ export function parseArguments(arguments_) { ? "output" : argument === "--manifest" ? "manifest" - : argument === "--expected-release-commit" - ? "expectedReleaseCommit" - : null; + : argument === "--tarball" + ? "tarball" + : argument === "--expected-release-commit" + ? "expectedReleaseCommit" + : null; if (key === null || arguments_[index + 1] === undefined) { fail(`unknown or incomplete argument: ${argument}`); } @@ -561,6 +624,14 @@ function defaultRoot() { async function main() { const [command, ...arguments_] = process.argv.slice(2); const options = parseArguments(arguments_); + if (command === "verify-npm") { + if (options.tarball === undefined) fail("--tarball is required"); + verifyReviewedNpmTarball(await readFile(resolve(options.tarball))); + process.stdout.write( + `Verified the reviewed npm@${REVIEWED_NPM_VERSION} tarball.\n`, + ); + return; + } if (command === "check") { await validateRepository(options); process.stdout.write("Release metadata is valid.\n"); @@ -575,7 +646,7 @@ async function main() { await publishPreparedRelease(options); return; } - fail("usage: release-packages.mjs [options]"); + fail("usage: release-packages.mjs [options]"); } const isMain = diff --git a/tests/release-packages.test.ts b/tests/release-packages.test.ts index a23730b..aabc101 100644 --- a/tests/release-packages.test.ts +++ b/tests/release-packages.test.ts @@ -5,10 +5,13 @@ import { join } from "node:path"; import { describe, expect, it } from "vitest"; import { RELEASE_PACKAGES, + REVIEWED_NPM, decidePublication, + findInstallTimeScript, parseArguments, validateReleaseTag, validateRepository, + verifyReviewedNpmTarball, } from "../scripts/release-packages.mjs"; const git = process.platform === "win32" ? "git.exe" : "git"; @@ -44,6 +47,39 @@ describe("release package metadata", () => { await expect(validateRepository()).resolves.toBeDefined(); }); + it("refuses a script that would run on a consumer's install", async () => { + // `package.json` is always packed, so the `files` allowlist does not + // constrain these: one of them in the published manifest is arbitrary code + // execution on every downstream host. + expect(findInstallTimeScript({ prepack: "npm run build" })).toBeNull(); + expect(findInstallTimeScript(undefined)).toBeNull(); + expect(findInstallTimeScript({ preinstall: "node steal.js" })).toBe( + "preinstall", + ); + expect(findInstallTimeScript({ install: "node steal.js" })).toBe("install"); + expect(findInstallTimeScript({ postinstall: "node steal.js" })).toBe( + "postinstall", + ); + // The released manifest itself has none. + const { manifest } = await validateRepository(); + expect(findInstallTimeScript(manifest.scripts)).toBeNull(); + }); + + it("pins the npm CLI that builds the release by integrity", () => { + expect(() => + verifyReviewedNpmTarball(Buffer.from("not the npm CLI")), + ).toThrow("does not match the reviewed"); + const workflow = readFileSync( + join(process.cwd(), ".github", "workflows", "publish.yml"), + "utf8", + ); + expect(workflow).toContain(`REVIEWED_NPM_VERSION: ${REVIEWED_NPM.version}`); + expect(workflow).toContain("verify-npm --tarball"); + // Installing the registry spec directly would trust whatever bytes the + // registry serves for the tool that packs and publishes the release. + expect(workflow).not.toContain(`npm@${REVIEWED_NPM.version}`); + }); + it("requires the release tag to match a public package version", async () => { await expect(validateRepository({ releaseTag: "v9.9.9" })).rejects.toThrow( `release tag must be v${packageVersion}`, From 88f556c463f2ac54dc227f5902cd63317c8569cb Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Wed, 29 Jul 2026 20:40:30 -0400 Subject: [PATCH 2/2] Reject impossible calendar dates in occurredAt Codex review: the shape check accepted a day past the end of its month, and `Date.parse` normalizes rather than refuses one, so `2026-02-30T00:00:00Z` parsed as March 2 and would have been kept forever as a day nothing happened on. Every other out-of-range component already makes `Date.parse` return `NaN`, so only the day-of-month needed the check. Also resolves the contradictory test count in docs/securityscan.md that Copilot flagged: the summary now marks 24/24 as the scan-time baseline and points at the post-fix 30/30 figure. Co-Authored-By: Claude Fable 5 --- docs/securityscan.md | 10 +++++++--- packages/audit/src/index.test.ts | 22 +++++++++++++++++++++ packages/audit/src/index.ts | 33 ++++++++++++++++++++++++++++---- 3 files changed, 58 insertions(+), 7 deletions(-) diff --git a/docs/securityscan.md b/docs/securityscan.md index 240f887..6ad383f 100644 --- a/docs/securityscan.md +++ b/docs/securityscan.md @@ -27,7 +27,9 @@ Findings were appended as they were discovered during the scan. | 10 | Informational | `exports` target recursion in release validation is unbounded | ⚠️ Disputed | **No high, medium, or critical vulnerabilities were found.** `npm audit` -reports zero known vulnerabilities across 103 dependencies. All 24 tests pass. +reports zero known vulnerabilities across 103 dependencies. All 24 tests passed +at scan time; the baseline after the 2026-07-29 fixes is 30/30, recorded under +[Test baseline](#test-baseline). Every finding was re-examined against the code on 2026-07-29 and dispositioned below: seven were fixed, three were disputed. Each disputed item says why the @@ -105,8 +107,10 @@ regardless of name. ### 2. Low — `occurredAt` accepts non-ISO-8601 strings ✅ Resolved 2026-07-29 — `requireTimestamp` now requires an ISO 8601 date-time -shape (UTC designator or numeric offset) in addition to a parsable instant, so -`March 3, 2020` and `2026-07-26` are refused. +shape (UTC designator or numeric offset), a day-of-month that exists in its +month, and a parsable instant, so `March 3, 2020`, `2026-07-26`, and +`2026-02-30T00:00:00Z` (which `Date.parse` silently normalizes to March 2) are +all refused. **File:** `packages/audit/src/index.ts` — `requireTimestamp` (lines 155-161). diff --git a/packages/audit/src/index.test.ts b/packages/audit/src/index.test.ts index df94679..7f4c6b7 100644 --- a/packages/audit/src/index.test.ts +++ b/packages/audit/src/index.test.ts @@ -143,6 +143,28 @@ describe("the event shape", () => { expect(() => event({ occurredAt: "2026-13-01T00:00:00Z" })).toThrow( /ISO 8601 timestamp/, ); + // `Date.parse` normalizes a day past the end of its month instead of + // refusing it, so an impossible date would be kept forever as a day + // nothing happened on. + expect(Date.parse("2026-02-30T00:00:00Z")).not.toBeNaN(); + expect(() => event({ occurredAt: "2026-02-30T00:00:00Z" })).toThrow( + /ISO 8601 timestamp/, + ); + expect(() => event({ occurredAt: "2026-04-31T00:00:00Z" })).toThrow( + /ISO 8601 timestamp/, + ); + expect(() => event({ occurredAt: "2100-02-29T00:00:00Z" })).toThrow( + /ISO 8601 timestamp/, + ); + expect(event({ occurredAt: "2024-02-29T00:00:00Z" }).occurredAt).toBe( + "2024-02-29T00:00:00Z", + ); + expect(event({ occurredAt: "2000-02-29T00:00:00Z" }).occurredAt).toBe( + "2000-02-29T00:00:00Z", + ); + expect(event({ occurredAt: "2026-12-31T23:59:59.999Z" }).occurredAt).toBe( + "2026-12-31T23:59:59.999Z", + ); expect(event({ occurredAt: "2026-07-26T12:00:00Z" }).occurredAt).toBe( "2026-07-26T12:00:00Z", ); diff --git a/packages/audit/src/index.ts b/packages/audit/src/index.ts index 1cd892a..100664a 100644 --- a/packages/audit/src/index.ts +++ b/packages/audit/src/index.ts @@ -158,16 +158,41 @@ function requireText(value: unknown, field: string): string { * `Date.parse` is not this check on its own: it also accepts * implementation-defined formats such as `March 3, 2020`, which would be kept * verbatim in a record nothing in this package can correct afterwards, and - * which a consumer parsing strictly as ISO 8601 would reject. Both checks run, - * so a value that is the right shape but not a real instant, such as - * `2026-13-01T00:00:00Z`, is still refused. + * which a consumer parsing strictly as ISO 8601 would reject. The shape check, + * {@link isRealCalendarDate}, and `Date.parse` all run, so a value that is the + * right shape but not a real instant, such as `2026-13-01T00:00:00Z` or + * `2026-02-30T00:00:00Z`, is still refused. */ const ISO_TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/u; +const DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + +/** + * Whether the date part of an already shape-checked timestamp exists. + * + * The third check `Date.parse` cannot make: a day past the end of its month is + * normalized rather than refused, so `2026-02-30T00:00:00Z` parses as March 2 + * and would be kept forever as a day nothing happened on. Every other + * out-of-range component — month `00`, hour `25`, minute `61`, an offset of + * `+25:00` — does make `Date.parse` return `NaN`, so only the day needs this. + */ +function isRealCalendarDate(text: string): boolean { + const year = Number(text.slice(0, 4)); + const month = Number(text.slice(5, 7)); + const day = Number(text.slice(8, 10)); + const leapYear = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; + const days = month === 2 && leapYear ? 29 : DAYS_IN_MONTH[month - 1]; + return days !== undefined && day <= days; +} + function requireTimestamp(value: unknown, field: string): IsoTimestamp { const text = requireText(value, field); - if (!ISO_TIMESTAMP.test(text) || Number.isNaN(Date.parse(text))) { + if ( + !ISO_TIMESTAMP.test(text) || + !isRealCalendarDate(text) || + Number.isNaN(Date.parse(text)) + ) { throw new AuditError(`${field} must be an ISO 8601 timestamp`); } return text;