| 1 | #!/usr/bin/env node |
| 2 | /** |
| 3 | * CodeWhale cloud facts (facts/v1) authoring tool. Zero npm dependencies. |
| 4 | * |
| 5 | * node scripts/facts-publish.mjs keygen --key-id cwf-2026-09 --out /secure/path.key |
| 6 | * node scripts/facts-publish.mjs sign --source ../docs/cloud-facts/stable.json --channel stable \ |
| 7 | * --key-id cwf-2026-09 [--facts-version N] [--out envelope.json] |
| 8 | * node scripts/facts-publish.mjs verify envelope.json [--public-key <base64>] |
| 9 | * node scripts/facts-publish.mjs emit-sql envelope.json [--published-by who] [--public-key <base64>] |
| 10 | * node scripts/facts-publish.mjs publish envelope.json [--dry-run] [--published-by who] |
| 11 | * node scripts/facts-publish.mjs revoke --channel stable --version N --reason "..." [--dry-run] |
| 12 | * |
| 13 | * Secrets are read ONLY from the environment at sign/publish time and are never |
| 14 | * printed: |
| 15 | * CODEWHALE_FACTS_SIGNING_KEY PEM (PKCS#8) Ed25519 private key contents |
| 16 | * CODEWHALE_FACTS_SIGNING_KEY_FILE path to that PEM (alternative) |
| 17 | * SUPABASE_URL https://<ref>.supabase.co (publish/revoke) |
| 18 | * SUPABASE_SERVICE_ROLE_KEY service-role key (publish/revoke only; never embed) |
| 19 | * |
| 20 | * Signing contract (must match crates/config/src/cloud_facts/verify.rs and |
| 21 | * web/lib/cloud-facts.ts): Ed25519 detached signature over |
| 22 | * "codewhale-facts/v1\0" || key_id || "\0" || payload_bytes |
| 23 | * where payload_bytes is canonical JSON (sorted keys, no whitespace, UTF-8). |
| 24 | * Clients verify the exact bytes carried in payload_b64; they never re-canonicalize. |
| 25 | */ |
| 26 | import { createPrivateKey, createPublicKey, generateKeyPairSync, sign, verify, createHash } from "node:crypto"; |
| 27 | import { readFileSync, writeFileSync, mkdirSync, openSync, closeSync, readSync, fstatSync, lstatSync, constants } from "node:fs"; |
| 28 | import { dirname, resolve } from "node:path"; |
| 29 | import { fileURLToPath } from "node:url"; |
| 30 | |
| 31 | export const DOMAIN = "codewhale-facts/v1\0"; |
| 32 | export const ENVELOPE_VERSION = 1; |
| 33 | export const SCHEMA_VERSION = 1; |
| 34 | export const MAX_PAYLOAD_BYTES = 512 * 1024; |
| 35 | export const MAX_ENVELOPE_BYTES = 768 * 1024; |
| 36 | export const REGISTRY_CHANNEL = "registry"; |
| 37 | export const REGISTRY_SCHEMA = "codewhale.registry.v1"; |
| 38 | export const MAX_REGISTRY_PAYLOAD_BYTES = 8 * 1024 * 1024; |
| 39 | export const MAX_REGISTRY_ENVELOPE_BYTES = Math.floor(MAX_REGISTRY_PAYLOAD_BYTES / 3) * 4 + 64 * 1024; |
| 40 | const KEY_ID_RE = /^cwf-[a-z0-9-]{1,32}$/; |
| 41 | const CHANNEL_RE = /^[a-z0-9][a-z0-9-]{0,31}$/; |
| 42 | const CI_MARKERS = ["CI", "GITHUB_ACTIONS", "GITLAB_CI", "BUILDKITE", "CIRCLECI", "JENKINS_URL", "TF_BUILD"]; |
| 43 | |
| 44 | export function maxPayloadBytesFor(channel) { |
| 45 | return channel === REGISTRY_CHANNEL ? MAX_REGISTRY_PAYLOAD_BYTES : MAX_PAYLOAD_BYTES; |
| 46 | } |
| 47 | |
| 48 | export function maxEnvelopeBytesFor(channel) { |
| 49 | return channel === REGISTRY_CHANNEL ? MAX_REGISTRY_ENVELOPE_BYTES : MAX_ENVELOPE_BYTES; |
| 50 | } |
| 51 | |
| 52 | const here = dirname(fileURLToPath(import.meta.url)); |
| 53 | const WEB_ROOT = resolve(here, ".."); |
| 54 | const REPO_ROOT = resolve(WEB_ROOT, ".."); |
| 55 | |
| 56 | // --------------------------------------------------------------------------- |
| 57 | // Canonical JSON + signing primitives (exported for tests) |
| 58 | // --------------------------------------------------------------------------- |
| 59 | |
| 60 | export function canonicalize(value) { |
| 61 | if (value === null || typeof value !== "object") { |
| 62 | if (typeof value === "number" && !Number.isFinite(value)) { |
| 63 | throw new Error("non-finite number in payload"); |
| 64 | } |
| 65 | return JSON.stringify(value); |
| 66 | } |
| 67 | if (Array.isArray(value)) return `[${value.map(canonicalize).join(",")}]`; |
| 68 | const keys = Object.keys(value).sort(); |
| 69 | const parts = []; |
| 70 | for (const key of keys) { |
| 71 | const v = value[key]; |
| 72 | if (v === undefined) continue; |
| 73 | parts.push(`${JSON.stringify(key)}:${canonicalize(v)}`); |
| 74 | } |
| 75 | return `{${parts.join(",")}}`; |
| 76 | } |
| 77 | |
| 78 | export function signingMessage(keyId, payloadBytes) { |
| 79 | return Buffer.concat([Buffer.from(DOMAIN, "utf8"), Buffer.from(keyId, "utf8"), Buffer.from([0]), payloadBytes]); |
| 80 | } |
| 81 | |
| 82 | export function rawPublicKeyFromKeyObject(keyObject) { |
| 83 | const spki = keyObject.export({ type: "spki", format: "der" }); |
| 84 | // Ed25519 SPKI DER is a fixed 12-byte prefix followed by the 32-byte key. |
| 85 | return spki.subarray(spki.length - 32); |
| 86 | } |
| 87 | |
| 88 | export function publicKeyObjectFromRaw(rawB64) { |
| 89 | const raw = strictBase64(rawB64, 32); |
| 90 | if (raw.length !== 32) throw new Error("public key must decode to 32 bytes"); |
| 91 | const prefix = Buffer.from("302a300506032b6570032100", "hex"); |
| 92 | return createPublicKey({ key: Buffer.concat([prefix, raw]), type: "spki", format: "der" }); |
| 93 | } |
| 94 | |
| 95 | export function signPayload(privateKey, keyId, payloadBytes) { |
| 96 | return sign(null, signingMessage(keyId, payloadBytes), privateKey); |
| 97 | } |
| 98 | |
| 99 | /** Canonical base64 is checked before decoding to bound allocation. */ |
| 100 | export function strictBase64(value, maxBytes) { |
| 101 | if (typeof value !== "string" || !value.length || value.length > 4 * Math.ceil(maxBytes / 3) || |
| 102 | (value.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(value))) throw new Error("invalid base64"); |
| 103 | const bytes = Buffer.from(value, "base64"); |
| 104 | if (bytes.length > maxBytes || bytes.toString("base64") !== value) throw new Error("invalid base64"); |
| 105 | return bytes; |
| 106 | } |
| 107 | |
| 108 | export function utcTime(value) { |
| 109 | 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; |
| 110 | const time = Date.parse(value); |
| 111 | return Number.isFinite(time) && new Date(time).toISOString().slice(0, 19) === value.slice(0, 19) ? time : null; |
| 112 | } |
| 113 | |
| 114 | export function verifyEnvelope(envelope, publicKeyB64) { |
| 115 | const errors = []; |
| 116 | if (!isPlainObject(envelope)) return { ok: false, errors: ["envelope must be an object"] }; |
| 117 | if (envelope.envelope !== ENVELOPE_VERSION) errors.push("unsupported envelope version"); |
| 118 | if (envelope.alg !== "ed25519") errors.push("unsupported signature algorithm"); |
| 119 | if (typeof envelope.key_id !== "string" || !KEY_ID_RE.test(envelope.key_id)) errors.push("bad key_id"); |
| 120 | if (envelope.schema_version !== SCHEMA_VERSION) errors.push("unsupported schema version"); |
| 121 | if (!Number.isSafeInteger(envelope.facts_version) || envelope.facts_version <= 0) errors.push("facts_version must be a positive safe integer"); |
| 122 | if (typeof envelope.channel !== "string" || !CHANNEL_RE.test(envelope.channel)) errors.push("bad channel"); |
| 123 | if (typeof envelope.applies_to !== "string" || envelope.applies_to.length > 200 || !VERSION_REQ_RE.test(envelope.applies_to)) errors.push("bad applies_to"); |
| 124 | if (utcTime(envelope.published_at) === null || (envelope.not_after != null && utcTime(envelope.not_after) === null)) errors.push("bad timestamp"); |
| 125 | if (typeof envelope.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(envelope.sha256)) errors.push("bad sha256"); |
| 126 | if (!Array.isArray(envelope.sigs) || envelope.sigs.length > 7) errors.push("bad extra signatures"); |
| 127 | else for (const candidate of envelope.sigs) { |
| 128 | if (!isPlainObject(candidate) || typeof candidate.key_id !== "string" || !KEY_ID_RE.test(candidate.key_id)) { errors.push("bad extra signature"); continue; } |
| 129 | try { if (strictBase64(candidate.sig_b64, 64).length !== 64) errors.push("bad extra signature size"); } |
| 130 | catch { errors.push("bad extra signature encoding"); } |
| 131 | } |
| 132 | if (errors.length) return { ok: false, errors }; |
| 133 | let payloadBytes, sig, key; |
| 134 | try { |
| 135 | payloadBytes = strictBase64(envelope.payload_b64, maxPayloadBytesFor(envelope.channel)); |
| 136 | sig = strictBase64(envelope.sig_b64, 64); |
| 137 | if (sig.length !== 64) throw new Error("bad signature size"); |
| 138 | key = publicKeyObjectFromRaw(publicKeyB64); |
| 139 | } catch { return { ok: false, errors: ["invalid payload, signature or public key encoding"] }; } |
| 140 | const sha = createHash("sha256").update(payloadBytes).digest("hex"); |
| 141 | if (envelope.sha256 !== sha) return { ok: false, errors: ["sha256 mismatch"] }; |
| 142 | if (!verify(null, signingMessage(envelope.key_id, payloadBytes), key, sig)) return { ok: false, errors: ["bad signature"] }; |
| 143 | let payload; |
| 144 | try { payload = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(payloadBytes)); } |
| 145 | catch { return { ok: false, errors: ["payload is not UTF-8 JSON"] }; } |
| 146 | if (envelope.channel === REGISTRY_CHANNEL) { |
| 147 | errors.push(...validateRegistrySource(payload)); |
| 148 | if (envelope.facts_version !== payload?.revision) errors.push("outer facts_version differs from signed revision"); |
| 149 | if (envelope.published_at !== payload?.generated_at) errors.push("outer published_at differs from signed generated_at"); |
| 150 | if (envelope.applies_to !== (payload?.applies_to ?? "*")) errors.push("outer applies_to differs from signed payload"); |
| 151 | if ((envelope.not_after ?? null) !== (payload?.not_after ?? null)) errors.push("outer not_after differs from signed payload"); |
| 152 | if (payload?.not_after != null && utcTime(payload.not_after) <= utcTime(payload.generated_at)) errors.push("not_after must follow generated_at"); |
| 153 | return errors.length ? { ok: false, errors } : { ok: true, errors: [], payload, sha256: sha }; |
| 154 | } |
| 155 | errors.push(...validateSource(payload)); |
| 156 | for (const field of ["channel", "facts_version", "applies_to", "schema_version", "published_at"]) { |
| 157 | if (envelope[field] !== payload?.[field]) errors.push(`outer ${field} differs from signed payload`); |
| 158 | } |
| 159 | if ((envelope.not_after ?? null) !== (payload?.not_after ?? null)) errors.push("outer not_after differs from signed payload"); |
| 160 | if (payload?.not_after != null && utcTime(payload.not_after) <= utcTime(payload.published_at)) errors.push("not_after must follow published_at"); |
| 161 | return errors.length ? { ok: false, errors } : { ok: true, errors: [], payload, sha256: sha }; |
| 162 | } |
| 163 | |
| 164 | // --------------------------------------------------------------------------- |
| 165 | // Source validation (docs/cloud-facts/<channel>.json) |
| 166 | // --------------------------------------------------------------------------- |
| 167 | |
| 168 | const MODEL_OPS = new Set(["upsert", "deprecate", "hide"]); |
| 169 | const LEVELS = new Set(["info", "warn"]); |
| 170 | const SURFACES = new Set(["tui", "desktop", "web"]); |
| 171 | const VERSION_REQ_RE = /^(\*|(?:>=|<=|>|<|=|\^|~)?\s*\d+(\.\d+){0,2}(-[0-9A-Za-z.-]+)?(\s*,\s*(?:>=|<=|>|<|=|\^|~)?\s*\d+(\.\d+){0,2}(-[0-9A-Za-z.-]+)?)*)$/; |
| 172 | |
| 173 | function isPlainObject(v) { |
| 174 | return v !== null && typeof v === "object" && !Array.isArray(v); |
| 175 | } |
| 176 | |
| 177 | function optString(errors, where, obj, key, max = 500) { |
| 178 | const v = obj[key]; |
| 179 | if (v === undefined || v === null) return; |
| 180 | if (typeof v !== "string" || v.length > max) errors.push(`${where}.${key} must be a string (<= ${max} chars)`); |
| 181 | } |
| 182 | |
| 183 | function optVersionReq(errors, where, obj, key = "applies_to") { |
| 184 | const v = obj[key]; |
| 185 | if (v === undefined || v === null) return; |
| 186 | if (typeof v !== "string" || v.length > 200 || !VERSION_REQ_RE.test(v.trim())) errors.push(`${where}.${key} is not a semver requirement: ${JSON.stringify(v)}`); |
| 187 | } |
| 188 | |
| 189 | export function validateSource(source) { |
| 190 | const errors = []; |
| 191 | if (!isPlainObject(source)) return ["source must be an object"]; |
| 192 | if (source.schema_version !== undefined && source.schema_version !== SCHEMA_VERSION) { |
| 193 | errors.push(`schema_version must be ${SCHEMA_VERSION}`); |
| 194 | } |
| 195 | if (source.channel !== undefined && !CHANNEL_RE.test(String(source.channel))) errors.push("channel slug invalid"); |
| 196 | if (source.facts_version !== undefined && !(Number.isSafeInteger(source.facts_version) && source.facts_version > 0)) { |
| 197 | errors.push("facts_version must be a positive integer"); |
| 198 | } |
| 199 | optVersionReq(errors, "root", source); |
| 200 | optString(errors, "root", source, "not_after", 40); |
| 201 | for (const field of ["published_at", "not_after"]) { |
| 202 | if (source[field] != null && utcTime(source[field]) === null) errors.push(`${field} must be a valid UTC timestamp`); |
| 203 | } |
| 204 | const models = source.models ?? []; |
| 205 | if (!Array.isArray(models)) errors.push("models must be an array"); |
| 206 | else { |
| 207 | models.forEach((m, i) => { |
| 208 | const where = `models[${i}]`; |
| 209 | if (!isPlainObject(m)) return errors.push(`${where} must be an object`); |
| 210 | if (typeof m.provider !== "string" || !m.provider) errors.push(`${where}.provider required`); |
| 211 | if (typeof m.id !== "string" || !m.id) errors.push(`${where}.id required`); |
| 212 | if (m.op !== undefined && !MODEL_OPS.has(m.op)) errors.push(`${where}.op must be one of ${[...MODEL_OPS].join("/")}`); |
| 213 | for (const k of ["context_window", "max_output"]) { |
| 214 | if (m[k] !== undefined && !(Number.isSafeInteger(m[k]) && m[k] > 0)) errors.push(`${where}.${k} must be a positive integer`); |
| 215 | } |
| 216 | if (m.pricing !== undefined) { |
| 217 | if (!isPlainObject(m.pricing)) errors.push(`${where}.pricing must be an object`); |
| 218 | else for (const k of Object.keys(m.pricing)) { |
| 219 | if (!["input_per_m", "output_per_m", "cache_read_per_m"].includes(k)) errors.push(`${where}.pricing.${k} unknown`); |
| 220 | else if (typeof m.pricing[k] !== "number" || !Number.isFinite(m.pricing[k]) || m.pricing[k] < 0) errors.push(`${where}.pricing.${k} must be a non-negative number`); |
| 221 | } |
| 222 | } |
| 223 | if (m.reasoning !== undefined && typeof m.reasoning !== "boolean") errors.push(`${where}.reasoning must be boolean`); |
| 224 | // Additive field: older clients deserialize it as false and keep provider |
| 225 | // roster dominance, so an unsigned or unaware reader loses nothing. |
| 226 | if (m.allow_unlisted !== undefined) { |
| 227 | if (typeof m.allow_unlisted !== "boolean") errors.push(`${where}.allow_unlisted must be boolean`); |
| 228 | else if (m.allow_unlisted) { |
| 229 | if (m.op !== undefined && m.op !== "upsert") errors.push(`${where}.allow_unlisted requires op upsert`); |
| 230 | // The client drops the assertion in a payload that cannot expire. |
| 231 | if (!source.not_after) errors.push(`${where}.allow_unlisted requires a payload not_after`); |
| 232 | } |
| 233 | } |
| 234 | optString(errors, where, m, "display_name", 120); |
| 235 | optString(errors, where, m, "deprecated_at", 40); |
| 236 | optString(errors, where, m, "replacement", 200); |
| 237 | optString(errors, where, m, "note", 300); |
| 238 | optVersionReq(errors, where, m); |
| 239 | }); |
| 240 | } |
| 241 | const defaults = source.provider_defaults ?? {}; |
| 242 | if (!isPlainObject(defaults)) errors.push("provider_defaults must be an object"); |
| 243 | else for (const [provider, d] of Object.entries(defaults)) { |
| 244 | const where = `provider_defaults.${provider}`; |
| 245 | if (!isPlainObject(d)) { errors.push(`${where} must be an object`); continue; } |
| 246 | optString(errors, where, d, "default_model", 200); |
| 247 | optString(errors, where, d, "base_url", 300); |
| 248 | if (d.base_url !== undefined) { |
| 249 | try { |
| 250 | const url = new URL(d.base_url); |
| 251 | if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash || /[\\\s]/.test(d.base_url)) throw new Error(); |
| 252 | } catch { errors.push(`${where}.base_url must be an unambiguous credential-free https URL`); } |
| 253 | } |
| 254 | optVersionReq(errors, where, d); |
| 255 | } |
| 256 | if (source.release !== undefined && source.release !== null) { |
| 257 | const r = source.release; |
| 258 | const where = "release"; |
| 259 | if (!isPlainObject(r)) errors.push("release must be an object"); |
| 260 | else { |
| 261 | if (typeof r.latest !== "string" || !/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(r.latest)) errors.push("release.latest must be a semver version"); |
| 262 | if (r.yanked !== undefined && !(Array.isArray(r.yanked) && r.yanked.every((v) => typeof v === "string"))) errors.push("release.yanked must be a string array"); |
| 263 | optString(errors, where, r, "min_supported", 40); |
| 264 | optString(errors, where, r, "notice", 300); |
| 265 | optString(errors, where, r, "release_url", 300); |
| 266 | optVersionReq(errors, where, r); |
| 267 | } |
| 268 | } |
| 269 | const ann = source.announcements ?? []; |
| 270 | if (!Array.isArray(ann)) errors.push("announcements must be an array"); |
| 271 | else { |
| 272 | const seen = new Set(); |
| 273 | ann.forEach((a, i) => { |
| 274 | const where = `announcements[${i}]`; |
| 275 | if (!isPlainObject(a)) return errors.push(`${where} must be an object`); |
| 276 | if (typeof a.id !== "string" || !/^[a-z0-9][a-z0-9-]{0,63}$/.test(a.id)) errors.push(`${where}.id invalid`); |
| 277 | if (seen.has(a.id)) errors.push(`${where}.id duplicated`); |
| 278 | seen.add(a.id); |
| 279 | if (a.level !== undefined && !LEVELS.has(a.level)) errors.push(`${where}.level must be info|warn`); |
| 280 | if (typeof a.text !== "string" || !a.text.trim() || a.text.length > 200) errors.push(`${where}.text required (<= 200 chars)`); |
| 281 | optString(errors, where, a, "url", 300); |
| 282 | if (a.surfaces !== undefined && !(Array.isArray(a.surfaces) && a.surfaces.every((s) => SURFACES.has(s)))) errors.push(`${where}.surfaces invalid`); |
| 283 | optVersionReq(errors, where, a); |
| 284 | optString(errors, where, a, "starts_at", 40); |
| 285 | optString(errors, where, a, "expires_at", 40); |
| 286 | }); |
| 287 | } |
| 288 | const allowed = new Set(["$schema", "_meta", "schema_version", "channel", "facts_version", "published_at", "not_after", "applies_to", "models", "provider_defaults", "release", "announcements"]); |
| 289 | for (const k of Object.keys(source)) if (!allowed.has(k)) errors.push(`unknown top-level field ${k}`); |
| 290 | return errors; |
| 291 | } |
| 292 | |
| 293 | export function canonicalUtcTimestamp(value) { |
| 294 | const time = utcTime(value); |
| 295 | if (time === null) return null; |
| 296 | return new Date(time).toISOString().replace(/\.000Z$/, "Z"); |
| 297 | } |
| 298 | |
| 299 | export function validateRegistrySource(source) { |
| 300 | const errors = []; |
| 301 | if (!isPlainObject(source)) return ["registry source must be an object"]; |
| 302 | if (source.schema !== REGISTRY_SCHEMA) errors.push(`schema must be ${REGISTRY_SCHEMA}`); |
| 303 | if (!Number.isSafeInteger(source.revision) || source.revision <= 0) errors.push("revision must be a positive integer"); |
| 304 | if (typeof source.content_hash !== "string" || !/^sha256:[a-f0-9]{64}$/.test(source.content_hash)) { |
| 305 | errors.push("content_hash must be sha256:<64 hex>"); |
| 306 | } |
| 307 | const canonicalGenerated = canonicalUtcTimestamp(source.generated_at); |
| 308 | if (canonicalGenerated === null || source.generated_at !== canonicalGenerated) { |
| 309 | errors.push("generated_at must be a canonical UTC timestamp"); |
| 310 | } |
| 311 | if (source.not_after !== undefined && source.not_after !== null) { |
| 312 | const canonicalNotAfter = canonicalUtcTimestamp(source.not_after); |
| 313 | if (canonicalNotAfter === null || source.not_after !== canonicalNotAfter) { |
| 314 | errors.push("not_after must be a canonical UTC timestamp"); |
| 315 | } |
| 316 | } |
| 317 | if (!Array.isArray(source.providers)) errors.push("providers must be an array"); |
| 318 | if (!Array.isArray(source.models)) errors.push("models must be an array"); |
| 319 | if (!Array.isArray(source.offerings)) errors.push("offerings must be an array"); |
| 320 | if (!isPlainObject(source.dialects)) errors.push("dialects must be an object"); |
| 321 | optVersionReq(errors, "root", source); |
| 322 | return errors; |
| 323 | } |
| 324 | |
| 325 | export function buildRegistryPayload(source, { factsVersion, publishedAt, notAfter, appliesTo } = {}) { |
| 326 | if (!isPlainObject(source)) throw new Error("registry source must be an object"); |
| 327 | const revision = factsVersion ?? source.revision; |
| 328 | const generatedAt = canonicalUtcTimestamp(publishedAt ?? source.generated_at); |
| 329 | if (!generatedAt) throw new Error("generated_at must be a valid UTC timestamp"); |
| 330 | const payload = { |
| 331 | ...source, |
| 332 | schema: REGISTRY_SCHEMA, |
| 333 | revision, |
| 334 | generated_at: generatedAt, |
| 335 | }; |
| 336 | const resolvedAppliesTo = appliesTo ?? source.applies_to; |
| 337 | if (resolvedAppliesTo !== undefined) payload.applies_to = String(resolvedAppliesTo).trim(); |
| 338 | const resolvedNotAfter = notAfter === undefined ? source.not_after : notAfter; |
| 339 | if (resolvedNotAfter != null) { |
| 340 | const canonicalExpiry = canonicalUtcTimestamp(resolvedNotAfter); |
| 341 | if (!canonicalExpiry) throw new Error("not_after must be a valid UTC timestamp"); |
| 342 | payload.not_after = canonicalExpiry; |
| 343 | } else { |
| 344 | delete payload.not_after; |
| 345 | } |
| 346 | const errors = validateRegistrySource(payload); |
| 347 | if (errors.length) throw new Error(`registry invalid:\n - ${errors.join("\n - ")}`); |
| 348 | return payload; |
| 349 | } |
| 350 | |
| 351 | /** Build the signed payload object (no signing) from a source file. */ |
| 352 | export function buildPayload(source, { channel, factsVersion, publishedAt }) { |
| 353 | if (channel === REGISTRY_CHANNEL) { |
| 354 | return buildRegistryPayload(source, { factsVersion, publishedAt }); |
| 355 | } |
| 356 | const errors = validateSource(source); |
| 357 | if (errors.length) throw new Error(`source invalid:\n - ${errors.join("\n - ")}`); |
| 358 | const payload = { |
| 359 | schema_version: SCHEMA_VERSION, |
| 360 | channel, |
| 361 | facts_version: factsVersion, |
| 362 | published_at: publishedAt, |
| 363 | applies_to: typeof source.applies_to === "string" ? source.applies_to.trim() : "*", |
| 364 | models: source.models ?? [], |
| 365 | provider_defaults: source.provider_defaults ?? {}, |
| 366 | release: source.release ?? null, |
| 367 | announcements: source.announcements ?? [], |
| 368 | }; |
| 369 | if (source.not_after) payload.not_after = source.not_after; |
| 370 | const payloadErrors = validateSource(payload); |
| 371 | if (payloadErrors.length || utcTime(publishedAt) === null || !Number.isSafeInteger(factsVersion) || factsVersion <= 0 || !CHANNEL_RE.test(channel)) { |
| 372 | throw new Error("invalid signed payload metadata"); |
| 373 | } |
| 374 | return payload; |
| 375 | } |
| 376 | |
| 377 | export function buildEnvelope({ privateKey, keyId, payload }) { |
| 378 | if (!KEY_ID_RE.test(keyId)) throw new Error(`key_id must match ${KEY_ID_RE}`); |
| 379 | const isRegistry = payload?.schema === REGISTRY_SCHEMA; |
| 380 | const channel = isRegistry ? REGISTRY_CHANNEL : payload.channel; |
| 381 | const maxPayload = maxPayloadBytesFor(channel); |
| 382 | const payloadBytes = Buffer.from(canonicalize(payload), "utf8"); |
| 383 | if (payloadBytes.length > maxPayload) throw new Error(`payload exceeds ${maxPayload} bytes`); |
| 384 | const sig = signPayload(privateKey, keyId, payloadBytes); |
| 385 | const sha256 = createHash("sha256").update(payloadBytes).digest("hex"); |
| 386 | const envelope = { |
| 387 | envelope: ENVELOPE_VERSION, |
| 388 | channel, |
| 389 | facts_version: isRegistry ? payload.revision : payload.facts_version, |
| 390 | schema_version: isRegistry ? SCHEMA_VERSION : payload.schema_version, |
| 391 | key_id: keyId, |
| 392 | alg: "ed25519", |
| 393 | applies_to: isRegistry ? (typeof payload.applies_to === "string" ? payload.applies_to : "*") : payload.applies_to, |
| 394 | published_at: isRegistry ? payload.generated_at : payload.published_at, |
| 395 | payload_b64: payloadBytes.toString("base64"), |
| 396 | sig_b64: sig.toString("base64"), |
| 397 | sigs: [], |
| 398 | sha256, |
| 399 | }; |
| 400 | if (payload.not_after != null) envelope.not_after = payload.not_after; |
| 401 | const pub = rawPublicKeyFromKeyObject(createPublicKey(privateKey)).toString("base64"); |
| 402 | const check = verifyEnvelope(envelope, pub); |
| 403 | if (!check.ok) throw new Error(`self-verify failed: ${check.errors.join("; ")}`); |
| 404 | return envelope; |
| 405 | } |
| 406 | |
| 407 | // --------------------------------------------------------------------------- |
| 408 | // CLI helpers |
| 409 | // --------------------------------------------------------------------------- |
| 410 | |
| 411 | function parseArgs(argv) { |
| 412 | const positional = []; |
| 413 | const flags = {}; |
| 414 | for (let i = 0; i < argv.length; i += 1) { |
| 415 | const arg = argv[i]; |
| 416 | if (arg.startsWith("--")) { |
| 417 | const key = arg.slice(2); |
| 418 | const next = argv[i + 1]; |
| 419 | if (next === undefined || next.startsWith("--")) flags[key] = true; |
| 420 | else { flags[key] = next; i += 1; } |
| 421 | } else positional.push(arg); |
| 422 | } |
| 423 | return { positional, flags }; |
| 424 | } |
| 425 | |
| 426 | /** Bounded, regular, single-link file reads; no symlink or FIFO following. */ |
| 427 | export function readBoundedFile(path, maxBytes = MAX_ENVELOPE_BYTES) { |
| 428 | const before = lstatSync(path); |
| 429 | if (!before.isFile() || before.nlink !== 1) throw new Error("file is not a regular single-link file"); |
| 430 | const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0)); |
| 431 | try { |
| 432 | const stat = fstatSync(fd); |
| 433 | if (!stat.isFile() || stat.nlink !== 1 || stat.size > maxBytes || stat.ino !== before.ino || stat.dev !== before.dev) throw new Error("file is not a bounded regular single-link file"); |
| 434 | const bytes = Buffer.alloc(maxBytes + 1); |
| 435 | let size = 0; |
| 436 | while (size <= maxBytes) { |
| 437 | const count = readSync(fd, bytes, size, maxBytes + 1 - size, null); |
| 438 | if (!count) break; |
| 439 | size += count; |
| 440 | } |
| 441 | if (size > maxBytes) throw new Error("file exceeds size limit"); |
| 442 | return bytes.subarray(0, size); |
| 443 | } finally { closeSync(fd); } |
| 444 | } |
| 445 | |
| 446 | function loadPrivateKeyFromEnv() { |
| 447 | refuseUnderCi(); |
| 448 | let pem = process.env.CODEWHALE_FACTS_SIGNING_KEY; |
| 449 | const file = process.env.CODEWHALE_FACTS_SIGNING_KEY_FILE; |
| 450 | if (!pem && file) pem = readBoundedFile(file, 16 * 1024).toString("utf8"); |
| 451 | if (!pem) throw new Error("set CODEWHALE_FACTS_SIGNING_KEY (PEM) or CODEWHALE_FACTS_SIGNING_KEY_FILE"); |
| 452 | if (Buffer.byteLength(pem) > 16 * 1024) throw new Error("signing key exceeds size limit"); |
| 453 | const key = createPrivateKey({ key: pem, format: "pem" }); |
| 454 | if (key.asymmetricKeyType !== "ed25519") throw new Error("signing key must be Ed25519"); |
| 455 | return key; |
| 456 | } |
| 457 | |
| 458 | export function validateTrustedKeys(keys) { |
| 459 | const seen = new Set(); |
| 460 | for (const key of keys) { |
| 461 | if (!KEY_ID_RE.test(key.keyId) || seen.has(key.keyId) || !["active", "retired"].includes(key.status) || !["founder", "automation"].includes(key.role) || strictBase64(key.publicKey, 32).length !== 32 || seen.has(key.publicKey)) throw new Error("invalid or duplicated pinned key"); |
| 462 | seen.add(key.keyId); |
| 463 | seen.add(key.publicKey); |
| 464 | } |
| 465 | return keys; |
| 466 | } |
| 467 | |
| 468 | /** Deliberately narrow syntax: a changed/unparseable table must fail the gate. */ |
| 469 | export function parseTsKeys(text) { |
| 470 | const source = text.replace(/\/\*[\s\S]*?\*\//g, "").replace(/^\s*\/\/.*$/gm, ""); |
| 471 | const tables = [...source.matchAll(/^\s*export\s+const\s+TRUSTED_KEYS\s*:\s*readonly\s+TrustedKey\[\]\s*=\s*\[([\s\S]*?)\]\s*;/gm)]; |
| 472 | if (tables.length !== 1) throw new Error("cannot parse exactly one TypeScript TRUSTED_KEYS table"); |
| 473 | const table = tables[0]; |
| 474 | const body = table[1].replace(/^\s*\/\/.*$/gm, ""); |
| 475 | const keys = []; |
| 476 | const remainder = body.replace(/\{\s*keyId:\s*"([^"]+)",\s*publicKey:\s*"([^"]+)",\s*status:\s*"([^"]+)",\s*role:\s*"([^"]+)"\s*,?\s*\}/g, (_, keyId, publicKey, status, role) => { |
| 477 | keys.push({ keyId, publicKey, status, role }); |
| 478 | return ""; |
| 479 | }); |
| 480 | if (remainder.replace(/[\s,]/g, "")) throw new Error("unparsed TypeScript TRUSTED_KEYS entry"); |
| 481 | return validateTrustedKeys(keys); |
| 482 | } |
| 483 | |
| 484 | function loadTrustedKeysFromRepo() { |
| 485 | const keys = parseTsKeys(readBoundedFile(resolve(WEB_ROOT, "lib/cloud-facts/keys.ts"), 64 * 1024).toString("utf8")); |
| 486 | return new Map(keys.map((key) => [key.keyId, key])); |
| 487 | } |
| 488 | |
| 489 | const AUTOMATION_CHANNEL_SUFFIX = "-models"; |
| 490 | const AUTOMATION_MAX_VALIDITY_MS = 7 * 24 * 60 * 60 * 1000; |
| 491 | const AUTOMATION_MAX_MODELS = 256; |
| 492 | const AUTOMATION_PAYLOAD_FIELDS = new Set([ |
| 493 | "schema_version", "channel", "facts_version", "published_at", "not_after", "applies_to", |
| 494 | "models", "provider_defaults", "release", "announcements", |
| 495 | ]); |
| 496 | const AUTOMATION_MODEL_FIELDS = new Set([ |
| 497 | "provider", "id", "op", "context_window", "max_output", "reasoning", "display_name", |
| 498 | "deprecated_at", "replacement", "note", "applies_to", "pricing_withheld", |
| 499 | ]); |
| 500 | |
| 501 | export function automationScopeViolation(facts, channel) { |
| 502 | const published = utcTime(facts.published_at); |
| 503 | const expires = facts.not_after == null ? null : utcTime(facts.not_after); |
| 504 | if (published === null || (facts.not_after != null && expires === null)) return "timestamp is not whole-second UTC"; |
| 505 | 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`; |
| 506 | const plain = (value, max) => value === undefined || (typeof value === "string" && [...value].length <= max && !/\p{Cc}/u.test(value)); |
| 507 | if (!plain(facts.applies_to, 200)) return "applies_to is too long or not plain"; |
| 508 | if (isPlainObject(facts.provider_defaults) && Object.keys(facts.provider_defaults).length > 0) return "provider defaults"; |
| 509 | if (facts.release != null) return "release facts"; |
| 510 | if (Array.isArray(facts.announcements) && facts.announcements.length > 0) return "announcements"; |
| 511 | const unknown = Object.keys(facts).find((field) => !AUTOMATION_PAYLOAD_FIELDS.has(field)); |
| 512 | if (unknown !== undefined) return `field ${JSON.stringify(unknown)} is not allowed`; |
| 513 | const models = facts.models === undefined ? [] : facts.models; |
| 514 | if (!Array.isArray(models)) return "models is not a list"; |
| 515 | if (models.length > AUTOMATION_MAX_MODELS) return `more than ${AUTOMATION_MAX_MODELS} models`; |
| 516 | for (const model of models) { |
| 517 | if (!isPlainObject(model) || typeof model.provider !== "string" || !model.provider || typeof model.id !== "string" || !model.id) return "malformed model entry"; |
| 518 | const name = `${model.provider}/${model.id}`; |
| 519 | const field = Object.keys(model).find((key) => !AUTOMATION_MODEL_FIELDS.has(key)); |
| 520 | if (field !== undefined) return `${name}: field ${JSON.stringify(field)} is not allowed`; |
| 521 | const nullField = Object.keys(model).find((key) => model[key] === null); |
| 522 | if (nullField !== undefined) return `${name}: field ${JSON.stringify(nullField)} is null`; |
| 523 | const op = model.op === undefined ? "upsert" : model.op; |
| 524 | if (op !== "upsert" && op !== "deprecate") return `${name} is not an upsert or deprecation`; |
| 525 | if (model.reasoning !== undefined && typeof model.reasoning !== "boolean") return `${name}: malformed model entry`; |
| 526 | if (!plain(model.provider, 64) || !plain(model.id, 200) || !plain(model.display_name, 120) || !plain(model.deprecated_at, 40) || |
| 527 | !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`; |
| 528 | const window = model.context_window; |
| 529 | const output = model.max_output; |
| 530 | const windowOk = window === undefined || (typeof window === "number" && Number.isSafeInteger(window) && window >= 1024 && window <= 20_000_000); |
| 531 | const outputOk = output === undefined || (typeof output === "number" && Number.isSafeInteger(output) && output >= 1 && output <= 2_000_000 && (typeof window !== "number" || output <= window)); |
| 532 | if (!windowOk || !outputOk) return `${name}: limit out of range`; |
| 533 | } |
| 534 | const wholeSecond = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/; |
| 535 | if (typeof facts.published_at !== "string" || !wholeSecond.test(facts.published_at) || |
| 536 | (facts.not_after != null && (typeof facts.not_after !== "string" || !wholeSecond.test(facts.not_after)))) return "timestamp is not whole-second UTC"; |
| 537 | if (facts.facts_version !== published / 1000) return "facts_version is not the publication time"; |
| 538 | if (expires === null) return "no not_after"; |
| 539 | if (expires <= published || expires - published > AUTOMATION_MAX_VALIDITY_MS) return "validity outside the automation limit"; |
| 540 | return null; |
| 541 | } |
| 542 | |
| 543 | const REGISTRY_PROVIDER_TRUST_FIELDS = [ |
| 544 | "origin", "kind", "base_url", "base_url_config_key", "env_vars", "api_key_env", |
| 545 | "secret_store_slot", "config_key", "wire", "wire_policy", "auth", "aliases", |
| 546 | "selector_aliases", "subagent_aliases", "credential_help", "credential_url", |
| 547 | "docs_url", "discovery", "catalog_id", "catalog_source_id", "tui_wire_tag", |
| 548 | "table_field", "web", |
| 549 | ]; |
| 550 | |
| 551 | function sortKeysDeep(value) { |
| 552 | if (Array.isArray(value)) return value.map(sortKeysDeep); |
| 553 | if (!isPlainObject(value)) return value; |
| 554 | const out = {}; |
| 555 | for (const key of Object.keys(value).sort()) { |
| 556 | if (value[key] !== undefined) out[key] = sortKeysDeep(value[key]); |
| 557 | } |
| 558 | return out; |
| 559 | } |
| 560 | |
| 561 | function projectProviderTrust(row) { |
| 562 | const synthesized = row.origin === "descriptor" ? { ...row } : row; |
| 563 | if (row.origin === "descriptor") { |
| 564 | if (synthesized.wire_policy === undefined) { |
| 565 | synthesized.wire_policy = typeof synthesized.wire === "string" && synthesized.wire ? synthesized.wire : "openai-compatible"; |
| 566 | } |
| 567 | if (synthesized.auth === undefined) { |
| 568 | const env = typeof synthesized.api_key_env === "string" && synthesized.api_key_env |
| 569 | ? synthesized.api_key_env |
| 570 | : `${String(synthesized.id).toUpperCase().replace(/-/g, "_")}_API_KEY`; |
| 571 | synthesized.auth = { secret_slot: synthesized.id, env_vars: [env] }; |
| 572 | } |
| 573 | } |
| 574 | const out = {}; |
| 575 | for (const field of REGISTRY_PROVIDER_TRUST_FIELDS) { |
| 576 | if (synthesized[field] !== undefined) out[field] = synthesized[field]; |
| 577 | } |
| 578 | return sortKeysDeep(out); |
| 579 | } |
| 580 | |
| 581 | export function deriveBundledRegistryTrust(descriptors) { |
| 582 | const providers = {}; |
| 583 | for (const row of descriptors.providers || []) providers[row.id] = projectProviderTrust({ ...row, origin: "builtin" }); |
| 584 | for (const row of descriptors.descriptors || []) providers[row.id] = projectProviderTrust({ ...row, origin: "descriptor" }); |
| 585 | const compat = {}; |
| 586 | for (const [key, value] of Object.entries(descriptors)) { |
| 587 | if (key !== "providers" && key !== "descriptors") compat[key] = value; |
| 588 | } |
| 589 | return sortKeysDeep({ providers, providerDescriptorsCompat: compat }); |
| 590 | } |
| 591 | |
| 592 | let cachedBundledRegistryTrust = null; |
| 593 | function loadBundledRegistryTrust() { |
| 594 | if (!cachedBundledRegistryTrust) { |
| 595 | cachedBundledRegistryTrust = readJson(resolve(WEB_ROOT, "lib/cloud-facts/bundled-providers.json"), 512 * 1024); |
| 596 | } |
| 597 | return cachedBundledRegistryTrust; |
| 598 | } |
| 599 | |
| 600 | export function registryAutomationScopeViolation(facts, bundledTrust = loadBundledRegistryTrust()) { |
| 601 | const published = utcTime(facts.generated_at); |
| 602 | const expires = facts.not_after == null ? null : utcTime(facts.not_after); |
| 603 | if (published === null || (facts.not_after != null && expires === null)) return "timestamp is not valid UTC"; |
| 604 | if (expires === null) return "no not_after"; |
| 605 | if (expires <= published || expires - published > AUTOMATION_MAX_VALIDITY_MS) return "validity outside the automation limit"; |
| 606 | if (!Array.isArray(facts.providers)) return "providers is not a list"; |
| 607 | const bundledProviders = bundledTrust?.providers ?? {}; |
| 608 | const bundledIds = Object.keys(bundledProviders); |
| 609 | const seen = new Set(); |
| 610 | for (const provider of facts.providers) { |
| 611 | if (!isPlainObject(provider) || typeof provider.id !== "string" || !provider.id) return "malformed provider entry"; |
| 612 | if (seen.has(provider.id)) return `${provider.id}: duplicate provider`; |
| 613 | seen.add(provider.id); |
| 614 | if (provider.origin !== "builtin" && provider.origin !== "descriptor") return `${provider.id}: unsupported provider origin`; |
| 615 | if (provider.admission !== undefined) return `${provider.id}: admitted provider requires a founder signature`; |
| 616 | if (!(provider.id in bundledProviders)) return `${provider.id}: unbundled provider requires a founder signature`; |
| 617 | if (canonicalize(projectProviderTrust(provider)) !== canonicalize(bundledProviders[provider.id])) { |
| 618 | return `${provider.id}: provider trust fields require a founder signature`; |
| 619 | } |
| 620 | } |
| 621 | if (seen.size !== bundledIds.length) return "missing bundled provider requires a founder signature"; |
| 622 | if (isPlainObject(facts.engine_compat) && facts.engine_compat.provider_descriptors !== undefined) { |
| 623 | if (canonicalize(facts.engine_compat.provider_descriptors) !== canonicalize(bundledTrust?.providerDescriptorsCompat ?? {})) { |
| 624 | return "engine_compat.provider_descriptors requires a founder signature"; |
| 625 | } |
| 626 | } |
| 627 | return null; |
| 628 | } |
| 629 | |
| 630 | export function activePublishingKey(envelope, keys, now = Date.now()) { |
| 631 | const key = validateTrustedKeys(keys).find((key) => key.keyId === envelope.key_id && key.status === "active"); |
| 632 | if (!key) throw new Error("primary signing key is not pinned and active; refusing publication"); |
| 633 | const check = verifyEnvelope(envelope, key.publicKey); |
| 634 | if (!check.ok) throw new Error(`envelope does not verify: ${check.errors.join("; ")}`); |
| 635 | if (key.role !== "founder") { |
| 636 | const violation = envelope.channel === REGISTRY_CHANNEL |
| 637 | ? registryAutomationScopeViolation(check.payload) |
| 638 | : automationScopeViolation(check.payload, envelope.channel); |
| 639 | if (violation !== null) throw new Error(`payload is outside the automation key's scope: ${violation}`); |
| 640 | } |
| 641 | const publishedTime = envelope.channel === REGISTRY_CHANNEL |
| 642 | ? utcTime(check.payload.generated_at) |
| 643 | : utcTime(check.payload.published_at); |
| 644 | if (!Number.isFinite(now) || publishedTime > now + 300_000 || |
| 645 | (check.payload.not_after != null && utcTime(check.payload.not_after) <= now)) throw new Error("publication timestamp is future or expired"); |
| 646 | return { key, check }; |
| 647 | } |
| 648 | |
| 649 | function refuseUnderCi() { |
| 650 | for (const marker of CI_MARKERS) { |
| 651 | if (process.env[marker] && !/^(0|false|no|off)$/i.test(process.env[marker])) { |
| 652 | throw new Error(`refusing to run with a secret under CI (${marker} is set); publish from the founder's machine`); |
| 653 | } |
| 654 | } |
| 655 | } |
| 656 | |
| 657 | function sqlLiteral(value) { |
| 658 | if (value === null || value === undefined) return "null"; |
| 659 | return `'${String(value).replace(/'/g, "''")}'`; |
| 660 | } |
| 661 | |
| 662 | export function emitSql(envelope, { publishedBy = "", publicKeyB64, notes = "" }) { |
| 663 | if (!publicKeyB64) throw new Error("public key required to emit the facts_key row"); |
| 664 | const check = verifyEnvelope(envelope, publicKeyB64); |
| 665 | if (!check.ok) throw new Error(`envelope does not verify: ${check.errors.join("; ")}`); |
| 666 | const payloadJson = Buffer.from(envelope.payload_b64, "base64").toString("utf8"); |
| 667 | return [ |
| 668 | "begin;", |
| 669 | `insert into public.facts_key (key_id, scope, algorithm, public_key, status)`, |
| 670 | ` values (${sqlLiteral(envelope.key_id)}, 'global', 'ed25519', ${sqlLiteral(publicKeyB64)}, 'active')`, |
| 671 | ` on conflict (key_id) do nothing;`, |
| 672 | `insert into public.facts_release (channel_id, facts_version, schema_version, envelope_version, applies_to, key_id, payload_b64, sig_b64, sigs, payload, published_at, not_after, published_by, notes)`, |
| 673 | ` select c.id, ${envelope.facts_version}, ${envelope.schema_version}, ${envelope.envelope}, ${sqlLiteral(envelope.applies_to)}, ${sqlLiteral(envelope.key_id)},`, |
| 674 | ` ${sqlLiteral(envelope.payload_b64)}, ${sqlLiteral(envelope.sig_b64)}, ${sqlLiteral(JSON.stringify(envelope.sigs ?? []))}::jsonb,`, |
| 675 | ` ${sqlLiteral(payloadJson)}::jsonb, ${sqlLiteral(envelope.published_at)}::timestamptz, ${sqlLiteral(check.payload.not_after ?? null)}::timestamptz,`, |
| 676 | ` ${sqlLiteral(publishedBy)}, ${sqlLiteral(notes)}`, |
| 677 | ` from public.facts_channel c where c.scope = 'global' and c.slug = ${sqlLiteral(envelope.channel)};`, |
| 678 | "commit;", |
| 679 | "", |
| 680 | ].join("\n"); |
| 681 | } |
| 682 | |
| 683 | async function postgrest(path, { method = "GET", body, prefer } = {}) { |
| 684 | refuseUnderCi(); |
| 685 | const url = process.env.SUPABASE_URL; |
| 686 | const key = process.env.SUPABASE_SERVICE_ROLE_KEY || process.env.SUPABASE_SECRET_KEY; |
| 687 | if (!url || !key) throw new Error("SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY are required"); |
| 688 | const endpoint = new URL(url); |
| 689 | if (endpoint.protocol !== "https:" || endpoint.username || endpoint.password || endpoint.search || endpoint.hash) throw new Error("invalid Supabase endpoint"); |
| 690 | const res = await fetch(`${url.replace(/\/$/, "")}/rest/v1/${path}`, { |
| 691 | method, |
| 692 | signal: AbortSignal.timeout(30_000), |
| 693 | redirect: "error", |
| 694 | headers: { |
| 695 | apikey: key, |
| 696 | Authorization: `Bearer ${key}`, |
| 697 | "Content-Type": "application/json", |
| 698 | ...(prefer ? { Prefer: prefer } : {}), |
| 699 | }, |
| 700 | body: body === undefined ? undefined : JSON.stringify(body), |
| 701 | }); |
| 702 | if (!res.ok) { await res.body?.cancel(); throw Object.assign(new Error(`PostgREST request failed (HTTP ${res.status})`), { status: res.status }); } |
| 703 | const text = await readBoundedResponse(res); |
| 704 | return text ? JSON.parse(text) : null; |
| 705 | } |
| 706 | |
| 707 | /** |
| 708 | * Insert one signed release and prove what landed. A re-run of the same |
| 709 | * envelope (the first run's reply was lost) reports the stored row instead of |
| 710 | * failing on the version high-water mark; different bytes at that version |
| 711 | * stay an error. `request` is postgrest() or a test double. |
| 712 | */ |
| 713 | export async function publishRelease(request, envelope, row, publicKey) { |
| 714 | const channels = await request(`facts_channel?scope=eq.global&slug=eq.${encodeURIComponent(envelope.channel)}&select=id`); |
| 715 | if (channels?.length !== 1) throw new Error(`channel ${envelope.channel} does not exist`); |
| 716 | const channelId = channels[0].id; |
| 717 | await request("facts_key", { method: "POST", body: { key_id: envelope.key_id, scope: "global", algorithm: "ed25519", public_key: publicKey, status: "active" }, prefer: "resolution=ignore-duplicates,return=minimal" }); |
| 718 | let inserted; |
| 719 | try { |
| 720 | inserted = await request("facts_release?select=id,payload_sha256", { method: "POST", body: { ...row, channel_id: channelId }, prefer: "return=representation" }); |
| 721 | } catch (error) { |
| 722 | if (error?.status !== 409) throw error; |
| 723 | const existing = await request(`facts_release?channel_id=eq.${channelId}&facts_version=eq.${envelope.facts_version}&select=id,payload_sha256,status`); |
| 724 | if (existing?.length === 1 && existing[0].payload_sha256 === envelope.sha256) { |
| 725 | return { published: false, already_published: true, channel: envelope.channel, facts_version: envelope.facts_version, release_id: existing[0].id, payload_sha256: existing[0].payload_sha256, status: existing[0].status }; |
| 726 | } |
| 727 | throw new Error(`facts_version ${envelope.facts_version} is at or below channel ${envelope.channel}'s high-water mark and is not this envelope; publish a higher facts_version`); |
| 728 | } |
| 729 | if (inserted?.length !== 1 || inserted[0].payload_sha256 !== envelope.sha256) { |
| 730 | throw new Error(`facts_release insert did not return exactly this envelope (rows: ${inserted?.length ?? 0}); inspect channel ${envelope.channel} before retrying`); |
| 731 | } |
| 732 | return { published: true, channel: envelope.channel, facts_version: envelope.facts_version, release_id: inserted[0].id, payload_sha256: inserted[0].payload_sha256 }; |
| 733 | } |
| 734 | |
| 735 | /** |
| 736 | * Revoke one published release. Only a `published` row flips, so a re-run |
| 737 | * keeps the first revocation's time and reason; a version that matches |
| 738 | * nothing is an error, never a silent `revoked: 0`. `head` says whether the |
| 739 | * channel now serves nothing (revoking an older version changes no delivery). |
| 740 | */ |
| 741 | export async function revokeRelease(request, { channel, version, reason, at }) { |
| 742 | const channels = await request(`facts_channel?scope=eq.global&slug=eq.${encodeURIComponent(channel)}&select=id,max_facts_version`); |
| 743 | if (channels?.length !== 1) throw new Error(`channel ${channel} does not exist`); |
| 744 | const head = Number(channels[0].max_facts_version) === version; |
| 745 | const release = `facts_release?channel_id=eq.${channels[0].id}&facts_version=eq.${version}`; |
| 746 | const updated = await request(`${release}&status=eq.published`, { |
| 747 | method: "PATCH", |
| 748 | body: { status: "revoked", revoked_at: at, revoke_reason: reason }, |
| 749 | prefer: "return=representation", |
| 750 | }); |
| 751 | if (updated?.length === 1) return { revoked: 1, already_revoked: false, head, channel, facts_version: version }; |
| 752 | if ((updated?.length ?? 0) > 1) throw new Error(`revoke matched ${updated.length} releases for ${channel} v${version}; inspect the channel`); |
| 753 | const existing = await request(`${release}&select=status,revoked_at,revoke_reason`); |
| 754 | if (existing?.length === 1 && existing[0].status === "revoked") { |
| 755 | return { revoked: 0, already_revoked: true, head, channel, facts_version: version, revoked_at: existing[0].revoked_at, revoke_reason: existing[0].revoke_reason }; |
| 756 | } |
| 757 | throw new Error(`channel ${channel} has no published facts_version ${version} to revoke`); |
| 758 | } |
| 759 | |
| 760 | export async function readBoundedResponse(response, maxBytes = MAX_ENVELOPE_BYTES) { |
| 761 | const length = response.headers.get("content-length"); |
| 762 | if (length !== null && (!/^\d+$/.test(length) || Number(length) > maxBytes)) { |
| 763 | await response.body?.cancel(); |
| 764 | throw new Error("response exceeds size limit or has invalid length"); |
| 765 | } |
| 766 | if (!response.body) return ""; |
| 767 | const reader = response.body.getReader(); |
| 768 | const chunks = []; |
| 769 | let size = 0; |
| 770 | try { |
| 771 | while (true) { |
| 772 | const { value, done } = await reader.read(); |
| 773 | if (done) break; |
| 774 | size += value.byteLength; |
| 775 | if (size > maxBytes) throw new Error("response exceeds size limit"); |
| 776 | chunks.push(value); |
| 777 | } |
| 778 | } catch (error) { try { await reader.cancel(); } catch { /* Keep rejection. */ } throw error; } |
| 779 | finally { reader.releaseLock(); } |
| 780 | return new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks, size)); |
| 781 | } |
| 782 | |
| 783 | function readJson(path, maxBytes = MAX_REGISTRY_ENVELOPE_BYTES) { |
| 784 | return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(readBoundedFile(path, maxBytes))); |
| 785 | } |
| 786 | |
| 787 | function nowIso() { |
| 788 | return new Date().toISOString().replace(/\.\d{3}Z$/, "Z"); |
| 789 | } |
| 790 | |
| 791 | async function main(argv) { |
| 792 | const { positional, flags } = parseArgs(argv); |
| 793 | const cmd = positional[0]; |
| 794 | if (!cmd || flags.help) { |
| 795 | console.log(readFileSync(fileURLToPath(import.meta.url), "utf8").split("\n").slice(1, 26).join("\n")); |
| 796 | return 0; |
| 797 | } |
| 798 | if (cmd === "keygen") { |
| 799 | const keyId = String(flags["key-id"] ?? ""); |
| 800 | if (!KEY_ID_RE.test(keyId)) throw new Error("--key-id must match cwf-[a-z0-9-]{1,32}"); |
| 801 | const out = flags.out ? resolve(String(flags.out)) : null; |
| 802 | if (!out) throw new Error("--out <path> is required (write the private key OUTSIDE any repository)"); |
| 803 | refuseUnderCi(); |
| 804 | const { privateKey, publicKey } = generateKeyPairSync("ed25519"); |
| 805 | mkdirSync(dirname(out), { recursive: true, mode: 0o700 }); |
| 806 | const fd = openSync(out, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), 0o600); |
| 807 | try { writeFileSync(fd, privateKey.export({ type: "pkcs8", format: "pem" })); } |
| 808 | finally { closeSync(fd); } |
| 809 | const raw = rawPublicKeyFromKeyObject(publicKey); |
| 810 | console.log(JSON.stringify({ |
| 811 | key_id: keyId, |
| 812 | algorithm: "ed25519", |
| 813 | public_key_b64: raw.toString("base64"), |
| 814 | public_key_bytes: [...raw], |
| 815 | private_key_file: out, |
| 816 | note: "Private key written with mode 0600. Move it into custody (password manager); never commit it.", |
| 817 | }, null, 2)); |
| 818 | return 0; |
| 819 | } |
| 820 | if (cmd === "sign") { |
| 821 | refuseUnderCi(); |
| 822 | const sourcePath = resolve(String(flags.source ?? resolve(REPO_ROOT, "docs/cloud-facts/stable.json"))); |
| 823 | const source = readJson(sourcePath); |
| 824 | const defaultChannel = source?.schema === REGISTRY_SCHEMA ? REGISTRY_CHANNEL : (source.channel ?? "stable"); |
| 825 | const channel = String(flags.channel ?? defaultChannel); |
| 826 | if (!CHANNEL_RE.test(channel)) throw new Error("bad channel slug"); |
| 827 | const factsVersion = Number(flags["facts-version"] ?? (channel === REGISTRY_CHANNEL ? source.revision : source.facts_version)); |
| 828 | if (!Number.isSafeInteger(factsVersion) || factsVersion <= 0) throw new Error("--facts-version (or source.facts_version) must be a positive integer"); |
| 829 | const keyId = String(flags["key-id"] ?? ""); |
| 830 | const privateKey = loadPrivateKeyFromEnv(); |
| 831 | const publishedAt = String(flags["published-at"] ?? (channel === REGISTRY_CHANNEL && source.generated_at ? canonicalUtcTimestamp(source.generated_at) : nowIso())); |
| 832 | const payload = channel === REGISTRY_CHANNEL |
| 833 | ? buildRegistryPayload(source, { factsVersion, publishedAt, notAfter: flags["not-after"] }) |
| 834 | : buildPayload(source, { channel, factsVersion, publishedAt }); |
| 835 | const envelope = buildEnvelope({ privateKey, keyId, payload }); |
| 836 | const text = `${JSON.stringify(envelope, null, 2)}\n`; |
| 837 | if (flags.out) { |
| 838 | writeFileSync(resolve(String(flags.out)), text); |
| 839 | console.error(`wrote ${flags.out} (channel=${channel} facts_version=${factsVersion} key_id=${keyId} sha256=${envelope.sha256})`); |
| 840 | } else process.stdout.write(text); |
| 841 | return 0; |
| 842 | } |
| 843 | if (cmd === "verify") { |
| 844 | const envelope = readJson(resolve(String(positional[1] ?? ""))); |
| 845 | let pub = flags["public-key"]; |
| 846 | let trusted; |
| 847 | if (!pub) { |
| 848 | trusted = loadTrustedKeysFromRepo().get(envelope.key_id); |
| 849 | if (!trusted || trusted.status !== "active") throw new Error("key is not pinned and active; use --public-key only for explicit offline verification"); |
| 850 | pub = trusted.publicKey; |
| 851 | } |
| 852 | const result = verifyEnvelope(envelope, String(pub)); |
| 853 | if (result.ok && trusted && trusted.role !== "founder") { |
| 854 | const violation = envelope.channel === REGISTRY_CHANNEL |
| 855 | ? registryAutomationScopeViolation(result.payload) |
| 856 | : automationScopeViolation(result.payload, envelope.channel); |
| 857 | if (violation !== null) { |
| 858 | result.ok = false; |
| 859 | result.errors = [`payload is outside the automation key's scope: ${violation}`]; |
| 860 | } |
| 861 | } |
| 862 | console.log(JSON.stringify({ ok: result.ok, errors: result.errors, channel: envelope.channel, facts_version: envelope.facts_version, key_id: envelope.key_id, sha256: result.sha256 ?? null }, null, 2)); |
| 863 | return result.ok ? 0 : 1; |
| 864 | } |
| 865 | if (cmd === "emit-sql") { |
| 866 | const envelope = readJson(resolve(String(positional[1] ?? ""))); |
| 867 | let pub = flags["public-key"]; |
| 868 | if (!pub) pub = activePublishingKey(envelope, [...loadTrustedKeysFromRepo().values()]).key.publicKey; |
| 869 | process.stdout.write(emitSql(envelope, { publishedBy: String(flags["published-by"] ?? ""), publicKeyB64: pub ? String(pub) : undefined, notes: String(flags.notes ?? "") })); |
| 870 | return 0; |
| 871 | } |
| 872 | if (cmd === "publish") { |
| 873 | const envelope = readJson(resolve(String(positional[1] ?? ""))); |
| 874 | if (flags["public-key"] !== undefined) throw new Error("--public-key is only for offline verify/emit-sql; publication requires the active pinned table"); |
| 875 | const { key, check } = activePublishingKey(envelope, [...loadTrustedKeysFromRepo().values()]); |
| 876 | const pub = key.publicKey; |
| 877 | const row = { |
| 878 | facts_version: envelope.facts_version, |
| 879 | schema_version: envelope.schema_version, |
| 880 | envelope_version: envelope.envelope, |
| 881 | applies_to: envelope.applies_to, |
| 882 | key_id: envelope.key_id, |
| 883 | payload_b64: envelope.payload_b64, |
| 884 | sig_b64: envelope.sig_b64, |
| 885 | sigs: envelope.sigs ?? [], |
| 886 | payload: check.payload, |
| 887 | published_at: envelope.published_at, |
| 888 | not_after: check.payload.not_after ?? null, |
| 889 | published_by: String(flags["published-by"] ?? ""), |
| 890 | notes: String(flags.notes ?? ""), |
| 891 | }; |
| 892 | if (flags["dry-run"]) { |
| 893 | console.log(JSON.stringify({ dry_run: true, channel: envelope.channel, facts_key: { key_id: envelope.key_id, public_key: pub }, facts_release: { ...row, payload_b64: `<${envelope.payload_b64.length} chars>` } }, null, 2)); |
| 894 | return 0; |
| 895 | } |
| 896 | console.log(JSON.stringify(await publishRelease(postgrest, envelope, row, pub), null, 2)); |
| 897 | return 0; |
| 898 | } |
| 899 | if (cmd === "revoke") { |
| 900 | const channel = String(flags.channel ?? ""); |
| 901 | const version = Number(flags.version); |
| 902 | const reason = String(flags.reason ?? ""); |
| 903 | if (!CHANNEL_RE.test(channel) || !Number.isSafeInteger(version) || version <= 0 || !reason) throw new Error("--channel, --version and --reason are required"); |
| 904 | if (flags["dry-run"]) { |
| 905 | console.log(JSON.stringify({ dry_run: true, channel, facts_version: version, status: "revoked", revoke_reason: reason }, null, 2)); |
| 906 | return 0; |
| 907 | } |
| 908 | console.log(JSON.stringify(await revokeRelease(postgrest, { channel, version, reason, at: nowIso() }), null, 2)); |
| 909 | return 0; |
| 910 | } |
| 911 | throw new Error(`unknown command ${cmd}`); |
| 912 | } |
| 913 | |
| 914 | const invokedDirectly = process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url); |
| 915 | if (invokedDirectly) { |
| 916 | main(process.argv.slice(2)).then((code) => process.exit(code)).catch((err) => { |
| 917 | console.error(`facts-publish: ${err.message}`); |
| 918 | process.exit(1); |
| 919 | }); |
| 920 | } |
| 921 |