返回 CodeWhale
cloud-facts.test.ts
根目录 / web / lib / cloud-facts.test.ts
1 import { createHash, generateKeyPairSync, sign } from "node:crypto";
2 import { execFileSync, spawnSync } from "node:child_process";
3 import { readFileSync, mkdtempSync, writeFileSync, rmSync, symlinkSync, linkSync } from "node:fs";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { fileURLToPath } from "node:url";
7 import { describe, expect, it, vi } from "vitest";
8 import {
9 etagFor, resolveCloudFacts, verifyEnvelope, signingMessage, responseFor,
10 MAX_ENVELOPE_BYTES, type CloudFactsEnvelope, type FactsCurrentRow, type CloudFactsResult,
11 } from "./cloud-facts";
12 import bundledRegistryTrust from "./cloud-facts/bundled-providers.json";
13 import { MAX_REGISTRY_ENVELOPE_BYTES, TRUSTED_KEYS, type TrustedKey } from "./cloud-facts/keys";
14 import { GET, HEAD } from "../app/api/facts/v1/[channel]/route";
15 import {
16 activePublishingKey,
17 buildEnvelope,
18 buildRegistryPayload,
19 emitSql,
20 publishRelease,
21 readBoundedFile,
22 readBoundedResponse,
23 revokeRelease,
24 verifyEnvelope as verifyForPublisher,
25 } from "../scripts/facts-publish.mjs";
26 import { parseRustKeys, parseTsKeys } from "../scripts/check-cloud-facts.mjs";
27
28 const fixturePath = new URL("../../crates/cloud-facts/fixtures/envelope-stable-v7.json", import.meta.url);
29 const fixture = JSON.parse(readFileSync(fixturePath, "utf8")) as CloudFactsEnvelope;
30 const futureFixture = JSON.parse(readFileSync(new URL("../../crates/cloud-facts/fixtures/envelope-future-only-v8.json", import.meta.url), "utf8")) as CloudFactsEnvelope;
31 const TEST_KEY: TrustedKey = { keyId: "cwf-test-only", publicKey: "8+FLDW4OorUETUVks0hpQAi5Lj4wg3kjKjfYFzLbJ7U=", status: "active", role: "founder" };
32 const NOW = Date.parse("2026-09-07T00:00:00Z");
33 const basePayload = JSON.parse(Buffer.from(fixture.payload_b64, "base64").toString("utf8"));
34 // Ephemeral test keys exist only in memory and never enter production anchors.
35 const ephemeral = generateKeyPairSync("ed25519");
36 const EPHEMERAL_KEY: TrustedKey = { keyId: "cwf-ephemeral-test", publicKey: ephemeral.publicKey.export({ type: "spki", format: "der" }).subarray(-32).toString("base64"), status: "active", role: "founder" };
37
38 function signed(overrides: Record<string, unknown> = {}): CloudFactsEnvelope {
39 const payload = { ...basePayload, ...overrides };
40 const bytes = Buffer.from(JSON.stringify(payload));
41 return {
42 envelope: 1, channel: payload.channel, facts_version: payload.facts_version,
43 schema_version: payload.schema_version, key_id: EPHEMERAL_KEY.keyId, alg: "ed25519",
44 applies_to: payload.applies_to, published_at: payload.published_at,
45 not_after: payload.not_after ?? null, payload_b64: bytes.toString("base64"),
46 sig_b64: sign(null, signingMessage(EPHEMERAL_KEY.keyId, bytes), ephemeral.privateKey).toString("base64"),
47 sigs: [], sha256: createHash("sha256").update(bytes).digest("hex"),
48 };
49 }
50
51 function rowFrom(envelope = fixture, overrides: Partial<FactsCurrentRow> = {}): FactsCurrentRow {
52 return { channel: envelope.channel, release_id: "00000000-0000-0000-0000-000000000001",
53 facts_version: envelope.facts_version, schema_version: envelope.schema_version,
54 envelope_version: envelope.envelope, applies_to: envelope.applies_to, key_id: envelope.key_id,
55 payload_b64: envelope.payload_b64, sig_b64: envelope.sig_b64, sigs: envelope.sigs,
56 payload_sha256: envelope.sha256, published_at: envelope.published_at,
57 not_after: envelope.not_after ?? null, ...overrides };
58 }
59
60 function supabaseFetch(rows: unknown, status = 200): typeof fetch {
61 return vi.fn(async () => new Response(JSON.stringify(rows), { status, headers: { "Content-Type": "application/json" } })) as typeof fetch;
62 }
63
64 class MemKV {
65 store = new Map<string, string>();
66 async get(key: string, type: "stream") {
67 expect(type).toBe("stream");
68 const raw = this.store.get(key);
69 return raw === undefined ? null : new Response(raw).body;
70 }
71 async put(key: string, value: string) { this.store.set(key, value); }
72 }
73 const env = { SUPABASE_URL: "https://example.supabase.co", SUPABASE_PUBLISHABLE_KEY: "sb_publishable_test" };
74 const opts = { keys: [TEST_KEY], now: () => NOW };
75 const failing = supabaseFetch(null, 503);
76
77 function overflowingStream() {
78 let pulls = 0;
79 const cancel = vi.fn();
80 return { cancel, pulls: () => pulls, stream: new ReadableStream<Uint8Array>({
81 pull(controller) { pulls += 1; controller.enqueue(new Uint8Array(MAX_ENVELOPE_BYTES / 2 + 1)); },
82 cancel,
83 }) };
84 }
85
86 describe("cloud facts verification", () => {
87 it("authenticates public fixtures, including a future-only client applicability range", async () => {
88 for (const envelope of [fixture, futureFixture]) {
89 expect(await verifyEnvelope(envelope, [TEST_KEY], { channel: "stable", now: NOW })).toEqual({ ok: true, keyId: TEST_KEY.keyId, mode: "verified" });
90 expect(verifyForPublisher(envelope, TEST_KEY.publicKey).ok).toBe(true);
91 }
92 const result = await resolveCloudFacts("stable", env, { ...opts, fetchImpl: supabaseFetch([rowFrom(futureFixture)]) });
93 expect(result).toMatchObject({ kind: "ok", envelope: { applies_to: ">=99.0.0", facts_version: 8 } });
94 });
95
96 it("pins a well-formed production anchor and refuses empty or retired-only trust before any reads", async () => {
97 // The anchor itself is checked for shape, not for a specific key: pinning a
98 // second key or rotating must not fail this test, but a malformed one must.
99 // Byte-for-byte agreement with the Rust table is `check-cloud-facts.mjs`.
100 expect(TRUSTED_KEYS.length).toBeGreaterThan(0);
101 for (const key of TRUSTED_KEYS) {
102 expect(key.keyId).toMatch(/^cwf-[A-Za-z0-9._-]+$/);
103 expect(["active", "retired"]).toContain(key.status);
104 // Standard base64 of a raw 32-byte Ed25519 public key.
105 expect(Buffer.from(key.publicKey, "base64")).toHaveLength(32);
106 }
107 expect(TRUSTED_KEYS.some((key) => key.status === "active")).toBe(true);
108
109 // The property that actually matters is unchanged: with no usable key the
110 // layer fails closed *before* any network or cache read.
111 const fetchImpl = vi.fn();
112 const get = vi.fn();
113 for (const keys of [[], [{ ...TEST_KEY, status: "retired" as const }]]) {
114 expect(await verifyEnvelope(fixture, keys)).toEqual({ ok: false, reason: "no-active-keys" });
115 expect(await resolveCloudFacts("stable", { ...env, CURATED_KV: { get, put: vi.fn() } }, { keys, fetchImpl })).toEqual({ kind: "unavailable", reason: "no-active-keys" });
116 }
117 expect(fetchImpl).not.toHaveBeenCalled();
118 expect(get).not.toHaveBeenCalled();
119 });
120
121 it("rejects invalid signatures, unknown keys, retired keys and ambiguous key tables", async () => {
122 expect(await verifyEnvelope({ ...fixture, sig_b64: `A${fixture.sig_b64.slice(1)}` }, [TEST_KEY])).toEqual({ ok: false, reason: "bad-signature" });
123 expect(await verifyEnvelope(fixture, [EPHEMERAL_KEY])).toEqual({ ok: false, reason: "unknown-key" });
124 expect(await verifyEnvelope(fixture, [{ ...TEST_KEY, status: "retired" }, EPHEMERAL_KEY])).toEqual({ ok: false, reason: "retired-key" });
125 expect(await verifyEnvelope(fixture, [TEST_KEY, TEST_KEY])).toEqual({ ok: false, reason: "no-active-keys" });
126 });
127
128 it("cross-checks every unsigned metadata field with the signed payload", async () => {
129 for (const change of [{ channel: "beta" }, { facts_version: 8 }, { schema_version: 2 },
130 { applies_to: ">=99.0.0" }, { published_at: "2026-09-01T00:00:00Z" },
131 { not_after: "2026-10-01T00:00:00Z" }, { sha256: "0".repeat(64) }]) {
132 expect((await verifyEnvelope({ ...fixture, ...change }, [TEST_KEY], { channel: "stable", now: NOW })).ok).toBe(false);
133 expect(verifyForPublisher({ ...fixture, ...change }, TEST_KEY.publicKey).ok).toBe(false);
134 }
135 expect(await verifyEnvelope(signed({ channel: "beta" }), [EPHEMERAL_KEY], { channel: "stable", now: NOW })).toEqual({ ok: false, reason: "wrong-channel" });
136 });
137
138 it("rejects signed bad versions, applicability, schema and UTC dates", async () => {
139 for (const change of [{ facts_version: "7; DROP TABLE public.facts_key;" }, { facts_version: 0 },
140 { facts_version: Number.MAX_SAFE_INTEGER + 1 }, { schema_version: 2 }, { applies_to: "><=3" },
141 { published_at: "2026-02-30T00:00:00Z" }, { published_at: "not-a-date" }]) {
142 const envelope = signed(change);
143 expect((await verifyEnvelope(envelope, [EPHEMERAL_KEY], { now: NOW })).ok).toBe(false);
144 expect(verifyForPublisher(envelope, EPHEMERAL_KEY.publicKey).ok).toBe(false);
145 }
146 });
147
148 it("rejects future publication, expiry and reversed signed time windows", async () => {
149 expect(await verifyEnvelope(fixture, [TEST_KEY], { now: Date.parse("2026-08-29T00:00:00Z") })).toEqual({ ok: false, reason: "bad-payload" });
150 const expired = signed({ not_after: "2026-09-06T00:00:00Z" });
151 expect(await verifyEnvelope(expired, [EPHEMERAL_KEY], { now: NOW })).toEqual({ ok: false, reason: "expired" });
152 expect((await resolveCloudFacts("stable", env, { keys: [EPHEMERAL_KEY], now: () => NOW, fetchImpl: supabaseFetch([rowFrom(expired)]) })).kind).toBe("unverifiable");
153 expect((await verifyEnvelope(signed({ not_after: "2026-08-29T00:00:00Z" }), [EPHEMERAL_KEY], { now: NOW })).ok).toBe(false);
154 const zeroValidity = signed({ not_after: basePayload.published_at });
155 expect(await verifyEnvelope(zeroValidity, [EPHEMERAL_KEY], { now: NOW })).toEqual({ ok: false, reason: "bad-payload" });
156 expect(verifyForPublisher(zeroValidity, EPHEMERAL_KEY.publicKey).ok).toBe(false);
157 });
158
159 it("rejects oversized/noncanonical base64 and hostile signature shapes without throwing", async () => {
160 for (const value of [null, [], {}, { ...fixture, payload_b64: "A".repeat(MAX_ENVELOPE_BYTES) },
161 { ...fixture, payload_b64: `${fixture.payload_b64}\n` }, { ...fixture, sig_b64: `${fixture.sig_b64}garbage` },
162 { ...fixture, sigs: "not-an-array" }, { ...fixture, sigs: Array(9).fill({ key_id: TEST_KEY.keyId, sig_b64: fixture.sig_b64 }) },
163 { ...fixture, sigs: [null] }]) {
164 expect((await verifyEnvelope(value, [TEST_KEY])).ok).toBe(false);
165 expect(verifyForPublisher(value, TEST_KEY.publicKey).ok).toBe(false);
166 }
167 });
168
169 it("reports the authenticating rotation key and changes ETag for signature-only updates", async () => {
170 const rotated = { ...fixture, sigs: [{ key_id: EPHEMERAL_KEY.keyId,
171 sig_b64: sign(null, signingMessage(EPHEMERAL_KEY.keyId, Buffer.from(fixture.payload_b64, "base64")), ephemeral.privateKey).toString("base64") }] };
172 const keys = [{ ...TEST_KEY, status: "retired" as const }, EPHEMERAL_KEY];
173 expect(await verifyEnvelope(rotated, keys, { now: NOW })).toEqual({ ok: true, keyId: EPHEMERAL_KEY.keyId, mode: "verified" });
174 expect(await etagFor(rotated)).not.toBe(await etagFor(fixture));
175 const result = await resolveCloudFacts("stable", env, { keys, now: () => NOW, fetchImpl: supabaseFetch([rowFrom(rotated)]) });
176 expect(result).toMatchObject({ kind: "ok", keyId: EPHEMERAL_KEY.keyId });
177 const request = new Request("https://example.test", { headers: { "if-none-match": await etagFor(fixture) } });
178 const response = responseFor(result, request, "stable", "GET");
179 expect(response.status).toBe(200);
180 expect(response.headers.get("x-facts-key")).toBe(EPHEMERAL_KEY.keyId);
181 });
182 });
183
184 describe("cloud facts transport", () => {
185 it("uses one global channel query with a publishable credential and writes only a verified cache", async () => {
186 const kv = new MemKV();
187 const fetchImpl = supabaseFetch([rowFrom(fixture, { published_at: "2026-08-30T00:00:00+00:00" })]);
188 const result = await resolveCloudFacts("stable", { ...env, CURATED_KV: kv }, { ...opts, fetchImpl });
189 expect(result).toMatchObject({ kind: "ok", source: "supabase", verified: "verified" });
190 const [url, init] = vi.mocked(fetchImpl).mock.calls[0];
191 const parsed = new URL(String(url));
192 expect(parsed.origin).toBe(env.SUPABASE_URL);
193 expect(parsed.pathname).toBe("/rest/v1/facts_current");
194 expect(Object.fromEntries(parsed.searchParams)).toMatchObject({ channel: "eq.stable", scope: "eq.global", limit: "1" });
195 expect(init?.headers).toMatchObject({ apikey: env.SUPABASE_PUBLISHABLE_KEY, Authorization: `Bearer ${env.SUPABASE_PUBLISHABLE_KEY}` });
196 expect(init?.redirect).toBe("error");
197 if (result.kind !== "ok") throw new Error("expected verified result");
198 expect(kv.store.get("facts:cloud:stable")).toBe(result.body);
199 expect(result.etag).toBe(`"${createHash("sha256").update(result.body).digest("hex")}"`);
200 });
201
202 it("rejects service/secret credentials before dispatch", async () => {
203 const fetchImpl = vi.fn();
204 const serviceJwt = `a.${Buffer.from(JSON.stringify({ role: "service_role" })).toString("base64url")}.b`;
205 for (const key of ["sb_secret_do-not-send", serviceJwt]) {
206 expect((await resolveCloudFacts("stable", { ...env, SUPABASE_PUBLISHABLE_KEY: key }, { ...opts, fetchImpl })).kind).toBe("unavailable");
207 }
208 expect(fetchImpl).not.toHaveBeenCalled();
209 });
210
211 it("distinguishes no row and invalid channel and refuses a mismatched signed channel", async () => {
212 const fetchImpl = supabaseFetch([]);
213 expect((await resolveCloudFacts("Bad Slug", env, { ...opts, fetchImpl })).kind).toBe("none");
214 expect(fetchImpl).not.toHaveBeenCalled();
215 expect((await resolveCloudFacts("stable", env, { ...opts, fetchImpl })).kind).toBe("none");
216 const beta = signed({ channel: "beta" });
217 expect(await resolveCloudFacts("stable", env, { keys: [EPHEMERAL_KEY], now: () => NOW, fetchImpl: supabaseFetch([rowFrom(beta)]) })).toMatchObject({ kind: "unverifiable", reason: "wrong-channel" });
218 });
219
220 it("never caches digest/signature failures and does not amplify them through a 304", async () => {
221 for (const change of [{ payload_sha256: "0".repeat(64) }, { sig_b64: `A${fixture.sig_b64.slice(1)}` }]) {
222 const kv = new MemKV();
223 const result = await resolveCloudFacts("stable", { ...env, CURATED_KV: kv }, { ...opts, fetchImpl: supabaseFetch([rowFrom(fixture, change)]) });
224 expect(["sha-mismatch", "unverifiable"]).toContain(result.kind);
225 expect(kv.store.size).toBe(0);
226 expect(responseFor(result, new Request("https://example.test", { headers: { "if-none-match": "*" } }), "stable", "GET").status).not.toBe(304);
227 }
228 });
229
230 it("revalidates cached digest, channel, expiry and current trust after an outage", async () => {
231 const kv = new MemKV();
232 await kv.put("facts:cloud:stable", JSON.stringify(fixture));
233 expect(await resolveCloudFacts("stable", { ...env, CURATED_KV: kv }, { ...opts, fetchImpl: failing })).toMatchObject({ kind: "ok", source: "kv-stale" });
234 for (const envelope of [{ ...fixture, sha256: "0".repeat(64) }, signed({ channel: "beta" }), signed({ not_after: "2026-09-06T00:00:00Z" })]) {
235 await kv.put("facts:cloud:stable", JSON.stringify(envelope));
236 expect((await resolveCloudFacts("stable", { ...env, CURATED_KV: kv }, { keys: [TEST_KEY, EPHEMERAL_KEY], now: () => NOW, fetchImpl: failing })).kind).toBe("unavailable");
237 }
238 await kv.put("facts:cloud:stable", JSON.stringify(fixture));
239 expect((await resolveCloudFacts("stable", { ...env, CURATED_KV: kv }, { keys: [EPHEMERAL_KEY], now: () => NOW, fetchImpl: failing })).kind).toBe("unavailable");
240 });
241
242 it("never resurrects a revoked head through the stale cache after an outage", async () => {
243 const kv = new MemKV();
244 const ttls: unknown[] = [];
245 const put = kv.put.bind(kv);
246 kv.put = async (key: string, value: string, options?: { expirationTtl?: number }) => { ttls.push(options?.expirationTtl); await put(key, value); };
247 expect((await resolveCloudFacts("stable", { ...env, CURATED_KV: kv }, { ...opts, fetchImpl: supabaseFetch([rowFrom(fixture)]) })).kind).toBe("ok");
248 // The operator revokes the head: facts_current returns no row.
249 expect((await resolveCloudFacts("stable", { ...env, CURATED_KV: kv }, { ...opts, fetchImpl: supabaseFetch([]) })).kind).toBe("none");
250 // Supabase then goes down. The revoked envelope must not come back.
251 expect(await resolveCloudFacts("stable", { ...env, CURATED_KV: kv }, { ...opts, fetchImpl: failing })).toMatchObject({ kind: "unavailable" });
252 // The bridge lasts no longer than a client's own 6 h staleness bound.
253 expect(ttls.length).toBeGreaterThan(0);
254 expect(ttls.every((ttl) => ttl === 6 * 60 * 60)).toBe(true);
255 });
256
257 it("caps and cancels PostgREST streaming bodies before JSON parsing", async () => {
258 const oversized = overflowingStream();
259 const fetchImpl = vi.fn(async () => new Response(oversized.stream));
260 expect((await resolveCloudFacts("stable", env, { ...opts, fetchImpl })).kind).toBe("unavailable");
261 expect(oversized.cancel).toHaveBeenCalledOnce();
262 expect(oversized.pulls()).toBeLessThanOrEqual(3);
263 const declared = overflowingStream();
264 expect((await resolveCloudFacts("stable", env, { ...opts, fetchImpl: vi.fn(async () => new Response(declared.stream, { headers: { "content-length": String(MAX_ENVELOPE_BYTES + 1) } })) })).kind).toBe("unavailable");
265 expect(declared.cancel).toHaveBeenCalledOnce();
266 });
267
268 it("caps KV streams and isolates malformed cache objects", async () => {
269 const oversized = overflowingStream();
270 const get = vi.fn(async () => oversized.stream);
271 expect((await resolveCloudFacts("stable", { ...env, CURATED_KV: { get, put: vi.fn() } }, { ...opts, fetchImpl: failing })).kind).toBe("unavailable");
272 expect(get).toHaveBeenCalledWith("facts:cloud:stable", "stream");
273 expect(oversized.cancel).toHaveBeenCalledOnce();
274 const kv = new MemKV();
275 for (const bad of ["not-json", "null", JSON.stringify({ sigs: null })]) {
276 await kv.put("facts:cloud:stable", bad);
277 expect((await resolveCloudFacts("stable", { ...env, CURATED_KV: kv }, { ...opts, fetchImpl: failing })).kind).toBe("unavailable");
278 }
279 });
280 });
281
282 describe("facts response protocol", () => {
283 const req = (headers: Record<string, string> = {}) => new Request("https://codewhale.net/api/facts/v1/stable", { headers });
284 async function ok(): Promise<CloudFactsResult> { return { kind: "ok", envelope: fixture, body: JSON.stringify(fixture), etag: await etagFor(fixture), source: "supabase", verified: "verified", keyId: TEST_KEY.keyId }; }
285
286 it("serves cacheable GET, conditional 304 and bodyless successful HEAD", async () => {
287 const result = await ok();
288 if (result.kind !== "ok") throw new Error("fixture result");
289 const get = responseFor(result, req(), "stable", "GET");
290 expect(get.status).toBe(200);
291 expect(get.headers.get("cache-control")).toContain("s-maxage=300");
292 expect(get.headers.get("set-cookie")).toBeNull();
293 expect(get.headers.get("vary")).toBeNull();
294 expect(await get.json()).toEqual(fixture);
295 for (const tag of [result.etag, `W/${result.etag}`, "*"]) {
296 const response = responseFor(result, req({ "if-none-match": tag }), "stable", "GET");
297 expect(response.status).toBe(304);
298 expect(await response.text()).toBe("");
299 }
300 const head = responseFor(result, req(), "stable", "HEAD");
301 expect(head.headers.get("content-length")).toBe(String(Buffer.byteLength(result.body)));
302 expect(await head.text()).toBe("");
303 });
304
305 it("returns bodyless HEAD for every error and the invalid-channel route", async () => {
306 const cases: CloudFactsResult[] = [{ kind: "none" }, { kind: "sha-mismatch", channel: "stable", factsVersion: 7 },
307 { kind: "unverifiable", channel: "stable", factsVersion: 7, reason: "bad-signature" }, { kind: "unavailable", reason: "no-active-keys" }];
308 for (const result of cases) {
309 const response = responseFor(result, req(), "stable", "HEAD");
310 expect([404, 502, 503]).toContain(response.status);
311 expect(await response.text()).toBe("");
312 }
313 expect(await (await HEAD(req(), { params: Promise.resolve({ channel: "Bad Slug" }) })).text()).toBe("");
314 const get = await GET(req(), { params: Promise.resolve({ channel: "Bad Slug" }) });
315 expect(get.status).toBe(404);
316 });
317
318 it("keeps CDN freshness inside a signed expiry without stale-serving extensions", async () => {
319 const envelope = signed({ not_after: new Date(Date.now() + 90_000).toISOString() });
320 const result = await resolveCloudFacts("stable", env, { keys: [EPHEMERAL_KEY], fetchImpl: supabaseFetch([rowFrom(envelope)]) });
321 expect(result.kind).toBe("ok");
322 const response = responseFor(result, req(), "stable", "GET");
323 const control = response.headers.get("cache-control")!;
324 expect(control).toContain("must-revalidate");
325 expect(control).not.toContain("stale-");
326 expect(Number(control.match(/s-maxage=(\d+)/)?.[1])).toBeLessThanOrEqual(90);
327 });
328
329 it("gives an envelope with no signed expiry short revalidation and no stale-serving extensions", async () => {
330 const envelope = signed({ not_after: null });
331 const result = await resolveCloudFacts("stable", env, { keys: [EPHEMERAL_KEY], now: () => NOW, fetchImpl: supabaseFetch([rowFrom(envelope)]) });
332 expect(result.kind).toBe("ok");
333 const control = responseFor(result, req(), "stable", "GET").headers.get("cache-control")!;
334 expect(control).toContain("must-revalidate");
335 expect(control).not.toContain("stale-");
336 expect(Number(control.match(/s-maxage=(\d+)/)?.[1])).toBeLessThanOrEqual(300);
337 });
338 });
339
340 describe("facts publisher boundaries", () => {
341 const script = fileURLToPath(new URL("../scripts/facts-publish.mjs", import.meta.url));
342
343 /** A PostgREST double over one channel and its releases. */
344 function fakePostgrest(head: number, releases: { facts_version: number; status: string; payload_sha256: string; revoked_at?: string; revoke_reason?: string }[]) {
345 const calls: string[] = [];
346 const request = async (path: string, init: { method?: string; body?: Record<string, unknown> } = {}) => {
347 calls.push(`${init.method ?? "GET"} ${path}`);
348 if (path.startsWith("facts_channel")) return [{ id: "c1", max_facts_version: head }];
349 if (path === "facts_key") return null;
350 if (path === "facts_release?select=id,payload_sha256" && init.method === "POST") {
351 if (Number(init.body?.facts_version) <= head) throw Object.assign(new Error("PostgREST request failed (HTTP 409)"), { status: 409 });
352 head = Number(init.body?.facts_version);
353 const stored = { id: "r-new", facts_version: head, status: "published", payload_sha256: String(init.body?.payload_sha256 ?? fixture.sha256) };
354 releases.push(stored);
355 return [{ id: stored.id, payload_sha256: stored.payload_sha256 }];
356 }
357 const version = Number(/facts_version=eq\.(\d+)/.exec(path)?.[1]);
358 const matches = releases.filter((r) => r.facts_version === version && (!path.includes("status=eq.published") || r.status === "published"));
359 if (init.method === "PATCH") for (const r of matches) Object.assign(r, init.body);
360 return matches.map((r) => ({ id: `r-${r.facts_version}`, ...r }));
361 };
362 return { request, calls, releases };
363 }
364
365 it("revokes once, keeps the first revocation on a re-run, and refuses an unknown version", async () => {
366 const pg = fakePostgrest(3, [{ facts_version: 3, status: "published", payload_sha256: "a" }]);
367 expect(await revokeRelease(pg.request, { channel: "stable", version: 3, reason: "bad price", at: "2026-09-30T00:00:00Z" }))
368 .toMatchObject({ revoked: 1, already_revoked: false, head: true });
369 const again = await revokeRelease(pg.request, { channel: "stable", version: 3, reason: "second run", at: "2026-10-01T00:00:00Z" });
370 expect(again).toMatchObject({ revoked: 0, already_revoked: true, revoked_at: "2026-09-30T00:00:00Z", revoke_reason: "bad price" });
371 expect(pg.releases[0]).toMatchObject({ revoked_at: "2026-09-30T00:00:00Z", revoke_reason: "bad price" });
372 await expect(revokeRelease(pg.request, { channel: "stable", version: 9, reason: "typo", at: "2026-10-01T00:00:00Z" })).rejects.toThrow("no published facts_version 9");
373 });
374
375 it("publishes exactly the envelope and treats a replay of the same bytes as already published", async () => {
376 const pg = fakePostgrest(fixture.facts_version - 1, []);
377 const row = { facts_version: fixture.facts_version };
378 expect(await publishRelease(pg.request, fixture, row, "pub")).toMatchObject({ published: true, payload_sha256: fixture.sha256 });
379 expect(await publishRelease(pg.request, fixture, row, "pub")).toMatchObject({ published: false, already_published: true, release_id: "r-new" });
380 const other = { ...fixture, sha256: "f".repeat(64) };
381 await expect(publishRelease(pg.request, other, row, "pub")).rejects.toThrow("high-water mark");
382 });
383
384 it("requires an active pinned primary key and cannot publish with an explicit fixture public key", () => {
385 expect(() => activePublishingKey(fixture, [])).toThrow("not pinned and active");
386 expect(() => activePublishingKey(fixture, [{ ...TEST_KEY, status: "retired" }])).toThrow("not pinned and active");
387 expect(activePublishingKey(fixture, [TEST_KEY], NOW).check.ok).toBe(true);
388 const result = spawnSync(process.execPath, [script, "publish", fileURLToPath(fixturePath), "--dry-run", "--public-key", TEST_KEY.publicKey], { encoding: "utf8" });
389 expect(result.status).toBe(1);
390 expect(result.stderr).toContain("publication requires the active pinned table");
391 });
392
393 it("refuses to publish authentically signed future or expired facts", () => {
394 expect(() => activePublishingKey(signed({ not_after: "2026-09-06T00:00:00Z" }), [EPHEMERAL_KEY], NOW)).toThrow("future or expired");
395 expect(() => activePublishingKey(signed({ published_at: "2026-09-08T00:00:00Z" }), [EPHEMERAL_KEY], NOW)).toThrow("future or expired");
396 });
397
398 it("refuses CI signing before reading a source or private credential path", () => {
399 const result = spawnSync(process.execPath, [script, "sign", "--source", "/nonexistent-source-must-not-be-read"], {
400 encoding: "utf8", env: { ...process.env, CI: "true", CODEWHALE_FACTS_SIGNING_KEY_FILE: "/nonexistent-key-must-not-be-read" },
401 });
402 expect(result.status).toBe(1);
403 expect(result.stderr).toContain("refusing to run with a secret under CI");
404 expect(result.stderr).not.toContain("ENOENT");
405 });
406
407 it("creates private keys exclusively without overwriting an existing file or symlink", () => {
408 const dir = mkdtempSync(join(tmpdir(), "facts-key-exclusion-"));
409 try {
410 const target = join(dir, "existing.key");
411 writeFileSync(target, "preserve-existing-file");
412 const cleanEnv = { ...process.env };
413 for (const marker of ["CI", "GITHUB_ACTIONS", "GITLAB_CI", "BUILDKITE", "CIRCLECI", "JENKINS_URL", "TF_BUILD"]) delete cleanEnv[marker];
414 const result = spawnSync(process.execPath, [script, "keygen", "--key-id", "cwf-test-exclusive", "--out", target], { encoding: "utf8", env: cleanEnv });
415 expect(result.status).toBe(1);
416 expect(readFileSync(target, "utf8")).toBe("preserve-existing-file");
417 if (process.platform !== "win32") {
418 const link = join(dir, "linked.key");
419 symlinkSync(target, link);
420 expect(spawnSync(process.execPath, [script, "keygen", "--key-id", "cwf-test-exclusive", "--out", link], { encoding: "utf8", env: cleanEnv }).status).toBe(1);
421 expect(readFileSync(target, "utf8")).toBe("preserve-existing-file");
422 }
423 } finally { rmSync(dir, { recursive: true, force: true }); }
424 });
425
426 it("rejects signed numeric SQL injection and emits escaped SQL only after verification", () => {
427 const malicious = signed({ facts_version: "7; DROP TABLE public.facts_key;" });
428 expect(() => emitSql(malicious, { publicKeyB64: EPHEMERAL_KEY.publicKey })).toThrow("positive safe integer");
429 const sql = emitSql(fixture, { publicKeyB64: TEST_KEY.publicKey, publishedBy: "O'Hara" });
430 expect(sql).toContain("select c.id, 7, 1, 1");
431 expect(sql).toContain("O''Hara");
432 });
433
434 it("parses intentional empty key tables but fails closed on unknown syntax or duplicate/invalid anchors", () => {
435 expect(parseTsKeys("export const TRUSTED_KEYS: readonly TrustedKey[] = [];")).toEqual([]);
436 expect(parseRustKeys("pub const TRUSTED_KEYS: &[TrustedKey] = &[];")).toEqual([]);
437 for (const text of ["no table", "export const TRUSTED_KEYS: readonly TrustedKey[] = [makeKey()];"]) expect(() => parseTsKeys(text)).toThrow();
438 expect(() => parseRustKeys("pub const TRUSTED_KEYS: &[TrustedKey] = &[make_key()];")).toThrow();
439 expect(() => parseTsKeys("// export const TRUSTED_KEYS: readonly TrustedKey[] = [];\nexport const TRUSTED_KEYS = makeKeys();")).toThrow();
440 expect(() => parseRustKeys("// pub const TRUSTED_KEYS: &[TrustedKey] = &[];\npub const TRUSTED_KEYS: &[TrustedKey] = &[make_key()];")).toThrow();
441 const entry = `{ keyId: "${TEST_KEY.keyId}", publicKey: "${TEST_KEY.publicKey}", status: "active", role: "founder" }`;
442 expect(() => parseTsKeys(`export const TRUSTED_KEYS: readonly TrustedKey[] = [${entry}, ${entry}];`)).toThrow();
443 expect(() => parseTsKeys(`export const TRUSTED_KEYS: readonly TrustedKey[] = [${entry.replace(TEST_KEY.publicKey, "bad")}];`)).toThrow();
444 const rust = `pub const TRUSTED_KEYS: &[TrustedKey] = &[TrustedKey { key_id: "${TEST_KEY.keyId}", public_key: [${[...Buffer.from(TEST_KEY.publicKey, "base64")].join(",")}], status: KeyStatus::Active, role: KeyRole::Founder }];`;
445 expect(parseRustKeys(rust)).toEqual([TEST_KEY]);
446 expect(parseRustKeys(rust.replace("KeyRole::Founder", "KeyRole::Automation"))).toEqual([{ ...TEST_KEY, role: "automation" }]);
447 expect(() => parseRustKeys(rust.replace(", role: KeyRole::Founder", ""))).toThrow();
448 expect(() => parseTsKeys(`export const TRUSTED_KEYS: readonly TrustedKey[] = [${entry.replace(', role: "founder"', "")}];`)).toThrow();
449 expect(() => parseTsKeys(`export const TRUSTED_KEYS: readonly TrustedKey[] = [${entry.replace('"founder"', '"root"')}];`)).toThrow();
450 });
451
452 it("bounds publisher file/response reads and rejects symlink and hardlink inputs", async () => {
453 const dir = mkdtempSync(join(tmpdir(), "facts-bounded-read-"));
454 try {
455 const target = join(dir, "source.json");
456 writeFileSync(target, "12345");
457 expect(() => readBoundedFile(target, 4)).toThrow();
458 if (process.platform !== "win32") {
459 const link = join(dir, "symlink.json");
460 symlinkSync(target, link);
461 expect(() => readBoundedFile(link)).toThrow();
462 linkSync(target, join(dir, "hardlink.json"));
463 expect(() => readBoundedFile(target)).toThrow();
464 }
465 const oversized = overflowingStream();
466 await expect(readBoundedResponse(new Response(oversized.stream))).rejects.toThrow("size limit");
467 expect(oversized.cancel).toHaveBeenCalledOnce();
468 } finally { rmSync(dir, { recursive: true, force: true }); }
469 });
470
471 it("the local facts gate verifies both public fixtures and reports the pinned anchor count", () => {
472 const checker = fileURLToPath(new URL("../scripts/check-cloud-facts.mjs", import.meta.url));
473 // Derived from the table rather than hardcoded, so rotating or adding an
474 // anchor does not require editing this assertion — only a gate that has
475 // drifted out of step with the table will fail it.
476 const active = TRUSTED_KEYS.filter((key) => key.status === "active").length;
477 expect(execFileSync(process.execPath, [checker], { encoding: "utf8" })).toContain(
478 `${active} active production keys`,
479 );
480 });
481 });
482
483 describe("automation key scope", () => {
484 const AUTOMATION_KEY: TrustedKey = { ...EPHEMERAL_KEY, role: "automation" };
485 const fixture = JSON.parse(readFileSync(new URL("../../crates/cloud-facts/fixtures/automation-scope-cases.json", import.meta.url), "utf8")) as
486 { now: number; cases: { name: string; channel: string; payload: Record<string, unknown>; out_of_scope: string | null }[] };
487 const now = fixture.now * 1000;
488
489 function sealed(payload: Record<string, unknown>, extra: CloudFactsEnvelope["sigs"] = []): CloudFactsEnvelope {
490 const bytes = Buffer.from(JSON.stringify(payload));
491 return {
492 envelope: 1, channel: payload.channel as string, facts_version: payload.facts_version as number,
493 schema_version: payload.schema_version as number, key_id: EPHEMERAL_KEY.keyId, alg: "ed25519",
494 applies_to: payload.applies_to as string, published_at: payload.published_at as string,
495 not_after: (payload.not_after as string | undefined) ?? null, payload_b64: bytes.toString("base64"),
496 sig_b64: sign(null, signingMessage(EPHEMERAL_KEY.keyId, bytes), ephemeral.privateKey).toString("base64"),
497 sigs: extra, sha256: createHash("sha256").update(bytes).digest("hex"),
498 };
499 }
500
501 it("judges every shared case as the fixture says, in the relay and in the publish script", async () => {
502 expect(fixture.cases).toHaveLength(25);
503 for (const { name, channel, payload, out_of_scope } of fixture.cases) {
504 const envelope = sealed(payload);
505 const relay = await verifyEnvelope(envelope, [AUTOMATION_KEY], { channel, now });
506 const publish = () => activePublishingKey(envelope, [AUTOMATION_KEY], now);
507 if (out_of_scope === null) {
508 expect(relay, name).toEqual({ ok: true, keyId: AUTOMATION_KEY.keyId, mode: "verified" });
509 expect(publish().key.keyId, name).toBe(AUTOMATION_KEY.keyId);
510 } else {
511 expect(relay, name).toEqual({ ok: false, reason: "out-of-scope" });
512 expect(publish, name).toThrow();
513 }
514 expect((await verifyEnvelope(envelope, [EPHEMERAL_KEY], { channel, now })).ok, name).toBe(true);
515 }
516 });
517
518 it("lets a founder signature decide in either order, and never a retired one", async () => {
519 const founder = generateKeyPairSync("ed25519");
520 const FOUNDER_KEY: TrustedKey = { keyId: "cwf-founder-test", publicKey: founder.publicKey.export({ type: "spki", format: "der" }).subarray(-32).toString("base64"), status: "active", role: "founder" };
521 const payload = fixture.cases.find((entry) => entry.name === "default model")!.payload;
522 const bytes = Buffer.from(JSON.stringify(payload));
523 const founderSig = { key_id: FOUNDER_KEY.keyId, sig_b64: sign(null, signingMessage(FOUNDER_KEY.keyId, bytes), founder.privateKey).toString("base64") };
524 const autoFirst = sealed(payload, [founderSig]);
525 const opts = { channel: "stable-models", now };
526 expect(await verifyEnvelope(autoFirst, [AUTOMATION_KEY, FOUNDER_KEY], opts)).toMatchObject({ ok: true, keyId: FOUNDER_KEY.keyId });
527 const founderFirst = { ...autoFirst, key_id: founderSig.key_id, sig_b64: founderSig.sig_b64, sigs: [{ key_id: autoFirst.key_id, sig_b64: autoFirst.sig_b64 }] };
528 expect(await verifyEnvelope(founderFirst, [AUTOMATION_KEY, FOUNDER_KEY], opts)).toMatchObject({ ok: true, keyId: FOUNDER_KEY.keyId });
529 expect(await verifyEnvelope(autoFirst, [AUTOMATION_KEY, { ...FOUNDER_KEY, status: "retired" }], opts)).toEqual({ ok: false, reason: "out-of-scope" });
530 });
531
532 it("pins no automation key in production and rejects one key under two ids", async () => {
533 expect(TRUSTED_KEYS.every((key) => key.role === "founder")).toBe(true);
534 const entry = (id: string, role: string) => `{ keyId: "${id}", publicKey: "${TEST_KEY.publicKey}", status: "active", role: "${role}" }`;
535 expect(() => parseTsKeys(`export const TRUSTED_KEYS: readonly TrustedKey[] = [${entry("cwf-a", "founder")}, ${entry("cwf-b", "automation")}];`)).toThrow();
536 expect(await verifyEnvelope(sealed(fixture.cases[0].payload), [EPHEMERAL_KEY, { ...AUTOMATION_KEY, keyId: "cwf-dup-key" }], { channel: "stable-models", now })).toEqual({ ok: false, reason: "no-active-keys" });
537 });
538 });
539
540 describe("registry channel relay and publisher", () => {
541 const AUTOMATION_KEY: TrustedKey = { ...EPHEMERAL_KEY, role: "automation" };
542 const REG_NOW = Date.parse("2026-11-17T19:00:00Z");
543
544 function bundledProvidersList(): Record<string, unknown>[] {
545 return Object.entries(bundledRegistryTrust.providers).map(([id, trust], position) => ({
546 id,
547 ...trust,
548 position,
549 label: id,
550 }));
551 }
552
553 function sampleRegistry(overrides: Record<string, unknown> = {}): Record<string, unknown> {
554 const providers = bundledProvidersList();
555 return {
556 schema: "codewhale.registry.v1",
557 revision: 12,
558 content_hash: `sha256:${"a".repeat(64)}`,
559 generated_at: "2026-11-17T18:00:00Z",
560 source: { engine: { repository: "codewhale", commit: "b".repeat(40) }, revision_seq: 12, revision_kind: "engine_import" },
561 counts: { providers: providers.length, models: 1, offerings: 1 },
562 providers,
563 models: [{ id: "deepseek/deepseek-v4-flash", catalog: { name: "DeepSeek Flash" } }],
564 offerings: [{ provider: "deepseek", id: "deepseek-flash", model: "deepseek/deepseek-v4-flash" }],
565 dialects: { default_profile: "standard", custom_allowed_profiles: ["standard"], profiles: [], bindings: [] },
566 engine_compat: { provider_descriptors: bundledRegistryTrust.providerDescriptorsCompat },
567 ...overrides,
568 };
569 }
570
571 it("verifies and serves founder-signed registry envelopes, including >512 KiB payloads and admitted providers", async () => {
572 expect(MAX_REGISTRY_ENVELOPE_BYTES).toBe(11_250_344);
573 const largePadding = "x".repeat(540 * 1024);
574 const payload = buildRegistryPayload(sampleRegistry({
575 generated_at: "2026-11-17T18:00:00.000Z",
576 providers: [
577 ...bundledProvidersList(),
578 {
579 id: "acme",
580 origin: "descriptor",
581 position: 99,
582 label: "Acme",
583 wire_policy: "openai-compatible",
584 base_url: "https://api.acme.example/v1",
585 auth: { secret_slot: "acme", env_vars: ["ACME_API_KEY"] },
586 admission: { id: "radm_1", reviewed_by: "founder", reviewed_at: "2026-11-17T18:00:00Z", founder_signature: "required" },
587 },
588 ],
589 engine_compat: { provider_descriptors: bundledRegistryTrust.providerDescriptorsCompat, pad: largePadding },
590 }));
591 expect(payload.generated_at).toBe("2026-11-17T18:00:00Z");
592 const envelope = buildEnvelope({ privateKey: ephemeral.privateKey, keyId: EPHEMERAL_KEY.keyId, payload });
593 expect(envelope.channel).toBe("registry");
594 expect(envelope.facts_version).toBe(12);
595 expect(envelope.published_at).toBe("2026-11-17T18:00:00Z");
596
597 expect(await verifyEnvelope(envelope, [EPHEMERAL_KEY], { channel: "registry", now: REG_NOW })).toEqual({
598 ok: true,
599 keyId: EPHEMERAL_KEY.keyId,
600 mode: "verified",
601 });
602 expect(verifyForPublisher(envelope, EPHEMERAL_KEY.publicKey).ok).toBe(true);
603 expect(activePublishingKey(envelope, [EPHEMERAL_KEY], REG_NOW).key.keyId).toBe(EPHEMERAL_KEY.keyId);
604 expect(emitSql(envelope, { publishedBy: "founder", publicKeyB64: EPHEMERAL_KEY.publicKey })).toContain("and c.slug = 'registry'");
605
606 const releaseRow = {
607 facts_version: envelope.facts_version,
608 schema_version: envelope.schema_version,
609 envelope_version: envelope.envelope,
610 applies_to: envelope.applies_to,
611 key_id: envelope.key_id,
612 payload_b64: envelope.payload_b64,
613 sig_b64: envelope.sig_b64,
614 sigs: envelope.sigs,
615 payload,
616 published_at: envelope.published_at,
617 not_after: envelope.not_after ?? null,
618 };
619 expect(Buffer.byteLength(JSON.stringify(releaseRow))).toBeGreaterThan(MAX_ENVELOPE_BYTES);
620 const seenPaths: string[] = [];
621 const postgrestOverHttp = async (path: string, init: { method?: string; body?: Record<string, unknown>; prefer?: string } = {}) => {
622 seenPaths.push(`${init.method ?? "GET"} ${path}`);
623 let bodyObj: unknown = null;
624 if (path.startsWith("facts_channel")) bodyObj = [{ id: "c-reg" }];
625 else if (path === "facts_key") bodyObj = null;
626 else if (path === "facts_release?select=id,payload_sha256") bodyObj = [{ id: "r-reg-12", payload_sha256: envelope.sha256 }];
627 else if (path === "facts_release") bodyObj = [{ id: "r-reg-12", payload_sha256: envelope.sha256, ...releaseRow }];
628 const res = new Response(bodyObj === null ? "" : JSON.stringify(bodyObj));
629 const text = await readBoundedResponse(res);
630 return text ? JSON.parse(text) : null;
631 };
632 const published = await publishRelease(postgrestOverHttp, envelope, releaseRow, EPHEMERAL_KEY.publicKey);
633 expect(published).toEqual({
634 published: true,
635 channel: "registry",
636 facts_version: 12,
637 release_id: "r-reg-12",
638 payload_sha256: envelope.sha256,
639 });
640 expect(seenPaths).toContain("POST facts_release?select=id,payload_sha256");
641
642 const kv = new MemKV();
643 const resolved = await resolveCloudFacts("registry", { ...env, CURATED_KV: kv }, {
644 keys: [EPHEMERAL_KEY],
645 now: () => REG_NOW,
646 fetchImpl: supabaseFetch([rowFrom(envelope, { published_at: "2026-11-17T18:00:00+00:00" })]),
647 });
648 expect(resolved).toMatchObject({ kind: "ok", keyId: EPHEMERAL_KEY.keyId, envelope: { channel: "registry", facts_version: 12, published_at: "2026-11-17T18:00:00Z" } });
649 const httpRes = responseFor(resolved, new Request("https://codewhale.dev/api/facts/v1/registry"), "registry", "GET");
650 expect(httpRes.status).toBe(200);
651 expect(httpRes.headers.get("X-Facts-Channel")).toBe("registry");
652 expect(httpRes.headers.get("X-Facts-Version")).toBe("12");
653 });
654
655 it("permits automation-signed model/offering registry updates with bounded not_after and refuses unbundled or mutated providers", async () => {
656 const providersWithNamingUpdate = bundledProvidersList().map((row) =>
657 row.id === "deepseek" ? { ...row, models: { ids: "strict", aliases: { "deepseek-next": "deepseek-chat" } } } : row,
658 );
659 const modelOnlyPayload = buildRegistryPayload(sampleRegistry({ providers: providersWithNamingUpdate }), {
660 notAfter: "2026-11-20T18:00:00Z",
661 });
662 const modelOnlyEnvelope = buildEnvelope({ privateKey: ephemeral.privateKey, keyId: EPHEMERAL_KEY.keyId, payload: modelOnlyPayload });
663 expect(await verifyEnvelope(modelOnlyEnvelope, [AUTOMATION_KEY], { channel: "registry", now: REG_NOW })).toEqual({
664 ok: true,
665 keyId: AUTOMATION_KEY.keyId,
666 mode: "verified",
667 });
668 expect(activePublishingKey(modelOnlyEnvelope, [AUTOMATION_KEY], REG_NOW).key.keyId).toBe(AUTOMATION_KEY.keyId);
669
670 const noExpiry = buildEnvelope({ privateKey: ephemeral.privateKey, keyId: EPHEMERAL_KEY.keyId, payload: buildRegistryPayload(sampleRegistry()) });
671 expect(await verifyEnvelope(noExpiry, [AUTOMATION_KEY], { channel: "registry", now: REG_NOW })).toEqual({ ok: false, reason: "out-of-scope" });
672 expect(() => activePublishingKey(noExpiry, [AUTOMATION_KEY], REG_NOW)).toThrow(/no not_after/);
673
674 const tooLong = buildEnvelope({
675 privateKey: ephemeral.privateKey,
676 keyId: EPHEMERAL_KEY.keyId,
677 payload: buildRegistryPayload(sampleRegistry(), { notAfter: "2026-12-01T18:00:00Z" }),
678 });
679 expect(await verifyEnvelope(tooLong, [AUTOMATION_KEY], { channel: "registry", now: REG_NOW })).toEqual({ ok: false, reason: "out-of-scope" });
680
681 for (const badRegistry of [
682 sampleRegistry({
683 providers: [
684 ...bundledProvidersList(),
685 {
686 id: "acme",
687 origin: "descriptor",
688 position: 99,
689 label: "Acme",
690 wire_policy: "openai-compatible",
691 base_url: "https://api.acme.example/v1",
692 auth: { secret_slot: "acme", env_vars: ["ACME_API_KEY"] },
693 },
694 ],
695 }),
696 sampleRegistry({
697 providers: bundledProvidersList().map((row) =>
698 row.id === "openai" ? { ...row, base_url: "https://evil.example/v1" } : row,
699 ),
700 }),
701 sampleRegistry({
702 providers: bundledProvidersList().slice(1),
703 }),
704 sampleRegistry({
705 engine_compat: { provider_descriptors: { ...bundledRegistryTrust.providerDescriptorsCompat, injected: true } },
706 }),
707 ]) {
708 const badEnvelope = buildEnvelope({
709 privateKey: ephemeral.privateKey,
710 keyId: EPHEMERAL_KEY.keyId,
711 payload: buildRegistryPayload(badRegistry, { notAfter: "2026-11-20T18:00:00Z" }),
712 });
713 expect(await verifyEnvelope(badEnvelope, [AUTOMATION_KEY], { channel: "registry", now: REG_NOW })).toEqual({
714 ok: false,
715 reason: "out-of-scope",
716 });
717 expect(() => activePublishingKey(badEnvelope, [AUTOMATION_KEY], REG_NOW)).toThrow(/founder signature/);
718 }
719 });
720
721 it("rejects tampered outer metadata, channel confusion, and oversized stable payloads", async () => {
722 const payload = buildRegistryPayload(sampleRegistry(), { notAfter: "2026-11-20T18:00:00Z", appliesTo: ">=0.10.3" });
723 const envelope = buildEnvelope({ privateKey: ephemeral.privateKey, keyId: EPHEMERAL_KEY.keyId, payload });
724 expect(envelope.applies_to).toBe(">=0.10.3");
725 expect(await verifyEnvelope(envelope, [EPHEMERAL_KEY], { channel: "registry", now: REG_NOW })).toEqual({
726 ok: true,
727 keyId: EPHEMERAL_KEY.keyId,
728 mode: "verified",
729 });
730 expect(await verifyEnvelope(envelope, [EPHEMERAL_KEY], { channel: "stable", now: REG_NOW })).toEqual({ ok: false, reason: "wrong-channel" });
731 for (const tampered of [
732 { facts_version: 13 },
733 { published_at: "2026-11-17T18:00:01Z" },
734 { applies_to: "*" },
735 { applies_to: ">=99.0.0" },
736 { not_after: null },
737 { not_after: "2026-11-21T18:00:00Z" },
738 ]) {
739 expect((await verifyEnvelope({ ...envelope, ...tampered }, [EPHEMERAL_KEY], { channel: "registry", now: REG_NOW })).ok).toBe(false);
740 expect(verifyForPublisher({ ...envelope, ...tampered }, EPHEMERAL_KEY.publicKey).ok).toBe(false);
741 }
742 });
743 });
744
744 lines TYPESCRIPT