Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
107 changes: 94 additions & 13 deletions docs/securityscan.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,21 +13,27 @@ 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.
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
observation, though accurate as a description, is not a weakness to close.

The package's central security claims were verified and held up:

Expand All @@ -53,6 +59,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).
Expand Down Expand Up @@ -96,6 +106,12 @@ 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), 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).

**Evidence.** Validation is `Number.isNaN(Date.parse(text))`. `Date.parse`
Expand All @@ -117,6 +133,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:
Expand All @@ -140,6 +160,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).

Expand All @@ -165,6 +189,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).
Expand All @@ -187,6 +219,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.

Expand All @@ -213,6 +252,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
Expand All @@ -222,6 +265,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 <tarball>` resolves
`@pegma/spine` and `@pegma/storage-core` from the registry (exact-pinned, so
Expand All @@ -233,6 +288,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
Expand All @@ -243,6 +310,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.
Expand Down Expand Up @@ -285,3 +360,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.
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion packages/audit/package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
111 changes: 111 additions & 0 deletions packages/audit/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
decodeAuditEvent,
defineAudit,
encodeAuditEvent,
type AuditDetails,
type AuditEvent,
} from "./index.js";

Expand Down Expand Up @@ -127,6 +128,88 @@ 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/,
);
// `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",
);
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<string, unknown>)["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", () => {
Expand Down Expand Up @@ -371,4 +454,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);
});
});
Loading
Loading