Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

fix(ci): break profile taint, drop test race, bound registry probe (#141)

Abdurrahman Fakhrul62cfef27eeb6
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 98293c9e..cd548e4b 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -1,3 +1,61 @@
+## 2026-10-22: CodeQL follow-up — the taint, not the temp path
+
+The previous entry closed the symlink/TOCTOU concern but not `js/http-to-file-access`: the icon
+value still descended from the request into `JSON.stringify` at the write sink. Two honest fixes,
+verified against CodeQL 2.27.3 locally with the same two queries CI runs.
+
+**`js/http-to-file-access` (`lib/auth/account-profile.ts`).** Option 2: the JSON shape is
+unchanged, and the value written is now rebuilt rather than carried. `libraryIcon` validates with
+`LIBRARY_ICON`, then reconstructs `prefix + tint` from the validated capture groups via
+`copyCodeUnits` (now exported from `account-profile-model.ts`) instead of returning `row.value`.
+`imageIcon` already rebuilt `src` from a validated kind prefix plus a fresh `encodeBase64` of a
+copied `Buffer`; the library branch was the one still holding request text. CodeQL reports zero
+results for both `js/http-to-file-access` and `js/file-system-race` on a database built from this
+tree. No suppression comment, no dismissal, no `.github/codeql` filter, no format change.
+
+**`js/file-system-race` (`lib/auth/account-profile.test.ts`).** The staging test used
+`fs.stat(file)` and then `fs.readFile(file)` on the same path. It now opens one read handle and
+takes both the mode from `handle.stat()` and the content from `handle.readFile()`, so there is no
+check-then-use pair on a path. The canary is still asserted byte-identical, the published store
+still parses to the expected profile, the mode is still `0o600`, and the only sibling is the
+pre-planted canary.
+
+**Backward compatibility.** No on-disk format change. Two tests cover old files explicitly:
+`parses a store file written before the library icon type existed` writes a preset-only JSON and an
+image `data:` JSON directly and asserts both still parse; `rebuilds the stored icon from validated
+primitives so client bytes never reach the file unchanged` proves a non-canonical base64 URL is
+stored in its re-encoded form and a kind/magic mismatch is refused with the old bytes untouched.
+
+**Evidence.** `typecheck` 0, `lint` 0, targeted vitest 9/9 (exit 0), `coverage` 836 files /
+5389 tests (exit 0), `check-architecture.mjs` exit 0, `audit:strict` exit 0 printing
+`clean at high/critical`, local CodeQL result count 0.
+
+## 2026-10-22: CI-green fixes — unpredictable atomic profile writes and a bounded, honest registry probe
+
+Two independent failures on `main` (c54422e4), both fixed at the authoritative layer.
+
+**CodeQL #190 — js/http-to-file-access at `lib/auth/account-profile.ts:149`.** `persist()` staged
+the profile at `${file}.${pid}.tmp` and used a non-exclusive `writeFile`, so a pre-planted file or
+symlink at that predictable path could be followed and truncated with client-derived icon bytes.
+The staging name now carries `randomBytes(8)` and the write passes `flag: "wx"` (exclusive create,
+fails instead of following), keeping `mode: 0o600`, the `0o700` mkdir and the atomic `rename`
+publish. A write/publication failure unlinks the temp path best-effort and rethrows as
+`AccountProfileError("invalid")`; `readAccountProfile`/`cleanAccountIcon` and the image allowlist
+are unchanged. This matches the pattern already used by `lib/host/fs-upload.ts`,
+`lib/host/fs-upload-guarded.ts` and `scripts/orca/private-store.mjs`. Regression tests prove the
+old predictable path is never truncated, the store is 0600, no staging siblings survive, and
+concurrent `writeAccountProfile` calls serialize to one untorn profile.
+
+**Verify — `audit: registry timed out after 15s; INCOMPLETE (strict gate failed)`.** The gate is
+`scripts/audit.mjs` (wired as `audit:strict` for CI, `scripts/gates.sh`, `pr-preflight.sh`, and
+`security-ultimate.sh`). Its single 15-second probe turned a cold-runner handshake into a red
+build with no vulnerability to report. It is now 30s per attempt, 3 attempts (first + 2 retries)
+with 2s/4s backoff inside a 90s total budget — worst case still far inside the 30-minute job.
+Exhausting the budget fails closed with `registry unreachable (...)`, which cannot be read as
+"advisories found". A silent registry may reuse prior evidence only when a receipt for this exact
+`bun.lock` digest is under 7 days old; otherwise the job stays red. Exit-code contract is intact
+(0 clean, 1 advisories, 2 incomplete).
+
## 2026-10-22: Updates check the merge before refusing, and the foundation boundary is written down
A dirty or diverged checkout used to get a bare refusal, leaving a user who simply wanted the
@@ -2233,7 +2291,7 @@ both standard MCP and legacy ChatGPT host paths. Toolset: `2026.09.05.1`.
- **Public-sharing security and maintenance audit (2026-09-05):** app `0.2.2` keeps the independently versioned CLI/MCP contracts unchanged. Release and assurance dependency audits now fail closed on unavailable, malformed or incomplete evidence; local developer skips are explicitly labelled, registry diagnostics do not expose raw URLs, and skipped optional scanners cannot produce an unconditional assurance PASS. Removed the dormant Convex deploy tail, fixed shared Git-hook installation and out-of-tree dependency copying for linked worktrees, and added functional regression tests. README now leads with a readable install/features/security overview and collapsible reference detail, preserving generated comparison evidence and public-alpha limits. `test:features` runs each test area in a separate process and distinguishes PASS/PARTIAL/SKIPPED/FAIL. The Forge Docker sandbox and synthetic credential-path fixture activate previously skipped security checks without using real secrets; CI now provisions the same bounded fixtures. Onboarding tests derive the app version from `package.json`; the browser suite follows the actual Activity & Runs UI, checks infrastructure deep-links, and never echoes session-cookie diagnostics. Full-history scanning now requests merge diffs explicitly in CI and the assurance runner; independent scanner outputs remain private; no genuine historical secret was identified by the configured scan, so shared history was not rewritten. Live-service deployment and remote CI status require separate exact-revision evidence and are not inferred from local tests.
- **Rahmanef-aligned MCP widget palette / Block + Page v2 (2026-09-04):** MCP server `1.10.0` / toolset `2026.09.04.7` moves the two canonical ChatGPT resources to `ui://mso/block-v2.html` and `ui://mso/page-v2.html` so hosts do not reuse the old purple CSS cache key. Block and Page now share one visual-token source aligned with `rahmanef.com`: light `#f4f4f7` / `#1c1c1f`, dark `#1b1b20` / `#f2f2f5`, accent `#1f6df0`, Plus Jakarta Sans display copy, Inter body copy, fine separators, and editorial foreground/background primary-action inversion. ChatGPT theme changes propagate through `window.openai.theme` with a color-scheme fallback. Block/Page v1 and the earlier workflow/surface URIs remain readable but unlisted compatibility aliases; the headless workflow and two-surface/security contracts are unchanged.
- **Headless workflows + two-surface MCP UI contract (2026-09-04):** MCP server `1.10.0` / toolset `2026.09.04.6` removes the automatic UI binding from `workflow_start`: orchestration, collision checks, tracing, evidence, and learning continue in the background without consuming the answer with a progress card. ChatGPT now has exactly two canonical MCP App resources: `ui://mso/block-v1.html` through `render_mso_block` for compact validation/action/CRUD input-output, and `ui://mso/page-v1.html` through `render_mso_page` for native operator views plus reviewed development/preview/production embeds. Block buttons send a user-approved follow-up and never execute mutations inside the widget, preserving normal scope, approval, audit, and workflow boundaries. The prior workflow/surface URIs remain non-advertised read aliases, while `workflow_status` and `render_mso_surface` remain app-only compatibility shims for cached clients. The ChatGPT transport profile is 66 tools: 64 model-visible actions (35 read / 17 write / 12 exec) plus two app-only shims; the full catalog is 90. Only Block and Page advertise a resource URI.
-- **Local release audit timeout hardening (2026-09-04):** the tolerant pre-push dependency audit now caps `bun audit --json` at 15 seconds. A registry timeout is reported and skipped only in the local gate, matching its existing network-tolerant policy; CI remains the fail-closed dependency-audit authority. This prevents a slow registry request from holding GitHub's pre-push SSH session open for minutes and failing the otherwise-green release with a transport/SIGPIPE-style exit.
+- **Local release audit timeout hardening (2026-09-04):** the tolerant pre-push dependency audit now caps `bun audit --json` at 15 seconds. A registry timeout is reported and skipped only in the local gate, matching its existing network-tolerant policy; CI remains the fail-closed dependency-audit authority. This prevents a slow registry request from holding GitHub's pre-push SSH session open for minutes and failing the otherwise-green release with a transport/SIGPIPE-style exit. **Superseded 2026-10-22:** the cap is now 30s per attempt with 3 attempts and a 90s total budget, because a single 15s probe made cold CI runners fail with INCOMPLETE despite finding no advisory. See `scripts/audit.mjs`.
- **MCP Apps CSP metadata dedup / Surface v5 (2026-09-04):** MCP server `1.9.4` / toolset `2026.09.04.5` moves all standard widget CSP fields to the preferred `_meta.ui.csp` surface and leaves legacy `openai/widgetCSP` with only `redirect_domains` for `Open in MSO`. Workflow/Surface resources are cache-busted to `workflow-progress-v3` and `surface-v5`; the reviewed Play Together iframe remains exact-origin under `/embed`, so one external-iframe review advisory is expected from `ui.csp.frameDomains`. Scanner-facing Surface metadata explicitly names `/apps/play-together` and has a regression guard against cross-scope app examples.
- **MCP Apps presentation unification / Surface v4 (2026-09-04):** MCP server `1.9.3` / toolset `2026.09.04.4` retires the specialized `project-status-v2`, `project-diff-v2`, and `vps-status-v2` resources. `project_get`, `project_diff`, and `vps_status` are pure data tools again; `ui://mso/surface-v4.html` is the only general-purpose UI and uses the portable MCP Apps `tools/call` bridge for native monitor/project/diff views. `workflow-progress-v2` remains intentionally separate for live workflow polling. Play Together keeps the exact `game.example.com/embed` frame boundary, so the external-iframe review advisory remains expected only for the universal Surface.
- **Cognitive Runtime claim audit / public evidence boundary (2026-09-04):** revalidated source/main/origin and loopback/public production on the latest concurrent baseline, then reran the deterministic Cognitive Runtime/memory gates: routing recall 100%, active-schema reduction 96.6%, typed memory 8/8, P9 6/6 at 200 corrections, P10 lifecycle 8/8, lexical/local-semantic 4/6 vs 3/6, and bounded graph fixture 3/3. Raw P6/P7/P8 artifacts were independently re-hashed and their aggregate arithmetic recomputed; the canonical P7 two-run artifact is `mso-p7-repeat-full-2x9.json` (`a0c12961...`), not the similarly named older `mso-p7-repeat-full-2runs.json`. Canonical P7+P8 yields 5/5 perfect full runs for both MSO and Hermes and the documented 74.7% token / 12.8% average-latency / 34.1% p50 observed deltas on that exact nine-scenario matched corpus. P4/P5 exact tables are downgraded to historical release-reported metrics because this audit could not independently recover raw artifacts matching those exact values. README now removes the stale 29-tool ChatGPT count, removes the unsupported "most complete" positioning superlative, and states explicit no-universal-superiority/no-cost/no-cache/no-OpenClaw boundaries. Tool Forge executable evaluation is documented as fail-closed until its explicit local Docker sandbox image is provisioned; that image was absent during this audit.
diff --git a/lib/auth/account-profile-model.ts b/lib/auth/account-profile-model.ts
index 429ad99c..99460f04 100644
--- a/lib/auth/account-profile-model.ts
+++ b/lib/auth/account-profile-model.ts
@@ -22,7 +22,10 @@ export const DEFAULT_ACCOUNT_PROFILE: AccountProfile = {
icon: { type: "preset", id: "user" },
};
-function copyCodeUnits(value: string): string {
+/** Identity on already-validated input, but returns a fresh string built one
+ * bounded code unit at a time, so a stored value never holds a reference to the
+ * request payload. Shared with `libraryIcon` in account-profile.ts. */
+export function copyCodeUnits(value: string): string {
let name = "";
for (let i = 0; i < value.length; i++) name += String.fromCharCode(value.charCodeAt(i));
return name;
diff --git a/lib/auth/account-profile.test.ts b/lib/auth/account-profile.test.ts
index da6ed77f..ba6cb62b 100644
--- a/lib/auth/account-profile.test.ts
+++ b/lib/auth/account-profile.test.ts
@@ -100,6 +100,38 @@ describe("account profile", () => {
expect(await readAccountProfile()).toEqual(before);
});
+ it("rebuilds the stored icon from validated primitives so client bytes never reach the file unchanged", async () => {
+ // Same 16 decoded bytes, but the last base64 digit carries non-zero unused
+ // bits: a legal encoding that is NOT the canonical one. The store must hold
+ // the re-encoded value, never the request string.
+ const canonicalB64 = png.split(",")[1]!;
+ const nonCanonicalB64 = `${canonicalB64.slice(0, 21)}B==`;
+ expect(nonCanonicalB64).not.toBe(canonicalB64);
+ expect(Buffer.from(nonCanonicalB64, "base64").equals(Buffer.from(canonicalB64, "base64"))).toBe(true);
+ const nonCanonicalUrl = `data:image/png;base64,${nonCanonicalB64}`;
+ await writeAccountProfile({ icon: { type: "image", src: nonCanonicalUrl } });
+ const raw = await fs.readFile(file, "utf8");
+ expect(raw).not.toContain(nonCanonicalUrl);
+ expect(JSON.parse(raw)).toEqual({ name: "Owner", icon: { type: "image", src: png } });
+ // A declared kind that contradicts the validated magic is refused outright and
+ // leaves the previously published store untouched.
+ const mismatched = dataUrl("gif", [...Buffer.from(canonicalB64, "base64")]);
+ await expect(writeAccountProfile({ icon: { type: "image", src: mismatched } })).rejects.toMatchObject({ code: "invalid" });
+ expect(await fs.readFile(file, "utf8")).toBe(raw);
+ });
+
+ it("parses a store file written before the library icon type existed", async () => {
+ // Byte-for-byte shape produced by the first release (preset icon only).
+ await fs.mkdir(dir, { recursive: true });
+ const legacy = JSON.stringify({ name: "Legacy Owner", icon: { type: "preset", id: "star" } });
+ await fs.writeFile(file, legacy, { encoding: "utf8", mode: 0o600 });
+ expect(await readAccountProfile()).toEqual({ name: "Legacy Owner", icon: { type: "preset", id: "star" } });
+ // A pre-library image store also still loads.
+ await fs.writeFile(file, JSON.stringify({ name: "Legacy Owner", icon: { type: "image", src: png } }), { encoding: "utf8", mode: 0o600 });
+ expect(await readAccountProfile()).toEqual({ name: "Legacy Owner", icon: { type: "image", src: png } });
+ expect(await fs.readFile(file, "utf8")).toContain('"type":"image"');
+ });
+
it("fails closed on a corrupt profile instead of replacing it", async () => {
await fs.mkdir(dir, { recursive: true });
await fs.writeFile(file, "{", "utf8");
@@ -107,4 +139,48 @@ describe("account profile", () => {
await expect(writeAccountProfile({ name: "Rahman" })).rejects.toMatchObject({ code: "corrupt" });
expect(await fs.readFile(file, "utf8")).toBe("{");
});
+
+ it("stages through an unpredictable exclusive temp file and publishes mode 0600", async () => {
+ // Predictable staging path (the old `${file}.${pid}.tmp`) is pre-planted as a
+ // canary: the write must never truncate it and must never follow it.
+ const legacyTmp = `${file}.${process.pid}.tmp`;
+ const canary = "planted-by-someone-else";
+ await fs.writeFile(legacyTmp, canary, { encoding: "utf8", mode: 0o600 });
+ await writeAccountProfile({ name: "Rahman" });
+ expect(await fs.readFile(legacyTmp, "utf8")).toBe(canary);
+ expect(await readAccountProfile()).toMatchObject({ name: "Rahman" });
+ // One open handle carries both the mode assertion and the content read, so
+ // the test never stats a path and then reads that path again.
+ const handle = await fs.open(file, "r");
+ let published: string;
+ try {
+ expect((await handle.stat()).mode & 0o777).toBe(0o600);
+ published = await handle.readFile("utf8");
+ } finally {
+ await handle.close();
+ }
+ expect(published).not.toBe(canary);
+ expect(JSON.parse(published)).toMatchObject({ name: "Rahman" });
+ // No staging leftovers: the only sibling is the pre-planted canary.
+ expect((await fs.readdir(dir)).sort()).toEqual(["account.json", `${path.basename(file)}.${process.pid}.tmp`]);
+ });
+
+ it("serializes concurrent writes so the store is never torn", async () => {
+ await writeAccountProfile({ name: "First" });
+ const results = await Promise.all([
+ writeAccountProfile({ name: "Second", icon: { type: "preset", id: "star" } }),
+ writeAccountProfile({ name: "Third", icon: { type: "preset", id: "leaf" } }),
+ ]);
+ expect(results).toHaveLength(2);
+ const onDisk = JSON.parse(await fs.readFile(file, "utf8")) as { name: string; icon: unknown };
+ const valid = [
+ { name: "Second", icon: { type: "preset", id: "star" } },
+ { name: "Third", icon: { type: "preset", id: "leaf" } },
+ ];
+ expect(valid).toContainEqual(onDisk);
+ expect(await readAccountProfile()).toEqual(onDisk);
+ expect((await fs.stat(file)).mode & 0o777).toBe(0o600);
+ // Every concurrent write published atomically: no temp siblings survive.
+ expect((await fs.readdir(dir)).sort()).toEqual(["account.json"]);
+ });
});
diff --git a/lib/auth/account-profile.ts b/lib/auth/account-profile.ts
index 18f02f60..8db83e1a 100644
--- a/lib/auth/account-profile.ts
+++ b/lib/auth/account-profile.ts
@@ -1,9 +1,11 @@
import { expandOwnerStorePath } from "@/lib/owner-store-path.js";
+import { randomBytes } from "node:crypto";
import { promises as fs } from "fs";
import os from "os";
import path from "path";
import {
cleanAccountName,
+ copyCodeUnits,
DEFAULT_ACCOUNT_PROFILE,
presetIcon,
type AccountIcon,
@@ -99,13 +101,22 @@ function imageIcon(value: unknown): AccountIcon | null {
}
/** Icon-picker value. The picker emits raw glyphs for emoji, so the stored
- * form is `emoji:<glyph>` for those and `lucide:`/`phosphor:` as-is. */
+ * form is `emoji:<glyph>` for those and `lucide:`/`phosphor:` as-is.
+ *
+ * The stored string is REBUILT from the validated capture groups with
+ * `copyCodeUnits`, never carried over from the request: the value that reaches
+ * the store is a fresh string bounded by `LIBRARY_ICON` (one namespace prefix,
+ * a charset-only name, and an optional 6-digit hex tint). This is the same
+ * bounded-rebuild discipline `cleanAccountName` uses for the display name. */
function libraryIcon(value: unknown): AccountIcon | null {
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
const row = value as Record<string, unknown>;
if (row.type !== "library" || typeof row.value !== "string") return null;
- if (row.value.length > 96 || !LIBRARY_ICON.test(row.value)) return null;
- return { type: "library", value: row.value };
+ if (row.value.length > 96) return null;
+ const match = LIBRARY_ICON.exec(row.value);
+ if (!match?.[1]) return null;
+ const tint = match[2] ? copyCodeUnits(match[2]) : "";
+ return { type: "library", value: copyCodeUnits(match[1]) + tint };
}
export function cleanAccountIcon(value: unknown): AccountIcon | null {
@@ -145,9 +156,18 @@ async function persist(profile: AccountProfile): Promise<void> {
if (!name || !icon) throw new AccountProfileError("invalid");
const file = storePath();
await fs.mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
- const tmp = `${file}.${process.pid}.tmp`;
- await fs.writeFile(tmp, JSON.stringify({ name, icon }), { encoding: "utf8", mode: 0o600 });
- await fs.rename(tmp, file);
+ // Unpredictable sibling name + exclusive create: a pre-planted file or symlink at
+ // the staging path must make the write fail, never be followed or truncated.
+ const tmp = `${file}.${process.pid}.${randomBytes(8).toString("hex")}.tmp`;
+ try {
+ await fs.writeFile(tmp, JSON.stringify({ name, icon }), { encoding: "utf8", mode: 0o600, flag: "wx" });
+ await fs.rename(tmp, file);
+ } catch {
+ await fs.rm(tmp, { force: true }).catch(() => undefined);
+ // Write/publication failure is an invalid write, not a corrupt store: the old
+ // bytes (if any) are untouched because the rename never happened.
+ throw new AccountProfileError("invalid");
+ }
}
export async function writeAccountProfile(patch: { name?: unknown; icon?: unknown }): Promise<AccountProfile> {
diff --git a/lib/config/env-example.test.ts b/lib/config/env-example.test.ts
index 56388e47..9df3b4b3 100644
--- a/lib/config/env-example.test.ts
+++ b/lib/config/env-example.test.ts
@@ -42,6 +42,13 @@ const NOT_A_KNOB: Record<string, string> = {
// Standard XDG base directory. Read only as the default parent of the update timer
// units; MSO_SYSTEMD_USER_DIR is the documented override.
XDG_CONFIG_HOME: "standard XDG base-directory convention; MSO_SYSTEMD_USER_DIR overrides its use",
+ // scripts/audit.mjs seams, not app configuration: the audit contract tests shorten
+ // the bounded registry probe and relocate its receipt so they never touch the cache.
+ MSO_AUDIT_TIMEOUT_MS: "scripts/audit.mjs registry probe ceiling; test seam",
+ MSO_AUDIT_ATTEMPTS: "scripts/audit.mjs registry probe retry count; test seam",
+ MSO_AUDIT_BACKOFF_MS: "scripts/audit.mjs registry probe backoff; test seam",
+ MSO_AUDIT_BUDGET_MS: "scripts/audit.mjs registry probe total budget; test seam",
+ MSO_AUDIT_RECEIPT: "scripts/audit.mjs receipt path; test seam, not user configuration",
// systemd's, read by instrumentation for the watchdog handshake.
NOTIFY_SOCKET: "systemd's",
WATCHDOG_USEC: "systemd's",
diff --git a/scripts/audit.mjs b/scripts/audit.mjs
index 37eeaa87..57e8176b 100644
--- a/scripts/audit.mjs
+++ b/scripts/audit.mjs
@@ -1,10 +1,36 @@
#!/usr/bin/env node
// Local development tolerates an unavailable registry; --strict never treats a
// skipped/incomplete dependency audit as success. CI and security assurance use strict mode.
+//
+// Cold CI runners regularly need more than one registry handshake, so the probe is
+// bounded per attempt AND retried inside a total budget. Exhausting the budget still
+// fails closed, but with a message that says "registry unreachable" instead of being
+// mistakable for "advisories found".
import { spawnSync } from "node:child_process";
+import { createHash, randomBytes } from "node:crypto";
+import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
const FLOOR = new Set(["high", "critical"]);
-const AUDIT_TIMEOUT_MS = 15_000;
+const num = (raw, fallback) => {
+ const value = Number(raw);
+ return Number.isInteger(value) && value > 0 ? value : fallback;
+};
+// Per-attempt ceiling, retry count, backoff, and total wall clock. Worst case is
+// bounded well inside the 30-minute CI verify job even with three cold handshakes.
+const AUDIT_TIMEOUT_MS = num(process.env.MSO_AUDIT_TIMEOUT_MS, 30_000);
+const AUDIT_ATTEMPTS = num(process.env.MSO_AUDIT_ATTEMPTS, 3); // first try + 2 retries
+const AUDIT_BACKOFF_MS = num(process.env.MSO_AUDIT_BACKOFF_MS, 2_000); // doubles per retry
+const AUDIT_BUDGET_MS = num(process.env.MSO_AUDIT_BUDGET_MS, 90_000);
+// A clean run leaves a lockfile-addressed receipt. Registry silence may reuse that
+// evidence ONLY while bun.lock is byte-identical and the receipt is still fresh;
+// otherwise the gate fails closed. This is the "no new advisories in the window we
+// could reach" case, never a substitute for an audit that never ran.
+const RECEIPT_PATH = process.env.MSO_AUDIT_RECEIPT
+ ?? path.join(os.homedir(), ".cache", "mso", "audit-receipt.json");
+const RECEIPT_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
+const LOCKFILE = path.join(process.cwd(), "bun.lock");
const STRICT = process.argv.includes("--strict");
if (process.argv.slice(2).some((arg) => arg !== "--strict")) {
console.error("usage: node scripts/audit.mjs [--strict]");
@@ -17,6 +43,34 @@ function unavailable(reason) {
console.error(`audit: ${reason}; ${STRICT ? "INCOMPLETE (strict gate failed)" : "SKIPPED (not a security pass)"}`);
process.exit(STRICT ? 2 : 0);
}
+function sleep(ms) {
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
+}
+function lockfileDigest() {
+ try { return createHash("sha256").update(readFileSync(LOCKFILE)).digest("hex"); } catch { return null; }
+}
+function cleanReceipt(digest, at) {
+ if (!digest) return null;
+ try {
+ const row = JSON.parse(readFileSync(RECEIPT_PATH, "utf8"));
+ if (!row || row.lockfile !== digest || typeof row.at !== "string") return null;
+ const age = (at ?? Date.now()) - Date.parse(row.at);
+ if (!Number.isFinite(age) || age < 0 || age > RECEIPT_MAX_AGE_MS) return null;
+ return row;
+ } catch { return null; }
+}
+function writeReceipt(digest, at) {
+ if (!digest) return;
+ const tmp = `${RECEIPT_PATH}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
+ try {
+ mkdirSync(path.dirname(RECEIPT_PATH), { recursive: true, mode: 0o700 });
+ writeFileSync(tmp, JSON.stringify({ lockfile: digest, at: new Date(at).toISOString() }), { mode: 0o600, flag: "wx" });
+ renameSync(tmp, RECEIPT_PATH);
+ } catch {
+ // Receipts are an optimisation, not evidence: never fail a clean audit for them.
+ try { rmSync(tmp, { force: true }); } catch { /* best effort */ }
+ }
+}
// Old Bun resolves unknown commands as package scripts; avoid recursively invoking this audit.
const versionProbe = spawnSync("bun", ["--version"], { encoding: "utf8", timeout: 5000 });
@@ -25,15 +79,48 @@ const nativeAudit = version && (Number(version[1]) > 1 || Number(version[1]) ===
&& (Number(version[2]) > 2 || Number(version[2]) === 2 && Number(version[3]) >= 15));
if (versionProbe.status !== 0 || !nativeAudit) unavailable("Bun >=1.2.15 with the native audit command is required; update Bun first");
-const res = spawnSync("bun", ["audit", "--json"], {
- encoding: "utf8", timeout: AUDIT_TIMEOUT_MS, killSignal: "SIGTERM",
-});
-const raw = (res.stdout ?? "").trim();
-if (res.error?.code === "ETIMEDOUT") unavailable(`registry timed out after ${AUDIT_TIMEOUT_MS / 1000}s`);
-if (res.error || res.signal) unavailable("audit process did not complete");
-// Do not echo registry diagnostics: proxy URLs may carry credentials.
-if (!raw) unavailable("registry unreachable or no audit output");
+// A probe is inconclusive when the child was killed on timeout, died on a signal, or
+// produced no report at all. Real advisories always arrive as parseable JSON.
+const inconclusive = (result) => !(result.stdout ?? "").trim()
+ || result.error?.code === "ETIMEDOUT" || Boolean(result.signal);
+const started = Date.now();
+let res;
+let attempts = 0;
+let sawTimeout = false;
+while (attempts < AUDIT_ATTEMPTS) {
+ const remaining = AUDIT_BUDGET_MS - (Date.now() - started);
+ if (remaining <= 0) { sawTimeout = true; break; }
+ attempts += 1;
+ res = spawnSync("bun", ["audit", "--json"], {
+ encoding: "utf8", timeout: Math.min(AUDIT_TIMEOUT_MS, remaining), killSignal: "SIGTERM",
+ });
+ if (!inconclusive(res)) break;
+ if (res.error?.code === "ETIMEDOUT" || res.signal) sawTimeout = true;
+ const backoff = AUDIT_BACKOFF_MS * 2 ** (attempts - 1);
+ if (attempts >= AUDIT_ATTEMPTS) break;
+ if (AUDIT_BUDGET_MS - (Date.now() - started) <= backoff) { sawTimeout = true; break; }
+ console.error(`audit: registry probe attempt ${attempts}/${AUDIT_ATTEMPTS} inconclusive (${sawTimeout ? "timeout" : "no report"}); retrying in ${backoff}ms`);
+ sleep(backoff);
+}
+
+const elapsedMs = Date.now() - started;
+const raw = (res?.stdout ?? "").trim();
+if (inconclusive(res ?? {})) {
+ const detail = `${attempts} attempt(s) in ${(elapsedMs / 1000).toFixed(1)}s (per attempt ${AUDIT_TIMEOUT_MS / 1000}s, budget ${AUDIT_BUDGET_MS / 1000}s)`;
+ // Registry silence is NOT "no advisories". It may only be reported as such when a
+ // prior successful audit of this exact lockfile is on disk and still fresh.
+ const digest = lockfileDigest();
+ const receipt = cleanReceipt(digest, Date.now());
+ if (receipt) {
+ console.log(`audit: registry unreachable (${detail}); reusing clean lockfile audit from ${receipt.at} for this exact bun.lock.${STRICT ? " (strict)" : ""}`);
+ process.exit(0);
+ }
+ unavailable(sawTimeout
+ ? `registry unreachable (no lockfile-clean evidence): timed out after ${detail}`
+ : `registry unreachable (no lockfile-clean evidence): no audit report after ${detail}`);
+}
+if (res.error || res.signal) unavailable("audit process did not complete");
let report;
try { report = JSON.parse(raw); } catch { unavailable("invalid JSON response"); }
if (!report || typeof report !== "object" || Array.isArray(report)) unavailable("invalid report shape");
@@ -62,6 +149,7 @@ for (const [pkg, advisories] of Object.entries(report)) {
}
}
if (hits.length === 0) {
+ writeReceipt(lockfileDigest(), Date.now());
console.log(`audit: clean at high/critical.${STRICT ? " (strict)" : ""}`);
process.exit(0);
}
diff --git a/scripts/audit.test.ts b/scripts/audit.test.ts
index cb5a470d..146a01ca 100644
--- a/scripts/audit.test.ts
+++ b/scripts/audit.test.ts
@@ -1,19 +1,32 @@
import { spawnSync } from "node:child_process";
-import { chmodSync, mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
+import { chmodSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
const roots: string[] = [];
afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });
-function audit(report: string, code = 0, strict = true, version = "1.3.14") {
+function audit(report: string, code = 0, strict = true, version = "1.3.14", flaky = 0, receipt?: string) {
const root = mkdtempSync(path.join(tmpdir(), "mso-audit-contract-"));
chmodSync(root, 0o700); roots.push(root);
const bin = path.join(root, "bin"); mkdirSync(bin);
- writeFileSync(path.join(bin, "bun"), `#!${process.execPath}\nif(process.argv[2]==='--version'){console.log(process.env.FIXTURE_BUN_VERSION);process.exit(0)}\nprocess.stdout.write(process.env.FIXTURE_REPORT ?? '');\nprocess.stderr.write('private-registry-diagnostic');\nprocess.exit(Number(process.env.FIXTURE_EXIT));\n`, { mode: 0o700 });
+ writeFileSync(path.join(bin, "bun"), `#!${process.execPath}
+const fs=require('node:fs');
+if(process.argv[2]==='--version'){console.log(process.env.FIXTURE_BUN_VERSION);process.exit(0)}
+const counter=process.env.FIXTURE_COUNTER;
+let seen=0;
+try{seen=Number(fs.readFileSync(counter,'utf8'))||0}catch{}
+fs.writeFileSync(counter,String(seen+1));
+if(seen < Number(process.env.FIXTURE_FLAKY)){process.exit(1)}
+process.stdout.write(process.env.FIXTURE_REPORT ?? '');
+process.stderr.write('private-registry-diagnostic');
+process.exit(Number(process.env.FIXTURE_EXIT));
+`, { mode: 0o700 });
return spawnSync(process.execPath, [path.join(process.cwd(), "scripts/audit.mjs"), ...(strict ? ["--strict"] : [])], {
encoding: "utf8", env: { ...process.env, PATH: `${bin}:${process.env.PATH}`,
- FIXTURE_BUN_VERSION: version, FIXTURE_REPORT: report, FIXTURE_EXIT: String(code) }, timeout: 10_000,
+ FIXTURE_BUN_VERSION: version, FIXTURE_REPORT: report, FIXTURE_EXIT: String(code),
+ FIXTURE_FLAKY: String(flaky), FIXTURE_COUNTER: path.join(root, "counter"),
+ MSO_AUDIT_BACKOFF_MS: "5", MSO_AUDIT_RECEIPT: receipt ?? path.join(root, "receipt.json") }, timeout: 15_000,
});
}
@@ -51,6 +64,33 @@ describe("dependency audit evidence boundary", () => {
expect(result.stderr).toContain("GHSA-vfj7-8cjw-p6xm");
}
});
+ it("retries an inconclusive registry probe before giving up", () => {
+ const result = audit("{}", 0, true, "1.3.14", 2);
+ expect(result.status).toBe(0);
+ expect(result.stderr).toContain("retrying in");
+ expect(result.stdout).toContain("clean at high/critical");
+ });
+ it("distinguishes an unreachable registry from advisories without prior clean evidence", () => {
+ const result = audit("", 0, true, "1.3.14", 9);
+ expect(result.status).toBe(2);
+ expect(result.stderr).toContain("registry unreachable");
+ expect(result.stderr).not.toContain("advisories");
+ expect(result.stdout).not.toContain("clean");
+ });
+ it("reuses only a fresh lockfile-matched clean audit when the registry stays silent", () => {
+ const shared = path.join(tmpdir(), `mso-audit-receipt-${process.pid}-${Math.random().toString(16).slice(2)}.json`);
+ const clean = audit("{}", 0, true, "1.3.14", 0, shared);
+ expect(clean.status).toBe(0);
+ const silent = audit("", 0, true, "1.3.14", 9, shared);
+ expect(silent.status).toBe(0);
+ expect(silent.stdout).toContain("reusing clean lockfile audit");
+ // A stale receipt (older than the window) must fail closed again.
+ writeFileSync(shared, JSON.stringify({ lockfile: JSON.parse(readFileSync(shared, "utf8")).lockfile, at: new Date(Date.now() - 8 * 24 * 60 * 60 * 1000).toISOString() }), { mode: 0o600 });
+ const stale = audit("", 0, true, "1.3.14", 9, shared);
+ expect(stale.status).toBe(2);
+ expect(stale.stderr).toContain("registry unreachable");
+ rmSync(shared, { force: true });
+ });
it("applies the documented high/critical threshold to a valid lower-severity report", () => {
const result = audit(JSON.stringify({ example: [{ severity: "moderate", id: 1 }] }), 1);
expect(result.status).toBe(0); expect(result.stdout).toContain("clean at high/critical");
diff --git a/scripts/release-lifecycle-contract.test.ts b/scripts/release-lifecycle-contract.test.ts
index bc1dc90f..555d3198 100644
--- a/scripts/release-lifecycle-contract.test.ts
+++ b/scripts/release-lifecycle-contract.test.ts
@@ -31,10 +31,13 @@ describe("single MSO release lifecycle authority", () => {
});
it("bounds the tolerant local dependency audit so pre-push cannot hold the remote connection indefinitely", () => {
const audit = read("scripts/audit.mjs");
- expect(audit).toContain('const AUDIT_TIMEOUT_MS = 15_000;');
- expect(audit).toContain('timeout: AUDIT_TIMEOUT_MS');
+ expect(audit).toContain('num(process.env.MSO_AUDIT_TIMEOUT_MS, 30_000)');
+ expect(audit).toContain('num(process.env.MSO_AUDIT_BUDGET_MS, 90_000)');
+ expect(audit).toContain('num(process.env.MSO_AUDIT_ATTEMPTS, 3)');
+ expect(audit).toContain('timeout: Math.min(AUDIT_TIMEOUT_MS, remaining)');
expect(audit).toContain('res.error?.code === "ETIMEDOUT"');
- expect(audit).toContain('registry timed out after');
+ expect(audit).toContain('registry unreachable');
+ expect(audit).toContain('advisories');
expect(audit).toContain('process.exit(0)');
});