返回 CodeWhale
cloud-facts.ts
根目录 / web / lib / cloud-facts.ts
1 /** Verified facts/v1 delivery. Supabase and KV are untrusted transports; only
2 * active, pinned public keys authenticate the exact payload bytes. */
3 import {
4 AUTOMATION_CHANNEL_SUFFIX,
5 AUTOMATION_MAX_MODELS,
6 AUTOMATION_MAX_VALIDITY_MS,
7 DOMAIN,
8 MAX_PAYLOAD_BYTES,
9 MAX_REGISTRY_ENVELOPE_BYTES,
10 MAX_REGISTRY_PAYLOAD_BYTES,
11 REGISTRY_CHANNEL,
12 REGISTRY_SCHEMA,
13 TRUSTED_KEYS,
14 type KeyRole,
15 type TrustedKey,
16 } from "./cloud-facts/keys";
17 import { readBoundedBody } from "./bounded-body";
18 import bundledRegistryTrust from "./cloud-facts/bundled-providers.json";
19 import { readBoundedKvJson, type KVStreamNamespace } from "./kv";
20
21 export const CHANNEL_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;
22 export const KV_PREFIX = "facts:cloud:";
23 export const SUPABASE_TIMEOUT_MS = 3000;
24 export const MAX_ENVELOPE_BYTES = 768 * 1024;
25
26 export function maxPayloadBytesFor(channel: string): number {
27 return channel === REGISTRY_CHANNEL ? MAX_REGISTRY_PAYLOAD_BYTES : MAX_PAYLOAD_BYTES;
28 }
29
30 export function maxEnvelopeBytesFor(channel: string): number {
31 return channel === REGISTRY_CHANNEL ? MAX_REGISTRY_ENVELOPE_BYTES : MAX_ENVELOPE_BYTES;
32 }
33 // The last-good copy only bridges a transport outage. It lives no longer than
34 // a client keeps applying its own cached envelope (payload ttl_secs, 6 h by
35 // default, docs/CLOUD_FACTS.md), so an outage cannot extend a withdrawn
36 // release beyond the staleness every client already accepts.
37 const KV_TTL_SECS = 60 * 60 * 6;
38 const KEY_ID_RE = /^cwf-[a-z0-9-]{1,32}$/;
39 const VERSION_REQ_RE = /^(\*|(?:>=|<=|>|<|=|\^|~)?\s*\d+(\.\d+){0,2}(-[0-9A-Za-z.-]+)?(\s*,\s*(?:>=|<=|>|<|=|\^|~)?\s*\d+(\.\d+){0,2}(-[0-9A-Za-z.-]+)?)*)$/;
40 const MAX_SIGNATURES = 7; // Plus the primary signature: eight candidates total.
41 const CLOCK_SKEW_MS = 5 * 60 * 1000;
42
43 export interface FactsCurrentRow {
44 channel: string;
45 release_id: string;
46 facts_version: number;
47 schema_version: number;
48 envelope_version: number;
49 applies_to: string;
50 key_id: string;
51 payload_b64: string;
52 sig_b64: string;
53 sigs: { key_id: string; sig_b64: string }[] | null;
54 payload_sha256: string;
55 published_at: string;
56 not_after: string | null;
57 }
58
59 export interface CloudFactsEnvelope {
60 envelope: number;
61 channel: string;
62 facts_version: number;
63 schema_version: number;
64 key_id: string;
65 alg: "ed25519";
66 applies_to: string;
67 published_at: string;
68 not_after?: string | null;
69 payload_b64: string;
70 sig_b64: string;
71 sigs: { key_id: string; sig_b64: string }[];
72 sha256: string;
73 }
74
75 export interface CloudFactsEnv {
76 SUPABASE_URL?: string;
77 SUPABASE_PUBLISHABLE_KEY?: string;
78 CURATED_KV?: KVStreamNamespace;
79 }
80
81 type Rejection = "no-active-keys" | "unknown-key" | "retired-key" | "bad-signature" |
82 "bad-envelope" | "bad-payload" | "sha-mismatch" | "wrong-channel" | "expired" | "out-of-scope";
83 export type Verification =
84 | { ok: true; keyId: string; mode: "verified" }
85 | { ok: false; reason: Rejection };
86
87 export type CloudFactsResult =
88 | {
89 kind: "ok";
90 envelope: CloudFactsEnvelope;
91 body: string;
92 etag: string;
93 source: "supabase" | "kv-stale";
94 verified: "verified";
95 keyId: string;
96 }
97 | { kind: "none" }
98 | { kind: "sha-mismatch"; channel: string; factsVersion: number }
99 | { kind: "unverifiable"; reason: string; channel: string; factsVersion: number }
100 | { kind: "unavailable"; reason: string };
101
102 export interface ResolveOptions {
103 fetchImpl?: typeof fetch;
104 keys?: readonly TrustedKey[];
105 timeoutMs?: number;
106 now?: () => number;
107 }
108
109 export function isValidChannel(slug: string): boolean {
110 return CHANNEL_RE.test(slug);
111 }
112
113 function isObject(value: unknown): value is Record<string, unknown> {
114 return value !== null && typeof value === "object" && !Array.isArray(value);
115 }
116
117 /** Reject noncanonical/oversized encodings before either decoder allocates. */
118 function b64ToBytes(value: unknown, maxBytes: number): Uint8Array {
119 if (typeof value !== "string" || !value.length || value.length > 4 * Math.ceil(maxBytes / 3) ||
120 (value.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(value))) {
121 throw new Error("invalid-base64");
122 }
123 const bin = atob(value);
124 if (bin.length > maxBytes || btoa(bin) !== value) throw new Error("invalid-base64");
125 return Uint8Array.from(bin, (char) => char.charCodeAt(0));
126 }
127
128 export async function sha256Hex(bytes: Uint8Array): Promise<string> {
129 const digest = await crypto.subtle.digest("SHA-256", bytes as BufferSource);
130 return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
131 }
132
133 export function signingMessage(keyId: string, payload: Uint8Array): Uint8Array {
134 const prefix = new TextEncoder().encode(`${DOMAIN}${keyId}\0`);
135 const out = new Uint8Array(prefix.length + payload.length);
136 out.set(prefix);
137 out.set(payload, prefix.length);
138 return out;
139 }
140
141 function hasActiveKeys(keys: readonly TrustedKey[]): boolean {
142 const seen = new Set<string>();
143 try {
144 for (const key of keys) {
145 if (!KEY_ID_RE.test(key.keyId) || seen.has(key.keyId) || seen.has(key.publicKey) ||
146 !["active", "retired"].includes(key.status) || !["founder", "automation"].includes(key.role) ||
147 b64ToBytes(key.publicKey, 32).length !== 32) return false;
148 seen.add(key.keyId);
149 seen.add(key.publicKey);
150 }
151 return keys.some((key) => key.status === "active");
152 } catch { return false; }
153 }
154
155 function utcTime(value: unknown): number | null {
156 if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/.test(value)) return null;
157 const time = Date.parse(value);
158 // Date.parse normalizes invalid civil dates such as February 30.
159 return Number.isFinite(time) && new Date(time).toISOString().slice(0, 19) === value.slice(0, 19) ? time : null;
160 }
161
162 function validSignature(value: unknown): boolean {
163 if (!isObject(value) || typeof value.key_id !== "string" || !KEY_ID_RE.test(value.key_id)) return false;
164 try { return b64ToBytes(value.sig_b64, 64).length === 64; } catch { return false; }
165 }
166
167 function isEnvelope(value: unknown): value is CloudFactsEnvelope {
168 if (!isObject(value)) return false;
169 return value.envelope === 1 && value.alg === "ed25519" && value.schema_version === 1 &&
170 typeof value.channel === "string" && isValidChannel(value.channel) &&
171 Number.isSafeInteger(value.facts_version) && Number(value.facts_version) > 0 &&
172 typeof value.applies_to === "string" && value.applies_to.length <= 200 && VERSION_REQ_RE.test(value.applies_to) &&
173 utcTime(value.published_at) !== null && (value.not_after == null || utcTime(value.not_after) !== null) &&
174 typeof value.sha256 === "string" && /^[a-f0-9]{64}$/.test(value.sha256) &&
175 typeof value.payload_b64 === "string" && validSignature(value) &&
176 Array.isArray(value.sigs) && value.sigs.length <= MAX_SIGNATURES && value.sigs.every(validSignature);
177 }
178
179 function rowTimestamp(value: string): string {
180 // PostgREST emits timestamptz as +00:00; the signed contract uses UTC Z.
181 if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?(?:Z|[+-]\d{2}:\d{2})$/.test(value)) return value;
182 const time = Date.parse(value);
183 return Number.isFinite(time) ? new Date(time).toISOString().replace(/\.000Z$/, "Z") : value;
184 }
185
186 export function envelopeFromRow(row: FactsCurrentRow): CloudFactsEnvelope {
187 return {
188 envelope: row.envelope_version,
189 channel: row.channel,
190 facts_version: row.facts_version,
191 schema_version: row.schema_version,
192 key_id: row.key_id,
193 alg: "ed25519",
194 applies_to: row.applies_to,
195 published_at: rowTimestamp(row.published_at),
196 not_after: row.not_after == null ? null : rowTimestamp(row.not_after),
197 payload_b64: row.payload_b64,
198 sig_b64: row.sig_b64,
199 sigs: row.sigs === null ? [] : row.sigs,
200 sha256: row.payload_sha256,
201 };
202 }
203
204 /** A strong validator covers signatures and every other byte of the response. */
205 export async function etagFor(envelope: CloudFactsEnvelope): Promise<string> {
206 return `"${await sha256Hex(new TextEncoder().encode(JSON.stringify(envelope)))}"`;
207 }
208
209 const AUTOMATION_PAYLOAD_FIELDS = new Set([
210 "schema_version", "channel", "facts_version", "published_at", "not_after", "applies_to",
211 "models", "provider_defaults", "release", "announcements",
212 ]);
213 const AUTOMATION_MODEL_FIELDS = new Set([
214 "provider", "id", "op", "context_window", "max_output", "reasoning", "display_name",
215 "deprecated_at", "replacement", "note", "applies_to", "pricing_withheld",
216 ]);
217
218 export function automationScopeViolation(facts: Record<string, unknown>, channel: string, published: number, expires: number | null): string | null {
219 if (!channel.endsWith(AUTOMATION_CHANNEL_SUFFIX) || channel.length <= AUTOMATION_CHANNEL_SUFFIX.length || !/^[a-z0-9]/.test(channel)) return `channel ${JSON.stringify(channel)} is not an automation channel`;
220 const plain = (value: unknown, max: number): boolean => value === undefined || (typeof value === "string" && [...value].length <= max && !/\p{Cc}/u.test(value));
221 if (!plain(facts.applies_to, 200)) return "applies_to is too long or not plain";
222 if (isObject(facts.provider_defaults) && Object.keys(facts.provider_defaults).length > 0) return "provider defaults";
223 if (facts.release != null) return "release facts";
224 if (Array.isArray(facts.announcements) && facts.announcements.length > 0) return "announcements";
225 const unknown = Object.keys(facts).find((field) => !AUTOMATION_PAYLOAD_FIELDS.has(field));
226 if (unknown !== undefined) return `field ${JSON.stringify(unknown)} is not allowed`;
227 const models = facts.models === undefined ? [] : facts.models;
228 if (!Array.isArray(models)) return "models is not a list";
229 if (models.length > AUTOMATION_MAX_MODELS) return `more than ${AUTOMATION_MAX_MODELS} models`;
230 for (const model of models) {
231 if (!isObject(model) || typeof model.provider !== "string" || !model.provider || typeof model.id !== "string" || !model.id) return "malformed model entry";
232 const name = `${model.provider}/${model.id}`;
233 const field = Object.keys(model).find((key) => !AUTOMATION_MODEL_FIELDS.has(key));
234 if (field !== undefined) return `${name}: field ${JSON.stringify(field)} is not allowed`;
235 const nullField = Object.keys(model).find((key) => model[key] === null);
236 if (nullField !== undefined) return `${name}: field ${JSON.stringify(nullField)} is null`;
237 const op = model.op === undefined ? "upsert" : model.op;
238 if (op !== "upsert" && op !== "deprecate") return `${name} is not an upsert or deprecation`;
239 if (model.reasoning !== undefined && typeof model.reasoning !== "boolean") return `${name}: malformed model entry`;
240 if (!plain(model.provider, 64) || !plain(model.id, 200) || !plain(model.display_name, 120) || !plain(model.deprecated_at, 40) ||
241 !plain(model.replacement, 200) || !plain(model.note, 300) || !plain(model.applies_to, 200) || !plain(model.pricing_withheld, 300)) return `${name}: text too long or not plain`;
242 const window = model.context_window;
243 const output = model.max_output;
244 const windowOk = window === undefined || (typeof window === "number" && Number.isSafeInteger(window) && window >= 1024 && window <= 20_000_000);
245 const outputOk = output === undefined || (typeof output === "number" && Number.isSafeInteger(output) && output >= 1 && output <= 2_000_000 && (typeof window !== "number" || output <= window));
246 if (!windowOk || !outputOk) return `${name}: limit out of range`;
247 }
248 const wholeSecond = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/;
249 if (typeof facts.published_at !== "string" || !wholeSecond.test(facts.published_at) ||
250 (facts.not_after != null && (typeof facts.not_after !== "string" || !wholeSecond.test(facts.not_after)))) return "timestamp is not whole-second UTC";
251 if (facts.facts_version !== published / 1000) return "facts_version is not the publication time";
252 if (expires === null) return "no not_after";
253 if (expires <= published || expires - published > AUTOMATION_MAX_VALIDITY_MS) return "validity outside the automation limit";
254 return null;
255 }
256
257 const REGISTRY_PROVIDER_TRUST_FIELDS = [
258 "origin", "kind", "base_url", "base_url_config_key", "env_vars", "api_key_env",
259 "secret_store_slot", "config_key", "wire", "wire_policy", "auth", "aliases",
260 "selector_aliases", "subagent_aliases", "credential_help", "credential_url",
261 "docs_url", "discovery", "catalog_id", "catalog_source_id", "tui_wire_tag",
262 "table_field", "web",
263 ] as const;
264
265 function canonicalJsonValue(value: unknown): string {
266 if (value === null || typeof value !== "object") return JSON.stringify(value);
267 if (Array.isArray(value)) return `[${value.map(canonicalJsonValue).join(",")}]`;
268 const record = value as Record<string, unknown>;
269 const parts: string[] = [];
270 for (const key of Object.keys(record).sort()) {
271 if (record[key] !== undefined) parts.push(`${JSON.stringify(key)}:${canonicalJsonValue(record[key])}`);
272 }
273 return `{${parts.join(",")}}`;
274 }
275
276 function projectProviderTrust(row: Record<string, unknown>): Record<string, unknown> {
277 const synthesized: Record<string, unknown> = row.origin === "descriptor" ? { ...row } : row;
278 if (row.origin === "descriptor") {
279 if (synthesized.wire_policy === undefined) {
280 synthesized.wire_policy = typeof synthesized.wire === "string" && synthesized.wire ? synthesized.wire : "openai-compatible";
281 }
282 if (synthesized.auth === undefined) {
283 const env = typeof synthesized.api_key_env === "string" && synthesized.api_key_env
284 ? synthesized.api_key_env
285 : `${String(synthesized.id).toUpperCase().replace(/-/g, "_")}_API_KEY`;
286 synthesized.auth = { secret_slot: synthesized.id, env_vars: [env] };
287 }
288 }
289 const out: Record<string, unknown> = {};
290 for (const field of REGISTRY_PROVIDER_TRUST_FIELDS) {
291 if (synthesized[field] !== undefined) out[field] = synthesized[field];
292 }
293 return out;
294 }
295
296 const BUNDLED_PROVIDER_TRUST: Readonly<Record<string, string>> = Object.fromEntries(
297 Object.entries(bundledRegistryTrust.providers).map(([id, trust]) => [id, canonicalJsonValue(trust)]),
298 );
299 const BUNDLED_PROVIDER_COUNT = Object.keys(BUNDLED_PROVIDER_TRUST).length;
300 const BUNDLED_DESCRIPTORS_COMPAT = canonicalJsonValue(bundledRegistryTrust.providerDescriptorsCompat);
301
302 export function registryAutomationScopeViolation(facts: Record<string, unknown>, published: number, expires: number | null): string | null {
303 if (expires === null) return "no not_after";
304 if (expires <= published || expires - published > AUTOMATION_MAX_VALIDITY_MS) return "validity outside the automation limit";
305 if (!Array.isArray(facts.providers)) return "providers is not a list";
306 const seen = new Set<string>();
307 for (const provider of facts.providers) {
308 if (!isObject(provider) || typeof provider.id !== "string" || !provider.id) return "malformed provider entry";
309 if (seen.has(provider.id)) return `${provider.id}: duplicate provider`;
310 seen.add(provider.id);
311 if (provider.origin !== "builtin" && provider.origin !== "descriptor") return `${provider.id}: unsupported provider origin`;
312 if (provider.admission !== undefined) return `${provider.id}: admitted provider requires a founder signature`;
313 const expectedTrust = BUNDLED_PROVIDER_TRUST[provider.id];
314 if (expectedTrust === undefined) return `${provider.id}: unbundled provider requires a founder signature`;
315 if (canonicalJsonValue(projectProviderTrust(provider)) !== expectedTrust) {
316 return `${provider.id}: provider trust fields require a founder signature`;
317 }
318 }
319 if (seen.size !== BUNDLED_PROVIDER_COUNT) return "missing bundled provider requires a founder signature";
320 if (isObject(facts.engine_compat) && facts.engine_compat.provider_descriptors !== undefined) {
321 if (canonicalJsonValue(facts.engine_compat.provider_descriptors) !== BUNDLED_DESCRIPTORS_COMPAT) {
322 return "engine_compat.provider_descriptors requires a founder signature";
323 }
324 }
325 return null;
326 }
327
328 /** Authenticate first, then validate signed metadata. A channel serves all
329 * client versions; each client evaluates the validated applicability range. */
330 export async function verifyEnvelope(
331 value: unknown,
332 keys: readonly TrustedKey[] = TRUSTED_KEYS,
333 opts: { channel?: string; now?: number } = {},
334 ): Promise<Verification> {
335 if (!hasActiveKeys(keys)) return { ok: false, reason: "no-active-keys" };
336 if (!isEnvelope(value)) return { ok: false, reason: "bad-envelope" };
337 const envelope = value;
338 let payload: Uint8Array;
339 try { payload = b64ToBytes(envelope.payload_b64, maxPayloadBytesFor(envelope.channel)); }
340 catch { return { ok: false, reason: "bad-envelope" }; }
341 let keyId: string | undefined;
342 let keyRole: KeyRole | undefined;
343 let sawKnown = false;
344 let sawRetired = false;
345 for (const candidate of [envelope, ...envelope.sigs]) {
346 const key = keys.find((key) => key.keyId === candidate.key_id);
347 if (!key) continue;
348 if (key.status !== "active") { sawRetired = true; continue; }
349 sawKnown = true;
350 try {
351 const publicKey = await crypto.subtle.importKey("raw", b64ToBytes(key.publicKey, 32) as BufferSource, { name: "Ed25519" }, false, ["verify"]);
352 if (await crypto.subtle.verify({ name: "Ed25519" }, publicKey, b64ToBytes(candidate.sig_b64, 64) as BufferSource, signingMessage(candidate.key_id, payload) as BufferSource)) {
353 if (key.role === "founder") {
354 keyId = candidate.key_id;
355 keyRole = key.role;
356 break;
357 }
358 if (keyId === undefined) {
359 keyId = candidate.key_id;
360 keyRole = key.role;
361 }
362 }
363 } catch { /* An invalid candidate cannot authenticate the payload. */ }
364 }
365 if (!keyId) return { ok: false, reason: sawKnown ? "bad-signature" : sawRetired ? "retired-key" : "unknown-key" };
366 if (await sha256Hex(payload) !== envelope.sha256) return { ok: false, reason: "sha-mismatch" };
367 let facts: Record<string, unknown>;
368 try {
369 const parsed: unknown = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(payload));
370 if (!isObject(parsed)) return { ok: false, reason: "bad-payload" };
371 facts = parsed;
372 } catch { return { ok: false, reason: "bad-payload" }; }
373 if (envelope.channel === REGISTRY_CHANNEL) {
374 if (
375 facts.schema !== REGISTRY_SCHEMA ||
376 facts.revision !== envelope.facts_version ||
377 typeof facts.generated_at !== "string" ||
378 utcTime(facts.generated_at) === null ||
379 facts.generated_at !== envelope.published_at ||
380 (facts.applies_to != null && typeof facts.applies_to !== "string") ||
381 (facts.applies_to == null ? "*" : facts.applies_to) !== envelope.applies_to ||
382 (facts.not_after != null && utcTime(facts.not_after) === null) ||
383 (facts.not_after == null ? null : facts.not_after) !== (envelope.not_after == null ? null : envelope.not_after) ||
384 !Array.isArray(facts.providers) ||
385 !Array.isArray(facts.models) ||
386 !Array.isArray(facts.offerings) ||
387 !isObject(facts.dialects)
388 ) {
389 return { ok: false, reason: "bad-payload" };
390 }
391 if (opts.channel !== undefined && envelope.channel !== opts.channel) return { ok: false, reason: "wrong-channel" };
392 const now = opts.now ?? Date.now();
393 const published = utcTime(facts.generated_at)!;
394 const expires = facts.not_after == null ? null : utcTime(facts.not_after);
395 if (!Number.isFinite(now) || published > now + CLOCK_SKEW_MS || (expires !== null && expires <= published)) {
396 return { ok: false, reason: "bad-payload" };
397 }
398 if (keyRole !== "founder" && registryAutomationScopeViolation(facts, published, expires) !== null) {
399 return { ok: false, reason: "out-of-scope" };
400 }
401 if (expires !== null && now >= expires) return { ok: false, reason: "expired" };
402 return { ok: true, keyId, mode: "verified" };
403 }
404 for (const field of ["channel", "facts_version", "schema_version", "applies_to"] as const) {
405 if (facts[field] !== envelope[field]) return { ok: false, reason: "bad-payload" };
406 }
407 if (utcTime(facts.published_at) === null || utcTime(facts.published_at) !== utcTime(envelope.published_at) ||
408 (facts.not_after != null && utcTime(facts.not_after) === null) ||
409 (facts.not_after == null ? null : utcTime(facts.not_after)) !== (envelope.not_after == null ? null : utcTime(envelope.not_after)) ||
410 (facts.models !== undefined && !Array.isArray(facts.models)) ||
411 (facts.provider_defaults !== undefined && !isObject(facts.provider_defaults)) ||
412 (facts.announcements !== undefined && !Array.isArray(facts.announcements)) ||
413 (facts.release != null && !isObject(facts.release))) return { ok: false, reason: "bad-payload" };
414 if (opts.channel !== undefined && envelope.channel !== opts.channel) return { ok: false, reason: "wrong-channel" };
415 const now = opts.now ?? Date.now();
416 const published = utcTime(facts.published_at)!;
417 const expires = facts.not_after == null ? null : utcTime(facts.not_after);
418 if (!Number.isFinite(now) || published > now + CLOCK_SKEW_MS ||
419 (expires !== null && expires <= published)) return { ok: false, reason: "bad-payload" };
420 if (keyRole !== "founder" && automationScopeViolation(facts, opts.channel ?? envelope.channel, published, expires) !== null) return { ok: false, reason: "out-of-scope" };
421 if (expires !== null && now >= expires) return { ok: false, reason: "expired" };
422 return { ok: true, keyId, mode: "verified" };
423 }
424
425 /** Only publishable keys (or legacy anon JWTs), never secret/service-role keys. */
426 function isPublishableKey(key: string): boolean {
427 if (/^sb_publishable_[A-Za-z0-9_-]+$/.test(key)) return true;
428 if (key.length > 8192) return false;
429 try {
430 const parts = key.split(".");
431 if (parts.length !== 3) return false;
432 const middle = parts[1].replace(/-/g, "+").replace(/_/g, "/");
433 const payload = JSON.parse(atob(middle.padEnd(Math.ceil(middle.length / 4) * 4, "=")));
434 return isObject(payload) && payload.role === "anon";
435 } catch { return false; }
436 }
437
438 export async function fetchCurrentRow(channel: string, env: CloudFactsEnv, opts: ResolveOptions = {}): Promise<FactsCurrentRow | null> {
439 if (!isValidChannel(channel)) throw new Error("invalid-channel");
440 const key = env.SUPABASE_PUBLISHABLE_KEY;
441 let base: URL;
442 try {
443 base = new URL(env.SUPABASE_URL ?? "");
444 if (base.protocol !== "https:" || base.username || base.password || base.search || base.hash || !key || !isPublishableKey(key)) throw new Error();
445 } catch { throw new Error("supabase-not-configured"); }
446 const controller = new AbortController();
447 const timer = setTimeout(() => controller.abort(), opts.timeoutMs ?? SUPABASE_TIMEOUT_MS);
448 try {
449 const url = new URL(`${base.href.replace(/\/+$/, "")}/rest/v1/facts_current`);
450 url.search = new URLSearchParams({ channel: `eq.${channel}`, scope: "eq.global", select: "channel,release_id,facts_version,schema_version,envelope_version,applies_to,key_id,payload_b64,sig_b64,sigs,payload_sha256,published_at,not_after", limit: "1" }).toString();
451 const res = await (opts.fetchImpl ?? fetch)(url, {
452 headers: { apikey: key!, Authorization: `Bearer ${key}`, Accept: "application/json" },
453 signal: controller.signal,
454 redirect: "error",
455 });
456 if (!res.ok) { await res.body?.cancel(); throw new Error(`supabase-http-${res.status}`); }
457 const bytes = await readBoundedBody(res, maxEnvelopeBytesFor(channel));
458 const rows: unknown = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
459 if (!Array.isArray(rows) || rows.length > 1) throw new Error("supabase-bad-row");
460 if (rows.length === 0) return null;
461 if (!isObject(rows[0]) || !isEnvelope(envelopeFromRow(rows[0] as unknown as FactsCurrentRow))) throw new Error("supabase-bad-row");
462 return rows[0] as unknown as FactsCurrentRow;
463 } finally { clearTimeout(timer); }
464 }
465
466 async function retireLastGood(env: CloudFactsEnv, channel: string): Promise<void> {
467 if (!env.CURATED_KV || !isEnvelope(await readBoundedKvJson(env.CURATED_KV, KV_PREFIX + channel, maxEnvelopeBytesFor(channel)))) return;
468 try {
469 await env.CURATED_KV.put(`${KV_PREFIX}${channel}`, JSON.stringify({ retired: "no-current-head" }), { expirationTtl: KV_TTL_SECS });
470 } catch { /* Best effort, like the write; the copy still expires on its TTL. */ }
471 }
472
473 export async function resolveCloudFacts(channel: string, env: CloudFactsEnv, opts: ResolveOptions = {}): Promise<CloudFactsResult> {
474 if (!isValidChannel(channel)) return { kind: "none" };
475 const keys = opts.keys ?? TRUSTED_KEYS;
476 const maxBytes = maxEnvelopeBytesFor(channel);
477 // Do not consult either transport when this release has no usable trust root.
478 if (!hasActiveKeys(keys)) return { kind: "unavailable", reason: "no-active-keys" };
479 let envelope: unknown;
480 let source: "supabase" | "kv-stale" = "supabase";
481 try {
482 const row = await fetchCurrentRow(channel, env, opts);
483 if (!row) {
484 // The head was revoked, expired or future-dated. Retire the last-good
485 // copy so a later outage cannot resurrect it through the stale path.
486 await retireLastGood(env, channel);
487 return { kind: "none" };
488 }
489 envelope = envelopeFromRow(row);
490 } catch {
491 source = "kv-stale";
492 envelope = await readBoundedKvJson(env.CURATED_KV, KV_PREFIX + channel, maxBytes);
493 if (!envelope) return { kind: "unavailable", reason: "facts-transport-unavailable" };
494 }
495 const verification = await verifyEnvelope(envelope, keys, { channel, now: (opts.now ?? Date.now)() });
496 if (!verification.ok) {
497 if (source === "kv-stale" || !isEnvelope(envelope)) return { kind: "unavailable", reason: `facts-${verification.reason}` };
498 if (verification.reason === "sha-mismatch") return { kind: "sha-mismatch", channel, factsVersion: envelope.facts_version };
499 return { kind: "unverifiable", reason: verification.reason, channel, factsVersion: envelope.facts_version };
500 }
501 const verified = envelope as CloudFactsEnvelope;
502 const body = JSON.stringify(verified);
503 if (new TextEncoder().encode(body).length > maxBytes) return { kind: "unavailable", reason: "facts-too-large" };
504 if (source === "supabase" && env.CURATED_KV) {
505 try { await env.CURATED_KV.put(`${KV_PREFIX}${channel}`, body, { expirationTtl: KV_TTL_SECS }); }
506 catch { /* The last-good cache is best effort. */ }
507 }
508 return { kind: "ok", envelope: verified, body, etag: await etagFor(verified), source, verified: "verified", keyId: verification.keyId };
509 }
510
511 export async function cloudFactsSummary(env: CloudFactsEnv, channel = "stable"): Promise<
512 { channel: string; factsVersion: number; publishedAt: string; keyId: string; source: string } | null
513 > {
514 try {
515 const result = await resolveCloudFacts(channel, env);
516 if (result.kind !== "ok") return null;
517 return { channel: result.envelope.channel, factsVersion: result.envelope.facts_version,
518 publishedAt: result.envelope.published_at, keyId: result.keyId, source: result.source };
519 } catch { return null; }
520 }
521
522 const CACHE_CONTROL = "public, max-age=300, s-maxage=300, must-revalidate";
523
524 function cacheControl(envelope: CloudFactsEnvelope): string {
525 if (envelope.not_after == null) return CACHE_CONTROL;
526 const seconds = Math.max(0, Math.min(300, Math.floor((utcTime(envelope.not_after)! - Date.now()) / 1000)));
527 // A CDN must not extend a signed deadline through stale serving directives.
528 return `public, max-age=${seconds}, s-maxage=${seconds}, must-revalidate`;
529 }
530
531 function baseHeaders(): Record<string, string> {
532 return {
533 "Content-Type": "application/json; charset=utf-8",
534 "Access-Control-Allow-Origin": "*",
535 "X-Content-Type-Options": "nosniff",
536 };
537 }
538
539 function errorResponse(status: number, body: Record<string, unknown>, method: "GET" | "HEAD", extra: Record<string, string> = {}): Response {
540 return new Response(method === "HEAD" ? null : JSON.stringify(body), {
541 status,
542 headers: { ...baseHeaders(), "Cache-Control": "no-store", ...extra },
543 });
544 }
545
546 function etagMatches(ifNoneMatch: string | null, etag: string): boolean {
547 if (!ifNoneMatch) return false;
548 return ifNoneMatch
549 .split(",")
550 .map((v) => v.trim().replace(/^W\//, ""))
551 .some((v) => v === etag || v === "*");
552 }
553
554 export function responseFor(result: CloudFactsResult, req: Request, channel: string, method: "GET" | "HEAD"): Response {
555 switch (result.kind) {
556 case "none":
557 return errorResponse(404, { error: "no-facts", channel }, method, { "Cache-Control": "public, max-age=60" });
558 case "sha-mismatch":
559 return errorResponse(502, { error: "facts-digest-mismatch", channel, factsVersion: result.factsVersion }, method);
560 case "unverifiable":
561 return errorResponse(503, { error: "facts-unverifiable", reason: result.reason, channel, factsVersion: result.factsVersion }, method, { "Retry-After": "600" });
562 case "unavailable":
563 return errorResponse(503, { error: "facts-unavailable", channel }, method, { "Retry-After": "600" });
564 case "ok": {
565 const headers: Record<string, string> = {
566 ...baseHeaders(),
567 "Cache-Control": cacheControl(result.envelope),
568 ETag: result.etag,
569 "X-Facts-Channel": result.envelope.channel,
570 "X-Facts-Version": String(result.envelope.facts_version),
571 "X-Facts-Source": result.source,
572 "X-Facts-Verified": result.verified,
573 "X-Facts-Key": result.keyId,
574 };
575 if (etagMatches(req.headers.get("if-none-match"), result.etag)) {
576 return new Response(null, { status: 304, headers });
577 }
578 headers["Content-Length"] = String(new TextEncoder().encode(result.body).length);
579 return new Response(method === "HEAD" ? null : result.body, { status: 200, headers });
580 }
581 }
582 }
583
583 lines TYPESCRIPT