From 0edcf0648fa71eec6b5e1fd0fa3f3ba09e182fb5 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 11:38:03 +0000 Subject: [PATCH 01/33] feat(aggregator): opt-in sanitized private bridge queue snapshot --- pm-stack/aggregator/src/bridge-snapshot.ts | 98 +++++++++++++++++++ pm-stack/aggregator/src/sources/live.ts | 6 ++ .../aggregator/test/bridge-snapshot.test.ts | 96 ++++++++++++++++++ 3 files changed, 200 insertions(+) create mode 100644 pm-stack/aggregator/src/bridge-snapshot.ts create mode 100644 pm-stack/aggregator/test/bridge-snapshot.test.ts diff --git a/pm-stack/aggregator/src/bridge-snapshot.ts b/pm-stack/aggregator/src/bridge-snapshot.ts new file mode 100644 index 0000000000..a7ed2a42ef --- /dev/null +++ b/pm-stack/aggregator/src/bridge-snapshot.ts @@ -0,0 +1,98 @@ +// Opt-in, credential-free projection for the private Fleet laptop bridge. +// This does not poll, execute commands, enroll a device or change services. +import { constants } from "node:fs"; +import { lstat, mkdir, open, rename, unlink } from "node:fs/promises"; +import { randomUUID } from "node:crypto"; +import { homedir } from "node:os"; +import { join } from "node:path"; +import type { QueueSnapshot } from "./queue.ts"; + +export const BRIDGE_STATUSES = ["queued", "claimed", "parked", "handed_off", "blocked", "done", "cancelled", "failed"] as const; +type Status = (typeof BRIDGE_STATUSES)[number]; +export interface BridgeQueueSnapshot { + version: 1; + fetchedAt: number; + available: boolean; + stale: boolean; + // The collector discards broker pagination totals. Never claim completeness, + // even for an empty page; health counts are not a consistent list snapshot. + complete: false; + total: null; + tasks: { id: number; status: Status; priority: number | null }[]; + counts: Record; +} +const counts = (): Record => Object.fromEntries(BRIDGE_STATUSES.map((s) => [s, 0])) as Record; +const nonnegative = (n: unknown): n is number => Number.isSafeInteger(n) && (n as number) >= 0; + +/** Allowlist output fields, never copy free-form content or error messages. */ +export function bridgeQueueSnapshot(source: QueueSnapshot, now = Date.now()): BridgeQueueSnapshot { + const unavailable = (): BridgeQueueSnapshot => ({ + version: 1, fetchedAt: now, available: false, stale: true, + complete: false, total: null, tasks: [], counts: counts(), + }); + if (!source.available || source.stale || !nonnegative(source.fetchedAt) + || source.fetchedAt > now + 5_000 || now - source.fetchedAt > 300_000 + || !Array.isArray(source.tasks) || !Array.isArray(source.queues)) return unavailable(); + const result: BridgeQueueSnapshot = { + version: 1, fetchedAt: source.fetchedAt, available: true, stale: false, + complete: false, total: null, tasks: [], counts: counts(), + }; + const ids = new Set(); + for (const task of source.tasks) { + if (!nonnegative(task.id) || task.id === 0 || ids.has(task.id) + || !BRIDGE_STATUSES.includes(task.status as Status) + || !(task.priority === null || (typeof task.priority === "number" && Number.isFinite(task.priority)))) return unavailable(); + ids.add(task.id); + if (result.tasks.length < 1000) result.tasks.push({ id: task.id, status: task.status as Status, priority: task.priority }); + } + for (const row of source.queues) { + for (const state of BRIDGE_STATUSES) { + const n = row[state === "handed_off" ? "handedOff" : state]; + if (!nonnegative(n) || !nonnegative(result.counts[state] + n)) return unavailable(); + result.counts[state] += n; + } + } + return result; +} + +/** Only the literal opt-in enables writes. home is injected by offline tests; + * production uses homedir(), never a caller argument or path environment flag. + * Existing directory ownership and symlinks are checked; only a new private + * temp file is opened (exclusive + NOFOLLOW), then atomically replaces target. + * This protects against accidental symlink traversal, not a hostile same-UID + * process concurrently renaming owned ancestor directories. + */ +export async function publishBridgeQueueSnapshot( + source: QueueSnapshot, + enabled = process.env.PM_AGG_BRIDGE_SNAPSHOT, + home = homedir(), + now = Date.now(), +): Promise { + if (enabled !== "1") return; + let directory = home; + const check = async () => { + const st = await lstat(directory); + if (!st.isDirectory() || st.isSymbolicLink() || (st.mode & 0o022) !== 0 + || (typeof process.getuid === "function" && st.uid !== process.getuid())) throw new Error("bridge snapshot directory refused"); + }; + await check(); + for (const part of [".local", "state", "pm-aggregator"]) { + directory = join(directory, part); + await mkdir(directory, { mode: 0o700 }).catch((err: NodeJS.ErrnoException) => { if (err.code !== "EEXIST") throw err; }); + await check(); + } + const target = join(directory, "bridge-queue.json"); + const existing = await lstat(target).catch((err: NodeJS.ErrnoException) => { if (err.code === "ENOENT") return null; throw err; }); + if (existing && (!existing.isFile() || existing.isSymbolicLink())) throw new Error("bridge snapshot target refused"); + const temp = join(directory, `.bridge-queue-${randomUUID()}.tmp`); + const file = await open(temp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600); + try { + await file.writeFile(JSON.stringify(bridgeQueueSnapshot(source, now)) + "\n"); + await file.sync(); + await file.close(); + await rename(temp, target); + } finally { + await file.close().catch(() => {}); + await unlink(temp).catch(() => {}); + } +} diff --git a/pm-stack/aggregator/src/sources/live.ts b/pm-stack/aggregator/src/sources/live.ts index 36b9447234..4870faa1fc 100644 --- a/pm-stack/aggregator/src/sources/live.ts +++ b/pm-stack/aggregator/src/sources/live.ts @@ -7,6 +7,7 @@ import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; import { createHash } from "node:crypto"; import { dirname, join } from "node:path"; import type { Config } from "../config.ts"; +import { publishBridgeQueueSnapshot } from "../bridge-snapshot.ts"; import { applyBoardDonePolicy, isRetiredDoneTableTitle } from "../board-policy.ts"; import { AA_PLAN_FACTS, aaApplyPriceOverlay, isAaSection } from "../aa.ts"; import { aaCacheFileName, aaPricesFingerprint, isAaBatchCacheEntry } from "../aa-batches.ts"; @@ -1564,10 +1565,15 @@ export function liveSource( const token = await readBrokerToken(cfg.queueBrokerTokenFile); if (!token) throw new Error(`queue broker token file unreadable: ${cfg.queueBrokerTokenFile}`); const snap = await fetchQueueSnapshot(cfg.queueBrokerUrl, token); + // Optional local projection only; no additional broker call or credential. + await publishBridgeQueueSnapshot(snap).catch(() => {}); queueCache = { value: snap, at: Date.now() }; return snap; } catch (err) { const msg = err instanceof Error ? err.message : String(err); + // Revoke a recent good projection on a known read failure. If disk + // publication fails too, the bridge rejects it after its five-minute TTL. + await publishBridgeQueueSnapshot(unavailableQueueSnapshot(Date.now(), "unavailable")).catch(() => {}); if (queueCache) { return { ...queueCache.value, available: false, stale: true, errors: [msg] }; } diff --git a/pm-stack/aggregator/test/bridge-snapshot.test.ts b/pm-stack/aggregator/test/bridge-snapshot.test.ts new file mode 100644 index 0000000000..a38e4c22fc --- /dev/null +++ b/pm-stack/aggregator/test/bridge-snapshot.test.ts @@ -0,0 +1,96 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, readFile, lstat, mkdir, symlink, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { bridgeQueueSnapshot, publishBridgeQueueSnapshot, BRIDGE_STATUSES } from "../src/bridge-snapshot.ts"; +import type { QueueSnapshot } from "../src/queue.ts"; + +const NOW = 1_800_000_000_000; +function source(): QueueSnapshot { + return { + available: true, stale: false, fetchedAt: NOW, errors: [], + tasks: [{ id: 12, status: "queued", priority: 10, title: "SECRET", payload: "SECRET", progressNext: "SECRET" }], + queues: [{ queued: 1, claimed: 2, parked: 3, handedOff: 4, blocked: 5, done: 6, cancelled: 7, failed: 8, queue: "SECRET" }], + } as unknown as QueueSnapshot; +} +const path = (home: string) => join(home, ".local/state/pm-aggregator/bridge-queue.json"); + +// Oracle: output has only declared scalar fields and unknown completeness. +test("projection drops every free-form field and does not invent complete pagination", () => { + const got = bridgeQueueSnapshot(source(), NOW); + assert.deepEqual(got, {version:1,fetchedAt:NOW,available:true,stale:false,complete:false,total:null, + tasks:[{id:12,status:"queued",priority:10}], + counts:{queued:1,claimed:2,parked:3,handed_off:4,blocked:5,done:6,cancelled:7,failed:8}}); + assert.ok(!JSON.stringify(got).includes("SECRET")); +}); + +test("all eight statuses retained and output is capped without claiming completeness", () => { + const input = source(); + input.tasks = Array.from({length: 1001}, (_, i) => ({...input.tasks[0],id:i+1,status:BRIDGE_STATUSES[i%8]})); + const got = bridgeQueueSnapshot(input, NOW); + assert.equal(got.tasks.length, 1000); + assert.equal(got.complete, false); + assert.equal(got.total, null); + assert.deepEqual([...new Set(got.tasks.map(t => t.status))].sort(), [...BRIDGE_STATUSES].sort()); +}); + +// Generated boundary corpus; oracle is fail closed with no stale row exposure. +test("invalid numbers, status, freshness, counts and unavailable source fail closed", () => { + const mutations: ((s: QueueSnapshot) => void)[] = [ + s => {s.available=false;}, s => {s.stale=true;}, s => {s.fetchedAt=NOW-300001;}, + s => {s.fetchedAt=NOW+5001;}, s => {s.tasks[0].status="untrusted";}, + s => {s.tasks.push({...s.tasks[0]});}, + ]; + for (const value of [NaN, Infinity, -1, 0, 0.5, Number.MAX_SAFE_INTEGER+1]) mutations.push(s => {s.tasks[0].id=value;}); + for (const value of [NaN, Infinity, -1, 0.5, Number.MAX_SAFE_INTEGER+1]) mutations.push(s => {s.queues[0].queued=value;}); + for (const mutate of mutations) { + const input=source(); mutate(input); + const got=bridgeQueueSnapshot(input,NOW); + assert.equal(got.available,false); assert.equal(got.stale,true); assert.deepEqual(got.tasks,[]); + } +}); + +test("disabled publisher performs no filesystem effects", async () => { + await publishBridgeQueueSnapshot(source(), undefined, "/path-that-does-not-exist", NOW); + await publishBridgeQueueSnapshot(source(), "true", "/path-that-does-not-exist", NOW); +}); + +test("private atomic file, failure marker and symlink denial", async () => { + const home=await mkdtemp(join(tmpdir(),"bridge-projection-")); + const other=await mkdtemp(join(tmpdir(),"bridge-target-")); + try { + await publishBridgeQueueSnapshot(source(),"1",home,NOW); + const first=JSON.parse(await readFile(path(home),"utf8")); + assert.equal(first.available,true); + assert.equal((await lstat(path(home))).mode & 0o777,0o600); + const bad=source(); bad.available=false; + await publishBridgeQueueSnapshot(bad,"1",home,NOW); + assert.equal(JSON.parse(await readFile(path(home),"utf8")).available,false); + await rm(path(home)); await symlink(join(other,"untouched"),path(home)); + await assert.rejects(publishBridgeQueueSnapshot(source(),"1",home,NOW), /target refused/); + await assert.rejects(lstat(join(other,"untouched")), {code:"ENOENT"}); + await rm(join(home,".local"),{recursive:true}); + await symlink(other,join(home,".local")); + await assert.rejects(publishBridgeQueueSnapshot(source(),"1",home,NOW), /directory refused/); + await assert.rejects(lstat(join(other,"state")), {code:"ENOENT"}); + } finally { await rm(home,{recursive:true,force:true}); await rm(other,{recursive:true,force:true}); } +}); + +test("writable ancestor refused before a file is written", async () => { + const home=await mkdtemp(join(tmpdir(),"bridge-mode-")); + try { + await mkdir(join(home,".local"),{mode:0o777}); + // mkdir is affected by umask, so explicitly set the unsafe fixture mode. + const {chmod}=await import("node:fs/promises"); await chmod(join(home,".local"),0o777); + await assert.rejects(publishBridgeQueueSnapshot(source(),"1",home,NOW), /directory refused/); + } finally {await rm(home,{recursive:true,force:true});} +}); + +test("live source wires success and failure publication without another broker read", async () => { + const live=await readFile(new URL("../src/sources/live.ts",import.meta.url),"utf8"); + const body=live.slice(live.indexOf("async function queueSnapshot()"),live.indexOf("\n return {",live.indexOf("async function queueSnapshot()"))); + assert.equal((body.match(/fetchQueueSnapshot\(/g)||[]).length,1); + assert.ok(body.includes("publishBridgeQueueSnapshot(snap)")); + assert.ok(body.includes('publishBridgeQueueSnapshot(unavailableQueueSnapshot(Date.now(), "unavailable"))')); +}); From 35daf8fbac7c69151406f537956c468e5e96d6ca Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 11:39:50 +0000 Subject: [PATCH 02/33] feat(fleet): add bounded outbound read-only laptop client --- pm-stack/private-laptop-bridge/adapters.mjs | 69 +++++++++ pm-stack/private-laptop-bridge/client.mjs | 118 +++++++++++++++ .../private-laptop-bridge/client.test.mjs | 135 ++++++++++++++++++ .../private-laptop-bridge.service.example | 30 ++++ 4 files changed, 352 insertions(+) create mode 100644 pm-stack/private-laptop-bridge/adapters.mjs create mode 100644 pm-stack/private-laptop-bridge/client.mjs create mode 100644 pm-stack/private-laptop-bridge/client.test.mjs create mode 100644 pm-stack/private-laptop-bridge/private-laptop-bridge.service.example diff --git a/pm-stack/private-laptop-bridge/adapters.mjs b/pm-stack/private-laptop-bridge/adapters.mjs new file mode 100644 index 0000000000..f33a26a8ea --- /dev/null +++ b/pm-stack/private-laptop-bridge/adapters.mjs @@ -0,0 +1,69 @@ +import { open, constants } from 'node:fs/promises'; +import { request } from 'node:http'; +import { homedir, uptime, loadavg, freemem } from 'node:os'; +import { join } from 'node:path'; +import { validateOperation, validateResult } from './protocol.mjs'; + +const STATES = ['queued', 'claimed', 'parked', 'handed_off', 'blocked', 'done', 'cancelled', 'failed']; +const MAX_SOURCE_BYTES = 1024 * 1024; +const integer = (v) => Number.isSafeInteger(v) && v >= 0; +const keys = (v, allowed) => v && typeof v === 'object' && !Array.isArray(v) && Object.keys(v).length === allowed.length && allowed.every(k => Object.hasOwn(v, k)); +const failure = (error = 'unavailable') => ({ ok: false, error }); + +// Only this producer-owned snapshot is read. No caller path, token, or broker +// command is accepted. O_NOFOLLOW and regular-file/size checks precede reading. +export async function readQueueSnapshot(home = homedir()) { + const file = await open(join(home, '.local/state/pm-aggregator/bridge-queue.json'), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); + try { + const st = await file.stat(); + if (!st.isFile() || st.size > MAX_SOURCE_BYTES) throw new Error('invalid-source'); + const buffer = Buffer.alloc(MAX_SOURCE_BYTES + 1); + let offset = 0; + while (offset < buffer.length) { + const { bytesRead } = await file.read(buffer, offset, buffer.length - offset, null); + if (!bytesRead) break; + offset += bytesRead; + } + if (offset > MAX_SOURCE_BYTES) throw new Error('invalid-source'); + return JSON.parse(buffer.subarray(0, offset).toString('utf8')); + } finally { await file.close(); } +} + +export function projectQueueSnapshot(snapshot, operation, args, now = Date.now()) { + if (!keys(snapshot, ['version','fetchedAt','available','stale','complete','total','tasks','counts']) || snapshot.version !== 1 || !Number.isSafeInteger(snapshot.fetchedAt) || snapshot.complete !== false || snapshot.total !== null) return failure('invalid-source'); + if (snapshot.available !== true || snapshot.stale !== false || now - snapshot.fetchedAt > 300000 || snapshot.fetchedAt > now + 5000) return failure(); + if (!Array.isArray(snapshot.tasks) || snapshot.tasks.length > 1000 || !keys(snapshot.counts, STATES) || !STATES.every(s => integer(snapshot.counts[s]))) return failure('invalid-source'); + if (!snapshot.tasks.every(t => keys(t, ['id','status','priority']) && integer(t.id) && t.id > 0 && STATES.includes(t.status) && (t.priority === null || Number.isFinite(t.priority)))) return failure('invalid-source'); + if (new Set(snapshot.tasks.map(t => t.id)).size !== snapshot.tasks.length) return failure('invalid-source'); + if (operation === 'fleet.queue.health') return { ok: true, data: Object.fromEntries(STATES.map(s => [s, snapshot.counts[s]])) }; + return { ok: true, data: { tasks: snapshot.tasks.filter(t => !args.status || t.status === args.status).slice(0, args.limit).map(({id,status}) => ({id,status})), complete: false, total: null } }; +} + +// A single unauthenticated GET liveness route over the existing broker's UDS. +// This never reads its all-verbs token and never falls back to TCP. +export function queueBrokerAlive(home = homedir()) { + return new Promise(resolve => { + const req = request({ socketPath: join(home, '.config/queue-broker/broker.sock'), method: 'GET', path: '/healthz', agent: false, headers: { connection: 'close' } }, res => { + let bytes = 0; + res.on('data', chunk => { bytes += chunk.length; if (bytes > 4096) req.destroy(); }); + res.on('end', () => { clearTimeout(timer); resolve(res.statusCode === 200 && bytes <= 4096); }); + res.on('error', () => { clearTimeout(timer); resolve(false); }); + }); + const timer = setTimeout(() => req.destroy(), 2000); + req.on('error', () => { clearTimeout(timer); resolve(false); }); + req.end(); + }); +} + +export function createAdapters({ readSnapshot = readQueueSnapshot, probe = queueBrokerAlive, clock = Date.now, diagnostics = () => ({ uptimeSeconds: Math.floor(uptime()), load1: loadavg()[0], memoryAvailableBytes: freemem() }) } = {}) { + return async function execute(operation, args) { + if (!validateOperation(operation, args)) return failure('invalid-source'); + let result; + try { + if (operation.startsWith('fleet.queue.')) result = projectQueueSnapshot(await readSnapshot(), operation, args, clock()); + else if (operation === 'laptop.health') result = { ok: true, data: { queueBroker: await probe() ? 'up' : 'down' } }; + else result = { ok: true, data: diagnostics() }; + } catch { return failure(); } + return validateResult(operation, result) ? result : failure('invalid-source'); + }; +} diff --git a/pm-stack/private-laptop-bridge/client.mjs b/pm-stack/private-laptop-bridge/client.mjs new file mode 100644 index 0000000000..0f82449097 --- /dev/null +++ b/pm-stack/private-laptop-bridge/client.mjs @@ -0,0 +1,118 @@ +// CLI contract: --config ABSOLUTE_PATH only, or --help alone. Parse the entire +// command line before file/network activity. No key generation or installation. +import { open, constants } from 'node:fs/promises'; +import { isAbsolute } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { setTimeout as delay } from 'node:timers/promises'; +import { signRequest, validateOperation, validateResult, identifier } from './protocol.mjs'; +import { createAdapters } from './adapters.mjs'; + +const exact = (v, list) => v && typeof v === 'object' && !Array.isArray(v) && Object.keys(v).length === list.length && list.every(k => Object.hasOwn(v, k)); +const id = identifier; +export class BridgeDenied extends Error { constructor() { super('bridge-denied'); } } +export function parseArgs(argv) { + if (argv.length === 1 && argv[0] === '--help') return { help: true }; + if (argv.length !== 2 || argv[0] !== '--config' || !isAbsolute(argv[1])) throw new Error('usage'); + return { config: argv[1] }; +} +export function requireNonRoot(getuid = process.getuid) { + if (typeof getuid !== 'function' || !Number.isInteger(getuid()) || getuid() <= 0) throw new Error('non-root-required'); +} +export function validateConfig(config) { + if (!exact(config, ['origin','audience','principal','privateKey'])) throw new Error('invalid-config'); + const origin = new URL(config.origin); + if (origin.protocol !== 'https:' || origin.origin !== config.origin || origin.username || origin.password || !id(config.principal) || typeof config.audience !== 'string' || config.audience.length < 1 || config.audience.length > 200) throw new Error('invalid-config'); + if (!exact(config.privateKey, ['kty','crv','x','d']) || config.privateKey.kty !== 'OKP' || config.privateKey.crv !== 'Ed25519' || !/^[A-Za-z0-9_-]{43}$/.test(config.privateKey.x) || !/^[A-Za-z0-9_-]{43}$/.test(config.privateKey.d)) throw new Error('invalid-config'); + return config; +} +export async function readConfig(path, getuid = process.getuid) { + requireNonRoot(getuid); + const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); + try { + const st = await file.stat(); + if (!st.isFile() || st.size > 8192 || st.uid !== getuid() || (st.mode & 0o077)) throw new Error('invalid-config'); + const buffer = Buffer.alloc(8193); + const { bytesRead } = await file.read(buffer, 0, buffer.length, 0); + if (bytesRead > 8192) throw new Error('invalid-config'); + return validateConfig(JSON.parse(buffer.subarray(0, bytesRead).toString('utf8'))); + } finally { await file.close(); } +} +async function readResponse(response, signal) { + if (!response.body) throw new Error('invalid-response'); + const reader = response.body.getReader(); + const abort = () => { void reader.cancel().catch(() => {}); }; + signal.addEventListener('abort', abort, { once: true }); + const chunks = []; let size = 0; + try { + for (;;) { + signal.throwIfAborted(); + const { done, value } = await reader.read(); + if (done) break; + size += value.length; + if (size > 16384) throw new Error('response-too-large'); + chunks.push(value); + } + signal.throwIfAborted(); + return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks))); + } finally { signal.removeEventListener('abort', abort); void reader.cancel().catch(() => {}); reader.releaseLock(); } +} +export function createClient({ origin, audience, principal, privateKey, fetch: fetchFn = globalThis.fetch, execute = createAdapters(), now = Date.now, sleep = delay, getuid = process.getuid, requestTimeoutMs = 5000 }) { + requireNonRoot(getuid); + const url = new URL(origin); + if (url.protocol !== 'https:' || url.origin !== origin || !id(principal) || typeof audience !== 'string' || !audience) throw new Error('invalid-config'); + async function send(path, body, signal) { + const bounded = signal ? AbortSignal.any([signal, AbortSignal.timeout(requestTimeoutMs)]) : AbortSignal.timeout(requestTimeoutMs); + const request = await signRequest({ origin, audience, principal, privateKey, path, body, now: now() }); + const response = await fetchFn(request, { redirect: 'error', signal: bounded }); + if ([401,403,410].includes(response.status)) { await response.body?.cancel(); throw new BridgeDenied(); } + if (!response.ok || response.redirected) { await response.body?.cancel(); throw new Error('bridge-unavailable'); } + return readResponse(response, bounded); + } + async function step(signal) { + const response = await send('/v1/poll', {}, signal); + if (!exact(response, ['job'])) throw new Error('invalid-response'); + const job = response.job; + if (job === null) return false; + if (!exact(job, ['id','lease','operation','args','expiresAt','leaseExpiresAt']) || !id(job.id) || !id(job.lease) || !validateOperation(job.operation, job.args) || !Number.isSafeInteger(job.expiresAt) || job.expiresAt <= now() || job.expiresAt > now() + 60000 || !Number.isSafeInteger(job.leaseExpiresAt) || job.leaseExpiresAt <= now() || job.leaseExpiresAt > now() + 15000 || job.leaseExpiresAt > job.expiresAt) throw new Error('invalid-job'); + signal?.throwIfAborted(); + const abort = AbortSignal.timeout(Math.max(1, Math.min(5000, job.leaseExpiresAt - now()))); + let onAbort; + const expired = new Promise((_, reject) => { onAbort = () => reject(new Error('execution-timeout')); abort.addEventListener('abort', onAbort, { once: true }); }); + let result; + try { result = await Promise.race([execute(job.operation, job.args), expired]); } + finally { abort.removeEventListener('abort', onAbort); } + signal?.throwIfAborted(); + if (job.expiresAt <= now() || job.leaseExpiresAt <= now()) throw new Error('expired-job'); + if (!validateResult(job.operation, result)) throw new Error('invalid-result'); + await send('/v1/result', { id: job.id, lease: job.lease, result }, signal); + return true; + } + async function run(signal) { + let backoff = 1000; + while (!signal?.aborted) { + try { await step(signal); backoff = 1000; await sleep(1000, undefined, { signal }); } + catch (error) { + if (signal?.aborted) return; + if (error instanceof BridgeDenied) throw error; // Explicit revocation needs owner reconnect. + try { await sleep(backoff, undefined, { signal }); } + catch (sleepError) { if (signal?.aborted) return; throw sleepError; } + backoff = Math.min(30000, backoff * 2); + } + } + } + return { step, run }; +} +export async function main(argv = process.argv.slice(2)) { + const args = parseArgs(argv); + if (args.help) { process.stdout.write('Usage: node client.mjs --config ABSOLUTE_PATH\n'); return; } + const config = await readConfig(args.config); + const privateKey = await crypto.subtle.importKey('jwk', config.privateKey, { name: 'Ed25519' }, false, ['sign']); + const abort = new AbortController(); + const stop = () => abort.abort(); + process.once('SIGTERM', stop); process.once('SIGINT', stop); + try { await createClient({ ...config, privateKey }).run(abort.signal); } + finally { process.removeListener('SIGTERM', stop); process.removeListener('SIGINT', stop); } +} +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + main().catch(error => { process.stderr.write(error.message === 'usage' ? 'Usage: node client.mjs --config ABSOLUTE_PATH\n' : 'Private laptop bridge stopped; inspect configuration and authorization.\n'); process.exitCode = error.message === 'usage' ? 2 : 1; }); +} diff --git a/pm-stack/private-laptop-bridge/client.test.mjs b/pm-stack/private-laptop-bridge/client.test.mjs new file mode 100644 index 0000000000..95de559a9e --- /dev/null +++ b/pm-stack/private-laptop-bridge/client.test.mjs @@ -0,0 +1,135 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtemp, mkdir, writeFile, symlink, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { createClient, parseArgs, requireNonRoot, validateConfig, BridgeDenied } from './client.mjs'; +import { createAdapters, projectQueueSnapshot, readQueueSnapshot } from './adapters.mjs'; + +const statuses = ['queued','claimed','parked','handed_off','blocked','done','cancelled','failed']; +const now = 1800000000000; +const snapshot = () => ({ version:1, fetchedAt:now, available:true, stale:false, complete:false, total:null, tasks: [{id:1,status:'queued',priority:0},{id:2,status:'cancelled',priority:null}], counts:Object.fromEntries(statuses.map(s => [s, s === 'queued' ? 1 : 0])) }); +const json = body => new Response(JSON.stringify(body), { headers:{'content-type':'application/json'} }); +const keys = await crypto.subtle.generateKey('Ed25519', true, ['sign','verify']); +const base = { origin:'https://bridge.invalid', audience:'test-bridge', principal:'amd-device', privateKey:keys.privateKey, now:()=>now, getuid:()=>1000 }; +const job = (overrides = {}) => ({ id:'job-1', lease:'lease-1', operation:'laptop.health', args:{}, expiresAt:now+60000, leaseExpiresAt:now+15000, ...overrides }); + +test('oracle: CLI grammar rejects every undeclared argument before activity', () => { + assert.deepEqual(parseArgs(['--help']), {help:true}); + assert.deepEqual(parseArgs(['--config','/owned/device.json']), {config:'/owned/device.json'}); + for (const argv of [[],['--config'],['--config=x'],['x'],['--help','x'],['--config','relative'],['--config','/x','--shell']]) assert.throws(()=>parseArgs(argv), /usage/); + assert.throws(()=>requireNonRoot(()=>0), /non-root/); + assert.throws(()=>requireNonRoot(null), /non-root/); +}); + +test('oracle: non-root gate runs before network and invalid origins cannot be configured', () => { + let calls=0; + assert.throws(()=>createClient({...base,getuid:()=>0,fetch:()=>calls++}), /non-root/); + assert.equal(calls,0); + for (const origin of ['http://bridge.invalid','https://bridge.invalid/path','https://user:pass@bridge.invalid','https://bridge.invalid/']) assert.throws(()=>createClient({...base,origin})); +}); + +test('oracle: configuration contains exactly owner provisioned Ed25519 identity', async () => { + const exported=await crypto.subtle.exportKey('jwk', keys.privateKey); + const privateKey=Object.fromEntries(['kty','crv','x','d'].map(k=>[k,exported[k]])); + const config={origin:base.origin,audience:base.audience,principal:base.principal,privateKey}; + assert.equal(validateConfig(config),config); + assert.throws(()=>validateConfig({...config,shell:'/bin/sh'})); + assert.throws(()=>validateConfig({...config,privateKey:{...privateKey,kty:'RSA'}})); +}); + +test('oracle: exact signed outbound poll, allowlisted adapter, and completion', async () => { + const requests=[]; + const client=createClient({...base, execute:async(op,args)=>{assert.equal(op,'laptop.health');assert.deepEqual(args,{});return {ok:true,data:{queueBroker:'up'}};}, fetch:async(request,options)=>{ + assert.equal(options.redirect,'error');assert.ok(options.signal);assert.ok(request.headers.get('x-bridge-signature')); + requests.push({path:new URL(request.url).pathname,body:await request.json()}); + return requests.length===1?json({job:job()}):json({ok:true}); + }}); + assert.equal(await client.step(),true); + assert.deepEqual(requests,[{path:'/v1/poll',body:{}},{path:'/v1/result',body:{id:'job-1',lease:'lease-1',result:{ok:true,data:{queueBroker:'up'}}}}]); +}); + +test('oracle: unknown capabilities/arguments/expiry never reach adapters', async () => { + let executes=0; + const cases=[job({operation:'shell'}),job({args:{url:'http://metadata.invalid'}}),job({expiresAt:now}),job({expiresAt:now+60001}),job({leaseExpiresAt:now}),job({leaseExpiresAt:now+15001}),{...job(),command:'id'},job({lease:'../escape'})]; + for (const item of cases) { + const client=createClient({...base,execute:async()=>{executes++;},fetch:async()=>json({job:item})}); + await assert.rejects(client.step(),/invalid-job/); + } + assert.equal(executes,0); +}); + +test('oracle: explicit authorization denial terminates instead of reconnecting', async () => { + for (const status of [401,403,410]) { + let slept=0; + const client=createClient({...base,fetch:async()=>new Response('',{status}),sleep:async()=>slept++}); + await assert.rejects(client.run(),BridgeDenied);assert.equal(slept,0); + } +}); + +test('oracle: disconnect backoff is bounded and successful reconnect resets it', async () => { + const abort=new AbortController();const waits=[];let calls=0; + const client=createClient({...base,fetch:async()=>{calls++;if(calls<=7)throw new Error('offline');return json({job:null});},sleep:async(ms)=>{waits.push(ms);if(calls===8)abort.abort();}}); + await client.run(abort.signal); + assert.deepEqual(waits,[1000,2000,4000,8000,16000,30000,30000,1000]); +}); + +test('oracle: redirects and overlarge responses fail closed', async () => { + for (const response of [new Response('',{status:302,headers:{location:'https://evil.invalid'}}),new Response('x'.repeat(16385))]) { + const client=createClient({...base,fetch:async()=>response}); + await assert.rejects(client.step()); + } +}); + +test('oracle: response stream deadline cancels stalled reads', async () => { + let canceled=false; + const keepalive=setTimeout(()=>{},1000); + try { + const client=createClient({...base,requestTimeoutMs:15,fetch:async()=>new Response(new ReadableStream({cancel(){canceled=true;}}))}); + await assert.rejects(client.step()); assert.equal(canceled,true); + } finally {clearTimeout(keepalive);} +}); + +test('oracle: expiry during execution suppresses result and secret-shaped output is rejected', async () => { + let clock=now,requests=0; + const client=createClient({...base,now:()=>clock,fetch:async()=>{requests++;return json({job:job()});},execute:async()=>{clock+=60001;return {ok:true,data:{queueBroker:'up'}};}}); + await assert.rejects(client.step(),/expired-job/);assert.equal(requests,1); + const leaked=createClient({...base,fetch:async()=>json({job:job()}),execute:async()=>({ok:true,data:{queueBroker:'up',token:'never-return'}})}); + await assert.rejects(leaked.step(),/invalid-result/); +}); + +test('oracle: real snapshot schema projects only IDs/status with explicit partial semantics', () => { + const result=projectQueueSnapshot(snapshot(),'fleet.queue.list',{limit:1},now); + assert.deepEqual(result,{ok:true,data:{tasks:[{id:1,status:'queued'}],complete:false,total:null}}); + assert.deepEqual(projectQueueSnapshot(snapshot(),'fleet.queue.health',{},now),{ok:true,data:snapshot().counts}); + assert.deepEqual(projectQueueSnapshot(snapshot(),'fleet.queue.list',{limit:20,status:'cancelled'},now).data.tasks,[{id:2,status:'cancelled'}]); +}); + +test('invariant/property corpus: malformed/stale snapshots never release source text', () => { + const cases=[null,{}, {...snapshot(),fetchedAt:now-300001},{...snapshot(),fetchedAt:now+5001},{...snapshot(),available:false},{...snapshot(),tasks:[{id:1,status:'queued',priority:null,payload:'secret'}]},{...snapshot(),counts:{...snapshot().counts,queued:-1}}]; + for(let i=0;i<200;i++)cases.push({...snapshot(),tasks:[{id:i%2?-i:1.5,status:'queued',priority:null}]}); + for(const source of cases) { + const result=projectQueueSnapshot(source,'fleet.queue.list',{limit:20},now); + assert.equal(result.ok,false);assert.ok(!JSON.stringify(result).includes('secret')); + } +}); + +test('oracle: production reader uses fixed file, rejects symlink and size overflow', async () => { + const home=await mkdtemp(join(tmpdir(),'bridge-fixture-'));const directory=join(home,'.local/state/pm-aggregator');const path=join(directory,'bridge-queue.json'); + try { + await mkdir(directory,{recursive:true});await writeFile(path,JSON.stringify(snapshot())); + assert.deepEqual(await readQueueSnapshot(home),snapshot()); + await rm(path);await symlink('/etc/passwd',path);await assert.rejects(readQueueSnapshot(home)); + await rm(path);await writeFile(path,'x'.repeat(1024*1024+1));await assert.rejects(readQueueSnapshot(home)); + } finally {await rm(home,{recursive:true,force:true});} +}); + +test('oracle: adapters return only bounded categorical/scalar data and swallow raw errors', async () => { + const execute=createAdapters({readSnapshot:async()=>snapshot(),clock:()=>now,probe:async()=>true,diagnostics:()=>({uptimeSeconds:10,load1:0.5,memoryAvailableBytes:1000})}); + assert.deepEqual(await execute('laptop.health',{}),{ok:true,data:{queueBroker:'up'}}); + assert.equal((await execute('fleet.queue.list',{limit:20})).data.tasks.length,2); + assert.equal((await execute('laptop.diagnostics',{})).data.uptimeSeconds,10); + const broken=createAdapters({readSnapshot:async()=>{throw new Error('sensitive-source-text');}}); + assert.deepEqual(await broken('fleet.queue.list',{limit:1}),{ok:false,error:'unavailable'}); + assert.deepEqual(await execute('shell',{command:'id'}),{ok:false,error:'invalid-source'}); +}); diff --git a/pm-stack/private-laptop-bridge/private-laptop-bridge.service.example b/pm-stack/private-laptop-bridge/private-laptop-bridge.service.example new file mode 100644 index 0000000000..bbefe8f328 --- /dev/null +++ b/pm-stack/private-laptop-bridge/private-laptop-bridge.service.example @@ -0,0 +1,30 @@ +# REVIEW ONLY: no installation, enablement, credentials, or persistent access. +# Owner must approve exact identity, key lifetime, service paths and operations. +# USER unit: no User=root, no root helper, no system-level privilege. +[Unit] +Description=Private read-only Fleet laptop bridge (approval required) + +[Service] +Type=simple +# Replace these reviewed paths with pinned Nix store runtime/package paths. +ExecStart=/APPROVED_NODE_PATH /APPROVED_BRIDGE_PATH/client.mjs --config %h/.config/private-laptop-bridge/device.json +WorkingDirectory=%h +NoNewPrivileges=true +ProtectSystem=strict +ProtectHome=read-only +PrivateTmp=true +PrivateDevices=true +ProtectKernelTunables=true +ProtectKernelModules=true +ProtectControlGroups=true +RestrictSUIDSGID=true +RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 +LockPersonality=true +CapabilityBoundingSet= +UMask=0077 +# A denied/revoked identity stops; no automatic restart loop after denial. +Restart=no +# ProtectHome=read-only is not a filesystem secrecy boundary. Before enabling, +# review mount isolation exposing only device.json, bridge-queue.json and the +# queue-broker socket. No other home reads are implemented by this program. +# No [Install] section: cannot be enabled as distributed. From aa0c7777da6c1d3abb80cdf6464bd1112ac4b715 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 11:40:54 +0000 Subject: [PATCH 03/33] feat(fleet): add private authenticated read-only bridge control plane --- .../private-laptop-bridge/control.test.mjs | 184 ++++++++++++++++++ pm-stack/private-laptop-bridge/package.json | 7 + pm-stack/private-laptop-bridge/protocol.mjs | 55 ++++++ pm-stack/private-laptop-bridge/worker.mjs | 143 ++++++++++++++ pm-stack/private-laptop-bridge/wrangler.jsonc | 10 + 5 files changed, 399 insertions(+) create mode 100644 pm-stack/private-laptop-bridge/control.test.mjs create mode 100644 pm-stack/private-laptop-bridge/package.json create mode 100644 pm-stack/private-laptop-bridge/protocol.mjs create mode 100644 pm-stack/private-laptop-bridge/worker.mjs create mode 100644 pm-stack/private-laptop-bridge/wrangler.jsonc diff --git a/pm-stack/private-laptop-bridge/control.test.mjs b/pm-stack/private-laptop-bridge/control.test.mjs new file mode 100644 index 0000000000..fa8761592c --- /dev/null +++ b/pm-stack/private-laptop-bridge/control.test.mjs @@ -0,0 +1,184 @@ +import {test} from 'node:test'; +import assert from 'node:assert/strict'; +import worker, {PrivateLaptopBridge} from './worker.mjs'; +import {operations, statuses, b64url, signRequest, validateOperation, validateResult, boundedText} from './protocol.mjs'; + +// Oracle: serialized durable transactions; rollback on failure. Instances share +// the same storage on restart. Crypto is real WebCrypto; keys never leave memory. +class Storage { + value; tail = Promise.resolve(); alarmAt; + transaction(fn) { + const result = this.tail.then(async () => { + let value = structuredClone(this.value), alarmAt = this.alarmAt; + const out = await fn({get: async () => structuredClone(value), put: async (_, x) => { value = structuredClone(x); }, setAlarm: async x => { alarmAt = x; }}); + this.value = value; this.alarmAt = alarmAt; return out; + }); + this.tail = result.catch(() => {}); return result; + } +} +async function setup() { + const keys = {}, principals = []; + for (const [id, role] of [['alice', 'caller'], ['bob', 'caller'], ['laptop', 'device']]) { + keys[id] = await crypto.subtle.generateKey('Ed25519', true, ['sign', 'verify']); + principals.push({id, role, device: 'amd', publicKey: b64url(await crypto.subtle.exportKey('raw', keys[id].publicKey)), scopes: [...operations], issuedAt: Date.now() - 1000, expiresAt: Date.now() + 1800000, revoked: false}); + } + const registry = {audience: 'offline-test', principals}; + const env = {ENABLED: 'true', BRIDGE_REGISTRY: JSON.stringify(registry)}; + const storage = new Storage(); let object = new PrivateLaptopBridge({storage}, env); + env.BRIDGE = {idFromName: x => x, get: () => ({fetch: req => object.fetch(req)})}; + const request = (id, path, body, options = {}) => signRequest({origin: 'https://bridge.invalid', audience: registry.audience, principal: id, privateKey: keys[id].privateKey, path, body, ...options}); + const call = async (id, path, body, options) => { const r = await worker.fetch(await request(id, path, body, options), env); return {status: r.status, body: await r.json()}; }; + const update = fn => { fn(registry); env.BRIDGE_REGISTRY = JSON.stringify(registry); }; + const start = (id = 'alice', operation = 'laptop.health', args = {}) => call(id, '/v1/call', {device: 'amd', operation, args}); + return {env, storage, request, call, update, start, restart: () => { object = new PrivateLaptopBridge({storage}, env); }, alarm: () => object.alarm()}; +} +const okHealth = {ok: true, data: {queueBroker: 'up'}}; + +test('normal caller -> outbound poll -> result -> owner read; persists through restart', async () => { + const h = await setup(); const task = await h.start(); assert.equal(task.status, 202); + assert.deepEqual((await h.call('alice', '/v1/read', {id: task.body.id})).body, {status: 'pending'}); + h.restart(); const {job} = (await h.call('laptop', '/v1/poll', {})).body; + assert.equal(job.id, task.body.id); + assert.equal((await h.call('laptop', '/v1/result', {id: job.id, lease: job.lease, result: okHealth})).status, 200); + assert.deepEqual((await h.call('alice', '/v1/read', {id: job.id})).body, {status: 'complete', result: okHealth}); + assert.equal((await h.call('bob', '/v1/read', {id: job.id})).status, 404); + assert.equal((await h.call('laptop', '/v1/result', {id: job.id, lease: job.lease, result: okHealth})).status, 409); +}); + +test('signature binds audience, principal, exact method/path/body; unknown or expired identities deny', async () => { + const h = await setup(); + assert.equal((await h.start('alice')).status, 202); // positive control + for (const options of [{audience: 'other'}, {now: Date.now() - 31000}, {now: Date.now() + 31000}]) assert.equal((await h.call('alice', '/v1/poll', {}, options)).status, 401); + const req = await h.request('alice', '/v1/poll', {}); + assert.equal((await worker.fetch(new Request(req.url, {method: 'POST', headers: req.headers, body: '{"extra":1}'}), h.env)).status, 401); + const r2 = await h.request('alice', '/v1/poll', {}); + assert.equal((await worker.fetch(new Request('https://bridge.invalid/v1/read', {method: 'POST', headers: r2.headers, body: '{}'}), h.env)).status, 401); + h.update(r => { r.principals[0].revoked = true; }); + assert.equal((await h.call('alice', '/v1/poll', {})).status, 401); +}); + +test('role, scope, operation schema and forbidden argument corpus fail closed', async () => { + const h = await setup(); + assert.equal((await h.call('alice', '/v1/poll', {})).status, 403); + assert.equal((await h.start('laptop')).status, 403); + for (const operation of ['exec', '/exec', 'files.read', 'laptop.health;id', '', null]) assert.equal((await h.start('alice', operation)).status, 400); + for (const args of [{command: 'id'}, {path: '/etc/passwd'}, {url: 'https://example.com'}, [], null]) assert.equal((await h.start('alice', 'laptop.health', args)).status, 400); + h.update(r => { r.principals[0].scopes = ['fleet.queue.health']; }); + assert.equal((await h.start()).status, 403); +}); + +test('replay is durable, concurrent duplicates execute once, rejected requests consume quota', async () => { + const h = await setup(); const nonce = 'fixed-nonce'; const req = await h.request('alice', '/v1/call', {device: 'amd', operation: 'laptop.health', args: {}}, {nonce}); + const results = await Promise.all(Array.from({length: 12}, () => worker.fetch(req.clone(), h.env))); + assert.equal(results.filter(r => r.status === 202).length, 1); assert.equal(results.filter(r => r.status === 409).length, 11); + h.restart(); assert.equal((await worker.fetch(req.clone(), h.env)).status, 409); + for (let n = 13; n < 60; n++) assert.equal((await h.call('alice', '/v1/poll', {})).status, 403); + assert.equal((await h.call('alice', '/v1/poll', {})).status, 429); + assert.equal(Object.keys(h.storage.value.jobs).length, 1); +}); + +test('disconnect/reconnect fences old lease; revoked caller and device cannot finish or read', async () => { + const h = await setup(); const task = await h.start(); + const first = (await h.call('laptop', '/v1/poll', {})).body.job; + assert.equal((await h.call('laptop', '/v1/poll', {})).body.job, null); + // Model passage of lease deadline without sleeping or weakening production clock. + h.storage.value.jobs[first.id].leaseUntil = Date.now() - 1; + h.restart(); const second = (await h.call('laptop', '/v1/poll', {})).body.job; + assert.notEqual(second.lease, first.lease); + assert.equal((await h.call('laptop', '/v1/result', {id: first.id, lease: first.lease, result: okHealth})).status, 409); + assert.equal((await h.call('laptop', '/v1/result', {id: second.id, lease: second.lease, result: okHealth})).status, 200); + h.update(r => { r.principals[2].revoked = true; }); + assert.equal((await h.call('alice', '/v1/read', {id: task.body.id})).status, 410); + assert.equal((await h.call('laptop', '/v1/poll', {})).status, 401); + const g = await setup(); await g.start(); g.update(r => { r.principals[0].revoked = true; }); + assert.equal((await g.call('laptop', '/v1/poll', {})).body.job, null); +}); + +test('expiry, queue capacity, malformed results, audit minimization, disabled/storage failures', async () => { + const h = await setup(); const start = await h.start(); const job = (await h.call('laptop', '/v1/poll', {})).body.job; + assert.equal((await h.call('laptop', '/v1/result', {id: job.id, lease: job.lease, result: {ok: true, data: {queueBroker: 'up', secret: 'marker'}}})).status, 400); + assert.equal(JSON.stringify(h.storage.value).includes('marker'), false); + h.storage.value.jobs[job.id].expiresAt = Date.now() - 1; + assert.equal((await h.call('alice', '/v1/read', {id: start.body.id})).status, 410); + for (let n = 1; n < 8; n++) assert.equal((await h.start()).status, 202); + assert.equal((await h.start()).status, 429); + assert.ok(new TextEncoder().encode(JSON.stringify(h.storage.value)).byteLength < 100000); + h.env.ENABLED = 'false'; assert.equal((await h.start()).status, 503); + h.env.ENABLED = 'true'; h.storage.transaction = async () => { throw new Error('private path and secrets'); }; + assert.deepEqual((await h.start()).body, {error: 'storage'}); +}); + +test('registry fails closed on absent config, shared caller/device key and long enrollment', async () => { + for (const change of [r => {r.principals[2].publicKey = r.principals[0].publicKey;}, r => {r.principals[0].expiresAt += 3600000;}, r => {r.principals[0].id = '__proto__';}]) { + const h = await setup(); h.update(change); assert.equal((await h.start()).status, 503); + } + for (const id of ['toString', 'valueOf', 'hasOwnProperty', '__defineGetter__']) { + const g = await setup(); g.update(r => {r.principals[0].id = id;}); assert.equal((await g.start()).status, 503); + } + const h = await setup(); delete h.env.BRIDGE_REGISTRY; assert.equal((await h.start()).status, 503); +}); + +test('schema property corpus: bounds, extra keys and all eight canonical statuses', () => { + for (let limit = -1000; limit <= 1000; limit++) assert.equal(validateOperation('fleet.queue.list', {limit}), limit >= 1 && limit <= 20); + for (const status of statuses) { + assert.equal(validateOperation('fleet.queue.list', {limit: 1, status}), true); + assert.equal(validateResult('fleet.queue.list', {ok: true, data: {tasks: [{id: 1, status}], complete: false, total: null, fetchedAt: Date.now()}}), true); + } + for (const key of ['__proto__', 'command', 'path', 'url', 'token', 'cwd', 'shell', 'argv']) { + const value = JSON.parse(`{"limit":1,"${key}":"marker"}`); + assert.equal(validateOperation('fleet.queue.list', value), false); + } + for (const n of [-1, NaN, Infinity, 1.5, Number.MAX_SAFE_INTEGER + 1]) assert.equal(validateResult('laptop.diagnostics', {ok: true, data: {uptimeSeconds: n, load1: 1, memoryFreeBytes: 0}}), false); +}); + +test('alarm removes expired state without later inbound traffic', async () => { + const h = await setup(); await h.start(); + for (const job of Object.values(h.storage.value.jobs)) job.retainUntil = 0; + for (const k of Object.keys(h.storage.value.nonces)) h.storage.value.nonces[k] = 0; + for (const q of Object.values(h.storage.value.quotas)) q.end = 0; + for (const e of h.storage.value.audit) e.at = 0; + await h.alarm(); assert.deepEqual(h.storage.value, {nonces: {}, quotas: {}, jobs: {}, audit: []}); +}); + + +test('body size, streaming deadline and header limits reject before dispatch', async () => { + await assert.rejects(boundedText(new ReadableStream({start(c) {c.enqueue(new Uint8Array(8193));}})), /size/); + await assert.rejects(boundedText(new ReadableStream({}), 8192, 5), /timeout/); + const h = await setup(); + const large = await h.request('alice', '/v1/poll', {data: 'x'.repeat(8192)}); + assert.equal((await worker.fetch(large, h.env)).status, 413); + const req = await h.request('alice', '/v1/poll', {}); + req.headers.set('content-length', '90000000000'); + assert.equal((await worker.fetch(req, h.env)).status, 413); + const bad = await h.request('alice', '/v1/poll', {}); + bad.headers.set('x-bridge-signature', 'x'.repeat(9000)); + assert.equal((await worker.fetch(bad, h.env)).status, 401); + assert.equal(h.storage.value, undefined); +}); + +test('scope removal invalidates outstanding completion; role changes invalidate result reads', async () => { + const h = await setup(); await h.start(); + const job = (await h.call('laptop', '/v1/poll', {})).body.job; + h.update(r => {r.principals[0].scopes = ['fleet.queue.health'];}); + assert.equal((await h.call('laptop', '/v1/result', {id: job.id, lease: job.lease, result: okHealth})).status, 409); + const g = await setup(); await g.start(); const j = (await g.call('laptop', '/v1/poll', {})).body.job; + await g.call('laptop', '/v1/result', {id: j.id, lease: j.lease, result: okHealth}); + g.update(r => {r.principals[2].role = 'caller';}); + assert.equal((await g.call('alice', '/v1/read', {id: j.id})).status, 410); +}); + +test('source timestamps fail closed at completion and read; alarms are not postponed by new requests', async () => { + const h = await setup(); await h.start('alice', 'fleet.queue.health'); + const firstAlarm = h.storage.alarmAt; + const job = (await h.call('laptop', '/v1/poll', {})).body.job; + assert.equal(h.storage.alarmAt, firstAlarm); + const data = Object.fromEntries(statuses.map(s => [s, 0])); + assert.equal((await h.call('laptop', '/v1/result', {id: job.id, lease: job.lease, result: {ok: true, data: {...data, fetchedAt: Date.now() - 300001}}})).status, 400); + assert.equal((await h.call('laptop', '/v1/result', {id: job.id, lease: job.lease, result: {ok: true, data: {...data, fetchedAt: Date.now() + 60000}}})).status, 400); + assert.equal((await h.call('laptop', '/v1/result', {id: job.id, lease: job.lease, result: {ok: true, data: {...data, fetchedAt: Date.now()}}})).status, 200); + h.storage.value.jobs[job.id].result.data.fetchedAt = Date.now() - 300001; + assert.equal((await h.call('alice', '/v1/read', {id: job.id})).status, 410); + h.storage.value.audit.unshift({at: Date.now() - 180001, principal: 'alice', role: 'caller', route: '/v1/read', status: 200}); + await h.call('alice', '/v1/read', {id: job.id}); + assert.ok(h.storage.value.audit.every(e => e.at > Date.now() - 180000)); +}); diff --git a/pm-stack/private-laptop-bridge/package.json b/pm-stack/private-laptop-bridge/package.json new file mode 100644 index 0000000000..fde248f40f --- /dev/null +++ b/pm-stack/private-laptop-bridge/package.json @@ -0,0 +1,7 @@ +{ + "name": "private-laptop-bridge", + "private": true, + "type": "module", + "scripts": {"test": "node --test *.test.mjs"}, + "engines": {"node": ">=24"} +} diff --git a/pm-stack/private-laptop-bridge/protocol.mjs b/pm-stack/private-laptop-bridge/protocol.mjs new file mode 100644 index 0000000000..73565fc79b --- /dev/null +++ b/pm-stack/private-laptop-bridge/protocol.mjs @@ -0,0 +1,55 @@ +// Protocol v1. Only these named, read-only capabilities cross the bridge. +export const operations = Object.freeze(['fleet.queue.list', 'fleet.queue.health', 'laptop.health', 'laptop.diagnostics']); +export const statuses = Object.freeze(['queued', 'claimed', 'parked', 'handed_off', 'blocked', 'done', 'cancelled', 'failed']); +export const MAX_BODY = 8192; +export const isObject = x => x !== null && typeof x === 'object' && !Array.isArray(x); +export const exact = (x, required, optional = []) => isObject(x) && required.every(k => Object.hasOwn(x, k)) && Object.keys(x).every(k => [...required, ...optional].includes(k)); +export const identifier = x => typeof x === 'string' && !Object.hasOwn(Object.prototype, x) && x !== 'prototype' && /^[a-zA-Z0-9_-]{1,64}$/.test(x); +export function validateOperation(operation, args) { + if (!operations.includes(operation)) return false; + if (operation !== 'fleet.queue.list') return exact(args, []); + return exact(args, ['limit'], ['status']) && Number.isInteger(args.limit) && args.limit >= 1 && args.limit <= 20 && (!Object.hasOwn(args, 'status') || statuses.includes(args.status)); +} +export const b64url = bytes => btoa(String.fromCharCode(...new Uint8Array(bytes))).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, ''); +export function unbase64(value) { + if (typeof value !== 'string' || !/^[A-Za-z0-9_-]+$/.test(value)) throw new Error('encoding'); + const bytes = Uint8Array.from(atob(value.replaceAll('-', '+').replaceAll('_', '/')), c => c.charCodeAt(0)); + if (b64url(bytes) !== value) throw new Error('encoding'); + return bytes; +} +export function signingBytes({audience, principal, method, path, timestamp, nonce, body}) { + return new TextEncoder().encode(JSON.stringify(['fleet-private-bridge/v1', audience, principal, method, path, timestamp, nonce, body])); +} +export async function signRequest({origin, audience, principal, privateKey, path, body, now = Date.now(), nonce = crypto.randomUUID()}) { + const raw = JSON.stringify(body); + const timestamp = String(now); + const signature = b64url(await crypto.subtle.sign('Ed25519', privateKey, signingBytes({audience, principal, method: 'POST', path, timestamp, nonce, body: raw}))); + return new Request(new URL(path, origin), {method: 'POST', headers: {'content-type': 'application/json', 'x-bridge-principal': principal, 'x-bridge-timestamp': timestamp, 'x-bridge-nonce': nonce, 'x-bridge-signature': signature}, body: raw}); +} +export async function boundedText(stream, limit = MAX_BODY, timeoutMs = 3000) { + if (!stream) return ''; + const reader = stream.getReader(); let size = 0; const chunks = []; + let timer; + const deadline = new Promise((_, reject) => { timer = setTimeout(() => { reject(new Error('timeout')); void reader.cancel().catch(() => {}); }, timeoutMs); }); + try { + while (true) { + const {value, done} = await Promise.race([reader.read(), deadline]); if (done) break; + size += value.byteLength; if (size > limit) { void reader.cancel().catch(() => {}); throw new Error('size'); } + chunks.push(value); + } + } finally { clearTimeout(timer); reader.releaseLock(); } + const bytes = new Uint8Array(size); let offset = 0; + for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.length; } + return new TextDecoder('utf-8', {fatal: true}).decode(bytes); +} +const count = x => Number.isSafeInteger(x) && x >= 0; +export function validateResult(operation, result) { + if (!operations.includes(operation) || !isObject(result)) return false; + if (result.ok === false) return exact(result, ['ok', 'error']) && ['unavailable', 'invalid-source', 'timeout'].includes(result.error); + if (result.ok !== true || !exact(result, ['ok', 'data'])) return false; + const d = result.data; + if (operation === 'fleet.queue.list') return exact(d, ['tasks', 'complete', 'total', 'fetchedAt']) && count(d.fetchedAt) && d.complete === false && d.total === null && Array.isArray(d.tasks) && d.tasks.length <= 20 && d.tasks.every(t => exact(t, ['id', 'status']) && count(t.id) && t.id > 0 && statuses.includes(t.status)); + if (operation === 'fleet.queue.health') return exact(d, [...statuses, 'fetchedAt']) && count(d.fetchedAt) && statuses.every(k => count(d[k])); + if (operation === 'laptop.health') return exact(d, ['queueBroker']) && ['up', 'down'].includes(d.queueBroker); + return exact(d, ['uptimeSeconds', 'load1', 'memoryFreeBytes']) && count(d.uptimeSeconds) && count(d.memoryFreeBytes) && Number.isFinite(d.load1) && d.load1 >= 0 && d.load1 <= 100000; +} diff --git a/pm-stack/private-laptop-bridge/worker.mjs b/pm-stack/private-laptop-bridge/worker.mjs new file mode 100644 index 0000000000..752f5fce68 --- /dev/null +++ b/pm-stack/private-laptop-bridge/worker.mjs @@ -0,0 +1,143 @@ +import {operations, exact, identifier, unbase64, signingBytes, boundedText, validateOperation, validateResult} from './protocol.mjs'; + +const nextExpiry = s => Math.min(...Object.values(s.nonces), ...Object.values(s.quotas).map(q => q.end), ...Object.values(s.jobs).map(j => j.retainUntil), ...s.audit.map(e => e.at + 180000)); +const paths = ['/v1/call', '/v1/poll', '/v1/result', '/v1/read']; +const response = (status, body) => { + // Unauthenticated denials cannot safely name an identity. Never echo request values. + if (status >= 400) console.warn(JSON.stringify({event: 'bridge.denied', status, code: body.error})); + return Response.json(body, {status, headers: {'cache-control': 'no-store', 'x-content-type-options': 'nosniff'}}); +}; +const deny = (status, error) => ({status, body: {error}}); +const active = (p, now) => p && !p.revoked && p.issuedAt <= now && p.expiresAt > now; +const sourceFresh = (op, result, now) => !op.startsWith('fleet.queue.') || !result?.ok || (result.data.fetchedAt <= now + 30000 && now - result.data.fetchedAt <= 300000); +const allows = (p, device, op, now) => active(p, now) && p.device === device && p.scopes.includes(op); + +function registry(raw) { + if (typeof raw !== 'string' || raw.length > 16384) throw new Error('config'); + const r = JSON.parse(raw); + if (!exact(r, ['audience', 'principals']) || !identifier(r.audience) || !Array.isArray(r.principals) || r.principals.length < 2 || r.principals.length > 16) throw new Error('config'); + const ids = new Set(), keys = new Set(), principals = {}; + for (const p of r.principals) { + if (!exact(p, ['id', 'role', 'device', 'publicKey', 'scopes', 'issuedAt', 'expiresAt', 'revoked']) || !identifier(p.id) || !identifier(p.device) || !['caller', 'device'].includes(p.role) || typeof p.revoked !== 'boolean' || !Number.isSafeInteger(p.issuedAt) || !Number.isSafeInteger(p.expiresAt) || p.expiresAt <= p.issuedAt || p.expiresAt - p.issuedAt > 3600000 || !Array.isArray(p.scopes) || p.scopes.length < 1 || p.scopes.length > operations.length || new Set(p.scopes).size !== p.scopes.length || !p.scopes.every(s => operations.includes(s)) || ids.has(p.id) || keys.has(p.publicKey) || unbase64(p.publicKey).length !== 32) throw new Error('config'); + ids.add(p.id); keys.add(p.publicKey); principals[p.id] = p; + } + return {audience: r.audience, principals}; +} + +export class PrivateLaptopBridge { + constructor(state, env) { this.state = state; this.env = env; } + async fetch(request) { + if (this.env.ENABLED !== 'true') return response(503, {error: 'disabled'}); + let now = Date.now(); let config; + try { config = registry(this.env.BRIDGE_REGISTRY); } catch { return response(503, {error: 'configuration'}); } + const url = new URL(request.url); + if (request.method !== 'POST' || url.search || !paths.includes(url.pathname)) return response(404, {error: 'route'}); + if (request.headers.get('content-type') !== 'application/json') return response(415, {error: 'content-type'}); + const id = request.headers.get('x-bridge-principal'); + const principal = identifier(id) && Object.hasOwn(config.principals, id) ? config.principals[id] : null; + const timestamp = request.headers.get('x-bridge-timestamp'), nonce = request.headers.get('x-bridge-nonce'); + if (!active(principal, now) || !/^\d{13}$/.test(timestamp ?? '') || Math.abs(now - Number(timestamp)) > 30000 || !identifier(nonce)) return response(401, {error: 'authentication'}); + const length = request.headers.get('content-length'); + if (length !== null && (!/^\d{1,5}$/.test(length) || Number(length) > 8192)) return response(413, {error: 'body'}); + if (request.headers.get('x-bridge-signature')?.length !== 86) return response(401, {error: 'authentication'}); + let raw; + try { raw = await boundedText(request.body); } catch { return response(413, {error: 'body'}); } + try { + const key = await crypto.subtle.importKey('raw', unbase64(principal.publicKey), 'Ed25519', false, ['verify']); + if (!await crypto.subtle.verify('Ed25519', key, unbase64(request.headers.get('x-bridge-signature')), signingBytes({audience: config.audience, principal: id, method: request.method, path: url.pathname, timestamp, nonce, body: raw}))) return response(401, {error: 'authentication'}); + } catch { return response(401, {error: 'authentication'}); } + try { + const outcome = await this.state.storage.transaction(async tx => { + now = Date.now(); + if (!active(principal, now) || Math.abs(now - Number(timestamp)) > 30000) return deny(401, 'authentication'); + const s = await tx.get('state') ?? {nonces: {}, quotas: {}, jobs: {}, audit: []}; + for (const [k, expiry] of Object.entries(s.nonces)) if (expiry <= now) delete s.nonces[k]; + for (const [k, q] of Object.entries(s.quotas)) if (q.end <= now) delete s.quotas[k]; + for (const [k, job] of Object.entries(s.jobs)) if (job.retainUntil <= now) delete s.jobs[k]; + const replay = `${id}:${nonce}`; + let result; + const q = s.quotas[id] ?? {end: now + 60000, count: 0}; + s.quotas[id] = q; + if (q.count >= 60) result = deny(429, 'quota'); + else { + q.count++; + if (s.nonces[replay]) result = deny(409, 'replay'); + else if (Object.keys(s.nonces).length >= 256) result = deny(429, 'capacity'); + else { + s.nonces[replay] = now + 61000; + let body; try { body = JSON.parse(raw); } catch { body = null; } + result = this.route(url.pathname, body, principal, config, s, now); + } + } + // Audit contains only server-selected codes and validated identity labels. + s.audit.push({at: now, principal: id, role: principal.role, route: url.pathname, status: result.status}); + s.audit = s.audit.filter(e => e.at + 180000 > now).slice(-64); + await tx.put('state', s); + // Keep data retention bounded even when no later request arrives. + await tx.setAlarm(nextExpiry(s)); + return result; + }); + return response(outcome.status, outcome.body); + } catch { return response(503, {error: 'storage'}); } + } + async alarm() { + // All records expire within 180s. A single serialized transaction prevents + // deleting a request accepted concurrently with cleanup. + const now = Date.now(); + await this.state.storage.transaction(async tx => { + const s = await tx.get('state'); if (!s) return; + for (const [k, expiry] of Object.entries(s.nonces)) if (expiry <= now) delete s.nonces[k]; + for (const [k, q] of Object.entries(s.quotas)) if (q.end <= now) delete s.quotas[k]; + for (const [k, job] of Object.entries(s.jobs)) if (job.retainUntil <= now) delete s.jobs[k]; + s.audit = s.audit.filter(e => e.at + 180000 > now); + await tx.put('state', s); + const next = nextExpiry(s); + if (Number.isFinite(next)) await tx.setAlarm(next); + }); + } + route(path, body, p, config, s, now) { + const liveJob = job => job && job.expiresAt > now && allows(config.principals[job.caller], job.device, job.operation, now) && config.principals[job.caller].role === 'caller'; + if (path === '/v1/call') { + if (p.role !== 'caller') return deny(403, 'role'); + if (!exact(body, ['device', 'operation', 'args']) || !identifier(body.device) || !validateOperation(body.operation, body.args)) return deny(400, 'operation'); + if (!allows(p, body.device, body.operation, now)) return deny(403, 'scope'); + if (!Object.values(config.principals).some(d => d.role === 'device' && allows(d, body.device, body.operation, now))) return deny(403, 'device'); + if (Object.keys(s.jobs).length >= 8) return deny(429, 'capacity'); + const id = crypto.randomUUID(); + s.jobs[id] = {id, device: body.device, operation: body.operation, args: body.args, caller: p.id, expiresAt: now + 60000, retainUntil: now + 120000, lease: null, leaseUntil: 0, assignee: null}; + return {status: 202, body: {id, expiresAt: s.jobs[id].expiresAt}}; + } + if (path === '/v1/poll') { + if (p.role !== 'device') return deny(403, 'role'); + if (!exact(body, [])) return deny(400, 'body'); + const job = Object.values(s.jobs).find(j => liveJob(j) && !j.result && j.leaseUntil <= now && allows(p, j.device, j.operation, now)); + if (!job) return {status: 200, body: {job: null}}; + job.lease = crypto.randomUUID(); job.leaseUntil = Math.min(now + 15000, job.expiresAt); job.assignee = p.id; + return {status: 200, body: {job: {id: job.id, lease: job.lease, operation: job.operation, args: job.args, expiresAt: job.expiresAt, leaseExpiresAt: job.leaseUntil}}}; + } + if (path === '/v1/result') { + if (p.role !== 'device') return deny(403, 'role'); + if (!exact(body, ['id', 'lease', 'result']) || !identifier(body.id) || !identifier(body.lease)) return deny(400, 'body'); + const job = s.jobs[body.id]; + if (!liveJob(job) || job.result || job.leaseUntil <= now || job.lease !== body.lease || job.assignee !== p.id || !allows(p, job.device, job.operation, now)) return deny(409, 'lease'); + if (!validateResult(job.operation, body.result) || !sourceFresh(job.operation, body.result, now) || (job.operation === 'fleet.queue.list' && body.result.ok && (body.result.data.tasks.length > job.args.limit || (job.args.status && body.result.data.tasks.some(t => t.status !== job.args.status))))) return deny(400, 'result'); + job.result = body.result; + return {status: 200, body: {accepted: true}}; + } + if (p.role !== 'caller') return deny(403, 'role'); + if (!exact(body, ['id']) || !identifier(body.id)) return deny(400, 'body'); + const job = s.jobs[body.id]; + if (!job || job.caller !== p.id) return deny(404, 'job'); + if (!liveJob(job) || (job.assignee && (config.principals[job.assignee]?.role !== 'device' || !allows(config.principals[job.assignee], job.device, job.operation, now)))) return deny(410, 'expired-or-revoked'); + if (job.result && !sourceFresh(job.operation, job.result, now)) return deny(410, 'stale-source'); + return {status: 200, body: job.result ? {status: 'complete', result: job.result} : {status: 'pending'}}; + } +} + +export default { + async fetch(request, env) { + if (env.ENABLED !== 'true' || !env.BRIDGE) return response(503, {error: 'disabled'}); + try { return await env.BRIDGE.get(env.BRIDGE.idFromName('owner-v1')).fetch(request); } + catch { return response(503, {error: 'storage'}); } + }, +}; diff --git a/pm-stack/private-laptop-bridge/wrangler.jsonc b/pm-stack/private-laptop-bridge/wrangler.jsonc new file mode 100644 index 0000000000..4151db7e24 --- /dev/null +++ b/pm-stack/private-laptop-bridge/wrangler.jsonc @@ -0,0 +1,10 @@ +{ + "name": "private-laptop-bridge-staging", + "main": "worker.mjs", + "compatibility_date": "2026-07-30", + "workers_dev": false, + "preview_urls": false, + "vars": {"ENABLED": "false"}, + "durable_objects": {"bindings": [{"name": "BRIDGE", "class_name": "PrivateLaptopBridge"}]}, + "migrations": [{"tag": "v1", "new_sqlite_classes": ["PrivateLaptopBridge"]}] +} From 1db89cd19b8bf28b808f8931f9bcedd7108f5cdc Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 11:40:55 +0000 Subject: [PATCH 04/33] fix(fleet): enforce lease deadline and snapshot provenance --- pm-stack/private-laptop-bridge/adapters.mjs | 14 +++++++++----- pm-stack/private-laptop-bridge/client.mjs | 3 ++- pm-stack/private-laptop-bridge/client.test.mjs | 18 +++++++++++++----- 3 files changed, 24 insertions(+), 11 deletions(-) diff --git a/pm-stack/private-laptop-bridge/adapters.mjs b/pm-stack/private-laptop-bridge/adapters.mjs index f33a26a8ea..30ff036822 100644 --- a/pm-stack/private-laptop-bridge/adapters.mjs +++ b/pm-stack/private-laptop-bridge/adapters.mjs @@ -1,4 +1,4 @@ -import { open, constants } from 'node:fs/promises'; +import { open, lstat, constants } from 'node:fs/promises'; import { request } from 'node:http'; import { homedir, uptime, loadavg, freemem } from 'node:os'; import { join } from 'node:path'; @@ -13,10 +13,14 @@ const failure = (error = 'unavailable') => ({ ok: false, error }); // Only this producer-owned snapshot is read. No caller path, token, or broker // command is accepted. O_NOFOLLOW and regular-file/size checks precede reading. export async function readQueueSnapshot(home = homedir()) { + for (const directory of [home, join(home, '.local'), join(home, '.local/state'), join(home, '.local/state/pm-aggregator')]) { + const st = await lstat(directory); + if (!st.isDirectory() || st.uid !== process.getuid() || (st.mode & 0o022)) throw new Error('invalid-source'); + } const file = await open(join(home, '.local/state/pm-aggregator/bridge-queue.json'), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); try { const st = await file.stat(); - if (!st.isFile() || st.size > MAX_SOURCE_BYTES) throw new Error('invalid-source'); + if (!st.isFile() || st.size > MAX_SOURCE_BYTES || st.uid !== process.getuid() || (st.mode & 0o022)) throw new Error('invalid-source'); const buffer = Buffer.alloc(MAX_SOURCE_BYTES + 1); let offset = 0; while (offset < buffer.length) { @@ -35,8 +39,8 @@ export function projectQueueSnapshot(snapshot, operation, args, now = Date.now() if (!Array.isArray(snapshot.tasks) || snapshot.tasks.length > 1000 || !keys(snapshot.counts, STATES) || !STATES.every(s => integer(snapshot.counts[s]))) return failure('invalid-source'); if (!snapshot.tasks.every(t => keys(t, ['id','status','priority']) && integer(t.id) && t.id > 0 && STATES.includes(t.status) && (t.priority === null || Number.isFinite(t.priority)))) return failure('invalid-source'); if (new Set(snapshot.tasks.map(t => t.id)).size !== snapshot.tasks.length) return failure('invalid-source'); - if (operation === 'fleet.queue.health') return { ok: true, data: Object.fromEntries(STATES.map(s => [s, snapshot.counts[s]])) }; - return { ok: true, data: { tasks: snapshot.tasks.filter(t => !args.status || t.status === args.status).slice(0, args.limit).map(({id,status}) => ({id,status})), complete: false, total: null } }; + if (operation === 'fleet.queue.health') return { ok: true, data: { ...Object.fromEntries(STATES.map(s => [s, snapshot.counts[s]])), fetchedAt: snapshot.fetchedAt } }; + return { ok: true, data: { tasks: snapshot.tasks.filter(t => !args.status || t.status === args.status).slice(0, args.limit).map(({id,status}) => ({id,status})), complete: false, total: null, fetchedAt: snapshot.fetchedAt } }; } // A single unauthenticated GET liveness route over the existing broker's UDS. @@ -55,7 +59,7 @@ export function queueBrokerAlive(home = homedir()) { }); } -export function createAdapters({ readSnapshot = readQueueSnapshot, probe = queueBrokerAlive, clock = Date.now, diagnostics = () => ({ uptimeSeconds: Math.floor(uptime()), load1: loadavg()[0], memoryAvailableBytes: freemem() }) } = {}) { +export function createAdapters({ readSnapshot = readQueueSnapshot, probe = queueBrokerAlive, clock = Date.now, diagnostics = () => ({ uptimeSeconds: Math.floor(uptime()), load1: loadavg()[0], memoryFreeBytes: freemem() }) } = {}) { return async function execute(operation, args) { if (!validateOperation(operation, args)) return failure('invalid-source'); let result; diff --git a/pm-stack/private-laptop-bridge/client.mjs b/pm-stack/private-laptop-bridge/client.mjs index 0f82449097..4e7584dffd 100644 --- a/pm-stack/private-laptop-bridge/client.mjs +++ b/pm-stack/private-laptop-bridge/client.mjs @@ -84,7 +84,8 @@ export function createClient({ origin, audience, principal, privateKey, fetch: f signal?.throwIfAborted(); if (job.expiresAt <= now() || job.leaseExpiresAt <= now()) throw new Error('expired-job'); if (!validateResult(job.operation, result)) throw new Error('invalid-result'); - await send('/v1/result', { id: job.id, lease: job.lease, result }, signal); + const accepted = await send('/v1/result', { id: job.id, lease: job.lease, result }, signal); + if (!exact(accepted, ['accepted']) || accepted.accepted !== true) throw new Error('invalid-ack'); return true; } async function run(signal) { diff --git a/pm-stack/private-laptop-bridge/client.test.mjs b/pm-stack/private-laptop-bridge/client.test.mjs index 95de559a9e..f8a3180fbf 100644 --- a/pm-stack/private-laptop-bridge/client.test.mjs +++ b/pm-stack/private-laptop-bridge/client.test.mjs @@ -1,6 +1,6 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { mkdtemp, mkdir, writeFile, symlink, rm } from 'node:fs/promises'; +import { mkdtemp, mkdir, writeFile, symlink, rm, chmod } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { createClient, parseArgs, requireNonRoot, validateConfig, BridgeDenied } from './client.mjs'; @@ -43,7 +43,7 @@ test('oracle: exact signed outbound poll, allowlisted adapter, and completion', const client=createClient({...base, execute:async(op,args)=>{assert.equal(op,'laptop.health');assert.deepEqual(args,{});return {ok:true,data:{queueBroker:'up'}};}, fetch:async(request,options)=>{ assert.equal(options.redirect,'error');assert.ok(options.signal);assert.ok(request.headers.get('x-bridge-signature')); requests.push({path:new URL(request.url).pathname,body:await request.json()}); - return requests.length===1?json({job:job()}):json({ok:true}); + return requests.length===1?json({job:job()}):json({accepted:true}); }}); assert.equal(await client.step(),true); assert.deepEqual(requests,[{path:'/v1/poll',body:{}},{path:'/v1/result',body:{id:'job-1',lease:'lease-1',result:{ok:true,data:{queueBroker:'up'}}}}]); @@ -100,8 +100,8 @@ test('oracle: expiry during execution suppresses result and secret-shaped output test('oracle: real snapshot schema projects only IDs/status with explicit partial semantics', () => { const result=projectQueueSnapshot(snapshot(),'fleet.queue.list',{limit:1},now); - assert.deepEqual(result,{ok:true,data:{tasks:[{id:1,status:'queued'}],complete:false,total:null}}); - assert.deepEqual(projectQueueSnapshot(snapshot(),'fleet.queue.health',{},now),{ok:true,data:snapshot().counts}); + assert.deepEqual(result,{ok:true,data:{tasks:[{id:1,status:'queued'}],complete:false,total:null,fetchedAt:now}}); + assert.deepEqual(projectQueueSnapshot(snapshot(),'fleet.queue.health',{},now),{ok:true,data:{...snapshot().counts,fetchedAt:now}}); assert.deepEqual(projectQueueSnapshot(snapshot(),'fleet.queue.list',{limit:20,status:'cancelled'},now).data.tasks,[{id:2,status:'cancelled'}]); }); @@ -119,13 +119,21 @@ test('oracle: production reader uses fixed file, rejects symlink and size overfl try { await mkdir(directory,{recursive:true});await writeFile(path,JSON.stringify(snapshot())); assert.deepEqual(await readQueueSnapshot(home),snapshot()); + await chmod(path,0o666);await assert.rejects(readQueueSnapshot(home));await chmod(path,0o600); + await chmod(directory,0o777);await assert.rejects(readQueueSnapshot(home));await chmod(directory,0o700); await rm(path);await symlink('/etc/passwd',path);await assert.rejects(readQueueSnapshot(home)); await rm(path);await writeFile(path,'x'.repeat(1024*1024+1));await assert.rejects(readQueueSnapshot(home)); } finally {await rm(home,{recursive:true,force:true});} }); +test('oracle: completion acknowledgement must confirm acceptance', async () => { + let calls=0; + const client=createClient({...base,fetch:async()=>++calls===1?json({job:job()}):json({ok:true}),execute:async()=>({ok:true,data:{queueBroker:'up'}})}); + await assert.rejects(client.step(),/invalid-ack/); +}); + test('oracle: adapters return only bounded categorical/scalar data and swallow raw errors', async () => { - const execute=createAdapters({readSnapshot:async()=>snapshot(),clock:()=>now,probe:async()=>true,diagnostics:()=>({uptimeSeconds:10,load1:0.5,memoryAvailableBytes:1000})}); + const execute=createAdapters({readSnapshot:async()=>snapshot(),clock:()=>now,probe:async()=>true,diagnostics:()=>({uptimeSeconds:10,load1:0.5,memoryFreeBytes:1000})}); assert.deepEqual(await execute('laptop.health',{}),{ok:true,data:{queueBroker:'up'}}); assert.equal((await execute('fleet.queue.list',{limit:20})).data.tasks.length,2); assert.equal((await execute('laptop.diagnostics',{})).data.uptimeSeconds,10); From 0ba3dd75a22d83690ce5131a03fa5b8e067cd3d3 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 11:45:50 +0000 Subject: [PATCH 05/33] Verify private Fleet bridge end to end in offline Workers staging --- pm-stack/private-laptop-bridge/.gitignore | 2 + pm-stack/private-laptop-bridge/README.md | 229 +++++ .../private-laptop-bridge/VERIFICATION.md | 52 + pm-stack/private-laptop-bridge/caller.mjs | 143 +++ pm-stack/private-laptop-bridge/model.test.mjs | 125 +++ .../private-laptop-bridge/package-lock.json | 951 ++++++++++++++++++ pm-stack/private-laptop-bridge/package.json | 11 +- .../private-laptop-bridge/runtime.test.mjs | 271 +++++ 8 files changed, 1782 insertions(+), 2 deletions(-) create mode 100644 pm-stack/private-laptop-bridge/.gitignore create mode 100644 pm-stack/private-laptop-bridge/README.md create mode 100644 pm-stack/private-laptop-bridge/VERIFICATION.md create mode 100644 pm-stack/private-laptop-bridge/caller.mjs create mode 100644 pm-stack/private-laptop-bridge/model.test.mjs create mode 100644 pm-stack/private-laptop-bridge/package-lock.json create mode 100644 pm-stack/private-laptop-bridge/runtime.test.mjs diff --git a/pm-stack/private-laptop-bridge/.gitignore b/pm-stack/private-laptop-bridge/.gitignore new file mode 100644 index 0000000000..0dcc8a4190 --- /dev/null +++ b/pm-stack/private-laptop-bridge/.gitignore @@ -0,0 +1,2 @@ +node_modules/ +.wrangler/ diff --git a/pm-stack/private-laptop-bridge/README.md b/pm-stack/private-laptop-bridge/README.md new file mode 100644 index 0000000000..3ab286e35a --- /dev/null +++ b/pm-stack/private-laptop-bridge/README.md @@ -0,0 +1,229 @@ +# Private laptop bridge — offline candidate + +**Not deployed; not a replacement-ready cutover.** Desktop Commander remains the +fallback. This package implements bounded Fleet reads, not a shell. Aster still +needs an approved caller integration, a privately reachable control plane, and +verified enrollment on Drew's AMD NixOS laptop before relying on it. + +## Permission boundary + +The caller submits one named read. The laptop makes an outbound poll, executes a +fixed local adapter, and returns a projected result. The Cloudflare Durable +Object holds only short-lived RPC requests/results; the Fleet queue remains the +existing Turso-backed queue. No endpoint claims, dispatches, changes tasks, +restarts services, reads arbitrary files, fetches arbitrary URLs, executes a +command, or accepts scripts. Builds/tests are deliberately outside this version. + +The Worker is default-disabled, has no routes, workers.dev or preview URLs, and +contains no private keys. Device and caller identities are independently pinned +public keys with separate roles, device binding, operation scopes, expiration and +revocation. Possession of a device key does not grant caller permissions. A +request signature covers its audience, endpoint, method, timestamp, nonce and +exact body. Durable replay checks, short leases, quotas and strict output schemas +apply before a result becomes visible to its requesting caller. + +Only synthetic, memory-only test keys are created by tests. No credential is +created, transferred or enrolled by installation code. Runtime signing material +must be provisioned by an independently approved owner procedure. The existing +queue broker credential is never loaded by this bridge. + +## Existing components and decisions + +Inspected main at `ad4e6967008968b2f28334ddd89d8de24af4ba73` (2026-11-22), +including newly merged [#12505](https://github.com/developing-today/code/pull/12505). + +* `pm-stack/console/edge` demonstrates Workers/Durable Object packaging and an + outbound host sync. Its tunnel fallback, laptop-driven authority bootstrap, + persistent key auto-generation, and held write actions are unsuitable here. + This bridge is separate and fails closed without a fallback proxy. +* `pkgs/fleet/crates/fleet-queue/src/queue_broker.rs` uses the same + `X-Agent-Token` for all POST verbs on TCP **and** Unix sockets. The comment in + `pm-stack/aggregator/src/queue.ts` describing a read-capable token does not + establish a restricted credential. The client therefore never calls those + authenticated endpoints or reads their token file. +* The existing aggregator already reads `/health` and `/list`. An opt-in + sanitized snapshot producer supplies queue metadata to this bridge without + adding another credential consumer. Publication does not add a polling timer: + it occurs when the existing collector refreshes. Unrefreshed data expires. +* `pkgs/laptop-agent/src/laptop_agent.py` exposes general `/exec`, `/jobs` and + `/file`. None is called or proxied here. +* `home/common/default.nix` declares `desktop-commander-remote`; this change does + not modify it, its saved authorization, native Codex, or laptop networking. + +Work inspected while open: [#12312](https://github.com/developing-today/code/pull/12312) +(mcpx laptop SSH), [#12226](https://github.com/developing-today/code/pull/12226) +(health hooks), [#12299](https://github.com/developing-today/code/pull/12299) +(OpenCode restart behavior), [#12500](https://github.com/developing-today/code/pull/12500) +(Fleet credential cache parsing). Those are not dependencies or deployed by this +package. #12500 subsequently landed and was included when updating the base to +`7bfcaff23`; no bridge credential flow reuses the cache daemon. + +## Workflow coverage and native Codex + +| Workflow | This bridge | Native Codex / remaining evidence | +| --- | --- | --- | +| Bounded queue task status | Sanitized snapshot, numeric IDs and statuses; honest partial/stale reporting | Detailed payloads, titles and bound sessions excluded | +| Queue counters | Sanitized existing collector counters | Live broker parity still needs laptop verification | +| Laptop health | Fixed credential-free local health observation | No service changes | +| Bounded diagnostics | Strict scalar/categorical projection | No environment, logs or arbitrary files | +| Repository exploration, editing, builds, test development, interactive debugging | No permission | Aster's separate native Codex setup | +| Arbitrary shell / filesystem operations | No permission | Native Codex with its own authorization; never add as a bridge fallback | +| Dispatch, enqueue, cancel, service restart, deployment | No permission | Separate explicit permission review required | + +Repository sources establish Commander capability, **not an observed inventory of +Aster's actual Commander calls**. Available conversation history only describes +proposed Fleet reads and a prior reachability check. Do not call this workflow +parity or retire Commander based on synthetic tests. During the authorized pilot, +record actual operation names (not command output/secrets), map each to a bridge +read or native Codex, and verify unsupported essential workflows have a working +replacement. + +## Rollout gates — nothing below has been applied + +1. Review this exact commit, schemas, local data permissions and security tests. + Keep all production deployment automation absent. Confirm snapshot contents + expose only the requested metadata and truncation/freshness semantics. +2. Drew must approve the **specific** caller identity/scopes, device identity, + signing-key provisioning and lifetime, private ingress design/hostname, + Cloudflare account/resources/cost cap, permitted local paths/socket, and + non-root service configuration. This package does not choose a public gateway. + A service binding alone is not a laptop-accessible transport: the authorized + private caller/device ingress remains a required integration decision. +3. In approved isolated staging, enroll separate short-lived identities through + an owner-controlled channel. Never accept a device-reported caller key or an + unauthenticated key-discovery endpoint. Prove wrong-role, wrong-device, + wrong-audience, expired and revoked identities fail at every stage. +4. Explicitly approve enabling `PM_AGG_BRIDGE_SNAPSHOT=1` on the existing + aggregator and installing the **disabled example** non-root bridge unit. + Confirm actual permissions, Nix Node path, fixed snapshot location and local + health socket. Observe a fresh real snapshot; then simulate stale/missing + snapshots and prove they cannot report healthy/empty success. +5. Start the client manually for the approved pilot window. Demonstrate Aster + submitting and receiving each authorized read end to end on AMD. Disconnect + the laptop, reconnect after lease loss, and prove the old lease cannot complete. + Check bounded output, quota exhaustion and no secret data in audit records. +6. Revoke both identities independently and demonstrate denial of submit, poll, + completion and stored-result retrieval. Registry changes via deployment are + not instantaneous: confirm the active configuration and observed denials; + do not claim revocation completed just because deployment was requested. +7. Confirm native Codex covers every required non-bridge operation. Only after + owner acceptance of the observed parity and rollback rehearsal may a separate + change propose retiring Desktop Commander. Its credentials/service must remain + intact throughout this implementation and pilot. + +## Rollback + +Disable the bridge first (`ENABLED` not `true`), revoke the caller/device entries, +and stop the new user service. Remove private ingress/service bindings only under +the same approved change procedure. Disable the aggregator snapshot opt-in; +remaining snapshots age out and are never treated as fresh indefinitely. Short +RPC/result lifetimes bound recoverable data; explicit deletion of cloud resources +or credential material needs its own approved cleanup. Resume Fleet through the +unchanged Desktop Commander/native Codex paths. Never silently forward a failed +bridge request to either general-purpose agent. + +## Runtime references + +Cloudflare documents [Durable Object state](https://developers.cloudflare.com/durable-objects/api/state/) +and [explicit preview URL controls](https://developers.cloudflare.com/changelog/post/2025-09-17-update-preview-url-setting/). +Runtime tests must use the deployed Worker entry and real Durable Object storage, +not only a JavaScript storage double. Offline success does not establish private +network reachability, actual NixOS sandbox compatibility, caller connector support, +or production revocation propagation. + +## Fixed interface and limits + +| Operation | Arguments | Result data | +| --- | --- | --- | +| `fleet.queue.list` | `{limit: 1..20, status?: enum}` | At most `limit` task IDs/statuses, `complete:false`, `total:null`, `fetchedAt` | +| `fleet.queue.health` | `{}` | Eight numeric status counters and `fetchedAt` | +| `laptop.health` | `{}` | `queueBroker: "up"` or `"down"`; liveness only, not Turso readiness | +| `laptop.diagnostics` | `{}` | `uptimeSeconds`, `load1`, `memoryFreeBytes` (OS free memory, not Linux MemAvailable) | + +Status enum: `queued`, `claimed`, `parked`, `handed_off`, `blocked`, `done`, +`cancelled`, `failed`. Extra fields are rejected. Unavailable/invalid/timed-out +local sources return a fixed error enum; raw exception text never crosses the +bridge. Both the device and control plane validate results. Queue source age is +checked at execution, completion and retrieval; a stale successful result cannot +be read as current. An unknown queue total is deliberately not fabricated from +counters collected in a separate query. + +The signed POST routes are `/v1/call`, `/v1/poll`, `/v1/result`, `/v1/read`. +There is no administrative, enrollment or proxy route. The public-key registry +is deployment configuration, not writable by a caller/device. Each principal +has `id`, `role`, `device`, `publicKey` (raw Ed25519 base64url), `scopes`, +`issuedAt`, `expiresAt` (milliseconds), and `revoked`; the registry also has a +unique `audience`. A registry with shared keys, unsupported fields or enrollment +longer than one hour fails closed. The default configuration contains no registry +and `ENABLED=false`. + +Request freshness is 30 seconds; bodies are capped at 8 KiB with a three-second +read deadline. There are at most eight retained RPCs, 256 live nonces, 60 +accepted-signature requests per principal per minute, and 64 recent audit rows. +Requests expire after 60 seconds, leases after at most 15 seconds, and retained +RPC state after 120 seconds. Alarms purge expired storage; failed storage never +falls back to memory. Reconnect can repeat only an allowed read and receives a +new lease; the previous lease cannot commit. All accepted-signature attempts, +including replay and invalid arguments, consume quota. Unknown/invalid signatures +produce constant denial log records; they cannot create identity-specific state. + +Audit stores only timestamp, validated principal/role, fixed route and status. +It stores no bodies, results, paths, private keys or exception messages. Denial +console records contain fixed event/status/code fields. Cloudflare log retention, +ingress rate limits, deployment access and spending ceilings must be set during +the approved infrastructure review; application quotas do not prevent an +unauthenticated flood from incurring ingress/runtime costs. The authority boundary +assumes trusted reviewed Worker code, trusted non-root local account, and an +independently secured private ingress. A malicious same-UID process is outside +this boundary; the service example's read-only home is not full filesystem secrecy. + +## Offline verification + +Requires Node 24+. From this directory: + +```sh +npm ci +npm test +node --test ../aggregator/test/bridge-snapshot.test.ts +``` + +`runtime.test.mjs` executes the actual Worker with Miniflare/workerd and SQLite +Durable Object storage, including persistence across restart. Outbound network +access from that Worker is rejected by the harness. Keys exist only in memory; +local temporary database fixtures are removed after tests. The unit/property and +state-machine tests complement this runtime evidence. No test deploys a Worker, +connects to AMD, reads live credentials or installs a service. + +No CI workflow or schedule is added. The repository disables automatic PR CI; +this PR must not imply absent checks passed. Full aggregator/Bun verification and +NixOS service sandbox validation remain separate from the focused snapshot tests. + +## Caller integration checkpoint + +`caller.mjs` exports `createCaller({origin, audience, principal, device, privateKey})`. +An approved caller supplies its own Ed25519 CryptoKey and fixed HTTPS origin; the +SDK does not load files, discover credentials, enroll identities, or install an +Aster connector. Its four methods return accepted handles. `read(handle)` checks +once; `wait(handle)` polls for at most the request lifetime. A failed read retains +the handle for explicit resumption. An uncertain submit is never retried +automatically because its acknowledgement may have been lost after acceptance. + +```js +const handle = await fleet.fleetQueueList({ limit: 10, status: 'blocked' }); +const observation = await fleet.wait(handle); +``` + +The device CLI accepts only `--config ABSOLUTE_PATH` or `--help`. The approved +configuration must be an owner-only regular file containing exactly `origin`, +`audience`, `principal`, and an externally provisioned Ed25519 private JWK +(`kty`, `crv`, `x`, `d`). No example contains key material. The CLI refuses root, +follows no redirects, stops on authorization denial, and reconnects with bounded +backoff after transport failure. The supplied service file is a review template +with placeholder executable paths and no installation target. + +Queue freshness is demand-driven: publication follows the aggregator's existing +`source.queue()` refresh, currently used by its service view. Enabling publication +alone does not guarantee a periodic fresh snapshot. Verify the actual refresh +cadence during the pilot; if the source is idle, the bridge correctly becomes +unavailable after five minutes. Adding a scheduled refresh would be a separate +reviewed change with the Fleet schedule registry updated in the same pass. diff --git a/pm-stack/private-laptop-bridge/VERIFICATION.md b/pm-stack/private-laptop-bridge/VERIFICATION.md new file mode 100644 index 0000000000..515e6ea7ef --- /dev/null +++ b/pm-stack/private-laptop-bridge/VERIFICATION.md @@ -0,0 +1,52 @@ +# Offline verification checkpoint — 2026-11-22 + +Implementation based on developing-today/code `ad4e69670`, refreshed by merge to +`7bfcaff23` before review. Executed as non-root UID 1000 in an isolated cloud +worktree, not on Drew's laptop. Node v24.19.0; Miniflare 4.20260730.0; +compatibility date 2026-07-30; SQLite Durable Object storage. + +| Check | Result | +| --- | --- | +| Clean `npm ci` using checked-in lockfile | Passed | +| `npm test` from `pm-stack/private-laptop-bridge` | 39 passed, 0 failed (~33 s) | +| Control plane | 12 passing tests | +| Laptop client/adapters | 15 passing tests | +| Model-based authorization | 1 passing test, 50 seeds × 40 transitions | +| Real workerd acceptance + caller SDK | 11 passing tests | +| `node --test pm-stack/aggregator/test/bridge-snapshot.test.ts` | 7 passed, 0 failed | +| `git diff --check` | Passed | + +The generated model achieved 150 accepted calls, 62 leases, 16 completions, +59 invalid/stale-lease denials, 72 replay denials, 4 completed reads and +231 non-owner read denials. The coverage assertions prevent vacuous success. + +Real-runtime evidence includes all four named operations through the actual +producer, fixed-file adapter, client, Worker, SQLite object and caller SDK. A +synthetic Unix socket server stands in for the queue broker liveness endpoint; +its assertions permit only GET /healthz with no broker token. Synthetic keypairs +exist only in memory. Temporary snapshots/databases are removed after tests; +Worker outbound I/O is explicitly rejected by the harness. Restart tests use the +same temporary persistent SQLite store and reject an already accepted nonce. +The disconnect test waits for the actual 15-second lease boundary, obtains a +new lease, refuses the stale completion and accepts the new completion. + +Review found and fixed an inherited-object identity-name edge case, explicit +lease deadline/ack validation, queue freshness at completion/retrieval, and audit +retention/alarm scheduling. The final independent security review found no +blocking issue within this offline scope. This is engineering test evidence, +not a security certification. + +## Not verified / not performed + +* No Cloudflare deployment, routing, public management endpoint or identity + enrollment; no live key or secret creation/transfer. +* No AMD connection, NixOS service installation/network/security change, or + Desktop Commander/native Codex modification. +* No actual Aster connector call, private ingress validation, live queue parity, + observed workflow inventory, production revocation propagation or cutover. +* No full aggregator Bun suite/typecheck or real systemd sandbox validation. +* No automatic PR CI claim. Current repo policy disables it; focused local + offline execution was explicitly requested for this task. + +Follow the README's rollout/rollback gates. Keep the PR a draft and keep the +fallback until owner-approved end-to-end laptop acceptance is complete. diff --git a/pm-stack/private-laptop-bridge/caller.mjs b/pm-stack/private-laptop-bridge/caller.mjs new file mode 100644 index 0000000000..bfe22c5ad5 --- /dev/null +++ b/pm-stack/private-laptop-bridge/caller.mjs @@ -0,0 +1,143 @@ +// Caller SDK: four named reads, an explicit accepted handle, and bounded polling. +// Keys are supplied by an approved caller integration; no enrollment or files. +import { exact, identifier, validateOperation, validateResult, signRequest } from './protocol.mjs'; + +export class CallerError extends Error { + constructor(code, handle) { + super(code); + this.name = 'CallerError'; + this.code = code; + // A caller can resume an uncertain read with its original accepted handle. + // Never attach raw responses, credentials or transport errors. + if (handle) this.handle = handle; + } +} + +function validHandle(handle) { + return exact(handle, ['id', 'operation', 'expiresAt', 'args']) && identifier(handle.id) + && validateOperation(handle.operation, handle.args) && Number.isSafeInteger(handle.expiresAt); +} + +export function createCaller({ origin, audience, principal, device, privateKey, fetch: fetchFn = globalThis.fetch, + now = Date.now, requestTimeoutMs = 3000 }) { + let url; + try { url = new URL(origin); } catch { throw new CallerError('invalid-config'); } + if (url.protocol !== 'https:' || url.origin !== origin || url.username || url.password + || !identifier(audience) || !identifier(principal) || !identifier(device) + || !privateKey || privateKey.type !== 'private' || privateKey.algorithm?.name !== 'Ed25519' + || !Number.isInteger(requestTimeoutMs) || requestTimeoutMs < 1 || requestTimeoutMs > 3000) throw new CallerError('invalid-config'); + + async function transport(path, body, signal) { + const controller = new AbortController(); + let timer, reader, response; + const abort = () => controller.abort(); + if (signal?.aborted) throw new CallerError('cancelled'); + signal?.addEventListener('abort', abort, { once: true }); + const aborted = new Promise((_, reject) => { + controller.signal.addEventListener('abort', () => { + void reader?.cancel().catch(() => {}); + reject(new CallerError(signal?.aborted ? 'cancelled' : 'timeout')); + }, { once: true }); + timer = setTimeout(abort, requestTimeoutMs); + }); + try { + const work = async () => { + controller.signal.throwIfAborted(); + const request = await signRequest({ origin, audience, principal, privateKey, path, body, now: now() }); + controller.signal.throwIfAborted(); + response = await fetchFn(request, { redirect: 'error', signal: controller.signal }); + if (controller.signal.aborted) { void response.body?.cancel().catch(() => {}); controller.signal.throwIfAborted(); } + if (response.redirected || (response.status >= 300 && response.status < 400)) throw new CallerError('invalid-response'); + if ([401, 403, 410].includes(response.status)) throw new CallerError('denied'); + if (response.status === 429) throw new CallerError('quota'); + if (!response.ok) throw new CallerError('unavailable'); + if (!response.body) throw new CallerError('invalid-response'); + reader = response.body.getReader(); + const chunks = []; let size = 0; + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + size += value.byteLength; + if (size > 8192) throw new CallerError('invalid-response'); + chunks.push(value); + } + const bytes = new Uint8Array(size); let offset = 0; + for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; } + const decoded = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); + return { status: response.status, body: decoded }; + }; + return await Promise.race([work(), aborted]); + } catch (error) { + if (error instanceof CallerError) throw error; + throw new CallerError('unavailable'); + } finally { + clearTimeout(timer); + signal?.removeEventListener('abort', abort); + if (reader) { void reader.cancel().catch(() => {}); reader.releaseLock(); } + else { void response?.body?.cancel().catch(() => {}); } + } + } + + async function submit(operation, args, { signal } = {}) { + if (!validateOperation(operation, args)) throw new CallerError('invalid-operation'); + if (signal?.aborted) throw new CallerError('cancelled'); + const requested = structuredClone(args); + let reply; + try { reply = await transport('/v1/call', { device, operation, args: requested }, signal); } + catch (error) { + // Never automatically retry a submit: a lost acknowledgement may already + // have created a read request. Authentication/quota refusals are definite. + if (['denied', 'quota'].includes(error.code)) throw error; + throw new CallerError('submit-outcome-unknown'); + } + if (reply.status !== 202 || !exact(reply.body, ['id', 'expiresAt']) || !identifier(reply.body.id) + || !Number.isSafeInteger(reply.body.expiresAt) || reply.body.expiresAt <= now() + || reply.body.expiresAt > now() + 60000) throw new CallerError('submit-outcome-unknown'); + return Object.freeze({ id: reply.body.id, operation, expiresAt: reply.body.expiresAt, args: Object.freeze(requested) }); + } + + async function read(handle, { signal } = {}) { + if (!validHandle(handle)) throw new CallerError('invalid-handle'); + if (handle.expiresAt <= now()) throw new CallerError('expired', handle); + try { + const reply = await transport('/v1/read', { id: handle.id }, signal); + if (reply.status !== 200) throw new CallerError('invalid-response'); + if (exact(reply.body, ['status']) && reply.body.status === 'pending') return { status: 'pending', handle }; + if (!exact(reply.body, ['status', 'result']) || reply.body.status !== 'complete' + || !validateResult(handle.operation, reply.body.result)) throw new CallerError('invalid-response'); + const r = reply.body.result; + if (r.ok && handle.operation === 'fleet.queue.list' + && (r.data.tasks.length > handle.args.limit || (handle.args.status && r.data.tasks.some(task => task.status !== handle.args.status)))) throw new CallerError('invalid-response'); + if (r.ok && handle.operation.startsWith('fleet.queue.') + && (r.data.fetchedAt > now() || r.data.fetchedAt < now() - 300000)) throw new CallerError('stale-result'); + return { status: 'complete', handle, result: r }; + } catch (error) { + throw new CallerError(error instanceof CallerError ? error.code : 'unavailable', handle); + } + } + + async function wait(handle, { signal } = {}) { + if (!validHandle(handle)) throw new CallerError('invalid-handle'); + // Bound wall-clock time even if an injected clock stalls. Reads may be + // resumed with the handle; no submission happens inside this loop. + const stop = Date.now() + Math.min(60000, Math.max(0, handle.expiresAt - now())); + while (Date.now() < stop) { + const reply = await read(handle, { signal }); + if (reply.status === 'complete') return reply; + await new Promise((resolve, reject) => { + const abort = () => { clearTimeout(timer); signal?.removeEventListener('abort', abort); reject(new CallerError('cancelled', handle)); }; + const timer = setTimeout(() => { signal?.removeEventListener('abort', abort); resolve(); }, Math.min(1000, Math.max(0, stop - Date.now()))); + signal?.addEventListener('abort', abort, { once: true }); + if (signal?.aborted) abort(); + }); + } + throw new CallerError('expired', handle); + } + return Object.freeze({ + fleetQueueList: (args, options) => submit('fleet.queue.list', args, options), + fleetQueueHealth: options => submit('fleet.queue.health', {}, options), + laptopHealth: options => submit('laptop.health', {}, options), + laptopDiagnostics: options => submit('laptop.diagnostics', {}, options), + read, wait, + }); +} diff --git a/pm-stack/private-laptop-bridge/model.test.mjs b/pm-stack/private-laptop-bridge/model.test.mjs new file mode 100644 index 0000000000..bfaa860892 --- /dev/null +++ b/pm-stack/private-laptop-bridge/model.test.mjs @@ -0,0 +1,125 @@ +import {test} from 'node:test'; +import assert from 'node:assert/strict'; +import worker, {PrivateLaptopBridge} from './worker.mjs'; +import {b64url, signRequest} from './protocol.mjs'; + +// Oracle: an independent, deterministic transition model. The generated traces +// never edit implementation state or deadlines. Only Date advances; a reconnect +// reconstructs the object with its unchanged durable storage. Keys stay in RAM. +class Storage { + value; + async transaction(fn) { + let value = structuredClone(this.value); + const result = await fn({get: async () => structuredClone(value), put: async (_, next) => { value = structuredClone(next); }, setAlarm: async () => {}}); + this.value = value; + return result; + } +} +function random(seed) { + return () => { seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0; return seed; }; +} +const good = {ok:true, data:{queueBroker:'up'}}; + +test('model: 50 seeded call/poll/lease/replay/revoke/reconnect traces preserve authorization', async t => { + const start = 1800000000000; + t.mock.timers.enable({apis:['Date'], now:start}); + const keys = {}, definitions = []; + for (const [id, role] of [['alice','caller'], ['bob','caller'], ['laptop','device']]) { + keys[id] = await crypto.subtle.generateKey('Ed25519', true, ['sign','verify']); + definitions.push({id, role, device:'amd', publicKey:b64url(await crypto.subtle.exportKey('raw',keys[id].publicKey)), scopes:['laptop.health'], issuedAt:start-1000, expiresAt:start+3599000, revoked:false}); + } + const coverage={accepted:0,leased:0,completed:0,staleLeaseDenied:0,replayDenied:0,completeRead:0,ownerDenied:0}; + for (let seed=1; seed<=50; seed++) { + let now = start; + t.mock.timers.setTime(now); + const rng=random(seed), store=new Storage(); + const config={audience:'model-test',principals:structuredClone(definitions)}; + const env={ENABLED:'true',BRIDGE_REGISTRY:JSON.stringify(config)}; + let object=new PrivateLaptopBridge({storage:store},env); + env.BRIDGE={idFromName:x=>x,get:()=>({fetch:req=>object.fetch(req)})}; + const revoked={alice:false,bob:false,laptop:false}; + const jobs=new Map(), leases=[], replays=[]; + let nextNonce=0; + const make=(principal,path,body)=>signRequest({origin:'https://bridge.invalid',audience:'model-test',principal,privateKey:keys[principal].privateKey,path,body,now,nonce:`seed-${seed}-${nextNonce++}`}); + const send=async request=>{const response=await worker.fetch(request.clone(),env);return {status:response.status,body:await response.json()};}; + const gc=()=>{for(const [id,j] of jobs)if(j.retainUntil<=now)jobs.delete(id);}; + const live=j=>j && j.expiresAt>now && !revoked.alice; + const check=(got,want,step,action)=>assert.equal(got,want,`seed=${seed} step=${step} action=${action}`); + for(let step=0;step<40;step++) { + const action=rng()%9; + if(action===0) { // The model owns deadline arithmetic, not worker state. + now += [1000,16000,65000][rng()%3]; t.mock.timers.setTime(now); continue; + } + if(action===1) { + const principal=rng()%2?'alice':'laptop'; revoked[principal]=!revoked[principal]; + config.principals.find(p=>p.id===principal).revoked=revoked[principal]; + env.BRIDGE_REGISTRY=JSON.stringify(config); continue; + } + if(action===2) { object=new PrivateLaptopBridge({storage:store},env); continue; } + if(action===3 || jobs.size===0) { + const request=await make('alice','/v1/call',{device:'amd',operation:'laptop.health',args:{}}); + if(!revoked.alice)gc(); + const expected=revoked.alice?401:revoked.laptop?403:jobs.size>=8?429:202; + const got=await send(request);check(got.status,expected,step,'call'); + if(got.status===202) { + coverage.accepted++; + jobs.set(got.body.id,{expiresAt:now+60000,retainUntil:now+120000,lease:null,leaseUntil:0,assignee:null,done:false}); + replays.push({request,at:now}); + } + continue; + } + if(action===4) { + if(!revoked.laptop)gc(); + const eligible=[...jobs.entries()].find(([,j])=>live(j)&&!j.done&&j.leaseUntil<=now); + const got=await send(await make('laptop','/v1/poll',{})); + check(got.status,revoked.laptop?401:200,step,'poll'); + if(got.status===200) { + if(!eligible)assert.equal(got.body.job,null); + else { + coverage.leased++; + const [id,j]=eligible;assert.equal(got.body.job.id,id); + assert.equal(got.body.job.leaseExpiresAt,Math.min(now+15000,j.expiresAt)); + j.lease=got.body.job.lease;j.leaseUntil=Math.min(now+15000,j.expiresAt);j.assignee='laptop'; + leases.push({id,lease:j.lease}); + } + } + continue; + } + if(action===5 && leases.length) { + const old=leases[rng()%leases.length]; + if(!revoked.laptop)gc(); + const j=jobs.get(old.id); + const valid=live(j)&&!j.done&&j.lease===old.lease&&j.leaseUntil>now; + const got=await send(await make('laptop','/v1/result',{...old,result:good})); + check(got.status,revoked.laptop?401:valid?200:409,step,'finish'); + if(got.status===200){j.done=true;coverage.completed++;} + if(got.status===409)coverage.staleLeaseDenied++; + continue; + } + if(action===6 && replays.length) { + const replay=replays[rng()%replays.length]; + const authenticated=!revoked.alice&&now-replay.at<=30000; + if(authenticated)gc(); + const before=jobs.size; + const got=await send(replay.request); + check(got.status,authenticated?409:401,step,'replay'); + if(got.status===409)coverage.replayDenied++; + assert.equal(Object.keys(store.value?.jobs??{}).length,before); + continue; + } + const principal=rng()%2?'alice':'bob'; + if(!revoked[principal])gc(); + const entries=[...jobs.entries()]; + const [id,j]=entries.length?entries[rng()%entries.length]:['missing',null]; + const got=await send(await make(principal,'/v1/read',{id})); + const expected=revoked[principal]?401:!j||principal!=='alice'?404:!live(j)||(j.assignee&&revoked.laptop)?410:200; + check(got.status,expected,step,'read'); + if(got.status===404&&principal==='bob')coverage.ownerDenied++; + if(got.status===200&&j.done)coverage.completeRead++; + if(got.status===200)assert.deepEqual(got.body,j.done?{status:'complete',result:good}:{status:'pending'}); + } + } + // Guard against vacuous seeded traces that happen never to reach a state. + for(const [state,count] of Object.entries(coverage))assert.ok(count>0,`missing generated coverage: ${state}`); + t.diagnostic(JSON.stringify(coverage)); +}); diff --git a/pm-stack/private-laptop-bridge/package-lock.json b/pm-stack/private-laptop-bridge/package-lock.json new file mode 100644 index 0000000000..546d61260f --- /dev/null +++ b/pm-stack/private-laptop-bridge/package-lock.json @@ -0,0 +1,951 @@ +{ + "name": "private-laptop-bridge", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "private-laptop-bridge", + "devDependencies": { + "miniflare": "4.20260730.0" + }, + "engines": { + "node": ">=24" + } + }, + "node_modules/@cloudflare/workerd-darwin-64": { + "version": "1.20260730.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-64/-/workerd-darwin-64-1.20260730.1.tgz", + "integrity": "sha512-+MBHmPaiTe2KajryW0T24rZvWFxb41hD3d8anNzQqHzft6vSEb18+sp0znSwxgij7ApPhSM1+vhkNg4f3YMguA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-darwin-arm64": { + "version": "1.20260730.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-arm64/-/workerd-darwin-arm64-1.20260730.1.tgz", + "integrity": "sha512-SBHKntPkKvNPgaCrTe99xC1CAl8ygJDzlYfK0LbuJ1muKadIw35WnhO0wu894fKBtllsVQdNzDLee+cm0ppLSQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-linux-64": { + "version": "1.20260730.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-64/-/workerd-linux-64-1.20260730.1.tgz", + "integrity": "sha512-ouyPOSMbiKPeSwUJUvxtMcxGAXs2J4aPE4T5ABIYX5ClcQx5j5bbHTmnqOQEY8sAuLTPjH7dY+iB6UI5ISlwwA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-linux-arm64": { + "version": "1.20260730.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-arm64/-/workerd-linux-arm64-1.20260730.1.tgz", + "integrity": "sha512-YQ+Mi78U3TPdgBPtwq+Sm6rJU+Ihl2y0pjYtuuKkdmUbYzL7oLR6Xqq9wljhasnuCFICssDJaqhMep5WizYoEQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-windows-64": { + "version": "1.20260730.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-windows-64/-/workerd-windows-64-1.20260730.1.tgz", + "integrity": "sha512-27fAN+vUECW1oYVc1KOcHYpkL8COM2Uxtxql7TL595kxbjoqS5yckw7NLz7bTf2pALFCZWjqXDjZGJ/xbG4ZKQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cspotcode/source-map-support": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", + "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.9" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@emnapi/runtime": { + "version": "1.11.3", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", + "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@img/colour": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", + "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.2.tgz", + "integrity": "sha512-eEieHsMksAW4IiO5NzauESRl2D2qz3J/kwUxUrSfV06A93eEaRfMpHXyUb1mAqrR7i8U9A0GRqE9pjn6u1Jjpg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.3.1" + } + }, + "node_modules/@img/sharp-darwin-x64": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.2.tgz", + "integrity": "sha512-BaktuGPCeHJMARpodR8jK4uKiZrPAy9WrfQW0sdI37clracq8Bp01AYS3SZgi5FS/y5twa9t4+LIuuxQjqRrWw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.3.1" + } + }, + "node_modules/@img/sharp-freebsd-wasm32": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.2.tgz", + "integrity": "sha512-YoAxdnd8hPUkvLHd3bWY+YA8nw3xM/RyRopYucNsWHVSan8NLVM3X2volsfoRDcXdUJPg6tXahSd7HXPK7lRnw==", + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "dependencies": { + "@img/sharp-wasm32": "0.35.2" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.1.tgz", + "integrity": "sha512-4V/M3roRMTYjiwZY9IOVQOE8OyeCxFAkYmyZDrZl51uOKjibm3oeEJ4WAmLxutAfzFbC9jqUiPs2gbnGflH+7g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.1.tgz", + "integrity": "sha512-c0/DxItpJv2+dGhgycJBBgotdqruGYDvA79drdh0MD1dFpy7JzJ/PlXwi1H4rFf0eTy8tgbI91aHDnZIceY3jQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.1.tgz", + "integrity": "sha512-aGGy9aWzXgHBG7HNyQPWorZthlp7+x6fDRoPAQbGO3ThcttuTyKIx3NuSHb6zb4gBNq6/yNn9f1cy9nFKS/Vmg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.1.tgz", + "integrity": "sha512-JznefmcK9j1JKPz8AkQDh89kjojubyfOasWBPKfzMIhPwsgDy9evpE/naJTXXXmghS1iFwR8u/kTwh/I2/+GCw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-ppc64": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.1.tgz", + "integrity": "sha512-1EkwGNCZk6iWNCMWqrvdJ+r1j0PT1zIz60CNPhYnJlK/zyeWqlsPZIe+ocBVqPF8k/Ssee/NCk+tE9Ryrko6ng==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-riscv64": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.1.tgz", + "integrity": "sha512-Ilays+w2bXdnxzxtQdmXR62u8o8GYa3eL4+Gr+1KiE4xperMZUslRaVPJwwPkzlHEjGfXAfRVAa/7CYCtSqsBw==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.1.tgz", + "integrity": "sha512-VfBwVHQTbRoj4XlpA/KLZ7ltgMpz+4WSejFzQ+GnoImjo1PtEJ59QB2qR1xQEeRPYIkNrPIm2L4cICMvz4C2ew==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.1.tgz", + "integrity": "sha512-+c8ukgwU62DS54nCAjw7keOfHUkmr0B5QHEdcOqRnodF/MNXJbVI8Eopoj4B/0H8Asr65I+A4Amrn7a85/md6A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.1.tgz", + "integrity": "sha512-qlKb/pwbkAi1WMsJrYHk7CuDrd12s27U2QnRhFYUoJNrRCmkosMTttuRFat/DDB3IlDm5qE1TJgZ4JDnHX8Ldw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.1.tgz", + "integrity": "sha512-yO21HwoUVLN8Qa+/SBjQLMYwBWAVJjeGPNe+hc0OUeMeifEtJqu5a1c4HayE1nNpDih9y3/KkoltfkDodmKAlg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-arm": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.2.tgz", + "integrity": "sha512-SE4kzF2mepn6z+6E7L6lsV8FzuLL6IPQdyX8ZiwROAG/G8td+hP/m7FsFPwidtrF19gvajuC9l6TxAVcsA4S7A==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.3.1" + } + }, + "node_modules/@img/sharp-linux-arm64": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.2.tgz", + "integrity": "sha512-af12Pnd0ZGu2HfP8NayB0kk6eC/lrfbQE6HlR4jD+34wdJ1Vw9TF6TMn6ZvffT+WgqVsl0hRbmNvz2u/23VmwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.3.1" + } + }, + "node_modules/@img/sharp-linux-ppc64": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.2.tgz", + "integrity": "sha512-hYSBm7zcNtDCozCxQHYZJiu63b/bXsgRZuOxCIBZsStMM9Vap47iFHdbX4kCvQsblPB/k+clhELpdQJHQLSHvg==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-ppc64": "1.3.1" + } + }, + "node_modules/@img/sharp-linux-riscv64": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.2.tgz", + "integrity": "sha512-qQt0Kc13+Hoan/Awq/qMSQw3L+RI1NCRPgD5cUJ/1WSSmIoysLOc72jlRM3E0OHN9Yr313jgeQ2T+zW+F03QFA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-riscv64": "1.3.1" + } + }, + "node_modules/@img/sharp-linux-s390x": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.2.tgz", + "integrity": "sha512-E4fLLfRPzDLlEeDaTzI98OFLcv++WL5ChLLMwPoVd0CIoZQqupBSNbOisPL5am9XsbQ9T84+iiMpUvbFtkunbA==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.3.1" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.2.tgz", + "integrity": "sha512-gi0zFJJRLswfCZmHtJdikXPOc5u7qamSOS3NHedLqLd4W8Q0NqjdBr6TTRIgsfFjqfTsHFgdfvJ9LwqSgcHiAA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.3.1" + } + }, + "node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.2.tgz", + "integrity": "sha512-siWbOW1u6HFnFLrp0waKyW7VEf7jYvcDWdrXEFa8AkdAQgEvuu5Fz8/Y70w9EeqAdwDtfU012BhEHHaDqvQNzg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.3.1" + } + }, + "node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.2.tgz", + "integrity": "sha512-YBqMMcjDi4QGYiSn4vNOYBhmlC4z5AXqkOUUqI2e0AFA4urNv4ESgOgwNl3K+4etQhha0twXlzeF20bbULm9Yg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.3.1" + } + }, + "node_modules/@img/sharp-wasm32": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.2.tgz", + "integrity": "sha512-Mrv4JQNYVQ94xH+jzZ9r+gowleN8mv2FTgKT+PI6bx5C0G8TdNYndu161pg2i7uoBwxy2ImPMHrJOM2LZef7Bw==", + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.11.1" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-webcontainers-wasm32": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.2.tgz", + "integrity": "sha512-QNV27pxs9wpApEiCfvHM1RDoP1w1+2KrUWWDPEhEwg+latvOrfuhWrHWZKwdSFwU6jh3myjw/yOCRsUIuOft3g==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@img/sharp-wasm32": "0.35.2" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-arm64": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.2.tgz", + "integrity": "sha512-BiVRYc/t6/Vl3e1hBx0hugG4oN9Pydf4fgMSpxTQJmwGUg/YoXTWHiFeRymHfCZzifxu4F4rpk/I67D0LQ20wQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-ia32": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.2.tgz", + "integrity": "sha512-YYEhx9PImCC7T0tI8JDMi4DB9LwLCXCU5OWNYEXAxh5Q1ShKkyC6byxzoBJ3gEFDnH2lQckWuDe70G7mB2XJog==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-x64": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.2.tgz", + "integrity": "sha512-imoOyBcoM/iiUr4J6VPpCNjPnjvP/Gks95898yB8YqoGGYmHYbOyCuNv9FMhFgtaiHFGbHW8bxKqRV6VjtXThQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz", + "integrity": "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", + "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.0.3", + "@jridgewell/sourcemap-codec": "^1.4.10" + } + }, + "node_modules/@poppinss/colors": { + "version": "4.1.6", + "resolved": "https://registry.npmjs.org/@poppinss/colors/-/colors-4.1.6.tgz", + "integrity": "sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg==", + "dev": true, + "license": "MIT", + "dependencies": { + "kleur": "^4.1.5" + } + }, + "node_modules/@poppinss/dumper": { + "version": "0.6.5", + "resolved": "https://registry.npmjs.org/@poppinss/dumper/-/dumper-0.6.5.tgz", + "integrity": "sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@poppinss/colors": "^4.1.5", + "@sindresorhus/is": "^7.0.2", + "supports-color": "^10.0.0" + } + }, + "node_modules/@poppinss/exception": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@poppinss/exception/-/exception-1.2.3.tgz", + "integrity": "sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@sindresorhus/is": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-7.2.0.tgz", + "integrity": "sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sindresorhus/is?sponsor=1" + } + }, + "node_modules/@speed-highlight/core": { + "version": "1.2.24", + "resolved": "https://registry.npmjs.org/@speed-highlight/core/-/core-1.2.24.tgz", + "integrity": "sha512-qeW2e1l78afw8VhRPfPQ1Gjj+KU5XFQ/OFV5ti6eTa9bruO7mJyZtA4vw0ofqmA3tKCkROE9xLk3VZoeRc98nw==", + "dev": true, + "license": "CC0-1.0" + }, + "node_modules/cookie": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz", + "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/error-stack-parser-es": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/error-stack-parser-es/-/error-stack-parser-es-1.0.5.tgz", + "integrity": "sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/kleur": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz", + "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/miniflare": { + "version": "4.20260730.0", + "resolved": "https://registry.npmjs.org/miniflare/-/miniflare-4.20260730.0.tgz", + "integrity": "sha512-1Z9SB9r/o//80UA02Re3QhtcecSHAyAjf5EcKBfQVlQrCg7Miy79hl2PvtkwFLIaJ5rcrOPdDcRr577okwZPsg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspotcode/source-map-support": "0.8.1", + "sharp": "0.35.2", + "undici": "7.28.0", + "workerd": "1.20260730.1", + "ws": "8.21.0", + "youch": "4.1.0-beta.10" + }, + "bin": { + "miniflare": "bootstrap.js" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/semver": { + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/sharp": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.2.tgz", + "integrity": "sha512-FVtFjtBCMiJS6yb5CX7Sop45WFMpeGw6oRKuJnXYgf/f1ms/D7LE/ZUSNxnW7rZ/dbslQWYkoqFHGPaDBtaK4w==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@img/colour": "^1.1.0", + "detect-libc": "^2.1.2", + "semver": "^7.8.4" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.35.2", + "@img/sharp-darwin-x64": "0.35.2", + "@img/sharp-freebsd-wasm32": "0.35.2", + "@img/sharp-libvips-darwin-arm64": "1.3.1", + "@img/sharp-libvips-darwin-x64": "1.3.1", + "@img/sharp-libvips-linux-arm": "1.3.1", + "@img/sharp-libvips-linux-arm64": "1.3.1", + "@img/sharp-libvips-linux-ppc64": "1.3.1", + "@img/sharp-libvips-linux-riscv64": "1.3.1", + "@img/sharp-libvips-linux-s390x": "1.3.1", + "@img/sharp-libvips-linux-x64": "1.3.1", + "@img/sharp-libvips-linuxmusl-arm64": "1.3.1", + "@img/sharp-libvips-linuxmusl-x64": "1.3.1", + "@img/sharp-linux-arm": "0.35.2", + "@img/sharp-linux-arm64": "0.35.2", + "@img/sharp-linux-ppc64": "0.35.2", + "@img/sharp-linux-riscv64": "0.35.2", + "@img/sharp-linux-s390x": "0.35.2", + "@img/sharp-linux-x64": "0.35.2", + "@img/sharp-linuxmusl-arm64": "0.35.2", + "@img/sharp-linuxmusl-x64": "0.35.2", + "@img/sharp-webcontainers-wasm32": "0.35.2", + "@img/sharp-win32-arm64": "0.35.2", + "@img/sharp-win32-ia32": "0.35.2", + "@img/sharp-win32-x64": "0.35.2" + } + }, + "node_modules/supports-color": { + "version": "10.2.2", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-10.2.2.tgz", + "integrity": "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/tslib": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", + "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", + "dev": true, + "license": "0BSD", + "optional": true + }, + "node_modules/undici": { + "version": "7.28.0", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.28.0.tgz", + "integrity": "sha512-cRZYrTDwWznlnRiPjggAGxZXanty6M8RV1ff8Wm4LWXBp7/IG8v5DnOm74DtUBp9OONpK75YlPnIjQqX0dBDtA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.18.1" + } + }, + "node_modules/workerd": { + "version": "1.20260730.1", + "resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20260730.1.tgz", + "integrity": "sha512-zmfNIjwYSWFY5chGBOjWtH3xAE7p97FTC6vR4Ep98290ho6AeAR/NVcBD274YCLEUYzqm8yxdtZlxMybU8a3jA==", + "dev": true, + "hasInstallScript": true, + "license": "Apache-2.0", + "bin": { + "workerd": "bin/workerd" + }, + "engines": { + "node": ">=16" + }, + "optionalDependencies": { + "@cloudflare/workerd-darwin-64": "1.20260730.1", + "@cloudflare/workerd-darwin-arm64": "1.20260730.1", + "@cloudflare/workerd-linux-64": "1.20260730.1", + "@cloudflare/workerd-linux-arm64": "1.20260730.1", + "@cloudflare/workerd-windows-64": "1.20260730.1" + } + }, + "node_modules/ws": { + "version": "8.21.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz", + "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/youch": { + "version": "4.1.0-beta.10", + "resolved": "https://registry.npmjs.org/youch/-/youch-4.1.0-beta.10.tgz", + "integrity": "sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@poppinss/colors": "^4.1.5", + "@poppinss/dumper": "^0.6.4", + "@speed-highlight/core": "^1.2.7", + "cookie": "^1.0.2", + "youch-core": "^0.3.3" + } + }, + "node_modules/youch-core": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/youch-core/-/youch-core-0.3.3.tgz", + "integrity": "sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@poppinss/exception": "^1.2.2", + "error-stack-parser-es": "^1.0.5" + } + } + } +} diff --git a/pm-stack/private-laptop-bridge/package.json b/pm-stack/private-laptop-bridge/package.json index fde248f40f..2aff715e93 100644 --- a/pm-stack/private-laptop-bridge/package.json +++ b/pm-stack/private-laptop-bridge/package.json @@ -2,6 +2,13 @@ "name": "private-laptop-bridge", "private": true, "type": "module", - "scripts": {"test": "node --test *.test.mjs"}, - "engines": {"node": ">=24"} + "scripts": { + "test": "node --test *.test.mjs" + }, + "engines": { + "node": ">=24" + }, + "devDependencies": { + "miniflare": "4.20260730.0" + } } diff --git a/pm-stack/private-laptop-bridge/runtime.test.mjs b/pm-stack/private-laptop-bridge/runtime.test.mjs new file mode 100644 index 0000000000..1819343ed1 --- /dev/null +++ b/pm-stack/private-laptop-bridge/runtime.test.mjs @@ -0,0 +1,271 @@ +// Real workerd + SQLite Durable Object acceptance tests. No deployment, external +// requests or persistent private keys. Oracle: protocol outcomes and persistent +// replay/lease invariants, exercised through the exported Worker entry point. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtemp, mkdir, readFile, rm } from 'node:fs/promises'; +import { createServer } from 'node:http'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { setTimeout as delay } from 'node:timers/promises'; +import { Miniflare } from 'miniflare'; + +const here = dirname(fileURLToPath(import.meta.url)); +const source = here; +const clientSource = here; +const { signRequest, b64url, operations } = await import(pathToFileURL(join(source, 'protocol.mjs'))); +const origin = 'https://private-bridge.invalid'; +const audience = 'offline-acceptance'; +const result = { ok: true, data: { queueBroker: 'up' } }; + +async function harness(t) { + const dir = await mkdtemp(join(tmpdir(), 'private-bridge-runtime-')); + const keys = {}; + const principals = []; + const now = Date.now(); + for (const [id, role, device] of [['caller','caller','amd'], ['other','caller','amd'], ['device','device','amd'], ['wrong-device','device','other']]) { + keys[id] = await crypto.subtle.generateKey('Ed25519', true, ['sign','verify']); + principals.push({ id, role, device, publicKey: b64url(await crypto.subtle.exportKey('raw', keys[id].publicKey)), scopes: [...operations], issuedAt: now - 1000, expiresAt: now + 120000, revoked: false }); + } + const registry = { audience, principals }; + let mf; + const options = () => ({ + name: 'private-laptop-bridge-offline', + host: '127.0.0.1', + modules: true, + scriptPath: join(source, 'worker.mjs'), + modulesRules: [{ type: 'ESModule', include: ['**/*.mjs'] }], + compatibilityDate: '2026-07-30', + bindings: { ENABLED: 'true', BRIDGE_REGISTRY: JSON.stringify(registry) }, + durableObjects: { BRIDGE: { className: 'PrivateLaptopBridge', useSQLite: true } }, + durableObjectsPersist: dir, + // All calls enter through dispatchFetch; the actual application has no + // upstream fetch. Block external I/O if future code accidentally adds one. + outboundService: () => new Response('external I/O forbidden in offline test', { status: 599 }), + }); + async function start() { mf = new Miniflare(options()); await mf.ready; } + await start(); + t.after(async () => { await mf?.dispose(); await rm(dir, { recursive: true, force: true }); }); + async function dispatch(request, init = {}) { + return mf.dispatchFetch(request.url, { method: request.method, headers: Object.fromEntries(request.headers), body: await request.text(), ...init }); + } + async function signed(id, path, body, overrides = {}) { + return signRequest({ origin, audience, principal: id, privateKey: keys[id].privateKey, path, body, ...overrides }); + } + async function send(id, path, body, overrides = {}) { + const res = await dispatch(await signed(id, path, body, overrides)); + return { status: res.status, body: await res.json() }; + } + async function submit(id = 'caller', operation = 'laptop.health', args = {}) { + const reply = await send(id, '/v1/call', { device: 'amd', operation, args }); + assert.equal(reply.status, 202, JSON.stringify(reply)); + return reply.body; + } + return { + keys, registry, signed, dispatch, send, submit, + async restart() { await mf.dispose(); await start(); }, + async reconfigure() { await mf.setOptions(options()); await mf.ready; }, + }; +} + +test('workerd: caller -> device -> result read, with ownership and strict output rejection', async t => { + const h = await harness(t); + const call = await h.submit(); + assert.deepEqual(await h.send('caller', '/v1/read', { id: call.id }), { status: 200, body: { status: 'pending' } }); + assert.equal((await h.send('other', '/v1/read', { id: call.id })).status, 404); + const { body: { job }, status } = await h.send('device', '/v1/poll', {}); + assert.equal(status, 200); + assert.equal(job.id, call.id); + assert.equal(job.operation, 'laptop.health'); + assert.deepEqual(await h.send('wrong-device', '/v1/poll', {}), { status: 200, body: { job: null } }); + assert.equal((await h.send('device', '/v1/result', { id: job.id, lease: job.lease, result: { ok: true, data: { queueBroker: 'up', token: 'must-not-leave-device' } } })).status, 400); + assert.equal((await h.send('device', '/v1/result', { id: job.id, lease: job.lease, result })).status, 200); + assert.deepEqual(await h.send('caller', '/v1/read', { id: call.id }), { status: 200, body: { status: 'complete', result } }); + assert.equal((await h.send('device', '/v1/result', { id: job.id, lease: job.lease, result })).status, 409); +}); + +test('workerd: concurrent replay has one winner and nonce survives runtime restart', async t => { + const h = await harness(t); + const request = await h.signed('caller', '/v1/call', { device: 'amd', operation: 'laptop.health', args: {} }); + const replay = request.clone(); + const restartReplay = request.clone(); + const replies = await Promise.all([h.dispatch(request), h.dispatch(replay)]); + assert.deepEqual(replies.map(r => r.status).sort(), [202, 409]); + await h.restart(); + assert.equal((await h.dispatch(restartReplay)).status, 409); + const { body: { job } } = await h.send('device', '/v1/poll', {}); + assert.ok(job, 'the accepted RPC also survives runtime restart'); + assert.deepEqual((await h.send('device', '/v1/poll', {})).body, { job: null }); +}); + +test('workerd: signature binds role, audience, bytes and freshness; unsupported operations denied', async t => { + const h = await harness(t); + assert.equal((await h.send('device', '/v1/call', { device: 'amd', operation: 'laptop.health', args: {} })).status, 403); + assert.equal((await h.send('caller', '/v1/poll', {})).status, 403); + assert.equal((await h.send('caller', '/v1/read', { id: 'missing' }, { audience: 'another-audience' })).status, 401); + assert.equal((await h.send('caller', '/v1/read', { id: 'missing' }, { now: Date.now() - 31000 })).status, 401); + const valid = await h.signed('caller', '/v1/call', { device: 'amd', operation: 'laptop.health', args: {} }); + assert.equal((await h.dispatch(valid, { body: '{"device":"amd","operation":"shell","args":{}}' })).status, 401); + for (const [operation, args] of [['shell', {}], ['laptop.health', { url: 'http://127.0.0.1/secrets' }], ['fleet.queue.list', { limit: 21 }], ['fleet.queue.list', { limit: 1, query: 'arbitrary SQL' }]]) { + assert.equal((await h.send('caller', '/v1/call', { device: 'amd', operation, args })).status, 400); + } + assert.equal((await h.send('caller', '/v1/call', { device: 'other', operation: 'laptop.health', args: {} })).status, 403); +}); + +test('workerd: caller and device revocation deny delivery and completed result disclosure', async t => { + const h = await harness(t); + const pending = await h.submit(); + h.registry.principals.find(p => p.id === 'caller').revoked = true; + await h.reconfigure(); + assert.equal((await h.send('caller', '/v1/read', { id: pending.id })).status, 401); + assert.deepEqual((await h.send('device', '/v1/poll', {})).body, { job: null }); + h.registry.principals.find(p => p.id === 'caller').revoked = false; + await h.reconfigure(); + const { body: { job } } = await h.send('device', '/v1/poll', {}); + assert.equal(job.id, pending.id); + assert.equal((await h.send('device', '/v1/result', { id: job.id, lease: job.lease, result })).status, 200); + h.registry.principals.find(p => p.id === 'device').revoked = true; + await h.reconfigure(); + assert.equal((await h.send('device', '/v1/poll', {})).status, 401); + assert.equal((await h.send('device', '/v1/result', { id: job.id, lease: job.lease, result })).status, 401); + assert.equal((await h.send('caller', '/v1/read', { id: job.id })).status, 410); + assert.equal((await h.send('caller', '/v1/call', { device: 'amd', operation: 'laptop.health', args: {} })).status, 403); +}); + +test('workerd: registry expiration and scope removal fail closed on stored requests', async t => { + const h = await harness(t); + const pending = await h.submit(); + h.registry.principals.find(p => p.id === 'caller').scopes = ['laptop.diagnostics']; + await h.reconfigure(); + assert.equal((await h.send('caller', '/v1/read', { id: pending.id })).status, 410); + assert.deepEqual((await h.send('device', '/v1/poll', {})).body, { job: null }); + const p = h.registry.principals.find(p => p.id === 'caller'); + p.issuedAt = Date.now() - 10000; + p.expiresAt = Date.now() - 1000; + await h.reconfigure(); + assert.equal((await h.send('caller', '/v1/read', { id: pending.id })).status, 401); +}); + +test('workerd: signed quotas, bounded bodies and finite RPC capacity', async t => { + const h = await harness(t); + const oversized = await h.send('caller', '/v1/read', { id: 'x'.repeat(9000) }); + assert.equal(oversized.status, 413); + for (let i = 0; i < 60; i++) assert.equal((await h.send('other', '/v1/read', { id: 'missing' })).status, 404); + assert.equal((await h.send('other', '/v1/read', { id: 'missing' })).status, 429); + for (let i = 0; i < 8; i++) await h.submit(); + assert.equal((await h.send('caller', '/v1/call', { device: 'amd', operation: 'laptop.health', args: {} })).status, 429); +}); + +test('workerd: lost poll reconnect redelivers read after lease expiry and fences old completion', async t => { + const h = await harness(t); + const pending = await h.submit(); + const first = (await h.send('device', '/v1/poll', {})).body.job; + assert.equal(first.id, pending.id); + await h.restart(); + assert.deepEqual((await h.send('device', '/v1/poll', {})).body, { job: null }); + // This intentionally waits on the actual workerd clock, not a mocked timer. + await delay(15250); + const second = (await h.send('device', '/v1/poll', {})).body.job; + assert.equal(second.id, first.id); + assert.notEqual(second.lease, first.lease); + assert.equal((await h.send('device', '/v1/result', { id: first.id, lease: first.lease, result })).status, 409); + assert.equal((await h.send('device', '/v1/result', { id: second.id, lease: second.lease, result })).status, 200); + assert.deepEqual((await h.send('caller', '/v1/read', { id: pending.id })).body, { status: 'complete', result }); +}); + +test('workerd: actual non-root laptop client completes each named read through Worker', async t => { + const { createClient } = await import(pathToFileURL(join(clientSource, 'client.mjs'))); + const { createCaller } = await import('./caller.mjs'); + const h = await harness(t); + const { createAdapters, readQueueSnapshot, queueBrokerAlive } = await import('./adapters.mjs'); + const { publishBridgeQueueSnapshot } = await import('../aggregator/src/bridge-snapshot.ts'); + const home = await mkdtemp(join(tmpdir(), 'private-bridge-source-')); + const fetchedAt = Date.now(); + const counts = { queued: 1, claimed: 0, parked: 0, handedOff: 0, blocked: 0, done: 0, cancelled: 0, failed: 0 }; + await publishBridgeQueueSnapshot({ fetchedAt, available: true, stale: false, errors: ['must-not-export'], + queues: [counts], tasks: [{ id: 42, status: 'queued', priority: 1, title: 'must-not-export', payload: { token: 'must-not-export' } }], + }, '1', home, fetchedAt); + assert.equal((await readFile(join(home, '.local/state/pm-aggregator/bridge-queue.json'), 'utf8')).includes('must-not-export'), false); + await mkdir(join(home, '.config/queue-broker'), { recursive: true, mode: 0o700 }); + let healthRequests = 0; + const broker = createServer((request, response) => { + healthRequests++; + assert.equal(request.method, 'GET'); assert.equal(request.url, '/healthz'); + assert.equal(request.headers['x-agent-token'], undefined); + response.end('{"ok":true}'); + }); + await new Promise(resolve => broker.listen(join(home, '.config/queue-broker/broker.sock'), resolve)); + t.after(async () => { await new Promise(resolve => broker.close(resolve)); await rm(home, { recursive: true, force: true }); }); + const samples = { + 'fleet.queue.list': { ok: true, data: { tasks: [{ id: 42, status: 'queued' }], complete: false, total: null, fetchedAt } }, + 'fleet.queue.health': { ok: true, data: { queued: 1, claimed: 0, parked: 0, handed_off: 0, blocked: 0, done: 0, cancelled: 0, failed: 0, fetchedAt } }, + 'laptop.health': result, + 'laptop.diagnostics': { ok: true, data: { uptimeSeconds: 123, load1: 0.25, memoryFreeBytes: 1024 } }, + }; + const seen = []; + const adapters = createAdapters({ readSnapshot: () => readQueueSnapshot(home), probe: () => queueBrokerAlive(home), diagnostics: () => samples['laptop.diagnostics'].data }); + const client = createClient({ origin, audience, principal: 'device', privateKey: h.keys.device.privateKey, getuid: () => 1000, + fetch: async (request, init) => { assert.equal(init.redirect, 'error'); return h.dispatch(request); }, + execute: async (operation, args) => { seen.push({ operation, args }); return adapters(operation, args); }, + }); + const caller = createCaller({ origin, audience, principal: 'caller', device: 'amd', privateKey: h.keys.caller.privateKey, fetch: request => h.dispatch(request) }); + const methods = { 'fleet.queue.list': 'fleetQueueList', 'fleet.queue.health': 'fleetQueueHealth', 'laptop.health': 'laptopHealth', 'laptop.diagnostics': 'laptopDiagnostics' }; + for (const operation of operations) { + const args = operation === 'fleet.queue.list' ? { limit: 1, status: 'queued' } : {}; + const call = operation === 'fleet.queue.list' ? await caller[methods[operation]](args) : await caller[methods[operation]](); + assert.equal(await client.step(), true); + assert.deepEqual(await caller.wait(call), { status: 'complete', handle: call, result: samples[operation] }); + } + assert.deepEqual(seen.map(x => x.operation), operations); + assert.equal(await client.step(), false); + assert.equal(healthRequests, 1); +}); + +test('caller SDK: validates before I/O and never retries uncertain submissions', async () => { + const { createCaller, CallerError } = await import('./caller.mjs'); + const keys = await crypto.subtle.generateKey('Ed25519', true, ['sign','verify']); + const base = { origin, audience, principal: 'caller', device: 'amd', privateKey: keys.privateKey }; + assert.throws(() => createCaller({ ...base, origin: 'http://localhost' }), /invalid-config/); + let calls = 0; + const caller = createCaller({ ...base, fetch: async () => { calls++; throw new Error('secret-bearing transport detail'); } }); + await assert.rejects(caller.fleetQueueList({ limit: 1, command: 'anything' }), { code: 'invalid-operation' }); + assert.equal(calls, 0); + await assert.rejects(caller.laptopHealth(), error => error instanceof CallerError && error.code === 'submit-outcome-unknown' && !error.message.includes('secret')); + assert.equal(calls, 1); + await assert.rejects(caller.laptopHealth({ signal: AbortSignal.abort() }), { code: 'cancelled' }); + assert.equal(calls, 1); +}); + +test('caller SDK: uncertain reads preserve accepted handle and malformed results are refused', async () => { + const { createCaller } = await import('./caller.mjs'); + const keys = await crypto.subtle.generateKey('Ed25519', true, ['sign','verify']); + const handle = { id: 'test-id', operation: 'laptop.health', expiresAt: Date.now() + 60000, args: {} }; + let mode = 'failed'; + const caller = createCaller({ origin, audience, principal: 'caller', device: 'amd', privateKey: keys.privateKey, + fetch: async () => { + if (mode === 'failed') throw new Error('private stack trace'); + if (mode === 'extra') return Response.json({ status: 'complete', result: { ok: true, data: { queueBroker: 'up', raw: 'forbidden' } } }); + if (mode === 'oversize') return new Response('x'.repeat(9000)); + if (mode === 'redirect') return new Response('', { status: 302, headers: { location: 'https://elsewhere.invalid' } }); + return Response.json({ status: 'complete', result }); + }, + }); + await assert.rejects(caller.read(handle), error => error.code === 'unavailable' && error.handle === handle); + for (mode of ['extra','oversize','redirect']) await assert.rejects(caller.read(handle), error => error.code === 'invalid-response' && error.handle === handle); + mode = 'good'; + assert.deepEqual(await caller.read(handle), { status: 'complete', handle, result }); +}); + +test('caller SDK: transport and streamed response deadlines are bounded', async () => { + const { createCaller } = await import('./caller.mjs'); + const keys = await crypto.subtle.generateKey('Ed25519', true, ['sign','verify']); + const base = { origin, audience, principal: 'caller', device: 'amd', privateKey: keys.privateKey, requestTimeoutMs: 30 }; + const silent = createCaller({ ...base, fetch: async () => new Promise(() => {}) }); + await assert.rejects(silent.laptopHealth(), { code: 'submit-outcome-unknown' }); + let cancelled = false; + const streaming = createCaller({ ...base, fetch: async () => new Response(new ReadableStream({ cancel() { cancelled = true; } })) }); + const handle = { id: 'test-id', operation: 'laptop.health', expiresAt: Date.now() + 60000, args: {} }; + await assert.rejects(streaming.read(handle), error => error.code === 'timeout' && error.handle === handle); + assert.equal(cancelled, true); +}); From dab58829a6d17498da3cae7e9f9456e85f6f6b64 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 11:59:08 +0000 Subject: [PATCH 06/33] Harden private bridge and prepare bounded Gateway staging rehearsal --- doc/fleet-schedule-registry.md | 3 +- pm-stack/aggregator/src/bridge-refresh.ts | 75 + pm-stack/aggregator/src/bridge-snapshot.ts | 3 +- pm-stack/aggregator/src/queue.ts | 19 +- pm-stack/aggregator/src/sources/live.ts | 11 + .../aggregator/test/bridge-refresh.test.ts | 118 + .../aggregator/test/bridge-snapshot.test.ts | 2 +- pm-stack/private-laptop-bridge/README.md | 56 +- pm-stack/private-laptop-bridge/STAGING.md | 287 ++ .../private-laptop-bridge/VERIFICATION.md | 40 +- pm-stack/private-laptop-bridge/aster.mjs | 99 + pm-stack/private-laptop-bridge/aster.test.mjs | 168 ++ pm-stack/private-laptop-bridge/caller.mjs | 18 +- pm-stack/private-laptop-bridge/client.mjs | 32 +- .../private-laptop-bridge/client.test.mjs | 4 +- .../private-laptop-bridge/freshness.test.mjs | 141 + pm-stack/private-laptop-bridge/gateway.mjs | 52 + .../private-laptop-bridge/gateway.test.mjs | 97 + .../private-laptop-bridge/package-lock.json | 2674 ++++++++++++++--- pm-stack/private-laptop-bridge/package.json | 7 +- .../private-laptop-bridge.service.example | 3 + .../private-laptop-bridge/review.test.mjs | 84 + .../private-laptop-bridge/runtime.test.mjs | 12 +- pm-stack/private-laptop-bridge/worker.mjs | 4 +- .../wrangler.staging.jsonc | 20 + 25 files changed, 3566 insertions(+), 463 deletions(-) create mode 100644 pm-stack/aggregator/src/bridge-refresh.ts create mode 100644 pm-stack/aggregator/test/bridge-refresh.test.ts create mode 100644 pm-stack/private-laptop-bridge/STAGING.md create mode 100644 pm-stack/private-laptop-bridge/aster.mjs create mode 100644 pm-stack/private-laptop-bridge/aster.test.mjs create mode 100644 pm-stack/private-laptop-bridge/freshness.test.mjs create mode 100644 pm-stack/private-laptop-bridge/gateway.mjs create mode 100644 pm-stack/private-laptop-bridge/gateway.test.mjs create mode 100644 pm-stack/private-laptop-bridge/review.test.mjs create mode 100644 pm-stack/private-laptop-bridge/wrangler.staging.jsonc diff --git a/doc/fleet-schedule-registry.md b/doc/fleet-schedule-registry.md index 00aba3ba7d..c01f490eeb 100644 --- a/doc/fleet-schedule-registry.md +++ b/doc/fleet-schedule-registry.md @@ -376,7 +376,7 @@ registered. The primary user's repos are maintained by git's own per-user launchd agents, which `git maintenance start` installs outside Nix; they are not recorded here until a review reads them on the Mac. -## Surface 6 — PM-stack process intervals (4 entries) +## Surface 6 — PM-stack process intervals (5 entries, including one proposed/disabled) Recurring loops owned by PM-stack processes (aggregator, console). These are not external scheduler surfaces; this inventory records timers that run only @@ -388,6 +388,7 @@ while the service is alive. | Console state refresh | developing-today/code | every 5 seconds | live console process only | PR #12452 | `pm-stack/console/src/docs.ts` (`Docs.start`) | not recorded | Reads only while the app was opened in the last 10 minutes; remove if state is no longer served from memory | 2026-11-22 | 2026-11-22 | | Console notifier | developing-today/code | every 60 seconds | live console process only | PR #12452 | `pm-stack/console/src/notify.ts` (`Notifier.start`) | not recorded | Reads only while a device is subscribed; remove if notifications move to another sender | 2026-11-22 | 2026-11-22 | | Console report to the edge | developing-today/code | 5 to 30 seconds | live console process only | PR #12505 | `pm-stack/console/src/sync.ts` (`EdgeLink.start`) | not recorded | Runs only when PM_CONSOLE_EDGE_URL is set; remove if the app is no longer served from the edge | 2026-11-22 | 2026-11-22 | +| Private laptop bridge queue refresh pilot | developing-today/code | immediate, then 65 seconds after completion, for at most one hour | **proposed / disabled; NOT active; no timer installed** | Drew approval required before enablement | `pm-stack/aggregator/src/bridge-refresh.ts` and `sources/live.ts` | at most 57 collector starts; reuses existing queue collector credentials and cache | Requires both literal `PM_AGG_BRIDGE_SNAPSHOT=1` and `PM_AGG_BRIDGE_REFRESH=1`; no overlap; independent one-hour stop even on hung read; cancellation hook; remove both flags after approved pilot so process restart cannot begin another | 2026-11-22 | 2026-11-22 | ## Surface 7 — Cloudflare Worker cron triggers (2 entries) diff --git a/pm-stack/aggregator/src/bridge-refresh.ts b/pm-stack/aggregator/src/bridge-refresh.ts new file mode 100644 index 0000000000..757fcd4d86 --- /dev/null +++ b/pm-stack/aggregator/src/bridge-refresh.ts @@ -0,0 +1,75 @@ +// Disabled-by-default refresh pilot for the existing queue collector. This +// module owns no credentials, source data, timestamps, files or network client. +export const BRIDGE_REFRESH_INTERVAL_MS = 65_000; +export const BRIDGE_REFRESH_LIFETIME_MS = 3_600_000; +export const BRIDGE_REFRESH_MAX_RUNS = 57; + +interface Timer { unref?(): unknown } +interface Options { + snapshot?: string; + refresh?: string; + signal?: AbortSignal; + now?: () => number; + schedule?: (callback: () => void, milliseconds: number) => Timer; + cancel?: (timer: Timer) => void; +} + +/** Both literal "1" flags are required; undefined/"0" disable. Unknown values + * are refused before a timer or collector starts. A process restart begins a + * new pilot only if both flags remain set: deployment approval must include + * removing them after the one-hour observation window. + */ +export function startBridgeRefresh( + collect: () => Promise, + options: Options = {}, +) { + const { snapshot, refresh, signal } = options; + for (const value of [snapshot, refresh]) { + if (value !== undefined && value !== "0" && value !== "1") throw new Error("invalid bridge refresh flag"); + } + const enabled = snapshot === "1" && refresh === "1"; + const now = options.now ?? (() => performance.now()); + const schedule = options.schedule ?? ((callback, ms) => setTimeout(callback, ms)); + const cancel = options.cancel ?? (timer => clearTimeout(timer as ReturnType)); + let stopped = !enabled || Boolean(signal?.aborted), running = false, runs = 0; + let next: Timer | undefined, deadline: Timer | undefined; + let expiresAt = 0; + + const stop = () => { + stopped = true; + if (next) cancel(next); + if (deadline) cancel(deadline); + next = undefined; deadline = undefined; + signal?.removeEventListener("abort", stop); + }; + const arm = (callback: () => void, ms: number) => { + const timer = schedule(callback, ms); + timer.unref?.(); + return timer; + }; + const tick = async () => { + if (stopped || running) return; + if (now() >= expiresAt || runs >= BRIDGE_REFRESH_MAX_RUNS) { stop(); return; } + running = true; + runs++; + try { await collect(); } + catch { /* Existing collector owns failure publication; no raw error logs. */ } + finally { + running = false; + // The independent deadline fires even when collect never settles. A late + // completion may publish its genuine observation, but cannot rearm us. + if (!stopped && now() < expiresAt && runs < BRIDGE_REFRESH_MAX_RUNS) { + next = arm(() => { next = undefined; void tick(); }, BRIDGE_REFRESH_INTERVAL_MS); + } else stop(); + } + }; + if (!stopped) { + const start = now(); + if (!Number.isFinite(start)) throw new Error("invalid bridge refresh clock"); + expiresAt = start + BRIDGE_REFRESH_LIFETIME_MS; + signal?.addEventListener("abort", stop, { once: true }); + deadline = arm(stop, BRIDGE_REFRESH_LIFETIME_MS); + void tick(); + } + return Object.freeze({ enabled, stop, get stopped() { return stopped; }, get running() { return running; }, get runs() { return runs; } }); +} diff --git a/pm-stack/aggregator/src/bridge-snapshot.ts b/pm-stack/aggregator/src/bridge-snapshot.ts index a7ed2a42ef..9867511437 100644 --- a/pm-stack/aggregator/src/bridge-snapshot.ts +++ b/pm-stack/aggregator/src/bridge-snapshot.ts @@ -30,7 +30,8 @@ export function bridgeQueueSnapshot(source: QueueSnapshot, now = Date.now()): Br version: 1, fetchedAt: now, available: false, stale: true, complete: false, total: null, tasks: [], counts: counts(), }); - if (!source.available || source.stale || !nonnegative(source.fetchedAt) + if (source.bridgeVerified !== true || source.available !== true || source.stale !== false + || !Array.isArray(source.errors) || source.errors.length !== 0 || !nonnegative(source.fetchedAt) || source.fetchedAt > now + 5_000 || now - source.fetchedAt > 300_000 || !Array.isArray(source.tasks) || !Array.isArray(source.queues)) return unavailable(); const result: BridgeQueueSnapshot = { diff --git a/pm-stack/aggregator/src/queue.ts b/pm-stack/aggregator/src/queue.ts index 0c899deef6..cd17b7085d 100644 --- a/pm-stack/aggregator/src/queue.ts +++ b/pm-stack/aggregator/src/queue.ts @@ -111,6 +111,11 @@ export interface QueueTask { } export interface QueueSnapshot { + /** Set only by the raw broker read after checking explicit success, complete + * row containers and all eight counters. Legacy UI projection is permissive + * (missing values become zero); the private bridge must not treat those + * defaults as evidence that the queue was observed idle. */ + bridgeVerified?: boolean; /** When the broker read that produced this snapshot completed * (the source timestamp every payload carries). */ fetchedAt: number; @@ -284,17 +289,29 @@ export async function fetchQueueSnapshot( listLimit = 200, ): Promise { const health = await brokerPost(fetchImpl, brokerUrl, token, "/health", {}); + const states = ["queued", "claimed", "parked", "handed_off", "blocked", "done", "cancelled", "failed"]; + const object = (v: unknown): v is Record => v !== null && typeof v === "object" && !Array.isArray(v); + const count = (n: unknown): n is number => Number.isSafeInteger(n) && (n as number) >= 0; + let bridgeVerified = health.ok === true && Array.isArray(health.rows) + && health.rows.every((row: unknown) => object(row) && typeof row.queue === "string" && row.queue.length > 0 + && states.every(state => count(row[state]))); const healthRows = (Array.isArray(health.rows) ? health.rows : []) as BrokerHealthRow[]; + bridgeVerified &&= new Set(healthRows.map(row => row.queue)).size === healthRows.length; const taskRows: BrokerTaskRow[] = []; for (const row of healthRows) { + if (!object(row)) { bridgeVerified = false; continue; } if (typeof row.queue !== "string" || row.queue === "") continue; const list = await brokerPost(fetchImpl, brokerUrl, token, "/list", { queue: row.queue, rich: true, limit: listLimit, }); + bridgeVerified &&= list.ok === true && Array.isArray(list.rows) + && list.rows.every((task: unknown) => object(task) && count(task.id) && task.id > 0 + && states.includes(task.status as string) + && (task.priority === null || (typeof task.priority === "number" && Number.isFinite(task.priority)))); if (Array.isArray(list.rows)) taskRows.push(...(list.rows as BrokerTaskRow[])); } const fetchedAt = now(); - return projectQueueSnapshot(healthRows, taskRows, fetchedAt, fetchedAt); + return { ...projectQueueSnapshot(healthRows, taskRows, fetchedAt, fetchedAt), bridgeVerified }; } diff --git a/pm-stack/aggregator/src/sources/live.ts b/pm-stack/aggregator/src/sources/live.ts index 4870faa1fc..c51d9e858b 100644 --- a/pm-stack/aggregator/src/sources/live.ts +++ b/pm-stack/aggregator/src/sources/live.ts @@ -8,6 +8,7 @@ import { createHash } from "node:crypto"; import { dirname, join } from "node:path"; import type { Config } from "../config.ts"; import { publishBridgeQueueSnapshot } from "../bridge-snapshot.ts"; +import { startBridgeRefresh } from "../bridge-refresh.ts"; import { applyBoardDonePolicy, isRetiredDoneTableTitle } from "../board-policy.ts"; import { AA_PLAN_FACTS, aaApplyPriceOverlay, isAaSection } from "../aa.ts"; import { aaCacheFileName, aaPricesFingerprint, isAaBatchCacheEntry } from "../aa-batches.ts"; @@ -888,6 +889,8 @@ export function isFeedAttentionEntry(v: unknown): v is SessionFeedEntry { export function liveSource( cfg: Config, opts?: { + /** Optional shutdown hook for the explicitly enabled one-hour queue pilot. */ + bridgeRefreshSignal?: AbortSignal; standingAuto?: () => Promise; onEvent?: (event: NewStreamEvent) => void; hasEvent?: (kind: string, ref: string) => Promise; @@ -1585,6 +1588,14 @@ export function liveSource( } return queueInFlight; } + // Proposed/disabled one-hour pilot. Reuse exactly this collector and its + // single-flight cache; do not add a credential reader or fabricate timestamps. + // 65 seconds after completion exceeds the existing 60-second cache TTL. + startBridgeRefresh(queueSnapshot, { + snapshot: process.env.PM_AGG_BRIDGE_SNAPSHOT, + refresh: process.env.PM_AGG_BRIDGE_REFRESH, + signal: opts?.bridgeRefreshSignal, + }); return { async board() { try { diff --git a/pm-stack/aggregator/test/bridge-refresh.test.ts b/pm-stack/aggregator/test/bridge-refresh.test.ts new file mode 100644 index 0000000000..98db710976 --- /dev/null +++ b/pm-stack/aggregator/test/bridge-refresh.test.ts @@ -0,0 +1,118 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +import { startBridgeRefresh, BRIDGE_REFRESH_INTERVAL_MS, BRIDGE_REFRESH_LIFETIME_MS, BRIDGE_REFRESH_MAX_RUNS } from "../src/bridge-refresh.ts"; + +// Oracle: a deterministic scheduler advances exactly to due deadlines; no real +// timer, socket, credential read, filesystem write or collector is started. +class Clock { + time = 0; + created: { at: number; fn: () => void; active: boolean; unrefs: number; unref(): void }[] = []; + now = () => this.time; + schedule = (fn: () => void, ms: number) => { + const timer = { at: this.time + ms, fn, active: true, unrefs: 0, unref() { this.unrefs++; } }; + this.created.push(timer); return timer; + }; + cancel = (timer: { unref?(): unknown }) => { const entry = this.created.find(item => item === timer); if (entry) entry.active = false; }; + options = () => ({ snapshot: "1", refresh: "1", now: this.now, schedule: this.schedule, cancel: this.cancel }); + async advance(target: number) { + for (;;) { + await Promise.resolve(); await Promise.resolve(); + const next = this.created.filter(t => t.active && t.at <= target).sort((a,b) => a.at-b.at)[0]; + if (!next) break; + this.time = next.at; next.active = false; next.fn(); + } + this.time = target; + await Promise.resolve(); await Promise.resolve(); + } +} + +test("default, partial opt-in and unknown flag values start no work or timers", () => { + const clock = new Clock(); let starts = 0; + for (const flags of [{}, {snapshot:"1"}, {refresh:"1"}, {snapshot:"0",refresh:"1"}, {snapshot:"1",refresh:"0"}]) { + const controller = startBridgeRefresh(async () => { starts++; }, {...clock.options(),snapshot:undefined,refresh:undefined,...flags}); + assert.equal(controller.enabled,false);assert.equal(controller.stopped,true); + } + for (const value of ["", "true", "false", "yes", "01", "1 ", "--enable"]) { + assert.throws(() => startBridgeRefresh(async () => { starts++; }, {...clock.options(),refresh:value}), /invalid.*flag/); + assert.throws(() => startBridgeRefresh(async () => { starts++; }, {...clock.options(),snapshot:value}), /invalid.*flag/); + } + assert.equal(starts,0);assert.equal(clock.created.length,0); +}); + +test("opt-in starts immediately, repeats after 65 seconds, and all timers are unref'd", async () => { + const clock = new Clock(); const starts: number[] = []; + const controller = startBridgeRefresh(async () => { starts.push(clock.now()); }, clock.options()); + assert.deepEqual(starts,[0]); + await clock.advance(64999);assert.deepEqual(starts,[0]); + await clock.advance(65000);assert.deepEqual(starts,[0,65000]); + await clock.advance(130000);assert.deepEqual(starts,[0,65000,130000]); + assert.ok(clock.created.every(timer => timer.unrefs === 1)); + controller.stop();assert.equal(controller.stopped,true); + assert.ok(clock.created.every(timer => !timer.active)); +}); + +test("finite pilot makes at most 57 starts and stops permanently at one hour", async () => { + const clock = new Clock(); let starts=0; + const controller = startBridgeRefresh(async () => { starts++; }, clock.options()); + await clock.advance(BRIDGE_REFRESH_LIFETIME_MS); + assert.equal(controller.stopped,true); + assert.equal(starts,Math.ceil(BRIDGE_REFRESH_LIFETIME_MS / BRIDGE_REFRESH_INTERVAL_MS)); + assert.ok(starts <= BRIDGE_REFRESH_MAX_RUNS); + assert.ok(clock.created.every(timer => !timer.active)); + const ended=starts;await clock.advance(BRIDGE_REFRESH_LIFETIME_MS*10);assert.equal(starts,ended); +}); + +test("slow or hung collector never overlaps and independent deadline stops rearming", async () => { + const clock = new Clock(); let starts=0;let finish!:()=>void; + const controller = startBridgeRefresh(() => { starts++;return new Promise(resolve => {finish=resolve;}); }, clock.options()); + assert.equal(controller.running,true); + await clock.advance(900000);assert.equal(starts,1); + await clock.advance(BRIDGE_REFRESH_LIFETIME_MS);assert.equal(controller.stopped,true); + finish();await Promise.resolve();await Promise.resolve(); + assert.equal(controller.running,false); + await clock.advance(BRIDGE_REFRESH_LIFETIME_MS*2);assert.equal(starts,1); + assert.ok(clock.created.every(timer => !timer.active)); +}); + +test("slow successful read waits 65 seconds after completion, exceeding source cache lifetime", async () => { + const clock = new Clock();let starts=0;let finish!:()=>void; + const controller=startBridgeRefresh(() => {starts++;return new Promise(resolve=>{finish=resolve;});},clock.options()); + await clock.advance(40000);assert.equal(starts,1); + finish();await Promise.resolve();await Promise.resolve(); + await clock.advance(104999);assert.equal(starts,1); + await clock.advance(105000);assert.equal(starts,2); + controller.stop();finish(); +}); + +test("failure is retried without fabricating a newer successful source timestamp", async () => { + const clock=new Clock();let starts=0;let sourceFetchedAt=0; + const controller=startBridgeRefresh(async()=>{ + starts++; + if(starts===2)throw new Error("synthetic failure; not logged"); + sourceFetchedAt=clock.now(); + },clock.options()); + await clock.advance(65000);assert.equal(starts,2);assert.equal(sourceFetchedAt,0); + await clock.advance(130000);assert.equal(starts,3);assert.equal(sourceFetchedAt,130000); + controller.stop(); +}); + +test("abort and explicit cancellation prevent new starts, including late completion", async () => { + const clock=new Clock();const abort=new AbortController();let starts=0;let finish!:()=>void; + const controller=startBridgeRefresh(()=>{starts++;return new Promise(resolve=>{finish=resolve;});},{...clock.options(),signal:abort.signal}); + abort.abort();assert.equal(controller.stopped,true);finish(); + await clock.advance(3600000);assert.equal(starts,1); + const prior=clock.created.length; + const disabled=startBridgeRefresh(async()=>{starts++;},{...clock.options(),signal:abort.signal}); + assert.equal(disabled.stopped,true);assert.equal(starts,1);assert.equal(clock.created.length,prior); +}); + +test("live hook calls existing single-flight collector; helper owns no credential or publication path", async () => { + const source=await readFile(new URL("../src/sources/live.ts",import.meta.url),"utf8"); + const helper=await readFile(new URL("../src/bridge-refresh.ts",import.meta.url),"utf8"); + assert.ok(source.includes("startBridgeRefresh(queueSnapshot, {")); + assert.ok(source.includes("refresh: process.env.PM_AGG_BRIDGE_REFRESH")); + assert.ok(source.includes("snapshot: process.env.PM_AGG_BRIDGE_SNAPSHOT")); + assert.ok(source.includes("signal: opts?.bridgeRefreshSignal")); + for(const forbidden of ["readBrokerToken", "fetchQueueSnapshot", "publishBridgeQueueSnapshot", "writeFile", "fetch("]) assert.equal(helper.includes(forbidden),false); +}); diff --git a/pm-stack/aggregator/test/bridge-snapshot.test.ts b/pm-stack/aggregator/test/bridge-snapshot.test.ts index a38e4c22fc..883348fc0e 100644 --- a/pm-stack/aggregator/test/bridge-snapshot.test.ts +++ b/pm-stack/aggregator/test/bridge-snapshot.test.ts @@ -9,7 +9,7 @@ import type { QueueSnapshot } from "../src/queue.ts"; const NOW = 1_800_000_000_000; function source(): QueueSnapshot { return { - available: true, stale: false, fetchedAt: NOW, errors: [], + bridgeVerified: true, available: true, stale: false, fetchedAt: NOW, errors: [], tasks: [{ id: 12, status: "queued", priority: 10, title: "SECRET", payload: "SECRET", progressNext: "SECRET" }], queues: [{ queued: 1, claimed: 2, parked: 3, handedOff: 4, blocked: 5, done: 6, cancelled: 7, failed: 8, queue: "SECRET" }], } as unknown as QueueSnapshot; diff --git a/pm-stack/private-laptop-bridge/README.md b/pm-stack/private-laptop-bridge/README.md index 3ab286e35a..8e415ab296 100644 --- a/pm-stack/private-laptop-bridge/README.md +++ b/pm-stack/private-laptop-bridge/README.md @@ -1,7 +1,9 @@ # Private laptop bridge — offline candidate **Not deployed; not a replacement-ready cutover.** Desktop Commander remains the -fallback. This package implements bounded Fleet reads, not a shell. Aster still +fallback. [The staging approval packet](STAGING.md) specifies private Gateway +ingress, resources, identities, costs, installation and rollback. This package +implements bounded Fleet reads, not a shell. Aster still needs an approved caller integration, a privately reachable control plane, and verified enrollment on Drew's AMD NixOS laptop before relying on it. @@ -43,8 +45,10 @@ including newly merged [#12505](https://github.com/developing-today/code/pull/12 authenticated endpoints or reads their token file. * The existing aggregator already reads `/health` and `/list`. An opt-in sanitized snapshot producer supplies queue metadata to this bridge without - adding another credential consumer. Publication does not add a polling timer: - it occurs when the existing collector refreshes. Unrefreshed data expires. + adding another credential consumer. Publication follows the existing collector; + a separately gated one-hour refresh pilot can maintain its cadence. Unrefreshed + data expires, and raw broker provenance must be verified before zeros count as + an observed idle queue. * `pkgs/laptop-agent/src/laptop_agent.py` exposes general `/exec`, `/jobs` and `/file`. None is called or proxied here. * `home/common/default.nix` declares `desktop-commander-remote`; this change does @@ -93,7 +97,8 @@ replacement. an owner-controlled channel. Never accept a device-reported caller key or an unauthenticated key-discovery endpoint. Prove wrong-role, wrong-device, wrong-audience, expired and revoked identities fail at every stage. -4. Explicitly approve enabling `PM_AGG_BRIDGE_SNAPSHOT=1` on the existing +4. Explicitly approve enabling `PM_AGG_BRIDGE_SNAPSHOT=1` and, for the bounded + refresh pilot, `PM_AGG_BRIDGE_REFRESH=1` on the existing aggregator and installing the **disabled example** non-root bridge unit. Confirm actual permissions, Nix Node path, fixed snapshot location and local health socket. Observe a fresh real snapshot; then simulate stale/missing @@ -115,7 +120,7 @@ replacement. Disable the bridge first (`ENABLED` not `true`), revoke the caller/device entries, and stop the new user service. Remove private ingress/service bindings only under -the same approved change procedure. Disable the aggregator snapshot opt-in; +the same approved change procedure. Remove both aggregator opt-in flags; remaining snapshots age out and are never treated as fresh indefinitely. Short RPC/result lifetimes bound recoverable data; explicit deletion of cloud resources or credential material needs its own approved cleanup. Resume Fleet through the @@ -167,6 +172,15 @@ new lease; the previous lease cannot commit. All accepted-signature attempts, including replay and invalid arguments, consume quota. Unknown/invalid signatures produce constant denial log records; they cannot create identity-specific state. +Accepted calls and leased jobs include `serverNow`. The clients convert the +advertised server-relative lifetime to a conservative local deadline starting at +request send time, so network transit consumes the budget and ±30-second clock +offset does not extend a lease. Caller handle `expiresAt` is therefore on the +caller runner's clock, not server UTC. Queue observation timestamps remain source +timestamps; a future source timestamp is refused by the caller rather than shown +as a successful current observation. Idle polling is two seconds, leaving room +within the device quota for result submissions. + Audit stores only timestamp, validated principal/role, fixed route and status. It stores no bodies, results, paths, private keys or exception messages. Denial console records contain fixed event/status/code fields. Cloudflare log retention, @@ -183,8 +197,8 @@ Requires Node 24+. From this directory: ```sh npm ci -npm test -node --test ../aggregator/test/bridge-snapshot.test.ts +npm run rehearse +npm run check:staging ``` `runtime.test.mjs` executes the actual Worker with Miniflare/workerd and SQLite @@ -194,7 +208,13 @@ local temporary database fixtures are removed after tests. The unit/property and state-machine tests complement this runtime evidence. No test deploys a Worker, connects to AMD, reads live credentials or installs a service. -No CI workflow or schedule is added. The repository disables automatic PR CI; +`check:staging` is a local Wrangler bundle dry run, not a deployment. The deployed +candidate's default HTTP handler always denies; only the Gateway RPC entrypoint +can reach the signed bridge, after trusted-context checks. The real Gateway DNS, +device enrollment and TLS-trust path still requires the approval packet's smoke. + +No CI workflow or active schedule is added. The optional process interval is +registered as proposed/disabled. The repository disables automatic PR CI; this PR must not imply absent checks passed. Full aggregator/Bun verification and NixOS service sandbox validation remain separate from the focused snapshot tests. @@ -221,9 +241,17 @@ follows no redirects, stops on authorization denial, and reconnects with bounded backoff after transport failure. The supplied service file is a review template with placeholder executable paths and no installation target. -Queue freshness is demand-driven: publication follows the aggregator's existing -`source.queue()` refresh, currently used by its service view. Enabling publication -alone does not guarantee a periodic fresh snapshot. Verify the actual refresh -cadence during the pilot; if the source is idle, the bridge correctly becomes -unavailable after five minutes. Adding a scheduled refresh would be a separate -reviewed change with the Fleet schedule registry updated in the same pass. +Queue publication alone remains demand-driven. The separately approved refresh +pilot requires **both** literal flags, reads immediately then 65 seconds after +completion (beyond the 60-second cache), never overlaps, and stops scheduling +after one hour. It uses a monotonic clock and unref'd timers. An already running +read may finish after the stop; it cannot schedule another. Removing both flags +prevents restart from beginning another pilot. No successful read means no new +source timestamp: after five minutes the client reports unavailable, never idle. +Fresh explicit zero counters are an observed idle queue; an empty partial task +list still has `complete:false,total:null` and proves no global empty total. + +`aster.mjs` supplies the four strictly parsed commands in STAGING.md for an +approved non-root caller runner. Its end-to-end test exercises actual CLI parsing, +signing, Worker/SQLite execution, the laptop client, and bounded JSON output. No +Aster connector or runner access is installed by this package. diff --git a/pm-stack/private-laptop-bridge/STAGING.md b/pm-stack/private-laptop-bridge/STAGING.md new file mode 100644 index 0000000000..42daaca972 --- /dev/null +++ b/pm-stack/private-laptop-bridge/STAGING.md @@ -0,0 +1,287 @@ +# Private staging and Aster pilot — approval packet + +Prepared 2026-11-22. **Not deployed, enrolled, enabled, or replacement-ready.** +This is a bounded one-hour proposal, not authorization. Resource identifiers, +verified owner email, exact runtime/store paths and the UTC pilot window must be +filled from read-only inventory and approved before execution. No secrets belong +in this document. Desktop Commander remains installed and usable. + +## Selected ingress and the remaining feasibility gate + +Use **Cloudflare Gateway Forward**, not a public Worker URL. The official guide +supports a Worker with no public route, `workers_dev:false`, +`preview_urls:false`, invoked through `GatewayMiddleware.handle()`; HTTPS needs +Gateway HTTP filtering, TLS decryption and a trusted root. It can return a +synthetic response without contacting an origin. This capability is in public +beta on all Zero Trust plans. WebSocket and CONNECT traffic bypass this mechanism; +this bridge uses only ordinary HTTPS POSTs. Invocation failures fail closed. +[Cloudflare Forward guide](https://developers.cloudflare.com/cloudflare-one/traffic-controls/integrate-workers/forward-traffic/) + +Proposed path: + +```text +Aster's approved isolated caller runner AMD non-root client + independently held caller signing key device signing key + | | + +---- outbound HTTPS through scoped Gateway ---+ + | + GatewayMiddleware RPC entrypoint + (no next(), no origin forwarding) + | + existing bridge Durable Object + independent request signature checks +``` + +Workers VPC connects Workers **to** private services. It does not itself let the +laptop reach a private Worker. Service bindings likewise do not supply a laptop +transport. No Workers VPC binding, Tunnel, public route, or generic network proxy +is proposed. [Workers VPC services](https://developers.cloudflare.com/workers-vpc/configuration/vpc-services/) + +**DNS/on-ramp gate is unresolved, not papered over.** Proposed host is +`private-bridge-staging.security.cab`, subject to confirming owner control and +absence of an existing record/wildcard route. Do not point it at `pm.security.cab` +or any real application. The intended arrangement has no public A/AAAA/CNAME and +an exact-host Gateway DNS override to the non-serving documentation address +`192.0.2.1` (proposed, not yet tested), with a 60-second DNS TTL where supported. +No server or tunnel is attached to that address; confirm no local route repurposes it. +Gateway documents custom DNS override answers; it does not establish that a +reserved sink address passes every pre-HTTP proxy check. The combined path needs +a credential-free live smoke before any real bridge keys or Fleet data are used. +[DNS override](https://developers.cloudflare.com/cloudflare-one/traffic-controls/dns-policies/) + +The smoke must show the Forward entrypoint returns a fixed synthetic response +without an origin connection. Then remove/disable the Forward rule and test +again, plus bypass Gateway entirely: both paths must fail without reaching an +application or exposing a request body. Test A and AAAA behavior, cached answers, +wrong hostname, alternate port, CONNECT and WebSocket. If the sink arrangement +is rejected or cannot prove that property, **stop the pilot** and review a new +transport; do not substitute a public authenticated management endpoint. The +current code can be reviewed/deployed disabled, but is not yet an approved, +operational private transport. + +There is no evidence that AMD or the current Aster Work executor is already +Gateway-enrolled. The Work executor must not be assumed to support a persistent +VPN client or root certificate installation. A separate owner-controlled isolated +caller runner is a prerequisite if the existing executor cannot provide the +approved on-ramp. Cloudflare's clientless proxy alternatives are not a proven +shortcut here: identity proxy setup uses interactive authorization, while +source-IP proxy endpoints require Enterprise. They also need review for broader +private-network reach; neither is selected for this pilot. +[Proxy endpoints](https://developers.cloudflare.com/cloudflare-one/networks/resolvers-and-proxies/proxy-endpoints/) + +A lower-priority HTTP Block is **not** a fallback for Forward: Gateway evaluates +request Blocks before Forward, so a matching Block prevents invocation. Do not +add an always-matching Block and expect ordering to fix it. A missing Forward +policy is different from a Worker error: traffic can proceed normally, making +the non-serving sink and bypass smoke essential. + +## Exact proposed resources and authority + +| Resource | Proposed permission / constraint | +| --- | --- | +| Cloudflare account | Existing owner account, ID verified before approval; no account-wide policy changes | +| Worker | `private-laptop-bridge-staging`, no routes/custom domains/public previews; default disabled | +| Storage | One new SQLite-backed `PrivateLaptopBridge` Durable Object namespace; only bounded RPC state/audit | +| Gateway rules | DNS rule `private-laptop-bridge-pilot-dns` and HTTP rule `private-laptop-bridge-one-hour-pilot`, initially disabled; owner-email and approved device-posture restriction; inspect only pilot host traffic | +| Network enrollment | Only AMD and a separately identified caller runner; dedicated test profile; preserve Tailscale and all existing routing | +| TLS trust | Only the two dedicated bridge Node processes; approved Gateway root public certificate, fingerprint verified; no global OS/browser trust installation | +| Device principal | `amd-pilot`, role `device`, device `amd`, public key only at Worker | +| Caller principal | `aster-pilot`, role `caller`, device `amd`, a different public key | +| Signature audience | `fleet-private-bridge-staging-v1`, unique to this staging instance | +| Bridge scopes | `fleet.queue.list`, `fleet.queue.health`, `laptop.health`, `laptop.diagnostics` only | +| Lifetime | Both principals issued at pilot start and expire no later than start + 3,600,000 ms; no renewal | +| AMD local reads | Fixed sanitized queue snapshot and fixed credential-free health adapter inputs only; no queue/secrets token | +| AMD process | New manually started user unit `private-laptop-bridge-pilot.service`, no enablement/linger; `RuntimeMaxSec=3600`, `Restart=no` | +| Local configuration | AMD `%h/.config/private-laptop-bridge/device.json`; caller `%h/.config/private-laptop-bridge/aster.json`; owner-only files, independently provisioned keys | +| Public CA file | `%h/.config/private-laptop-bridge/gateway-ca.pem` on each approved runner, fingerprint checked; per-process use only | +| Data destination | This staging Worker/DO and authenticated caller only; no log-body capture, external telemetry export or shared artifacts | + +The Gateway entrypoint should pin account ID, Forward policy ID, hostname, and +verified owner email, denying unavailable identity. The context reference exposes +`accountId`, `policyId`, `host`, `uri`, and an async `identity()` returning an +optional email; it does **not** expose a documented raw device ID. A required +posture check is matched by UUID in `devicePosture().checks.passed`; absent or +failed lookup must deny. Gateway identity is an additional gate, never a +replacement for the independently pinned caller/device signing keys. +[Available context](https://developers.cloudflare.com/cloudflare-one/traffic-controls/integrate-workers/available-context/) + +Deploy using the owner's existing approved short-lived administrative mechanism. +Runtime principals need **no Cloudflare API permissions**. The deployment actor +needs Workers script deployment permissions for the chosen account; an owner +administrator separately applies the exact reviewed Gateway rule changes. The +Gateway rule API lists `Zero Trust Write` as an accepted permission: this is broad +administrative power, not a credential to install on AMD or the caller. Prefer +owner-applied dashboard changes or verified resource-scoped administration over +minting a general automation token. No DNS-zone write permission is needed for +the proposed Gateway-only override. No Access service token or Tunnel token is +needed. [Gateway rule API](https://developers.cloudflare.com/api/go/resources/zero_trust/subresources/gateway/subresources/rules/methods/create/) + +Review-only Forward request shape (not executed; placeholders must be resolved, +precedence compared against existing rules, then the exact diff approved): + +```json +{ + "name": "private-laptop-bridge-one-hour-pilot", + "enabled": false, + "precedence": 1000, + "action": "forward", + "filters": ["http"], + "traffic": "http.request.host == \"private-bridge-staging.security.cab\" and http.request.method == \"POST\" and http.request.uri.path in {\"/v1/call\" \"/v1/read\" \"/v1/poll\" \"/v1/result\"}", + "identity": "identity.email == \"VERIFIED_OWNER_EMAIL\"", + "device_posture": "any(device_posture.checks.passed[*] in {\"APPROVED_PILOT_POSTURE_UUID\"})", + "rule_settings": {"forward": {"worker_id": "ACTUAL_32_HEX_WORKER_ID"}} +} +``` + +Validate expression syntax using the account's policy builder/API before +activation. This skeleton is not proof of a saved rule. An HTTP rule does not +support the DNS rule `expiration` facility; use principal expiry and client +process lifetime for the hard stop, then explicitly remove pilot routing. +[HTTP selectors](https://developers.cloudflare.com/cloudflare-one/traffic-controls/http-policies/) + +## TLS and laptop install boundaries + +`NODE_EXTRA_CA_CERTS` can extend trust for a single launched Node process with a +PEM certificate file; it is read on startup. This does not restrict the trusted +CA to one hostname. Therefore use a bridge-only process, pinned origin, no generic +fetch tool and no subprocesses. Do not set it globally or use +`NODE_TLS_REJECT_UNAUTHORIZED=0`. Confirm behavior with the pinned Nix Node build +and certificate fingerprint. [Node CLI certificate settings](https://nodejs.org/api/cli.html#node_extra_ca_certsfile) + +Gateway profile enrollment/routing remains a separate network/security change +requiring approval even with per-process trust. A new dedicated two-device pilot profile that only routes +and decrypts this host must be proven before AMD participation. Do not install a +tenant-wide catch-all Do Not Inspect exception or disable existing inspection +policies. Review the existing on-ramp, device-profile assignment, DNS forwarding, +HTTP inspection and Tailscale coexistence together; exact-host HTTP rules alone +do not prove that other traffic is excluded from TLS interception. If the available +on-ramp requires broad TLS interception or changing existing Tailscale paths, +that exceeds this proposal and is a blocker. + +After approval, install only the reviewed commit's client/protocol/adapters and a +pinned Node runtime; review the exact Nix store paths. Owner provisions separate +signing material locally on each host using a separately approved procedure; +private halves never go to Cloudflare, the other host, chat, or the repository. +The existing client accepts a private owner-only config file; no auto-key-creation +or pairing flow exists. Review and fill the disabled unit example, add a +one-hour `RuntimeMaxSec=3600`, keep `Restart=no`, and start manually without enable, +linger, cron, timer, or an `[Install]` section. The optional extra-CA file is public +certificate data, not a signing key, and must also be explicitly allowed by any +mount isolation. + +Separately approve both `PM_AGG_BRIDGE_SNAPSHOT=1` and +`PM_AGG_BRIDGE_REFRESH=1` for the existing aggregator. The new, default-disabled +process interval reuses its existing collector: immediate read, then 65 seconds +after completion, never overlapping, at most 57 starts, with an independent +one-hour stop. It is registered as proposed/disabled in the Fleet schedule +registry. An in-flight collector may complete and publish its actual observation +after that stop, but cannot start another refresh. A restart with both flags set +starts another pilot, so remove both flags afterward. No external timer is added. +Verify actual home/path permissions and that the client reads the same file. +Only explicitly verified broker data can publish a successful snapshot; malformed +envelopes or missing counters cannot become zero/idle. Known failures publish an +unavailable marker; failed publication can preserve the prior observation only +until its original five-minute TTL. It never refreshes that observation's timestamp. + +## Aster's concrete caller path + +For the first pilot, Aster uses an **already authorized executor** on the approved +isolated runner to invoke `aster.mjs` with its own `aster-pilot` identity. +That executor's existence, owner and Gateway capability must be verified; current +Work access alone establishes none of them. The SDK can submit an allowlisted +operation and wait/read its accepted handle; it cannot enroll, dispatch, or run a +host command. The wrapper accepts only these forms (after approval, with the +reviewed Node/runtime paths and per-process CA environment): + +```sh +node aster.mjs --config /APPROVED_HOME/.config/private-laptop-bridge/aster.json queue-list --limit 10 --status blocked +node aster.mjs --config /APPROVED_HOME/.config/private-laptop-bridge/aster.json queue-health +node aster.mjs --config /APPROVED_HOME/.config/private-laptop-bridge/aster.json laptop-health +node aster.mjs --config /APPROVED_HOME/.config/private-laptop-bridge/aster.json laptop-diagnostics +``` + +It emits bounded `accepted` then `complete` JSON records or a fixed error code. +Use the SDK to resume a known accepted handle and preserve +uncertain submission outcomes rather than automatically re-submitting. + +If Aster cannot reach that runner with an existing authorized execution surface, +implementation is blocked pending a specific integration decision. A private +custom MCP connector could expose only these four SDK operations, keep the caller +key on the runner, and validate the same input/output schemas. That connector +requires its own reviewed authentication, hosting and installation approval; it is +not installed or implemented here. Do not install a generic shell connector, +reuse Desktop Commander as the new caller path, or put a key in a public MCP URL. + +## One-hour acceptance and rollback + +1. Before the clock starts: approve exact commit, account, host, identity/public + keys, network/profile/CA changes, local paths, resource diff and zero-incremental + budget. Complete the credential-free DNS/Forward smoke above. +2. Minute 0–10: enable staging registry and routing, start caller and AMD client, + observe fresh snapshot and one successful result for each scope. Record only + operation, timestamp, outcome and bounded scalar verification evidence. +3. Minute 10–30: Aster independently repeats each read; compare counters/task IDs + to the approved local source. Verify partial lists say partial. Record which + actual Commander workflow each covers and which remains native Codex work. +4. Minute 30–45: wrong key/role/device/audience, denied operation, stale snapshot, + replay, quota, reconnect/expired lease, missing Gateway identity and disabled + Forward path all fail as expected; no origin receives payloads. +5. Minute 45–55: revoke caller then device independently and verify stored result + retrieval, submit, poll and completion denial. Observe active configuration, + not just deployment acknowledgement. Demonstrate rollback. +6. By minute 60: expiry closes all authorized requests, clients stop; owner disables + the bridge and both pilot policies, removes only new enrollment/profile/trust + changes, restores aggregator setting and stops the new user unit. Remove + Forward policy before deleting its Worker; remove the DNS override, wait its + observed TTL and flush only pilot-client DNS caches; preserve the minimal audit receipt. + Dispose of pilot private keys locally under the approved process. + +No automatic cutover follows a successful pilot. Retiring Commander requires a +separate owner-approved parity record and native Codex verification. + +## Cost and capability assumptions (fetched 2026-11-22) + +Proposed incremental budget: **$0; no plan upgrade**. Confirm remaining shared +account allowances before approval. Cloudflare lists Zero Trust Free at $0 for +50 users; paid PAYG is $7/user/month. Two pilot devices do not establish that the +account has available seats. [Cloudflare pricing](https://www.cloudflare.com/plans/) + +Workers Free includes 100,000 requests/day with a 10 ms CPU limit per invocation; +Workers Paid has a $5 monthly subscription. Do not upgrade automatically if the +signature path hits CPU limits. [Workers pricing](https://developers.cloudflare.com/workers/platform/pricing/) + +SQLite Durable Objects are available on Free: 100,000 requests/day, 13,000 GB-s/day, +5 million row reads/day, 100,000 row writes/day and 5 GB stored. Exceeding free +limits can make requests fail; the pilot must not treat that as an auth bypass. +[Durable Objects pricing](https://developers.cloudflare.com/durable-objects/platform/pricing/) + +One client polling every two seconds produces at most 1,800 idle polls/hour plus +result and caller traffic. Limit the pilot to 60 submitted reads. With prompt +completion this is roughly 2,100 ingress requests, 2,100 DO requests, plus alarm +invocations. Reserve at least 10,000 requests of remaining allowance **in each** +Worker and DO category; they are separately metered, and alarm invocations also +count. Slow/disconnected callers may consume more polling requests. Verify actual +storage operations/CPU in staging rather than equating an HTTP request with one +SQL row operation. This estimate is workload arithmetic, not a bill or +quota reservation. Stop if existing usage leaves insufficient headroom. No +storage/Logpush/paid retention add-on is proposed. + +The optional refresh pilot starts at most 57 existing collector passes per hour. +Each pass performs one existing broker health read plus one bounded list read per +reported queue; this is local broker/Turso workload, not a new direct Cloudflare +or Turso credential. Account/API allowances and the actual number of queues must +be checked before enabling it. Free-plan limits are capacity limits, not a +guaranteed reserved budget; no $0 claim is valid if the account is already paid +and incurs incremental overages. The owner must approve the account-specific cap. + +## Exact actions still requiring approval + +The code/config is buildable offline; this packet does not authorize any of: +deploying the Worker/SQLite namespace; creating/enabling the two Gateway policies; +enrolling either device or changing its routing/DNS/TLS trust; provisioning keys +or registering their public halves; installing/starting the AMD unit; changing +aggregator flags; giving Aster a new executor/connector; removing pilot credentials +or infrastructure; or retiring Desktop Commander. Resolve real account/rule/posture +IDs, verified email, runner ownership, Nix paths, certificate fingerprint and +pilot UTC window into a final diff first. Seek approval for that exact diff, +starting with the credential-free network smoke; do not request blanket access. diff --git a/pm-stack/private-laptop-bridge/VERIFICATION.md b/pm-stack/private-laptop-bridge/VERIFICATION.md index 515e6ea7ef..19347cbcda 100644 --- a/pm-stack/private-laptop-bridge/VERIFICATION.md +++ b/pm-stack/private-laptop-bridge/VERIFICATION.md @@ -1,4 +1,42 @@ -# Offline verification checkpoint — 2026-11-22 +# Offline verification checkpoints — 2026-11-22 + +## Follow-up review and private staging candidate + +The next revision adds `npm run rehearse` (all bridge, Gateway, Aster, freshness, +publisher and bounded-refresh tests) and `npm run check:staging` (Wrangler bundle +dry run, never deployment). The PR records the final tested commit and results; +the original checkpoint below remains historical evidence for `0ba3dd75a`. + +Concrete findings fixed in this follow-up: + +* Raw malformed broker counters could normalize to zero and look idle. Bridge + publication now requires explicit validated broker provenance and fresh, + error-free observations. Eight integration cases prove idle versus unavailable, + exact TTL boundaries, missing data, stale completed results and retained-file + behavior after failed publication. +* Awaiting cancellation of a denied response could hang the device client. + Cleanup is nonblocking; pending/rejecting cancellation regression tests pass. +* Slight clock differences rejected legitimate short leases. `serverNow` and + conservative request-start-relative deadlines tolerate valid offsets while + charging transport time against the lease. Regression coverage includes + ±500 ms, ±29 seconds, delayed responses and inconsistent advertised lifetimes. +* Idle polling consumed the entire per-minute device quota. Two-second polling + reserves capacity for results. + +The disabled refresh pilot has eight deterministic scheduler tests proving +strict opt-in, cache-safe cadence, no overlap, monotonic one-hour stop, cancellation +and no rearming after a hung/late collector. The real Gateway RPC harness verifies +trusted context/identity/posture gating, direct HTTP denial, and zero upstream +continuation calls. Aster's four-command CLI has seven tests including actual +CLI → signed SDK → workerd/SQLite → laptop-client roundtrips. + +Wrangler 4.166.0 successfully bundled the private staging configuration in a +local dry run. Bun 1.4.5 ran the existing queue suite: 18 passed, zero failed. +These checks do not prove real Gateway routing or AMD service behavior. The +DNS sink/on-ramp composition, exact account/device inventory and certificate +trust remain mandatory approval-gated live tests in [STAGING.md](STAGING.md). + +## Original checkpoint Implementation based on developing-today/code `ad4e69670`, refreshed by merge to `7bfcaff23` before review. Executed as non-root UID 1000 in an isolated cloud diff --git a/pm-stack/private-laptop-bridge/aster.mjs b/pm-stack/private-laptop-bridge/aster.mjs new file mode 100644 index 0000000000..e7607c80f0 --- /dev/null +++ b/pm-stack/private-laptop-bridge/aster.mjs @@ -0,0 +1,99 @@ +// CLI contract (fixed order, no aliases or --name=value): +// --help +// --config ABSOLUTE_PATH queue-list --limit N [--status STATUS] +// --config ABSOLUTE_PATH queue-health|laptop-health|laptop-diagnostics +// Parse every argument before config reads, key import or network activity. +// The approved caller config is owner-only; device is fixed to amd. No key is +// generated, enrolled or printed, and no command/URL/path reaches the laptop. +import { isAbsolute } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { createCaller } from './caller.mjs'; +import { readConfig, requireNonRoot } from './client.mjs'; +import { identifier, statuses, validateOperation, validateResult } from './protocol.mjs'; + +export const USAGE = 'Usage: node aster.mjs --config ABSOLUTE_PATH queue-list --limit N [--status STATUS]\n' + + ' node aster.mjs --config ABSOLUTE_PATH queue-health|laptop-health|laptop-diagnostics\n' + + ' node aster.mjs --help\n'; +const COMMANDS = Object.freeze({ + 'queue-list': { operation: 'fleet.queue.list', method: 'fleetQueueList' }, + 'queue-health': { operation: 'fleet.queue.health', method: 'fleetQueueHealth' }, + 'laptop-health': { operation: 'laptop.health', method: 'laptopHealth' }, + 'laptop-diagnostics': { operation: 'laptop.diagnostics', method: 'laptopDiagnostics' }, +}); +const SAFE_ERRORS = new Set(['non-root-required', 'invalid-config', 'invalid-operation', 'invalid-response', + 'invalid-handle', 'denied', 'quota', 'unavailable', 'timeout', 'cancelled', 'expired', 'stale-result', + 'submit-outcome-unknown']); + +export function parseAsterArgs(argv) { + if (!Array.isArray(argv) || !argv.every(v => typeof v === 'string')) throw new Error('usage'); + if (argv.length === 1 && argv[0] === '--help') return { help: true }; + if (argv.length < 3 || argv[0] !== '--config' || !isAbsolute(argv[1]) || argv[1].includes('\0') + || !Object.hasOwn(COMMANDS, argv[2])) throw new Error('usage'); + const command = argv[2]; + let args = {}; + if (command === 'queue-list') { + if (![5, 7].includes(argv.length) || argv[3] !== '--limit' || !/^(?:[1-9]|1[0-9]|20)$/.test(argv[4])) throw new Error('usage'); + args = { limit: Number(argv[4]) }; + if (argv.length === 7) { + if (argv[5] !== '--status' || !statuses.includes(argv[6])) throw new Error('usage'); + args.status = argv[6]; + } + } else if (argv.length !== 3) throw new Error('usage'); + const { operation, method } = COMMANDS[command]; + if (!validateOperation(operation, args)) throw new Error('usage'); + return { config: argv[1], command, operation, method, args }; +} + +const importSigningKey = jwk => crypto.subtle.importKey('jwk', jwk, { name: 'Ed25519' }, false, ['sign']); + +/** All injected dependencies are for offline tests/in-process integration; none + * are configurable through argv or the remote protocol. Returns a process code. */ +export async function runAster(argv, { loadConfig = readConfig, importKey = importSigningKey, callerFactory = createCaller, + getuid = process.getuid, stdout = text => process.stdout.write(text), stderr = text => process.stderr.write(text), signal } = {}) { + let command; + try { command = parseAsterArgs(argv); } + catch { stderr(USAGE); return 2; } + if (command.help) { stdout(USAGE); return 0; } + const emit = value => { + const line = JSON.stringify(value) + '\n'; + if (Buffer.byteLength(line, 'utf8') > 8192) throw new Error('invalid-response'); + stdout(line); + }; + try { + requireNonRoot(getuid); + const config = await loadConfig(command.config, getuid); + const privateKey = await importKey(config.privateKey); + const caller = callerFactory({ origin: config.origin, audience: config.audience, principal: config.principal, privateKey, device: 'amd' }); + const deadline = signal ? AbortSignal.any([signal, AbortSignal.timeout(65000)]) : AbortSignal.timeout(65000); + const options = { signal: deadline }; + const handle = command.command === 'queue-list' + ? await caller[command.method](command.args, options) + : await caller[command.method](options); + // Only projected handle fields leave this process. expiresAt is a deadline + // on this caller runner's clock, not a server UTC timestamp. + if (!handle || !identifier(handle.id) || handle.operation !== command.operation || !Number.isSafeInteger(handle.expiresAt)) throw new Error('invalid-response'); + emit({ event: 'accepted', handle: { id: handle.id, operation: command.operation, expiresAt: handle.expiresAt, args: command.args } }); + const reply = await caller.wait(handle, options); + if (reply?.status !== 'complete' || !validateResult(command.operation, reply.result)) throw new Error('invalid-response'); + if (command.command === 'queue-list' && reply.result.ok && (reply.result.data.tasks.length > command.args.limit + || (command.args.status && reply.result.data.tasks.some(task => task.status !== command.args.status)))) throw new Error('invalid-response'); + emit({ event: 'complete', id: handle.id, operation: command.operation, result: reply.result }); + return reply.result.ok ? 0 : 1; + } catch (error) { + const candidate = error?.code ?? error?.message; + const code = SAFE_ERRORS.has(candidate) ? candidate : 'unavailable'; + // No raw exception text, caller config, private key, response or stack. + stderr(JSON.stringify({ event: 'error', error: code }) + '\n'); + return 1; + } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const controller = new AbortController(); + const stop = () => controller.abort(); + process.once('SIGINT', stop); process.once('SIGTERM', stop); + runAster(process.argv.slice(2), { signal: controller.signal }) + .then(code => { process.exitCode = code; }) + .catch(() => { process.stderr.write('{"event":"error","error":"unavailable"}\n'); process.exitCode = 1; }) + .finally(() => { process.removeListener('SIGINT', stop); process.removeListener('SIGTERM', stop); }); +} diff --git a/pm-stack/private-laptop-bridge/aster.test.mjs b/pm-stack/private-laptop-bridge/aster.test.mjs new file mode 100644 index 0000000000..bcb6550d5f --- /dev/null +++ b/pm-stack/private-laptop-bridge/aster.test.mjs @@ -0,0 +1,168 @@ +// Oracle: complete CLI grammar, fixed operation dispatch, and only sanitized +// accepted/result/error records. All dependencies are synthetic; no live access. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { parseAsterArgs, runAster } from './aster.mjs'; + +const configPath = '/owner/caller.json'; +const argv = (...args) => ['--config', configPath, ...args]; +const counts = { queued: 1, claimed: 0, parked: 0, handed_off: 0, blocked: 0, done: 0, cancelled: 0, failed: 0 }; +const samples = { + 'fleet.queue.list': { ok: true, data: { tasks: [{ id: 1, status: 'queued' }], complete: false, total: null, fetchedAt: Date.now() } }, + 'fleet.queue.health': { ok: true, data: { ...counts, fetchedAt: Date.now() } }, + 'laptop.health': { ok: true, data: { queueBroker: 'up' } }, + 'laptop.diagnostics': { ok: true, data: { uptimeSeconds: 123, load1: 0.25, memoryFreeBytes: 1024 } }, +}; +function fixtures(overrides = {}) { + const stdout = [], stderr = [], activity = []; + const config = { origin: 'https://bridge.invalid', audience: 'aster-test', principal: 'aster-caller', privateKey: { sensitive: 'never-print' } }; + const methods = { fleetQueueList: 'fleet.queue.list', fleetQueueHealth: 'fleet.queue.health', laptopHealth: 'laptop.health', laptopDiagnostics: 'laptop.diagnostics' }; + const caller = Object.fromEntries(Object.entries(methods).map(([method, operation]) => [method, async (...args) => { + activity.push({ method, args }); + return { id: 'read-1', operation, expiresAt: Date.now() + 60000, privateTimingState: 'never-print' }; + }])); + caller.wait = async (handle, options) => { activity.push({ method: 'wait', handle, options }); return { status: 'complete', handle, result: samples[handle.operation] }; }; + const deps = { + getuid: () => 1000, + loadConfig: async (path, getuid) => { activity.push({ method: 'config', path }); assert.equal(getuid(), 1000); return config; }, + importKey: async key => { assert.equal(key, config.privateKey); activity.push({ method: 'import' }); return 'in-memory-CryptoKey'; }, + callerFactory: options => { activity.push({ method: 'factory', options }); return caller; }, + stdout: text => stdout.push(text), stderr: text => stderr.push(text), ...overrides, + }; + return { deps, stdout, stderr, activity, caller }; +} + +test('Aster: entire grammar is strict and malformed arguments never read config or network', async () => { + const malformed = [[], ['queue-health'], ['--help','extra'], argv('queue-list'), argv('queue-list','--limit'), + argv('queue-list','--limit','0'), argv('queue-list','--limit','21'), argv('queue-list','--limit','01'), + argv('queue-list','--limit','1e1'), argv('queue-list','--limit=1'), argv('queue-list','--limit','1','--status','unknown'), + argv('queue-list','--limit','1','--status','queued','--limit','2'), argv('queue-health','--url','http://local'), + argv('laptop-health','stray'), argv('shell','echo','hi'), ['--config','relative','laptop-health'], + ['--config','/owner/\0bad','laptop-health'], argv('constructor'), argv('__proto__'), + ]; + for (const args of malformed) { + const f = fixtures(); + assert.throws(() => parseAsterArgs(args), /usage/); + assert.equal(await runAster(args, f.deps), 2); + assert.deepEqual(f.activity, []); + assert.deepEqual(f.stdout, []); + } + assert.deepEqual(parseAsterArgs(argv('queue-list','--limit','20','--status','queued')).args, { limit: 20, status: 'queued' }); +}); + +test('Aster: root refusal precedes config reads, help has no data access', async () => { + const f = fixtures({ getuid: () => 0 }); + assert.equal(await runAster(argv('laptop-health'), f.deps), 1); + assert.deepEqual(f.activity, []); + assert.deepEqual(f.stderr.map(JSON.parse), [{ event: 'error', error: 'non-root-required' }]); + const help = fixtures(); + assert.equal(await runAster(['--help'], help.deps), 0); + assert.deepEqual(help.activity, []); +}); + +test('Aster: four commands dispatch named reads and emit bounded projected records only', async () => { + const commands = [['queue-list','--limit','1','--status','queued'], ['queue-health'], ['laptop-health'], ['laptop-diagnostics']]; + for (const command of commands) { + const f = fixtures(); + assert.equal(await runAster(argv(...command), f.deps), 0); + assert.deepEqual(f.stderr, []); + const records = f.stdout.map(JSON.parse); + assert.equal(records.length, 2); + assert.equal(records[0].event, 'accepted'); + assert.equal(records[1].event, 'complete'); + assert.deepEqual(records[1].result, samples[records[1].operation]); + assert.equal(f.stdout.join('').includes('never-print'), false); + assert.ok(f.stdout.every(line => Buffer.byteLength(line) <= 8192)); + const factory = f.activity.find(a => a.method === 'factory'); + assert.equal(factory.options.device, 'amd'); + assert.equal(factory.options.privateKey, 'in-memory-CryptoKey'); + const wait = f.activity.find(a => a.method === 'wait'); + assert.equal(wait.handle.privateTimingState, 'never-print', 'original SDK timing handle remains internal'); + assert.ok(wait.options.signal instanceof AbortSignal); + } +}); + +test('Aster: uncertain submit stops once without waiting or retrying', async () => { + const f = fixtures(); + let submits = 0; + f.caller.laptopHealth = async () => { submits++; throw Object.assign(new Error('sensitive transport message'), { code: 'submit-outcome-unknown' }); }; + assert.equal(await runAster(argv('laptop-health'), f.deps), 1); + assert.equal(submits, 1); + assert.deepEqual(f.stdout, []); + assert.equal(f.activity.some(a => a.method === 'wait'), false); + assert.deepEqual(f.stderr.map(JSON.parse), [{ event: 'error', error: 'submit-outcome-unknown' }]); +}); + +test('Aster: read failure retains accepted receipt but never exposes raw errors', async () => { + const f = fixtures(); + f.caller.wait = async () => { throw new Error('secret network details'); }; + assert.equal(await runAster(argv('laptop-health'), f.deps), 1); + assert.equal(f.stdout.map(JSON.parse)[0].event, 'accepted'); + assert.equal(f.stdout.length, 1); + assert.deepEqual(f.stderr.map(JSON.parse), [{ event: 'error', error: 'unavailable' }]); +}); + +test('Aster: malformed or excessive output fails before disclosure; unavailable stays a failure', async () => { + for (const result of [{ ok: true, data: { queueBroker: 'up', token: 'secret' } }, + { ok: true, data: { queueBroker: 'secret'.repeat(3000) } }]) { + const f = fixtures(); + f.caller.wait = async () => ({ status: 'complete', result }); + assert.equal(await runAster(argv('laptop-health'), f.deps), 1); + assert.equal(f.stdout.length, 1); + assert.equal(f.stdout.join('').includes('secret'), false); + assert.deepEqual(f.stderr.map(JSON.parse), [{ event: 'error', error: 'invalid-response' }]); + } + const f = fixtures(); + f.caller.wait = async () => ({ status: 'complete', result: { ok: false, error: 'unavailable' } }); + assert.equal(await runAster(argv('laptop-health'), f.deps), 1); + assert.deepEqual(f.stdout.map(JSON.parse)[1].result, { ok: false, error: 'unavailable' }); +}); + +test('Aster: real CLI -> signed caller SDK -> workerd -> device -> projected output', async t => { + const { Miniflare } = await import('miniflare'); + const { createCaller } = await import('./caller.mjs'); + const { createClient } = await import('./client.mjs'); + const { b64url, operations } = await import('./protocol.mjs'); + const { fileURLToPath } = await import('node:url'); + const origin = 'https://aster-bridge.invalid', audience = 'aster-offline'; + const keys = {}, principals = []; + const at = Date.now(); + for (const [id, role] of [['aster','caller'], ['amd-device','device']]) { + keys[id] = await crypto.subtle.generateKey('Ed25519', true, ['sign','verify']); + principals.push({ id, role, device: 'amd', publicKey: b64url(await crypto.subtle.exportKey('raw', keys[id].publicKey)), + issuedAt: at - 1000, expiresAt: at + 120000, revoked: false, scopes: [...operations] }); + } + const mf = new Miniflare({ name: 'aster-cli-offline', host: '127.0.0.1', modules: true, + scriptPath: fileURLToPath(new URL('./worker.mjs', import.meta.url)), modulesRules: [{ type: 'ESModule', include: ['**/*.mjs'] }], + compatibilityDate: '2026-07-30', bindings: { ENABLED: 'true', BRIDGE_REGISTRY: JSON.stringify({ audience, principals }) }, + durableObjects: { BRIDGE: { className: 'PrivateLaptopBridge', useSQLite: true } }, durableObjectsPersist: false, + outboundService: () => new Response('offline only', { status: 599 }), + }); + t.after(() => mf.dispose()); + await mf.ready; + const dispatch = async (request, init) => { + assert.equal(init.redirect, 'error'); + return mf.dispatchFetch(request.url, { method: request.method, headers: Object.fromEntries(request.headers), body: await request.text() }); + }; + const device = createClient({ origin, audience, principal: 'amd-device', privateKey: keys['amd-device'].privateKey, + getuid: () => 1000, fetch: dispatch, execute: async operation => samples[operation] }); + const jwk = await crypto.subtle.exportKey('jwk', keys.aster.privateKey); + const config = { origin, audience, principal: 'aster', privateKey: Object.fromEntries(['kty','crv','x','d'].map(k => [k,jwk[k]])) }; + const commands = [['queue-list','--limit','1','--status','queued'], ['queue-health'], ['laptop-health'], ['laptop-diagnostics']]; + for (const command of commands) { + const stdout = [], stderr = []; + const code = await runAster(argv(...command), { getuid: () => 1000, loadConfig: async () => config, + callerFactory: options => { + const caller = createCaller({ ...options, fetch: dispatch }); + return { ...caller, wait: async (handle, waitOptions) => { assert.equal(await device.step(), true); return caller.wait(handle, waitOptions); } }; + }, stdout: text => stdout.push(text), stderr: text => stderr.push(text), + }); + assert.equal(code, 0, stderr.join('')); + assert.deepEqual(stderr, []); + const [accepted, complete] = stdout.map(JSON.parse); + assert.equal(accepted.event, 'accepted'); + assert.equal(complete.id, accepted.handle.id); + assert.deepEqual(complete.result, samples[complete.operation]); + assert.equal(stdout.join('').includes(jwk.d), false); + } +}); diff --git a/pm-stack/private-laptop-bridge/caller.mjs b/pm-stack/private-laptop-bridge/caller.mjs index bfe22c5ad5..e051caf367 100644 --- a/pm-stack/private-laptop-bridge/caller.mjs +++ b/pm-stack/private-laptop-bridge/caller.mjs @@ -30,6 +30,7 @@ export function createCaller({ origin, audience, principal, device, privateKey, async function transport(path, body, signal) { const controller = new AbortController(); let timer, reader, response; + const startedAt = now(); const abort = () => controller.abort(); if (signal?.aborted) throw new CallerError('cancelled'); signal?.addEventListener('abort', abort, { once: true }); @@ -43,7 +44,7 @@ export function createCaller({ origin, audience, principal, device, privateKey, try { const work = async () => { controller.signal.throwIfAborted(); - const request = await signRequest({ origin, audience, principal, privateKey, path, body, now: now() }); + const request = await signRequest({ origin, audience, principal, privateKey, path, body, now: startedAt }); controller.signal.throwIfAborted(); response = await fetchFn(request, { redirect: 'error', signal: controller.signal }); if (controller.signal.aborted) { void response.body?.cancel().catch(() => {}); controller.signal.throwIfAborted(); } @@ -64,7 +65,7 @@ export function createCaller({ origin, audience, principal, device, privateKey, const bytes = new Uint8Array(size); let offset = 0; for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; } const decoded = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); - return { status: response.status, body: decoded }; + return { status: response.status, body: decoded, startedAt }; }; return await Promise.race([work(), aborted]); } catch (error) { @@ -90,10 +91,15 @@ export function createCaller({ origin, audience, principal, device, privateKey, if (['denied', 'quota'].includes(error.code)) throw error; throw new CallerError('submit-outcome-unknown'); } - if (reply.status !== 202 || !exact(reply.body, ['id', 'expiresAt']) || !identifier(reply.body.id) - || !Number.isSafeInteger(reply.body.expiresAt) || reply.body.expiresAt <= now() - || reply.body.expiresAt > now() + 60000) throw new CallerError('submit-outcome-unknown'); - return Object.freeze({ id: reply.body.id, operation, expiresAt: reply.body.expiresAt, args: Object.freeze(requested) }); + if (reply.status !== 202 || !exact(reply.body, ['id', 'expiresAt', 'serverNow']) || !identifier(reply.body.id) + || !Number.isSafeInteger(reply.body.serverNow) || Math.abs(reply.body.serverNow - reply.startedAt) > 30000 + || !Number.isSafeInteger(reply.body.expiresAt) || reply.body.expiresAt <= reply.body.serverNow + || reply.body.expiresAt - reply.body.serverNow > 60000) throw new CallerError('submit-outcome-unknown'); + // The handle deadline is local, not server UTC. Count transport latency + // against the server-issued duration, independently of clock offset. + const expiresAt = reply.startedAt + (reply.body.expiresAt - reply.body.serverNow); + if (expiresAt <= now()) throw new CallerError('submit-outcome-unknown'); + return Object.freeze({ id: reply.body.id, operation, expiresAt, args: Object.freeze(requested) }); } async function read(handle, { signal } = {}) { diff --git a/pm-stack/private-laptop-bridge/client.mjs b/pm-stack/private-laptop-bridge/client.mjs index 4e7584dffd..ddca5068cd 100644 --- a/pm-stack/private-laptop-bridge/client.mjs +++ b/pm-stack/private-laptop-bridge/client.mjs @@ -62,36 +62,48 @@ export function createClient({ origin, audience, principal, privateKey, fetch: f if (url.protocol !== 'https:' || url.origin !== origin || !id(principal) || typeof audience !== 'string' || !audience) throw new Error('invalid-config'); async function send(path, body, signal) { const bounded = signal ? AbortSignal.any([signal, AbortSignal.timeout(requestTimeoutMs)]) : AbortSignal.timeout(requestTimeoutMs); - const request = await signRequest({ origin, audience, principal, privateKey, path, body, now: now() }); + const startedAt = now(); + const request = await signRequest({ origin, audience, principal, privateKey, path, body, now: startedAt }); const response = await fetchFn(request, { redirect: 'error', signal: bounded }); - if ([401,403,410].includes(response.status)) { await response.body?.cancel(); throw new BridgeDenied(); } - if (!response.ok || response.redirected) { await response.body?.cancel(); throw new Error('bridge-unavailable'); } - return readResponse(response, bounded); + if ([401,403,410].includes(response.status)) { void response.body?.cancel().catch(() => {}); throw new BridgeDenied(); } + if (!response.ok || response.redirected) { void response.body?.cancel().catch(() => {}); throw new Error('bridge-unavailable'); } + return { body: await readResponse(response, bounded), startedAt }; } async function step(signal) { - const response = await send('/v1/poll', {}, signal); + const {body: response, startedAt} = await send('/v1/poll', {}, signal); if (!exact(response, ['job'])) throw new Error('invalid-response'); const job = response.job; if (job === null) return false; - if (!exact(job, ['id','lease','operation','args','expiresAt','leaseExpiresAt']) || !id(job.id) || !id(job.lease) || !validateOperation(job.operation, job.args) || !Number.isSafeInteger(job.expiresAt) || job.expiresAt <= now() || job.expiresAt > now() + 60000 || !Number.isSafeInteger(job.leaseExpiresAt) || job.leaseExpiresAt <= now() || job.leaseExpiresAt > now() + 15000 || job.leaseExpiresAt > job.expiresAt) throw new Error('invalid-job'); + if (!exact(job, ['id','lease','operation','args','expiresAt','leaseExpiresAt','serverNow']) || !id(job.id) || !id(job.lease) || !validateOperation(job.operation, job.args) + || !Number.isSafeInteger(job.serverNow) || Math.abs(job.serverNow - startedAt) > 30000 + || !Number.isSafeInteger(job.expiresAt) || job.expiresAt <= job.serverNow || job.expiresAt - job.serverNow > 60000 + || !Number.isSafeInteger(job.leaseExpiresAt) || job.leaseExpiresAt <= job.serverNow || job.leaseExpiresAt - job.serverNow > 15000 + || job.leaseExpiresAt > job.expiresAt) throw new Error('invalid-job'); + // Translate server-relative lifetimes to local deadlines. Starting at the + // request send time conservatively charges both network legs to the budget; + // the clocks may differ by the protocol's authenticated 30-second skew. + const expiresAt = startedAt + (job.expiresAt - job.serverNow); + const leaseExpiresAt = startedAt + (job.leaseExpiresAt - job.serverNow); + if (expiresAt <= now() || leaseExpiresAt <= now()) throw new Error('expired-job'); signal?.throwIfAborted(); - const abort = AbortSignal.timeout(Math.max(1, Math.min(5000, job.leaseExpiresAt - now()))); + const abort = AbortSignal.timeout(Math.max(1, Math.min(5000, leaseExpiresAt - now()))); let onAbort; const expired = new Promise((_, reject) => { onAbort = () => reject(new Error('execution-timeout')); abort.addEventListener('abort', onAbort, { once: true }); }); let result; try { result = await Promise.race([execute(job.operation, job.args), expired]); } finally { abort.removeEventListener('abort', onAbort); } signal?.throwIfAborted(); - if (job.expiresAt <= now() || job.leaseExpiresAt <= now()) throw new Error('expired-job'); + if (expiresAt <= now() || leaseExpiresAt <= now()) throw new Error('expired-job'); if (!validateResult(job.operation, result)) throw new Error('invalid-result'); - const accepted = await send('/v1/result', { id: job.id, lease: job.lease, result }, signal); + const {body: accepted} = await send('/v1/result', { id: job.id, lease: job.lease, result }, signal); if (!exact(accepted, ['accepted']) || accepted.accepted !== true) throw new Error('invalid-ack'); return true; } async function run(signal) { let backoff = 1000; while (!signal?.aborted) { - try { await step(signal); backoff = 1000; await sleep(1000, undefined, { signal }); } + // Reserve request quota for completions; idle polling uses at most 30/min. + try { await step(signal); backoff = 1000; await sleep(2000, undefined, { signal }); } catch (error) { if (signal?.aborted) return; if (error instanceof BridgeDenied) throw error; // Explicit revocation needs owner reconnect. diff --git a/pm-stack/private-laptop-bridge/client.test.mjs b/pm-stack/private-laptop-bridge/client.test.mjs index f8a3180fbf..3d0701f31b 100644 --- a/pm-stack/private-laptop-bridge/client.test.mjs +++ b/pm-stack/private-laptop-bridge/client.test.mjs @@ -12,7 +12,7 @@ const snapshot = () => ({ version:1, fetchedAt:now, available:true, stale:false, const json = body => new Response(JSON.stringify(body), { headers:{'content-type':'application/json'} }); const keys = await crypto.subtle.generateKey('Ed25519', true, ['sign','verify']); const base = { origin:'https://bridge.invalid', audience:'test-bridge', principal:'amd-device', privateKey:keys.privateKey, now:()=>now, getuid:()=>1000 }; -const job = (overrides = {}) => ({ id:'job-1', lease:'lease-1', operation:'laptop.health', args:{}, expiresAt:now+60000, leaseExpiresAt:now+15000, ...overrides }); +const job = (overrides = {}) => ({ id:'job-1', lease:'lease-1', operation:'laptop.health', args:{}, expiresAt:now+60000, leaseExpiresAt:now+15000, serverNow:now, ...overrides }); test('oracle: CLI grammar rejects every undeclared argument before activity', () => { assert.deepEqual(parseArgs(['--help']), {help:true}); @@ -71,7 +71,7 @@ test('oracle: disconnect backoff is bounded and successful reconnect resets it', const abort=new AbortController();const waits=[];let calls=0; const client=createClient({...base,fetch:async()=>{calls++;if(calls<=7)throw new Error('offline');return json({job:null});},sleep:async(ms)=>{waits.push(ms);if(calls===8)abort.abort();}}); await client.run(abort.signal); - assert.deepEqual(waits,[1000,2000,4000,8000,16000,30000,30000,1000]); + assert.deepEqual(waits,[1000,2000,4000,8000,16000,30000,30000,2000]); }); test('oracle: redirects and overlarge responses fail closed', async () => { diff --git a/pm-stack/private-laptop-bridge/freshness.test.mjs b/pm-stack/private-laptop-bridge/freshness.test.mjs new file mode 100644 index 0000000000..bda2bb69be --- /dev/null +++ b/pm-stack/private-laptop-bridge/freshness.test.mjs @@ -0,0 +1,141 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtemp, rm, readFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fetchQueueSnapshot, unavailableQueueSnapshot } from '../aggregator/src/queue.ts'; +import { publishBridgeQueueSnapshot } from '../aggregator/src/bridge-snapshot.ts'; +import { createAdapters, readQueueSnapshot } from './adapters.mjs'; +import { createClient } from './client.mjs'; +import { createCaller } from './caller.mjs'; +import worker, { PrivateLaptopBridge } from './worker.mjs'; +import { operations, statuses, b64url } from './protocol.mjs'; + +const NOW = 1800000000000; +const rawIdle = () => ({ queue: 'repo-health-code-pilot', ...Object.fromEntries(statuses.map(s => [s, 0])) }); +const path = home => join(home, '.local/state/pm-aggregator/bridge-queue.json'); + +// Real broker collector, producer, private file, adapter, client, Worker and +// caller are exercised. Only HTTP broker data and atomic DO storage are fake. +class Storage { + value; tail = Promise.resolve(); + transaction(fn) { + const promise = this.tail.then(async () => { + let value = structuredClone(this.value); + const result = await fn({ get: async () => structuredClone(value), put: async (_, next) => { value = structuredClone(next); }, setAlarm: async () => {} }); + this.value = value; return result; + }); + this.tail = promise.catch(() => {}); return promise; + } +} +async function harness(t) { + let clock = NOW; + t.mock.method(Date, 'now', () => clock); + const home = await mkdtemp(join(tmpdir(), 'bridge-freshness-')); + t.after(() => rm(home, { recursive: true, force: true })); + const keys = {}, principals = []; + for (const [id, role] of [['owner','caller'], ['laptop','device']]) { + keys[id] = await crypto.subtle.generateKey('Ed25519', true, ['sign','verify']); + principals.push({ id, role, device:'amd', publicKey:b64url(await crypto.subtle.exportKey('raw', keys[id].publicKey)), scopes:[...operations], issuedAt:NOW-1000, expiresAt:NOW+1800000, revoked:false }); + } + const env = { ENABLED:'true', BRIDGE_REGISTRY:JSON.stringify({ audience:'freshness-test', principals }) }; + const object = new PrivateLaptopBridge({ storage:new Storage() }, env); + env.BRIDGE = { idFromName:x=>x, get:()=>({ fetch:r=>object.fetch(r) }) }; + const fetch = request => worker.fetch(request, env); + const execute = createAdapters({ readSnapshot:()=>readQueueSnapshot(home), clock:()=>clock }); + const config = { origin:'https://bridge.invalid', audience:'freshness-test', fetch, now:()=>clock }; + const client = createClient({ ...config, principal:'laptop', privateKey:keys.laptop.privateKey, execute, getuid:()=>1000 }); + const caller = createCaller({ ...config, principal:'owner', device:'amd', privateKey:keys.owner.privateKey }); + const collect = (health={ok:true,rows:[rawIdle()]}, list={ok:true,rows:[]}, fetchedAt=clock) => fetchQueueSnapshot('http://synthetic.invalid', 'synthetic-not-a-secret', async url=>({ ok:true,status:200,json:async()=>url.endsWith('/health')?health:list }), ()=>fetchedAt); + const publish = source => publishBridgeQueueSnapshot(source, '1', home, clock); + const roundtrip = async (list=false) => { + const handle = list ? await caller.fleetQueueList({limit:20}) : await caller.fleetQueueHealth(); + assert.equal(await client.step(), true); + return caller.read(handle); + }; + return {home,collect,publish,roundtrip,execute,client,caller,setTime:value=>{clock=value;}}; +} + +test('fresh explicit zero counters are observed idle; empty list stays incomplete and total unknown', async t => { + const h=await harness(t); const source=await h.collect(); + assert.equal(source.bridgeVerified,true); + await h.publish(source); + const health=await h.roundtrip(); + assert.deepEqual(health.result,{ok:true,data:{...Object.fromEntries(statuses.map(s=>[s,0])),fetchedAt:NOW}}); + const list=await h.roundtrip(true); + assert.deepEqual(list.result,{ok:true,data:{tasks:[],complete:false,total:null,fetchedAt:NOW}}); + assert.equal(JSON.parse(await readFile(path(h.home),'utf8')).available,true); +}); + +test('malformed raw broker omission cannot become idle through legacy zero coercion', async t => { + const h=await harness(t); + const cases=[{}, {ok:true}, {ok:true,rows:[{queue:'code'}]}, {ok:true,rows:[{...rawIdle(),queued:null}]}, {ok:true,rows:[{...rawIdle(),queued:-1}]}, {ok:true,rows:[{...rawIdle(),queue:''}]}, {ok:true,rows:[rawIdle(),rawIdle()]}]; + for(const health of cases) { + const source=await h.collect(health); + assert.equal(source.bridgeVerified,false); + await h.publish(source); + assert.deepEqual((await h.roundtrip()).result,{ok:false,error:'unavailable'}); + // Advance quota window; never mask a denial as evidence of stale rejection. + h.setTime(NOW+60000); + } +}); + +test('missing or malformed list envelope and unverified/truthy source never release idle', async t => { + const h=await harness(t); + for(const list of [{}, {ok:true}, {rows:[]}, {ok:true,rows:null}]) { + const source=await h.collect(undefined,list); + assert.equal(source.bridgeVerified,false); + await h.publish(source); + assert.deepEqual((await h.roundtrip(true)).result,{ok:false,error:'unavailable'}); + } + const valid=await h.collect(); + for(const mutation of [{bridgeVerified:undefined},{available:'yes'},{stale:undefined},{errors:['private-error']}]) { + await h.publish({...valid,...mutation}); + assert.deepEqual(await h.execute('fleet.queue.health',{}),{ok:false,error:'unavailable'}); + } +}); + +test('idle snapshot freshness boundary is explicit: exactly five minutes allowed, one ms later unavailable', async t => { + const h=await harness(t); await h.publish(await h.collect()); + h.setTime(NOW+300000); + assert.equal((await h.roundtrip()).result.ok,true); + h.setTime(NOW+300001); + assert.deepEqual((await h.roundtrip()).result,{ok:false,error:'unavailable'}); +}); + +test('missing file and known unavailable marker are not an observed idle queue', async t => { + const h=await harness(t); + assert.deepEqual((await h.roundtrip()).result,{ok:false,error:'unavailable'}); + await h.publish(await h.collect()); + assert.equal((await h.roundtrip()).result.ok,true); + await h.publish(unavailableQueueSnapshot(NOW,'not-exported')); + assert.deepEqual((await h.roundtrip()).result,{ok:false,error:'unavailable'}); +}); + +test('failed publisher leaves prior observation readable only until original TTL, never refreshes its timestamp', async t => { + const h=await harness(t); await h.publish(await h.collect()); + h.setTime(NOW+10000); + // A producer crash before atomic rename preserves the previous observation. + await assert.rejects(h.publish(null)); + const retained=await h.roundtrip(); + assert.equal(retained.result.ok,true);assert.equal(retained.result.data.fetchedAt,NOW); + h.setTime(NOW+300001); + assert.deepEqual((await h.roundtrip()).result,{ok:false,error:'unavailable'}); +}); + +test('future source timestamps never reach caller as successful idle, including tolerated device skew', async t => { + const h=await harness(t); + await h.publish(await h.collect(undefined,undefined,NOW+1)); + const handle=await h.caller.fleetQueueHealth();await h.client.step(); + await assert.rejects(h.caller.read(handle),error=>error.code==='stale-result'); + await h.publish(await h.collect(undefined,undefined,NOW+5001)); + assert.deepEqual((await h.roundtrip()).result,{ok:false,error:'unavailable'}); +}); + +test('result becoming stale after device completion is denied at read rather than returned idle', async t => { + const h=await harness(t); await h.publish(await h.collect()); + h.setTime(NOW+299999); + const handle=await h.caller.fleetQueueHealth();await h.client.step(); + h.setTime(NOW+300001); + await assert.rejects(h.caller.read(handle),error=>error.code==='denied'); +}); diff --git a/pm-stack/private-laptop-bridge/gateway.mjs b/pm-stack/private-laptop-bridge/gateway.mjs new file mode 100644 index 0000000000..3e48509e5f --- /dev/null +++ b/pm-stack/private-laptop-bridge/gateway.mjs @@ -0,0 +1,52 @@ +// Private Gateway Forward RPC ingress. No public HTTP management entrypoint. +// Context contract: https://developers.cloudflare.com/cloudflare-one/traffic-controls/integrate-workers/available-context/ +import { WorkerEntrypoint } from 'cloudflare:workers'; +import bridge from './worker.mjs'; +export { PrivateLaptopBridge } from './worker.mjs'; + +const paths = new Set(['/v1/call', '/v1/poll', '/v1/result', '/v1/read']); +const uuid = value => typeof value === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(value); +const deny = (status, error) => { + console.warn(JSON.stringify({event: 'bridge.gateway-denied', status, code: error})); + return Response.json({error}, {status, headers: {'cache-control': 'no-store', 'x-content-type-options': 'nosniff'}}); +}; +function configuration(env) { + const {GATEWAY_HOST: host, GATEWAY_ACCOUNT_ID: account, GATEWAY_POLICY_ID: policy, GATEWAY_IDENTITY_EMAIL: email, GATEWAY_POSTURE_ID: posture} = env; + // All fields are owner-supplied non-secret identifiers. Blank placeholders deny. + if (typeof host !== 'string' || host.length > 253 || host.split('.').some(label => label.length > 63) || !/^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,63}$/.test(host) || typeof account !== 'string' || !/^[0-9a-f]{32}$/.test(account) || !uuid(policy) || !uuid(posture) || typeof email !== 'string' || email.length > 254 || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) return null; + return {host, account, policy, email, posture}; +} +function allowedUrl(raw, host) { + try { + const url = new URL(raw); + return url.protocol === 'https:' && url.hostname === host && !url.port && !url.username && !url.password && !url.search && !url.hash && paths.has(url.pathname); + } catch { return false; } +} + +export class GatewayMiddleware extends WorkerEntrypoint { + async handle(request, context, _next) { + // _next is deliberately never invoked: no upstream origin, generic proxy, + // network fallback, or route around this authorization decision exists here. + if (this.env.ENABLED !== 'true') return deny(503, 'disabled'); + const config = configuration(this.env); + if (!config) return deny(503, 'gateway-configuration'); + if (request.method !== 'POST' || request.headers.has('upgrade') || !allowedUrl(request.url, config.host)) return deny(403, 'gateway-route'); + try { + if (!context || context.accountId !== config.account || context.policyId !== config.policy || context.host !== config.host || (context.sni !== undefined && context.sni !== config.host) || !allowedUrl(context.uri, config.host) || new URL(context.uri).pathname !== new URL(request.url).pathname) return deny(403, 'gateway-context'); + // These are trusted Gateway RPC getters, never request headers. A Worker + // service binding to this entrypoint is privileged and must not be granted + // to an untrusted Worker: that Worker could fabricate this context. + let timer; + try { + const deadline = new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('deadline')), 3000); }); + const [identity, posture] = await Promise.race([Promise.all([context.identity(), context.devicePosture()]), deadline]); + if (!identity || identity.email !== config.email || !Array.isArray(posture?.checks?.passed) || !posture.checks.passed.includes(config.posture)) return deny(403, 'gateway-identity'); + } finally { clearTimeout(timer); } + } catch { return deny(503, 'gateway-context-unavailable'); } + // Independent signed caller/device authentication, replay and scope checks + // still run inside the existing Durable Object control plane. + return bridge.fetch(request, this.env); + } +} + +export default {fetch() { return deny(403, 'private-rpc-only'); }}; diff --git a/pm-stack/private-laptop-bridge/gateway.test.mjs b/pm-stack/private-laptop-bridge/gateway.test.mjs new file mode 100644 index 0000000000..47a57c7604 --- /dev/null +++ b/pm-stack/private-laptop-bridge/gateway.test.mjs @@ -0,0 +1,97 @@ +// Real Workers RPC + SQLite Durable Object tests. The Gateway metadata provider +// is synthetic; these tests do not prove Cloudflare Gateway/WARP/DNS enrollment. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { Miniflare } from 'miniflare'; +import { b64url, operations, signRequest } from './protocol.mjs'; +const here = dirname(fileURLToPath(import.meta.url)); +const host = 'private-bridge-staging.invalid'; +const account = 'a'.repeat(32), policy = '11111111-1111-1111-1111-111111111111', posture = '22222222-2222-2222-2222-222222222222'; +const email = 'synthetic-owner@example.invalid'; +const harnessSource = ` +export default { + async fetch(request, env) { + const mode = request.headers.get('x-test-mode') || 'normal'; + const url = new URL(request.url); + const context = { + accountId: '${account}', policyId: '${policy}', host: '${host}', uri: request.url, sni: '${host}', + identity: async () => { + if (mode === 'identity-hang') return new Promise(() => {}); + if (mode === 'identity-error') throw new Error('synthetic identity failure'); + if (mode === 'identity-missing') return null; + return {email: mode === 'identity-wrong' ? 'other@example.invalid' : '${email}'}; + }, + devicePosture: async () => { + if (mode === 'posture-error') throw new Error('synthetic posture failure'); + return {checks:{passed: mode === 'posture-missing' ? [] : ['${posture}']}}; + } + }; + if (mode === 'account-wrong') context.accountId = 'b'.repeat(32); + if (mode === 'policy-wrong') context.policyId = '33333333-3333-3333-3333-333333333333'; + if (mode === 'context-host-wrong') context.host = 'other.invalid'; + if (mode === 'context-uri-wrong') context.uri = 'https://${host}/v1/poll'; + if (mode === 'context-sni-wrong') context.sni = 'other.invalid'; + if (mode === 'identity-header') { context.identity = async () => null; const headers = new Headers(request.headers); headers.set('cf-access-authenticated-user-email','${email}'); request = new Request(request, {headers}); } + let nextCalls = 0; + const response = await env.PRIVATE.handle(request, mode === 'context-missing' ? null : context, async () => {nextCalls++; throw new Error('next must never run');}); + const headers = new Headers(response.headers); headers.set('x-test-next-calls', String(nextCalls)); + return new Response(response.body, {status: response.status, headers}); + } +};`; +async function harness(t, overrides = {}) { + const keys = {}, principals = []; + for (const [id, role] of [['caller','caller'], ['device','device']]) { + keys[id] = await crypto.subtle.generateKey('Ed25519', true, ['sign','verify']); + principals.push({id, role, device:'amd', publicKey:b64url(await crypto.subtle.exportKey('raw', keys[id].publicKey)), scopes:[...operations], issuedAt:Date.now()-1000, expiresAt:Date.now()+120000, revoked:false}); + } + const mf = new Miniflare({host:'127.0.0.1', workers:[ + {name:'gateway-harness', modules:true, script:harnessSource, compatibilityDate:'2026-07-30', serviceBindings:{PRIVATE:{name:'private-bridge',entrypoint:'GatewayMiddleware'}}, outboundService:() => {throw new Error('outbound forbidden');}}, + {name:'private-bridge', modules:true, scriptPath:join(here,'gateway.mjs'), modulesRules:[{type:'ESModule',include:['**/*.mjs']}], compatibilityDate:'2026-07-30', bindings:{ENABLED:'true', BRIDGE_REGISTRY:JSON.stringify({audience:'gateway-offline',principals}), GATEWAY_HOST:host,GATEWAY_ACCOUNT_ID:account,GATEWAY_POLICY_ID:policy,GATEWAY_IDENTITY_EMAIL:email,GATEWAY_POSTURE_ID:posture,...overrides},durableObjects:{BRIDGE:{className:'PrivateLaptopBridge',useSQLite:true}},outboundService:() => {throw new Error('outbound forbidden');}} + ]}); + await mf.ready; + t.after(() => mf.dispose()); + async function send(id, path, body, mode = 'normal', url = `https://${host}${path}`, method = 'POST') { + const request = await signRequest({origin:`https://${host}`,audience:'gateway-offline',principal:id,privateKey:keys[id].privateKey,path,body}); + request.headers.set('x-test-mode',mode); + const response = await mf.dispatchFetch(url,{method,headers:Object.fromEntries(request.headers),...(method !== 'GET' ? {body:await request.text()} : {})}); + assert.equal(response.headers.get('x-test-next-calls'),'0'); + return {status:response.status,body:await response.json()}; + } + return {mf,send,keys}; +} + +test('private Gateway RPC reaches signed DO normal flow; ordinary HTTP is always denied',async t=>{ + const h=await harness(t); + const submitted=await h.send('caller','/v1/call',{device:'amd',operation:'laptop.health',args:{}}); + assert.equal(submitted.status,202,JSON.stringify(submitted)); + const polled=await h.send('device','/v1/poll',{});assert.equal(polled.status,200); + const {job}=polled.body;assert.equal(job.id,submitted.body.id); + const result={ok:true,data:{queueBroker:'up'}}; + assert.equal((await h.send('device','/v1/result',{id:job.id,lease:job.lease,result})).status,200); + assert.deepEqual((await h.send('caller','/v1/read',{id:job.id})).body,{status:'complete',result}); + const direct=await h.mf.getWorker('private-bridge'); + const signed=await signRequest({origin:`https://${host}`,audience:'gateway-offline',principal:'caller',privateKey:h.keys.caller.privateKey,path:'/v1/call',body:{device:'amd',operation:'laptop.health',args:{}}}); + const response=await direct.fetch(signed.url,{method:'POST',headers:Object.fromEntries(signed.headers),body:await signed.text()}); + assert.equal(response.status,403);assert.deepEqual(await response.json(),{error:'private-rpc-only'}); +}); + +test('private Gateway RPC rejects route and trusted-context mismatches without next',async t=>{ + const h=await harness(t); + for(const mode of ['account-wrong','policy-wrong','context-host-wrong','context-uri-wrong','context-sni-wrong','context-missing','identity-missing','identity-wrong','posture-missing','identity-header']) { + assert.equal((await h.send('caller','/v1/call',{device:'amd',operation:'laptop.health',args:{}},mode)).status,403,mode); + } + for(const mode of ['identity-error','posture-error','identity-hang']) assert.equal((await h.send('caller','/v1/call',{},mode)).status,503,mode); + for(const url of [`http://${host}/v1/call`,`https://other.invalid/v1/call`,`https://${host}:8443/v1/call`,`https://${host}/exec`,`https://${host}/v1/call?extra=1`]) assert.equal((await h.send('caller','/v1/call',{},'normal',url)).status,403,url); + assert.equal((await h.send('caller','/v1/call',{},'normal',`https://${host}/v1/call`,'GET')).status,403); + // Gateway authorization cannot replace the independent signed role check. + assert.equal((await h.send('caller','/v1/poll',{})).status,403); +}); + +test('private Gateway deployment remains disabled or fails closed on incomplete identifiers',async t=>{ + const disabled=await harness(t,{ENABLED:'false'}); + assert.equal((await disabled.send('caller','/v1/call',{})).status,503); + const incomplete=await harness(t,{GATEWAY_POLICY_ID:''}); + assert.equal((await incomplete.send('caller','/v1/call',{})).status,503); +}); diff --git a/pm-stack/private-laptop-bridge/package-lock.json b/pm-stack/private-laptop-bridge/package-lock.json index 546d61260f..96675a798c 100644 --- a/pm-stack/private-laptop-bridge/package-lock.json +++ b/pm-stack/private-laptop-bridge/package-lock.json @@ -6,12 +6,39 @@ "": { "name": "private-laptop-bridge", "devDependencies": { - "miniflare": "4.20260730.0" + "miniflare": "4.20260730.0", + "wrangler": "4.166.0" }, "engines": { "node": ">=24" } }, + "node_modules/@cloudflare/kv-asset-handler": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/@cloudflare/kv-asset-handler/-/kv-asset-handler-0.5.1.tgz", + "integrity": "sha512-48OysfSW3MkQY1XjkhkpPkgrEkOvgfoyHzA2eyX5wpzFpijC02uWigv3hkNdJdT3C7ybW/U17yYHXeR68pLeww==", + "dev": true, + "license": "MIT OR Apache-2.0", + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@cloudflare/unenv-preset": { + "version": "2.16.2", + "resolved": "https://registry.npmjs.org/@cloudflare/unenv-preset/-/unenv-preset-2.16.2.tgz", + "integrity": "sha512-JBP1+Z7ZSNG/d4mRP+y8VC5dka3tZVMLEZRvS+rzQ4DGV1EoxRFQckcJTTkXbHSQiTj0DtNI01Zwb/V2fX0mvQ==", + "dev": true, + "license": "MIT OR Apache-2.0", + "peerDependencies": { + "unenv": "2.0.0-rc.24", + "workerd": ">1.20260305.0 <2.0.0-0" + }, + "peerDependenciesMeta": { + "workerd": { + "optional": true + } + } + }, "node_modules/@cloudflare/workerd-darwin-64": { "version": "1.20260730.1", "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-64/-/workerd-darwin-64-1.20260730.1.tgz", @@ -97,6 +124,37 @@ "node": ">=16" } }, + "node_modules/@cloudflare/workers-utils": { + "version": "0.56.0", + "resolved": "https://registry.npmjs.org/@cloudflare/workers-utils/-/workers-utils-0.56.0.tgz", + "integrity": "sha512-Fw3/zR+pQp+5hKn1CHIRkCYz49fyAb2qRqCq01jBGqlKL0rRnZyXYD4j0h9cjaWPYYQUOe5y6L7BNp2ZwsHg5A==", + "dev": true, + "license": "MIT OR Apache-2.0", + "dependencies": { + "@cspotcode/source-map-support": "0.8.1", + "chalk": "5.3.0", + "dotenv": "16.3.1", + "undici": "7.30.2" + }, + "peerDependencies": { + "vitest": "^4.1.0 || ^5.0.0" + }, + "peerDependenciesMeta": { + "vitest": { + "optional": true + } + } + }, + "node_modules/@cloudflare/workers-utils/node_modules/undici": { + "version": "7.30.2", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.30.2.tgz", + "integrity": "sha512-mLyPQnHwUxaM/rideoK/+KL8DaAJLRl4aBCfmX444aCSLnIaomqPLtNRe2jdCYcsk5wZzXrDIQC8ZeYNRAYyIA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.18.1" + } + }, "node_modules/@cspotcode/source-map-support": { "version": "0.8.1", "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", @@ -121,329 +179,2185 @@ "tslib": "^2.4.0" } }, - "node_modules/@img/colour": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", - "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==", + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "cpu": [ + "ppc64" + ], "dev": true, "license": "MIT", + "optional": true, + "os": [ + "aix" + ], "engines": { "node": ">=18" } }, - "node_modules/@img/sharp-darwin-arm64": { - "version": "0.35.2", - "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.2.tgz", - "integrity": "sha512-eEieHsMksAW4IiO5NzauESRl2D2qz3J/kwUxUrSfV06A93eEaRfMpHXyUb1mAqrR7i8U9A0GRqE9pjn6u1Jjpg==", + "node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", "cpu": [ - "arm64" + "arm" ], "dev": true, - "license": "Apache-2.0", + "license": "MIT", "optional": true, "os": [ - "darwin" + "android" ], "engines": { - "node": ">=20.9.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-darwin-arm64": "1.3.1" + "node": ">=18" } }, - "node_modules/@img/sharp-darwin-x64": { - "version": "0.35.2", - "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.2.tgz", - "integrity": "sha512-BaktuGPCeHJMARpodR8jK4uKiZrPAy9WrfQW0sdI37clracq8Bp01AYS3SZgi5FS/y5twa9t4+LIuuxQjqRrWw==", + "node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", "cpu": [ - "x64" + "arm64" ], "dev": true, - "license": "Apache-2.0", + "license": "MIT", "optional": true, "os": [ - "darwin" + "android" ], "engines": { - "node": ">=20.9.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-darwin-x64": "1.3.1" + "node": ">=18" } }, - "node_modules/@img/sharp-freebsd-wasm32": { - "version": "0.35.2", - "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.2.tgz", - "integrity": "sha512-YoAxdnd8hPUkvLHd3bWY+YA8nw3xM/RyRopYucNsWHVSan8NLVM3X2volsfoRDcXdUJPg6tXahSd7HXPK7lRnw==", + "node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "cpu": [ + "x64" + ], "dev": true, - "license": "Apache-2.0", + "license": "MIT", "optional": true, "os": [ - "freebsd" + "android" ], - "dependencies": { - "@img/sharp-wasm32": "0.35.2" - }, "engines": { - "node": ">=20.9.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" + "node": ">=18" } }, - "node_modules/@img/sharp-libvips-darwin-arm64": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.1.tgz", - "integrity": "sha512-4V/M3roRMTYjiwZY9IOVQOE8OyeCxFAkYmyZDrZl51uOKjibm3oeEJ4WAmLxutAfzFbC9jqUiPs2gbnGflH+7g==", + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", "cpu": [ "arm64" ], "dev": true, - "license": "LGPL-3.0-or-later", + "license": "MIT", "optional": true, "os": [ "darwin" ], - "funding": { - "url": "https://opencollective.com/libvips" + "engines": { + "node": ">=18" } }, - "node_modules/@img/sharp-libvips-darwin-x64": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.1.tgz", - "integrity": "sha512-c0/DxItpJv2+dGhgycJBBgotdqruGYDvA79drdh0MD1dFpy7JzJ/PlXwi1H4rFf0eTy8tgbI91aHDnZIceY3jQ==", + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", "cpu": [ "x64" ], "dev": true, - "license": "LGPL-3.0-or-later", + "license": "MIT", "optional": true, "os": [ "darwin" ], - "funding": { - "url": "https://opencollective.com/libvips" + "engines": { + "node": ">=18" } }, - "node_modules/@img/sharp-libvips-linux-arm": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.1.tgz", - "integrity": "sha512-aGGy9aWzXgHBG7HNyQPWorZthlp7+x6fDRoPAQbGO3ThcttuTyKIx3NuSHb6zb4gBNq6/yNn9f1cy9nFKS/Vmg==", + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", "cpu": [ - "arm" + "arm64" ], "dev": true, - "license": "LGPL-3.0-or-later", + "license": "MIT", "optional": true, "os": [ - "linux" + "freebsd" ], - "funding": { - "url": "https://opencollective.com/libvips" + "engines": { + "node": ">=18" } }, - "node_modules/@img/sharp-libvips-linux-arm64": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.1.tgz", - "integrity": "sha512-JznefmcK9j1JKPz8AkQDh89kjojubyfOasWBPKfzMIhPwsgDy9evpE/naJTXXXmghS1iFwR8u/kTwh/I2/+GCw==", + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", "cpu": [ - "arm64" + "x64" ], "dev": true, - "license": "LGPL-3.0-or-later", + "license": "MIT", "optional": true, "os": [ - "linux" + "freebsd" ], - "funding": { - "url": "https://opencollective.com/libvips" + "engines": { + "node": ">=18" } }, - "node_modules/@img/sharp-libvips-linux-ppc64": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.1.tgz", - "integrity": "sha512-1EkwGNCZk6iWNCMWqrvdJ+r1j0PT1zIz60CNPhYnJlK/zyeWqlsPZIe+ocBVqPF8k/Ssee/NCk+tE9Ryrko6ng==", + "node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", "cpu": [ - "ppc64" + "arm" ], "dev": true, - "license": "LGPL-3.0-or-later", + "license": "MIT", "optional": true, "os": [ "linux" ], - "funding": { - "url": "https://opencollective.com/libvips" + "engines": { + "node": ">=18" } }, - "node_modules/@img/sharp-libvips-linux-riscv64": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.1.tgz", - "integrity": "sha512-Ilays+w2bXdnxzxtQdmXR62u8o8GYa3eL4+Gr+1KiE4xperMZUslRaVPJwwPkzlHEjGfXAfRVAa/7CYCtSqsBw==", + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", "cpu": [ - "riscv64" + "arm64" ], "dev": true, - "license": "LGPL-3.0-or-later", + "license": "MIT", "optional": true, "os": [ "linux" ], - "funding": { - "url": "https://opencollective.com/libvips" + "engines": { + "node": ">=18" } }, - "node_modules/@img/sharp-libvips-linux-s390x": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.1.tgz", - "integrity": "sha512-VfBwVHQTbRoj4XlpA/KLZ7ltgMpz+4WSejFzQ+GnoImjo1PtEJ59QB2qR1xQEeRPYIkNrPIm2L4cICMvz4C2ew==", + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", "cpu": [ - "s390x" + "ia32" ], "dev": true, - "license": "LGPL-3.0-or-later", + "license": "MIT", "optional": true, "os": [ "linux" ], - "funding": { - "url": "https://opencollective.com/libvips" + "engines": { + "node": ">=18" } }, - "node_modules/@img/sharp-libvips-linux-x64": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.1.tgz", - "integrity": "sha512-+c8ukgwU62DS54nCAjw7keOfHUkmr0B5QHEdcOqRnodF/MNXJbVI8Eopoj4B/0H8Asr65I+A4Amrn7a85/md6A==", + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", "cpu": [ - "x64" + "loong64" ], "dev": true, - "license": "LGPL-3.0-or-later", + "license": "MIT", "optional": true, "os": [ "linux" ], - "funding": { - "url": "https://opencollective.com/libvips" + "engines": { + "node": ">=18" } }, - "node_modules/@img/sharp-libvips-linuxmusl-arm64": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.1.tgz", - "integrity": "sha512-qlKb/pwbkAi1WMsJrYHk7CuDrd12s27U2QnRhFYUoJNrRCmkosMTttuRFat/DDB3IlDm5qE1TJgZ4JDnHX8Ldw==", + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", "cpu": [ - "arm64" + "mips64el" ], "dev": true, - "license": "LGPL-3.0-or-later", + "license": "MIT", "optional": true, "os": [ "linux" ], - "funding": { - "url": "https://opencollective.com/libvips" + "engines": { + "node": ">=18" } }, - "node_modules/@img/sharp-libvips-linuxmusl-x64": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.1.tgz", - "integrity": "sha512-yO21HwoUVLN8Qa+/SBjQLMYwBWAVJjeGPNe+hc0OUeMeifEtJqu5a1c4HayE1nNpDih9y3/KkoltfkDodmKAlg==", + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", "cpu": [ - "x64" + "ppc64" ], "dev": true, - "license": "LGPL-3.0-or-later", + "license": "MIT", "optional": true, "os": [ "linux" ], - "funding": { - "url": "https://opencollective.com/libvips" + "engines": { + "node": ">=18" } }, - "node_modules/@img/sharp-linux-arm": { - "version": "0.35.2", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.2.tgz", - "integrity": "sha512-SE4kzF2mepn6z+6E7L6lsV8FzuLL6IPQdyX8ZiwROAG/G8td+hP/m7FsFPwidtrF19gvajuC9l6TxAVcsA4S7A==", + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", "cpu": [ - "arm" + "riscv64" ], "dev": true, - "license": "Apache-2.0", + "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { - "node": ">=20.9.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-linux-arm": "1.3.1" + "node": ">=18" } }, - "node_modules/@img/sharp-linux-arm64": { - "version": "0.35.2", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.2.tgz", - "integrity": "sha512-af12Pnd0ZGu2HfP8NayB0kk6eC/lrfbQE6HlR4jD+34wdJ1Vw9TF6TMn6ZvffT+WgqVsl0hRbmNvz2u/23VmwA==", + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", "cpu": [ - "arm64" + "s390x" ], "dev": true, - "license": "Apache-2.0", + "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { - "node": ">=20.9.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-linux-arm64": "1.3.1" + "node": ">=18" } }, - "node_modules/@img/sharp-linux-ppc64": { - "version": "0.35.2", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.2.tgz", - "integrity": "sha512-hYSBm7zcNtDCozCxQHYZJiu63b/bXsgRZuOxCIBZsStMM9Vap47iFHdbX4kCvQsblPB/k+clhELpdQJHQLSHvg==", + "node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", "cpu": [ - "ppc64" + "x64" ], "dev": true, - "license": "Apache-2.0", + "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { - "node": ">=20.9.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/colour": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", + "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.2.tgz", + "integrity": "sha512-eEieHsMksAW4IiO5NzauESRl2D2qz3J/kwUxUrSfV06A93eEaRfMpHXyUb1mAqrR7i8U9A0GRqE9pjn6u1Jjpg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.3.1" + } + }, + "node_modules/@img/sharp-darwin-x64": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.2.tgz", + "integrity": "sha512-BaktuGPCeHJMARpodR8jK4uKiZrPAy9WrfQW0sdI37clracq8Bp01AYS3SZgi5FS/y5twa9t4+LIuuxQjqRrWw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.3.1" + } + }, + "node_modules/@img/sharp-freebsd-wasm32": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.2.tgz", + "integrity": "sha512-YoAxdnd8hPUkvLHd3bWY+YA8nw3xM/RyRopYucNsWHVSan8NLVM3X2volsfoRDcXdUJPg6tXahSd7HXPK7lRnw==", + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "dependencies": { + "@img/sharp-wasm32": "0.35.2" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.1.tgz", + "integrity": "sha512-4V/M3roRMTYjiwZY9IOVQOE8OyeCxFAkYmyZDrZl51uOKjibm3oeEJ4WAmLxutAfzFbC9jqUiPs2gbnGflH+7g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.1.tgz", + "integrity": "sha512-c0/DxItpJv2+dGhgycJBBgotdqruGYDvA79drdh0MD1dFpy7JzJ/PlXwi1H4rFf0eTy8tgbI91aHDnZIceY3jQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.1.tgz", + "integrity": "sha512-aGGy9aWzXgHBG7HNyQPWorZthlp7+x6fDRoPAQbGO3ThcttuTyKIx3NuSHb6zb4gBNq6/yNn9f1cy9nFKS/Vmg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.1.tgz", + "integrity": "sha512-JznefmcK9j1JKPz8AkQDh89kjojubyfOasWBPKfzMIhPwsgDy9evpE/naJTXXXmghS1iFwR8u/kTwh/I2/+GCw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-ppc64": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.1.tgz", + "integrity": "sha512-1EkwGNCZk6iWNCMWqrvdJ+r1j0PT1zIz60CNPhYnJlK/zyeWqlsPZIe+ocBVqPF8k/Ssee/NCk+tE9Ryrko6ng==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-riscv64": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.1.tgz", + "integrity": "sha512-Ilays+w2bXdnxzxtQdmXR62u8o8GYa3eL4+Gr+1KiE4xperMZUslRaVPJwwPkzlHEjGfXAfRVAa/7CYCtSqsBw==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.1.tgz", + "integrity": "sha512-VfBwVHQTbRoj4XlpA/KLZ7ltgMpz+4WSejFzQ+GnoImjo1PtEJ59QB2qR1xQEeRPYIkNrPIm2L4cICMvz4C2ew==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.1.tgz", + "integrity": "sha512-+c8ukgwU62DS54nCAjw7keOfHUkmr0B5QHEdcOqRnodF/MNXJbVI8Eopoj4B/0H8Asr65I+A4Amrn7a85/md6A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.1.tgz", + "integrity": "sha512-qlKb/pwbkAi1WMsJrYHk7CuDrd12s27U2QnRhFYUoJNrRCmkosMTttuRFat/DDB3IlDm5qE1TJgZ4JDnHX8Ldw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.1.tgz", + "integrity": "sha512-yO21HwoUVLN8Qa+/SBjQLMYwBWAVJjeGPNe+hc0OUeMeifEtJqu5a1c4HayE1nNpDih9y3/KkoltfkDodmKAlg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-arm": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.2.tgz", + "integrity": "sha512-SE4kzF2mepn6z+6E7L6lsV8FzuLL6IPQdyX8ZiwROAG/G8td+hP/m7FsFPwidtrF19gvajuC9l6TxAVcsA4S7A==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.3.1" + } + }, + "node_modules/@img/sharp-linux-arm64": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.2.tgz", + "integrity": "sha512-af12Pnd0ZGu2HfP8NayB0kk6eC/lrfbQE6HlR4jD+34wdJ1Vw9TF6TMn6ZvffT+WgqVsl0hRbmNvz2u/23VmwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.3.1" + } + }, + "node_modules/@img/sharp-linux-ppc64": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.2.tgz", + "integrity": "sha512-hYSBm7zcNtDCozCxQHYZJiu63b/bXsgRZuOxCIBZsStMM9Vap47iFHdbX4kCvQsblPB/k+clhELpdQJHQLSHvg==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { "@img/sharp-libvips-linux-ppc64": "1.3.1" } }, - "node_modules/@img/sharp-linux-riscv64": { - "version": "0.35.2", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.2.tgz", - "integrity": "sha512-qQt0Kc13+Hoan/Awq/qMSQw3L+RI1NCRPgD5cUJ/1WSSmIoysLOc72jlRM3E0OHN9Yr313jgeQ2T+zW+F03QFA==", + "node_modules/@img/sharp-linux-riscv64": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.2.tgz", + "integrity": "sha512-qQt0Kc13+Hoan/Awq/qMSQw3L+RI1NCRPgD5cUJ/1WSSmIoysLOc72jlRM3E0OHN9Yr313jgeQ2T+zW+F03QFA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-riscv64": "1.3.1" + } + }, + "node_modules/@img/sharp-linux-s390x": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.2.tgz", + "integrity": "sha512-E4fLLfRPzDLlEeDaTzI98OFLcv++WL5ChLLMwPoVd0CIoZQqupBSNbOisPL5am9XsbQ9T84+iiMpUvbFtkunbA==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.3.1" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.2.tgz", + "integrity": "sha512-gi0zFJJRLswfCZmHtJdikXPOc5u7qamSOS3NHedLqLd4W8Q0NqjdBr6TTRIgsfFjqfTsHFgdfvJ9LwqSgcHiAA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.3.1" + } + }, + "node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.2.tgz", + "integrity": "sha512-siWbOW1u6HFnFLrp0waKyW7VEf7jYvcDWdrXEFa8AkdAQgEvuu5Fz8/Y70w9EeqAdwDtfU012BhEHHaDqvQNzg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.3.1" + } + }, + "node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.2.tgz", + "integrity": "sha512-YBqMMcjDi4QGYiSn4vNOYBhmlC4z5AXqkOUUqI2e0AFA4urNv4ESgOgwNl3K+4etQhha0twXlzeF20bbULm9Yg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.3.1" + } + }, + "node_modules/@img/sharp-wasm32": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.2.tgz", + "integrity": "sha512-Mrv4JQNYVQ94xH+jzZ9r+gowleN8mv2FTgKT+PI6bx5C0G8TdNYndu161pg2i7uoBwxy2ImPMHrJOM2LZef7Bw==", + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.11.1" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-webcontainers-wasm32": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.2.tgz", + "integrity": "sha512-QNV27pxs9wpApEiCfvHM1RDoP1w1+2KrUWWDPEhEwg+latvOrfuhWrHWZKwdSFwU6jh3myjw/yOCRsUIuOft3g==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@img/sharp-wasm32": "0.35.2" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-arm64": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.2.tgz", + "integrity": "sha512-BiVRYc/t6/Vl3e1hBx0hugG4oN9Pydf4fgMSpxTQJmwGUg/YoXTWHiFeRymHfCZzifxu4F4rpk/I67D0LQ20wQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-ia32": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.2.tgz", + "integrity": "sha512-YYEhx9PImCC7T0tI8JDMi4DB9LwLCXCU5OWNYEXAxh5Q1ShKkyC6byxzoBJ3gEFDnH2lQckWuDe70G7mB2XJog==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-x64": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.2.tgz", + "integrity": "sha512-imoOyBcoM/iiUr4J6VPpCNjPnjvP/Gks95898yB8YqoGGYmHYbOyCuNv9FMhFgtaiHFGbHW8bxKqRV6VjtXThQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz", + "integrity": "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", + "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.0.3", + "@jridgewell/sourcemap-codec": "^1.4.10" + } + }, + "node_modules/@poppinss/colors": { + "version": "4.1.6", + "resolved": "https://registry.npmjs.org/@poppinss/colors/-/colors-4.1.6.tgz", + "integrity": "sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg==", + "dev": true, + "license": "MIT", + "dependencies": { + "kleur": "^4.1.5" + } + }, + "node_modules/@poppinss/dumper": { + "version": "0.6.5", + "resolved": "https://registry.npmjs.org/@poppinss/dumper/-/dumper-0.6.5.tgz", + "integrity": "sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@poppinss/colors": "^4.1.5", + "@sindresorhus/is": "^7.0.2", + "supports-color": "^10.0.0" + } + }, + "node_modules/@poppinss/exception": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@poppinss/exception/-/exception-1.2.3.tgz", + "integrity": "sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@sindresorhus/is": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-7.2.0.tgz", + "integrity": "sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sindresorhus/is?sponsor=1" + } + }, + "node_modules/@speed-highlight/core": { + "version": "1.2.24", + "resolved": "https://registry.npmjs.org/@speed-highlight/core/-/core-1.2.24.tgz", + "integrity": "sha512-qeW2e1l78afw8VhRPfPQ1Gjj+KU5XFQ/OFV5ti6eTa9bruO7mJyZtA4vw0ofqmA3tKCkROE9xLk3VZoeRc98nw==", + "dev": true, + "license": "CC0-1.0" + }, + "node_modules/@types/node": { + "version": "18.19.130", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.130.tgz", + "integrity": "sha512-GRaXQx6jGfL8sKfaIDD6OupbIHBr9jv7Jnaml9tB7l4v068PAOXqfcujMMo5PhbIs6ggR1XODELqahT2R8v0fg==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~5.26.4" + } + }, + "node_modules/@types/node-fetch": { + "version": "2.6.13", + "resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.6.13.tgz", + "integrity": "sha512-QGpRVpzSaUs30JBSGPjOg4Uveu384erbHBoT1zeONvyCfwQxIkUshLAOqN/k9EjGviPRmWTTe6aH2qySWKTVSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*", + "form-data": "^4.0.4" + } + }, + "node_modules/@types/yargs": { + "version": "17.0.24", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.24.tgz", + "integrity": "sha512-6i0aC7jV6QzQB8ne1joVZ0eSFIstHsCrobmOtghM11yGlH0j43FKL2UhWdELkyps0zuf7qVTUVCCR+tgSlyLLw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/yargs-parser": "*" + } + }, + "node_modules/@types/yargs-parser": { + "version": "21.0.3", + "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-21.0.3.tgz", + "integrity": "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/abort-controller": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz", + "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==", + "dev": true, + "license": "MIT", + "dependencies": { + "event-target-shim": "^5.0.0" + }, + "engines": { + "node": ">=6.5" + } + }, + "node_modules/agentkeepalive": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/agentkeepalive/-/agentkeepalive-4.6.0.tgz", + "integrity": "sha512-kja8j7PjmncONqaTsB8fQ+wE2mSU2DJ9D4XKoJ5PFWIdRMa6SLSN1ff4mOr4jCbfRSsxR4keIiySJU0N9T5hIQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "humanize-ms": "^1.2.1" + }, + "engines": { + "node": ">= 8.0.0" + } + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/chalk": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.3.0.tgz", + "integrity": "sha512-dLitG79d+GV1Nb/VYcCDFivJeK1hiukt9QjRNVOsUtTy1rR1YJsmpGGTZ3qJos+uw7WmWF4wUwBd9jxjocFC2w==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/cloudflare": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/cloudflare/-/cloudflare-5.2.0.tgz", + "integrity": "sha512-dVzqDpPFYR9ApEC9e+JJshFJZXcw4HzM8W+3DHzO5oy9+8rLC53G7x6fEf9A7/gSuSCxuvndzui5qJKftfIM9A==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@types/node": "^18.11.18", + "@types/node-fetch": "^2.6.4", + "abort-controller": "^3.0.0", + "agentkeepalive": "^4.2.1", + "form-data-encoder": "1.7.2", + "formdata-node": "^4.3.2", + "node-fetch": "^2.6.7" + } + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dev": true, + "license": "MIT", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/cookie": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz", + "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/devtools-protocol": { + "version": "0.0.1182435", + "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1182435.tgz", + "integrity": "sha512-EmlkWb62wSbQNE1gRZZsi4KZYRaF5Skpp183LhRU7+sadKR06O1dHCjZmFSEG6Kv7P6S/UYLxcY3NlYwqKM99w==", + "dev": true, + "license": "BSD-3-Clause" + }, + "node_modules/dotenv": { + "version": "16.3.1", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.3.1.tgz", + "integrity": "sha512-IPzF4w4/Rd94bA9imS68tZBaYyBWSCE47V1RGuMrB94iyTOIEwRmVL2x/4An+6mETpLrKJ5hQkB8W4kFAadeIQ==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/motdotla/dotenv?sponsor=1" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/error-stack-parser-es": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/error-stack-parser-es/-/error-stack-parser-es-1.0.5.tgz", + "integrity": "sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/esbuild": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" + } + }, + "node_modules/event-target-shim": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", + "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/form-data": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz", + "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.4", + "mime-types": "^2.1.35" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/form-data-encoder": { + "version": "1.7.2", + "resolved": "https://registry.npmjs.org/form-data-encoder/-/form-data-encoder-1.7.2.tgz", + "integrity": "sha512-qfqtYan3rxrnCk1VYaA4H+Ms9xdpPqvLZa6xmMgFvhO32x7/3J/ExcTd6qpxM0vH2GdMI+poehyBZvqfMTto8A==", + "dev": true, + "license": "MIT" + }, + "node_modules/formdata-node": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/formdata-node/-/formdata-node-4.4.1.tgz", + "integrity": "sha512-0iirZp3uVDjVGt9p49aTaqjk84TrglENEDuqfdlZQ1roC9CWlPk6Avf8EEnZNcAqPonwkG35x4n3ww/1THYAeQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "node-domexception": "1.0.0", + "web-streams-polyfill": "4.0.0-beta.3" + }, + "engines": { + "node": ">= 12.20" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "dev": true, + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/humanize-ms": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/humanize-ms/-/humanize-ms-1.2.1.tgz", + "integrity": "sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.0.0" + } + }, + "node_modules/kleur": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz", + "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dev": true, + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/miniflare": { + "version": "4.20260730.0", + "resolved": "https://registry.npmjs.org/miniflare/-/miniflare-4.20260730.0.tgz", + "integrity": "sha512-1Z9SB9r/o//80UA02Re3QhtcecSHAyAjf5EcKBfQVlQrCg7Miy79hl2PvtkwFLIaJ5rcrOPdDcRr577okwZPsg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspotcode/source-map-support": "0.8.1", + "sharp": "0.35.2", + "undici": "7.28.0", + "workerd": "1.20260730.1", + "ws": "8.21.0", + "youch": "4.1.0-beta.10" + }, + "bin": { + "miniflare": "bootstrap.js" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/node-domexception": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", + "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==", + "deprecated": "Use your platform's native DOMException instead", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "github", + "url": "https://paypal.me/jimmywarting" + } + ], + "license": "MIT", + "engines": { + "node": ">=10.5.0" + } + }, + "node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/path-to-regexp": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-6.3.0.tgz", + "integrity": "sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/sharp": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.2.tgz", + "integrity": "sha512-FVtFjtBCMiJS6yb5CX7Sop45WFMpeGw6oRKuJnXYgf/f1ms/D7LE/ZUSNxnW7rZ/dbslQWYkoqFHGPaDBtaK4w==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@img/colour": "^1.1.0", + "detect-libc": "^2.1.2", + "semver": "^7.8.4" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.35.2", + "@img/sharp-darwin-x64": "0.35.2", + "@img/sharp-freebsd-wasm32": "0.35.2", + "@img/sharp-libvips-darwin-arm64": "1.3.1", + "@img/sharp-libvips-darwin-x64": "1.3.1", + "@img/sharp-libvips-linux-arm": "1.3.1", + "@img/sharp-libvips-linux-arm64": "1.3.1", + "@img/sharp-libvips-linux-ppc64": "1.3.1", + "@img/sharp-libvips-linux-riscv64": "1.3.1", + "@img/sharp-libvips-linux-s390x": "1.3.1", + "@img/sharp-libvips-linux-x64": "1.3.1", + "@img/sharp-libvips-linuxmusl-arm64": "1.3.1", + "@img/sharp-libvips-linuxmusl-x64": "1.3.1", + "@img/sharp-linux-arm": "0.35.2", + "@img/sharp-linux-arm64": "0.35.2", + "@img/sharp-linux-ppc64": "0.35.2", + "@img/sharp-linux-riscv64": "0.35.2", + "@img/sharp-linux-s390x": "0.35.2", + "@img/sharp-linux-x64": "0.35.2", + "@img/sharp-linuxmusl-arm64": "0.35.2", + "@img/sharp-linuxmusl-x64": "0.35.2", + "@img/sharp-webcontainers-wasm32": "0.35.2", + "@img/sharp-win32-arm64": "0.35.2", + "@img/sharp-win32-ia32": "0.35.2", + "@img/sharp-win32-x64": "0.35.2" + } + }, + "node_modules/supports-color": { + "version": "10.2.2", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-10.2.2.tgz", + "integrity": "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", + "dev": true, + "license": "MIT" + }, + "node_modules/tslib": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", + "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", + "dev": true, + "license": "0BSD", + "optional": true + }, + "node_modules/undici": { + "version": "7.28.0", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.28.0.tgz", + "integrity": "sha512-cRZYrTDwWznlnRiPjggAGxZXanty6M8RV1ff8Wm4LWXBp7/IG8v5DnOm74DtUBp9OONpK75YlPnIjQqX0dBDtA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.18.1" + } + }, + "node_modules/undici-types": { + "version": "5.26.5", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", + "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==", + "dev": true, + "license": "MIT" + }, + "node_modules/unenv": { + "version": "2.0.0-rc.24", + "resolved": "https://registry.npmjs.org/unenv/-/unenv-2.0.0-rc.24.tgz", + "integrity": "sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw==", + "dev": true, + "license": "MIT", + "dependencies": { + "pathe": "^2.0.3" + } + }, + "node_modules/web-streams-polyfill": { + "version": "4.0.0-beta.3", + "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-4.0.0-beta.3.tgz", + "integrity": "sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", + "dev": true, + "license": "BSD-2-Clause" + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "dev": true, + "license": "MIT", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/workerd": { + "version": "1.20260730.1", + "resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20260730.1.tgz", + "integrity": "sha512-zmfNIjwYSWFY5chGBOjWtH3xAE7p97FTC6vR4Ep98290ho6AeAR/NVcBD274YCLEUYzqm8yxdtZlxMybU8a3jA==", + "dev": true, + "hasInstallScript": true, + "license": "Apache-2.0", + "bin": { + "workerd": "bin/workerd" + }, + "engines": { + "node": ">=16" + }, + "optionalDependencies": { + "@cloudflare/workerd-darwin-64": "1.20260730.1", + "@cloudflare/workerd-darwin-arm64": "1.20260730.1", + "@cloudflare/workerd-linux-64": "1.20260730.1", + "@cloudflare/workerd-linux-arm64": "1.20260730.1", + "@cloudflare/workerd-windows-64": "1.20260730.1" + } + }, + "node_modules/wrangler": { + "version": "4.166.0", + "resolved": "https://registry.npmjs.org/wrangler/-/wrangler-4.166.0.tgz", + "integrity": "sha512-qMz0sHGXqEC0Va8T6dAaG0ggp9tCcuHHYMUQzRKbtZg6+MPAPb6oBu1757IaeugNJHPAz+twHiA+zDyXWQLsLw==", + "dev": true, + "license": "MIT OR Apache-2.0", + "dependencies": { + "@cloudflare/kv-asset-handler": "0.5.1", + "@cloudflare/unenv-preset": "2.16.2", + "@cloudflare/workers-utils": "0.56.0", + "@cspotcode/source-map-support": "0.8.1", + "@types/yargs": "17.0.24", + "cloudflare": "5.2.0", + "devtools-protocol": "0.0.1182435", + "esbuild": "0.28.2", + "miniflare": "5.20261119.0-beta", + "path-to-regexp": "6.3.0", + "undici": "7.30.2", + "unenv": "2.0.0-rc.24", + "workerd": "1.20261119.1" + }, + "bin": { + "cf-wrangler": "bin/cf-wrangler.js", + "wrangler": "bin/wrangler.js", + "wrangler2": "bin/wrangler.js" + }, + "engines": { + "node": ">=22.12.0" + }, + "optionalDependencies": { + "fsevents": "2.3.3" + }, + "peerDependencies": { + "@cloudflare/workers-types": "^5.20261119.1" + }, + "peerDependenciesMeta": { + "@cloudflare/workers-types": { + "optional": true + } + } + }, + "node_modules/wrangler/node_modules/@cloudflare/workerd-darwin-64": { + "version": "1.20261119.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-64/-/workerd-darwin-64-1.20261119.1.tgz", + "integrity": "sha512-yotoiTGXCl1gTRX+y5ZWSAmzAg6CcBJXhJL6C1DGWUhsjjezNe8FdzraNsefVTOeKsOid2EC+hqOzewczKLvmQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/wrangler/node_modules/@cloudflare/workerd-darwin-arm64": { + "version": "1.20261119.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-arm64/-/workerd-darwin-arm64-1.20261119.1.tgz", + "integrity": "sha512-VPOmfEmMubvw4SPcg/yDgamQXsiVAENgxeCJO8pDggRJFaF93SP0g/hktD8sbfmWBS19BO1kX1EsdgHSgRL9jA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/wrangler/node_modules/@cloudflare/workerd-linux-64": { + "version": "1.20261119.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-64/-/workerd-linux-64-1.20261119.1.tgz", + "integrity": "sha512-aaDf78smiN12Uuwtg6TG6iLVS61sLpy/7DC5PYORf2+TCYw/bygcaqqb8zQJ+XwZ3xYhm/Ws80c/yMMhCMTFYA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/wrangler/node_modules/@cloudflare/workerd-linux-arm64": { + "version": "1.20261119.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-arm64/-/workerd-linux-arm64-1.20261119.1.tgz", + "integrity": "sha512-LkyAvTMcKqRUP73HRScWWwTSz3pw09um1hxR+rcGdvsGzao8IR59XXTp/tul6kFdVBL2mD8U3X6j2O8t7I4viw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/wrangler/node_modules/@cloudflare/workerd-windows-64": { + "version": "1.20261119.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-windows-64/-/workerd-windows-64-1.20261119.1.tgz", + "integrity": "sha512-y4RO3QFNWt4j4uq2kmP5tklTvdA3qOA0PXuA66vsCmEtZYYb71ldefJcq5Dt0jrexKf/i4BBaLXZMVYLnohb0g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/wrangler/node_modules/@img/sharp-darwin-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.5.tgz", + "integrity": "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.3.4" + } + }, + "node_modules/wrangler/node_modules/@img/sharp-darwin-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.5.tgz", + "integrity": "sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.3.4" + } + }, + "node_modules/wrangler/node_modules/@img/sharp-freebsd-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.5.tgz", + "integrity": "sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==", + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "dependencies": { + "@img/sharp-wasm32": "0.35.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/wrangler/node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.4.tgz", + "integrity": "sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/wrangler/node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.4.tgz", + "integrity": "sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/wrangler/node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.4.tgz", + "integrity": "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/wrangler/node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.4.tgz", + "integrity": "sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/wrangler/node_modules/@img/sharp-libvips-linux-ppc64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.4.tgz", + "integrity": "sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/wrangler/node_modules/@img/sharp-libvips-linux-riscv64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.4.tgz", + "integrity": "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==", "cpu": [ "riscv64" ], "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/wrangler/node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.4.tgz", + "integrity": "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/wrangler/node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.4.tgz", + "integrity": "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/wrangler/node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.4.tgz", + "integrity": "sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/wrangler/node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.4.tgz", + "integrity": "sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/wrangler/node_modules/@img/sharp-linux-arm": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.5.tgz", + "integrity": "sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==", + "cpu": [ + "arm" + ], + "dev": true, "license": "Apache-2.0", "optional": true, "os": [ @@ -456,13 +2370,82 @@ "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linux-riscv64": "1.3.1" + "@img/sharp-libvips-linux-arm": "1.3.4" } }, - "node_modules/@img/sharp-linux-s390x": { - "version": "0.35.2", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.2.tgz", - "integrity": "sha512-E4fLLfRPzDLlEeDaTzI98OFLcv++WL5ChLLMwPoVd0CIoZQqupBSNbOisPL5am9XsbQ9T84+iiMpUvbFtkunbA==", + "node_modules/wrangler/node_modules/@img/sharp-linux-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.5.tgz", + "integrity": "sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.3.4" + } + }, + "node_modules/wrangler/node_modules/@img/sharp-linux-ppc64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.5.tgz", + "integrity": "sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-ppc64": "1.3.4" + } + }, + "node_modules/wrangler/node_modules/@img/sharp-linux-riscv64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.5.tgz", + "integrity": "sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-riscv64": "1.3.4" + } + }, + "node_modules/wrangler/node_modules/@img/sharp-linux-s390x": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.5.tgz", + "integrity": "sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==", "cpu": [ "s390x" ], @@ -479,13 +2462,13 @@ "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linux-s390x": "1.3.1" + "@img/sharp-libvips-linux-s390x": "1.3.4" } }, - "node_modules/@img/sharp-linux-x64": { - "version": "0.35.2", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.2.tgz", - "integrity": "sha512-gi0zFJJRLswfCZmHtJdikXPOc5u7qamSOS3NHedLqLd4W8Q0NqjdBr6TTRIgsfFjqfTsHFgdfvJ9LwqSgcHiAA==", + "node_modules/wrangler/node_modules/@img/sharp-linux-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.5.tgz", + "integrity": "sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==", "cpu": [ "x64" ], @@ -502,13 +2485,13 @@ "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linux-x64": "1.3.1" + "@img/sharp-libvips-linux-x64": "1.3.4" } }, - "node_modules/@img/sharp-linuxmusl-arm64": { - "version": "0.35.2", - "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.2.tgz", - "integrity": "sha512-siWbOW1u6HFnFLrp0waKyW7VEf7jYvcDWdrXEFa8AkdAQgEvuu5Fz8/Y70w9EeqAdwDtfU012BhEHHaDqvQNzg==", + "node_modules/wrangler/node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.5.tgz", + "integrity": "sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==", "cpu": [ "arm64" ], @@ -525,13 +2508,13 @@ "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linuxmusl-arm64": "1.3.1" + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4" } }, - "node_modules/@img/sharp-linuxmusl-x64": { - "version": "0.35.2", - "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.2.tgz", - "integrity": "sha512-YBqMMcjDi4QGYiSn4vNOYBhmlC4z5AXqkOUUqI2e0AFA4urNv4ESgOgwNl3K+4etQhha0twXlzeF20bbULm9Yg==", + "node_modules/wrangler/node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.5.tgz", + "integrity": "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==", "cpu": [ "x64" ], @@ -548,18 +2531,18 @@ "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linuxmusl-x64": "1.3.1" + "@img/sharp-libvips-linuxmusl-x64": "1.3.4" } }, - "node_modules/@img/sharp-wasm32": { - "version": "0.35.2", - "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.2.tgz", - "integrity": "sha512-Mrv4JQNYVQ94xH+jzZ9r+gowleN8mv2FTgKT+PI6bx5C0G8TdNYndu161pg2i7uoBwxy2ImPMHrJOM2LZef7Bw==", + "node_modules/wrangler/node_modules/@img/sharp-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.5.tgz", + "integrity": "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==", "dev": true, "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", "optional": true, "dependencies": { - "@emnapi/runtime": "^1.11.1" + "@emnapi/runtime": "^1.11.3" }, "engines": { "node": ">=20.9.0" @@ -568,10 +2551,10 @@ "url": "https://opencollective.com/libvips" } }, - "node_modules/@img/sharp-webcontainers-wasm32": { - "version": "0.35.2", - "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.2.tgz", - "integrity": "sha512-QNV27pxs9wpApEiCfvHM1RDoP1w1+2KrUWWDPEhEwg+latvOrfuhWrHWZKwdSFwU6jh3myjw/yOCRsUIuOft3g==", + "node_modules/wrangler/node_modules/@img/sharp-webcontainers-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.5.tgz", + "integrity": "sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==", "cpu": [ "wasm32" ], @@ -579,7 +2562,7 @@ "license": "Apache-2.0", "optional": true, "dependencies": { - "@img/sharp-wasm32": "0.35.2" + "@img/sharp-wasm32": "0.35.5" }, "engines": { "node": ">=20.9.0" @@ -588,10 +2571,10 @@ "url": "https://opencollective.com/libvips" } }, - "node_modules/@img/sharp-win32-arm64": { - "version": "0.35.2", - "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.2.tgz", - "integrity": "sha512-BiVRYc/t6/Vl3e1hBx0hugG4oN9Pydf4fgMSpxTQJmwGUg/YoXTWHiFeRymHfCZzifxu4F4rpk/I67D0LQ20wQ==", + "node_modules/wrangler/node_modules/@img/sharp-win32-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.5.tgz", + "integrity": "sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==", "cpu": [ "arm64" ], @@ -608,10 +2591,10 @@ "url": "https://opencollective.com/libvips" } }, - "node_modules/@img/sharp-win32-ia32": { - "version": "0.35.2", - "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.2.tgz", - "integrity": "sha512-YYEhx9PImCC7T0tI8JDMi4DB9LwLCXCU5OWNYEXAxh5Q1ShKkyC6byxzoBJ3gEFDnH2lQckWuDe70G7mB2XJog==", + "node_modules/wrangler/node_modules/@img/sharp-win32-ia32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.5.tgz", + "integrity": "sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==", "cpu": [ "ia32" ], @@ -628,10 +2611,10 @@ "url": "https://opencollective.com/libvips" } }, - "node_modules/@img/sharp-win32-x64": { - "version": "0.35.2", - "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.2.tgz", - "integrity": "sha512-imoOyBcoM/iiUr4J6VPpCNjPnjvP/Gks95898yB8YqoGGYmHYbOyCuNv9FMhFgtaiHFGbHW8bxKqRV6VjtXThQ==", + "node_modules/wrangler/node_modules/@img/sharp-win32-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.5.tgz", + "integrity": "sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==", "cpu": [ "x64" ], @@ -648,171 +2631,42 @@ "url": "https://opencollective.com/libvips" } }, - "node_modules/@jridgewell/resolve-uri": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz", - "integrity": "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@jridgewell/sourcemap-codec": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", - "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@jridgewell/trace-mapping": { - "version": "0.3.9", - "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", - "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/resolve-uri": "^3.0.3", - "@jridgewell/sourcemap-codec": "^1.4.10" - } - }, - "node_modules/@poppinss/colors": { - "version": "4.1.6", - "resolved": "https://registry.npmjs.org/@poppinss/colors/-/colors-4.1.6.tgz", - "integrity": "sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg==", - "dev": true, - "license": "MIT", - "dependencies": { - "kleur": "^4.1.5" - } - }, - "node_modules/@poppinss/dumper": { - "version": "0.6.5", - "resolved": "https://registry.npmjs.org/@poppinss/dumper/-/dumper-0.6.5.tgz", - "integrity": "sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@poppinss/colors": "^4.1.5", - "@sindresorhus/is": "^7.0.2", - "supports-color": "^10.0.0" - } - }, - "node_modules/@poppinss/exception": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/@poppinss/exception/-/exception-1.2.3.tgz", - "integrity": "sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@sindresorhus/is": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-7.2.0.tgz", - "integrity": "sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sindresorhus/is?sponsor=1" - } - }, - "node_modules/@speed-highlight/core": { - "version": "1.2.24", - "resolved": "https://registry.npmjs.org/@speed-highlight/core/-/core-1.2.24.tgz", - "integrity": "sha512-qeW2e1l78afw8VhRPfPQ1Gjj+KU5XFQ/OFV5ti6eTa9bruO7mJyZtA4vw0ofqmA3tKCkROE9xLk3VZoeRc98nw==", - "dev": true, - "license": "CC0-1.0" - }, - "node_modules/cookie": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz", - "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/detect-libc": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", - "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=8" - } - }, - "node_modules/error-stack-parser-es": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/error-stack-parser-es/-/error-stack-parser-es-1.0.5.tgz", - "integrity": "sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA==", - "dev": true, - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/antfu" - } - }, - "node_modules/kleur": { - "version": "4.1.5", - "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz", - "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/miniflare": { - "version": "4.20260730.0", - "resolved": "https://registry.npmjs.org/miniflare/-/miniflare-4.20260730.0.tgz", - "integrity": "sha512-1Z9SB9r/o//80UA02Re3QhtcecSHAyAjf5EcKBfQVlQrCg7Miy79hl2PvtkwFLIaJ5rcrOPdDcRr577okwZPsg==", + "node_modules/wrangler/node_modules/miniflare": { + "version": "5.20261119.0-beta", + "resolved": "https://registry.npmjs.org/miniflare/-/miniflare-5.20261119.0-beta.tgz", + "integrity": "sha512-HdNQIUPgde5Yg0qFaI6iiYd0aOxAgKQTXDstkBN2G1tPBdslNrUKdySwaGdBix0IFd+yh8M0gkqzw68dIZ2Ugw==", "dev": true, "license": "MIT", "dependencies": { "@cspotcode/source-map-support": "0.8.1", - "sharp": "0.35.2", - "undici": "7.28.0", - "workerd": "1.20260730.1", + "sharp": "0.35.5", + "undici": "7.30.2", + "workerd": "1.20261119.1", "ws": "8.21.0", "youch": "4.1.0-beta.10" }, - "bin": { - "miniflare": "bootstrap.js" - }, "engines": { - "node": ">=22.0.0" - } - }, - "node_modules/semver": { - "version": "7.8.6", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", - "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" + "node": ">=22.12.0" }, - "engines": { - "node": ">=10" + "peerDependencies": { + "kerberos": "^2.0.0" + }, + "peerDependenciesMeta": { + "kerberos": { + "optional": true + } } }, - "node_modules/sharp": { - "version": "0.35.2", - "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.2.tgz", - "integrity": "sha512-FVtFjtBCMiJS6yb5CX7Sop45WFMpeGw6oRKuJnXYgf/f1ms/D7LE/ZUSNxnW7rZ/dbslQWYkoqFHGPaDBtaK4w==", + "node_modules/wrangler/node_modules/sharp": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz", + "integrity": "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==", "dev": true, "license": "Apache-2.0", "dependencies": { "@img/colour": "^1.1.0", "detect-libc": "^2.1.2", - "semver": "^7.8.4" + "semver": "^7.8.5" }, "engines": { "node": ">=20.9.0" @@ -821,68 +2675,52 @@ "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-darwin-arm64": "0.35.2", - "@img/sharp-darwin-x64": "0.35.2", - "@img/sharp-freebsd-wasm32": "0.35.2", - "@img/sharp-libvips-darwin-arm64": "1.3.1", - "@img/sharp-libvips-darwin-x64": "1.3.1", - "@img/sharp-libvips-linux-arm": "1.3.1", - "@img/sharp-libvips-linux-arm64": "1.3.1", - "@img/sharp-libvips-linux-ppc64": "1.3.1", - "@img/sharp-libvips-linux-riscv64": "1.3.1", - "@img/sharp-libvips-linux-s390x": "1.3.1", - "@img/sharp-libvips-linux-x64": "1.3.1", - "@img/sharp-libvips-linuxmusl-arm64": "1.3.1", - "@img/sharp-libvips-linuxmusl-x64": "1.3.1", - "@img/sharp-linux-arm": "0.35.2", - "@img/sharp-linux-arm64": "0.35.2", - "@img/sharp-linux-ppc64": "0.35.2", - "@img/sharp-linux-riscv64": "0.35.2", - "@img/sharp-linux-s390x": "0.35.2", - "@img/sharp-linux-x64": "0.35.2", - "@img/sharp-linuxmusl-arm64": "0.35.2", - "@img/sharp-linuxmusl-x64": "0.35.2", - "@img/sharp-webcontainers-wasm32": "0.35.2", - "@img/sharp-win32-arm64": "0.35.2", - "@img/sharp-win32-ia32": "0.35.2", - "@img/sharp-win32-x64": "0.35.2" - } - }, - "node_modules/supports-color": { - "version": "10.2.2", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-10.2.2.tgz", - "integrity": "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" + "@img/sharp-darwin-arm64": "0.35.5", + "@img/sharp-darwin-x64": "0.35.5", + "@img/sharp-freebsd-wasm32": "0.35.5", + "@img/sharp-libvips-darwin-arm64": "1.3.4", + "@img/sharp-libvips-darwin-x64": "1.3.4", + "@img/sharp-libvips-linux-arm": "1.3.4", + "@img/sharp-libvips-linux-arm64": "1.3.4", + "@img/sharp-libvips-linux-ppc64": "1.3.4", + "@img/sharp-libvips-linux-riscv64": "1.3.4", + "@img/sharp-libvips-linux-s390x": "1.3.4", + "@img/sharp-libvips-linux-x64": "1.3.4", + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4", + "@img/sharp-libvips-linuxmusl-x64": "1.3.4", + "@img/sharp-linux-arm": "0.35.5", + "@img/sharp-linux-arm64": "0.35.5", + "@img/sharp-linux-ppc64": "0.35.5", + "@img/sharp-linux-riscv64": "0.35.5", + "@img/sharp-linux-s390x": "0.35.5", + "@img/sharp-linux-x64": "0.35.5", + "@img/sharp-linuxmusl-arm64": "0.35.5", + "@img/sharp-linuxmusl-x64": "0.35.5", + "@img/sharp-webcontainers-wasm32": "0.35.5", + "@img/sharp-win32-arm64": "0.35.5", + "@img/sharp-win32-ia32": "0.35.5", + "@img/sharp-win32-x64": "0.35.5" }, - "funding": { - "url": "https://github.com/chalk/supports-color?sponsor=1" + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } } }, - "node_modules/tslib": { - "version": "2.9.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", - "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", - "dev": true, - "license": "0BSD", - "optional": true - }, - "node_modules/undici": { - "version": "7.28.0", - "resolved": "https://registry.npmjs.org/undici/-/undici-7.28.0.tgz", - "integrity": "sha512-cRZYrTDwWznlnRiPjggAGxZXanty6M8RV1ff8Wm4LWXBp7/IG8v5DnOm74DtUBp9OONpK75YlPnIjQqX0dBDtA==", + "node_modules/wrangler/node_modules/undici": { + "version": "7.30.2", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.30.2.tgz", + "integrity": "sha512-mLyPQnHwUxaM/rideoK/+KL8DaAJLRl4aBCfmX444aCSLnIaomqPLtNRe2jdCYcsk5wZzXrDIQC8ZeYNRAYyIA==", "dev": true, "license": "MIT", "engines": { "node": ">=20.18.1" } }, - "node_modules/workerd": { - "version": "1.20260730.1", - "resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20260730.1.tgz", - "integrity": "sha512-zmfNIjwYSWFY5chGBOjWtH3xAE7p97FTC6vR4Ep98290ho6AeAR/NVcBD274YCLEUYzqm8yxdtZlxMybU8a3jA==", + "node_modules/wrangler/node_modules/workerd": { + "version": "1.20261119.1", + "resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20261119.1.tgz", + "integrity": "sha512-lalSvY+ad5asqMgzA/DfrZo7wvuvOHJc/aS1UctUrwu76fJE/LkSKJlprfBu0LeU79Qai5d+xFooQA9CIfj+dQ==", "dev": true, "hasInstallScript": true, "license": "Apache-2.0", @@ -893,11 +2731,11 @@ "node": ">=16" }, "optionalDependencies": { - "@cloudflare/workerd-darwin-64": "1.20260730.1", - "@cloudflare/workerd-darwin-arm64": "1.20260730.1", - "@cloudflare/workerd-linux-64": "1.20260730.1", - "@cloudflare/workerd-linux-arm64": "1.20260730.1", - "@cloudflare/workerd-windows-64": "1.20260730.1" + "@cloudflare/workerd-darwin-64": "1.20261119.1", + "@cloudflare/workerd-darwin-arm64": "1.20261119.1", + "@cloudflare/workerd-linux-64": "1.20261119.1", + "@cloudflare/workerd-linux-arm64": "1.20261119.1", + "@cloudflare/workerd-windows-64": "1.20261119.1" } }, "node_modules/ws": { diff --git a/pm-stack/private-laptop-bridge/package.json b/pm-stack/private-laptop-bridge/package.json index 2aff715e93..3456cd8359 100644 --- a/pm-stack/private-laptop-bridge/package.json +++ b/pm-stack/private-laptop-bridge/package.json @@ -3,12 +3,15 @@ "private": true, "type": "module", "scripts": { - "test": "node --test *.test.mjs" + "test": "node --test *.test.mjs", + "rehearse": "node --test --test-concurrency=1 *.test.mjs ../aggregator/test/bridge-snapshot.test.ts ../aggregator/test/bridge-refresh.test.ts", + "check:staging": "WRANGLER_SEND_METRICS=false wrangler deploy --dry-run --config wrangler.staging.jsonc --outdir .wrangler/staging-dry-run" }, "engines": { "node": ">=24" }, "devDependencies": { - "miniflare": "4.20260730.0" + "miniflare": "4.20260730.0", + "wrangler": "4.166.0" } } diff --git a/pm-stack/private-laptop-bridge/private-laptop-bridge.service.example b/pm-stack/private-laptop-bridge/private-laptop-bridge.service.example index bbefe8f328..2f41435276 100644 --- a/pm-stack/private-laptop-bridge/private-laptop-bridge.service.example +++ b/pm-stack/private-laptop-bridge/private-laptop-bridge.service.example @@ -24,6 +24,9 @@ CapabilityBoundingSet= UMask=0077 # A denied/revoked identity stops; no automatic restart loop after denial. Restart=no +RuntimeMaxSec=3600 +# Optional approved per-process Gateway trust; never set globally: +# Environment=NODE_EXTRA_CA_CERTS=/APPROVED_GATEWAY_PUBLIC_CA_PEM # ProtectHome=read-only is not a filesystem secrecy boundary. Before enabling, # review mount isolation exposing only device.json, bridge-queue.json and the # queue-broker socket. No other home reads are implemented by this program. diff --git a/pm-stack/private-laptop-bridge/review.test.mjs b/pm-stack/private-laptop-bridge/review.test.mjs new file mode 100644 index 0000000000..fc0d2ba96e --- /dev/null +++ b/pm-stack/private-laptop-bridge/review.test.mjs @@ -0,0 +1,84 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {createClient,BridgeDenied} from './client.mjs'; +import {createCaller} from './caller.mjs'; +import worker,{PrivateLaptopBridge} from './worker.mjs'; +import {b64url,boundedText} from './protocol.mjs'; + +const NOW=1800000000000; +const keys={caller:await crypto.subtle.generateKey('Ed25519',true,['sign','verify']),device:await crypto.subtle.generateKey('Ed25519',true,['sign','verify'])}; +const origin='https://bridge.invalid',audience='review-test'; +const result={ok:true,data:{queueBroker:'up'}}; +class Storage { + value; + async transaction(fn){let next=structuredClone(this.value);const out=await fn({get:async()=>structuredClone(next),put:async(_,v)=>{next=structuredClone(v);},setAlarm:async()=>{}});this.value=next;return out;} +} +async function harness(t,offset=0) { + let clock=NOW; + t.mock.method(Date,'now',()=>clock); + const principals=[]; + for(const [id,role] of [['caller','caller'],['device','device']])principals.push({id,role,device:'amd',publicKey:b64url(await crypto.subtle.exportKey('raw',keys[id].publicKey)),scopes:['laptop.health'],issuedAt:NOW-60000,expiresAt:NOW+1800000,revoked:false}); + const env={ENABLED:'true',BRIDGE_REGISTRY:JSON.stringify({audience,principals})}; + const object=new PrivateLaptopBridge({storage:new Storage()},env); + env.BRIDGE={idFromName:x=>x,get:()=>({fetch:req=>object.fetch(req)})}; + const dispatch=req=>worker.fetch(req,env); + const config={origin,audience,now:()=>clock-offset,fetch:dispatch}; + const caller=createCaller({...config,principal:'caller',device:'amd',privateKey:keys.caller.privateKey}); + const deviceConfig={...config,principal:'device',privateKey:keys.device.privateKey,getuid:()=>1000,execute:async()=>result}; + return {caller,deviceConfig,dispatch,advance:ms=>{clock+=ms;},localNow:()=>clock-offset}; +} + +for(const offset of [-29000,-500,0,500,29000])test(`clock oracle: authenticated ${offset}ms offset preserves conservative caller/device lifetimes`,async t=>{ + const h=await harness(t,offset); + const handle=await h.caller.laptopHealth(); + assert.equal(handle.expiresAt,h.localNow()+60000); + const client=createClient(h.deviceConfig); + assert.equal(await client.step(),true); + assert.deepEqual((await h.caller.read(handle)).result,result); +}); + +test('deadline oracle: delayed poll response consumes the lease before any adapter executes',async t=>{ + const h=await harness(t,29000);await h.caller.laptopHealth();let executed=0; + const client=createClient({...h.deviceConfig,execute:async()=>{executed++;return result;},fetch:async request=>{const response=await h.dispatch(request);h.advance(16000);return response;}}); + await assert.rejects(client.step(),/expired-job/);assert.equal(executed,0); +}); + +for(const offset of [-29000,29000])test(`deadline oracle: actual lease expiration blocks completion with ${offset}ms skew`,async t=>{ + const h=await harness(t,offset);await h.caller.laptopHealth();let completions=0; + const client=createClient({...h.deviceConfig,execute:async()=>{h.advance(15000);return result;},fetch:async request=>{if(new URL(request.url).pathname==='/v1/result')completions++;return h.dispatch(request);}}); + await assert.rejects(client.step(),/expired-job/);assert.equal(completions,0); +}); + +test('deadline oracle: delayed call acknowledgement is never exposed as a fresh handle',async t=>{ + const h=await harness(t,500); + const caller=createCaller({origin,audience,principal:'caller',device:'amd',privateKey:keys.caller.privateKey,now:h.localNow,fetch:async request=>{const response=await h.dispatch(request);h.advance(60000);return response;}}); + await assert.rejects(caller.laptopHealth(),{code:'submit-outcome-unknown'}); +}); + +test('schema oracle: inconsistent server deadlines and excessive skew are rejected before execution',async()=>{ + const base={id:'job',lease:'lease',operation:'laptop.health',args:{},serverNow:NOW,expiresAt:NOW+60000,leaseExpiresAt:NOW+15000}; + const bad=[{...base,serverNow:NOW+30001},{...base,serverNow:NOW-30001},{...base,expiresAt:NOW+60001},{...base,leaseExpiresAt:NOW+15001},{...base,leaseExpiresAt:NOW},{...base,expiresAt:NOW+1000,leaseExpiresAt:NOW+2000},{...base,serverNow:undefined}]; + let executed=0; + for(const job of bad){const client=createClient({origin,audience,principal:'device',privateKey:keys.device.privateKey,now:()=>NOW,getuid:()=>1000,execute:async()=>{executed++;return result;},fetch:async()=>Response.json({job})});await assert.rejects(client.step(),/invalid-job/);} + assert.equal(executed,0); + for(const body of [{id:'job',serverNow:NOW+30001,expiresAt:NOW+60000},{id:'job',serverNow:NOW,expiresAt:NOW+60001},{id:'job',expiresAt:NOW+60000}]){ + const caller=createCaller({origin,audience,principal:'caller',device:'amd',privateKey:keys.caller.privateKey,now:()=>NOW,fetch:async()=>Response.json(body,{status:202})}); + await assert.rejects(caller.laptopHealth(),{code:'submit-outcome-unknown'}); + } +}); + +test('cleanup oracle: denial is immediate even when stream cancellation stalls or rejects',async()=>{ + for(const status of [401,403,410,503])for(const cancel of [()=>new Promise(()=>{}),()=>Promise.reject(new Error('private cancellation detail'))]){ + const client=createClient({origin,audience,principal:'device',privateKey:keys.device.privateKey,getuid:()=>1000,requestTimeoutMs:5,fetch:async()=>new Response(new ReadableStream({cancel}),{status})}); + let timer; + try { + const got=await Promise.race([client.step().then(()=>null,error=>error),new Promise(resolve=>{timer=setTimeout(()=>resolve('stalled'),100);})]); + assert.notEqual(got,'stalled'); + if(status===503)assert.equal(got.message,'bridge-unavailable');else assert.ok(got instanceof BridgeDenied); + }finally{clearTimeout(timer);} + } +}); + +test('cleanup oracle: Worker body timeout does not await hostile cancellation',async()=>{ + await assert.rejects(boundedText(new ReadableStream({cancel:()=>new Promise(()=>{})}),8192,5),/timeout/); +}); diff --git a/pm-stack/private-laptop-bridge/runtime.test.mjs b/pm-stack/private-laptop-bridge/runtime.test.mjs index 1819343ed1..881bd8cb6c 100644 --- a/pm-stack/private-laptop-bridge/runtime.test.mjs +++ b/pm-stack/private-laptop-bridge/runtime.test.mjs @@ -182,10 +182,14 @@ test('workerd: actual non-root laptop client completes each named read through W const { publishBridgeQueueSnapshot } = await import('../aggregator/src/bridge-snapshot.ts'); const home = await mkdtemp(join(tmpdir(), 'private-bridge-source-')); const fetchedAt = Date.now(); - const counts = { queued: 1, claimed: 0, parked: 0, handedOff: 0, blocked: 0, done: 0, cancelled: 0, failed: 0 }; - await publishBridgeQueueSnapshot({ fetchedAt, available: true, stale: false, errors: ['must-not-export'], - queues: [counts], tasks: [{ id: 42, status: 'queued', priority: 1, title: 'must-not-export', payload: { token: 'must-not-export' } }], - }, '1', home, fetchedAt); + const { fetchQueueSnapshot } = await import('../aggregator/src/queue.ts'); + const counts = { queue: 'synthetic-code-pilot', queued: 1, claimed: 0, parked: 0, handed_off: 0, blocked: 0, done: 0, cancelled: 0, failed: 0 }; + const snapshot = await fetchQueueSnapshot('http://synthetic-broker.invalid', 'synthetic-not-a-secret', async url => ({ + ok: true, status: 200, json: async () => url.endsWith('/health') ? {ok: true, rows: [counts]} : { + ok: true, rows: [{ id: 42, queue: 'synthetic-code-pilot', status: 'queued', priority: 1, title: 'must-not-export', payload: { token: 'must-not-export' } }], + }, + }), () => fetchedAt); + await publishBridgeQueueSnapshot(snapshot, '1', home, fetchedAt); assert.equal((await readFile(join(home, '.local/state/pm-aggregator/bridge-queue.json'), 'utf8')).includes('must-not-export'), false); await mkdir(join(home, '.config/queue-broker'), { recursive: true, mode: 0o700 }); let healthRequests = 0; diff --git a/pm-stack/private-laptop-bridge/worker.mjs b/pm-stack/private-laptop-bridge/worker.mjs index 752f5fce68..dad53bdafd 100644 --- a/pm-stack/private-laptop-bridge/worker.mjs +++ b/pm-stack/private-laptop-bridge/worker.mjs @@ -105,7 +105,7 @@ export class PrivateLaptopBridge { if (Object.keys(s.jobs).length >= 8) return deny(429, 'capacity'); const id = crypto.randomUUID(); s.jobs[id] = {id, device: body.device, operation: body.operation, args: body.args, caller: p.id, expiresAt: now + 60000, retainUntil: now + 120000, lease: null, leaseUntil: 0, assignee: null}; - return {status: 202, body: {id, expiresAt: s.jobs[id].expiresAt}}; + return {status: 202, body: {id, expiresAt: s.jobs[id].expiresAt, serverNow: now}}; } if (path === '/v1/poll') { if (p.role !== 'device') return deny(403, 'role'); @@ -113,7 +113,7 @@ export class PrivateLaptopBridge { const job = Object.values(s.jobs).find(j => liveJob(j) && !j.result && j.leaseUntil <= now && allows(p, j.device, j.operation, now)); if (!job) return {status: 200, body: {job: null}}; job.lease = crypto.randomUUID(); job.leaseUntil = Math.min(now + 15000, job.expiresAt); job.assignee = p.id; - return {status: 200, body: {job: {id: job.id, lease: job.lease, operation: job.operation, args: job.args, expiresAt: job.expiresAt, leaseExpiresAt: job.leaseUntil}}}; + return {status: 200, body: {job: {id: job.id, lease: job.lease, operation: job.operation, args: job.args, expiresAt: job.expiresAt, leaseExpiresAt: job.leaseUntil, serverNow: now}}}; } if (path === '/v1/result') { if (p.role !== 'device') return deny(403, 'role'); diff --git a/pm-stack/private-laptop-bridge/wrangler.staging.jsonc b/pm-stack/private-laptop-bridge/wrangler.staging.jsonc new file mode 100644 index 0000000000..78ce9c46e7 --- /dev/null +++ b/pm-stack/private-laptop-bridge/wrangler.staging.jsonc @@ -0,0 +1,20 @@ +{ + // A reviewable deployment candidate only. No credentials, live IDs or routes. + // Gateway Forward must invoke GatewayMiddleware by RPC after explicit approval. + "name": "private-laptop-bridge-staging", + "main": "gateway.mjs", + "compatibility_date": "2026-07-30", + "workers_dev": false, + "preview_urls": false, + "routes": [], + "vars": { + "ENABLED": "false", + "GATEWAY_HOST": "private-bridge-staging.invalid", + "GATEWAY_ACCOUNT_ID": "", + "GATEWAY_POLICY_ID": "", + "GATEWAY_IDENTITY_EMAIL": "", + "GATEWAY_POSTURE_ID": "" + }, + "durable_objects": {"bindings": [{"name": "BRIDGE", "class_name": "PrivateLaptopBridge"}]}, + "migrations": [{"tag": "v1", "new_sqlite_classes": ["PrivateLaptopBridge"]}] +} From 8998b776d092452f77a2ad8fb9c85ba2d8f77adb Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 12:10:13 +0000 Subject: [PATCH 07/33] Prepare credential-free private Gateway smoke and record runner evidence --- pm-stack/private-laptop-bridge/DISCOVERY.md | 131 ++++++++++++++++++ pm-stack/private-laptop-bridge/STAGING.md | 3 + .../private-laptop-bridge/VERIFICATION.md | 16 +++ pm-stack/private-laptop-bridge/smoke.mjs | 20 +++ pm-stack/private-laptop-bridge/smoke.test.mjs | 29 ++++ .../wrangler.smoke.jsonc | 18 +++ 6 files changed, 217 insertions(+) create mode 100644 pm-stack/private-laptop-bridge/DISCOVERY.md create mode 100644 pm-stack/private-laptop-bridge/smoke.mjs create mode 100644 pm-stack/private-laptop-bridge/smoke.test.mjs create mode 100644 pm-stack/private-laptop-bridge/wrangler.smoke.jsonc diff --git a/pm-stack/private-laptop-bridge/DISCOVERY.md b/pm-stack/private-laptop-bridge/DISCOVERY.md new file mode 100644 index 0000000000..1c34832de9 --- /dev/null +++ b/pm-stack/private-laptop-bridge/DISCOVERY.md @@ -0,0 +1,131 @@ +# Private staging discovery and smoke approval gate + +Read-only checkpoint: 2026-11-22. No Cloudflare resource, secret, laptop, +network setting or access grant changed. No AMD or proposed-host probe ran. + +## Verified metadata and limits of inference + +- Historical Wrangler verification (2026-10-21), + `doc/platform/toolchains/cloudflare-wrangler.md`, names + `Developing.today.llc.domains.0@gmail.com's Account`, ID prefix `234b866b…`. + No complete account ID or current Cloudflare One Gateway configuration was + available through the connected tools or inspected tracked configuration. +- `pm-stack/console/scripts/expose.py` configures `amd-6-pm-stack`, + `pm.security.cab`, and owner default `drewrypope@gmail.com`; account and Access + organization are discovered dynamically. These defaults do not verify current + ownership, Gateway enrollment or a suitable caller runner. +- Existing `lab-cluster` and `sandbox-link` tunnels use public hostnames. They + are not a private Gateway ingress substitute. `home/common/default.nix`'s + Gateway reference is AI Gateway, not Cloudflare One evidence. Referenced local + account files and secret values were not read. +- `nixos/users/dot-ssh/default.nix` defines Aster's `dot-ssh`, UID 1339, no sudo, + with empty authorized keys. This is not evidence of an installed runner. +- This Work runtime's provider configuration reports no outbound identities or + secret bindings. Its local proxy's read-only status at + **2026-11-22T12:07:24Z** reports Tailscale configured, state `Running`, + `routing_ready: true`, and 301 accepted routes. Route contents and DNS data were + not printed. Tailscale lives in the managed proxy; missing local VPN binaries + or interfaces does not disprove it. Neither proxy readiness nor Tailscale + establishes a Cloudflare Gateway on-ramp or target reachability. + +**No existing account/Gateway/runner can yet be selected as verified suitable.** +No live probe was authorized, so it would be incorrect to claim that the private +host is demonstrably unreachable. The verified blocker is missing Gateway +on-ramp evidence and exact account/policy ownership metadata, not a measured +network failure. Do not install WARP/Tailscale or grant Aster access to resolve it. + +Next safe route: owner selects an already enrolled, approved Gateway runner and +supplies read-only full account ID, Gateway organization, existing on-ramp/TLS +configuration, policy ordering, runner ownership and remaining allowance evidence. +Use that runner for the narrow smoke only. If Aster's managed proxy cannot use +that on-ramp, an owner-operated caller on the approved runner is the first pilot +route; native Codex may operate it only under separate authorization. A future +fixed-operation relay reachable through existing Tailscale would require its own +reviewed authentication/scopes and approval. No generic relay or proxy is proposed +or implemented here. A successful owner-run smoke alone does not make Aster ready. + +## Separate smoke implementation + +`smoke.mjs` exports `GatewayMiddleware` for trusted Gateway RPC and denies ordinary +HTTP. `wrangler.smoke.jsonc` is disabled with blank IDs and `.invalid` hostname; +no public routes, workers.dev, preview URLs, DO, secrets, storage, service bindings, +observability or upstream are configured. It accepts only `GET /smoke/v1` at the +pinned HTTPS host, from the pinned Gateway account/policy context, during an +explicit maximum ten-minute window. Authorization/cookie/upgrade headers and +bodies are denied; response is the constant `private-bridge-smoke-v1`. +It neither invokes identity/posture getters nor logs requests. No Fleet or laptop +operation is reachable. The required entrypoint and no-public-route deployment +pattern follow [Cloudflare Forward documentation](https://developers.cloudflare.com/cloudflare-one/traffic-controls/integrate-workers/forward-traffic/). Platform/Gateway metadata logging is separate and must +be inspected before approval; it is not disabled by this Worker setting. + +This is genuinely **bridge-credential-free**: no new credentials, registry, +signing keys, API tokens, enrollment, secret reads or secret transfer. Existing +Gateway transport authentication may still be necessary; it is not a promise of +an entirely unauthenticated private network. Deployment uses the owner's existing +approved administrative path outside the smoke request. + +Offline reproduction (Node 24, from this directory): + +```sh +npm ci +node --test smoke.test.mjs +WRANGLER_SEND_METRICS=false npx wrangler deploy --dry-run --config wrangler.smoke.jsonc --outdir .wrangler/smoke-dry-run +npm run rehearse +``` + +The Miniflare harness synthesizes Gateway context using a test-only service +binding. Never deploy that harness or give any other Worker such a binding. +It proves handler success/denial, not actual Gateway routing or private DNS. + +## Exact approval request to finalize after metadata is verified + +**Not executable approval yet:** replace every bracketed field with inspected +metadata and attach the resolved config/policy diff before presenting to Drew. +No implicit authority to perform any step below is claimed. + +> Approve a single ten-minute routing smoke in Cloudflare account [full ID, +> verified owner], using existing Gateway organization [ID] and already approved +> runner [exact identity/runtime/on-ramp]. Deploy only Worker +> `private-laptop-bridge-smoke` from [reviewed commit], without public routes, +> workers.dev, preview URLs, bindings, storage or secrets. Create temporary +> Gateway-only DNS policy `private-laptop-bridge-smoke-dns` for +> `private-bridge-smoke.security.cab` -> `192.0.2.1` (TTL 60, no public DNS or +> origin), and HTTP Forward policy `private-laptop-bridge-smoke-forward`, scoped +> to that host, GET `/smoke/v1`, and the existing approved runner identity. +> Use [exact policy ordering and IDs], [START_MS, END_MS UTC], no new enrollment, +> certificates, TLS trust or access grants. Perform at most twelve manual +> requests: normal fixed response, wrong path/method, and controlled no-Forward, +> expired-window and off-on-ramp denials using [already authorized runtimes]. +> No Authorization/Cookie header, client secret, Fleet payload or AMD request is +> sent. Record only status, fixed response, time and redacted routing outcome. +> Then disable and delete exactly these two temporary policies and Worker; +> verify removal and retain the existing fallback. Approve this cleanup in the +> same action set. Stop on unexpected public resolution, successful bypass, +> resource mismatch or any need for new permissions. Maximum incremental spend +> $0, no upgrade; require existing allowance headroom for twelve requests. + +`192.0.2.1` is a proposed non-serving documentation sink, not proof of routing. +Before the run, inspect public DNS/wildcards, Workers routes and Gateway policy +ordering using authorized read-only metadata. A Forward miss must not reach any +origin. The HTTP Block-before-Forward ordering described in STAGING.md still +applies. Do not test CONNECT/WebSocket by creating a tunnel; verify rejection +policy and absent origin. If DNS sink composition fails, stop rather than adding +public ingress. Off-on-ramp denial needs a separately approved runtime and cannot +be inferred from direct Worker denial in Miniflare. + +No recurring polling or persistent access is introduced. The Worker expiration +bounds response availability, not resource lifetime; explicit approved cleanup +is mandatory even after failure. No budget reservation or current-plan assertion +is made without account metadata. The full bridge pilot and AMD installation +remain separate later approvals under STAGING.md. + +## Review checkpoint + +At `dab58829a6d17498da3cae7e9f9456e85f6f6b64`, GitHub reported zero check runs, +zero commit statuses, zero Actions runs, zero reviews and zero inline review +comments. The combined status `pending` meant absent statuses, not running CI. +The draft was mergeable/clean. CodeRabbit's sole comment skipped draft review. +There were no external findings to resolve. The independent local review found +that the original signed bridge was unsuitable for a credential-free smoke; +this separate artifact addresses that concrete gap. See VERIFICATION.md for +final-head offline test evidence; no CI pass or live reachability is claimed. diff --git a/pm-stack/private-laptop-bridge/STAGING.md b/pm-stack/private-laptop-bridge/STAGING.md index 42daaca972..54180c4231 100644 --- a/pm-stack/private-laptop-bridge/STAGING.md +++ b/pm-stack/private-laptop-bridge/STAGING.md @@ -285,3 +285,6 @@ or infrastructure; or retiring Desktop Commander. Resolve real account/rule/post IDs, verified email, runner ownership, Nix paths, certificate fingerprint and pilot UTC window into a final diff first. Seek approval for that exact diff, starting with the credential-free network smoke; do not request blanket access. + +Read-only account/runner discovery and the separate smoke approval gate are in +[DISCOVERY.md](DISCOVERY.md). diff --git a/pm-stack/private-laptop-bridge/VERIFICATION.md b/pm-stack/private-laptop-bridge/VERIFICATION.md index 19347cbcda..5731de3275 100644 --- a/pm-stack/private-laptop-bridge/VERIFICATION.md +++ b/pm-stack/private-laptop-bridge/VERIFICATION.md @@ -88,3 +88,19 @@ not a security certification. Follow the README's rollout/rollback gates. Keep the PR a draft and keep the fallback until owner-approved end-to-end laptop acceptance is complete. + +## Routing-smoke follow-up (2026-11-22) + +The separate `smoke.mjs` has three real Miniflare RPC acceptance tests: constant +success without credentials/storage, ordinary HTTP and route/context/credential +header denials, and disabled/invalid/expired/future/overlong-window denials. +The test oracle is the fixed response or exact denial status. It never calls +AMD, Cloudflare or an origin. Independent review corrected the exported entrypoint +to Cloudflare's required `GatewayMiddleware` and added rejection of accidental +bridge credential headers. `wrangler.smoke.jsonc` dry run bundles 1.96 KiB +(0.98 KiB gzip), with only disabled non-secret configuration variables. + +The final commit is tested again after committing; exact SHA and command results +are recorded in the draft PR checkpoint to avoid a self-referential commit hash. +Read-only discovery and the unapproved, metadata-blocked ten-minute smoke packet +are in DISCOVERY.md. Proxy routing readiness is not private-host reachability. diff --git a/pm-stack/private-laptop-bridge/smoke.mjs b/pm-stack/private-laptop-bridge/smoke.mjs new file mode 100644 index 0000000000..106bd4df38 --- /dev/null +++ b/pm-stack/private-laptop-bridge/smoke.mjs @@ -0,0 +1,20 @@ +// Stateless Gateway routing rehearsal. No bridge credentials, storage or Fleet data. +import { WorkerEntrypoint } from 'cloudflare:workers'; +const reply = (status) => new Response(status === 200 ? 'private-bridge-smoke-v1\n' : 'denied\n', { + status, headers: {'cache-control':'no-store','content-type':'text/plain','x-content-type-options':'nosniff'} +}); +export class GatewayMiddleware extends WorkerEntrypoint { + async handle(request, context, _next) { + const {ENABLED, GATEWAY_HOST:host, GATEWAY_ACCOUNT_ID:account, GATEWAY_POLICY_ID:policy, START_MS:start, END_MS:end} = this.env; + const now = Date.now(), begins = Number(start), ends = Number(end); + if (ENABLED !== 'true' || !/^\d{13}$/.test(start || '') || !/^\d{13}$/.test(end || '') || ends <= begins || ends - begins > 600000 || now < begins || now >= ends) return reply(503); + if (typeof host !== 'string' || host.length > 253 || host.split('.').some(x => x.length > 63) || !/^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,63}$/.test(host) || !/^[0-9a-f]{32}$/.test(account || '') || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(policy || '')) return reply(503); + const expected = `https://${host}/smoke/v1`; + if (request.method !== 'GET' || request.url !== expected || request.body !== null || [...request.headers.keys()].some(h => ['authorization','proxy-authorization','cookie','upgrade'].includes(h) || h.startsWith('x-bridge-'))) return reply(403); + if (!context || context.accountId !== account || context.policyId !== policy || context.host !== host || context.uri !== expected || (context.sni !== undefined && context.sni !== host)) return reply(403); + // Gateway policy supplies the approved transport restriction. Service bindings + // could fabricate context and must never be granted to other Workers. + return reply(200); + } +} +export default {fetch() {return reply(403);}}; diff --git a/pm-stack/private-laptop-bridge/smoke.test.mjs b/pm-stack/private-laptop-bridge/smoke.test.mjs new file mode 100644 index 0000000000..a0a2e67bb7 --- /dev/null +++ b/pm-stack/private-laptop-bridge/smoke.test.mjs @@ -0,0 +1,29 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {Miniflare} from 'miniflare'; +import {fileURLToPath} from 'node:url'; +const host='private-bridge-smoke.invalid', account='a'.repeat(32), policy='11111111-1111-1111-1111-111111111111'; +async function harness(t, overrides={}) { + const mf=new Miniflare({host:'127.0.0.1',workers:[ + {name:'harness',modules:true,compatibilityDate:'2026-07-30',serviceBindings:{SMOKE:{name:'smoke',entrypoint:'GatewayMiddleware'}},script:`export default {async fetch(r,e){const c={accountId:'${account}',policyId:'${policy}',host:'${host}',uri:r.url,sni:'${host}'}; const mode=r.headers.get('x-mode'); if(mode==='upgrade') {const h=new Headers(r.headers);h.set('upgrade','websocket');r=new Request(r,{headers:h});} if(mode==='missing') return e.SMOKE.handle(r,null); if(mode==='wrong') c.policyId='wrong'; if(mode==='uri') c.uri+='?x'; return e.SMOKE.handle(r,c,()=>{throw Error('no next')});}}`}, + {name:'smoke',modules:true,compatibilityDate:'2026-07-30',scriptPath:fileURLToPath(new URL('./smoke.mjs',import.meta.url)),bindings:{ENABLED:'true',GATEWAY_HOST:host,GATEWAY_ACCOUNT_ID:account,GATEWAY_POLICY_ID:policy,START_MS:String(Date.now()-1000),END_MS:String(Date.now()+60000),...overrides},outboundService:()=>{throw Error('no outbound');}} + ]}); await mf.ready; t.after(()=>mf.dispose()); return mf; +} +test('stateless smoke succeeds without keys, registry, identity getters, storage or upstream',async t=>{ + const mf=await harness(t); const r=await mf.dispatchFetch(`https://${host}/smoke/v1`); assert.equal(r.status,200);assert.equal(await r.text(),'private-bridge-smoke-v1\n');assert.equal(r.headers.get('cache-control'),'no-store'); + const direct=await mf.getWorker('smoke'); assert.equal((await direct.fetch(`https://${host}/smoke/v1`)).status,403); +}); +test('smoke denies untrusted routes, credentials and context',async t=>{ + const mf=await harness(t); + for(const [url,options] of [ + [`http://${host}/smoke/v1`,{}],[`https://${host}/smoke/v1?x`,{}],[`https://${host}/v1/call`,{}], + ...['missing','wrong','uri','upgrade'].map(mode=>[`https://${host}/smoke/v1`,{headers:{'x-mode':mode}}]), + ...['authorization','proxy-authorization','cookie','x-bridge-signature'].map(h=>[`https://${host}/smoke/v1`,{headers:{[h]:'synthetic'}}]), + [`https://${host}/smoke/v1`,{method:'POST',body:'synthetic'}] + ]) assert.equal((await mf.dispatchFetch(url,options)).status,403); +}); +test('smoke requires explicit configuration and at most ten minute active window',async t=>{ + for(const override of [{ENABLED:'false'},{GATEWAY_ACCOUNT_ID:''},{GATEWAY_POLICY_ID:''},{START_MS:''},{END_MS:String(Date.now()-1)},{START_MS:String(Date.now()+60000),END_MS:String(Date.now()+120000)},{START_MS:String(Date.now()-1000),END_MS:String(Date.now()+600001)}]) { + const mf=await harness(t,override); assert.equal((await mf.dispatchFetch(`https://${host}/smoke/v1`)).status,503); + } +}); diff --git a/pm-stack/private-laptop-bridge/wrangler.smoke.jsonc b/pm-stack/private-laptop-bridge/wrangler.smoke.jsonc new file mode 100644 index 0000000000..47d1de24ab --- /dev/null +++ b/pm-stack/private-laptop-bridge/wrangler.smoke.jsonc @@ -0,0 +1,18 @@ +{ + "name": "private-laptop-bridge-smoke", + "main": "smoke.mjs", + "compatibility_date": "2026-07-30", + "workers_dev": false, + "preview_urls": false, + "routes": [], + "observability": {"enabled": false}, + "limits": {"cpu_ms": 10}, + "vars": { + "ENABLED": "false", + "GATEWAY_HOST": "private-bridge-smoke.invalid", + "GATEWAY_ACCOUNT_ID": "", + "GATEWAY_POLICY_ID": "", + "START_MS": "", + "END_MS": "" + } +} From 4f6e3fbbcf2711ac1fe3fa7cfe7c8849642a2dda Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 13:14:44 +0000 Subject: [PATCH 08/33] Add protected cf version workflow for private bridge smoke --- .../workflows/private-laptop-bridge-smoke.yml | 123 + pm-stack/private-laptop-bridge/DISCOVERY.md | 52 + pm-stack/private-laptop-bridge/README.md | 3 + .../cloudflare.config.ts | 18 + .../private-laptop-bridge/package-lock.json | 2570 +++++++++++++---- pm-stack/private-laptop-bridge/package.json | 3 +- 6 files changed, 2219 insertions(+), 550 deletions(-) create mode 100644 .github/workflows/private-laptop-bridge-smoke.yml create mode 100644 pm-stack/private-laptop-bridge/cloudflare.config.ts diff --git a/.github/workflows/private-laptop-bridge-smoke.yml b/.github/workflows/private-laptop-bridge-smoke.yml new file mode 100644 index 0000000000..b8e433fb2e --- /dev/null +++ b/.github/workflows/private-laptop-bridge-smoke.yml @@ -0,0 +1,123 @@ +name: Private laptop bridge smoke Worker + +on: + workflow_dispatch: + inputs: + action: + description: Upload a disabled version, or promote a previously reviewed version + type: choice + required: true + options: [upload, promote] + version_id: + description: Exact version UUID; required for promote and ignored for upload + type: string + required: false + +permissions: + contents: read + +concurrency: + group: private-laptop-bridge-smoke-deploy + cancel-in-progress: false + +jobs: + deploy: + if: github.repository == 'developing-today/code' && github.ref == 'refs/heads/main' + environment: cloudflare-staging + runs-on: ubuntu-24.04 + timeout-minutes: 15 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.sha }} + persist-credentials: false + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + with: + node-version: 24.22.0 + cache: npm + cache-dependency-path: pm-stack/private-laptop-bridge/package-lock.json + - name: Install pinned cf CLI and locked project tooling + working-directory: pm-stack/private-laptop-bridge + run: npm ci --ignore-scripts --no-audit --no-fund + - name: Validate request and Cloudflare target + env: + ACTION_KIND: ${{ inputs.action }} + VERSION_ID: ${{ inputs.version_id }} + CF_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }} + CF_API_TOKEN: ${{ secrets.CF_API_TOKEN }} + run: | + set -euo pipefail + [[ "$GITHUB_REF" == refs/heads/main && "$GITHUB_EVENT_NAME" == workflow_dispatch ]] + [[ "$CF_ACCOUNT_ID" =~ ^[0-9a-f]{32}$ && -n "$CF_API_TOKEN" ]] + if [[ "$ACTION_KIND" == upload ]]; then + [[ -z "$VERSION_ID" ]] + elif [[ "$ACTION_KIND" == promote ]]; then + [[ "$VERSION_ID" =~ ^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$ ]] + else exit 2; fi + - name: Test stateless smoke Worker + if: inputs.action == 'upload' + working-directory: pm-stack/private-laptop-bridge + run: node --test smoke.test.mjs + - name: Upload immutable version only + if: inputs.action == 'upload' + working-directory: pm-stack/private-laptop-bridge + env: + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }} + CLOUDFLARE_API_TOKEN: ${{ secrets.CF_API_TOKEN }} + run: | + set -euo pipefail + sha="$GITHUB_SHA" + tag="git-${sha:0:12}" + npx --no-install cf -q workers versions create --worker private-laptop-bridge-smoke --tag "$tag" --message "smoke candidate $sha" + npx --no-install cf -q workers versions list --worker-id private-laptop-bridge-smoke > "$RUNNER_TEMP/versions.json" + python3 - "$RUNNER_TEMP/versions.json" "$tag" "$GITHUB_STEP_SUMMARY" <<'PY' + import json,sys + d=json.load(open(sys.argv[1])); versions=d if isinstance(d,list) else d.get('result', d.get('versions', [])) + if isinstance(versions,dict): versions=versions.get('items',[]) + found=[v for v in versions if v.get('annotations',{}).get('workers/tag')==sys.argv[2]] + if not found: raise SystemExit('Uploaded version with exact git tag not listed by Cloudflare') + found.sort(key=lambda v:v.get('metadata',{}).get('created_on',''),reverse=True) + version=found[0]['id'] + open(sys.argv[3],'a').write(f"Uploaded immutable version `{version}` for `{sys.argv[2]}`. It is not deployed.\n") + print(version) + PY + version="$(python3 -c 'import json,sys;d=json.load(open(sys.argv[1]));vs=d if isinstance(d,list) else d.get("result",d.get("versions",[]));vs=vs.get("items",[]) if isinstance(vs,dict) else vs;tag="git-"+sys.argv[2][:12];m=[v for v in vs if v.get("annotations",{}).get("workers/tag")==tag];m.sort(key=lambda v:v.get("metadata",{}).get("created_on",""),reverse=True);print(m[0]["id"])' "$RUNNER_TEMP/versions.json" "$GITHUB_SHA")" + curl --fail --silent --show-error --max-time 15 -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/workers/scripts/private-laptop-bridge-smoke/versions?deployable=true" > "$RUNNER_TEMP/deployable.json" + python3 - "$RUNNER_TEMP/deployable.json" "$version" <<'PY' + import json,sys + d=json.load(open(sys.argv[1])); vs=d.get('result',[]); vs=vs.get('items',[]) if isinstance(vs,dict) else vs + if not d.get('success') or sys.argv[2] not in [v.get('id') for v in vs]: raise SystemExit('Uploaded version is not in deployable set') + PY + echo "Candidate version: $version" >> "$GITHUB_STEP_SUMMARY" + - name: Verify exact promotion candidate + if: inputs.action == 'promote' + env: + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }} + CLOUDFLARE_API_TOKEN: ${{ secrets.CF_API_TOKEN }} + VERSION_ID: ${{ inputs.version_id }} + run: | + set -euo pipefail + curl --fail --silent --show-error --max-time 15 -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/workers/scripts/private-laptop-bridge-smoke/versions?deployable=true" > "$RUNNER_TEMP/deployable.json" + python3 - "$RUNNER_TEMP/deployable.json" "$VERSION_ID" <<'PY' + import json,sys + d=json.load(open(sys.argv[1])); vs=d.get('result',[]); vs=vs.get('items',[]) if isinstance(vs,dict) else vs + if not d.get('success') or sys.argv[2] not in [v.get('id') for v in vs]: raise SystemExit('Exact requested version is not deployable') + PY + - name: Promote exact immutable version to 100 percent + if: inputs.action == 'promote' + working-directory: pm-stack/private-laptop-bridge + env: + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }} + CLOUDFLARE_API_TOKEN: ${{ secrets.CF_API_TOKEN }} + VERSION_ID: ${{ inputs.version_id }} + run: | + set -euo pipefail + npx --no-install cf -q workers deployments create --worker private-laptop-bridge-smoke --strategy percentage --versions "[{\"version_id\":\"$VERSION_ID\",\"percentage\":100}]" + npx --no-install cf -q workers deployments list --worker private-laptop-bridge-smoke > "$RUNNER_TEMP/deployments.json" + python3 - "$RUNNER_TEMP/deployments.json" "$VERSION_ID" "$GITHUB_STEP_SUMMARY" <<'PY' + import json,sys + d=json.load(open(sys.argv[1])); rows=d if isinstance(d,list) else d.get('result',d.get('deployments',[])); rows=rows.get('items',[]) if isinstance(rows,dict) else rows + matches=[x for x in rows if any(v.get('version_id')==sys.argv[2] and int(v.get('percentage',0))==100 for v in x.get('versions',[]))] + if not matches: raise SystemExit('Deployment read-back did not confirm exact version at 100 percent') + open(sys.argv[3],'a').write(f"Promoted `{sys.argv[2]}` and verified deployment read-back at 100%. Smoke ingress remains separately controlled by Gateway policy.\n") + PY diff --git a/pm-stack/private-laptop-bridge/DISCOVERY.md b/pm-stack/private-laptop-bridge/DISCOVERY.md index 1c34832de9..a23d98a2ae 100644 --- a/pm-stack/private-laptop-bridge/DISCOVERY.md +++ b/pm-stack/private-laptop-bridge/DISCOVERY.md @@ -129,3 +129,55 @@ There were no external findings to resolve. The independent local review found that the original signed bridge was unsuitable for a credential-free smoke; this separate artifact addresses that concrete gap. See VERIFICATION.md for final-head offline test evidence; no CI pass or live reachability is claimed. + +## GitHub Actions deployment boundary + +`.github/workflows/private-laptop-bridge-smoke.yml` is manual only, accepts no +branch/ref input, and runs only when the dispatch ref is exactly `main` in +`developing-today/code`. It checks out the triggering SHA, has `contents: read` +only, serializes runs without cancellation, pins Actions by commit and pins +Node/cf through the workflow and npm lockfile. It targets only +`private-laptop-bridge-smoke`; it does not deploy `private-laptop-bridge-staging` +or create/modify Gateway DNS, HTTP Forward, TLS or identity policies. Upload +creates an immutable version and checks Cloudflare's `deployable=true` set. +Promotion is a separate explicit dispatch with the exact version UUID, repeats +the deployability check, creates a 100% deployment, and reads back the exact +version/percentage. Re-promoting an earlier retained version is the recovery +path; a fix-forward uploads a new version and then separately promotes that +UUID. Neither path changes Gateway traffic policy. Smoke application behavior +stays disabled until the reviewed config carries its bounded test window. + +Before enabling the `cloudflare-staging` GitHub Environment, configure required +reviewers and prevent untrusted branches from using it. Set exactly these +**environment** secrets (never repository-wide): + +- `CF_ACCOUNT_ID`: full 32-character account ID for the verified staging account. +- `CF_API_TOKEN`: short-lived/rotatable token restricted to that account, with + **Workers Scripts: Edit** and **Workers Scripts: Read** only. No Gateway, + Access, DNS, Zone, User, or account administration permissions. The token is + used only in the protected job environment and never printed. + +Those resource names/scopes are the minimum for version upload/list, deployable +version API read and deployment create/list. Verify them against Cloudflare's +current token permission catalogue before provisioning. Do not store AMD laptop +runtime keys or Gateway credentials in this environment. The environment and +secret names are proposed; no secrets were read or configured. + +Exact target for this workflow is the isolated staging smoke Worker named +`private-laptop-bridge-smoke` in the verified account. Steps: owner establishes +required-reviewer protection and scoped environment secrets; dispatch +`upload` on `main`; inspect the summary's exact immutable version and checks; +review the source/config diff; dispatch `promote` with that exact UUID under the +environment approval; verify deployment read-back. Gateway Forward remains +unchanged, so this does not test private ingress by itself. For rollback, dispatch +`promote` with the previously recorded known-good UUID. For a code fix, upload a +new commit's version and promote its UUID only after review. If no retained known- +good version exists or deployment read-back mismatches, stop and use Cloudflare's +owner console to inspect; never edit traffic policies as automated recovery. + +This is not the bridge runtime release workflow. The live bridge requires a +separate reviewed `cf` native configuration for its Durable Object, explicit +nonsecret Gateway identifiers and staging registry/separate runtime identity +provisioning. It must not be silently folded into this smoke deploy. The existing +`wrangler.staging.jsonc` remains a local dry-run artifact; existing production +traffic and access policies are untouched. diff --git a/pm-stack/private-laptop-bridge/README.md b/pm-stack/private-laptop-bridge/README.md index 8e415ab296..022f998c08 100644 --- a/pm-stack/private-laptop-bridge/README.md +++ b/pm-stack/private-laptop-bridge/README.md @@ -255,3 +255,6 @@ list still has `complete:false,total:null` and proves no global empty total. approved non-root caller runner. Its end-to-end test exercises actual CLI parsing, signing, Worker/SQLite execution, the laptop client, and bounded JSON output. No Aster connector or runner access is installed by this package. + + +The separate stateless smoke Worker has a manual, protected GitHub Actions deployment using the pinned `cf` Versions API flow. It uploads immutable versions first and requires a second explicit exact-UUID promotion. It does not deploy the bridge Worker or change Gateway policies; see [DISCOVERY.md](DISCOVERY.md). diff --git a/pm-stack/private-laptop-bridge/cloudflare.config.ts b/pm-stack/private-laptop-bridge/cloudflare.config.ts new file mode 100644 index 0000000000..3561454f4f --- /dev/null +++ b/pm-stack/private-laptop-bridge/cloudflare.config.ts @@ -0,0 +1,18 @@ +import {bindings, defineConfig} from 'cf/config'; +import * as entrypoint from './smoke.mjs' with {type:'cf-worker'}; + +// Staging deployment target is the bounded, stateless network smoke only. +// The live bridge remains disabled pending a separately reviewed config. +export default defineConfig({ + worker: { + name: 'private-laptop-bridge-smoke', + compatibilityDate: '2026-07-30', + entrypoint, + env: { + ENABLED: bindings.text('false'), + GATEWAY_HOST: bindings.text('private-bridge-smoke.invalid'), + GATEWAY_ACCOUNT_ID: bindings.text(''), GATEWAY_POLICY_ID: bindings.text(''), + START_MS: bindings.text(''), END_MS: bindings.text(''), + }, + }, +}); diff --git a/pm-stack/private-laptop-bridge/package-lock.json b/pm-stack/private-laptop-bridge/package-lock.json index 96675a798c..44b521a595 100644 --- a/pm-stack/private-laptop-bridge/package-lock.json +++ b/pm-stack/private-laptop-bridge/package-lock.json @@ -6,6 +6,7 @@ "": { "name": "private-laptop-bridge", "devDependencies": { + "cf": "1.0.0-beta.20", "miniflare": "4.20260730.0", "wrangler": "4.166.0" }, @@ -13,6 +14,26 @@ "node": ">=24" } }, + "node_modules/@cloudflare/build-output-utils": { + "version": "0.9.3", + "resolved": "https://registry.npmjs.org/@cloudflare/build-output-utils/-/build-output-utils-0.9.3.tgz", + "integrity": "sha512-0MgvIq6UxbRWLwB2QJU7qjLqpPkfygOebN3UiENhdp+z6zpRKrNnwkms2ynadmxCOh3sL2v+SI0/pNXxgXdteA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cloudflare/config": "0.27.0" + } + }, + "node_modules/@cloudflare/config": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@cloudflare/config/-/config-0.27.0.tgz", + "integrity": "sha512-wNnL0z4lj5Gm2fze5qXTOvRPbUOi4jlMmwPk7ArCUakI5oVxgjfl3Rhnfd/Mmzo3g86x/ofH75yPIhsa5msqdQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "zod": "4.6.5" + } + }, "node_modules/@cloudflare/kv-asset-handler": { "version": "0.5.1", "resolved": "https://registry.npmjs.org/@cloudflare/kv-asset-handler/-/kv-asset-handler-0.5.1.tgz", @@ -23,26 +44,21 @@ "node": ">=22.0.0" } }, - "node_modules/@cloudflare/unenv-preset": { - "version": "2.16.2", - "resolved": "https://registry.npmjs.org/@cloudflare/unenv-preset/-/unenv-preset-2.16.2.tgz", - "integrity": "sha512-JBP1+Z7ZSNG/d4mRP+y8VC5dka3tZVMLEZRvS+rzQ4DGV1EoxRFQckcJTTkXbHSQiTj0DtNI01Zwb/V2fX0mvQ==", + "node_modules/@cloudflare/runtime-types": { + "version": "0.1.14", + "resolved": "https://registry.npmjs.org/@cloudflare/runtime-types/-/runtime-types-0.1.14.tgz", + "integrity": "sha512-Hx4/RGjTNKPTB0z6q9MRv6GzvnL496EBvvBaUpANilSLfQJFXVkmClrbiMkzTFjzVRTgMsOhO8exwwkZu3OM8w==", "dev": true, - "license": "MIT OR Apache-2.0", - "peerDependencies": { - "unenv": "2.0.0-rc.24", - "workerd": ">1.20260305.0 <2.0.0-0" - }, - "peerDependenciesMeta": { - "workerd": { - "optional": true - } + "license": "MIT", + "dependencies": { + "miniflare": "5.20261019.1-beta", + "workerd": "1.20261019.1" } }, - "node_modules/@cloudflare/workerd-darwin-64": { - "version": "1.20260730.1", - "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-64/-/workerd-darwin-64-1.20260730.1.tgz", - "integrity": "sha512-+MBHmPaiTe2KajryW0T24rZvWFxb41hD3d8anNzQqHzft6vSEb18+sp0znSwxgij7ApPhSM1+vhkNg4f3YMguA==", + "node_modules/@cloudflare/runtime-types/node_modules/@cloudflare/workerd-darwin-64": { + "version": "1.20261019.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-64/-/workerd-darwin-64-1.20261019.1.tgz", + "integrity": "sha512-5ZILbAta/fBQvhmAYeCE7dKMMYIr7N9wJEX50fEGLKSIwGtvT0HzSfHNIK/O7cBQ4gHQ2WfIiPClvwcye6E0fA==", "cpu": [ "x64" ], @@ -56,10 +72,10 @@ "node": ">=16" } }, - "node_modules/@cloudflare/workerd-darwin-arm64": { - "version": "1.20260730.1", - "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-arm64/-/workerd-darwin-arm64-1.20260730.1.tgz", - "integrity": "sha512-SBHKntPkKvNPgaCrTe99xC1CAl8ygJDzlYfK0LbuJ1muKadIw35WnhO0wu894fKBtllsVQdNzDLee+cm0ppLSQ==", + "node_modules/@cloudflare/runtime-types/node_modules/@cloudflare/workerd-darwin-arm64": { + "version": "1.20261019.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-arm64/-/workerd-darwin-arm64-1.20261019.1.tgz", + "integrity": "sha512-cww2Ab6lVMxpTiEEjKmPI58p5EMo0vYTZSH+3WkqXJdQgc3ES66GuL247+U2B2YWajhhu2tqj7jySrXneU749g==", "cpu": [ "arm64" ], @@ -73,10 +89,10 @@ "node": ">=16" } }, - "node_modules/@cloudflare/workerd-linux-64": { - "version": "1.20260730.1", - "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-64/-/workerd-linux-64-1.20260730.1.tgz", - "integrity": "sha512-ouyPOSMbiKPeSwUJUvxtMcxGAXs2J4aPE4T5ABIYX5ClcQx5j5bbHTmnqOQEY8sAuLTPjH7dY+iB6UI5ISlwwA==", + "node_modules/@cloudflare/runtime-types/node_modules/@cloudflare/workerd-linux-64": { + "version": "1.20261019.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-64/-/workerd-linux-64-1.20261019.1.tgz", + "integrity": "sha512-4++VRi9vkQROYqrpZYOixIJuVDmujkwrT4kszsxNFlvcmsX6Mr2GumvxIN3gIixS3vJUh3Umdtkthqj5X0S3Xw==", "cpu": [ "x64" ], @@ -90,10 +106,10 @@ "node": ">=16" } }, - "node_modules/@cloudflare/workerd-linux-arm64": { - "version": "1.20260730.1", - "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-arm64/-/workerd-linux-arm64-1.20260730.1.tgz", - "integrity": "sha512-YQ+Mi78U3TPdgBPtwq+Sm6rJU+Ihl2y0pjYtuuKkdmUbYzL7oLR6Xqq9wljhasnuCFICssDJaqhMep5WizYoEQ==", + "node_modules/@cloudflare/runtime-types/node_modules/@cloudflare/workerd-linux-arm64": { + "version": "1.20261019.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-arm64/-/workerd-linux-arm64-1.20261019.1.tgz", + "integrity": "sha512-75PVtJOwfjScQ53sbLtQXI7D8yP1c21t+WEUPaYbqkzaz4ZqfR5wAd+zuWs8G5Q7kOj2SQIvEfY5Sn8Y+UVrnA==", "cpu": [ "arm64" ], @@ -107,10 +123,10 @@ "node": ">=16" } }, - "node_modules/@cloudflare/workerd-windows-64": { - "version": "1.20260730.1", - "resolved": "https://registry.npmjs.org/@cloudflare/workerd-windows-64/-/workerd-windows-64-1.20260730.1.tgz", - "integrity": "sha512-27fAN+vUECW1oYVc1KOcHYpkL8COM2Uxtxql7TL595kxbjoqS5yckw7NLz7bTf2pALFCZWjqXDjZGJ/xbG4ZKQ==", + "node_modules/@cloudflare/runtime-types/node_modules/@cloudflare/workerd-windows-64": { + "version": "1.20261019.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-windows-64/-/workerd-windows-64-1.20261019.1.tgz", + "integrity": "sha512-z49fvKTETMCnG6wnMcQwxx9CpryFceiKz04FRjq26EkhCyzRNJ6c3UXhyZz3r5f1CXnnBZc5DcU8ZouPkUJCqw==", "cpu": [ "x64" ], @@ -124,517 +140,2026 @@ "node": ">=16" } }, - "node_modules/@cloudflare/workers-utils": { - "version": "0.56.0", - "resolved": "https://registry.npmjs.org/@cloudflare/workers-utils/-/workers-utils-0.56.0.tgz", - "integrity": "sha512-Fw3/zR+pQp+5hKn1CHIRkCYz49fyAb2qRqCq01jBGqlKL0rRnZyXYD4j0h9cjaWPYYQUOe5y6L7BNp2ZwsHg5A==", + "node_modules/@cloudflare/runtime-types/node_modules/@img/sharp-darwin-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.5.tgz", + "integrity": "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==", + "cpu": [ + "arm64" + ], "dev": true, - "license": "MIT OR Apache-2.0", - "dependencies": { - "@cspotcode/source-map-support": "0.8.1", - "chalk": "5.3.0", - "dotenv": "16.3.1", - "undici": "7.30.2" + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" }, - "peerDependencies": { - "vitest": "^4.1.0 || ^5.0.0" + "funding": { + "url": "https://opencollective.com/libvips" }, - "peerDependenciesMeta": { - "vitest": { - "optional": true - } + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.3.4" } }, - "node_modules/@cloudflare/workers-utils/node_modules/undici": { - "version": "7.30.2", - "resolved": "https://registry.npmjs.org/undici/-/undici-7.30.2.tgz", - "integrity": "sha512-mLyPQnHwUxaM/rideoK/+KL8DaAJLRl4aBCfmX444aCSLnIaomqPLtNRe2jdCYcsk5wZzXrDIQC8ZeYNRAYyIA==", + "node_modules/@cloudflare/runtime-types/node_modules/@img/sharp-darwin-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.5.tgz", + "integrity": "sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==", + "cpu": [ + "x64" + ], "dev": true, - "license": "MIT", + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], "engines": { - "node": ">=20.18.1" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.3.4" } }, - "node_modules/@cspotcode/source-map-support": { - "version": "0.8.1", - "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", - "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==", + "node_modules/@cloudflare/runtime-types/node_modules/@img/sharp-freebsd-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.5.tgz", + "integrity": "sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==", "dev": true, - "license": "MIT", + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], "dependencies": { - "@jridgewell/trace-mapping": "0.3.9" + "@img/sharp-wasm32": "0.35.5" }, "engines": { - "node": ">=12" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" } }, - "node_modules/@emnapi/runtime": { - "version": "1.11.3", - "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", - "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", + "node_modules/@cloudflare/runtime-types/node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.4.tgz", + "integrity": "sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==", + "cpu": [ + "arm64" + ], "dev": true, - "license": "MIT", + "license": "LGPL-3.0-or-later", "optional": true, - "dependencies": { - "tslib": "^2.4.0" + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" } }, - "node_modules/@esbuild/aix-ppc64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", - "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "node_modules/@cloudflare/runtime-types/node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.4.tgz", + "integrity": "sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==", "cpu": [ - "ppc64" + "x64" ], "dev": true, - "license": "MIT", + "license": "LGPL-3.0-or-later", "optional": true, "os": [ - "aix" + "darwin" ], - "engines": { - "node": ">=18" + "funding": { + "url": "https://opencollective.com/libvips" } }, - "node_modules/@esbuild/android-arm": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", - "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", + "node_modules/@cloudflare/runtime-types/node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.4.tgz", + "integrity": "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==", "cpu": [ "arm" ], "dev": true, - "license": "MIT", + "license": "LGPL-3.0-or-later", "optional": true, "os": [ - "android" + "linux" ], - "engines": { - "node": ">=18" + "funding": { + "url": "https://opencollective.com/libvips" } }, - "node_modules/@esbuild/android-arm64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", - "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", + "node_modules/@cloudflare/runtime-types/node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.4.tgz", + "integrity": "sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==", "cpu": [ "arm64" ], "dev": true, - "license": "MIT", + "license": "LGPL-3.0-or-later", "optional": true, "os": [ - "android" + "linux" ], - "engines": { - "node": ">=18" + "funding": { + "url": "https://opencollective.com/libvips" } }, - "node_modules/@esbuild/android-x64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", - "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "node_modules/@cloudflare/runtime-types/node_modules/@img/sharp-libvips-linux-ppc64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.4.tgz", + "integrity": "sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==", "cpu": [ - "x64" + "ppc64" ], "dev": true, - "license": "MIT", + "license": "LGPL-3.0-or-later", "optional": true, "os": [ - "android" + "linux" ], - "engines": { - "node": ">=18" + "funding": { + "url": "https://opencollective.com/libvips" } }, - "node_modules/@esbuild/darwin-arm64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", - "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", + "node_modules/@cloudflare/runtime-types/node_modules/@img/sharp-libvips-linux-riscv64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.4.tgz", + "integrity": "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==", "cpu": [ - "arm64" + "riscv64" ], "dev": true, - "license": "MIT", + "license": "LGPL-3.0-or-later", "optional": true, "os": [ - "darwin" + "linux" ], - "engines": { - "node": ">=18" + "funding": { + "url": "https://opencollective.com/libvips" } }, - "node_modules/@esbuild/darwin-x64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", - "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", + "node_modules/@cloudflare/runtime-types/node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.4.tgz", + "integrity": "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==", "cpu": [ - "x64" + "s390x" ], "dev": true, - "license": "MIT", + "license": "LGPL-3.0-or-later", "optional": true, "os": [ - "darwin" + "linux" ], - "engines": { - "node": ">=18" + "funding": { + "url": "https://opencollective.com/libvips" } }, - "node_modules/@esbuild/freebsd-arm64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", - "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", + "node_modules/@cloudflare/runtime-types/node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.4.tgz", + "integrity": "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==", "cpu": [ - "arm64" + "x64" ], "dev": true, - "license": "MIT", + "license": "LGPL-3.0-or-later", "optional": true, "os": [ - "freebsd" + "linux" ], - "engines": { - "node": ">=18" + "funding": { + "url": "https://opencollective.com/libvips" } }, - "node_modules/@esbuild/freebsd-x64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", - "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", + "node_modules/@cloudflare/runtime-types/node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.4.tgz", + "integrity": "sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==", "cpu": [ - "x64" + "arm64" ], "dev": true, - "license": "MIT", + "license": "LGPL-3.0-or-later", "optional": true, "os": [ - "freebsd" + "linux" ], - "engines": { - "node": ">=18" + "funding": { + "url": "https://opencollective.com/libvips" } }, - "node_modules/@esbuild/linux-arm": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", - "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", + "node_modules/@cloudflare/runtime-types/node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.4.tgz", + "integrity": "sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==", "cpu": [ - "arm" + "x64" ], "dev": true, - "license": "MIT", + "license": "LGPL-3.0-or-later", "optional": true, "os": [ "linux" ], - "engines": { - "node": ">=18" + "funding": { + "url": "https://opencollective.com/libvips" } }, - "node_modules/@esbuild/linux-arm64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", - "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", + "node_modules/@cloudflare/runtime-types/node_modules/@img/sharp-linux-arm": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.5.tgz", + "integrity": "sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==", "cpu": [ - "arm64" + "arm" ], "dev": true, - "license": "MIT", + "license": "Apache-2.0", "optional": true, "os": [ "linux" ], "engines": { - "node": ">=18" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.3.4" } }, - "node_modules/@esbuild/linux-ia32": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", - "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", + "node_modules/@cloudflare/runtime-types/node_modules/@img/sharp-linux-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.5.tgz", + "integrity": "sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==", "cpu": [ - "ia32" + "arm64" ], "dev": true, - "license": "MIT", + "license": "Apache-2.0", "optional": true, "os": [ "linux" ], "engines": { - "node": ">=18" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.3.4" } }, - "node_modules/@esbuild/linux-loong64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", - "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", + "node_modules/@cloudflare/runtime-types/node_modules/@img/sharp-linux-ppc64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.5.tgz", + "integrity": "sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==", "cpu": [ - "loong64" + "ppc64" ], "dev": true, - "license": "MIT", + "license": "Apache-2.0", "optional": true, "os": [ "linux" ], "engines": { - "node": ">=18" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-ppc64": "1.3.4" } }, - "node_modules/@esbuild/linux-mips64el": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", - "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", + "node_modules/@cloudflare/runtime-types/node_modules/@img/sharp-linux-riscv64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.5.tgz", + "integrity": "sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==", "cpu": [ - "mips64el" + "riscv64" ], "dev": true, - "license": "MIT", + "license": "Apache-2.0", "optional": true, "os": [ "linux" ], "engines": { - "node": ">=18" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-riscv64": "1.3.4" } }, - "node_modules/@esbuild/linux-ppc64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", - "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", + "node_modules/@cloudflare/runtime-types/node_modules/@img/sharp-linux-s390x": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.5.tgz", + "integrity": "sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==", "cpu": [ - "ppc64" + "s390x" ], "dev": true, - "license": "MIT", + "license": "Apache-2.0", "optional": true, "os": [ "linux" ], "engines": { - "node": ">=18" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.3.4" } }, - "node_modules/@esbuild/linux-riscv64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", - "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", + "node_modules/@cloudflare/runtime-types/node_modules/@img/sharp-linux-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.5.tgz", + "integrity": "sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==", "cpu": [ - "riscv64" + "x64" ], "dev": true, - "license": "MIT", + "license": "Apache-2.0", "optional": true, "os": [ "linux" ], "engines": { - "node": ">=18" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.3.4" } }, - "node_modules/@esbuild/linux-s390x": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", - "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", + "node_modules/@cloudflare/runtime-types/node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.5.tgz", + "integrity": "sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==", "cpu": [ - "s390x" + "arm64" ], "dev": true, - "license": "MIT", + "license": "Apache-2.0", "optional": true, "os": [ "linux" ], "engines": { - "node": ">=18" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4" } }, - "node_modules/@esbuild/linux-x64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", - "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", + "node_modules/@cloudflare/runtime-types/node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.5.tgz", + "integrity": "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==", "cpu": [ "x64" ], "dev": true, - "license": "MIT", + "license": "Apache-2.0", "optional": true, "os": [ "linux" ], "engines": { - "node": ">=18" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.3.4" } }, - "node_modules/@esbuild/netbsd-arm64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", - "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "node_modules/@cloudflare/runtime-types/node_modules/@img/sharp-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.5.tgz", + "integrity": "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==", + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.11.3" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@cloudflare/runtime-types/node_modules/@img/sharp-webcontainers-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.5.tgz", + "integrity": "sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@img/sharp-wasm32": "0.35.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@cloudflare/runtime-types/node_modules/@img/sharp-win32-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.5.tgz", + "integrity": "sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==", "cpu": [ "arm64" ], "dev": true, - "license": "MIT", + "license": "Apache-2.0 AND LGPL-3.0-or-later", "optional": true, "os": [ - "netbsd" + "win32" ], "engines": { - "node": ">=18" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" } }, - "node_modules/@esbuild/netbsd-x64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", - "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "node_modules/@cloudflare/runtime-types/node_modules/@img/sharp-win32-ia32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.5.tgz", + "integrity": "sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==", "cpu": [ - "x64" + "ia32" ], "dev": true, - "license": "MIT", + "license": "Apache-2.0 AND LGPL-3.0-or-later", "optional": true, "os": [ - "netbsd" + "win32" ], "engines": { - "node": ">=18" + "node": "^20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@cloudflare/runtime-types/node_modules/@img/sharp-win32-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.5.tgz", + "integrity": "sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@cloudflare/runtime-types/node_modules/miniflare": { + "version": "5.20261019.1-beta", + "resolved": "https://registry.npmjs.org/miniflare/-/miniflare-5.20261019.1-beta.tgz", + "integrity": "sha512-1n7MN2UqZnPniyYAqNuV1YEAaja66ozKGVCc5ZTmYQhTubnoAwGLccwb+ZWYLOajuw3pOaJ70u//bZMuURlRew==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspotcode/source-map-support": "0.8.1", + "sharp": "0.35.5", + "undici": "7.29.1", + "workerd": "1.20261019.1", + "ws": "8.21.0", + "youch": "4.1.0-beta.10" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@cloudflare/runtime-types/node_modules/sharp": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz", + "integrity": "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@img/colour": "^1.1.0", + "detect-libc": "^2.1.2", + "semver": "^7.8.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.35.5", + "@img/sharp-darwin-x64": "0.35.5", + "@img/sharp-freebsd-wasm32": "0.35.5", + "@img/sharp-libvips-darwin-arm64": "1.3.4", + "@img/sharp-libvips-darwin-x64": "1.3.4", + "@img/sharp-libvips-linux-arm": "1.3.4", + "@img/sharp-libvips-linux-arm64": "1.3.4", + "@img/sharp-libvips-linux-ppc64": "1.3.4", + "@img/sharp-libvips-linux-riscv64": "1.3.4", + "@img/sharp-libvips-linux-s390x": "1.3.4", + "@img/sharp-libvips-linux-x64": "1.3.4", + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4", + "@img/sharp-libvips-linuxmusl-x64": "1.3.4", + "@img/sharp-linux-arm": "0.35.5", + "@img/sharp-linux-arm64": "0.35.5", + "@img/sharp-linux-ppc64": "0.35.5", + "@img/sharp-linux-riscv64": "0.35.5", + "@img/sharp-linux-s390x": "0.35.5", + "@img/sharp-linux-x64": "0.35.5", + "@img/sharp-linuxmusl-arm64": "0.35.5", + "@img/sharp-linuxmusl-x64": "0.35.5", + "@img/sharp-webcontainers-wasm32": "0.35.5", + "@img/sharp-win32-arm64": "0.35.5", + "@img/sharp-win32-ia32": "0.35.5", + "@img/sharp-win32-x64": "0.35.5" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@cloudflare/runtime-types/node_modules/undici": { + "version": "7.29.1", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.29.1.tgz", + "integrity": "sha512-RYONW2MeafgYlkVOKYKkA/Ag7BmXqgIWCa8t1m0JcxrQg9pI9lEqRhAOruOBCbAohOa/gkCF+iPi9hrgvTzu6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.18.1" + } + }, + "node_modules/@cloudflare/runtime-types/node_modules/workerd": { + "version": "1.20261019.1", + "resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20261019.1.tgz", + "integrity": "sha512-UUYRUq/7DmeCl11YriNbcVbjUZVLtt8uuCXFu+nz77hGFf8d4DEVXoCYtnA+MlBatE4+wxoj47DVqzK3xGBAiw==", + "dev": true, + "hasInstallScript": true, + "license": "Apache-2.0", + "bin": { + "workerd": "bin/workerd" + }, + "engines": { + "node": ">=16" + }, + "optionalDependencies": { + "@cloudflare/workerd-darwin-64": "1.20261019.1", + "@cloudflare/workerd-darwin-arm64": "1.20261019.1", + "@cloudflare/workerd-linux-64": "1.20261019.1", + "@cloudflare/workerd-linux-arm64": "1.20261019.1", + "@cloudflare/workerd-windows-64": "1.20261019.1" + } + }, + "node_modules/@cloudflare/unenv-preset": { + "version": "2.16.2", + "resolved": "https://registry.npmjs.org/@cloudflare/unenv-preset/-/unenv-preset-2.16.2.tgz", + "integrity": "sha512-JBP1+Z7ZSNG/d4mRP+y8VC5dka3tZVMLEZRvS+rzQ4DGV1EoxRFQckcJTTkXbHSQiTj0DtNI01Zwb/V2fX0mvQ==", + "dev": true, + "license": "MIT OR Apache-2.0", + "peerDependencies": { + "unenv": "2.0.0-rc.24", + "workerd": ">1.20260305.0 <2.0.0-0" + }, + "peerDependenciesMeta": { + "workerd": { + "optional": true + } + } + }, + "node_modules/@cloudflare/workerd-darwin-64": { + "version": "1.20260730.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-64/-/workerd-darwin-64-1.20260730.1.tgz", + "integrity": "sha512-+MBHmPaiTe2KajryW0T24rZvWFxb41hD3d8anNzQqHzft6vSEb18+sp0znSwxgij7ApPhSM1+vhkNg4f3YMguA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-darwin-arm64": { + "version": "1.20260730.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-arm64/-/workerd-darwin-arm64-1.20260730.1.tgz", + "integrity": "sha512-SBHKntPkKvNPgaCrTe99xC1CAl8ygJDzlYfK0LbuJ1muKadIw35WnhO0wu894fKBtllsVQdNzDLee+cm0ppLSQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-linux-64": { + "version": "1.20260730.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-64/-/workerd-linux-64-1.20260730.1.tgz", + "integrity": "sha512-ouyPOSMbiKPeSwUJUvxtMcxGAXs2J4aPE4T5ABIYX5ClcQx5j5bbHTmnqOQEY8sAuLTPjH7dY+iB6UI5ISlwwA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-linux-arm64": { + "version": "1.20260730.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-arm64/-/workerd-linux-arm64-1.20260730.1.tgz", + "integrity": "sha512-YQ+Mi78U3TPdgBPtwq+Sm6rJU+Ihl2y0pjYtuuKkdmUbYzL7oLR6Xqq9wljhasnuCFICssDJaqhMep5WizYoEQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-windows-64": { + "version": "1.20260730.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-windows-64/-/workerd-windows-64-1.20260730.1.tgz", + "integrity": "sha512-27fAN+vUECW1oYVc1KOcHYpkL8COM2Uxtxql7TL595kxbjoqS5yckw7NLz7bTf2pALFCZWjqXDjZGJ/xbG4ZKQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workers-utils": { + "version": "0.56.0", + "resolved": "https://registry.npmjs.org/@cloudflare/workers-utils/-/workers-utils-0.56.0.tgz", + "integrity": "sha512-Fw3/zR+pQp+5hKn1CHIRkCYz49fyAb2qRqCq01jBGqlKL0rRnZyXYD4j0h9cjaWPYYQUOe5y6L7BNp2ZwsHg5A==", + "dev": true, + "license": "MIT OR Apache-2.0", + "dependencies": { + "@cspotcode/source-map-support": "0.8.1", + "chalk": "5.3.0", + "dotenv": "16.3.1", + "undici": "7.30.2" + }, + "peerDependencies": { + "vitest": "^4.1.0 || ^5.0.0" + }, + "peerDependenciesMeta": { + "vitest": { + "optional": true + } + } + }, + "node_modules/@cloudflare/workers-utils/node_modules/undici": { + "version": "7.30.2", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.30.2.tgz", + "integrity": "sha512-mLyPQnHwUxaM/rideoK/+KL8DaAJLRl4aBCfmX444aCSLnIaomqPLtNRe2jdCYcsk5wZzXrDIQC8ZeYNRAYyIA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.18.1" + } + }, + "node_modules/@cspotcode/source-map-support": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", + "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.9" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@emnapi/runtime": { + "version": "1.11.3", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", + "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/colour": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", + "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.2.tgz", + "integrity": "sha512-eEieHsMksAW4IiO5NzauESRl2D2qz3J/kwUxUrSfV06A93eEaRfMpHXyUb1mAqrR7i8U9A0GRqE9pjn6u1Jjpg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.3.1" + } + }, + "node_modules/@img/sharp-darwin-x64": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.2.tgz", + "integrity": "sha512-BaktuGPCeHJMARpodR8jK4uKiZrPAy9WrfQW0sdI37clracq8Bp01AYS3SZgi5FS/y5twa9t4+LIuuxQjqRrWw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.3.1" + } + }, + "node_modules/@img/sharp-freebsd-wasm32": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.2.tgz", + "integrity": "sha512-YoAxdnd8hPUkvLHd3bWY+YA8nw3xM/RyRopYucNsWHVSan8NLVM3X2volsfoRDcXdUJPg6tXahSd7HXPK7lRnw==", + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "dependencies": { + "@img/sharp-wasm32": "0.35.2" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.1.tgz", + "integrity": "sha512-4V/M3roRMTYjiwZY9IOVQOE8OyeCxFAkYmyZDrZl51uOKjibm3oeEJ4WAmLxutAfzFbC9jqUiPs2gbnGflH+7g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.1.tgz", + "integrity": "sha512-c0/DxItpJv2+dGhgycJBBgotdqruGYDvA79drdh0MD1dFpy7JzJ/PlXwi1H4rFf0eTy8tgbI91aHDnZIceY3jQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.1.tgz", + "integrity": "sha512-aGGy9aWzXgHBG7HNyQPWorZthlp7+x6fDRoPAQbGO3ThcttuTyKIx3NuSHb6zb4gBNq6/yNn9f1cy9nFKS/Vmg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.1.tgz", + "integrity": "sha512-JznefmcK9j1JKPz8AkQDh89kjojubyfOasWBPKfzMIhPwsgDy9evpE/naJTXXXmghS1iFwR8u/kTwh/I2/+GCw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-ppc64": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.1.tgz", + "integrity": "sha512-1EkwGNCZk6iWNCMWqrvdJ+r1j0PT1zIz60CNPhYnJlK/zyeWqlsPZIe+ocBVqPF8k/Ssee/NCk+tE9Ryrko6ng==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-riscv64": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.1.tgz", + "integrity": "sha512-Ilays+w2bXdnxzxtQdmXR62u8o8GYa3eL4+Gr+1KiE4xperMZUslRaVPJwwPkzlHEjGfXAfRVAa/7CYCtSqsBw==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.1.tgz", + "integrity": "sha512-VfBwVHQTbRoj4XlpA/KLZ7ltgMpz+4WSejFzQ+GnoImjo1PtEJ59QB2qR1xQEeRPYIkNrPIm2L4cICMvz4C2ew==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.1.tgz", + "integrity": "sha512-+c8ukgwU62DS54nCAjw7keOfHUkmr0B5QHEdcOqRnodF/MNXJbVI8Eopoj4B/0H8Asr65I+A4Amrn7a85/md6A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.1.tgz", + "integrity": "sha512-qlKb/pwbkAi1WMsJrYHk7CuDrd12s27U2QnRhFYUoJNrRCmkosMTttuRFat/DDB3IlDm5qE1TJgZ4JDnHX8Ldw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.1.tgz", + "integrity": "sha512-yO21HwoUVLN8Qa+/SBjQLMYwBWAVJjeGPNe+hc0OUeMeifEtJqu5a1c4HayE1nNpDih9y3/KkoltfkDodmKAlg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-arm": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.2.tgz", + "integrity": "sha512-SE4kzF2mepn6z+6E7L6lsV8FzuLL6IPQdyX8ZiwROAG/G8td+hP/m7FsFPwidtrF19gvajuC9l6TxAVcsA4S7A==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.3.1" + } + }, + "node_modules/@img/sharp-linux-arm64": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.2.tgz", + "integrity": "sha512-af12Pnd0ZGu2HfP8NayB0kk6eC/lrfbQE6HlR4jD+34wdJ1Vw9TF6TMn6ZvffT+WgqVsl0hRbmNvz2u/23VmwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.3.1" + } + }, + "node_modules/@img/sharp-linux-ppc64": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.2.tgz", + "integrity": "sha512-hYSBm7zcNtDCozCxQHYZJiu63b/bXsgRZuOxCIBZsStMM9Vap47iFHdbX4kCvQsblPB/k+clhELpdQJHQLSHvg==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-ppc64": "1.3.1" + } + }, + "node_modules/@img/sharp-linux-riscv64": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.2.tgz", + "integrity": "sha512-qQt0Kc13+Hoan/Awq/qMSQw3L+RI1NCRPgD5cUJ/1WSSmIoysLOc72jlRM3E0OHN9Yr313jgeQ2T+zW+F03QFA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-riscv64": "1.3.1" + } + }, + "node_modules/@img/sharp-linux-s390x": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.2.tgz", + "integrity": "sha512-E4fLLfRPzDLlEeDaTzI98OFLcv++WL5ChLLMwPoVd0CIoZQqupBSNbOisPL5am9XsbQ9T84+iiMpUvbFtkunbA==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.3.1" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.2.tgz", + "integrity": "sha512-gi0zFJJRLswfCZmHtJdikXPOc5u7qamSOS3NHedLqLd4W8Q0NqjdBr6TTRIgsfFjqfTsHFgdfvJ9LwqSgcHiAA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.3.1" + } + }, + "node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.2.tgz", + "integrity": "sha512-siWbOW1u6HFnFLrp0waKyW7VEf7jYvcDWdrXEFa8AkdAQgEvuu5Fz8/Y70w9EeqAdwDtfU012BhEHHaDqvQNzg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.3.1" + } + }, + "node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.2.tgz", + "integrity": "sha512-YBqMMcjDi4QGYiSn4vNOYBhmlC4z5AXqkOUUqI2e0AFA4urNv4ESgOgwNl3K+4etQhha0twXlzeF20bbULm9Yg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.3.1" + } + }, + "node_modules/@img/sharp-wasm32": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.2.tgz", + "integrity": "sha512-Mrv4JQNYVQ94xH+jzZ9r+gowleN8mv2FTgKT+PI6bx5C0G8TdNYndu161pg2i7uoBwxy2ImPMHrJOM2LZef7Bw==", + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.11.1" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-webcontainers-wasm32": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.2.tgz", + "integrity": "sha512-QNV27pxs9wpApEiCfvHM1RDoP1w1+2KrUWWDPEhEwg+latvOrfuhWrHWZKwdSFwU6jh3myjw/yOCRsUIuOft3g==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@img/sharp-wasm32": "0.35.2" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-arm64": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.2.tgz", + "integrity": "sha512-BiVRYc/t6/Vl3e1hBx0hugG4oN9Pydf4fgMSpxTQJmwGUg/YoXTWHiFeRymHfCZzifxu4F4rpk/I67D0LQ20wQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-ia32": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.2.tgz", + "integrity": "sha512-YYEhx9PImCC7T0tI8JDMi4DB9LwLCXCU5OWNYEXAxh5Q1ShKkyC6byxzoBJ3gEFDnH2lQckWuDe70G7mB2XJog==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-x64": { + "version": "0.35.2", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.2.tgz", + "integrity": "sha512-imoOyBcoM/iiUr4J6VPpCNjPnjvP/Gks95898yB8YqoGGYmHYbOyCuNv9FMhFgtaiHFGbHW8bxKqRV6VjtXThQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz", + "integrity": "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", + "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.0.3", + "@jridgewell/sourcemap-codec": "^1.4.10" + } + }, + "node_modules/@poppinss/colors": { + "version": "4.1.6", + "resolved": "https://registry.npmjs.org/@poppinss/colors/-/colors-4.1.6.tgz", + "integrity": "sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg==", + "dev": true, + "license": "MIT", + "dependencies": { + "kleur": "^4.1.5" + } + }, + "node_modules/@poppinss/dumper": { + "version": "0.6.5", + "resolved": "https://registry.npmjs.org/@poppinss/dumper/-/dumper-0.6.5.tgz", + "integrity": "sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@poppinss/colors": "^4.1.5", + "@sindresorhus/is": "^7.0.2", + "supports-color": "^10.0.0" + } + }, + "node_modules/@poppinss/exception": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@poppinss/exception/-/exception-1.2.3.tgz", + "integrity": "sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@sindresorhus/is": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-7.2.0.tgz", + "integrity": "sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sindresorhus/is?sponsor=1" + } + }, + "node_modules/@speed-highlight/core": { + "version": "1.2.24", + "resolved": "https://registry.npmjs.org/@speed-highlight/core/-/core-1.2.24.tgz", + "integrity": "sha512-qeW2e1l78afw8VhRPfPQ1Gjj+KU5XFQ/OFV5ti6eTa9bruO7mJyZtA4vw0ofqmA3tKCkROE9xLk3VZoeRc98nw==", + "dev": true, + "license": "CC0-1.0" + }, + "node_modules/@types/node": { + "version": "18.19.130", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.130.tgz", + "integrity": "sha512-GRaXQx6jGfL8sKfaIDD6OupbIHBr9jv7Jnaml9tB7l4v068PAOXqfcujMMo5PhbIs6ggR1XODELqahT2R8v0fg==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~5.26.4" + } + }, + "node_modules/@types/node-fetch": { + "version": "2.6.13", + "resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.6.13.tgz", + "integrity": "sha512-QGpRVpzSaUs30JBSGPjOg4Uveu384erbHBoT1zeONvyCfwQxIkUshLAOqN/k9EjGviPRmWTTe6aH2qySWKTVSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*", + "form-data": "^4.0.4" + } + }, + "node_modules/@types/yargs": { + "version": "17.0.24", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.24.tgz", + "integrity": "sha512-6i0aC7jV6QzQB8ne1joVZ0eSFIstHsCrobmOtghM11yGlH0j43FKL2UhWdELkyps0zuf7qVTUVCCR+tgSlyLLw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/yargs-parser": "*" + } + }, + "node_modules/@types/yargs-parser": { + "version": "21.0.3", + "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-21.0.3.tgz", + "integrity": "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/abort-controller": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz", + "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==", + "dev": true, + "license": "MIT", + "dependencies": { + "event-target-shim": "^5.0.0" + }, + "engines": { + "node": ">=6.5" + } + }, + "node_modules/agentkeepalive": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/agentkeepalive/-/agentkeepalive-4.6.0.tgz", + "integrity": "sha512-kja8j7PjmncONqaTsB8fQ+wE2mSU2DJ9D4XKoJ5PFWIdRMa6SLSN1ff4mOr4jCbfRSsxR4keIiySJU0N9T5hIQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "humanize-ms": "^1.2.1" + }, + "engines": { + "node": ">= 8.0.0" + } + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/blake3-wasm": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/blake3-wasm/-/blake3-wasm-2.1.5.tgz", + "integrity": "sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g==", + "dev": true, + "license": "MIT" + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" } }, - "node_modules/@esbuild/openbsd-arm64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", - "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", - "cpu": [ - "arm64" - ], + "node_modules/cf": { + "version": "1.0.0-beta.20", + "resolved": "https://registry.npmjs.org/cf/-/cf-1.0.0-beta.20.tgz", + "integrity": "sha512-sBg/zok+znpGvI00XwsUfuVz+5MyfnJcFY8YUwRXcl4eNg9qQWtnCf1YMq9rsWjcbr7BwjM1xbNJPTDhtkCRnw==", "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ], + "license": "MIT OR Apache-2.0", + "dependencies": { + "@cloudflare/build-output-utils": "0.9.3", + "@cloudflare/config": "0.27.0", + "@cloudflare/runtime-types": "0.1.14", + "blake3-wasm": "2.1.5", + "miniflare": "5.20261019.1-beta" + }, + "bin": { + "cf": "bin/cf", + "cloudflare": "bin/cf" + }, "engines": { - "node": ">=18" + "node": "^22.23.0 || ^24.22.0 || ^26.12.0" } }, - "node_modules/@esbuild/openbsd-x64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", - "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "node_modules/cf/node_modules/@cloudflare/workerd-darwin-64": { + "version": "1.20261019.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-64/-/workerd-darwin-64-1.20261019.1.tgz", + "integrity": "sha512-5ZILbAta/fBQvhmAYeCE7dKMMYIr7N9wJEX50fEGLKSIwGtvT0HzSfHNIK/O7cBQ4gHQ2WfIiPClvwcye6E0fA==", "cpu": [ "x64" ], "dev": true, - "license": "MIT", + "license": "Apache-2.0", "optional": true, "os": [ - "openbsd" + "darwin" ], "engines": { - "node": ">=18" + "node": ">=16" } }, - "node_modules/@esbuild/openharmony-arm64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", - "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "node_modules/cf/node_modules/@cloudflare/workerd-darwin-arm64": { + "version": "1.20261019.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-arm64/-/workerd-darwin-arm64-1.20261019.1.tgz", + "integrity": "sha512-cww2Ab6lVMxpTiEEjKmPI58p5EMo0vYTZSH+3WkqXJdQgc3ES66GuL247+U2B2YWajhhu2tqj7jySrXneU749g==", "cpu": [ "arm64" ], "dev": true, - "license": "MIT", + "license": "Apache-2.0", "optional": true, "os": [ - "openharmony" + "darwin" ], "engines": { - "node": ">=18" + "node": ">=16" } }, - "node_modules/@esbuild/sunos-x64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", - "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "node_modules/cf/node_modules/@cloudflare/workerd-linux-64": { + "version": "1.20261019.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-64/-/workerd-linux-64-1.20261019.1.tgz", + "integrity": "sha512-4++VRi9vkQROYqrpZYOixIJuVDmujkwrT4kszsxNFlvcmsX6Mr2GumvxIN3gIixS3vJUh3Umdtkthqj5X0S3Xw==", "cpu": [ "x64" ], "dev": true, - "license": "MIT", + "license": "Apache-2.0", "optional": true, "os": [ - "sunos" + "linux" ], "engines": { - "node": ">=18" + "node": ">=16" } }, - "node_modules/@esbuild/win32-arm64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", - "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "node_modules/cf/node_modules/@cloudflare/workerd-linux-arm64": { + "version": "1.20261019.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-arm64/-/workerd-linux-arm64-1.20261019.1.tgz", + "integrity": "sha512-75PVtJOwfjScQ53sbLtQXI7D8yP1c21t+WEUPaYbqkzaz4ZqfR5wAd+zuWs8G5Q7kOj2SQIvEfY5Sn8Y+UVrnA==", "cpu": [ "arm64" ], "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/win32-ia32": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", - "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", + "license": "Apache-2.0", "optional": true, "os": [ - "win32" + "linux" ], "engines": { - "node": ">=18" + "node": ">=16" } }, - "node_modules/@esbuild/win32-x64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", - "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "node_modules/cf/node_modules/@cloudflare/workerd-windows-64": { + "version": "1.20261019.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-windows-64/-/workerd-windows-64-1.20261019.1.tgz", + "integrity": "sha512-z49fvKTETMCnG6wnMcQwxx9CpryFceiKz04FRjq26EkhCyzRNJ6c3UXhyZz3r5f1CXnnBZc5DcU8ZouPkUJCqw==", "cpu": [ "x64" ], "dev": true, - "license": "MIT", + "license": "Apache-2.0", "optional": true, "os": [ "win32" ], "engines": { - "node": ">=18" - } - }, - "node_modules/@img/colour": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", - "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" + "node": ">=16" } }, - "node_modules/@img/sharp-darwin-arm64": { - "version": "0.35.2", - "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.2.tgz", - "integrity": "sha512-eEieHsMksAW4IiO5NzauESRl2D2qz3J/kwUxUrSfV06A93eEaRfMpHXyUb1mAqrR7i8U9A0GRqE9pjn6u1Jjpg==", + "node_modules/cf/node_modules/@img/sharp-darwin-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.5.tgz", + "integrity": "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==", "cpu": [ "arm64" ], @@ -651,13 +2176,13 @@ "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-darwin-arm64": "1.3.1" + "@img/sharp-libvips-darwin-arm64": "1.3.4" } }, - "node_modules/@img/sharp-darwin-x64": { - "version": "0.35.2", - "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.2.tgz", - "integrity": "sha512-BaktuGPCeHJMARpodR8jK4uKiZrPAy9WrfQW0sdI37clracq8Bp01AYS3SZgi5FS/y5twa9t4+LIuuxQjqRrWw==", + "node_modules/cf/node_modules/@img/sharp-darwin-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.5.tgz", + "integrity": "sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==", "cpu": [ "x64" ], @@ -674,13 +2199,13 @@ "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-darwin-x64": "1.3.1" + "@img/sharp-libvips-darwin-x64": "1.3.4" } }, - "node_modules/@img/sharp-freebsd-wasm32": { - "version": "0.35.2", - "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.2.tgz", - "integrity": "sha512-YoAxdnd8hPUkvLHd3bWY+YA8nw3xM/RyRopYucNsWHVSan8NLVM3X2volsfoRDcXdUJPg6tXahSd7HXPK7lRnw==", + "node_modules/cf/node_modules/@img/sharp-freebsd-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.5.tgz", + "integrity": "sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==", "dev": true, "license": "Apache-2.0", "optional": true, @@ -688,7 +2213,7 @@ "freebsd" ], "dependencies": { - "@img/sharp-wasm32": "0.35.2" + "@img/sharp-wasm32": "0.35.5" }, "engines": { "node": ">=20.9.0" @@ -697,10 +2222,10 @@ "url": "https://opencollective.com/libvips" } }, - "node_modules/@img/sharp-libvips-darwin-arm64": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.1.tgz", - "integrity": "sha512-4V/M3roRMTYjiwZY9IOVQOE8OyeCxFAkYmyZDrZl51uOKjibm3oeEJ4WAmLxutAfzFbC9jqUiPs2gbnGflH+7g==", + "node_modules/cf/node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.4.tgz", + "integrity": "sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==", "cpu": [ "arm64" ], @@ -714,10 +2239,10 @@ "url": "https://opencollective.com/libvips" } }, - "node_modules/@img/sharp-libvips-darwin-x64": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.1.tgz", - "integrity": "sha512-c0/DxItpJv2+dGhgycJBBgotdqruGYDvA79drdh0MD1dFpy7JzJ/PlXwi1H4rFf0eTy8tgbI91aHDnZIceY3jQ==", + "node_modules/cf/node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.4.tgz", + "integrity": "sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==", "cpu": [ "x64" ], @@ -731,10 +2256,10 @@ "url": "https://opencollective.com/libvips" } }, - "node_modules/@img/sharp-libvips-linux-arm": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.1.tgz", - "integrity": "sha512-aGGy9aWzXgHBG7HNyQPWorZthlp7+x6fDRoPAQbGO3ThcttuTyKIx3NuSHb6zb4gBNq6/yNn9f1cy9nFKS/Vmg==", + "node_modules/cf/node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.4.tgz", + "integrity": "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==", "cpu": [ "arm" ], @@ -748,10 +2273,10 @@ "url": "https://opencollective.com/libvips" } }, - "node_modules/@img/sharp-libvips-linux-arm64": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.1.tgz", - "integrity": "sha512-JznefmcK9j1JKPz8AkQDh89kjojubyfOasWBPKfzMIhPwsgDy9evpE/naJTXXXmghS1iFwR8u/kTwh/I2/+GCw==", + "node_modules/cf/node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.4.tgz", + "integrity": "sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==", "cpu": [ "arm64" ], @@ -765,10 +2290,10 @@ "url": "https://opencollective.com/libvips" } }, - "node_modules/@img/sharp-libvips-linux-ppc64": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.1.tgz", - "integrity": "sha512-1EkwGNCZk6iWNCMWqrvdJ+r1j0PT1zIz60CNPhYnJlK/zyeWqlsPZIe+ocBVqPF8k/Ssee/NCk+tE9Ryrko6ng==", + "node_modules/cf/node_modules/@img/sharp-libvips-linux-ppc64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.4.tgz", + "integrity": "sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==", "cpu": [ "ppc64" ], @@ -782,10 +2307,10 @@ "url": "https://opencollective.com/libvips" } }, - "node_modules/@img/sharp-libvips-linux-riscv64": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.1.tgz", - "integrity": "sha512-Ilays+w2bXdnxzxtQdmXR62u8o8GYa3eL4+Gr+1KiE4xperMZUslRaVPJwwPkzlHEjGfXAfRVAa/7CYCtSqsBw==", + "node_modules/cf/node_modules/@img/sharp-libvips-linux-riscv64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.4.tgz", + "integrity": "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==", "cpu": [ "riscv64" ], @@ -799,10 +2324,10 @@ "url": "https://opencollective.com/libvips" } }, - "node_modules/@img/sharp-libvips-linux-s390x": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.1.tgz", - "integrity": "sha512-VfBwVHQTbRoj4XlpA/KLZ7ltgMpz+4WSejFzQ+GnoImjo1PtEJ59QB2qR1xQEeRPYIkNrPIm2L4cICMvz4C2ew==", + "node_modules/cf/node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.4.tgz", + "integrity": "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==", "cpu": [ "s390x" ], @@ -816,10 +2341,10 @@ "url": "https://opencollective.com/libvips" } }, - "node_modules/@img/sharp-libvips-linux-x64": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.1.tgz", - "integrity": "sha512-+c8ukgwU62DS54nCAjw7keOfHUkmr0B5QHEdcOqRnodF/MNXJbVI8Eopoj4B/0H8Asr65I+A4Amrn7a85/md6A==", + "node_modules/cf/node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.4.tgz", + "integrity": "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==", "cpu": [ "x64" ], @@ -833,10 +2358,10 @@ "url": "https://opencollective.com/libvips" } }, - "node_modules/@img/sharp-libvips-linuxmusl-arm64": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.1.tgz", - "integrity": "sha512-qlKb/pwbkAi1WMsJrYHk7CuDrd12s27U2QnRhFYUoJNrRCmkosMTttuRFat/DDB3IlDm5qE1TJgZ4JDnHX8Ldw==", + "node_modules/cf/node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.4.tgz", + "integrity": "sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==", "cpu": [ "arm64" ], @@ -850,10 +2375,10 @@ "url": "https://opencollective.com/libvips" } }, - "node_modules/@img/sharp-libvips-linuxmusl-x64": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.1.tgz", - "integrity": "sha512-yO21HwoUVLN8Qa+/SBjQLMYwBWAVJjeGPNe+hc0OUeMeifEtJqu5a1c4HayE1nNpDih9y3/KkoltfkDodmKAlg==", + "node_modules/cf/node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.4.tgz", + "integrity": "sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==", "cpu": [ "x64" ], @@ -867,10 +2392,10 @@ "url": "https://opencollective.com/libvips" } }, - "node_modules/@img/sharp-linux-arm": { - "version": "0.35.2", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.2.tgz", - "integrity": "sha512-SE4kzF2mepn6z+6E7L6lsV8FzuLL6IPQdyX8ZiwROAG/G8td+hP/m7FsFPwidtrF19gvajuC9l6TxAVcsA4S7A==", + "node_modules/cf/node_modules/@img/sharp-linux-arm": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.5.tgz", + "integrity": "sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==", "cpu": [ "arm" ], @@ -887,13 +2412,13 @@ "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linux-arm": "1.3.1" + "@img/sharp-libvips-linux-arm": "1.3.4" } }, - "node_modules/@img/sharp-linux-arm64": { - "version": "0.35.2", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.2.tgz", - "integrity": "sha512-af12Pnd0ZGu2HfP8NayB0kk6eC/lrfbQE6HlR4jD+34wdJ1Vw9TF6TMn6ZvffT+WgqVsl0hRbmNvz2u/23VmwA==", + "node_modules/cf/node_modules/@img/sharp-linux-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.5.tgz", + "integrity": "sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==", "cpu": [ "arm64" ], @@ -910,13 +2435,13 @@ "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linux-arm64": "1.3.1" + "@img/sharp-libvips-linux-arm64": "1.3.4" } }, - "node_modules/@img/sharp-linux-ppc64": { - "version": "0.35.2", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.2.tgz", - "integrity": "sha512-hYSBm7zcNtDCozCxQHYZJiu63b/bXsgRZuOxCIBZsStMM9Vap47iFHdbX4kCvQsblPB/k+clhELpdQJHQLSHvg==", + "node_modules/cf/node_modules/@img/sharp-linux-ppc64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.5.tgz", + "integrity": "sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==", "cpu": [ "ppc64" ], @@ -933,13 +2458,13 @@ "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linux-ppc64": "1.3.1" + "@img/sharp-libvips-linux-ppc64": "1.3.4" } }, - "node_modules/@img/sharp-linux-riscv64": { - "version": "0.35.2", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.2.tgz", - "integrity": "sha512-qQt0Kc13+Hoan/Awq/qMSQw3L+RI1NCRPgD5cUJ/1WSSmIoysLOc72jlRM3E0OHN9Yr313jgeQ2T+zW+F03QFA==", + "node_modules/cf/node_modules/@img/sharp-linux-riscv64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.5.tgz", + "integrity": "sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==", "cpu": [ "riscv64" ], @@ -956,13 +2481,13 @@ "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linux-riscv64": "1.3.1" + "@img/sharp-libvips-linux-riscv64": "1.3.4" } }, - "node_modules/@img/sharp-linux-s390x": { - "version": "0.35.2", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.2.tgz", - "integrity": "sha512-E4fLLfRPzDLlEeDaTzI98OFLcv++WL5ChLLMwPoVd0CIoZQqupBSNbOisPL5am9XsbQ9T84+iiMpUvbFtkunbA==", + "node_modules/cf/node_modules/@img/sharp-linux-s390x": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.5.tgz", + "integrity": "sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==", "cpu": [ "s390x" ], @@ -979,13 +2504,13 @@ "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linux-s390x": "1.3.1" + "@img/sharp-libvips-linux-s390x": "1.3.4" } }, - "node_modules/@img/sharp-linux-x64": { - "version": "0.35.2", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.2.tgz", - "integrity": "sha512-gi0zFJJRLswfCZmHtJdikXPOc5u7qamSOS3NHedLqLd4W8Q0NqjdBr6TTRIgsfFjqfTsHFgdfvJ9LwqSgcHiAA==", + "node_modules/cf/node_modules/@img/sharp-linux-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.5.tgz", + "integrity": "sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==", "cpu": [ "x64" ], @@ -1002,13 +2527,13 @@ "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linux-x64": "1.3.1" - } - }, - "node_modules/@img/sharp-linuxmusl-arm64": { - "version": "0.35.2", - "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.2.tgz", - "integrity": "sha512-siWbOW1u6HFnFLrp0waKyW7VEf7jYvcDWdrXEFa8AkdAQgEvuu5Fz8/Y70w9EeqAdwDtfU012BhEHHaDqvQNzg==", + "@img/sharp-libvips-linux-x64": "1.3.4" + } + }, + "node_modules/cf/node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.5.tgz", + "integrity": "sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==", "cpu": [ "arm64" ], @@ -1025,13 +2550,13 @@ "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linuxmusl-arm64": "1.3.1" + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4" } }, - "node_modules/@img/sharp-linuxmusl-x64": { - "version": "0.35.2", - "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.2.tgz", - "integrity": "sha512-YBqMMcjDi4QGYiSn4vNOYBhmlC4z5AXqkOUUqI2e0AFA4urNv4ESgOgwNl3K+4etQhha0twXlzeF20bbULm9Yg==", + "node_modules/cf/node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.5.tgz", + "integrity": "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==", "cpu": [ "x64" ], @@ -1048,18 +2573,18 @@ "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linuxmusl-x64": "1.3.1" + "@img/sharp-libvips-linuxmusl-x64": "1.3.4" } }, - "node_modules/@img/sharp-wasm32": { - "version": "0.35.2", - "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.2.tgz", - "integrity": "sha512-Mrv4JQNYVQ94xH+jzZ9r+gowleN8mv2FTgKT+PI6bx5C0G8TdNYndu161pg2i7uoBwxy2ImPMHrJOM2LZef7Bw==", + "node_modules/cf/node_modules/@img/sharp-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.5.tgz", + "integrity": "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==", "dev": true, "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", "optional": true, "dependencies": { - "@emnapi/runtime": "^1.11.1" + "@emnapi/runtime": "^1.11.3" }, "engines": { "node": ">=20.9.0" @@ -1068,10 +2593,10 @@ "url": "https://opencollective.com/libvips" } }, - "node_modules/@img/sharp-webcontainers-wasm32": { - "version": "0.35.2", - "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.2.tgz", - "integrity": "sha512-QNV27pxs9wpApEiCfvHM1RDoP1w1+2KrUWWDPEhEwg+latvOrfuhWrHWZKwdSFwU6jh3myjw/yOCRsUIuOft3g==", + "node_modules/cf/node_modules/@img/sharp-webcontainers-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.5.tgz", + "integrity": "sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==", "cpu": [ "wasm32" ], @@ -1079,7 +2604,7 @@ "license": "Apache-2.0", "optional": true, "dependencies": { - "@img/sharp-wasm32": "0.35.2" + "@img/sharp-wasm32": "0.35.5" }, "engines": { "node": ">=20.9.0" @@ -1088,10 +2613,10 @@ "url": "https://opencollective.com/libvips" } }, - "node_modules/@img/sharp-win32-arm64": { - "version": "0.35.2", - "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.2.tgz", - "integrity": "sha512-BiVRYc/t6/Vl3e1hBx0hugG4oN9Pydf4fgMSpxTQJmwGUg/YoXTWHiFeRymHfCZzifxu4F4rpk/I67D0LQ20wQ==", + "node_modules/cf/node_modules/@img/sharp-win32-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.5.tgz", + "integrity": "sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==", "cpu": [ "arm64" ], @@ -1108,10 +2633,10 @@ "url": "https://opencollective.com/libvips" } }, - "node_modules/@img/sharp-win32-ia32": { - "version": "0.35.2", - "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.2.tgz", - "integrity": "sha512-YYEhx9PImCC7T0tI8JDMi4DB9LwLCXCU5OWNYEXAxh5Q1ShKkyC6byxzoBJ3gEFDnH2lQckWuDe70G7mB2XJog==", + "node_modules/cf/node_modules/@img/sharp-win32-ia32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.5.tgz", + "integrity": "sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==", "cpu": [ "ia32" ], @@ -1128,10 +2653,10 @@ "url": "https://opencollective.com/libvips" } }, - "node_modules/@img/sharp-win32-x64": { - "version": "0.35.2", - "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.2.tgz", - "integrity": "sha512-imoOyBcoM/iiUr4J6VPpCNjPnjvP/Gks95898yB8YqoGGYmHYbOyCuNv9FMhFgtaiHFGbHW8bxKqRV6VjtXThQ==", + "node_modules/cf/node_modules/@img/sharp-win32-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.5.tgz", + "integrity": "sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==", "cpu": [ "x64" ], @@ -1148,166 +2673,103 @@ "url": "https://opencollective.com/libvips" } }, - "node_modules/@jridgewell/resolve-uri": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz", - "integrity": "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@jridgewell/sourcemap-codec": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", - "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@jridgewell/trace-mapping": { - "version": "0.3.9", - "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", - "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/resolve-uri": "^3.0.3", - "@jridgewell/sourcemap-codec": "^1.4.10" - } - }, - "node_modules/@poppinss/colors": { - "version": "4.1.6", - "resolved": "https://registry.npmjs.org/@poppinss/colors/-/colors-4.1.6.tgz", - "integrity": "sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg==", + "node_modules/cf/node_modules/miniflare": { + "version": "5.20261019.1-beta", + "resolved": "https://registry.npmjs.org/miniflare/-/miniflare-5.20261019.1-beta.tgz", + "integrity": "sha512-1n7MN2UqZnPniyYAqNuV1YEAaja66ozKGVCc5ZTmYQhTubnoAwGLccwb+ZWYLOajuw3pOaJ70u//bZMuURlRew==", "dev": true, "license": "MIT", "dependencies": { - "kleur": "^4.1.5" + "@cspotcode/source-map-support": "0.8.1", + "sharp": "0.35.5", + "undici": "7.29.1", + "workerd": "1.20261019.1", + "ws": "8.21.0", + "youch": "4.1.0-beta.10" + }, + "engines": { + "node": ">=22.0.0" } }, - "node_modules/@poppinss/dumper": { - "version": "0.6.5", - "resolved": "https://registry.npmjs.org/@poppinss/dumper/-/dumper-0.6.5.tgz", - "integrity": "sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw==", + "node_modules/cf/node_modules/sharp": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz", + "integrity": "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==", "dev": true, - "license": "MIT", + "license": "Apache-2.0", "dependencies": { - "@poppinss/colors": "^4.1.5", - "@sindresorhus/is": "^7.0.2", - "supports-color": "^10.0.0" - } - }, - "node_modules/@poppinss/exception": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/@poppinss/exception/-/exception-1.2.3.tgz", - "integrity": "sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@sindresorhus/is": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-7.2.0.tgz", - "integrity": "sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw==", - "dev": true, - "license": "MIT", + "@img/colour": "^1.1.0", + "detect-libc": "^2.1.2", + "semver": "^7.8.5" + }, "engines": { - "node": ">=18" + "node": ">=20.9.0" }, "funding": { - "url": "https://github.com/sindresorhus/is?sponsor=1" - } - }, - "node_modules/@speed-highlight/core": { - "version": "1.2.24", - "resolved": "https://registry.npmjs.org/@speed-highlight/core/-/core-1.2.24.tgz", - "integrity": "sha512-qeW2e1l78afw8VhRPfPQ1Gjj+KU5XFQ/OFV5ti6eTa9bruO7mJyZtA4vw0ofqmA3tKCkROE9xLk3VZoeRc98nw==", - "dev": true, - "license": "CC0-1.0" - }, - "node_modules/@types/node": { - "version": "18.19.130", - "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.130.tgz", - "integrity": "sha512-GRaXQx6jGfL8sKfaIDD6OupbIHBr9jv7Jnaml9tB7l4v068PAOXqfcujMMo5PhbIs6ggR1XODELqahT2R8v0fg==", - "dev": true, - "license": "MIT", - "dependencies": { - "undici-types": "~5.26.4" - } - }, - "node_modules/@types/node-fetch": { - "version": "2.6.13", - "resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.6.13.tgz", - "integrity": "sha512-QGpRVpzSaUs30JBSGPjOg4Uveu384erbHBoT1zeONvyCfwQxIkUshLAOqN/k9EjGviPRmWTTe6aH2qySWKTVSw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*", - "form-data": "^4.0.4" - } - }, - "node_modules/@types/yargs": { - "version": "17.0.24", - "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.24.tgz", - "integrity": "sha512-6i0aC7jV6QzQB8ne1joVZ0eSFIstHsCrobmOtghM11yGlH0j43FKL2UhWdELkyps0zuf7qVTUVCCR+tgSlyLLw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/yargs-parser": "*" - } - }, - "node_modules/@types/yargs-parser": { - "version": "21.0.3", - "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-21.0.3.tgz", - "integrity": "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/abort-controller": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz", - "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==", - "dev": true, - "license": "MIT", - "dependencies": { - "event-target-shim": "^5.0.0" + "url": "https://opencollective.com/libvips" }, - "engines": { - "node": ">=6.5" + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.35.5", + "@img/sharp-darwin-x64": "0.35.5", + "@img/sharp-freebsd-wasm32": "0.35.5", + "@img/sharp-libvips-darwin-arm64": "1.3.4", + "@img/sharp-libvips-darwin-x64": "1.3.4", + "@img/sharp-libvips-linux-arm": "1.3.4", + "@img/sharp-libvips-linux-arm64": "1.3.4", + "@img/sharp-libvips-linux-ppc64": "1.3.4", + "@img/sharp-libvips-linux-riscv64": "1.3.4", + "@img/sharp-libvips-linux-s390x": "1.3.4", + "@img/sharp-libvips-linux-x64": "1.3.4", + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4", + "@img/sharp-libvips-linuxmusl-x64": "1.3.4", + "@img/sharp-linux-arm": "0.35.5", + "@img/sharp-linux-arm64": "0.35.5", + "@img/sharp-linux-ppc64": "0.35.5", + "@img/sharp-linux-riscv64": "0.35.5", + "@img/sharp-linux-s390x": "0.35.5", + "@img/sharp-linux-x64": "0.35.5", + "@img/sharp-linuxmusl-arm64": "0.35.5", + "@img/sharp-linuxmusl-x64": "0.35.5", + "@img/sharp-webcontainers-wasm32": "0.35.5", + "@img/sharp-win32-arm64": "0.35.5", + "@img/sharp-win32-ia32": "0.35.5", + "@img/sharp-win32-x64": "0.35.5" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } } }, - "node_modules/agentkeepalive": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/agentkeepalive/-/agentkeepalive-4.6.0.tgz", - "integrity": "sha512-kja8j7PjmncONqaTsB8fQ+wE2mSU2DJ9D4XKoJ5PFWIdRMa6SLSN1ff4mOr4jCbfRSsxR4keIiySJU0N9T5hIQ==", + "node_modules/cf/node_modules/undici": { + "version": "7.29.1", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.29.1.tgz", + "integrity": "sha512-RYONW2MeafgYlkVOKYKkA/Ag7BmXqgIWCa8t1m0JcxrQg9pI9lEqRhAOruOBCbAohOa/gkCF+iPi9hrgvTzu6Q==", "dev": true, "license": "MIT", - "dependencies": { - "humanize-ms": "^1.2.1" - }, "engines": { - "node": ">= 8.0.0" + "node": ">=20.18.1" } }, - "node_modules/asynckit": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", - "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/call-bind-apply-helpers": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", - "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "node_modules/cf/node_modules/workerd": { + "version": "1.20261019.1", + "resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20261019.1.tgz", + "integrity": "sha512-UUYRUq/7DmeCl11YriNbcVbjUZVLtt8uuCXFu+nz77hGFf8d4DEVXoCYtnA+MlBatE4+wxoj47DVqzK3xGBAiw==", "dev": true, - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "function-bind": "^1.1.2" + "hasInstallScript": true, + "license": "Apache-2.0", + "bin": { + "workerd": "bin/workerd" }, "engines": { - "node": ">= 0.4" + "node": ">=16" + }, + "optionalDependencies": { + "@cloudflare/workerd-darwin-64": "1.20261019.1", + "@cloudflare/workerd-darwin-arm64": "1.20261019.1", + "@cloudflare/workerd-linux-64": "1.20261019.1", + "@cloudflare/workerd-linux-arm64": "1.20261019.1", + "@cloudflare/workerd-windows-64": "1.20261019.1" } }, "node_modules/chalk": { @@ -2784,6 +4246,16 @@ "@poppinss/exception": "^1.2.2", "error-stack-parser-es": "^1.0.5" } + }, + "node_modules/zod": { + "version": "4.6.5", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.5.tgz", + "integrity": "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } } } } diff --git a/pm-stack/private-laptop-bridge/package.json b/pm-stack/private-laptop-bridge/package.json index 3456cd8359..2b5e2f3319 100644 --- a/pm-stack/private-laptop-bridge/package.json +++ b/pm-stack/private-laptop-bridge/package.json @@ -12,6 +12,7 @@ }, "devDependencies": { "miniflare": "4.20260730.0", - "wrangler": "4.166.0" + "wrangler": "4.166.0", + "cf": "1.0.0-beta.20" } } From 2e43d9f946c6102bf96c193fabe5302241d0745b Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 13:28:19 +0000 Subject: [PATCH 09/33] Pin cf release candidate and add private bridge version release --- ....yml => private-laptop-bridge-release.yml} | 86 ++++++-- pm-stack/private-laptop-bridge/DISCOVERY.md | 129 +++++++----- pm-stack/private-laptop-bridge/README.md | 2 +- .../private-laptop-bridge/VERIFICATION.md | 23 +++ .../cloudflare.config.ts | 26 ++- .../deployment-config.test.mjs | 47 +++++ .../private-laptop-bridge/package-lock.json | 194 ++++++++++-------- pm-stack/private-laptop-bridge/package.json | 4 +- 8 files changed, 350 insertions(+), 161 deletions(-) rename .github/workflows/{private-laptop-bridge-smoke.yml => private-laptop-bridge-release.yml} (61%) create mode 100644 pm-stack/private-laptop-bridge/deployment-config.test.mjs diff --git a/.github/workflows/private-laptop-bridge-smoke.yml b/.github/workflows/private-laptop-bridge-release.yml similarity index 61% rename from .github/workflows/private-laptop-bridge-smoke.yml rename to .github/workflows/private-laptop-bridge-release.yml index b8e433fb2e..0a8ab8e563 100644 --- a/.github/workflows/private-laptop-bridge-smoke.yml +++ b/.github/workflows/private-laptop-bridge-release.yml @@ -1,4 +1,4 @@ -name: Private laptop bridge smoke Worker +name: Private laptop bridge Workers on: workflow_dispatch: @@ -8,6 +8,11 @@ on: type: choice required: true options: [upload, promote] + worker: + description: Exact pre-existing Worker target; each GitHub environment token must be scoped to only this Worker + type: choice + required: true + options: [smoke, bridge] version_id: description: Exact version UUID; required for promote and ignored for upload type: string @@ -17,13 +22,13 @@ permissions: contents: read concurrency: - group: private-laptop-bridge-smoke-deploy + group: private-laptop-bridge-${{ inputs.worker }}-deploy cancel-in-progress: false jobs: deploy: - if: github.repository == 'developing-today/code' && github.ref == 'refs/heads/main' - environment: cloudflare-staging + if: github.repository == 'developing-today/code' && github.ref == 'refs/heads/main' && (inputs.worker == 'bridge' || inputs.worker == 'smoke') + environment: ${{ inputs.worker == 'bridge' && 'cloudflare-staging' || inputs.worker == 'smoke' && 'cloudflare-staging-smoke' || 'invalid-worker-selection' }} runs-on: ubuntu-24.04 timeout-minutes: 15 steps: @@ -40,8 +45,10 @@ jobs: working-directory: pm-stack/private-laptop-bridge run: npm ci --ignore-scripts --no-audit --no-fund - name: Validate request and Cloudflare target + id: target env: ACTION_KIND: ${{ inputs.action }} + WORKER_KIND: ${{ inputs.worker }} VERSION_ID: ${{ inputs.version_id }} CF_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }} CF_API_TOKEN: ${{ secrets.CF_API_TOKEN }} @@ -54,22 +61,73 @@ jobs: elif [[ "$ACTION_KIND" == promote ]]; then [[ "$VERSION_ID" =~ ^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$ ]] else exit 2; fi - - name: Test stateless smoke Worker + case "$WORKER_KIND" in + smoke) echo "worker=private-laptop-bridge-smoke" >> "$GITHUB_OUTPUT"; echo "mode=default" >> "$GITHUB_OUTPUT" ;; + bridge) echo "worker=private-laptop-bridge-staging" >> "$GITHUB_OUTPUT"; echo "mode=bridge" >> "$GITHUB_OUTPUT" ;; + *) exit 2 ;; + esac + - name: Require an existing Worker (no bootstrap or resource creation) + working-directory: pm-stack/private-laptop-bridge + env: + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }} + CLOUDFLARE_API_TOKEN: ${{ secrets.CF_API_TOKEN }} + TARGET_WORKER: ${{ steps.target.outputs.worker }} + run: | + set -euo pipefail + npx --no-install cf -q workers get "$TARGET_WORKER" >/dev/null + - name: Test Worker entrypoint + if: inputs.action == 'upload' + working-directory: pm-stack/private-laptop-bridge + env: + WORKER_KIND: ${{ inputs.worker }} + run: | + set -euo pipefail + case "$WORKER_KIND" in + bridge) node --test gateway.test.mjs ;; + smoke) node --test smoke.test.mjs ;; + *) exit 2 ;; + esac + - name: Build pinned Build Output v1 + if: inputs.action == 'upload' + working-directory: pm-stack/private-laptop-bridge + env: + TARGET_MODE: ${{ steps.target.outputs.mode }} + run: | + set -euo pipefail + if [[ "$TARGET_MODE" == bridge ]]; then npx --no-install cf build --mode bridge; else npx --no-install cf build; fi + - name: Check Wrangler and cf Worker binding definitions agree if: inputs.action == 'upload' working-directory: pm-stack/private-laptop-bridge - run: node --test smoke.test.mjs + env: + TARGET_MODE: ${{ steps.target.outputs.mode }} + run: node deployment-config.test.mjs + - name: Validate the exact prebuilt Version API upload + if: inputs.action == 'upload' + working-directory: pm-stack/private-laptop-bridge + env: + TARGET_WORKER: ${{ steps.target.outputs.worker }} + TARGET_MODE: ${{ steps.target.outputs.mode }} + run: | + set -euo pipefail + args=(workers versions create --worker "$TARGET_WORKER" --tag offline-check --message offline-check --prebuilt --dry-run) + if [[ "$TARGET_MODE" == bridge ]]; then args+=(--mode bridge); fi + npx --no-install cf -q "${args[@]}" - name: Upload immutable version only if: inputs.action == 'upload' working-directory: pm-stack/private-laptop-bridge env: CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }} CLOUDFLARE_API_TOKEN: ${{ secrets.CF_API_TOKEN }} + TARGET_WORKER: ${{ steps.target.outputs.worker }} + TARGET_MODE: ${{ steps.target.outputs.mode }} run: | set -euo pipefail sha="$GITHUB_SHA" tag="git-${sha:0:12}" - npx --no-install cf -q workers versions create --worker private-laptop-bridge-smoke --tag "$tag" --message "smoke candidate $sha" - npx --no-install cf -q workers versions list --worker-id private-laptop-bridge-smoke > "$RUNNER_TEMP/versions.json" + args=(workers versions create --worker "$TARGET_WORKER" --tag "$tag" --message "candidate $sha" --prebuilt) + if [[ "$TARGET_MODE" == bridge ]]; then args+=(--mode bridge); fi + npx --no-install cf -q "${args[@]}" + npx --no-install cf -q workers versions list --worker-id "$TARGET_WORKER" > "$RUNNER_TEMP/versions.json" python3 - "$RUNNER_TEMP/versions.json" "$tag" "$GITHUB_STEP_SUMMARY" <<'PY' import json,sys d=json.load(open(sys.argv[1])); versions=d if isinstance(d,list) else d.get('result', d.get('versions', [])) @@ -82,7 +140,7 @@ jobs: print(version) PY version="$(python3 -c 'import json,sys;d=json.load(open(sys.argv[1]));vs=d if isinstance(d,list) else d.get("result",d.get("versions",[]));vs=vs.get("items",[]) if isinstance(vs,dict) else vs;tag="git-"+sys.argv[2][:12];m=[v for v in vs if v.get("annotations",{}).get("workers/tag")==tag];m.sort(key=lambda v:v.get("metadata",{}).get("created_on",""),reverse=True);print(m[0]["id"])' "$RUNNER_TEMP/versions.json" "$GITHUB_SHA")" - curl --fail --silent --show-error --max-time 15 -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/workers/scripts/private-laptop-bridge-smoke/versions?deployable=true" > "$RUNNER_TEMP/deployable.json" + curl --fail --silent --show-error --max-time 15 -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/workers/scripts/$TARGET_WORKER/versions?deployable=true" > "$RUNNER_TEMP/deployable.json" python3 - "$RUNNER_TEMP/deployable.json" "$version" <<'PY' import json,sys d=json.load(open(sys.argv[1])); vs=d.get('result',[]); vs=vs.get('items',[]) if isinstance(vs,dict) else vs @@ -95,9 +153,10 @@ jobs: CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }} CLOUDFLARE_API_TOKEN: ${{ secrets.CF_API_TOKEN }} VERSION_ID: ${{ inputs.version_id }} + TARGET_WORKER: ${{ steps.target.outputs.worker }} run: | set -euo pipefail - curl --fail --silent --show-error --max-time 15 -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/workers/scripts/private-laptop-bridge-smoke/versions?deployable=true" > "$RUNNER_TEMP/deployable.json" + curl --fail --silent --show-error --max-time 15 -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/workers/scripts/$TARGET_WORKER/versions?deployable=true" > "$RUNNER_TEMP/deployable.json" python3 - "$RUNNER_TEMP/deployable.json" "$VERSION_ID" <<'PY' import json,sys d=json.load(open(sys.argv[1])); vs=d.get('result',[]); vs=vs.get('items',[]) if isinstance(vs,dict) else vs @@ -110,14 +169,15 @@ jobs: CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }} CLOUDFLARE_API_TOKEN: ${{ secrets.CF_API_TOKEN }} VERSION_ID: ${{ inputs.version_id }} + TARGET_WORKER: ${{ steps.target.outputs.worker }} run: | set -euo pipefail - npx --no-install cf -q workers deployments create --worker private-laptop-bridge-smoke --strategy percentage --versions "[{\"version_id\":\"$VERSION_ID\",\"percentage\":100}]" - npx --no-install cf -q workers deployments list --worker private-laptop-bridge-smoke > "$RUNNER_TEMP/deployments.json" + npx --no-install cf -q workers deployments create --worker "$TARGET_WORKER" --strategy percentage --versions "[{\"version_id\":\"$VERSION_ID\",\"percentage\":100}]" + npx --no-install cf -q workers deployments list --worker "$TARGET_WORKER" > "$RUNNER_TEMP/deployments.json" python3 - "$RUNNER_TEMP/deployments.json" "$VERSION_ID" "$GITHUB_STEP_SUMMARY" <<'PY' import json,sys d=json.load(open(sys.argv[1])); rows=d if isinstance(d,list) else d.get('result',d.get('deployments',[])); rows=rows.get('items',[]) if isinstance(rows,dict) else rows matches=[x for x in rows if any(v.get('version_id')==sys.argv[2] and int(v.get('percentage',0))==100 for v in x.get('versions',[]))] if not matches: raise SystemExit('Deployment read-back did not confirm exact version at 100 percent') - open(sys.argv[3],'a').write(f"Promoted `{sys.argv[2]}` and verified deployment read-back at 100%. Smoke ingress remains separately controlled by Gateway policy.\n") + open(sys.argv[3],'a').write(f"Promoted `{sys.argv[2]}` and verified deployment read-back at 100%. Gateway and traffic policies remain unchanged.\n") PY diff --git a/pm-stack/private-laptop-bridge/DISCOVERY.md b/pm-stack/private-laptop-bridge/DISCOVERY.md index a23d98a2ae..b0305a0ad0 100644 --- a/pm-stack/private-laptop-bridge/DISCOVERY.md +++ b/pm-stack/private-laptop-bridge/DISCOVERY.md @@ -130,54 +130,81 @@ that the original signed bridge was unsuitable for a credential-free smoke; this separate artifact addresses that concrete gap. See VERIFICATION.md for final-head offline test evidence; no CI pass or live reachability is claimed. -## GitHub Actions deployment boundary - -`.github/workflows/private-laptop-bridge-smoke.yml` is manual only, accepts no -branch/ref input, and runs only when the dispatch ref is exactly `main` in -`developing-today/code`. It checks out the triggering SHA, has `contents: read` -only, serializes runs without cancellation, pins Actions by commit and pins -Node/cf through the workflow and npm lockfile. It targets only -`private-laptop-bridge-smoke`; it does not deploy `private-laptop-bridge-staging` -or create/modify Gateway DNS, HTTP Forward, TLS or identity policies. Upload -creates an immutable version and checks Cloudflare's `deployable=true` set. -Promotion is a separate explicit dispatch with the exact version UUID, repeats -the deployability check, creates a 100% deployment, and reads back the exact -version/percentage. Re-promoting an earlier retained version is the recovery -path; a fix-forward uploads a new version and then separately promotes that -UUID. Neither path changes Gateway traffic policy. Smoke application behavior -stays disabled until the reviewed config carries its bounded test window. - -Before enabling the `cloudflare-staging` GitHub Environment, configure required -reviewers and prevent untrusted branches from using it. Set exactly these -**environment** secrets (never repository-wide): - -- `CF_ACCOUNT_ID`: full 32-character account ID for the verified staging account. -- `CF_API_TOKEN`: short-lived/rotatable token restricted to that account, with - **Workers Scripts: Edit** and **Workers Scripts: Read** only. No Gateway, - Access, DNS, Zone, User, or account administration permissions. The token is - used only in the protected job environment and never printed. - -Those resource names/scopes are the minimum for version upload/list, deployable -version API read and deployment create/list. Verify them against Cloudflare's -current token permission catalogue before provisioning. Do not store AMD laptop -runtime keys or Gateway credentials in this environment. The environment and -secret names are proposed; no secrets were read or configured. - -Exact target for this workflow is the isolated staging smoke Worker named -`private-laptop-bridge-smoke` in the verified account. Steps: owner establishes -required-reviewer protection and scoped environment secrets; dispatch -`upload` on `main`; inspect the summary's exact immutable version and checks; -review the source/config diff; dispatch `promote` with that exact UUID under the -environment approval; verify deployment read-back. Gateway Forward remains -unchanged, so this does not test private ingress by itself. For rollback, dispatch -`promote` with the previously recorded known-good UUID. For a code fix, upload a -new commit's version and promote its UUID only after review. If no retained known- -good version exists or deployment read-back mismatches, stop and use Cloudflare's -owner console to inspect; never edit traffic policies as automated recovery. - -This is not the bridge runtime release workflow. The live bridge requires a -separate reviewed `cf` native configuration for its Durable Object, explicit -nonsecret Gateway identifiers and staging registry/separate runtime identity -provisioning. It must not be silently folded into this smoke deploy. The existing -`wrangler.staging.jsonc` remains a local dry-run artifact; existing production -traffic and access policies are untouched. +## GitHub Actions release boundaries and account preflight + +Official Cloudflare docs now confirm the compatibility pair. The November 17 +release-candidate changelog says `cf@1.0.0-rc.1` switches Build Output to v1 and +requires Wrangler 4.163.0 or later for Wrangler-built projects. The November 18 +project docs say `cf build` writes `.cloudflare/output/v1/`, `cf workers versions +create --prebuilt` consumes it, and `--prebuilt` skips automatic configuration. +The lockfile pins `cf@1.0.0-rc.1`, `@cloudflare/build-output-utils@1.0.0-rc.1`, +and its build producer `wrangler@4.166.0`. Node is pinned at 24.22.0 to meet the +RC's declared engine range. The prebuilt dry-run is run after a separate local +build; this prevents CI from triggering unreviewed auto-configuration. + +The manual workflow `.github/workflows/private-laptop-bridge-release.yml` runs only +for this repository's `main` ref, checks out the event SHA, has `contents: read` +only, serializes per Worker, and pins Actions, Node, cf, Wrangler and lockfile +versions. The `smoke` target is `private-laptop-bridge-smoke` under GitHub +Environment `cloudflare-staging-smoke`. The real bridge target is +`private-laptop-bridge-staging` under `cloudflare-staging`. Both environments +use names `CF_ACCOUNT_ID` and `CF_API_TOKEN`; each token must be independently +account-owned and scoped as **Workers Editor for that one individual existing +Worker**. It must not be scoped to the Workers product or whole account. There +are no environment secrets configured by this change. GitHub environments must +have required reviewers and reject untrusted refs before secrets are provisioned. + +Each upload path runs named runtime tests, `cf build` (bridge build uses mode +`bridge`), a source/config binding equivalence test, then +`cf workers versions create --prebuilt --dry-run` and the actual immutable +version upload. It verifies the uploaded UUID appears in the deployable set. +Promotion is a distinct manual invocation with the exact UUID; it repeats the +deployable check, creates a 100% deployment, and verifies read-back. Recovery is +an explicit promotion of a recorded known-good retained UUID. Fix-forward uploads +a new version and separately promotes it. These actions do not apply Gateway +routes, Workers routes/domains, DNS, TLS settings or access policies. + +**Target existence is not verified.** The tracked Wrangler configs and `cf` +config give only the proposed names `private-laptop-bridge-smoke` and +`private-laptop-bridge-staging`; they prove neither is present in Cloudflare. +The only account evidence found is historical from 2026-10-21: +`Developing.today.llc.domains.0@gmail.com's Account`, partial ID `234b866b…` in +`doc/platform/toolchains/cloudflare-wrangler.md`. No full account ID or live +metadata was obtained. The first workflow step calls `cf workers get` and fails +closed if the selected exact target is absent; it never bootstraps, creates +account resources or widens scopes. Before adding secrets, an authorized owner +must independently confirm full account ID/ownership and existence of the exact +Worker named by that GitHub Environment, then verify the resulting token cannot +read or edit another Worker. No target was probed in this work session. + +If a Worker is absent, its first creation is a **separate owner-reviewed +bootstrap**, because Cloudflare requires Workers product-level Admin to create a +new Worker and per-Worker Editor cannot be granted until the Worker exists. A +candidate owner-operated bootstrap for the bridge is `cf deploy --mode bridge` +from this reviewed commit, using the selected Cloudflare owner/admin identity. +It creates and deploys the first version together, so require an explicit review +of the resolved Build Output and resources first: the Worker must be +`ENABLED=false`, have no routes/workers.dev/previews, and the only resource +creation must be the intended SQLite Durable Object class. Stop if `cf deploy` +shows any other binding/resource or if the account/target is not positively +identified. The smoke Worker requires its own reviewed first deployment. These +are documented commands/plans only; no bootstrap was run. Do not create or store +a Workers-product/whole-account token in GitHub. After bootstrap, provision the +account-owned **Individual Workers → Editor** token for that one exact existing +Worker. The smoke Worker and DO bridge have separate GitHub environments/tokens +so each credential names only one Worker. The bridge environment also cannot +modify Gateway policies; those use a separate approval and administrative path. + +Offline results on the current follow-up commit (recorded in the PR): Node 24.22.0 + cf 1.0.0-rc.1 + Wrangler +4.166.0; both smoke and `--mode bridge` pass `cf build` and the corresponding +`cf workers versions create --prebuilt --dry-run`. The bridge dry-run reports +only the DO namespace binding `BRIDGE -> PrivateLaptopBridge`, disabled +`ENABLED=false`, placeholder Gateway identifiers and empty registry; it creates +nothing. `deployment-config.test.mjs` compares the local/staging Wrangler DO +class and SQLite migration declarations against the cf config. Gateway runtime +unit tests and smoke tests pass. These results prove local Build Output and +configuration consistency, not Cloudflare account reachability, live target +existence, deployment, Gateway routing or laptop readiness. + + +Official references: [cf 1.0.0-rc.1 changelog](https://developers.cloudflare.com/changelog/post/2026-11-17-release-candidate/), [cf project builds and prebuilt uploads](https://developers.cloudflare.com/cf/projects/), and [Workers individual resource Editor permissions](https://developers.cloudflare.com/workers/authorization/workers/). diff --git a/pm-stack/private-laptop-bridge/README.md b/pm-stack/private-laptop-bridge/README.md index 022f998c08..d9fd503782 100644 --- a/pm-stack/private-laptop-bridge/README.md +++ b/pm-stack/private-laptop-bridge/README.md @@ -257,4 +257,4 @@ signing, Worker/SQLite execution, the laptop client, and bounded JSON output. No Aster connector or runner access is installed by this package. -The separate stateless smoke Worker has a manual, protected GitHub Actions deployment using the pinned `cf` Versions API flow. It uploads immutable versions first and requires a second explicit exact-UUID promotion. It does not deploy the bridge Worker or change Gateway policies; see [DISCOVERY.md](DISCOVERY.md). +The stateless smoke Worker and private Durable Object bridge have separate protected GitHub Actions targets using the pinned `cf` Build Output v1 and Versions API flow. Uploads create immutable versions; a separate exact-UUID promotion performs a 100% deployment. Each environment token must be scoped to its one pre-existing Worker. The workflow refuses bootstrap and never changes Gateway policies. See [DISCOVERY.md](DISCOVERY.md) for exact staging prerequisites and recovery. diff --git a/pm-stack/private-laptop-bridge/VERIFICATION.md b/pm-stack/private-laptop-bridge/VERIFICATION.md index 5731de3275..866e33dbd8 100644 --- a/pm-stack/private-laptop-bridge/VERIFICATION.md +++ b/pm-stack/private-laptop-bridge/VERIFICATION.md @@ -104,3 +104,26 @@ The final commit is tested again after committing; exact SHA and command results are recorded in the draft PR checkpoint to avoid a self-referential commit hash. Read-only discovery and the unapproved, metadata-blocked ten-minute smoke packet are in DISCOVERY.md. Proxy routing readiness is not private-host reachability. + + +## cf release-candidate toolchain follow-up + +Offline verification used Node 24.22.0, `cf@1.0.0-rc.1`, +`@cloudflare/build-output-utils@1.0.0-rc.1`, and Wrangler 4.166.0. Commands +ran in `pm-stack/private-laptop-bridge` with a writable XDG config directory: + +```sh +cf build +cf workers versions create --worker private-laptop-bridge-smoke --tag offline-smoke --message offline-smoke --prebuilt --dry-run +cf build --mode bridge +cf workers versions create --worker private-laptop-bridge-staging --tag offline-bridge --message offline-bridge --mode bridge --prebuilt --dry-run +node --test deployment-config.test.mjs smoke.test.mjs gateway.test.mjs +``` + +Both Builds completed and both prebuilt Version API dry-runs exited without +credentials or upload. The bridge dry-run displayed only the `BRIDGE` +`PrivateLaptopBridge` Durable Object binding and default-disabled placeholder +vars; bundle was 17.84 KiB (5.31 KiB gzip). Smoke was 1.96 KiB (0.98 KiB gzip). +Nine targeted tests passed (3 binding/release config, 3 Gateway RPC, 3 smoke). +The workflow YAML and all embedded shell blocks passed local parsing. This is +not evidence of target existence or a live Cloudflare deployment. diff --git a/pm-stack/private-laptop-bridge/cloudflare.config.ts b/pm-stack/private-laptop-bridge/cloudflare.config.ts index 3561454f4f..8b1a740cc8 100644 --- a/pm-stack/private-laptop-bridge/cloudflare.config.ts +++ b/pm-stack/private-laptop-bridge/cloudflare.config.ts @@ -1,13 +1,29 @@ -import {bindings, defineConfig} from 'cf/config'; -import * as entrypoint from './smoke.mjs' with {type:'cf-worker'}; +import {bindings, defineConfig, exports} from 'cf/config'; +import * as smoke from './smoke.mjs' with {type:'cf-worker'}; +import * as bridge from './gateway.mjs' with {type:'cf-worker'}; // Staging deployment target is the bounded, stateless network smoke only. // The live bridge remains disabled pending a separately reviewed config. -export default defineConfig({ +export default defineConfig(({mode}) => mode === 'bridge' ? ({ + worker: { + name: 'private-laptop-bridge-staging', + compatibilityDate: '2026-07-30', + entrypoint: bridge, + exports: {PrivateLaptopBridge: exports.durableObject({storage: 'sqlite'})}, + env: { + ENABLED: bindings.text('false'), + GATEWAY_HOST: bindings.text('private-bridge-staging.invalid'), + GATEWAY_ACCOUNT_ID: bindings.text(''), GATEWAY_POLICY_ID: bindings.text(''), + GATEWAY_IDENTITY_EMAIL: bindings.text(''), GATEWAY_POSTURE_ID: bindings.text(''), + BRIDGE_REGISTRY: bindings.text(''), + BRIDGE: bindings.durableObject({worker: 'private-laptop-bridge-staging', exportName: 'PrivateLaptopBridge'}), + }, + }, +}) : ({ worker: { name: 'private-laptop-bridge-smoke', compatibilityDate: '2026-07-30', - entrypoint, + entrypoint: smoke, env: { ENABLED: bindings.text('false'), GATEWAY_HOST: bindings.text('private-bridge-smoke.invalid'), @@ -15,4 +31,4 @@ export default defineConfig({ START_MS: bindings.text(''), END_MS: bindings.text(''), }, }, -}); +})); diff --git a/pm-stack/private-laptop-bridge/deployment-config.test.mjs b/pm-stack/private-laptop-bridge/deployment-config.test.mjs new file mode 100644 index 0000000000..43a7a48034 --- /dev/null +++ b/pm-stack/private-laptop-bridge/deployment-config.test.mjs @@ -0,0 +1,47 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {readFile} from 'node:fs/promises'; + +const read = name => readFile(new URL(name, import.meta.url), 'utf8'); +function parseJsonc(source) { + // These repository configs use line comments only and do not contain URLs + // in JSON strings with //; keep this helper deliberately limited. + return JSON.parse(source.split('\n').filter(line => !line.trimStart().startsWith('//')).join('\n')); +} + +test('Wrangler local and staging definitions preserve the same DO class and SQLite migration', async () => { + const local = parseJsonc(await read('./wrangler.jsonc')); + const staging = parseJsonc(await read('./wrangler.staging.jsonc')); + for (const config of [local, staging]) { + assert.equal(config.name, 'private-laptop-bridge-staging'); + assert.equal(config.compatibility_date, '2026-07-30'); + assert.equal(config.workers_dev, false); + assert.equal(config.preview_urls, false); + assert.deepEqual(config.durable_objects.bindings, [{name:'BRIDGE',class_name:'PrivateLaptopBridge'}]); + assert.deepEqual(config.migrations, [{tag:'v1',new_sqlite_classes:['PrivateLaptopBridge']}]); + } + assert.equal(local.main, 'worker.mjs'); + assert.equal(staging.main, 'gateway.mjs'); +}); + +test('cf release config matches the reviewed private bridge resources and remains disabled', async () => { + const config = await read('./cloudflare.config.ts'); + assert.match(config, /name:\s*'private-laptop-bridge-staging'/); + assert.match(config, /mode\s*===\s*'bridge'/); + assert.match(config, /entrypoint:\s*bridge/); + assert.match(config, /PrivateLaptopBridge:\s*exports\.durableObject\(\{storage:\s*'sqlite'\}\)/); + assert.match(config, /BRIDGE:\s*bindings\.durableObject\(\{worker:\s*'private-laptop-bridge-staging',\s*exportName:\s*'PrivateLaptopBridge'\}\)/); + assert.match(config, /ENABLED:\s*bindings\.text\('false'\)/); + assert.match(config, /GATEWAY_HOST:\s*bindings\.text\('private-bridge-staging\.invalid'\)/); + assert.match(config, /BRIDGE_REGISTRY:\s*bindings\.text\(''\)/); +}); + +test('pinned cf release and Wrangler producer satisfy the documented Build Output v1 pair', async () => { + const pkg = JSON.parse(await read('./package.json')); + const lock = JSON.parse(await read('./package-lock.json')); + assert.equal(pkg.devDependencies.cf, '1.0.0-rc.1'); + assert.equal(lock.packages['node_modules/cf'].version, pkg.devDependencies.cf); + assert.equal(pkg.devDependencies.wrangler, '4.166.0'); + assert.equal(lock.packages['node_modules/wrangler'].version, pkg.devDependencies.wrangler); + assert.equal(lock.packages['node_modules/@cloudflare/build-output-utils'].version, '1.0.0-rc.1'); +}); diff --git a/pm-stack/private-laptop-bridge/package-lock.json b/pm-stack/private-laptop-bridge/package-lock.json index 44b521a595..29acd5a41c 100644 --- a/pm-stack/private-laptop-bridge/package-lock.json +++ b/pm-stack/private-laptop-bridge/package-lock.json @@ -6,32 +6,32 @@ "": { "name": "private-laptop-bridge", "devDependencies": { - "cf": "1.0.0-beta.20", + "cf": "1.0.0-rc.1", "miniflare": "4.20260730.0", "wrangler": "4.166.0" }, "engines": { - "node": ">=24" + "node": ">=24.22.0" } }, "node_modules/@cloudflare/build-output-utils": { - "version": "0.9.3", - "resolved": "https://registry.npmjs.org/@cloudflare/build-output-utils/-/build-output-utils-0.9.3.tgz", - "integrity": "sha512-0MgvIq6UxbRWLwB2QJU7qjLqpPkfygOebN3UiENhdp+z6zpRKrNnwkms2ynadmxCOh3sL2v+SI0/pNXxgXdteA==", + "version": "1.0.0-rc.1", + "resolved": "https://registry.npmjs.org/@cloudflare/build-output-utils/-/build-output-utils-1.0.0-rc.1.tgz", + "integrity": "sha512-IrzZL1UEdVMZPRarrKu2VpnL3MIeNVhCItTebB88SwQ1YJ4mLAe1kQtXmIH7MpdgDYnxAsTZXMtuw9q5jRWCcw==", "dev": true, "license": "MIT", "dependencies": { - "@cloudflare/config": "0.27.0" + "@cloudflare/config": "1.0.0-rc.1" } }, "node_modules/@cloudflare/config": { - "version": "0.27.0", - "resolved": "https://registry.npmjs.org/@cloudflare/config/-/config-0.27.0.tgz", - "integrity": "sha512-wNnL0z4lj5Gm2fze5qXTOvRPbUOi4jlMmwPk7ArCUakI5oVxgjfl3Rhnfd/Mmzo3g86x/ofH75yPIhsa5msqdQ==", + "version": "1.0.0-rc.1", + "resolved": "https://registry.npmjs.org/@cloudflare/config/-/config-1.0.0-rc.1.tgz", + "integrity": "sha512-NQgB+fQbk8IU0iJ6/G9LCSQjJ7JuyRn5CALrPKnQ8vxqayOJlX+av9adhLCMYBeC80ocncW1Gy7quv00uLV3LQ==", "dev": true, "license": "MIT", "dependencies": { - "zod": "4.6.5" + "zod": "4.6.6" } }, "node_modules/@cloudflare/kv-asset-handler": { @@ -45,20 +45,20 @@ } }, "node_modules/@cloudflare/runtime-types": { - "version": "0.1.14", - "resolved": "https://registry.npmjs.org/@cloudflare/runtime-types/-/runtime-types-0.1.14.tgz", - "integrity": "sha512-Hx4/RGjTNKPTB0z6q9MRv6GzvnL496EBvvBaUpANilSLfQJFXVkmClrbiMkzTFjzVRTgMsOhO8exwwkZu3OM8w==", + "version": "0.1.30", + "resolved": "https://registry.npmjs.org/@cloudflare/runtime-types/-/runtime-types-0.1.30.tgz", + "integrity": "sha512-p68T70lDZT7Vyv5c2SDzB0uqVRVCtj/3WMgXVQESnWVyTybcCwXRM9Ekmh2rQ+aPGhtIWiACvd8pX2yGA9Z5mw==", "dev": true, "license": "MIT", "dependencies": { - "miniflare": "5.20261019.1-beta", - "workerd": "1.20261019.1" + "miniflare": "5.20261117.0-beta", + "workerd": "1.20261117.1" } }, "node_modules/@cloudflare/runtime-types/node_modules/@cloudflare/workerd-darwin-64": { - "version": "1.20261019.1", - "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-64/-/workerd-darwin-64-1.20261019.1.tgz", - "integrity": "sha512-5ZILbAta/fBQvhmAYeCE7dKMMYIr7N9wJEX50fEGLKSIwGtvT0HzSfHNIK/O7cBQ4gHQ2WfIiPClvwcye6E0fA==", + "version": "1.20261117.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-64/-/workerd-darwin-64-1.20261117.1.tgz", + "integrity": "sha512-qfAYw6iPoey0BmPsp4z5ARWOa+XSBD3gQzmcBI2ql9pKTSA5eEC8F1oI6BIk/FVguhomfSn5gS4RzbWhTd/EpQ==", "cpu": [ "x64" ], @@ -73,9 +73,9 @@ } }, "node_modules/@cloudflare/runtime-types/node_modules/@cloudflare/workerd-darwin-arm64": { - "version": "1.20261019.1", - "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-arm64/-/workerd-darwin-arm64-1.20261019.1.tgz", - "integrity": "sha512-cww2Ab6lVMxpTiEEjKmPI58p5EMo0vYTZSH+3WkqXJdQgc3ES66GuL247+U2B2YWajhhu2tqj7jySrXneU749g==", + "version": "1.20261117.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-arm64/-/workerd-darwin-arm64-1.20261117.1.tgz", + "integrity": "sha512-cInx5Cr9O27oW+ujyI49lTRQZra/lMgWUFiKmGY3jxDncATSxzfQ6udXHkVvK4//1/PfxQTDyMjdQUIN8m6Aqg==", "cpu": [ "arm64" ], @@ -90,9 +90,9 @@ } }, "node_modules/@cloudflare/runtime-types/node_modules/@cloudflare/workerd-linux-64": { - "version": "1.20261019.1", - "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-64/-/workerd-linux-64-1.20261019.1.tgz", - "integrity": "sha512-4++VRi9vkQROYqrpZYOixIJuVDmujkwrT4kszsxNFlvcmsX6Mr2GumvxIN3gIixS3vJUh3Umdtkthqj5X0S3Xw==", + "version": "1.20261117.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-64/-/workerd-linux-64-1.20261117.1.tgz", + "integrity": "sha512-gZLA8X11m/luZwn+YA3+mDu61vdxNJzpksP/QZqjydKTQ+VUCulsK5gtn9Bqst1p3KJu2kafQpJ1nDQv4B23jA==", "cpu": [ "x64" ], @@ -107,9 +107,9 @@ } }, "node_modules/@cloudflare/runtime-types/node_modules/@cloudflare/workerd-linux-arm64": { - "version": "1.20261019.1", - "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-arm64/-/workerd-linux-arm64-1.20261019.1.tgz", - "integrity": "sha512-75PVtJOwfjScQ53sbLtQXI7D8yP1c21t+WEUPaYbqkzaz4ZqfR5wAd+zuWs8G5Q7kOj2SQIvEfY5Sn8Y+UVrnA==", + "version": "1.20261117.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-arm64/-/workerd-linux-arm64-1.20261117.1.tgz", + "integrity": "sha512-gxWngFojq41ULKNKb9rpWYvKotN5hT2I/xot+Bpy31cXzrwcTgtDLSMb2t75sW5BJxH7hihFvikgYb577kB3Zg==", "cpu": [ "arm64" ], @@ -124,9 +124,9 @@ } }, "node_modules/@cloudflare/runtime-types/node_modules/@cloudflare/workerd-windows-64": { - "version": "1.20261019.1", - "resolved": "https://registry.npmjs.org/@cloudflare/workerd-windows-64/-/workerd-windows-64-1.20261019.1.tgz", - "integrity": "sha512-z49fvKTETMCnG6wnMcQwxx9CpryFceiKz04FRjq26EkhCyzRNJ6c3UXhyZz3r5f1CXnnBZc5DcU8ZouPkUJCqw==", + "version": "1.20261117.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-windows-64/-/workerd-windows-64-1.20261117.1.tgz", + "integrity": "sha512-0OR2Btx5EDonOKvvuGDq8rxBSggxoF1ThQjbZN3vsu3GlaF/oXW5f9/iB78OgV0CzMPTi+hZgzc1NR95UJCURA==", "cpu": [ "x64" ], @@ -658,21 +658,29 @@ } }, "node_modules/@cloudflare/runtime-types/node_modules/miniflare": { - "version": "5.20261019.1-beta", - "resolved": "https://registry.npmjs.org/miniflare/-/miniflare-5.20261019.1-beta.tgz", - "integrity": "sha512-1n7MN2UqZnPniyYAqNuV1YEAaja66ozKGVCc5ZTmYQhTubnoAwGLccwb+ZWYLOajuw3pOaJ70u//bZMuURlRew==", + "version": "5.20261117.0-beta", + "resolved": "https://registry.npmjs.org/miniflare/-/miniflare-5.20261117.0-beta.tgz", + "integrity": "sha512-D2ygY04wQUmbpwgBhj828piErZoj7UMlXNGr4EWQp/c1PNGHyYOh0dMIyobjwOXiD5Ifl1EaEVAoNuBHK+qtkw==", "dev": true, "license": "MIT", "dependencies": { "@cspotcode/source-map-support": "0.8.1", "sharp": "0.35.5", - "undici": "7.29.1", - "workerd": "1.20261019.1", + "undici": "7.30.1", + "workerd": "1.20261117.1", "ws": "8.21.0", "youch": "4.1.0-beta.10" }, "engines": { - "node": ">=22.0.0" + "node": ">=22.12.0" + }, + "peerDependencies": { + "kerberos": "^2.0.0" + }, + "peerDependenciesMeta": { + "kerberos": { + "optional": true + } } }, "node_modules/@cloudflare/runtime-types/node_modules/sharp": { @@ -726,9 +734,9 @@ } }, "node_modules/@cloudflare/runtime-types/node_modules/undici": { - "version": "7.29.1", - "resolved": "https://registry.npmjs.org/undici/-/undici-7.29.1.tgz", - "integrity": "sha512-RYONW2MeafgYlkVOKYKkA/Ag7BmXqgIWCa8t1m0JcxrQg9pI9lEqRhAOruOBCbAohOa/gkCF+iPi9hrgvTzu6Q==", + "version": "7.30.1", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.30.1.tgz", + "integrity": "sha512-03KrMbjIFDWQR5RNPrSw3bd1r12JpyFQl9/yxjUbJtqkjmllqC5lFjZh6ujeuJCKr8EOQvRW872Oy/az+nLYxg==", "dev": true, "license": "MIT", "engines": { @@ -736,9 +744,9 @@ } }, "node_modules/@cloudflare/runtime-types/node_modules/workerd": { - "version": "1.20261019.1", - "resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20261019.1.tgz", - "integrity": "sha512-UUYRUq/7DmeCl11YriNbcVbjUZVLtt8uuCXFu+nz77hGFf8d4DEVXoCYtnA+MlBatE4+wxoj47DVqzK3xGBAiw==", + "version": "1.20261117.1", + "resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20261117.1.tgz", + "integrity": "sha512-iakDbGVtJRiErpWSM5fYT0z3spJ2Mo1x/POsEajBNLqUbTRwm8vMqbB7g8zPN2tzs6eZYNiO5ECyEnAXO9Foxw==", "dev": true, "hasInstallScript": true, "license": "Apache-2.0", @@ -749,11 +757,11 @@ "node": ">=16" }, "optionalDependencies": { - "@cloudflare/workerd-darwin-64": "1.20261019.1", - "@cloudflare/workerd-darwin-arm64": "1.20261019.1", - "@cloudflare/workerd-linux-64": "1.20261019.1", - "@cloudflare/workerd-linux-arm64": "1.20261019.1", - "@cloudflare/workerd-windows-64": "1.20261019.1" + "@cloudflare/workerd-darwin-64": "1.20261117.1", + "@cloudflare/workerd-darwin-arm64": "1.20261117.1", + "@cloudflare/workerd-linux-64": "1.20261117.1", + "@cloudflare/workerd-linux-arm64": "1.20261117.1", + "@cloudflare/workerd-windows-64": "1.20261117.1" } }, "node_modules/@cloudflare/unenv-preset": { @@ -2051,17 +2059,17 @@ } }, "node_modules/cf": { - "version": "1.0.0-beta.20", - "resolved": "https://registry.npmjs.org/cf/-/cf-1.0.0-beta.20.tgz", - "integrity": "sha512-sBg/zok+znpGvI00XwsUfuVz+5MyfnJcFY8YUwRXcl4eNg9qQWtnCf1YMq9rsWjcbr7BwjM1xbNJPTDhtkCRnw==", + "version": "1.0.0-rc.1", + "resolved": "https://registry.npmjs.org/cf/-/cf-1.0.0-rc.1.tgz", + "integrity": "sha512-mQ9X/FVE1QP2ebXVF/9tlbqoO0TB3tKxUJocaWsic6IuNvThmJc/Ou/4ABJNB/Sj8HxEzvrjT1PRqjySVO5YoA==", "dev": true, "license": "MIT OR Apache-2.0", "dependencies": { - "@cloudflare/build-output-utils": "0.9.3", - "@cloudflare/config": "0.27.0", - "@cloudflare/runtime-types": "0.1.14", + "@cloudflare/build-output-utils": "1.0.0-rc.1", + "@cloudflare/config": "1.0.0-rc.1", + "@cloudflare/runtime-types": "0.1.30", "blake3-wasm": "2.1.5", - "miniflare": "5.20261019.1-beta" + "miniflare": "5.20261117.0-beta" }, "bin": { "cf": "bin/cf", @@ -2072,9 +2080,9 @@ } }, "node_modules/cf/node_modules/@cloudflare/workerd-darwin-64": { - "version": "1.20261019.1", - "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-64/-/workerd-darwin-64-1.20261019.1.tgz", - "integrity": "sha512-5ZILbAta/fBQvhmAYeCE7dKMMYIr7N9wJEX50fEGLKSIwGtvT0HzSfHNIK/O7cBQ4gHQ2WfIiPClvwcye6E0fA==", + "version": "1.20261117.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-64/-/workerd-darwin-64-1.20261117.1.tgz", + "integrity": "sha512-qfAYw6iPoey0BmPsp4z5ARWOa+XSBD3gQzmcBI2ql9pKTSA5eEC8F1oI6BIk/FVguhomfSn5gS4RzbWhTd/EpQ==", "cpu": [ "x64" ], @@ -2089,9 +2097,9 @@ } }, "node_modules/cf/node_modules/@cloudflare/workerd-darwin-arm64": { - "version": "1.20261019.1", - "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-arm64/-/workerd-darwin-arm64-1.20261019.1.tgz", - "integrity": "sha512-cww2Ab6lVMxpTiEEjKmPI58p5EMo0vYTZSH+3WkqXJdQgc3ES66GuL247+U2B2YWajhhu2tqj7jySrXneU749g==", + "version": "1.20261117.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-arm64/-/workerd-darwin-arm64-1.20261117.1.tgz", + "integrity": "sha512-cInx5Cr9O27oW+ujyI49lTRQZra/lMgWUFiKmGY3jxDncATSxzfQ6udXHkVvK4//1/PfxQTDyMjdQUIN8m6Aqg==", "cpu": [ "arm64" ], @@ -2106,9 +2114,9 @@ } }, "node_modules/cf/node_modules/@cloudflare/workerd-linux-64": { - "version": "1.20261019.1", - "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-64/-/workerd-linux-64-1.20261019.1.tgz", - "integrity": "sha512-4++VRi9vkQROYqrpZYOixIJuVDmujkwrT4kszsxNFlvcmsX6Mr2GumvxIN3gIixS3vJUh3Umdtkthqj5X0S3Xw==", + "version": "1.20261117.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-64/-/workerd-linux-64-1.20261117.1.tgz", + "integrity": "sha512-gZLA8X11m/luZwn+YA3+mDu61vdxNJzpksP/QZqjydKTQ+VUCulsK5gtn9Bqst1p3KJu2kafQpJ1nDQv4B23jA==", "cpu": [ "x64" ], @@ -2123,9 +2131,9 @@ } }, "node_modules/cf/node_modules/@cloudflare/workerd-linux-arm64": { - "version": "1.20261019.1", - "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-arm64/-/workerd-linux-arm64-1.20261019.1.tgz", - "integrity": "sha512-75PVtJOwfjScQ53sbLtQXI7D8yP1c21t+WEUPaYbqkzaz4ZqfR5wAd+zuWs8G5Q7kOj2SQIvEfY5Sn8Y+UVrnA==", + "version": "1.20261117.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-arm64/-/workerd-linux-arm64-1.20261117.1.tgz", + "integrity": "sha512-gxWngFojq41ULKNKb9rpWYvKotN5hT2I/xot+Bpy31cXzrwcTgtDLSMb2t75sW5BJxH7hihFvikgYb577kB3Zg==", "cpu": [ "arm64" ], @@ -2140,9 +2148,9 @@ } }, "node_modules/cf/node_modules/@cloudflare/workerd-windows-64": { - "version": "1.20261019.1", - "resolved": "https://registry.npmjs.org/@cloudflare/workerd-windows-64/-/workerd-windows-64-1.20261019.1.tgz", - "integrity": "sha512-z49fvKTETMCnG6wnMcQwxx9CpryFceiKz04FRjq26EkhCyzRNJ6c3UXhyZz3r5f1CXnnBZc5DcU8ZouPkUJCqw==", + "version": "1.20261117.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-windows-64/-/workerd-windows-64-1.20261117.1.tgz", + "integrity": "sha512-0OR2Btx5EDonOKvvuGDq8rxBSggxoF1ThQjbZN3vsu3GlaF/oXW5f9/iB78OgV0CzMPTi+hZgzc1NR95UJCURA==", "cpu": [ "x64" ], @@ -2674,21 +2682,29 @@ } }, "node_modules/cf/node_modules/miniflare": { - "version": "5.20261019.1-beta", - "resolved": "https://registry.npmjs.org/miniflare/-/miniflare-5.20261019.1-beta.tgz", - "integrity": "sha512-1n7MN2UqZnPniyYAqNuV1YEAaja66ozKGVCc5ZTmYQhTubnoAwGLccwb+ZWYLOajuw3pOaJ70u//bZMuURlRew==", + "version": "5.20261117.0-beta", + "resolved": "https://registry.npmjs.org/miniflare/-/miniflare-5.20261117.0-beta.tgz", + "integrity": "sha512-D2ygY04wQUmbpwgBhj828piErZoj7UMlXNGr4EWQp/c1PNGHyYOh0dMIyobjwOXiD5Ifl1EaEVAoNuBHK+qtkw==", "dev": true, "license": "MIT", "dependencies": { "@cspotcode/source-map-support": "0.8.1", "sharp": "0.35.5", - "undici": "7.29.1", - "workerd": "1.20261019.1", + "undici": "7.30.1", + "workerd": "1.20261117.1", "ws": "8.21.0", "youch": "4.1.0-beta.10" }, "engines": { - "node": ">=22.0.0" + "node": ">=22.12.0" + }, + "peerDependencies": { + "kerberos": "^2.0.0" + }, + "peerDependenciesMeta": { + "kerberos": { + "optional": true + } } }, "node_modules/cf/node_modules/sharp": { @@ -2742,9 +2758,9 @@ } }, "node_modules/cf/node_modules/undici": { - "version": "7.29.1", - "resolved": "https://registry.npmjs.org/undici/-/undici-7.29.1.tgz", - "integrity": "sha512-RYONW2MeafgYlkVOKYKkA/Ag7BmXqgIWCa8t1m0JcxrQg9pI9lEqRhAOruOBCbAohOa/gkCF+iPi9hrgvTzu6Q==", + "version": "7.30.1", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.30.1.tgz", + "integrity": "sha512-03KrMbjIFDWQR5RNPrSw3bd1r12JpyFQl9/yxjUbJtqkjmllqC5lFjZh6ujeuJCKr8EOQvRW872Oy/az+nLYxg==", "dev": true, "license": "MIT", "engines": { @@ -2752,9 +2768,9 @@ } }, "node_modules/cf/node_modules/workerd": { - "version": "1.20261019.1", - "resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20261019.1.tgz", - "integrity": "sha512-UUYRUq/7DmeCl11YriNbcVbjUZVLtt8uuCXFu+nz77hGFf8d4DEVXoCYtnA+MlBatE4+wxoj47DVqzK3xGBAiw==", + "version": "1.20261117.1", + "resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20261117.1.tgz", + "integrity": "sha512-iakDbGVtJRiErpWSM5fYT0z3spJ2Mo1x/POsEajBNLqUbTRwm8vMqbB7g8zPN2tzs6eZYNiO5ECyEnAXO9Foxw==", "dev": true, "hasInstallScript": true, "license": "Apache-2.0", @@ -2765,11 +2781,11 @@ "node": ">=16" }, "optionalDependencies": { - "@cloudflare/workerd-darwin-64": "1.20261019.1", - "@cloudflare/workerd-darwin-arm64": "1.20261019.1", - "@cloudflare/workerd-linux-64": "1.20261019.1", - "@cloudflare/workerd-linux-arm64": "1.20261019.1", - "@cloudflare/workerd-windows-64": "1.20261019.1" + "@cloudflare/workerd-darwin-64": "1.20261117.1", + "@cloudflare/workerd-darwin-arm64": "1.20261117.1", + "@cloudflare/workerd-linux-64": "1.20261117.1", + "@cloudflare/workerd-linux-arm64": "1.20261117.1", + "@cloudflare/workerd-windows-64": "1.20261117.1" } }, "node_modules/chalk": { @@ -4248,9 +4264,9 @@ } }, "node_modules/zod": { - "version": "4.6.5", - "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.5.tgz", - "integrity": "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==", + "version": "4.6.6", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.6.tgz", + "integrity": "sha512-4UmzQUF5fxvfcYHlbjBmejU+w+hbDnWFx4aS8kBx7nPBHcO2SqPbpAG8snbdg+Xse4pRefR98hgjFgIMCI/UhA==", "dev": true, "license": "MIT", "funding": { diff --git a/pm-stack/private-laptop-bridge/package.json b/pm-stack/private-laptop-bridge/package.json index 2b5e2f3319..e840ef0f0f 100644 --- a/pm-stack/private-laptop-bridge/package.json +++ b/pm-stack/private-laptop-bridge/package.json @@ -8,11 +8,11 @@ "check:staging": "WRANGLER_SEND_METRICS=false wrangler deploy --dry-run --config wrangler.staging.jsonc --outdir .wrangler/staging-dry-run" }, "engines": { - "node": ">=24" + "node": ">=24.22.0" }, "devDependencies": { "miniflare": "4.20260730.0", "wrangler": "4.166.0", - "cf": "1.0.0-beta.20" + "cf": "1.0.0-rc.1" } } From f78023b932f0daf2cc4ff8abddb8d998fbe1b7a5 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 14:28:43 +0000 Subject: [PATCH 10/33] Harden private bridge release provenance and preflight --- .../private-laptop-bridge-release.yml | 228 ++++++++++++------ pm-stack/private-laptop-bridge/DISCOVERY.md | 63 +++-- .../private-laptop-bridge/VERIFICATION.md | 45 ++++ .../cloudflare.config.ts | 11 + .../release-artifact.mjs | 71 ++++++ .../release-contract.mjs | 201 +++++++++++++++ .../release-contract.test.mjs | 125 ++++++++++ .../staging-preflight.json | 59 +++++ pm-stack/private-laptop-bridge/wrangler.jsonc | 2 + .../wrangler.staging.jsonc | 2 + 10 files changed, 711 insertions(+), 96 deletions(-) create mode 100644 pm-stack/private-laptop-bridge/release-artifact.mjs create mode 100644 pm-stack/private-laptop-bridge/release-contract.mjs create mode 100644 pm-stack/private-laptop-bridge/release-contract.test.mjs create mode 100644 pm-stack/private-laptop-bridge/staging-preflight.json diff --git a/.github/workflows/private-laptop-bridge-release.yml b/.github/workflows/private-laptop-bridge-release.yml index 0a8ab8e563..1dea346bf9 100644 --- a/.github/workflows/private-laptop-bridge-release.yml +++ b/.github/workflows/private-laptop-bridge-release.yml @@ -1,183 +1,253 @@ -name: Private laptop bridge Workers +name: Private laptop bridge Workers release on: workflow_dispatch: inputs: action: - description: Upload a disabled version, or promote a previously reviewed version + description: Upload an immutable candidate or promote a candidate from an exact successful upload run type: choice required: true options: [upload, promote] worker: - description: Exact pre-existing Worker target; each GitHub environment token must be scoped to only this Worker + description: Exact pre-existing Worker; each environment token is scoped to only this Worker type: choice required: true options: [smoke, bridge] - version_id: - description: Exact version UUID; required for promote and ignored for upload + upload_run_id: + description: Successful main-branch upload workflow run ID; required only for promote type: string required: false permissions: + actions: read contents: read concurrency: - group: private-laptop-bridge-${{ inputs.worker }}-deploy + group: private-laptop-bridge-${{ inputs.worker }}-release cancel-in-progress: false jobs: - deploy: + release: if: github.repository == 'developing-today/code' && github.ref == 'refs/heads/main' && (inputs.worker == 'bridge' || inputs.worker == 'smoke') environment: ${{ inputs.worker == 'bridge' && 'cloudflare-staging' || inputs.worker == 'smoke' && 'cloudflare-staging-smoke' || 'invalid-worker-selection' }} runs-on: ubuntu-24.04 - timeout-minutes: 15 + timeout-minutes: 25 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ github.sha }} + fetch-depth: 1 persist-credentials: false - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 24.22.0 cache: npm cache-dependency-path: pm-stack/private-laptop-bridge/package-lock.json - - name: Install pinned cf CLI and locked project tooling - working-directory: pm-stack/private-laptop-bridge - run: npm ci --ignore-scripts --no-audit --no-fund - - name: Validate request and Cloudflare target + - name: Validate trusted request and fixed target id: target + working-directory: pm-stack/private-laptop-bridge env: ACTION_KIND: ${{ inputs.action }} WORKER_KIND: ${{ inputs.worker }} - VERSION_ID: ${{ inputs.version_id }} - CF_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }} - CF_API_TOKEN: ${{ secrets.CF_API_TOKEN }} + UPLOAD_RUN_ID: ${{ inputs.upload_run_id }} run: | set -euo pipefail - [[ "$GITHUB_REF" == refs/heads/main && "$GITHUB_EVENT_NAME" == workflow_dispatch ]] - [[ "$CF_ACCOUNT_ID" =~ ^[0-9a-f]{32}$ && -n "$CF_API_TOKEN" ]] - if [[ "$ACTION_KIND" == upload ]]; then - [[ -z "$VERSION_ID" ]] - elif [[ "$ACTION_KIND" == promote ]]; then - [[ "$VERSION_ID" =~ ^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$ ]] - else exit 2; fi + [[ "$GITHUB_REPOSITORY" == developing-today/code && "$GITHUB_REF" == refs/heads/main && "$GITHUB_EVENT_NAME" == workflow_dispatch ]] + if [[ "$ACTION_KIND" == upload ]]; then [[ -z "$UPLOAD_RUN_ID" ]]; elif [[ "$ACTION_KIND" == promote ]]; then [[ "$UPLOAD_RUN_ID" =~ ^[0-9]{1,20}$ ]]; else exit 2; fi case "$WORKER_KIND" in - smoke) echo "worker=private-laptop-bridge-smoke" >> "$GITHUB_OUTPUT"; echo "mode=default" >> "$GITHUB_OUTPUT" ;; - bridge) echo "worker=private-laptop-bridge-staging" >> "$GITHUB_OUTPUT"; echo "mode=bridge" >> "$GITHUB_OUTPUT" ;; + smoke) echo "worker=private-laptop-bridge-smoke" >> "$GITHUB_OUTPUT"; echo "environment=cloudflare-staging-smoke" >> "$GITHUB_OUTPUT"; echo "mode=default" >> "$GITHUB_OUTPUT" ;; + bridge) echo "worker=private-laptop-bridge-staging" >> "$GITHUB_OUTPUT"; echo "environment=cloudflare-staging" >> "$GITHUB_OUTPUT"; echo "mode=bridge" >> "$GITHUB_OUTPUT" ;; *) exit 2 ;; esac - - name: Require an existing Worker (no bootstrap or resource creation) + - name: Download handoff from exact upload run + if: inputs.action == 'promote' + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: private-bridge-candidate-${{ inputs.upload_run_id }} + run-id: ${{ inputs.upload_run_id }} + github-token: ${{ github.token }} + path: ${{ runner.temp }}/private-bridge-handoff + - name: Read exact upload workflow run metadata + if: inputs.action == 'promote' + env: + GH_TOKEN: ${{ github.token }} + RUN_ID: ${{ inputs.upload_run_id }} + run: | + set -euo pipefail + curl --fail --silent --show-error --max-time 15 \ + -H "Authorization: Bearer $GH_TOKEN" -H 'Accept: application/vnd.github+json' \ + "$GITHUB_API_URL/repos/$GITHUB_REPOSITORY/actions/runs/$RUN_ID" > "$RUNNER_TEMP/upload-run.json" + curl --fail --silent --show-error --max-time 15 \ + -H "Authorization: Bearer $GH_TOKEN" -H 'Accept: application/vnd.github+json' \ + "$GITHUB_API_URL/repos/$GITHUB_REPOSITORY/actions/runs/$RUN_ID/jobs?per_page=100" > "$RUNNER_TEMP/upload-jobs.json" + - name: Validate upload run and artifact target provenance + if: inputs.action == 'promote' + id: provenance working-directory: pm-stack/private-laptop-bridge env: - CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }} - CLOUDFLARE_API_TOKEN: ${{ secrets.CF_API_TOKEN }} TARGET_WORKER: ${{ steps.target.outputs.worker }} + TARGET_ENV: ${{ steps.target.outputs.environment }} + TARGET_MODE: ${{ steps.target.outputs.mode }} + CF_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }} + run: | + set -euo pipefail + node release-artifact.mjs provenance \ + "$RUNNER_TEMP/private-bridge-handoff/candidate.json" "$RUNNER_TEMP/upload-run.json" \ + "$RUNNER_TEMP/upload-jobs.json" \ + | tee "$RUNNER_TEMP/upload-source-sha" + echo "source_sha=$(cat "$RUNNER_TEMP/upload-source-sha")" >> "$GITHUB_OUTPUT" + - name: Verify owner proof unchanged since upload + if: inputs.action == 'promote' + working-directory: pm-stack/private-laptop-bridge + env: + CF_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }} + TARGET_WORKER: ${{ steps.target.outputs.worker }} + TARGET_ENV: ${{ steps.target.outputs.environment }} + HANDOFF: ${{ runner.temp }}/private-bridge-handoff/candidate.json + run: node release-artifact.mjs current-proof "$HANDOFF" + - name: Check out the exact uploaded source commit + if: inputs.action == 'promote' + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ steps.provenance.outputs.source_sha }} + fetch-depth: 0 + persist-credentials: false + - name: Require source remains on current protected main history + if: inputs.action == 'promote' + env: + SOURCE_SHA: ${{ steps.provenance.outputs.source_sha }} run: | set -euo pipefail - npx --no-install cf -q workers get "$TARGET_WORKER" >/dev/null - - name: Test Worker entrypoint + git fetch --no-tags origin main + git merge-base --is-ancestor "$SOURCE_SHA" FETCH_HEAD + - name: Install exact locked toolchain + working-directory: pm-stack/private-laptop-bridge + run: npm ci --ignore-scripts --no-audit --no-fund + - name: Validate account owner proof before Cloudflare access + working-directory: pm-stack/private-laptop-bridge + env: + CF_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }} + TARGET_WORKER: ${{ steps.target.outputs.worker }} + TARGET_ENV: ${{ steps.target.outputs.environment }} + run: node release-artifact.mjs preflight + - name: Require existing exact Worker; never bootstrap from CI + working-directory: pm-stack/private-laptop-bridge + env: + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }} + CLOUDFLARE_API_TOKEN: ${{ secrets.CF_API_TOKEN }} + TARGET_WORKER: ${{ steps.target.outputs.worker }} + run: npx --no-install cf -q workers get "$TARGET_WORKER" >/dev/null + - name: Verify source tests and effective local config if: inputs.action == 'upload' working-directory: pm-stack/private-laptop-bridge env: WORKER_KIND: ${{ inputs.worker }} run: | set -euo pipefail + node --test deployment-config.test.mjs release-contract.test.mjs case "$WORKER_KIND" in bridge) node --test gateway.test.mjs ;; smoke) node --test smoke.test.mjs ;; *) exit 2 ;; esac - - name: Build pinned Build Output v1 - if: inputs.action == 'upload' + - name: Build exact Build Output v1 from candidate source + if: inputs.action == 'upload' || inputs.action == 'promote' working-directory: pm-stack/private-laptop-bridge env: TARGET_MODE: ${{ steps.target.outputs.mode }} run: | set -euo pipefail if [[ "$TARGET_MODE" == bridge ]]; then npx --no-install cf build --mode bridge; else npx --no-install cf build; fi - - name: Check Wrangler and cf Worker binding definitions agree - if: inputs.action == 'upload' + - name: Check Wrangler and cf binding declarations working-directory: pm-stack/private-laptop-bridge env: TARGET_MODE: ${{ steps.target.outputs.mode }} run: node deployment-config.test.mjs - - name: Validate the exact prebuilt Version API upload - if: inputs.action == 'upload' + - name: Validate effective prebuilt upload payload working-directory: pm-stack/private-laptop-bridge env: TARGET_WORKER: ${{ steps.target.outputs.worker }} TARGET_MODE: ${{ steps.target.outputs.mode }} + DRY_RUN_OUTPUT: ${{ runner.temp }}/cf-version-dry-run.txt run: | set -euo pipefail - args=(workers versions create --worker "$TARGET_WORKER" --tag offline-check --message offline-check --prebuilt --dry-run) + args=(workers versions create --worker "$TARGET_WORKER" --tag "${GITHUB_SHA}" --message "offline validation" --prebuilt --dry-run) if [[ "$TARGET_MODE" == bridge ]]; then args+=(--mode bridge); fi - npx --no-install cf -q "${args[@]}" - - name: Upload immutable version only + npx --no-install cf -q "${args[@]}" 2>&1 | tee "$DRY_RUN_OUTPUT" + node release-artifact.mjs dry-run + - name: Upload an immutable candidate and write exact provenance artifact if: inputs.action == 'upload' + id: upload working-directory: pm-stack/private-laptop-bridge env: CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }} CLOUDFLARE_API_TOKEN: ${{ secrets.CF_API_TOKEN }} + CF_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }} TARGET_WORKER: ${{ steps.target.outputs.worker }} + TARGET_ENV: ${{ steps.target.outputs.environment }} TARGET_MODE: ${{ steps.target.outputs.mode }} + VERSION_RESPONSE: ${{ runner.temp }}/cf-version-response.json + WRANGLER_OUTPUT_FILE_PATH: ${{ runner.temp }}/cf-version-response.json + VERSION_LIST: ${{ runner.temp }}/cf-version-list.json + CANDIDATE_FILE: ${{ runner.temp }}/candidate.json run: | set -euo pipefail + rm -f "$VERSION_RESPONSE" sha="$GITHUB_SHA" - tag="git-${sha:0:12}" - args=(workers versions create --worker "$TARGET_WORKER" --tag "$tag" --message "candidate $sha" --prebuilt) + digest_json="$(node release-artifact.mjs digest)" + config_digest="$(node -e 'let x="";process.stdin.on("data",d=>x+=d).on("end",()=>process.stdout.write(JSON.parse(x).config_digest))' <<< "$digest_json")" + build_digest="$(node -e 'let x="";process.stdin.on("data",d=>x+=d).on("end",()=>process.stdout.write(JSON.parse(x).build_digest))' <<< "$digest_json")" + preflight_digest="$(node -e 'let x="";process.stdin.on("data",d=>x+=d).on("end",()=>process.stdout.write(JSON.parse(x).preflight_digest))' <<< "$digest_json")" + provenance="$(node -e 'let x="";process.stdin.on("data",d=>x+=d).on("end",()=>{let j=JSON.parse(x);let c=require("node:crypto");process.stdout.write(c.createHash("sha256").update(JSON.stringify({worker:process.env.TARGET_WORKER,sourceSha:process.env.GITHUB_SHA,configDigest:j.config_digest,buildDigest:j.build_digest,preflightDigest:j.preflight_digest})).digest("hex"))})' <<< "$digest_json")" + args=(workers versions create --worker "$TARGET_WORKER" --tag "$sha" --message "provenance=$provenance" --prebuilt) if [[ "$TARGET_MODE" == bridge ]]; then args+=(--mode bridge); fi npx --no-install cf -q "${args[@]}" - npx --no-install cf -q workers versions list --worker-id "$TARGET_WORKER" > "$RUNNER_TEMP/versions.json" - python3 - "$RUNNER_TEMP/versions.json" "$tag" "$GITHUB_STEP_SUMMARY" <<'PY' - import json,sys - d=json.load(open(sys.argv[1])); versions=d if isinstance(d,list) else d.get('result', d.get('versions', [])) - if isinstance(versions,dict): versions=versions.get('items',[]) - found=[v for v in versions if v.get('annotations',{}).get('workers/tag')==sys.argv[2]] - if not found: raise SystemExit('Uploaded version with exact git tag not listed by Cloudflare') - found.sort(key=lambda v:v.get('metadata',{}).get('created_on',''),reverse=True) - version=found[0]['id'] - open(sys.argv[3],'a').write(f"Uploaded immutable version `{version}` for `{sys.argv[2]}`. It is not deployed.\n") - print(version) - PY - version="$(python3 -c 'import json,sys;d=json.load(open(sys.argv[1]));vs=d if isinstance(d,list) else d.get("result",d.get("versions",[]));vs=vs.get("items",[]) if isinstance(vs,dict) else vs;tag="git-"+sys.argv[2][:12];m=[v for v in vs if v.get("annotations",{}).get("workers/tag")==tag];m.sort(key=lambda v:v.get("metadata",{}).get("created_on",""),reverse=True);print(m[0]["id"])' "$RUNNER_TEMP/versions.json" "$GITHUB_SHA")" - curl --fail --silent --show-error --max-time 15 -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/workers/scripts/$TARGET_WORKER/versions?deployable=true" > "$RUNNER_TEMP/deployable.json" - python3 - "$RUNNER_TEMP/deployable.json" "$version" <<'PY' - import json,sys - d=json.load(open(sys.argv[1])); vs=d.get('result',[]); vs=vs.get('items',[]) if isinstance(vs,dict) else vs - if not d.get('success') or sys.argv[2] not in [v.get('id') for v in vs]: raise SystemExit('Uploaded version is not in deployable set') - PY - echo "Candidate version: $version" >> "$GITHUB_STEP_SUMMARY" - - name: Verify exact promotion candidate + npx --no-install cf -q workers versions list --worker-id "$TARGET_WORKER" > "$VERSION_LIST" + node release-artifact.mjs make-handoff "$VERSION_RESPONSE" "$VERSION_LIST" "$CANDIDATE_FILE" + echo "candidate_sha=$sha" >> "$GITHUB_OUTPUT" + - name: Preserve candidate artifact for fourteen days + if: inputs.action == 'upload' + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: private-bridge-candidate-${{ github.run_id }} + path: ${{ runner.temp }}/candidate.json + if-no-files-found: error + retention-days: 14 + - name: Verify artifact provenance, exact version and deployable set if: inputs.action == 'promote' + working-directory: pm-stack/private-laptop-bridge env: + CF_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }} CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }} CLOUDFLARE_API_TOKEN: ${{ secrets.CF_API_TOKEN }} - VERSION_ID: ${{ inputs.version_id }} TARGET_WORKER: ${{ steps.target.outputs.worker }} + TARGET_ENV: ${{ steps.target.outputs.environment }} + TARGET_MODE: ${{ steps.target.outputs.mode }} + CHECKED_OUT_SHA: ${{ steps.provenance.outputs.source_sha }} + HANDOFF: ${{ runner.temp }}/private-bridge-handoff/candidate.json + UPLOAD_RUN_JSON: ${{ runner.temp }}/upload-run.json + VERSION_LIST: ${{ runner.temp }}/cf-version-list.json + DEPLOYABLE_LIST: ${{ runner.temp }}/cf-deployable-list.json run: | set -euo pipefail - curl --fail --silent --show-error --max-time 15 -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/workers/scripts/$TARGET_WORKER/versions?deployable=true" > "$RUNNER_TEMP/deployable.json" - python3 - "$RUNNER_TEMP/deployable.json" "$VERSION_ID" <<'PY' - import json,sys - d=json.load(open(sys.argv[1])); vs=d.get('result',[]); vs=vs.get('items',[]) if isinstance(vs,dict) else vs - if not d.get('success') or sys.argv[2] not in [v.get('id') for v in vs]: raise SystemExit('Exact requested version is not deployable') - PY - - name: Promote exact immutable version to 100 percent + node release-artifact.mjs preflight + npx --no-install cf -q workers versions list --worker-id "$TARGET_WORKER" > "$VERSION_LIST" + curl --fail --silent --show-error --max-time 15 \ + -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \ + "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/workers/scripts/$TARGET_WORKER/versions?deployable=true" > "$DEPLOYABLE_LIST" + node release-artifact.mjs verify-handoff "$HANDOFF" "$UPLOAD_RUN_JSON" "$RUNNER_TEMP/upload-jobs.json" "$VERSION_LIST" "$DEPLOYABLE_LIST" + - name: Promote only the exact artifact version if: inputs.action == 'promote' working-directory: pm-stack/private-laptop-bridge env: CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }} CLOUDFLARE_API_TOKEN: ${{ secrets.CF_API_TOKEN }} - VERSION_ID: ${{ inputs.version_id }} TARGET_WORKER: ${{ steps.target.outputs.worker }} + HANDOFF: ${{ runner.temp }}/private-bridge-handoff/candidate.json + DEPLOYMENTS: ${{ runner.temp }}/cf-deployments.json run: | set -euo pipefail - npx --no-install cf -q workers deployments create --worker "$TARGET_WORKER" --strategy percentage --versions "[{\"version_id\":\"$VERSION_ID\",\"percentage\":100}]" - npx --no-install cf -q workers deployments list --worker "$TARGET_WORKER" > "$RUNNER_TEMP/deployments.json" - python3 - "$RUNNER_TEMP/deployments.json" "$VERSION_ID" "$GITHUB_STEP_SUMMARY" <<'PY' - import json,sys - d=json.load(open(sys.argv[1])); rows=d if isinstance(d,list) else d.get('result',d.get('deployments',[])); rows=rows.get('items',[]) if isinstance(rows,dict) else rows - matches=[x for x in rows if any(v.get('version_id')==sys.argv[2] and int(v.get('percentage',0))==100 for v in x.get('versions',[]))] - if not matches: raise SystemExit('Deployment read-back did not confirm exact version at 100 percent') - open(sys.argv[3],'a').write(f"Promoted `{sys.argv[2]}` and verified deployment read-back at 100%. Gateway and traffic policies remain unchanged.\n") - PY + version_id="$(node -e 'let h=require(process.env.HANDOFF);process.stdout.write(h.version_id)')" + npx --no-install cf -q workers deployments create --worker "$TARGET_WORKER" --strategy percentage --versions "[{\"version_id\":\"$version_id\",\"percentage\":100}]" + npx --no-install cf -q workers deployments list --worker "$TARGET_WORKER" > "$DEPLOYMENTS" + node release-artifact.mjs verify-deployment "$DEPLOYMENTS" "$HANDOFF" diff --git a/pm-stack/private-laptop-bridge/DISCOVERY.md b/pm-stack/private-laptop-bridge/DISCOVERY.md index b0305a0ad0..064ff1964a 100644 --- a/pm-stack/private-laptop-bridge/DISCOVERY.md +++ b/pm-stack/private-laptop-bridge/DISCOVERY.md @@ -177,23 +177,50 @@ must independently confirm full account ID/ownership and existence of the exact Worker named by that GitHub Environment, then verify the resulting token cannot read or edit another Worker. No target was probed in this work session. -If a Worker is absent, its first creation is a **separate owner-reviewed -bootstrap**, because Cloudflare requires Workers product-level Admin to create a -new Worker and per-Worker Editor cannot be granted until the Worker exists. A -candidate owner-operated bootstrap for the bridge is `cf deploy --mode bridge` -from this reviewed commit, using the selected Cloudflare owner/admin identity. -It creates and deploys the first version together, so require an explicit review -of the resolved Build Output and resources first: the Worker must be -`ENABLED=false`, have no routes/workers.dev/previews, and the only resource -creation must be the intended SQLite Durable Object class. Stop if `cf deploy` -shows any other binding/resource or if the account/target is not positively -identified. The smoke Worker requires its own reviewed first deployment. These -are documented commands/plans only; no bootstrap was run. Do not create or store -a Workers-product/whole-account token in GitHub. After bootstrap, provision the -account-owned **Individual Workers → Editor** token for that one exact existing -Worker. The smoke Worker and DO bridge have separate GitHub environments/tokens -so each credential names only one Worker. The bridge environment also cannot -modify Gateway policies; those use a separate approval and administrative path. +There is no permitted bootstrap path in this release workflow. The exact +`cf@1.0.0-rc.1` package is pinned in the lockfile and contains the +`@cloudflare/deploy-helpers@0.27.2` versions-upload checks. They reject a +missing Worker with “You cannot upload a new version of a Worker that does not +yet exist” before the Versions API upload. The Cloudflare Workers deployment +docs likewise state that the first upload must use a deploy command. This task +allows only an initial Versions upload, so do not substitute `cf deploy`, +Wrangler deploy, a direct API request, or a separate create workflow. The +existing-Worker precheck and the CLI both fail closed if either exact target is +absent. No bootstrap command was run or added. + +The real bridge has an additional Versions API constraint. Its Build Output +declares `PrivateLaptopBridge` as a new SQLite Durable Object export and binds +`BRIDGE` to that export. The pinned upload helper rejects pending Durable Object +migrations because Versions upload cannot apply them. It also handles +`ACTOR_BINDING_DEPENDS_ON_EXPORT_CODE` with the explicit explanation that +declarative exports are reconciled only when a version is deployed, so a +namespace for an unprovisioned export cannot exist at upload time. Therefore +the bridge can use this Versions-only release path only if an owner has already +verified that the exact existing `private-laptop-bridge-staging` Worker owns a +created SQLite `PrivateLaptopBridge` namespace and has completed the `v1` +migration, with no pending migration. The `BRIDGE` binding namespace ID must +match that same Worker namespace. The smoke Worker has no Durable Object and +still must already exist. + +`staging-preflight.json` is currently intentionally unverified and empty. CI +checks only validate a future owner-supplied read-only snapshot; the new contract +tests reject a missing Worker, mismatched namespace/class/Worker, an uncreated +export, a different migration tag, and pending migrations. An offline `cf +workers versions create --prebuilt --dry-run` does not exercise these remote +checks: the pinned helper skips API preflight on dry-run, and dry-run builds can +prove only the local Build Output. No live Worker, namespace, migration, route, +Gateway, or Cloudflare account was queried in this session. If the exact target +or completed namespace state is absent or cannot be proven, this workflow has +no allowed path forward; stop for Drew to decide whether the release scope +should change. + +Do not create or store a Workers-product/whole-account token in GitHub. If the +required targets and bridge namespace are already in place and independently +verified, routine CI uses separate account-owned **Individual Workers → Editor** +tokens, each restricted to one exact existing Worker. The smoke Worker and DO +bridge use separate GitHub environments/tokens. The bridge environment cannot +modify Gateway policies; those use a separate approval and administrative +path. Offline results on the current follow-up commit (recorded in the PR): Node 24.22.0 + cf 1.0.0-rc.1 + Wrangler 4.166.0; both smoke and `--mode bridge` pass `cf build` and the corresponding @@ -208,3 +235,5 @@ existence, deployment, Gateway routing or laptop readiness. Official references: [cf 1.0.0-rc.1 changelog](https://developers.cloudflare.com/changelog/post/2026-11-17-release-candidate/), [cf project builds and prebuilt uploads](https://developers.cloudflare.com/cf/projects/), and [Workers individual resource Editor permissions](https://developers.cloudflare.com/workers/authorization/workers/). + +Pinned implementation references: [cf 1.0.0-rc.1 package](https://www.npmjs.com/package/cf/v/1.0.0-rc.1), [its version-upload JSON shape](https://github.com/cloudflare/workers-sdk/blob/%40cloudflare/deploy-helpers%400.27.2/packages/deploy-helpers/src/deploy/versions-upload.ts#L98-L116), [output-file-only behavior](https://github.com/cloudflare/workers-sdk/blob/%40cloudflare/deploy-helpers%400.27.2/packages/workers-utils/src/output.ts#L7-L26), the [missing-Worker Versions guard](https://github.com/cloudflare/workers-sdk/blob/%40cloudflare/deploy-helpers%400.27.2/packages/deploy-helpers/src/deploy/helpers/validate-worker-props.ts#L290-L301), [dry-run API-check skip](https://github.com/cloudflare/workers-sdk/blob/%40cloudflare/deploy-helpers%400.27.2/packages/deploy-helpers/src/deploy/helpers/validate-worker-props.ts#L135-L159), [pending-migration rejection](https://github.com/cloudflare/workers-sdk/blob/%40cloudflare/deploy-helpers%400.27.2/packages/deploy-helpers/src/deploy/versions-upload.ts#L171-L193), and [unprovisioned DO export rejection](https://github.com/cloudflare/workers-sdk/blob/%40cloudflare/deploy-helpers%400.27.2/packages/deploy-helpers/src/deploy/versions-upload.ts#L378-L396). Cloudflare's [deployment management docs](https://developers.cloudflare.com/workers/versions-and-deployments/deployment-management/) separately specify first-upload and DO lifecycle constraints. diff --git a/pm-stack/private-laptop-bridge/VERIFICATION.md b/pm-stack/private-laptop-bridge/VERIFICATION.md index 866e33dbd8..2aa1abb240 100644 --- a/pm-stack/private-laptop-bridge/VERIFICATION.md +++ b/pm-stack/private-laptop-bridge/VERIFICATION.md @@ -127,3 +127,48 @@ vars; bundle was 17.84 KiB (5.31 KiB gzip). Smoke was 1.96 KiB (0.98 KiB gzip). Nine targeted tests passed (3 binding/release config, 3 Gateway RPC, 3 smoke). The workflow YAML and all embedded shell blocks passed local parsing. This is not evidence of target existence or a live Cloudflare deployment. + +## Versions-only release and bridge namespace preflight + +The lockfile pins `cf@1.0.0-rc.1`. Its installed package metadata records +`@cloudflare/deploy-helpers@0.27.2`, and its bundled Versions upload code +contains the missing-Worker rejection, the pending-DO-migration rejection, and +the API error handler for a binding to an export that has not yet been +provisioned. It states that declarative exports are reconciled when the version +is deployed. Cloudflare's [deployment management docs](https://developers.cloudflare.com/workers/versions-and-deployments/deployment-management/) +also require a deploy command for the first upload and for lifecycle-changing +DO exports/migrations. Current scope permits only Versions uploads, so the +workflow has no first-Worker bootstrap fallback and refuses absent Workers. + +The pinned `cf workers versions create` record is written to +`WRANGLER_OUTPUT_FILE_PATH`, not stdout; the workflow sets that path, clears it +first, and parses the single `version-upload` JSON record. The parser requires +`type: "version-upload"`, schema `version: 1`, the exact `worker_name`, and a +server-returned UUID `version_id`. Its `worker_tag` field is the stable Worker +identity, not the source commit. The workflow verifies the full source SHA and +provenance digest on that exact UUID's version annotations in the exact Worker +version list. + +The separate `Versions release proof` test accepts a synthetic snapshot only +when the bridge Worker already exists and its `BRIDGE` binding matches the same +Worker's created SQLite `PrivateLaptopBridge` namespace at completed migration +`v1`. It separately rejects absent Workers, namespace/class/Worker mismatches, +an uncreated export, a different migration tag, and pending migrations. The +smoke preflight requires its existing Worker but no DO. The tracked staging +proof remains `verified: false`; these tests validate the fail-closed gate and +do not assert live account state. + +After adding these tests, the focused local command +`node --test --test-reporter=spec release-contract.test.mjs deployment-config.test.mjs smoke.test.mjs gateway.test.mjs` +passed 19/19 under Node 24.22.0. Both `cf build` variants and both +`cf workers versions create --prebuilt --dry-run` variants were rerun; the +effective Build Output checks passed for the smoke and bridge targets. Dry-run +output confirms the bridge declares its `BRIDGE` Durable Object export and +disabled placeholders, but the pinned helper skips API checks during dry-run, +so this cannot validate missing-Worker or live namespace behavior. No upload, +deployment, promotion, account query, or secret use occurred. The local build +printed a proxy-environment warning; this should not be taken as proof of +network isolation. + +The workflow YAML parsed with PyYAML and all embedded `run:` blocks passed +`bash -n` after substituting GitHub expressions. `actionlint` was unavailable. diff --git a/pm-stack/private-laptop-bridge/cloudflare.config.ts b/pm-stack/private-laptop-bridge/cloudflare.config.ts index 8b1a740cc8..60bec39456 100644 --- a/pm-stack/private-laptop-bridge/cloudflare.config.ts +++ b/pm-stack/private-laptop-bridge/cloudflare.config.ts @@ -2,10 +2,20 @@ import {bindings, defineConfig, exports} from 'cf/config'; import * as smoke from './smoke.mjs' with {type:'cf-worker'}; import * as bridge from './gateway.mjs' with {type:'cf-worker'}; +const isolated = () => ({ + workersDev: false, + previewUrls: false, + domains: [], + triggers: [], + limits: {cpuMs: 10}, + observability: {enabled: false, logs: {enabled: false}, traces: {enabled: false}}, +}); + // Staging deployment target is the bounded, stateless network smoke only. // The live bridge remains disabled pending a separately reviewed config. export default defineConfig(({mode}) => mode === 'bridge' ? ({ worker: { + ...isolated(), name: 'private-laptop-bridge-staging', compatibilityDate: '2026-07-30', entrypoint: bridge, @@ -21,6 +31,7 @@ export default defineConfig(({mode}) => mode === 'bridge' ? ({ }, }) : ({ worker: { + ...isolated(), name: 'private-laptop-bridge-smoke', compatibilityDate: '2026-07-30', entrypoint: smoke, diff --git a/pm-stack/private-laptop-bridge/release-artifact.mjs b/pm-stack/private-laptop-bridge/release-artifact.mjs new file mode 100644 index 0000000000..cd1e3aa215 --- /dev/null +++ b/pm-stack/private-laptop-bridge/release-artifact.mjs @@ -0,0 +1,71 @@ +#!/usr/bin/env node +import {readFile,writeFile} from 'node:fs/promises'; +import {resolve} from 'node:path'; +import {assertDeployable,assertDryRunPayload,assertEffectivePayload,assertExactVersion,assertLatestServing,assertPreflight,assertUploadRun,assertVersionStillMatches,digestFiles,digestTree,makeHandoff,provenanceDigest} from './release-contract.mjs'; +const [action,...args]=process.argv.slice(2); +const required=(name)=>{const value=process.env[name];if(!value)throw new Error(`missing ${name}`);return value;}; +const json=async path=>JSON.parse(await readFile(path,'utf8')); +const write=(path,value)=>writeFile(path,JSON.stringify(value,null,2)+'\n',{mode:0o600}); +const root=process.cwd(); + +if(action==='preflight') { + const worker=required('TARGET_WORKER'), environment=required('TARGET_ENV'), accountId=required('CF_ACCOUNT_ID'); + const proof=await json(resolve(root,'staging-preflight.json')); + assertPreflight(proof,{accountId,worker,environment}); + console.log('owner read-only staging proof valid for '+worker); +} else if(action==='digest') { + const config_digest=await digestFiles(root), preflight_digest=await digestFiles(root,['staging-preflight.json']), build_digest=await digestTree(resolve(root,'.cloudflare/output/v1')); + console.log(JSON.stringify({config_digest,preflight_digest,build_digest})); +} else if(action==='dry-run') { + const worker=required('TARGET_WORKER'), mode=required('TARGET_MODE'); + assertDryRunPayload(await readFile(required('DRY_RUN_OUTPUT'),'utf8'),{worker,mode}); + const metadata=await json(resolve(root,'.cloudflare/output/v1/config.json')); + if(metadata.producer?.name!=='wrangler'||metadata.producer?.version!=='4.166.0'||metadata.buildContext?.mode!==(mode==='bridge'?'bridge':undefined)) throw new Error('Build Output producer or mode does not match pinned release'); + const payload=await json(resolve(root,'.cloudflare/output/v1/workers/default/worker.config.json')); + assertEffectivePayload(payload,{worker,mode}); + console.log('effective Build Output validated for '+worker); +} else if(action==='make-handoff') { + const [responsePath,versionsPath,outputPath]=args; + if(!responsePath||!versionsPath||!outputPath) throw new Error('usage: make-handoff '); + const source_sha=required('GITHUB_SHA'), worker=required('TARGET_WORKER'), environment=required('TARGET_ENV'), account_id=required('CF_ACCOUNT_ID'), mode=required('TARGET_MODE'); + const config_digest=await digestFiles(root), preflight_digest=await digestFiles(root,['staging-preflight.json']), build_digest=await digestTree(resolve(root,'.cloudflare/output/v1')); + const stdout=await readFile(responsePath,'utf8'), versionsJson=await readFile(versionsPath,'utf8'), tag=source_sha; + const version_id=assertExactVersion({stdout,versionsJson,worker,sourceSha:source_sha,configDigest:config_digest,buildDigest:build_digest,preflightDigest:preflight_digest}); + const artifact=makeHandoff({repository:required('GITHUB_REPOSITORY'),workflow:'.github/workflows/private-laptop-bridge-release.yml',upload_run_id:required('GITHUB_RUN_ID'),upload_run_attempt:Number(required('GITHUB_RUN_ATTEMPT')),source_sha,worker,environment,account_id,mode,version_id,tag,config_digest,build_digest,preflight_digest,provenance_digest:provenanceDigest({worker,sourceSha:source_sha,configDigest:config_digest,buildDigest:build_digest,preflightDigest:preflight_digest}),expected_disabled:true}); + await write(outputPath,artifact); console.log(version_id); +} else if(action==='provenance') { + const [handoffPath,runPath]=args; + const [,,jobsPath]=args; + if(!handoffPath||!runPath||!jobsPath) throw new Error('usage: provenance '); + const artifact=await json(handoffPath),run=await json(runPath),jobs=await json(jobsPath),worker=required('TARGET_WORKER'),environment=required('TARGET_ENV'),account=required('CF_ACCOUNT_ID'),mode=required('TARGET_MODE'); + const expectedMode=worker==='private-laptop-bridge-staging'?'bridge':worker==='private-laptop-bridge-smoke'?'default':null; + if(!expectedMode||artifact.worker!==worker||artifact.environment!==environment||artifact.account_id!==account||artifact.mode!==expectedMode||mode!==expectedMode) throw new Error('upload artifact target/environment/account/mode mismatch'); + assertUploadRun(run,jobs,artifact); console.log(artifact.source_sha); +} else if(action==='current-proof') { + const [handoffPath]=args; if(!handoffPath) throw new Error('usage: current-proof '); + const artifact=await json(handoffPath),account=required('CF_ACCOUNT_ID'),worker=required('TARGET_WORKER'),environment=required('TARGET_ENV'); + if(artifact.account_id!==account||artifact.worker!==worker||artifact.environment!==environment) throw new Error('current owner proof target differs from upload artifact'); + const proof=await json(resolve(root,'staging-preflight.json')); assertPreflight(proof,{accountId:account,worker,environment}); + const preflight_digest=await digestFiles(root,['staging-preflight.json']); + if(preflight_digest!==artifact.preflight_digest) throw new Error('current main owner proof changed since upload; upload a new candidate'); + console.log('current main owner proof matches uploaded candidate'); +} else if(action==='verify-handoff') { + const [handoffPath,runPath,jobsPath,versionsPath,deployablePath]=args; + if(!handoffPath||!runPath||!jobsPath||!versionsPath||!deployablePath) throw new Error('usage: verify-handoff '); + const artifact=await json(handoffPath), run=await json(runPath),jobs=await json(jobsPath), target=required('TARGET_WORKER'), account=required('CF_ACCOUNT_ID'), env=required('TARGET_ENV'), mode=required('TARGET_MODE'); + const expectedMode=target==='private-laptop-bridge-staging'?'bridge':'default'; + if(artifact.worker!==target||artifact.account_id!==account||artifact.environment!==env||artifact.mode!==expectedMode||mode!==expectedMode) throw new Error('promotion target/environment/account/mode differs from handoff'); + assertUploadRun(run,jobs,artifact); + const proof=await json(resolve(root,'staging-preflight.json')); assertPreflight(proof,{accountId:account,worker:target,environment:env}); + const config_digest=await digestFiles(root),preflight_digest=await digestFiles(root,['staging-preflight.json']),build_digest=await digestTree(resolve(root,'.cloudflare/output/v1')); + const head=required('CHECKED_OUT_SHA'); + if(head!==artifact.source_sha||config_digest!==artifact.config_digest||preflight_digest!==artifact.preflight_digest||build_digest!==artifact.build_digest) throw new Error('checked-out source/config/build/preflight digest does not equal uploaded artifact'); + assertVersionStillMatches(await readFile(versionsPath,'utf8'),artifact); + assertDeployable(await readFile(deployablePath,'utf8'),artifact.version_id); + console.log(`verified ${artifact.version_id} from run ${artifact.upload_run_id} at ${artifact.source_sha}`); +} else if(action==='verify-deployment') { + const [deploymentPath,handoffPath]=args; + if(!deploymentPath||!handoffPath) throw new Error('usage: verify-deployment '); + const artifact=await json(handoffPath);assertLatestServing(await readFile(deploymentPath,'utf8'),artifact.version_id); + console.log(`latest deployment is exactly ${artifact.version_id} at 100%`); +} else throw new Error('action must be preflight, digest, dry-run, make-handoff, provenance, verify-handoff, or verify-deployment'); diff --git a/pm-stack/private-laptop-bridge/release-contract.mjs b/pm-stack/private-laptop-bridge/release-contract.mjs new file mode 100644 index 0000000000..aae8178753 --- /dev/null +++ b/pm-stack/private-laptop-bridge/release-contract.mjs @@ -0,0 +1,201 @@ +import {createHash} from 'node:crypto'; +import {lstat, readFile, readdir} from 'node:fs/promises'; +import {join, relative, resolve, sep} from 'node:path'; + +const UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; +const SHA=/^[0-9a-f]{40}$/; +const DIGEST=/^[0-9a-f]{64}$/; +const NAMESPACE=/^(?:[0-9a-f]{32}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/; +const WORKFLOW='.github/workflows/private-laptop-bridge-release.yml'; +export const releaseConfigFiles=['cloudflare.config.ts','wrangler.jsonc','wrangler.staging.jsonc','wrangler.smoke.jsonc','package.json','package-lock.json','staging-preflight.json']; +const fail=(message)=>{throw new Error(message);}; +const digest=(bytes)=>createHash('sha256').update(bytes).digest('hex'); +const stable=(value)=>Array.isArray(value)?value.map(stable):value&&typeof value==='object'?Object.fromEntries(Object.keys(value).sort().map(key=>[key,stable(value[key])])):value; +const same=(a,b)=>JSON.stringify(stable(a))===JSON.stringify(stable(b)); + +export function extractServerVersionId(stdout,{worker}={}) { + let value; try {value=JSON.parse(stdout);} catch {fail('cf versions create did not return JSON; refusing to infer a version id');} + if(value?.type!=='version-upload'||value?.version!==1||value?.worker_name!==worker) fail('cf versions create response does not match the pinned version-upload schema and exact Worker'); + const id=value?.version_id; + if(typeof id!=='string'||!UUID.test(id)) fail('cf versions create response has no exact version UUID'); + return id; +} + +export function provenanceDigest({worker,sourceSha,configDigest,buildDigest,preflightDigest}) { + if(typeof worker!=='string'||!SHA.test(sourceSha)||!DIGEST.test(configDigest)||!DIGEST.test(buildDigest)||!DIGEST.test(preflightDigest)) fail('invalid provenance digest inputs'); + return digest(JSON.stringify({worker,sourceSha,configDigest,buildDigest,preflightDigest})); +} + +export async function digestFiles(root, files=releaseConfigFiles) { + const entries=[]; + for(const name of [...files].sort()) { + if(name.startsWith('/')||name.split(/[\\/]/).includes('..')) fail('digest path escapes project'); + const path=join(root,name), stat=await lstat(path); + if(!stat.isFile()||stat.isSymbolicLink()) fail(`digest input is not a regular file: ${name}`); + entries.push([name,digest(await readFile(path))]); + } + return digest(JSON.stringify(entries)); +} + +export async function digestTree(root) { + const abs=resolve(root), entries=[]; + async function walk(dir) { + for(const item of (await readdir(dir,{withFileTypes:true})).sort((a,b)=>a.name.localeCompare(b.name))) { + const path=join(dir,item.name), st=await lstat(path); + if(st.isSymbolicLink()) fail(`Build Output contains symlink: ${relative(abs,path)}`); + if(st.isDirectory()) await walk(path); + else if(st.isFile()) entries.push([relative(abs,path).split(sep).join('/'),digest(await readFile(path))]); + else fail(`Build Output contains unsupported entry: ${relative(abs,path)}`); + } + } + await walk(abs); if(!entries.length) fail('Build Output is empty'); + return digest(JSON.stringify(entries)); +} + +function parseItems(text,key) { + let body; try {body=JSON.parse(text);} catch {fail(`${key} response is not JSON`);} + if(body?.success===false) fail(`${key} API returned success=false`); + let rows=Array.isArray(body)?body:body?.result; + if(!Array.isArray(rows)) rows=rows?.items ?? body?.[key]; + if(!Array.isArray(rows)) fail(`${key} response contains no result list`); + return rows; +} + +export function assertExactVersion({stdout,versionsJson,worker,sourceSha,configDigest,buildDigest,preflightDigest}) { + if(!SHA.test(sourceSha)||!DIGEST.test(configDigest)||!DIGEST.test(buildDigest)||!DIGEST.test(preflightDigest)) fail('invalid source/config/build digest'); + const id=extractServerVersionId(stdout,{worker}); + const matches=parseItems(versionsJson,'versions').filter(v=>v.id===id); + if(matches.length!==1) fail('server-returned version UUID is absent or ambiguous in the exact Worker version list'); + const version=matches[0], expectedTag=sourceSha, expectedProof=provenanceDigest({worker,sourceSha,configDigest,buildDigest,preflightDigest}); + const tag=version.annotations?.['workers/tag']; + const message=version.annotations?.['workers/message']; + if(tag!==expectedTag) fail('exact version metadata tag does not bind the full source SHA'); + if(typeof message!=='string'||!message.includes(`provenance=${expectedProof}`)) fail('exact version metadata message does not bind the full source/config/build/preflight provenance digest'); + return id; +} + +const HANDOFF_KEYS=['schema','action','repository','workflow','upload_run_id','upload_run_attempt','source_sha','worker','environment','account_id','mode','version_id','tag','config_digest','build_digest','preflight_digest','provenance_digest','expected_disabled']; +export function makeHandoff(fields) { + const handoff={schema:1,action:'upload',...fields}; + validateHandoffShape(handoff); return Object.fromEntries(HANDOFF_KEYS.map(k=>[k,handoff[k]])); +} +function validateHandoffShape(h) { + if(!h||typeof h!=='object'||Array.isArray(h)||Object.keys(h).sort().join(',')!==[...HANDOFF_KEYS].sort().join(',')) fail('handoff fields are missing or unexpected'); + if(h.schema!==1||h.action!=='upload'||h.workflow!==WORKFLOW||!/^\d+$/.test(String(h.upload_run_id))||!Number.isInteger(h.upload_run_attempt)||h.upload_run_attempt<1||!SHA.test(h.source_sha)||!UUID.test(h.version_id)||!DIGEST.test(h.config_digest)||!DIGEST.test(h.build_digest)||!DIGEST.test(h.preflight_digest)||!DIGEST.test(h.provenance_digest)||h.provenance_digest!==provenanceDigest({worker:h.worker,sourceSha:h.source_sha,configDigest:h.config_digest,buildDigest:h.build_digest,preflightDigest:h.preflight_digest})||h.expected_disabled!==true) fail('handoff has invalid provenance or digest fields'); + if(h.repository!=='developing-today/code') fail('handoff repository mismatch'); + const target=h.worker==='private-laptop-bridge-staging'?'cloudflare-staging':h.worker==='private-laptop-bridge-smoke'?'cloudflare-staging-smoke':null; + if(!target||h.environment!==target) fail('handoff Worker/environment mismatch'); + const mode=h.worker==='private-laptop-bridge-staging'?'bridge':'default'; + if(h.mode!==mode||h.tag!==h.source_sha||! /^[0-9a-f]{32}$/.test(h.account_id)) fail('handoff target/account/source mismatch'); +} + +export function verifyPromotionProvenance(handoff, expected) { + validateHandoffShape(handoff); + for(const key of ['repository','workflow','upload_run_id','upload_run_attempt','source_sha','worker','environment','account_id','mode','version_id','config_digest','build_digest','preflight_digest','provenance_digest']) { + if(handoff[key]!==expected[key]) fail(`promotion provenance mismatch: ${key}`); + } + if(expected.action!=='upload'||expected.event!=='workflow_dispatch'||expected.branch!=='main'||expected.status!=='completed'||expected.conclusion!=='success'||expected.workflow_path!==WORKFLOW||expected.head_sha!==handoff.source_sha||expected.run_attempt!==handoff.upload_run_attempt||expected.repository!==handoff.repository) fail('upload run is not a successful trusted main-branch upload run'); + return true; +} + +export function assertVersionStillMatches(versionsJson,handoff) { + const rows=parseItems(versionsJson,'versions').filter(v=>v.id===handoff.version_id); + if(rows.length!==1) fail('handoff version is not uniquely present on the exact Worker'); + const v=rows[0]; + if(v.annotations?.['workers/tag']!==handoff.tag) fail('Cloudflare version source tag differs from handoff'); + const m=v.annotations?.['workers/message']??''; + if(!m.includes(`provenance=${handoff.provenance_digest}`)) fail('Cloudflare version digest metadata differs from handoff'); + return true; +} + +export function assertDeployable(deployableJson,versionId) { + if(!UUID.test(versionId)) fail('invalid target version UUID'); + if(!parseItems(deployableJson,'deployable versions').some(v=>v.id===versionId)) fail('exact handoff version is not deployable'); + return true; +} + +export function assertLatestServing(deploymentsJson,versionId) { + const rows=parseItems(deploymentsJson,'deployments'); + const dated=rows.map(row=>({row,at:Date.parse(row.created_on??row.created_at??'')})); + if(dated.some(x=>!Number.isFinite(x.at))) fail('deployment listing contains an invalid timestamp'); + const latestAt=Math.max(...dated.map(x=>x.at)); + const latest=dated.filter(x=>x.at===latestAt); + if(latest.length!==1) fail('latest deployment is ambiguous'); + const traffic=latest[0].row.versions; + if(!Array.isArray(traffic)||traffic.length!==1||traffic[0].version_id!==versionId||traffic[0].percentage!==100) fail('latest deployment is not the exact complete 100% version set'); + return true; +} + +export function assertUploadRun(run,jobsResponse,handoff) { + if(!run||run.id!==Number(handoff.upload_run_id)||run.run_attempt!==handoff.upload_run_attempt||run.status!=='completed'||run.conclusion!=='success'||run.event!=='workflow_dispatch'||run.head_branch!=='main'||run.head_sha!==handoff.source_sha||run.path?.split('@')[0]!==WORKFLOW||run.repository?.full_name!==handoff.repository) fail('upload run is not the exact successful trusted main-branch workflow run'); + let jobs; try {jobs=typeof jobsResponse==='string'?JSON.parse(jobsResponse):jobsResponse;} catch {fail('upload workflow job details are not JSON');} + const rows=jobs?.jobs; + if(!Array.isArray(rows)||jobs.total_count!==1||rows.length!==1) fail('upload run must contain exactly one workflow job'); + const job=rows[0]; + if(job.name!=='release'||job.run_id!==run.id||job.head_sha!==handoff.source_sha||job.status!=='completed'||job.conclusion!=='success'||!Array.isArray(job.steps)) fail('upload workflow job is not the exact successful source job'); + const steps=new Map(job.steps.map(step=>[step.name,step])); + for(const name of ['Upload an immutable candidate and write exact provenance artifact','Preserve candidate artifact for fourteen days']) { + const step=steps.get(name); if(step?.status!=='completed'||step?.conclusion!=='success') fail(`trusted upload run did not complete the required artifact step: ${name}`); + } + for(const name of ['Verify artifact provenance, exact version and deployable set','Promote only the exact artifact version']) { + const step=steps.get(name); if(step?.status!=='completed'||step?.conclusion!=='skipped') fail(`candidate run unexpectedly executed a promotion step: ${name}`); + } + return true; +} + +export function assertPreflight(proof,{accountId,worker,environment,now=Date.now()}) { + if(!proof||proof.schema!==1||proof.verified!==true||proof.account_id!==accountId||!proof.reviewed_by||!proof.reviewed_by.includes('@')||typeof proof.evidence_ref!=='string'||proof.evidence_ref.trim().length<3||!Number.isFinite(Date.parse(proof.verified_at))||!Number.isFinite(Date.parse(proof.expires_at))||Date.parse(proof.verified_at)>now||Date.parse(proof.expires_at)<=now||Date.parse(proof.expires_at)-Date.parse(proof.verified_at)>24*3600000) fail('owner read-only staging proof is absent, expired, or invalid'); + const release=proof.release_policy,allowedRefs=release?.allowed_environment_branches?.[environment]; + if(release?.repository!=='developing-today/code'||release?.branch!=='main'||release?.branch_protected!==true||release?.required_pull_request_reviews!==true||release?.force_push_disabled!==true||release?.admin_bypass_disabled!==true||release?.environment_reviewers_required?.[environment]!==true||release?.self_review_disabled?.[environment]!==true||!Array.isArray(allowedRefs)||!same(allowedRefs,['main'])||typeof release?.evidence_ref!=='string'||release.evidence_ref.trim().length<3) fail('trusted protected-main or deployment-environment approval proof is absent or invalid'); + const target=proof.targets?.[worker]; + const expectedVars=worker==='private-laptop-bridge-staging'?{ENABLED:'false',GATEWAY_HOST:'private-bridge-staging.invalid',GATEWAY_ACCOUNT_ID:'',GATEWAY_POLICY_ID:'',GATEWAY_IDENTITY_EMAIL:'',GATEWAY_POSTURE_ID:'',BRIDGE_REGISTRY:''}:{ENABLED:'false',GATEWAY_HOST:'private-bridge-smoke.invalid',GATEWAY_ACCOUNT_ID:'',GATEWAY_POLICY_ID:'',START_MS:'',END_MS:''}; + if(!target||target.environment!==environment||target.exists!==true||target.script_id!==worker||target.account_id!==accountId||target.workers_dev!==false||target.preview_urls!==false||!Array.isArray(target.routes)||target.routes.length!==0||!Array.isArray(target.custom_domains)||target.custom_domains.length!==0||target.application_enabled!==false||target.observability?.enabled!==false||target.observability?.logs!==false||target.observability?.traces!==false||target.limits?.cpu_ms!==10||!Array.isArray(target.gateway_forward_policy_ids)||target.gateway_forward_policy_ids.length!==0||!Array.isArray(target.gateway_caller_ids)||target.gateway_caller_ids.length!==0||JSON.stringify(Object.fromEntries(Object.entries(target.variables??{}).sort()))!==JSON.stringify(Object.fromEntries(Object.entries(expectedVars).sort()))||!Array.isArray(target.bindings)) fail('owner read-only proof does not verify the exact private disabled target'); + if(worker==='private-laptop-bridge-staging'&&(target.bindings.length!==1||target.bindings[0]?.name!=='BRIDGE'||target.bindings[0]?.type!=='durable_object_namespace'||target.bindings[0]?.class_name!=='PrivateLaptopBridge'||target.bindings[0]?.namespace_id!==target.do?.namespace_id||target.do?.worker_name!==worker||target.do?.class_name!=='PrivateLaptopBridge'||target.do?.storage!=='sqlite'||target.do?.export_state!=='created'||target.do?.migration_tag!=='v1'||target.do?.pending_migrations!==false||!NAMESPACE.test(target.do?.namespace_id??''))) fail('owner read-only proof does not verify the same-Worker SQLite Durable Object namespace and completed v1 migration state'); + if(worker==='private-laptop-bridge-smoke'&&(target.bindings.length!==0||target.do!==null)) fail('smoke target unexpectedly has a Durable Object namespace or binding'); + return true; +} + +export function assertDryRunPayload(text,{worker,mode}) { + if(typeof text!=='string'||!text.includes('--dry-run: exiting now.')) fail('cf prebuilt dry-run did not complete successfully'); + if(worker==='private-laptop-bridge-staging') { + if(mode!=='bridge'||!text.includes('env.BRIDGE (PrivateLaptopBridge')||!text.includes('env.ENABLED ("false")')||!text.includes('env.BRIDGE_REGISTRY ("")')) fail('effective bridge Build Output does not match disabled DO target'); + } else if(worker==='private-laptop-bridge-smoke') { + if(mode!=='default'||!text.includes('env.ENABLED ("false")')||!text.includes('env.GATEWAY_HOST ("private-bridge-smoke.invalid")')) fail('effective smoke Build Output does not match disabled target'); + } else fail('unknown Worker in Build Output verification'); + return true; +} + +export function assertEffectivePayload(config,{worker,mode}) { + const bridge=worker==='private-laptop-bridge-staging'; + const smoke=worker==='private-laptop-bridge-smoke'; + if((!bridge&&!smoke)||(bridge&&mode!=='bridge')||(smoke&&mode!=='default')) fail('Build Output mode does not match the fixed target'); + const common={ + name:worker, + compatibilityDate:'2026-07-30', + domains:[], + triggers:[], + limits:{cpuMs:10}, + observability:{enabled:false,logs:{enabled:false},traces:{enabled:false}}, + workersDev:false, + previewUrls:false, + }; + const variables=bridge?{ + ENABLED:'false',GATEWAY_HOST:'private-bridge-staging.invalid',GATEWAY_ACCOUNT_ID:'',GATEWAY_POLICY_ID:'', + GATEWAY_IDENTITY_EMAIL:'',GATEWAY_POSTURE_ID:'',BRIDGE_REGISTRY:'', + }:{ + ENABLED:'false',GATEWAY_HOST:'private-bridge-smoke.invalid',GATEWAY_ACCOUNT_ID:'',GATEWAY_POLICY_ID:'',START_MS:'',END_MS:'', + }; + const expectedEnv=Object.fromEntries(Object.entries(variables).map(([name,value])=>[name,{type:'text',value}])); + const allowedKeys=bridge + ?['name','compatibilityDate','domains','triggers','limits','observability','workersDev','previewUrls','env','exports','manifest'] + :['name','compatibilityDate','domains','triggers','limits','observability','workersDev','previewUrls','env','manifest']; + if(!config||typeof config!=='object'||Array.isArray(config)||Object.keys(config).sort().join(',')!==[...allowedKeys].sort().join(',')) fail('Build Output contains unexpected Worker settings or resources'); + for(const [key,value] of Object.entries(common)) if(!same(config[key],value)) fail(`effective Worker setting differs from the private target: ${key}`); + if(!same(config.env,{...expectedEnv,...(bridge?{BRIDGE:{type:'durable-object',worker:'private-laptop-bridge-staging',exportName:'PrivateLaptopBridge'}}:{})})) fail('effective Worker variables or bindings differ from the fixed disabled target'); + if(config.manifest?.type!=='complete'||config.manifest?.mainModule!==(bridge?'gateway.js':'smoke.js')||!config.manifest.modules||typeof config.manifest.modules!=='object') fail('effective Worker module manifest is incomplete or targets the wrong entrypoint'); + const modules=Object.keys(config.manifest.modules).sort(); + const expectedModules=bridge?['gateway.js','gateway.js.map']:['smoke.js','smoke.js.map']; + if(!same(modules,expectedModules)) fail('effective Worker module set differs from the reviewed entrypoint'); + if(bridge&&!same(config.exports,{PrivateLaptopBridge:{type:'durable-object',storage:'sqlite'}})) fail('effective bridge DO class or SQLite storage differs from the reviewed target'); + return true; +} diff --git a/pm-stack/private-laptop-bridge/release-contract.test.mjs b/pm-stack/private-laptop-bridge/release-contract.test.mjs new file mode 100644 index 0000000000..f8f5f4609c --- /dev/null +++ b/pm-stack/private-laptop-bridge/release-contract.test.mjs @@ -0,0 +1,125 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {assertDeployable,assertDryRunPayload,assertEffectivePayload,assertExactVersion,assertLatestServing,assertPreflight,assertUploadRun,assertVersionStillMatches,makeHandoff,provenanceDigest,verifyPromotionProvenance} from './release-contract.mjs'; + +const uuid='01234567-89ab-cdef-0123-456789abcdef', old='11111111-2222-3333-4444-555555555555'; +const sha='a'.repeat(40), cd='b'.repeat(64), bd='c'.repeat(64), pd='e'.repeat(64), acct='d'.repeat(32); +const proof=provenanceDigest({worker:'private-laptop-bridge-staging',sourceSha:sha,configDigest:cd,buildDigest:bd,preflightDigest:pd}); +const version={id:uuid,annotations:{'workers/tag':sha,'workers/message':`release provenance=${proof}`}}; +const list=rows=>JSON.stringify({success:true,result:{items:rows}}); +const cfVersionResponse=(fields={})=>JSON.stringify({type:'version-upload',version:1,worker_name:'private-laptop-bridge-staging',worker_tag:'worker-identity-guid',version_id:uuid,timestamp:'2026-11-22T12:00:00.000Z',...fields}); +const env={CF_ACCOUNT_ID:acct}; +const handoff=()=>makeHandoff({repository:'developing-today/code',workflow:'.github/workflows/private-laptop-bridge-release.yml',upload_run_id:'501',upload_run_attempt:1,source_sha:sha,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',account_id:acct,mode:'bridge',version_id:uuid,tag:sha,config_digest:cd,build_digest:bd,preflight_digest:pd,provenance_digest:proof,expected_disabled:true}); + +test('captures the exact UUID returned by cf and refuses tag-list aliasing',()=>{ + assert.equal(assertExactVersion({stdout:cfVersionResponse(),versionsJson:list([version,{...version,id:old}]),worker:'private-laptop-bridge-staging',sourceSha:sha,configDigest:cd,buildDigest:bd,preflightDigest:pd}),uuid); + assert.throws(()=>assertExactVersion({stdout:'uploaded successfully',versionsJson:list([version]),worker:'private-laptop-bridge-staging',sourceSha:sha,configDigest:cd,buildDigest:bd,preflightDigest:pd}),/did not return JSON/); + assert.throws(()=>assertExactVersion({stdout:cfVersionResponse(),versionsJson:list([{...version,id:old}]),worker:'private-laptop-bridge-staging',sourceSha:sha,configDigest:cd,buildDigest:bd,preflightDigest:pd}),/absent or ambiguous/); + assert.throws(()=>assertExactVersion({stdout:cfVersionResponse({version_id:'not-a-uuid'}),versionsJson:list([version]),worker:'private-laptop-bridge-staging',sourceSha:sha,configDigest:cd,buildDigest:bd,preflightDigest:pd}),/no exact version UUID/); + assert.throws(()=>assertExactVersion({stdout:cfVersionResponse({version_id:null}),versionsJson:list([version]),worker:'private-laptop-bridge-staging',sourceSha:sha,configDigest:cd,buildDigest:bd,preflightDigest:pd}),/no exact version UUID/); + assert.throws(()=>assertExactVersion({stdout:cfVersionResponse({worker_name:'private-laptop-bridge-smoke'}),versionsJson:list([version]),worker:'private-laptop-bridge-staging',sourceSha:sha,configDigest:cd,buildDigest:bd,preflightDigest:pd}),/does not match the pinned version-upload schema/); + assert.throws(()=>assertExactVersion({stdout:cfVersionResponse({version:2}),versionsJson:list([version]),worker:'private-laptop-bridge-staging',sourceSha:sha,configDigest:cd,buildDigest:bd,preflightDigest:pd}),/does not match the pinned version-upload schema/); + assert.throws(()=>assertExactVersion({stdout:JSON.stringify({success:true,result:version}),versionsJson:list([version]),worker:'private-laptop-bridge-staging',sourceSha:sha,configDigest:cd,buildDigest:bd,preflightDigest:pd}),/does not match the pinned version-upload schema/); +}); + +test('exact version must bind full SHA, exact config and actual Build Output digest',()=>{ + for(const v of [{...version,annotations:{...version.annotations,'workers/tag':sha.slice(0,12)}},{...version,annotations:{...version.annotations,'workers/message':`release provenance=${'e'.repeat(64)}`}},{...version,annotations:{...version.annotations,'workers/message':`release provenance=${'e'.repeat(64)}`}}]) assert.throws(()=>assertExactVersion({stdout:cfVersionResponse(),versionsJson:list([v]),worker:'private-laptop-bridge-staging',sourceSha:sha,configDigest:cd,buildDigest:bd,preflightDigest:pd})); +}); + +test('promotion handoff binds exact source, Worker, environment, account, upload run and attempt',()=>{ + const h=handoff(); + const base={repository:'developing-today/code',workflow:'.github/workflows/private-laptop-bridge-release.yml',upload_run_id:'501',upload_run_attempt:1,source_sha:sha,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',account_id:acct,mode:'bridge',version_id:uuid,config_digest:cd,build_digest:bd,preflight_digest:pd,provenance_digest:proof,action:'upload',event:'workflow_dispatch',branch:'main',status:'completed',conclusion:'success',workflow_path:'.github/workflows/private-laptop-bridge-release.yml',head_sha:sha,run_attempt:1}; + assert.equal(verifyPromotionProvenance(h,base),true); + for(const [key,value] of [['upload_run_id','502'],['worker','private-laptop-bridge-smoke'],['environment','cloudflare-staging-smoke'],['account_id','e'.repeat(32)],['config_digest','f'.repeat(64)],['build_digest','f'.repeat(64)],['preflight_digest','f'.repeat(64)],['provenance_digest','f'.repeat(64)],['upload_run_attempt',2],['event','pull_request'],['branch','feature'],['status','in_progress'],['conclusion','failure'],['head_sha','f'.repeat(40)],['workflow_path','other.yml']]) assert.throws(()=>verifyPromotionProvenance(h,{...base,[key]:value}),undefined,key); + const bad={...h,expected_disabled:false}; assert.throws(()=>verifyPromotionProvenance(bad,base),/invalid provenance/); +}); + +test('exact version is revalidated against Cloudflare metadata and deployable IDs',()=>{ + const h=handoff(); assert.equal(assertVersionStillMatches(list([version]),h),true); assert.equal(assertDeployable(list([{id:uuid}]),uuid),true); + assert.throws(()=>assertVersionStillMatches(list([{...version,annotations:{...version.annotations,'workers/tag':'git-short'}}]),h)); + assert.throws(()=>assertDeployable(list([{id:old}]),uuid)); +}); + +test('trusted workflow run must be exact successful main upload attempt',()=>{ + const h=handoff(); + const run={id:501,run_attempt:1,status:'completed',conclusion:'success',event:'workflow_dispatch',head_branch:'main',head_sha:sha,path:'.github/workflows/private-laptop-bridge-release.yml@refs/heads/main',repository:{full_name:'developing-today/code'}}; + const jobs={total_count:1,jobs:[{run_id:501,head_sha:sha,name:'release',status:'completed',conclusion:'success',steps:[ + {name:'Upload an immutable candidate and write exact provenance artifact',status:'completed',conclusion:'success'}, + {name:'Preserve candidate artifact for fourteen days',status:'completed',conclusion:'success'}, + {name:'Verify artifact provenance, exact version and deployable set',status:'completed',conclusion:'skipped'}, + {name:'Promote only the exact artifact version',status:'completed',conclusion:'skipped'}, + ]}]}; + assert.equal(assertUploadRun(run,jobs,h),true); + for(const change of [{id:502},{run_attempt:2},{status:'in_progress'},{conclusion:'failure'},{event:'pull_request'},{head_branch:'feature'},{head_sha:'f'.repeat(40)},{repository:{full_name:'fork/evil'}}]) assert.throws(()=>assertUploadRun({...run,...change},h)); + assert.throws(()=>assertUploadRun(run,{...jobs,total_count:2},h),/exactly one workflow job/); + for(const change of [ + {name:'Upload an immutable candidate and write exact provenance artifact',conclusion:'failure'}, + {name:'Preserve candidate artifact for fourteen days',conclusion:'skipped'}, + {name:'Promote only the exact artifact version',conclusion:'success'}, + ]) assert.throws(()=>assertUploadRun(run,{...jobs,jobs:[{...jobs.jobs[0],steps:jobs.jobs[0].steps.map(step=>step.name===change.name?{...step,conclusion:change.conclusion}:step)}]},h)); +}); + +test('stale historical deployment cannot mask a newer wrong or split deployment',()=>{ + const deployments=rows=>JSON.stringify({success:true,result:rows}); + const serving={id:'new',created_on:'2026-11-22T12:00:00Z',versions:[{version_id:uuid,percentage:100}]}; + const oldServing={id:'old',created_on:'2026-11-22T11:00:00Z',versions:[{version_id:uuid,percentage:100}]}; + assert.equal(assertLatestServing(deployments([oldServing,serving]),uuid),true); + assert.throws(()=>assertLatestServing(deployments([oldServing,{...serving,versions:[{version_id:old,percentage:100}]}]),uuid),/latest deployment/); + assert.throws(()=>assertLatestServing(deployments([oldServing,{...serving,versions:[{version_id:uuid,percentage:50},{version_id:old,percentage:50}]}]),uuid),/latest deployment/); + assert.throws(()=>assertLatestServing(deployments([oldServing,{...serving,versions:[{version_id:uuid,percentage:100},{version_id:old,percentage:0}]}]),uuid),/latest deployment/); +}); + +test('read-only owner proof fails closed for missing, stale, public or unexpected callers',()=>{ + const now=Date.parse('2026-11-22T12:00:00Z'); + const good={schema:1,verified:true,account_id:acct,reviewed_by:'owner@example.com',verified_at:'2026-11-22T11:00:00Z',expires_at:'2026-11-22T13:00:00Z',evidence_ref:'review-1',release_policy:{repository:'developing-today/code',branch:'main',branch_protected:true,required_pull_request_reviews:true,force_push_disabled:true,admin_bypass_disabled:true,environment_reviewers_required:{'cloudflare-staging':true,'cloudflare-staging-smoke':true},self_review_disabled:{'cloudflare-staging':true,'cloudflare-staging-smoke':true},allowed_environment_branches:{'cloudflare-staging':['main'],'cloudflare-staging-smoke':['main']},evidence_ref:'policy-review-1'},targets:{'private-laptop-bridge-staging':{environment:'cloudflare-staging',exists:true,script_id:'private-laptop-bridge-staging',account_id:acct,application_enabled:false,workers_dev:false,preview_urls:false,routes:[],custom_domains:[],observability:{enabled:false,logs:false,traces:false},limits:{cpu_ms:10},gateway_forward_policy_ids:[],gateway_caller_ids:[],variables:{ENABLED:'false',GATEWAY_HOST:'private-bridge-staging.invalid',GATEWAY_ACCOUNT_ID:'',GATEWAY_POLICY_ID:'',GATEWAY_IDENTITY_EMAIL:'',GATEWAY_POSTURE_ID:'',BRIDGE_REGISTRY:''},bindings:[{name:'BRIDGE',type:'durable_object_namespace',class_name:'PrivateLaptopBridge',namespace_id:'1'.repeat(32)}],do:{worker_name:'private-laptop-bridge-staging',class_name:'PrivateLaptopBridge',storage:'sqlite',export_state:'created',migration_tag:'v1',pending_migrations:false,namespace_id:'1'.repeat(32)}}}}; + assert.equal(assertPreflight(good,{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now}),true); + assert.throws(()=>assertPreflight({...good,verified:false},{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now}),/absent, expired, or invalid/); + assert.throws(()=>assertPreflight({...good,expires_at:'2026-11-22T11:59:59Z'},{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now}),/absent, expired, or invalid/); + assert.throws(()=>assertPreflight({...good,evidence_ref:''},{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now}),/absent, expired, or invalid/); + assert.throws(()=>assertPreflight({...good,release_policy:{...good.release_policy,branch_protected:false}},{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now}),/protected-main/); + assert.throws(()=>assertPreflight({...good,release_policy:{...good.release_policy,environment_reviewers_required:{'cloudflare-staging':false}}},{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now}),/protected-main/); + for(const change of [{gateway_caller_ids:['unexpected-caller']},{routes:['https://public.example/*']},{custom_domains:['public.example']},{workers_dev:true},{preview_urls:true},{gateway_forward_policy_ids:['unexpected-policy']},{observability:{enabled:false,logs:true,traces:false}},{limits:{cpu_ms:50}},{application_enabled:true},{variables:{...good.targets['private-laptop-bridge-staging'].variables,ENABLED:'true'}},{bindings:[]},{do:{...good.targets['private-laptop-bridge-staging'].do,worker_name:'other-worker'}},{do:{...good.targets['private-laptop-bridge-staging'].do,export_state:'pending'}},{do:{...good.targets['private-laptop-bridge-staging'].do,migration_tag:'v0'}},{do:{...good.targets['private-laptop-bridge-staging'].do,pending_migrations:true}}]) { + const target={...good.targets['private-laptop-bridge-staging'],...change}; + assert.throws(()=>assertPreflight({...good,targets:{...good.targets,'private-laptop-bridge-staging':target}},{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now})); + } + const smokeTarget={environment:'cloudflare-staging-smoke',exists:true,script_id:'private-laptop-bridge-smoke',account_id:acct,application_enabled:false,workers_dev:false,preview_urls:false,routes:[],custom_domains:[],observability:{enabled:false,logs:false,traces:false},limits:{cpu_ms:10},gateway_forward_policy_ids:[],gateway_caller_ids:[],variables:{ENABLED:'false',GATEWAY_HOST:'private-bridge-smoke.invalid',GATEWAY_ACCOUNT_ID:'',GATEWAY_POLICY_ID:'',START_MS:'',END_MS:''},bindings:[],do:null}; + assert.equal(assertPreflight({...good,targets:{'private-laptop-bridge-smoke':smokeTarget}},{accountId:acct,worker:'private-laptop-bridge-smoke',environment:'cloudflare-staging-smoke',now}),true); +}); + +test('Versions release proof separately requires an existing Worker and its ready same-Worker DO namespace',()=>{ + const now=Date.parse('2026-11-22T12:00:00Z'); + const policy={repository:'developing-today/code',branch:'main',branch_protected:true,required_pull_request_reviews:true,force_push_disabled:true,admin_bypass_disabled:true,environment_reviewers_required:{'cloudflare-staging':true},self_review_disabled:{'cloudflare-staging':true},allowed_environment_branches:{'cloudflare-staging':['main']},evidence_ref:'policy-review-1'}; + const bridge={environment:'cloudflare-staging',exists:true,script_id:'private-laptop-bridge-staging',account_id:acct,application_enabled:false,workers_dev:false,preview_urls:false,routes:[],custom_domains:[],observability:{enabled:false,logs:false,traces:false},limits:{cpu_ms:10},gateway_forward_policy_ids:[],gateway_caller_ids:[],variables:{ENABLED:'false',GATEWAY_HOST:'private-bridge-staging.invalid',GATEWAY_ACCOUNT_ID:'',GATEWAY_POLICY_ID:'',GATEWAY_IDENTITY_EMAIL:'',GATEWAY_POSTURE_ID:'',BRIDGE_REGISTRY:''},bindings:[{name:'BRIDGE',type:'durable_object_namespace',class_name:'PrivateLaptopBridge',namespace_id:'1'.repeat(32)}],do:{worker_name:'private-laptop-bridge-staging',class_name:'PrivateLaptopBridge',storage:'sqlite',export_state:'created',migration_tag:'v1',pending_migrations:false,namespace_id:'1'.repeat(32)}}; + const makeProof=(target=bridge)=>({schema:1,verified:true,account_id:acct,reviewed_by:'owner@example.com',verified_at:'2026-11-22T11:00:00Z',expires_at:'2026-11-22T13:00:00Z',evidence_ref:'worker-review-1',release_policy:policy,targets:{'private-laptop-bridge-staging':target}}); + const check=(proof)=>assertPreflight(proof,{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now}); + assert.equal(check(makeProof()),true); + assert.throws(()=>check(makeProof({...bridge,exists:false})),/exact private disabled target/); + for(const change of [ + {do:{...bridge.do,worker_name:'private-laptop-bridge-smoke'}}, + {do:{...bridge.do,export_state:'missing'}}, + {do:{...bridge.do,migration_tag:'v0'}}, + {do:{...bridge.do,pending_migrations:true}}, + {do:{...bridge.do,namespace_id:''}}, + {bindings:[{...bridge.bindings[0],namespace_id:'2'.repeat(32)}]}, + {bindings:[{...bridge.bindings[0],class_name:'OtherClass'}]}, + ]) assert.throws(()=>check(makeProof({...bridge,...change})),/same-Worker SQLite Durable Object namespace and completed v1 migration state/); +}); + +test('CI dry-run verifies the effective private Build Output but does not claim account route proof',()=>{ + const bridge='env.BRIDGE (PrivateLaptopBridge, defined in private-laptop-bridge-staging)\nenv.ENABLED ("false")\nenv.BRIDGE_REGISTRY ("")\n--dry-run: exiting now.'; + assert.equal(assertDryRunPayload(bridge,{worker:'private-laptop-bridge-staging',mode:'bridge'}),true); + assert.throws(()=>assertDryRunPayload(bridge.replace('env.ENABLED ("false")','env.ENABLED ("true")'),{worker:'private-laptop-bridge-staging',mode:'bridge'})); + assert.throws(()=>assertDryRunPayload(bridge.replace('env.BRIDGE (','env.OTHER ('),{worker:'private-laptop-bridge-staging',mode:'bridge'})); + assert.throws(()=>assertDryRunPayload('no output',{worker:'private-laptop-bridge-staging',mode:'bridge'})); +}); + +test('effective Build Output explicitly fixes CPU, observability, routes, preview, flags, variables and resource bindings',()=>{ + const base={name:'private-laptop-bridge-staging',compatibilityDate:'2026-07-30',domains:[],triggers:[],limits:{cpuMs:10},observability:{enabled:false,logs:{enabled:false},traces:{enabled:false}},workersDev:false,previewUrls:false,env:{ENABLED:{type:'text',value:'false'},GATEWAY_HOST:{type:'text',value:'private-bridge-staging.invalid'},GATEWAY_ACCOUNT_ID:{type:'text',value:''},GATEWAY_POLICY_ID:{type:'text',value:''},GATEWAY_IDENTITY_EMAIL:{type:'text',value:''},GATEWAY_POSTURE_ID:{type:'text',value:''},BRIDGE_REGISTRY:{type:'text',value:''},BRIDGE:{type:'durable-object',worker:'private-laptop-bridge-staging',exportName:'PrivateLaptopBridge'}},exports:{PrivateLaptopBridge:{type:'durable-object',storage:'sqlite'}},manifest:{type:'complete',mainModule:'gateway.js',modules:{'gateway.js':{type:'esm'},'gateway.js.map':{type:'sourcemap'}}}}; + assert.equal(assertEffectivePayload(base,{worker:'private-laptop-bridge-staging',mode:'bridge'}),true); + for(const mutation of [x=>x.limits.cpuMs=30,x=>x.observability.enabled=true,x=>x.workersDev=true,x=>x.previewUrls=true,x=>x.domains.push('public.example'),x=>x.triggers.push({route:'public.example/*'}),x=>x.env.ENABLED.value='true',x=>x.env.EXTRA={type:'text',value:'secret'},x=>x.env.BRIDGE.worker='other-worker',x=>x.exports.PrivateLaptopBridge.storage='kv',x=>x.forwardPolicies=['unexpected']]) { + const mutated=structuredClone(base); mutation(mutated); assert.throws(()=>assertEffectivePayload(mutated,{worker:'private-laptop-bridge-staging',mode:'bridge'})); + } + const smoke={name:'private-laptop-bridge-smoke',compatibilityDate:'2026-07-30',domains:[],triggers:[],limits:{cpuMs:10},observability:{enabled:false,logs:{enabled:false},traces:{enabled:false}},workersDev:false,previewUrls:false,env:{ENABLED:{type:'text',value:'false'},GATEWAY_HOST:{type:'text',value:'private-bridge-smoke.invalid'},GATEWAY_ACCOUNT_ID:{type:'text',value:''},GATEWAY_POLICY_ID:{type:'text',value:''},START_MS:{type:'text',value:''},END_MS:{type:'text',value:''}},manifest:{type:'complete',mainModule:'smoke.js',modules:{'smoke.js':{type:'esm'},'smoke.js.map':{type:'sourcemap'}}}}; + assert.equal(assertEffectivePayload(smoke,{worker:'private-laptop-bridge-smoke',mode:'default'}),true); + for(const mutated of [{...smoke,exports:{}},{...smoke,env:{...smoke.env,BRIDGE:{type:'durable-object'}}},{...smoke,observability:{enabled:true}}]) assert.throws(()=>assertEffectivePayload(mutated,{worker:'private-laptop-bridge-smoke',mode:'default'})); +}); diff --git a/pm-stack/private-laptop-bridge/staging-preflight.json b/pm-stack/private-laptop-bridge/staging-preflight.json new file mode 100644 index 0000000000..e6a125a662 --- /dev/null +++ b/pm-stack/private-laptop-bridge/staging-preflight.json @@ -0,0 +1,59 @@ +{ + "schema": 1, + "verified": false, + "account_id": "", + "reviewed_by": "", + "verified_at": "", + "expires_at": "", + "evidence_ref": "", + "release_policy": { + "repository": "developing-today/code", + "branch": "main", + "branch_protected": false, + "required_pull_request_reviews": false, + "force_push_disabled": false, + "admin_bypass_disabled": false, + "environment_reviewers_required": {"cloudflare-staging": false, "cloudflare-staging-smoke": false}, + "self_review_disabled": {"cloudflare-staging": false, "cloudflare-staging-smoke": false}, + "allowed_environment_branches": {"cloudflare-staging": [], "cloudflare-staging-smoke": []}, + "evidence_ref": "" + }, + "targets": { + "private-laptop-bridge-smoke": { + "environment": "cloudflare-staging-smoke", + "exists": false, + "script_id": "private-laptop-bridge-smoke", + "account_id": "", + "application_enabled": false, + "workers_dev": false, + "preview_urls": false, + "routes": [], + "custom_domains": [], + "observability": {"enabled": false, "logs": false, "traces": false}, + "limits": {"cpu_ms": 10}, + "gateway_forward_policy_ids": [], + "gateway_caller_ids": [], + "variables": {"ENABLED": "false", "GATEWAY_HOST": "private-bridge-smoke.invalid", "GATEWAY_ACCOUNT_ID": "", "GATEWAY_POLICY_ID": "", "START_MS": "", "END_MS": ""}, + "bindings": [], + "do": null + }, + "private-laptop-bridge-staging": { + "environment": "cloudflare-staging", + "exists": false, + "script_id": "private-laptop-bridge-staging", + "account_id": "", + "application_enabled": false, + "workers_dev": false, + "preview_urls": false, + "routes": [], + "custom_domains": [], + "observability": {"enabled": false, "logs": false, "traces": false}, + "limits": {"cpu_ms": 10}, + "gateway_forward_policy_ids": [], + "gateway_caller_ids": [], + "variables": {"ENABLED": "false", "GATEWAY_HOST": "private-bridge-staging.invalid", "GATEWAY_ACCOUNT_ID": "", "GATEWAY_POLICY_ID": "", "GATEWAY_IDENTITY_EMAIL": "", "GATEWAY_POSTURE_ID": "", "BRIDGE_REGISTRY": ""}, + "bindings": [{"name": "BRIDGE", "type": "durable_object_namespace", "class_name": "PrivateLaptopBridge", "namespace_id": ""}], + "do": {"worker_name": "private-laptop-bridge-staging", "class_name": "PrivateLaptopBridge", "storage": "sqlite", "export_state": "", "migration_tag": "", "pending_migrations": false, "namespace_id": ""} + } + } +} diff --git a/pm-stack/private-laptop-bridge/wrangler.jsonc b/pm-stack/private-laptop-bridge/wrangler.jsonc index 4151db7e24..863dfd2f05 100644 --- a/pm-stack/private-laptop-bridge/wrangler.jsonc +++ b/pm-stack/private-laptop-bridge/wrangler.jsonc @@ -4,6 +4,8 @@ "compatibility_date": "2026-07-30", "workers_dev": false, "preview_urls": false, + "limits": {"cpu_ms": 10}, + "observability": {"enabled": false}, "vars": {"ENABLED": "false"}, "durable_objects": {"bindings": [{"name": "BRIDGE", "class_name": "PrivateLaptopBridge"}]}, "migrations": [{"tag": "v1", "new_sqlite_classes": ["PrivateLaptopBridge"]}] diff --git a/pm-stack/private-laptop-bridge/wrangler.staging.jsonc b/pm-stack/private-laptop-bridge/wrangler.staging.jsonc index 78ce9c46e7..b719a7a624 100644 --- a/pm-stack/private-laptop-bridge/wrangler.staging.jsonc +++ b/pm-stack/private-laptop-bridge/wrangler.staging.jsonc @@ -6,6 +6,8 @@ "compatibility_date": "2026-07-30", "workers_dev": false, "preview_urls": false, + "limits": {"cpu_ms": 10}, + "observability": {"enabled": false}, "routes": [], "vars": { "ENABLED": "false", From c5a0c91eeaef1e816b595cf57e68ffc83b966607 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 14:44:59 +0000 Subject: [PATCH 11/33] Keep bridge owner proof private and bind promotion identity --- .../private-laptop-bridge-release.yml | 69 ++++++++++++++----- pm-stack/private-laptop-bridge/DISCOVERY.md | 42 ++++++----- .../private-laptop-bridge/VERIFICATION.md | 18 ++++- .../release-artifact.mjs | 35 ++++++---- .../release-contract.mjs | 15 +++- .../release-contract.test.mjs | 40 ++++++++--- .../staging-preflight.json | 1 - 7 files changed, 159 insertions(+), 61 deletions(-) diff --git a/.github/workflows/private-laptop-bridge-release.yml b/.github/workflows/private-laptop-bridge-release.yml index 1dea346bf9..5275ac910d 100644 --- a/.github/workflows/private-laptop-bridge-release.yml +++ b/.github/workflows/private-laptop-bridge-release.yml @@ -88,7 +88,7 @@ jobs: TARGET_WORKER: ${{ steps.target.outputs.worker }} TARGET_ENV: ${{ steps.target.outputs.environment }} TARGET_MODE: ${{ steps.target.outputs.mode }} - CF_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }} + CF_ACCOUNT_ID: ${{ inputs.worker == 'bridge' && secrets.CF_BRIDGE_ACCOUNT_ID || inputs.worker == 'smoke' && secrets.CF_SMOKE_ACCOUNT_ID }} run: | set -euo pipefail node release-artifact.mjs provenance \ @@ -100,11 +100,18 @@ jobs: if: inputs.action == 'promote' working-directory: pm-stack/private-laptop-bridge env: - CF_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }} + CF_ACCOUNT_ID: ${{ inputs.worker == 'bridge' && secrets.CF_BRIDGE_ACCOUNT_ID || inputs.worker == 'smoke' && secrets.CF_SMOKE_ACCOUNT_ID }} + OWNER_PROOF_JSON: ${{ inputs.worker == 'bridge' && secrets.CF_BRIDGE_OWNER_PROOF_JSON || inputs.worker == 'smoke' && secrets.CF_SMOKE_OWNER_PROOF_JSON }} TARGET_WORKER: ${{ steps.target.outputs.worker }} TARGET_ENV: ${{ steps.target.outputs.environment }} + SOURCE_SHA: ${{ steps.provenance.outputs.source_sha }} HANDOFF: ${{ runner.temp }}/private-bridge-handoff/candidate.json - run: node release-artifact.mjs current-proof "$HANDOFF" + run: | + set -euo pipefail + git fetch --no-tags origin main + main_sha="$(git rev-parse FETCH_HEAD)" + [[ "$SOURCE_SHA" == "$main_sha" ]] || { echo 'Candidate is not from the current protected main head; upload a fresh candidate.' >&2; exit 1; } + node release-artifact.mjs current-proof "$HANDOFF" - name: Check out the exact uploaded source commit if: inputs.action == 'promote' uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -126,15 +133,16 @@ jobs: - name: Validate account owner proof before Cloudflare access working-directory: pm-stack/private-laptop-bridge env: - CF_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }} + CF_ACCOUNT_ID: ${{ inputs.worker == 'bridge' && secrets.CF_BRIDGE_ACCOUNT_ID || inputs.worker == 'smoke' && secrets.CF_SMOKE_ACCOUNT_ID }} + OWNER_PROOF_JSON: ${{ inputs.worker == 'bridge' && secrets.CF_BRIDGE_OWNER_PROOF_JSON || inputs.worker == 'smoke' && secrets.CF_SMOKE_OWNER_PROOF_JSON }} TARGET_WORKER: ${{ steps.target.outputs.worker }} TARGET_ENV: ${{ steps.target.outputs.environment }} run: node release-artifact.mjs preflight - name: Require existing exact Worker; never bootstrap from CI working-directory: pm-stack/private-laptop-bridge env: - CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }} - CLOUDFLARE_API_TOKEN: ${{ secrets.CF_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: ${{ inputs.worker == 'bridge' && secrets.CF_BRIDGE_ACCOUNT_ID || inputs.worker == 'smoke' && secrets.CF_SMOKE_ACCOUNT_ID }} + CLOUDFLARE_API_TOKEN: ${{ inputs.worker == 'bridge' && secrets.CF_BRIDGE_API_TOKEN || inputs.worker == 'smoke' && secrets.CF_SMOKE_API_TOKEN }} TARGET_WORKER: ${{ steps.target.outputs.worker }} run: npx --no-install cf -q workers get "$TARGET_WORKER" >/dev/null - name: Verify source tests and effective local config @@ -180,9 +188,10 @@ jobs: id: upload working-directory: pm-stack/private-laptop-bridge env: - CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }} - CLOUDFLARE_API_TOKEN: ${{ secrets.CF_API_TOKEN }} - CF_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }} + CLOUDFLARE_ACCOUNT_ID: ${{ inputs.worker == 'bridge' && secrets.CF_BRIDGE_ACCOUNT_ID || inputs.worker == 'smoke' && secrets.CF_SMOKE_ACCOUNT_ID }} + CLOUDFLARE_API_TOKEN: ${{ inputs.worker == 'bridge' && secrets.CF_BRIDGE_API_TOKEN || inputs.worker == 'smoke' && secrets.CF_SMOKE_API_TOKEN }} + CF_ACCOUNT_ID: ${{ inputs.worker == 'bridge' && secrets.CF_BRIDGE_ACCOUNT_ID || inputs.worker == 'smoke' && secrets.CF_SMOKE_ACCOUNT_ID }} + OWNER_PROOF_JSON: ${{ inputs.worker == 'bridge' && secrets.CF_BRIDGE_OWNER_PROOF_JSON || inputs.worker == 'smoke' && secrets.CF_SMOKE_OWNER_PROOF_JSON }} TARGET_WORKER: ${{ steps.target.outputs.worker }} TARGET_ENV: ${{ steps.target.outputs.environment }} TARGET_MODE: ${{ steps.target.outputs.mode }} @@ -217,9 +226,10 @@ jobs: if: inputs.action == 'promote' working-directory: pm-stack/private-laptop-bridge env: - CF_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }} - CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }} - CLOUDFLARE_API_TOKEN: ${{ secrets.CF_API_TOKEN }} + CF_ACCOUNT_ID: ${{ inputs.worker == 'bridge' && secrets.CF_BRIDGE_ACCOUNT_ID || inputs.worker == 'smoke' && secrets.CF_SMOKE_ACCOUNT_ID }} + OWNER_PROOF_JSON: ${{ inputs.worker == 'bridge' && secrets.CF_BRIDGE_OWNER_PROOF_JSON || inputs.worker == 'smoke' && secrets.CF_SMOKE_OWNER_PROOF_JSON }} + CLOUDFLARE_ACCOUNT_ID: ${{ inputs.worker == 'bridge' && secrets.CF_BRIDGE_ACCOUNT_ID || inputs.worker == 'smoke' && secrets.CF_SMOKE_ACCOUNT_ID }} + CLOUDFLARE_API_TOKEN: ${{ inputs.worker == 'bridge' && secrets.CF_BRIDGE_API_TOKEN || inputs.worker == 'smoke' && secrets.CF_SMOKE_API_TOKEN }} TARGET_WORKER: ${{ steps.target.outputs.worker }} TARGET_ENV: ${{ steps.target.outputs.environment }} TARGET_MODE: ${{ steps.target.outputs.mode }} @@ -236,18 +246,43 @@ jobs: -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \ "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/workers/scripts/$TARGET_WORKER/versions?deployable=true" > "$DEPLOYABLE_LIST" node release-artifact.mjs verify-handoff "$HANDOFF" "$UPLOAD_RUN_JSON" "$RUNNER_TEMP/upload-jobs.json" "$VERSION_LIST" "$DEPLOYABLE_LIST" + - name: Revalidate current private proof immediately before promotion + if: inputs.action == 'promote' + working-directory: pm-stack/private-laptop-bridge + env: + CF_ACCOUNT_ID: ${{ inputs.worker == 'bridge' && secrets.CF_BRIDGE_ACCOUNT_ID || inputs.worker == 'smoke' && secrets.CF_SMOKE_ACCOUNT_ID }} + OWNER_PROOF_JSON: ${{ inputs.worker == 'bridge' && secrets.CF_BRIDGE_OWNER_PROOF_JSON || inputs.worker == 'smoke' && secrets.CF_SMOKE_OWNER_PROOF_JSON }} + TARGET_WORKER: ${{ steps.target.outputs.worker }} + TARGET_ENV: ${{ steps.target.outputs.environment }} + SOURCE_SHA: ${{ steps.provenance.outputs.source_sha }} + HANDOFF: ${{ runner.temp }}/private-bridge-handoff/candidate.json + run: | + set -euo pipefail + git fetch --no-tags origin main + main_sha="$(git rev-parse FETCH_HEAD)" + [[ "$SOURCE_SHA" == "$main_sha" ]] || { echo 'Candidate is not from the current protected main head; upload a fresh candidate.' >&2; exit 1; } + node release-artifact.mjs current-proof "$HANDOFF" - name: Promote only the exact artifact version if: inputs.action == 'promote' working-directory: pm-stack/private-laptop-bridge env: - CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }} - CLOUDFLARE_API_TOKEN: ${{ secrets.CF_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: ${{ inputs.worker == 'bridge' && secrets.CF_BRIDGE_ACCOUNT_ID || inputs.worker == 'smoke' && secrets.CF_SMOKE_ACCOUNT_ID }} + CLOUDFLARE_API_TOKEN: ${{ inputs.worker == 'bridge' && secrets.CF_BRIDGE_API_TOKEN || inputs.worker == 'smoke' && secrets.CF_SMOKE_API_TOKEN }} TARGET_WORKER: ${{ steps.target.outputs.worker }} HANDOFF: ${{ runner.temp }}/private-bridge-handoff/candidate.json DEPLOYMENTS: ${{ runner.temp }}/cf-deployments.json + DEPLOYMENT_CREATE_RESPONSE: ${{ runner.temp }}/cf-deployment-create.json + DEPLOYMENT_ID: ${{ runner.temp }}/cf-deployment-id.txt run: | set -euo pipefail + rm -f "$DEPLOYMENT_CREATE_RESPONSE" "$DEPLOYMENT_ID" version_id="$(node -e 'let h=require(process.env.HANDOFF);process.stdout.write(h.version_id)')" - npx --no-install cf -q workers deployments create --worker "$TARGET_WORKER" --strategy percentage --versions "[{\"version_id\":\"$version_id\",\"percentage\":100}]" - npx --no-install cf -q workers deployments list --worker "$TARGET_WORKER" > "$DEPLOYMENTS" - node release-artifact.mjs verify-deployment "$DEPLOYMENTS" "$HANDOFF" + npx --no-install cf -q workers deployments create --worker "$TARGET_WORKER" --strategy percentage --versions "[{\"version_id\":\"$version_id\",\"percentage\":100}]" > "$DEPLOYMENT_CREATE_RESPONSE" + node release-artifact.mjs verify-deployment-create "$DEPLOYMENT_CREATE_RESPONSE" "$HANDOFF" "$DEPLOYMENT_ID" + for attempt in 1 2 3 4 5; do + npx --no-install cf -q workers deployments list --worker "$TARGET_WORKER" > "$DEPLOYMENTS" + if node release-artifact.mjs verify-deployment "$DEPLOYMENTS" "$HANDOFF" "$DEPLOYMENT_ID" 2>/dev/null; then exit 0; fi + if [[ "$attempt" -lt 5 ]]; then sleep 2; fi + done + echo 'Deployment readback did not show the returned deployment as latest within five attempts.' >&2 + exit 1 diff --git a/pm-stack/private-laptop-bridge/DISCOVERY.md b/pm-stack/private-laptop-bridge/DISCOVERY.md index 064ff1964a..87a1ea2b2c 100644 --- a/pm-stack/private-laptop-bridge/DISCOVERY.md +++ b/pm-stack/private-laptop-bridge/DISCOVERY.md @@ -5,13 +5,12 @@ network setting or access grant changed. No AMD or proposed-host probe ran. ## Verified metadata and limits of inference -- Historical Wrangler verification (2026-10-21), - `doc/platform/toolchains/cloudflare-wrangler.md`, names - `Developing.today.llc.domains.0@gmail.com's Account`, ID prefix `234b866b…`. - No complete account ID or current Cloudflare One Gateway configuration was - available through the connected tools or inspected tracked configuration. +- Historical Wrangler verification (2026-10-21) mentions a Developing.today + account, but is insufficient to establish current account ownership or its + identifier. No current Cloudflare One Gateway configuration was available + through connected tools or inspected tracked configuration. - `pm-stack/console/scripts/expose.py` configures `amd-6-pm-stack`, - `pm.security.cab`, and owner default `drewrypope@gmail.com`; account and Access + `pm.security.cab`, and an owner default; account and Access organization are discovered dynamically. These defaults do not verify current ownership, Gateway enrollment or a suitable caller runner. - Existing `lab-cluster` and `sandbox-link` tunnels use public hostnames. They @@ -147,19 +146,31 @@ for this repository's `main` ref, checks out the event SHA, has `contents: read` only, serializes per Worker, and pins Actions, Node, cf, Wrangler and lockfile versions. The `smoke` target is `private-laptop-bridge-smoke` under GitHub Environment `cloudflare-staging-smoke`. The real bridge target is -`private-laptop-bridge-staging` under `cloudflare-staging`. Both environments -use names `CF_ACCOUNT_ID` and `CF_API_TOKEN`; each token must be independently -account-owned and scoped as **Workers Editor for that one individual existing -Worker**. It must not be scoped to the Workers product or whole account. There -are no environment secrets configured by this change. GitHub environments must -have required reviewers and reject untrusted refs before secrets are provisioned. +`private-laptop-bridge-staging` under `cloudflare-staging`. The bridge +environment uses `CF_BRIDGE_ACCOUNT_ID`, `CF_BRIDGE_API_TOKEN`, and +`CF_BRIDGE_OWNER_PROOF_JSON`; the smoke environment uses the corresponding +`CF_SMOKE_*` names. These are distinct environment-only secrets with no +repository-secret fallback. Each token must be independently account-owned and +scoped as **Workers Editor for that one individual existing Worker**. It must +not be scoped to the Workers product or whole account. No secret values are +configured or read by this change. The owner proof stays private in the +matching protected environment secret; only its digest is bound to a candidate. +The tracked `staging-preflight.json` is a redacted, unverified public contract +fixture. It contains no reviewer email, account ID, or DO namespace ID. The +private proof does not require a reviewer email; `evidence_ref` must be opaque +and non-PII. GitHub environments must have required reviewers and reject +untrusted refs before secrets are provisioned. Each upload path runs named runtime tests, `cf build` (bridge build uses mode `bridge`), a source/config binding equivalence test, then `cf workers versions create --prebuilt --dry-run` and the actual immutable version upload. It verifies the uploaded UUID appears in the deployable set. Promotion is a distinct manual invocation with the exact UUID; it repeats the -deployable check, creates a 100% deployment, and verifies read-back. Recovery is +deployable check, captures the create response deployment ID, and retries +read-back at most five times to verify that exact deployment is latest and +serves 100%. Immediately before promotion, the workflow requires the candidate +SHA to equal the freshly fetched protected `main` head and revalidates the +private owner proof. Recovery is an explicit promotion of a recorded known-good retained UUID. Fix-forward uploads a new version and separately promotes it. These actions do not apply Gateway routes, Workers routes/domains, DNS, TLS settings or access policies. @@ -167,10 +178,7 @@ routes, Workers routes/domains, DNS, TLS settings or access policies. **Target existence is not verified.** The tracked Wrangler configs and `cf` config give only the proposed names `private-laptop-bridge-smoke` and `private-laptop-bridge-staging`; they prove neither is present in Cloudflare. -The only account evidence found is historical from 2026-10-21: -`Developing.today.llc.domains.0@gmail.com's Account`, partial ID `234b866b…` in -`doc/platform/toolchains/cloudflare-wrangler.md`. No full account ID or live -metadata was obtained. The first workflow step calls `cf workers get` and fails +No current account ID or live metadata was obtained. The first workflow step calls `cf workers get` and fails closed if the selected exact target is absent; it never bootstraps, creates account resources or widens scopes. Before adding secrets, an authorized owner must independently confirm full account ID/ownership and existence of the exact diff --git a/pm-stack/private-laptop-bridge/VERIFICATION.md b/pm-stack/private-laptop-bridge/VERIFICATION.md index 2aa1abb240..15304f2630 100644 --- a/pm-stack/private-laptop-bridge/VERIFICATION.md +++ b/pm-stack/private-laptop-bridge/VERIFICATION.md @@ -158,9 +158,25 @@ smoke preflight requires its existing Worker but no DO. The tracked staging proof remains `verified: false`; these tests validate the fail-closed gate and do not assert live account state. +Owner evidence is supplied only through separate protected environment +secrets: `CF_BRIDGE_ACCOUNT_ID`, `CF_BRIDGE_API_TOKEN`, +`CF_BRIDGE_OWNER_PROOF_JSON` or their `CF_SMOKE_*` equivalents. No generic +repository secret fallback is used. The public fixture contains no reviewer +email or account/namespace identifiers; the private proof requires an opaque +evidence reference, not a person's email. Promotion re-parses and revalidates +the current private proof immediately before creating a deployment and requires +its digest to equal the candidate's protected proof digest. + +Deployment readback binds to the deployment `result.id` returned by the create +response, checks its exact one-version 100% set, then retries the list readback +at most five times, two seconds apart. Success requires that same ID to be the +latest deployment and to carry the exact 100% version. Tests cover the +create-response identity and stale/newer/split deployment cases. This path was +contract-tested offline; no create request or live readback was sent. + After adding these tests, the focused local command `node --test --test-reporter=spec release-contract.test.mjs deployment-config.test.mjs smoke.test.mjs gateway.test.mjs` -passed 19/19 under Node 24.22.0. Both `cf build` variants and both +passed 21/21 under Node 24.22.0. Both `cf build` variants and both `cf workers versions create --prebuilt --dry-run` variants were rerun; the effective Build Output checks passed for the smoke and bridge targets. Dry-run output confirms the bridge declares its `BRIDGE` Durable Object export and diff --git a/pm-stack/private-laptop-bridge/release-artifact.mjs b/pm-stack/private-laptop-bridge/release-artifact.mjs index cd1e3aa215..bf116dc253 100644 --- a/pm-stack/private-laptop-bridge/release-artifact.mjs +++ b/pm-stack/private-laptop-bridge/release-artifact.mjs @@ -1,20 +1,23 @@ #!/usr/bin/env node import {readFile,writeFile} from 'node:fs/promises'; import {resolve} from 'node:path'; -import {assertDeployable,assertDryRunPayload,assertEffectivePayload,assertExactVersion,assertLatestServing,assertPreflight,assertUploadRun,assertVersionStillMatches,digestFiles,digestTree,makeHandoff,provenanceDigest} from './release-contract.mjs'; +import {createHash} from 'node:crypto'; +import {assertDeployable,assertDeploymentCreated,assertDryRunPayload,assertEffectivePayload,assertExactVersion,assertLatestServing,assertPreflight,assertUploadRun,assertVersionStillMatches,digestFiles,digestTree,makeHandoff,provenanceDigest} from './release-contract.mjs'; const [action,...args]=process.argv.slice(2); const required=(name)=>{const value=process.env[name];if(!value)throw new Error(`missing ${name}`);return value;}; const json=async path=>JSON.parse(await readFile(path,'utf8')); +const privateProof=()=>{try{return JSON.parse(required('OWNER_PROOF_JSON'));}catch{throw new Error('OWNER_PROOF_JSON is missing or invalid JSON');}}; +const proofDigest=()=>createHash('sha256').update(required('OWNER_PROOF_JSON')).digest('hex'); const write=(path,value)=>writeFile(path,JSON.stringify(value,null,2)+'\n',{mode:0o600}); const root=process.cwd(); if(action==='preflight') { const worker=required('TARGET_WORKER'), environment=required('TARGET_ENV'), accountId=required('CF_ACCOUNT_ID'); - const proof=await json(resolve(root,'staging-preflight.json')); + const proof=privateProof(); assertPreflight(proof,{accountId,worker,environment}); console.log('owner read-only staging proof valid for '+worker); } else if(action==='digest') { - const config_digest=await digestFiles(root), preflight_digest=await digestFiles(root,['staging-preflight.json']), build_digest=await digestTree(resolve(root,'.cloudflare/output/v1')); + const config_digest=await digestFiles(root), preflight_digest=proofDigest(), build_digest=await digestTree(resolve(root,'.cloudflare/output/v1')); console.log(JSON.stringify({config_digest,preflight_digest,build_digest})); } else if(action==='dry-run') { const worker=required('TARGET_WORKER'), mode=required('TARGET_MODE'); @@ -28,7 +31,7 @@ if(action==='preflight') { const [responsePath,versionsPath,outputPath]=args; if(!responsePath||!versionsPath||!outputPath) throw new Error('usage: make-handoff '); const source_sha=required('GITHUB_SHA'), worker=required('TARGET_WORKER'), environment=required('TARGET_ENV'), account_id=required('CF_ACCOUNT_ID'), mode=required('TARGET_MODE'); - const config_digest=await digestFiles(root), preflight_digest=await digestFiles(root,['staging-preflight.json']), build_digest=await digestTree(resolve(root,'.cloudflare/output/v1')); + const config_digest=await digestFiles(root), preflight_digest=proofDigest(), build_digest=await digestTree(resolve(root,'.cloudflare/output/v1')); const stdout=await readFile(responsePath,'utf8'), versionsJson=await readFile(versionsPath,'utf8'), tag=source_sha; const version_id=assertExactVersion({stdout,versionsJson,worker,sourceSha:source_sha,configDigest:config_digest,buildDigest:build_digest,preflightDigest:preflight_digest}); const artifact=makeHandoff({repository:required('GITHUB_REPOSITORY'),workflow:'.github/workflows/private-laptop-bridge-release.yml',upload_run_id:required('GITHUB_RUN_ID'),upload_run_attempt:Number(required('GITHUB_RUN_ATTEMPT')),source_sha,worker,environment,account_id,mode,version_id,tag,config_digest,build_digest,preflight_digest,provenance_digest:provenanceDigest({worker,sourceSha:source_sha,configDigest:config_digest,buildDigest:build_digest,preflightDigest:preflight_digest}),expected_disabled:true}); @@ -45,8 +48,8 @@ if(action==='preflight') { const [handoffPath]=args; if(!handoffPath) throw new Error('usage: current-proof '); const artifact=await json(handoffPath),account=required('CF_ACCOUNT_ID'),worker=required('TARGET_WORKER'),environment=required('TARGET_ENV'); if(artifact.account_id!==account||artifact.worker!==worker||artifact.environment!==environment) throw new Error('current owner proof target differs from upload artifact'); - const proof=await json(resolve(root,'staging-preflight.json')); assertPreflight(proof,{accountId:account,worker,environment}); - const preflight_digest=await digestFiles(root,['staging-preflight.json']); + const proof=privateProof(); assertPreflight(proof,{accountId:account,worker,environment}); + const preflight_digest=proofDigest(); if(preflight_digest!==artifact.preflight_digest) throw new Error('current main owner proof changed since upload; upload a new candidate'); console.log('current main owner proof matches uploaded candidate'); } else if(action==='verify-handoff') { @@ -56,16 +59,22 @@ if(action==='preflight') { const expectedMode=target==='private-laptop-bridge-staging'?'bridge':'default'; if(artifact.worker!==target||artifact.account_id!==account||artifact.environment!==env||artifact.mode!==expectedMode||mode!==expectedMode) throw new Error('promotion target/environment/account/mode differs from handoff'); assertUploadRun(run,jobs,artifact); - const proof=await json(resolve(root,'staging-preflight.json')); assertPreflight(proof,{accountId:account,worker:target,environment:env}); - const config_digest=await digestFiles(root),preflight_digest=await digestFiles(root,['staging-preflight.json']),build_digest=await digestTree(resolve(root,'.cloudflare/output/v1')); + const proof=privateProof(); assertPreflight(proof,{accountId:account,worker:target,environment:env}); + const config_digest=await digestFiles(root),preflight_digest=proofDigest(),build_digest=await digestTree(resolve(root,'.cloudflare/output/v1')); const head=required('CHECKED_OUT_SHA'); if(head!==artifact.source_sha||config_digest!==artifact.config_digest||preflight_digest!==artifact.preflight_digest||build_digest!==artifact.build_digest) throw new Error('checked-out source/config/build/preflight digest does not equal uploaded artifact'); assertVersionStillMatches(await readFile(versionsPath,'utf8'),artifact); assertDeployable(await readFile(deployablePath,'utf8'),artifact.version_id); console.log(`verified ${artifact.version_id} from run ${artifact.upload_run_id} at ${artifact.source_sha}`); +} else if(action==='verify-deployment-create') { + const [responsePath,handoffPath,outputPath]=args; + if(!responsePath||!handoffPath||!outputPath) throw new Error('usage: verify-deployment-create '); + const artifact=await json(handoffPath),id=assertDeploymentCreated(await readFile(responsePath,'utf8'),artifact.version_id); + await writeFile(outputPath,id+'\n',{mode:0o600}); console.log('created deployment identity validated'); } else if(action==='verify-deployment') { - const [deploymentPath,handoffPath]=args; - if(!deploymentPath||!handoffPath) throw new Error('usage: verify-deployment '); - const artifact=await json(handoffPath);assertLatestServing(await readFile(deploymentPath,'utf8'),artifact.version_id); - console.log(`latest deployment is exactly ${artifact.version_id} at 100%`); -} else throw new Error('action must be preflight, digest, dry-run, make-handoff, provenance, verify-handoff, or verify-deployment'); + const [deploymentPath,handoffPath,deploymentIdPath]=args; + if(!deploymentPath||!handoffPath||!deploymentIdPath) throw new Error('usage: verify-deployment '); + const artifact=await json(handoffPath),deploymentId=(await readFile(deploymentIdPath,'utf8')).trim(); + assertLatestServing(await readFile(deploymentPath,'utf8'),artifact.version_id,deploymentId); + console.log(`latest deployment ${deploymentId} serves exact version ${artifact.version_id} at 100%`); +} else throw new Error('action must be preflight, digest, dry-run, make-handoff, provenance, verify-handoff, verify-deployment-create, or verify-deployment'); diff --git a/pm-stack/private-laptop-bridge/release-contract.mjs b/pm-stack/private-laptop-bridge/release-contract.mjs index aae8178753..9c7c21003d 100644 --- a/pm-stack/private-laptop-bridge/release-contract.mjs +++ b/pm-stack/private-laptop-bridge/release-contract.mjs @@ -114,7 +114,16 @@ export function assertDeployable(deployableJson,versionId) { return true; } -export function assertLatestServing(deploymentsJson,versionId) { +export function assertDeploymentCreated(responseJson,versionId) { + let body; try {body=JSON.parse(responseJson);} catch {fail('deployment-create response is not JSON');} + if(body?.success===false) fail('deployment-create API returned success=false'); + const deployment=body?.result; + if(!deployment||!UUID.test(deployment.id??'')||!Array.isArray(deployment.versions)||deployment.versions.length!==1||deployment.versions[0]?.version_id!==versionId||deployment.versions[0]?.percentage!==100) fail('created deployment identity or exact 100% version set is invalid'); + return deployment.id; +} + +export function assertLatestServing(deploymentsJson,versionId,deploymentId) { + if(!UUID.test(deploymentId??'')) fail('invalid deployment identity'); const rows=parseItems(deploymentsJson,'deployments'); const dated=rows.map(row=>({row,at:Date.parse(row.created_on??row.created_at??'')})); if(dated.some(x=>!Number.isFinite(x.at))) fail('deployment listing contains an invalid timestamp'); @@ -122,7 +131,7 @@ export function assertLatestServing(deploymentsJson,versionId) { const latest=dated.filter(x=>x.at===latestAt); if(latest.length!==1) fail('latest deployment is ambiguous'); const traffic=latest[0].row.versions; - if(!Array.isArray(traffic)||traffic.length!==1||traffic[0].version_id!==versionId||traffic[0].percentage!==100) fail('latest deployment is not the exact complete 100% version set'); + if(latest[0].row.id!==deploymentId||!Array.isArray(traffic)||traffic.length!==1||traffic[0].version_id!==versionId||traffic[0].percentage!==100) fail('latest deployment is not the returned deployment identity with the exact complete 100% version set'); return true; } @@ -144,7 +153,7 @@ export function assertUploadRun(run,jobsResponse,handoff) { } export function assertPreflight(proof,{accountId,worker,environment,now=Date.now()}) { - if(!proof||proof.schema!==1||proof.verified!==true||proof.account_id!==accountId||!proof.reviewed_by||!proof.reviewed_by.includes('@')||typeof proof.evidence_ref!=='string'||proof.evidence_ref.trim().length<3||!Number.isFinite(Date.parse(proof.verified_at))||!Number.isFinite(Date.parse(proof.expires_at))||Date.parse(proof.verified_at)>now||Date.parse(proof.expires_at)<=now||Date.parse(proof.expires_at)-Date.parse(proof.verified_at)>24*3600000) fail('owner read-only staging proof is absent, expired, or invalid'); + if(!proof||proof.schema!==1||proof.verified!==true||proof.account_id!==accountId||typeof proof.evidence_ref!=='string'||proof.evidence_ref.trim().length<3||!Number.isFinite(Date.parse(proof.verified_at))||!Number.isFinite(Date.parse(proof.expires_at))||Date.parse(proof.verified_at)>now||Date.parse(proof.expires_at)<=now||Date.parse(proof.expires_at)-Date.parse(proof.verified_at)>24*3600000) fail('owner read-only staging proof is absent, expired, or invalid'); const release=proof.release_policy,allowedRefs=release?.allowed_environment_branches?.[environment]; if(release?.repository!=='developing-today/code'||release?.branch!=='main'||release?.branch_protected!==true||release?.required_pull_request_reviews!==true||release?.force_push_disabled!==true||release?.admin_bypass_disabled!==true||release?.environment_reviewers_required?.[environment]!==true||release?.self_review_disabled?.[environment]!==true||!Array.isArray(allowedRefs)||!same(allowedRefs,['main'])||typeof release?.evidence_ref!=='string'||release.evidence_ref.trim().length<3) fail('trusted protected-main or deployment-environment approval proof is absent or invalid'); const target=proof.targets?.[worker]; diff --git a/pm-stack/private-laptop-bridge/release-contract.test.mjs b/pm-stack/private-laptop-bridge/release-contract.test.mjs index f8f5f4609c..ca8fb9b235 100644 --- a/pm-stack/private-laptop-bridge/release-contract.test.mjs +++ b/pm-stack/private-laptop-bridge/release-contract.test.mjs @@ -1,6 +1,7 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import {assertDeployable,assertDryRunPayload,assertEffectivePayload,assertExactVersion,assertLatestServing,assertPreflight,assertUploadRun,assertVersionStillMatches,makeHandoff,provenanceDigest,verifyPromotionProvenance} from './release-contract.mjs'; +import {readFile} from 'node:fs/promises'; +import {assertDeployable,assertDeploymentCreated,assertDryRunPayload,assertEffectivePayload,assertExactVersion,assertLatestServing,assertPreflight,assertUploadRun,assertVersionStillMatches,makeHandoff,provenanceDigest,verifyPromotionProvenance} from './release-contract.mjs'; const uuid='01234567-89ab-cdef-0123-456789abcdef', old='11111111-2222-3333-4444-555555555555'; const sha='a'.repeat(40), cd='b'.repeat(64), bd='c'.repeat(64), pd='e'.repeat(64), acct='d'.repeat(32); @@ -61,17 +62,25 @@ test('trusted workflow run must be exact successful main upload attempt',()=>{ test('stale historical deployment cannot mask a newer wrong or split deployment',()=>{ const deployments=rows=>JSON.stringify({success:true,result:rows}); - const serving={id:'new',created_on:'2026-11-22T12:00:00Z',versions:[{version_id:uuid,percentage:100}]}; - const oldServing={id:'old',created_on:'2026-11-22T11:00:00Z',versions:[{version_id:uuid,percentage:100}]}; - assert.equal(assertLatestServing(deployments([oldServing,serving]),uuid),true); - assert.throws(()=>assertLatestServing(deployments([oldServing,{...serving,versions:[{version_id:old,percentage:100}]}]),uuid),/latest deployment/); - assert.throws(()=>assertLatestServing(deployments([oldServing,{...serving,versions:[{version_id:uuid,percentage:50},{version_id:old,percentage:50}]}]),uuid),/latest deployment/); - assert.throws(()=>assertLatestServing(deployments([oldServing,{...serving,versions:[{version_id:uuid,percentage:100},{version_id:old,percentage:0}]}]),uuid),/latest deployment/); + const deploymentId='22222222-2222-3333-4444-555555555555'; + const serving={id:deploymentId,created_on:'2026-11-22T12:00:00Z',versions:[{version_id:uuid,percentage:100}]}; + const oldServing={id:old,created_on:'2026-11-22T11:00:00Z',versions:[{version_id:uuid,percentage:100}]}; + assert.equal(assertLatestServing(deployments([oldServing,serving]),uuid,deploymentId),true); + assert.throws(()=>assertLatestServing(deployments([oldServing,{...serving,id:'33333333-2222-3333-4444-555555555555'}]),uuid,deploymentId),/latest deployment/); + assert.throws(()=>assertLatestServing(deployments([oldServing,{...serving,versions:[{version_id:old,percentage:100}]}]),uuid,deploymentId),/latest deployment/); + assert.throws(()=>assertLatestServing(deployments([oldServing,{...serving,versions:[{version_id:uuid,percentage:50},{version_id:old,percentage:50}]}]),uuid,deploymentId),/latest deployment/); + assert.throws(()=>assertLatestServing(deployments([oldServing,{...serving,versions:[{version_id:uuid,percentage:100},{version_id:old,percentage:0}]}]),uuid,deploymentId),/latest deployment/); +}); + +test('deployment create response must return the exact 100 percent deployment identity',()=>{ + const deploymentId='22222222-2222-3333-4444-555555555555'; + assert.equal(assertDeploymentCreated(JSON.stringify({success:true,result:{id:deploymentId,versions:[{version_id:uuid,percentage:100}]}}),uuid),deploymentId); + for(const body of [{success:false,result:{id:deploymentId,versions:[{version_id:uuid,percentage:100}]}},{success:true,result:{id:'bad',versions:[{version_id:uuid,percentage:100}]}},{success:true,result:{id:deploymentId,versions:[{version_id:old,percentage:100}]}},{success:true,result:{id:deploymentId,versions:[{version_id:uuid,percentage:99}]}}]) assert.throws(()=>assertDeploymentCreated(JSON.stringify(body),uuid)); }); test('read-only owner proof fails closed for missing, stale, public or unexpected callers',()=>{ const now=Date.parse('2026-11-22T12:00:00Z'); - const good={schema:1,verified:true,account_id:acct,reviewed_by:'owner@example.com',verified_at:'2026-11-22T11:00:00Z',expires_at:'2026-11-22T13:00:00Z',evidence_ref:'review-1',release_policy:{repository:'developing-today/code',branch:'main',branch_protected:true,required_pull_request_reviews:true,force_push_disabled:true,admin_bypass_disabled:true,environment_reviewers_required:{'cloudflare-staging':true,'cloudflare-staging-smoke':true},self_review_disabled:{'cloudflare-staging':true,'cloudflare-staging-smoke':true},allowed_environment_branches:{'cloudflare-staging':['main'],'cloudflare-staging-smoke':['main']},evidence_ref:'policy-review-1'},targets:{'private-laptop-bridge-staging':{environment:'cloudflare-staging',exists:true,script_id:'private-laptop-bridge-staging',account_id:acct,application_enabled:false,workers_dev:false,preview_urls:false,routes:[],custom_domains:[],observability:{enabled:false,logs:false,traces:false},limits:{cpu_ms:10},gateway_forward_policy_ids:[],gateway_caller_ids:[],variables:{ENABLED:'false',GATEWAY_HOST:'private-bridge-staging.invalid',GATEWAY_ACCOUNT_ID:'',GATEWAY_POLICY_ID:'',GATEWAY_IDENTITY_EMAIL:'',GATEWAY_POSTURE_ID:'',BRIDGE_REGISTRY:''},bindings:[{name:'BRIDGE',type:'durable_object_namespace',class_name:'PrivateLaptopBridge',namespace_id:'1'.repeat(32)}],do:{worker_name:'private-laptop-bridge-staging',class_name:'PrivateLaptopBridge',storage:'sqlite',export_state:'created',migration_tag:'v1',pending_migrations:false,namespace_id:'1'.repeat(32)}}}}; + const good={schema:1,verified:true,account_id:acct,verified_at:'2026-11-22T11:00:00Z',expires_at:'2026-11-22T13:00:00Z',evidence_ref:'review-1',release_policy:{repository:'developing-today/code',branch:'main',branch_protected:true,required_pull_request_reviews:true,force_push_disabled:true,admin_bypass_disabled:true,environment_reviewers_required:{'cloudflare-staging':true,'cloudflare-staging-smoke':true},self_review_disabled:{'cloudflare-staging':true,'cloudflare-staging-smoke':true},allowed_environment_branches:{'cloudflare-staging':['main'],'cloudflare-staging-smoke':['main']},evidence_ref:'policy-review-1'},targets:{'private-laptop-bridge-staging':{environment:'cloudflare-staging',exists:true,script_id:'private-laptop-bridge-staging',account_id:acct,application_enabled:false,workers_dev:false,preview_urls:false,routes:[],custom_domains:[],observability:{enabled:false,logs:false,traces:false},limits:{cpu_ms:10},gateway_forward_policy_ids:[],gateway_caller_ids:[],variables:{ENABLED:'false',GATEWAY_HOST:'private-bridge-staging.invalid',GATEWAY_ACCOUNT_ID:'',GATEWAY_POLICY_ID:'',GATEWAY_IDENTITY_EMAIL:'',GATEWAY_POSTURE_ID:'',BRIDGE_REGISTRY:''},bindings:[{name:'BRIDGE',type:'durable_object_namespace',class_name:'PrivateLaptopBridge',namespace_id:'1'.repeat(32)}],do:{worker_name:'private-laptop-bridge-staging',class_name:'PrivateLaptopBridge',storage:'sqlite',export_state:'created',migration_tag:'v1',pending_migrations:false,namespace_id:'1'.repeat(32)}}}}; assert.equal(assertPreflight(good,{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now}),true); assert.throws(()=>assertPreflight({...good,verified:false},{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now}),/absent, expired, or invalid/); assert.throws(()=>assertPreflight({...good,expires_at:'2026-11-22T11:59:59Z'},{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now}),/absent, expired, or invalid/); @@ -90,7 +99,7 @@ test('Versions release proof separately requires an existing Worker and its read const now=Date.parse('2026-11-22T12:00:00Z'); const policy={repository:'developing-today/code',branch:'main',branch_protected:true,required_pull_request_reviews:true,force_push_disabled:true,admin_bypass_disabled:true,environment_reviewers_required:{'cloudflare-staging':true},self_review_disabled:{'cloudflare-staging':true},allowed_environment_branches:{'cloudflare-staging':['main']},evidence_ref:'policy-review-1'}; const bridge={environment:'cloudflare-staging',exists:true,script_id:'private-laptop-bridge-staging',account_id:acct,application_enabled:false,workers_dev:false,preview_urls:false,routes:[],custom_domains:[],observability:{enabled:false,logs:false,traces:false},limits:{cpu_ms:10},gateway_forward_policy_ids:[],gateway_caller_ids:[],variables:{ENABLED:'false',GATEWAY_HOST:'private-bridge-staging.invalid',GATEWAY_ACCOUNT_ID:'',GATEWAY_POLICY_ID:'',GATEWAY_IDENTITY_EMAIL:'',GATEWAY_POSTURE_ID:'',BRIDGE_REGISTRY:''},bindings:[{name:'BRIDGE',type:'durable_object_namespace',class_name:'PrivateLaptopBridge',namespace_id:'1'.repeat(32)}],do:{worker_name:'private-laptop-bridge-staging',class_name:'PrivateLaptopBridge',storage:'sqlite',export_state:'created',migration_tag:'v1',pending_migrations:false,namespace_id:'1'.repeat(32)}}; - const makeProof=(target=bridge)=>({schema:1,verified:true,account_id:acct,reviewed_by:'owner@example.com',verified_at:'2026-11-22T11:00:00Z',expires_at:'2026-11-22T13:00:00Z',evidence_ref:'worker-review-1',release_policy:policy,targets:{'private-laptop-bridge-staging':target}}); + const makeProof=(target=bridge)=>({schema:1,verified:true,account_id:acct,verified_at:'2026-11-22T11:00:00Z',expires_at:'2026-11-22T13:00:00Z',evidence_ref:'worker-review-1',release_policy:policy,targets:{'private-laptop-bridge-staging':target}}); const check=(proof)=>assertPreflight(proof,{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now}); assert.equal(check(makeProof()),true); assert.throws(()=>check(makeProof({...bridge,exists:false})),/exact private disabled target/); @@ -105,6 +114,19 @@ test('Versions release proof separately requires an existing Worker and its read ]) assert.throws(()=>check(makeProof({...bridge,...change})),/same-Worker SQLite Durable Object namespace and completed v1 migration state/); }); +test('tracked preflight fixture is redacted and never substitutes for private owner proof',async()=>{ + const text=await readFile(new URL('./staging-preflight.json',import.meta.url),'utf8'),fixture=JSON.parse(text); + assert.equal(fixture.verified,false); + assert.equal(fixture.account_id,''); + assert.equal('reviewed_by' in fixture,false); + assert.doesNotMatch(text,/@/); + for(const target of Object.values(fixture.targets)) { + assert.equal(target.account_id,''); + assert.equal(target.do?.namespace_id??'',''); + assert.ok(target.bindings.every(binding=>binding.namespace_id==='')); + } +}); + test('CI dry-run verifies the effective private Build Output but does not claim account route proof',()=>{ const bridge='env.BRIDGE (PrivateLaptopBridge, defined in private-laptop-bridge-staging)\nenv.ENABLED ("false")\nenv.BRIDGE_REGISTRY ("")\n--dry-run: exiting now.'; assert.equal(assertDryRunPayload(bridge,{worker:'private-laptop-bridge-staging',mode:'bridge'}),true); diff --git a/pm-stack/private-laptop-bridge/staging-preflight.json b/pm-stack/private-laptop-bridge/staging-preflight.json index e6a125a662..2ec0e3ca34 100644 --- a/pm-stack/private-laptop-bridge/staging-preflight.json +++ b/pm-stack/private-laptop-bridge/staging-preflight.json @@ -2,7 +2,6 @@ "schema": 1, "verified": false, "account_id": "", - "reviewed_by": "", "verified_at": "", "expires_at": "", "evidence_ref": "", From e049234766cd45e2020d1beb039f2109b7f61f38 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 00:18:17 +0000 Subject: [PATCH 12/33] Document empty Worker init scope blockers --- pm-stack/private-laptop-bridge/DISCOVERY.md | 48 +++++++++++++++---- .../private-laptop-bridge/VERIFICATION.md | 30 ++++++++++++ 2 files changed, 68 insertions(+), 10 deletions(-) diff --git a/pm-stack/private-laptop-bridge/DISCOVERY.md b/pm-stack/private-laptop-bridge/DISCOVERY.md index 87a1ea2b2c..12ba2a3433 100644 --- a/pm-stack/private-laptop-bridge/DISCOVERY.md +++ b/pm-stack/private-laptop-bridge/DISCOVERY.md @@ -185,16 +185,44 @@ must independently confirm full account ID/ownership and existence of the exact Worker named by that GitHub Environment, then verify the resulting token cannot read or edit another Worker. No target was probed in this work session. -There is no permitted bootstrap path in this release workflow. The exact -`cf@1.0.0-rc.1` package is pinned in the lockfile and contains the -`@cloudflare/deploy-helpers@0.27.2` versions-upload checks. They reject a -missing Worker with “You cannot upload a new version of a Worker that does not -yet exist” before the Versions API upload. The Cloudflare Workers deployment -docs likewise state that the first upload must use a deploy command. This task -allows only an initial Versions upload, so do not substitute `cf deploy`, -Wrangler deploy, a direct API request, or a separate create workflow. The -existing-Worker precheck and the CLI both fail closed if either exact target is -absent. No bootstrap command was run or added. +**Smoke Worker bootstrap is newly authorized as an empty metadata-only init,** +separate from the Versions release workflow. Cloudflare's official API exposes +`POST /accounts/{account_id}/workers/workers` to create a Worker metadata +object, while its script `PUT /workers/scripts/{script_name}` creates and +deploys a version to 100% immediately. The latter is not a safe substitute for +the requested empty init. The metadata endpoint supports disabling the +`workers.dev` subdomain, previews, logs and observability in its creation +payload, and returns a null `deployed_on` for a Worker that has never been +deployed. Sources: [Create Worker API](https://developers.cloudflare.com/api/resources/workers/subresources/beta/subresources/workers/methods/create/), +[Script Upload API](https://developers.cloudflare.com/api/resources/workers/subresources/scripts/methods/update/), +[Workers deployment behavior](https://developers.cloudflare.com/workers/platform/infrastructure-as-code/). + +**The init workflow is blocked and was not added or dispatched.** Cloudflare's +Create Worker API accepts `Workers Admin` or `Workers Scripts Write`; the +existing planned per-Worker Editor token for `cloudflare-staging-smoke` is not +one of those permissions and cannot create an absent Worker. Those documented +permissions are account-level, not scoped by the API to this single future +Worker. No protected, separately scoped bootstrap credential or verified +GitHub environment configuration is available in this repo. Reusing or +widening the routine Worker token, adding an account-wide credential to Actions, +or referencing an unverified new GitHub environment would violate the stated +boundary. GitHub admits `workflow_dispatch` only after the workflow exists on +the default branch ([GitHub's `workflow_dispatch` docs](https://docs.github.com/actions/managing-workflow-runs/manually-running-a-workflow)); +a PR branch cannot run the requested main-only job. No such merge or dispatch +was attempted. + +The requested route absence proof also needs account zone/route inventory: +the Worker metadata response includes domain/reference details but does not +provide an authoritative list of Workers routes, and the Routes API is +zone-scoped. Cloudflare documents `Workers Metadata Read-Only` or `Workers +Routes Read` for route listing and `Zone Read` for enumerating zones ([route +API](https://developers.cloudflare.com/api/resources/workers/subresources/routes/methods/list/), +[zone API](https://developers.cloudflare.com/api/resources/zones/methods/list/)). +The current narrow Worker token cannot prove that no stale route in any account +zone names this Worker. Therefore there is no safe check-then-create-and-verify +sequence to run with the currently approved credentials. +The existing-Worker precheck and pinned `cf@1.0.0-rc.1` Versions upload still +fail closed for a missing target. No init or Versions upload was run. The real bridge has an additional Versions API constraint. Its Build Output declares `PrivateLaptopBridge` as a new SQLite Durable Object export and binds diff --git a/pm-stack/private-laptop-bridge/VERIFICATION.md b/pm-stack/private-laptop-bridge/VERIFICATION.md index 15304f2630..1124866e75 100644 --- a/pm-stack/private-laptop-bridge/VERIFICATION.md +++ b/pm-stack/private-laptop-bridge/VERIFICATION.md @@ -188,3 +188,33 @@ network isolation. The workflow YAML parsed with PyYAML and all embedded `run:` blocks passed `bash -n` after substituting GitHub expressions. `actionlint` was unavailable. + +### Empty smoke Worker init request (2026-11-23) + +Drew authorized an empty Worker metadata init for only +`private-laptop-bridge-smoke`. Official Cloudflare docs distinguish +`POST /accounts/{account_id}/workers/workers` (metadata-only Worker creation) +from `PUT /accounts/{account_id}/workers/scripts/{script_name}` (script upload, +which implicitly creates and deploys a version). The metadata endpoint allows +the request to disable `subdomain.enabled`, `subdomain.previews_enabled`, +observability, and logpush. It returns `deployed_on: null` when the Worker has +never been deployed. Sources: [Create Worker API](https://developers.cloudflare.com/api/resources/workers/subresources/beta/subresources/workers/methods/create/), +[Upload Worker API](https://developers.cloudflare.com/api/resources/workers/subresources/scripts/methods/update/), +[Cloudflare's create/deploy API notes](https://developers.cloudflare.com/workers/platform/infrastructure-as-code/). + +No init workflow or provider action was run. The metadata create API accepts +`Workers Admin` or `Workers Scripts Write`; it does not list the planned +per-Worker Editor permission. Account-wide create credentials cannot be put +into the repository's Actions environment under the instruction against broad +token disclosure. The current environment's protection and credentials were +not read or changed. Moreover, proving that no route refers to this new name +requires enumerating all account zones (`Zone Read`) and their routes +(`Workers Metadata Read-Only` or `Workers Routes Read`, plus `Zone Read`; see +[route API](https://developers.cloudflare.com/api/resources/workers/subresources/routes/methods/list/) +and [zone API](https://developers.cloudflare.com/api/resources/zones/methods/list/)); +the narrow Worker credential cannot prove this, and those scopes were not granted. The +`workflow_dispatch` workflow is not on the default branch yet, so its required +main-only admission cannot be exercised from this draft. No secret, provider +setting, route, version, or deployment was changed, and no smoke version upload +was attempted. The bootstrap path remains blocked pending a credential and +read-only proof arrangement that satisfy these scope limits. From 2e4c9f68bf61963bd20a28572127d31a19f2150d Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 00:20:08 +0000 Subject: [PATCH 13/33] Clarify Worker init API compatibility blocker --- pm-stack/private-laptop-bridge/DISCOVERY.md | 7 +++++++ pm-stack/private-laptop-bridge/VERIFICATION.md | 11 +++++++++++ 2 files changed, 18 insertions(+) diff --git a/pm-stack/private-laptop-bridge/DISCOVERY.md b/pm-stack/private-laptop-bridge/DISCOVERY.md index 12ba2a3433..692136ccb3 100644 --- a/pm-stack/private-laptop-bridge/DISCOVERY.md +++ b/pm-stack/private-laptop-bridge/DISCOVERY.md @@ -221,6 +221,13 @@ API](https://developers.cloudflare.com/api/resources/workers/subresources/routes The current narrow Worker token cannot prove that no stale route in any account zone names this Worker. Therefore there is no safe check-then-create-and-verify sequence to run with the currently approved credentials. +There is also an API compatibility proof missing: the metadata create endpoint +is in Cloudflare's Beta Workers API (`/workers/workers/{worker_id}/versions`), +while the pinned `cf workers versions create` uses the Scripts API +(`/workers/scripts/{script_name}/versions`). The official API reference +documents both surfaces separately and does not state that creating a Beta +Worker makes it an existing Script for the pinned `cf` precheck/upload path. +This is an inference from the published endpoint surfaces, not a live result. The existing-Worker precheck and pinned `cf@1.0.0-rc.1` Versions upload still fail closed for a missing target. No init or Versions upload was run. diff --git a/pm-stack/private-laptop-bridge/VERIFICATION.md b/pm-stack/private-laptop-bridge/VERIFICATION.md index 1124866e75..f016385847 100644 --- a/pm-stack/private-laptop-bridge/VERIFICATION.md +++ b/pm-stack/private-laptop-bridge/VERIFICATION.md @@ -218,3 +218,14 @@ main-only admission cannot be exercised from this draft. No secret, provider setting, route, version, or deployment was changed, and no smoke version upload was attempted. The bootstrap path remains blocked pending a credential and read-only proof arrangement that satisfy these scope limits. + +One further compatibility question remains unproven: the metadata creation +endpoint is in the Beta Workers API and its versions path uses immutable +`worker_id` (`/workers/workers/{worker_id}/versions`); pinned `cf` uses the +separate Scripts API path keyed by `script_name` +(`/workers/scripts/{script_name}/versions`). The published [Workers API +reference](https://developers.cloudflare.com/api/resources/workers/) does not +document that a Beta Worker created with the metadata endpoint is recognized +as a Script by `cf`'s precheck and upload path. This is an API-surface inference, +not an observed provider result. It must be resolved in a synthetic or otherwise +approved environment before any smoke init/upload attempt. From 7593d77152d555da1a91551b8f139f2d614a55bb Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 00:37:13 +0000 Subject: [PATCH 14/33] Add guarded smoke Worker metadata bootstrap --- .../private-laptop-bridge-smoke-init.yml | 34 +++ pm-stack/private-laptop-bridge/DISCOVERY.md | 72 ++++--- .../private-laptop-bridge/VERIFICATION.md | 58 ++--- .../private-laptop-bridge/bootstrap-smoke.mjs | 198 ++++++++++++++++++ .../bootstrap-smoke.test.mjs | 156 ++++++++++++++ 5 files changed, 461 insertions(+), 57 deletions(-) create mode 100644 .github/workflows/private-laptop-bridge-smoke-init.yml create mode 100644 pm-stack/private-laptop-bridge/bootstrap-smoke.mjs create mode 100644 pm-stack/private-laptop-bridge/bootstrap-smoke.test.mjs diff --git a/.github/workflows/private-laptop-bridge-smoke-init.yml b/.github/workflows/private-laptop-bridge-smoke-init.yml new file mode 100644 index 0000000000..6c7ec1b4ca --- /dev/null +++ b/.github/workflows/private-laptop-bridge-smoke-init.yml @@ -0,0 +1,34 @@ +name: Initialize empty private laptop bridge smoke Worker + +on: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: private-laptop-bridge-smoke-init + cancel-in-progress: false + +jobs: + initialize: + if: github.repository == 'developing-today/code' && github.ref == 'refs/heads/main' && github.event_name == 'workflow_dispatch' + environment: cloudflare-smoke-bootstrap + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 1 + persist-credentials: false + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + with: + node-version: 24.22.0 + - name: Run offline bootstrap contract tests + run: node --test --test-reporter=spec pm-stack/private-laptop-bridge/bootstrap-smoke.test.mjs + - name: Create only the fixed empty Worker and verify it read-only + env: + CF_SMOKE_INIT_ACCOUNT_ID: ${{ secrets.CF_SMOKE_INIT_ACCOUNT_ID }} + CF_SMOKE_INIT_WRITE_TOKEN: ${{ secrets.CF_SMOKE_INIT_WRITE_TOKEN }} + CF_SMOKE_INIT_READ_TOKEN: ${{ secrets.CF_SMOKE_INIT_READ_TOKEN }} + run: node pm-stack/private-laptop-bridge/bootstrap-smoke.mjs diff --git a/pm-stack/private-laptop-bridge/DISCOVERY.md b/pm-stack/private-laptop-bridge/DISCOVERY.md index 692136ccb3..4e34430417 100644 --- a/pm-stack/private-laptop-bridge/DISCOVERY.md +++ b/pm-stack/private-laptop-bridge/DISCOVERY.md @@ -197,39 +197,47 @@ deployed. Sources: [Create Worker API](https://developers.cloudflare.com/api/res [Script Upload API](https://developers.cloudflare.com/api/resources/workers/subresources/scripts/methods/update/), [Workers deployment behavior](https://developers.cloudflare.com/workers/platform/infrastructure-as-code/). -**The init workflow is blocked and was not added or dispatched.** Cloudflare's -Create Worker API accepts `Workers Admin` or `Workers Scripts Write`; the -existing planned per-Worker Editor token for `cloudflare-staging-smoke` is not -one of those permissions and cannot create an absent Worker. Those documented -permissions are account-level, not scoped by the API to this single future -Worker. No protected, separately scoped bootstrap credential or verified -GitHub environment configuration is available in this repo. Reusing or -widening the routine Worker token, adding an account-wide credential to Actions, -or referencing an unverified new GitHub environment would violate the stated -boundary. GitHub admits `workflow_dispatch` only after the workflow exists on -the default branch ([GitHub's `workflow_dispatch` docs](https://docs.github.com/actions/managing-workflow-runs/manually-running-a-workflow)); -a PR branch cannot run the requested main-only job. No such merge or dispatch -was attempted. - -The requested route absence proof also needs account zone/route inventory: -the Worker metadata response includes domain/reference details but does not -provide an authoritative list of Workers routes, and the Routes API is -zone-scoped. Cloudflare documents `Workers Metadata Read-Only` or `Workers -Routes Read` for route listing and `Zone Read` for enumerating zones ([route -API](https://developers.cloudflare.com/api/resources/workers/subresources/routes/methods/list/), +**The separate smoke init workflow is implemented but not dispatched.** +[`private-laptop-bridge-smoke-init.yml`](../../.github/workflows/private-laptop-bridge-smoke-init.yml) +has no inputs, accepts only the protected default-branch `workflow_dispatch` +context, checks out the dispatch SHA (no caller-selected ref), and hard-codes +`private-laptop-bridge-smoke`. It uses the dedicated `cloudflare-smoke-bootstrap` +environment, not the routine release environment. The pinned Node script uses +only built-in APIs. It checks account ID suffix `cbfa`, inventories all account +zones and routes, and is idempotent: a safe existing empty Worker is verified +without writing; an absent Worker gets one metadata-only Beta Create Worker +POST; any mismatch fails without repair or retry. Read-only verification then +requires disabled `workers.dev` and preview URLs, null `deployed_on`, no +versions, no deployments, no custom domains and no account route targeting the +name. The only write is that one POST; this workflow contains no code or +Versions upload step. + +The environment must be configured and protected on `main` before a dispatch: +required reviewer approval, self-review disabled, and environment-only secrets +`CF_SMOKE_INIT_ACCOUNT_ID`, `CF_SMOKE_INIT_WRITE_TOKEN`, and +`CF_SMOKE_INIT_READ_TOKEN`. The write token must be short-lived and limited to +Cloudflare `Workers Scripts Write` (the Create Worker endpoint's minimum +documented write permission); it is separate from the routine +`cloudflare-staging-smoke` Individual Workers Editor credential. The read-only +token must cover Worker metadata/version/deployment read, `Zone Read`, and +`Workers Metadata Read-Only` for complete route enumeration. Missing or +unauthorized credentials fail before any create. No GitHub environment or +secret was read, created, or changed here. GitHub requires the workflow to be +on the default branch before `workflow_dispatch` can run ([GitHub docs](https://docs.github.com/actions/managing-workflow-runs/manually-running-a-workflow)); +the draft PR cannot yet run it. No merge or dispatch was attempted. + +The route check uses Cloudflare's paginated account zone list and zone-scoped +Worker Routes API, failing closed if any page or route read is unavailable +([route API](https://developers.cloudflare.com/api/resources/workers/subresources/routes/methods/list/), [zone API](https://developers.cloudflare.com/api/resources/zones/methods/list/)). -The current narrow Worker token cannot prove that no stale route in any account -zone names this Worker. Therefore there is no safe check-then-create-and-verify -sequence to run with the currently approved credentials. -There is also an API compatibility proof missing: the metadata create endpoint -is in Cloudflare's Beta Workers API (`/workers/workers/{worker_id}/versions`), -while the pinned `cf workers versions create` uses the Scripts API -(`/workers/scripts/{script_name}/versions`). The official API reference -documents both surfaces separately and does not state that creating a Beta -Worker makes it an existing Script for the pinned `cf` precheck/upload path. -This is an inference from the published endpoint surfaces, not a live result. -The existing-Worker precheck and pinned `cf@1.0.0-rc.1` Versions upload still -fail closed for a missing target. No init or Versions upload was run. +The [Sep. 2025 New Workers API changelog](https://developers.cloudflare.com/changelog/post/2025-09-03-new-workers-api/) +explicitly demonstrates metadata-only Worker creation, Beta Worker version +creation by returned ID, and the legacy `/scripts/{name}/deployments` API using +the returned Worker name. This supports resource identity across the new Worker +and legacy deployment APIs. It does not document the pinned `cf` Scripts +Versions upload cold-start path. That compatibility remains a separate check: +`cf` can be run only after the init action has successfully completed, and this +work did not dispatch either action or access Cloudflare. The real bridge has an additional Versions API constraint. Its Build Output declares `PrivateLaptopBridge` as a new SQLite Durable Object export and binds diff --git a/pm-stack/private-laptop-bridge/VERIFICATION.md b/pm-stack/private-laptop-bridge/VERIFICATION.md index f016385847..282dcedd6f 100644 --- a/pm-stack/private-laptop-bridge/VERIFICATION.md +++ b/pm-stack/private-laptop-bridge/VERIFICATION.md @@ -202,30 +202,38 @@ never been deployed. Sources: [Create Worker API](https://developers.cloudflare. [Upload Worker API](https://developers.cloudflare.com/api/resources/workers/subresources/scripts/methods/update/), [Cloudflare's create/deploy API notes](https://developers.cloudflare.com/workers/platform/infrastructure-as-code/). -No init workflow or provider action was run. The metadata create API accepts -`Workers Admin` or `Workers Scripts Write`; it does not list the planned -per-Worker Editor permission. Account-wide create credentials cannot be put -into the repository's Actions environment under the instruction against broad -token disclosure. The current environment's protection and credentials were -not read or changed. Moreover, proving that no route refers to this new name -requires enumerating all account zones (`Zone Read`) and their routes -(`Workers Metadata Read-Only` or `Workers Routes Read`, plus `Zone Read`; see -[route API](https://developers.cloudflare.com/api/resources/workers/subresources/routes/methods/list/) -and [zone API](https://developers.cloudflare.com/api/resources/zones/methods/list/)); -the narrow Worker credential cannot prove this, and those scopes were not granted. The -`workflow_dispatch` workflow is not on the default branch yet, so its required -main-only admission cannot be exercised from this draft. No secret, provider -setting, route, version, or deployment was changed, and no smoke version upload -was attempted. The bootstrap path remains blocked pending a credential and -read-only proof arrangement that satisfy these scope limits. +The init action and dependency-minimal verifier are implemented in the draft; +no init workflow or provider action was run. The write token required by the +official Create Worker endpoint is short-lived `Workers Scripts Write`, +separate from the routine per-Worker Editor credential. The dedicated protected +environment is `cloudflare-smoke-bootstrap` with environment-only secrets +`CF_SMOKE_INIT_ACCOUNT_ID`, `CF_SMOKE_INIT_WRITE_TOKEN`, and +`CF_SMOKE_INIT_READ_TOKEN`. The last token requires Worker metadata/version/ +deployment read, `Zone Read`, and `Workers Metadata Read-Only` for the complete +route scan. The workflow checks required secrets and the account suffix before +network calls; the script uses the read-only token for every GET and the write +token only for its single metadata-create POST. The environment and credentials +were not read or changed. Because `workflow_dispatch` must be on the default +branch before it can run, this draft cannot dispatch it yet; no merge or +dispatch was attempted. No Cloudflare resource or setting was changed, and no +smoke version upload was attempted. + +The script covers synthetic missing/existing target, exact target/account, +authorization failure, public/preview/domain exposure, route conflict, +create/readback identity mismatch, empty versus non-empty version/deployment +history, and missing credential behavior. Its only provider write path is the +one exact Beta `POST /workers/workers` call; it never updates, deletes, uploads +code, creates a version/deployment, or changes routes/settings. Cloudflare's +[Sep. 2025 New Workers API changelog](https://developers.cloudflare.com/changelog/post/2025-09-03-new-workers-api/) +supports creating the metadata Worker then using the returned name for the +legacy deployment API. The exact pinned `cf workers versions create` cold-start +path remains deliberately separate and unverified; no live or CLI upload was +attempted. One further compatibility question remains unproven: the metadata creation -endpoint is in the Beta Workers API and its versions path uses immutable -`worker_id` (`/workers/workers/{worker_id}/versions`); pinned `cf` uses the -separate Scripts API path keyed by `script_name` -(`/workers/scripts/{script_name}/versions`). The published [Workers API -reference](https://developers.cloudflare.com/api/resources/workers/) does not -document that a Beta Worker created with the metadata endpoint is recognized -as a Script by `cf`'s precheck and upload path. This is an API-surface inference, -not an observed provider result. It must be resolved in a synthetic or otherwise -approved environment before any smoke init/upload attempt. +endpoint is in the Beta Workers API and its version path uses Worker ID +(`/workers/workers/{worker_id}/versions`); pinned `cf` uses the Scripts API +path keyed by `script_name` (`/workers/scripts/{script_name}/versions`). The +changelog demonstrates cross-surface identity for deployments but not the +pinned `cf` cold version upload. This remains unverified and is not inferred +from a synthetic API fixture. diff --git a/pm-stack/private-laptop-bridge/bootstrap-smoke.mjs b/pm-stack/private-laptop-bridge/bootstrap-smoke.mjs new file mode 100644 index 0000000000..45e348c4ce --- /dev/null +++ b/pm-stack/private-laptop-bridge/bootstrap-smoke.mjs @@ -0,0 +1,198 @@ +#!/usr/bin/env node +// Create the smoke Worker metadata object only. No script/version/deployment, +// routes, domains, workers.dev setting changes, or settings updates are made. + +export const API = 'https://api.cloudflare.com/client/v4'; +export const ACCOUNT_SUFFIX = 'cbfa'; +export const WORKER_NAME = 'private-laptop-bridge-smoke'; +const PAGE_SIZE = 50; +const VERSION_PAGE_SIZE = 100; + +export const CREATE_BODY = Object.freeze({ + name: WORKER_NAME, + logpush: false, + observability: Object.freeze({ enabled: false }), + subdomain: Object.freeze({ enabled: false, previews_enabled: false }), +}); + +function fail(message) { throw new Error(message); } + +export function validateInputs({ accountId, writeToken, readToken }) { + if (!/^[a-f0-9]{32}$/i.test(accountId ?? '') || !accountId.toLowerCase().endsWith(ACCOUNT_SUFFIX)) { + fail('bootstrap account ID is missing or not the approved account'); + } + if (typeof writeToken !== 'string' || writeToken.length < 20) fail('bootstrap write credential is missing'); + if (typeof readToken !== 'string' || readToken.length < 20) fail('bootstrap read-only credential is missing'); +} + +function parseEnvelope(response, payload) { + if (!payload || typeof payload !== 'object' || Array.isArray(payload)) fail('Cloudflare returned an invalid response'); + if (!response.ok || payload.success !== true) { + const status = response.status; + fail(status === 401 || status === 403 + ? `Cloudflare authorization denied (HTTP ${status})` + : `Cloudflare API request failed (HTTP ${status})`); + } + if (!Object.hasOwn(payload, 'result')) fail('Cloudflare response omitted result'); + return payload.result; +} + +async function requestWithInfo(fetchImpl, url, token, { method = 'GET', body, allowWorkerNotFound = false } = {}) { + let response; + try { + response = await fetchImpl(url, { + method, + headers: { + authorization: `Bearer ${token}`, + accept: 'application/json', + ...(body === undefined ? {} : { 'content-type': 'application/json' }), + }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + redirect: 'error', + signal: AbortSignal.timeout(15_000), + }); + } catch { + fail('Cloudflare API request failed before a verified response; do not retry creation automatically'); + } + + let payload; + try { payload = await response.json(); } catch { fail(`Cloudflare returned invalid JSON (HTTP ${response.status})`); } + if (response.status === 404 && allowWorkerNotFound) { + if (payload?.success === false && Array.isArray(payload.errors) && payload.errors.length > 0 && + payload.errors.every(e => typeof e?.code === 'number' && /not found|does not exist|unknown worker/i.test(String(e.message)))) { + return { absent: true, resultInfo: payload.result_info }; + } + } + return { result: parseEnvelope(response, payload), resultInfo: payload.result_info }; +} + +async function request(fetchImpl, accountId, token, path, options = {}) { + return requestWithInfo(fetchImpl, `${API}/accounts/${encodeURIComponent(accountId)}${path}`, token, options); +} + +function assertWorker(worker) { + if (!worker || typeof worker !== 'object' || Array.isArray(worker)) fail('Worker readback is missing or malformed'); + if (worker.name !== WORKER_NAME || !/^[a-f0-9]{32}$/i.test(worker.id ?? '')) fail('Worker identity does not match the fixed smoke target'); + if (worker.logpush !== false || worker.observability?.enabled !== false) fail('Worker telemetry metadata is not explicitly disabled'); + if (worker.subdomain?.enabled !== false || worker.subdomain?.previews_enabled !== false) fail('Worker public subdomain or preview URL is enabled'); + if (!Object.hasOwn(worker, 'deployed_on') || worker.deployed_on !== null) fail('Worker already has or may have a deployment'); + if (!worker.references || !Array.isArray(worker.references.domains) || worker.references.domains.length !== 0) fail('Worker has a custom domain or domain state could not be verified'); + return worker; +} + +async function listAll(fetchImpl, accountId, readToken, pathname, pageSize, params = {}) { + const all = []; + let expectedTotal; + for (let page = 1; page <= 100; page += 1) { + const query = new URLSearchParams({ ...params, page: String(page), per_page: String(pageSize) }); + const { result, resultInfo } = await request(fetchImpl, accountId, readToken, `${pathname}?${query}`); + if (!Array.isArray(result)) fail('Cloudflare list response was not an array'); + all.push(...result); + if (!resultInfo || !Number.isInteger(resultInfo.total_pages) || resultInfo.total_pages < 0 || resultInfo.total_pages > 100 || + !Number.isInteger(resultInfo.total_count) || resultInfo.total_count < 0) { + fail('Cloudflare pagination metadata is missing or invalid'); + } + if (expectedTotal === undefined) expectedTotal = resultInfo.total_count; + if (resultInfo.total_count !== expectedTotal) fail('Cloudflare list changed during pagination'); + if (resultInfo.total_pages === 0 && page === 1 && expectedTotal === 0 && all.length === 0) return all; + if (resultInfo.total_pages < page) fail('Cloudflare pagination metadata is missing or invalid'); + if (page >= resultInfo.total_pages) { + if (all.length !== expectedTotal) fail('Cloudflare list did not return its complete item count'); + return all; + } + } + fail('Cloudflare pagination exceeded the hard page bound'); +} + +async function listZones(fetchImpl, accountId, readToken) { + const all = []; + let expectedTotal; + for (let page = 1; page <= 100; page += 1) { + const query = new URLSearchParams({ + 'account.id': accountId, + type: 'full,partial,secondary,internal', + page: String(page), + per_page: String(PAGE_SIZE), + }); + // Keep result_info for complete pagination proof. + const url = `${API}/zones?${query}`; + const { result, resultInfo } = await requestWithInfo(fetchImpl, url, readToken); + if (!Array.isArray(result)) fail('Cloudflare zone response was not an array'); + all.push(...result); + if (!resultInfo || !Number.isInteger(resultInfo.total_pages) || resultInfo.total_pages < 0 || resultInfo.total_pages > 100 || + !Number.isInteger(resultInfo.total_count) || resultInfo.total_count < 0) { + fail('Cloudflare zone pagination metadata is missing or invalid'); + } + if (expectedTotal === undefined) expectedTotal = resultInfo.total_count; + if (resultInfo.total_count !== expectedTotal) fail('Cloudflare zone inventory changed during pagination'); + if (resultInfo.total_pages === 0 && page === 1 && expectedTotal === 0 && all.length === 0) return all; + if (resultInfo.total_pages < page) fail('Cloudflare zone pagination metadata is missing or invalid'); + if (page >= resultInfo.total_pages) { + if (all.length !== expectedTotal) fail('Cloudflare zone inventory is incomplete'); + return all; + } + } + fail('Cloudflare zone pagination exceeded the hard page bound'); +} + +async function assertNoRoutes(fetchImpl, accountId, readToken) { + const zones = await listZones(fetchImpl, accountId, readToken); + for (const zone of zones) { + if (typeof zone?.id !== 'string' || !zone.id) fail('Cloudflare zone inventory contains an invalid zone ID'); + const { result } = await requestWithInfo(fetchImpl, `${API}/zones/${encodeURIComponent(zone.id)}/workers/routes`, readToken); + if (!Array.isArray(result)) fail('Cloudflare route response was not an array'); + if (result.some(route => route?.script === WORKER_NAME)) fail('A Cloudflare route already targets the smoke Worker'); + } +} + +async function assertNoVersionsAndDeployments(fetchImpl, accountId, readToken, workerId) { + const versions = await listAll(fetchImpl, accountId, readToken, `/workers/workers/${encodeURIComponent(workerId)}/versions`, VERSION_PAGE_SIZE); + if (versions.length !== 0) fail('Smoke Worker already has a version; no upload or deployment was attempted'); + const { result, resultInfo } = await request(fetchImpl, accountId, readToken, `/workers/scripts/${encodeURIComponent(WORKER_NAME)}/deployments?page=1&per_page=100`); + if (!result || !Array.isArray(result.deployments) || result.deployments.length !== 0 || resultInfo?.total_count !== 0) { + fail('Smoke Worker deployment history is non-empty or unverifiable'); + } +} + +async function readWorker(fetchImpl, accountId, readToken) { + const response = await request(fetchImpl, accountId, readToken, `/workers/workers/${encodeURIComponent(WORKER_NAME)}`, { allowWorkerNotFound: true }); + return response.absent ? null : assertWorker(response.result); +} + +export async function bootstrapSmoke({ accountId, writeToken, readToken, fetchImpl = fetch }) { + validateInputs({ accountId, writeToken, readToken }); + + const before = await readWorker(fetchImpl, accountId, readToken); + if (before) { + await assertNoRoutes(fetchImpl, accountId, readToken); + await assertNoVersionsAndDeployments(fetchImpl, accountId, readToken, before.id); + return 'already-present'; + } + + // The complete account route inventory is checked immediately before the + // only write. Any read/scope/pagination error exits before creation. + await assertNoRoutes(fetchImpl, accountId, readToken); + const created = await request(fetchImpl, accountId, writeToken, '/workers/workers', { method: 'POST', body: CREATE_BODY }); + assertWorker(created.result); + + // Re-read using the read-only token, never the create credential. + const after = await readWorker(fetchImpl, accountId, readToken); + if (!after || after.id !== created.result.id) fail('Created Worker identity does not match read-only provider readback'); + await assertNoRoutes(fetchImpl, accountId, readToken); + await assertNoVersionsAndDeployments(fetchImpl, accountId, readToken, after.id); + return 'created'; +} + +if (process.argv[1] && new URL(import.meta.url).pathname === process.argv[1]) { + try { + const status = await bootstrapSmoke({ + accountId: process.env.CF_SMOKE_INIT_ACCOUNT_ID, + writeToken: process.env.CF_SMOKE_INIT_WRITE_TOKEN, + readToken: process.env.CF_SMOKE_INIT_READ_TOKEN, + }); + console.log(`Smoke Worker init preflight passed (${status}); no code or deployment was uploaded.`); + } catch (error) { + console.error(error instanceof Error ? error.message : 'Smoke Worker initialization failed'); + process.exitCode = 1; + } +} diff --git a/pm-stack/private-laptop-bridge/bootstrap-smoke.test.mjs b/pm-stack/private-laptop-bridge/bootstrap-smoke.test.mjs new file mode 100644 index 0000000000..e065c8a670 --- /dev/null +++ b/pm-stack/private-laptop-bridge/bootstrap-smoke.test.mjs @@ -0,0 +1,156 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { bootstrapSmoke, CREATE_BODY, WORKER_NAME } from './bootstrap-smoke.mjs'; + +const accountId = `${'a'.repeat(28)}cbfa`; +const writeToken = 'synthetic-write-token-000000'; +const readToken = 'synthetic-read-token-0000000'; +const workerId = '0123456789abcdef0123456789abcdef'; +const safeWorker = () => ({ + id: workerId, + name: WORKER_NAME, + logpush: false, + observability: { enabled: false }, + subdomain: { enabled: false, previews_enabled: false }, + deployed_on: null, + references: { domains: [] }, +}); +const ok = (result, result_info = { total_pages: 1, page: 1, per_page: 50, total_count: Array.isArray(result) ? result.length : 0 }) => + new Response(JSON.stringify({ success: true, result, result_info }), { status: 200 }); +const missing = () => new Response(JSON.stringify({ success: false, errors: [{ code: 10007, message: 'Worker not found' }] }), { status: 404 }); + +function fixture({ worker = null, createdWorker = safeWorker(), route = null, zones = [{ id: 'z'.repeat(32) }], zoneResultInfo, versions = [], versionResultInfo, deployments = [], createResult = null, authFailure = false, writeAuthFailure = false } = {}) { + const state = { worker, createdWorker, route, zones, zoneResultInfo, versions, versionResultInfo, deployments, createResult, authFailure, writeAuthFailure, calls: [] }; + const fetchImpl = async (url, init = {}) => { + const parsed = new URL(url); + const method = init.method ?? 'GET'; + const token = init.headers?.authorization; + state.calls.push({ url: parsed, method, token, body: init.body ? JSON.parse(init.body) : undefined }); + if (state.authFailure && token === `Bearer ${readToken}`) { + return new Response(JSON.stringify({ success: false, errors: [{ code: 10000, message: 'Authentication error' }] }), { status: 403 }); + } + if (state.writeAuthFailure && method === 'POST' && token === `Bearer ${writeToken}`) { + return new Response(JSON.stringify({ success: false, errors: [{ code: 10000, message: 'Authentication error' }] }), { status: 403 }); + } + if (parsed.pathname === '/client/v4/zones') return ok(state.zones, state.zoneResultInfo ?? undefined); + if (parsed.pathname.endsWith('/workers/routes')) return ok(state.route ? [state.route] : []); + if (parsed.pathname.endsWith(`/workers/workers/${WORKER_NAME}`) && method === 'GET') { + return state.worker ? ok(state.worker, undefined) : missing(); + } + if (parsed.pathname.endsWith('/workers/workers') && method === 'POST') { + state.worker = state.createdWorker; + return ok(state.createResult ?? state.createdWorker, undefined); + } + if (parsed.pathname.endsWith(`/workers/workers/${workerId}/versions`)) return ok(state.versions, state.versionResultInfo ?? undefined); + if (parsed.pathname.endsWith(`/workers/scripts/${WORKER_NAME}/deployments`)) { + return ok({ deployments: state.deployments }, { total_pages: 1, page: 1, per_page: 100, total_count: state.deployments.length }); + } + throw new Error(`unexpected synthetic request ${method} ${parsed.pathname}`); + }; + return { state, fetchImpl }; +} + +test('missing target gets exactly one metadata-only create, then read-only no-exposure proof', async () => { + const { state, fetchImpl } = fixture(); + assert.equal(await bootstrapSmoke({ accountId, writeToken, readToken, fetchImpl }), 'created'); + const writes = state.calls.filter(call => call.method !== 'GET'); + assert.equal(writes.length, 1); + assert.equal(writes[0].method, 'POST'); + assert.equal(writes[0].token, `Bearer ${writeToken}`); + assert.deepEqual(writes[0].body, CREATE_BODY); + assert.ok(state.calls.filter(call => call.method === 'GET').every(call => call.token === `Bearer ${readToken}`)); + assert.equal(state.calls.some(call => call.url.pathname.includes('/scripts/') && call.method !== 'GET'), false); +}); + +test('provider zero-page pagination is accepted only with an explicit zero item count', async () => { + const { state, fetchImpl } = fixture({ + zones: [], + zoneResultInfo: { total_pages: 0, page: 1, per_page: 50, total_count: 0 }, + }); + assert.equal(await bootstrapSmoke({ accountId, writeToken, readToken, fetchImpl }), 'created'); + assert.equal(state.calls.some(call => call.method === 'POST'), true); +}); + +test('already existing safe target is idempotent and is never overwritten', async () => { + const { state, fetchImpl } = fixture({ worker: safeWorker() }); + assert.equal(await bootstrapSmoke({ accountId, writeToken, readToken, fetchImpl }), 'already-present'); + assert.equal(state.calls.some(call => call.method === 'POST'), false); +}); + +test('wrong account suffix and wrong returned target fail closed', async () => { + const { state, fetchImpl } = fixture(); + await assert.rejects(bootstrapSmoke({ accountId: `${'b'.repeat(28)}beef`, writeToken, readToken, fetchImpl }), /not the approved account/); + assert.equal(state.calls.length, 0); + + const wrong = safeWorker(); wrong.name = 'some-other-worker'; + const existing = fixture({ worker: wrong }); + await assert.rejects(bootstrapSmoke({ accountId, writeToken, readToken, fetchImpl: existing.fetchImpl }), /identity does not match/); + assert.equal(existing.state.calls.some(call => call.method === 'POST'), false); +}); + +test('read authorization failure is not mistaken for an absent Worker', async () => { + const { state, fetchImpl } = fixture({ authFailure: true }); + await assert.rejects(bootstrapSmoke({ accountId, writeToken, readToken, fetchImpl }), /authorization denied/); + assert.equal(state.calls.some(call => call.method === 'POST'), false); +}); + +test('create authorization failure is bounded to one denied create attempt', async () => { + const { state, fetchImpl } = fixture({ writeAuthFailure: true }); + await assert.rejects(bootstrapSmoke({ accountId, writeToken, readToken, fetchImpl }), /authorization denied/); + assert.equal(state.calls.filter(call => call.method === 'POST').length, 1); + assert.equal(state.calls.filter(call => call.method !== 'GET').length, 1); +}); + +test('pre-existing public Worker fails closed without edits', async t => { + for (const change of [ + w => { w.subdomain.enabled = true; }, + w => { w.subdomain.previews_enabled = true; }, + w => { w.deployed_on = '2026-11-23T00:00:00Z'; }, + w => { w.references.domains = [{ hostname: 'example.invalid' }]; }, + ]) { + const worker = safeWorker(); change(worker); + const { state, fetchImpl } = fixture({ worker }); + await t.test('unsafe existing state', async () => { + await assert.rejects(bootstrapSmoke({ accountId, writeToken, readToken, fetchImpl })); + assert.equal(state.calls.some(call => call.method === 'POST'), false); + }); + } +}); + +test('a route already pointing at the fixed name blocks creation', async () => { + const { state, fetchImpl } = fixture({ zones: [{ id: 'z'.repeat(32) }], route: { id: 'synthetic-route', pattern: 'example.invalid/*', script: WORKER_NAME } }); + await assert.rejects(bootstrapSmoke({ accountId, writeToken, readToken, fetchImpl }), /route already targets/); + assert.equal(state.calls.some(call => call.method === 'POST'), false); +}); + +test('incomplete account route inventory blocks creation', async () => { + const { state, fetchImpl } = fixture({ zoneResultInfo: { total_pages: 1, page: 1, per_page: 50, total_count: 2 } }); + await assert.rejects(bootstrapSmoke({ accountId, writeToken, readToken, fetchImpl }), /inventory is incomplete/); + assert.equal(state.calls.some(call => call.method === 'POST'), false); +}); + +test('create response identity mismatch fails without follow-up mutation', async () => { + const mismatch = safeWorker(); mismatch.id = 'ffffffffffffffffffffffffffffffff'; + const { state, fetchImpl } = fixture({ createResult: mismatch, createdWorker: safeWorker() }); + await assert.rejects(bootstrapSmoke({ accountId, writeToken, readToken, fetchImpl }), /Created Worker identity/); + assert.equal(state.calls.filter(call => call.method === 'POST').length, 1); +}); + +test('zero versions and zero deployments are required; any deployment blocks', async t => { + const { state, fetchImpl } = fixture({ worker: safeWorker() }); + assert.equal(await bootstrapSmoke({ accountId, writeToken, readToken, fetchImpl }), 'already-present'); + assert.ok(state.calls.some(call => call.url.pathname.endsWith('/versions'))); + assert.ok(state.calls.some(call => call.url.pathname.endsWith('/deployments'))); + + const deployed = fixture({ worker: safeWorker(), deployments: [{ id: 'synthetic-deployment' }] }); + await t.test('non-empty deployment history is denied', async () => { + await assert.rejects(bootstrapSmoke({ accountId, writeToken, readToken, fetchImpl: deployed.fetchImpl }), /deployment history/); + assert.equal(deployed.state.calls.some(call => call.method === 'POST'), false); + }); +}); + +test('missing read-only credential fails before any API call', async () => { + const { state, fetchImpl } = fixture(); + await assert.rejects(bootstrapSmoke({ accountId, writeToken, readToken: '', fetchImpl }), /read-only credential is missing/); + assert.equal(state.calls.length, 0); +}); From 5cfce29984796f1b2db1c51cfeb0741db31ed5f2 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 00:53:06 +0000 Subject: [PATCH 15/33] Harden private smoke Worker bootstrap proof --- .../private-laptop-bridge-smoke-init.yml | 8 +- pm-stack/private-laptop-bridge/DISCOVERY.md | 21 +- .../private-laptop-bridge/VERIFICATION.md | 21 +- .../private-laptop-bridge/bootstrap-smoke.mjs | 85 +++++-- .../bootstrap-smoke.test.mjs | 212 ++++++++++++------ 5 files changed, 248 insertions(+), 99 deletions(-) diff --git a/.github/workflows/private-laptop-bridge-smoke-init.yml b/.github/workflows/private-laptop-bridge-smoke-init.yml index 6c7ec1b4ca..afc10c4151 100644 --- a/.github/workflows/private-laptop-bridge-smoke-init.yml +++ b/.github/workflows/private-laptop-bridge-smoke-init.yml @@ -13,12 +13,15 @@ concurrency: jobs: initialize: if: github.repository == 'developing-today/code' && github.ref == 'refs/heads/main' && github.event_name == 'workflow_dispatch' + # Configure this environment out of band with required reviewers and main-only + # rules. This workflow cannot verify or create those GitHub environment rules. environment: cloudflare-smoke-bootstrap runs-on: ubuntu-24.04 timeout-minutes: 10 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: + ref: ${{ github.sha }} fetch-depth: 1 persist-credentials: false - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 @@ -28,7 +31,10 @@ jobs: run: node --test --test-reporter=spec pm-stack/private-laptop-bridge/bootstrap-smoke.test.mjs - name: Create only the fixed empty Worker and verify it read-only env: - CF_SMOKE_INIT_ACCOUNT_ID: ${{ secrets.CF_SMOKE_INIT_ACCOUNT_ID }} + # Both values must be provisioned as protected environment secrets; + # neither is a dispatch input or checked-in account/zone data. + CF_SMOKE_INIT_APPROVED_ACCOUNT_ID: ${{ secrets.CF_SMOKE_INIT_APPROVED_ACCOUNT_ID }} + CF_SMOKE_INIT_EXPECTED_ZONE_IDS: ${{ secrets.CF_SMOKE_INIT_EXPECTED_ZONE_IDS }} CF_SMOKE_INIT_WRITE_TOKEN: ${{ secrets.CF_SMOKE_INIT_WRITE_TOKEN }} CF_SMOKE_INIT_READ_TOKEN: ${{ secrets.CF_SMOKE_INIT_READ_TOKEN }} run: node pm-stack/private-laptop-bridge/bootstrap-smoke.mjs diff --git a/pm-stack/private-laptop-bridge/DISCOVERY.md b/pm-stack/private-laptop-bridge/DISCOVERY.md index 4e34430417..4cf2e64954 100644 --- a/pm-stack/private-laptop-bridge/DISCOVERY.md +++ b/pm-stack/private-laptop-bridge/DISCOVERY.md @@ -203,8 +203,9 @@ has no inputs, accepts only the protected default-branch `workflow_dispatch` context, checks out the dispatch SHA (no caller-selected ref), and hard-codes `private-laptop-bridge-smoke`. It uses the dedicated `cloudflare-smoke-bootstrap` environment, not the routine release environment. The pinned Node script uses -only built-in APIs. It checks account ID suffix `cbfa`, inventories all account -zones and routes, and is idempotent: a safe existing empty Worker is verified +only built-in APIs. It reads the approved full account ID from a protected +environment secret and compares the full zone inventory to a second protected +configuration value. It is idempotent: a safe existing empty Worker is verified without writing; an absent Worker gets one metadata-only Beta Create Worker POST; any mismatch fails without repair or retry. Read-only verification then requires disabled `workers.dev` and preview URLs, null `deployed_on`, no @@ -214,8 +215,15 @@ Versions upload step. The environment must be configured and protected on `main` before a dispatch: required reviewer approval, self-review disabled, and environment-only secrets -`CF_SMOKE_INIT_ACCOUNT_ID`, `CF_SMOKE_INIT_WRITE_TOKEN`, and -`CF_SMOKE_INIT_READ_TOKEN`. The write token must be short-lived and limited to +`CF_SMOKE_INIT_APPROVED_ACCOUNT_ID`, `CF_SMOKE_INIT_EXPECTED_ZONE_IDS`, +`CF_SMOKE_INIT_WRITE_TOKEN`, and `CF_SMOKE_INIT_READ_TOKEN`. The account ID +secret contains the full approved 32-hex ID; the zone inventory secret contains +the exact verified JSON array of all zone IDs (`[]` only when a trusted owner +has confirmed there are no zones). The script checks every returned zone's +owner, uniqueness, complete pagination, and exact match to this protected +inventory. It rejects identical read/write tokens. Only Cloudflare's +documented Worker-specific `404` / error `10007` / `Worker not found` response +counts as absent. The write token must be short-lived and limited to Cloudflare `Workers Scripts Write` (the Create Worker endpoint's minimum documented write permission); it is separate from the routine `cloudflare-staging-smoke` Individual Workers Editor credential. The read-only @@ -229,7 +237,10 @@ the draft PR cannot yet run it. No merge or dispatch was attempted. The route check uses Cloudflare's paginated account zone list and zone-scoped Worker Routes API, failing closed if any page or route read is unavailable ([route API](https://developers.cloudflare.com/api/resources/workers/subresources/routes/methods/list/), -[zone API](https://developers.cloudflare.com/api/resources/zones/methods/list/)). +[zone API](https://developers.cloudflare.com/api/resources/zones/methods/list/)). A +fresh-empty deployment response is accepted only with an explicit empty +`deployments` array; if `result_info.total_count` is present, it must be zero. +Missing deployment-list data alone never counts as an empty history. The [Sep. 2025 New Workers API changelog](https://developers.cloudflare.com/changelog/post/2025-09-03-new-workers-api/) explicitly demonstrates metadata-only Worker creation, Beta Worker version creation by returned ID, and the legacy `/scripts/{name}/deployments` API using diff --git a/pm-stack/private-laptop-bridge/VERIFICATION.md b/pm-stack/private-laptop-bridge/VERIFICATION.md index 282dcedd6f..1aff376633 100644 --- a/pm-stack/private-laptop-bridge/VERIFICATION.md +++ b/pm-stack/private-laptop-bridge/VERIFICATION.md @@ -207,13 +207,20 @@ no init workflow or provider action was run. The write token required by the official Create Worker endpoint is short-lived `Workers Scripts Write`, separate from the routine per-Worker Editor credential. The dedicated protected environment is `cloudflare-smoke-bootstrap` with environment-only secrets -`CF_SMOKE_INIT_ACCOUNT_ID`, `CF_SMOKE_INIT_WRITE_TOKEN`, and -`CF_SMOKE_INIT_READ_TOKEN`. The last token requires Worker metadata/version/ -deployment read, `Zone Read`, and `Workers Metadata Read-Only` for the complete -route scan. The workflow checks required secrets and the account suffix before -network calls; the script uses the read-only token for every GET and the write -token only for its single metadata-create POST. The environment and credentials -were not read or changed. Because `workflow_dispatch` must be on the default +`CF_SMOKE_INIT_APPROVED_ACCOUNT_ID`, `CF_SMOKE_INIT_EXPECTED_ZONE_IDS`, +`CF_SMOKE_INIT_WRITE_TOKEN`, and `CF_SMOKE_INIT_READ_TOKEN`. The first is the +full approved account ID; the second is the exact owner-verified zone ID array. +The last token requires Worker metadata/version/deployment read, `Zone Read`, +and `Workers Metadata Read-Only` for the complete route scan. The script +validates every zone's account owner, uniqueness, pagination, and exact match to +the approved inventory before creating. It rejects identical read and write +tokens and treats only the Worker-specific HTTP 404/error 10007 as absence. +The script uses the read-only token for every GET and the write token only for +its single metadata-create POST. A no-deployment result must contain an explicit +empty `deployments` array; missing optional `result_info` is acceptable only +when that array is present and empty, and any reported nonzero count is denied. +The environment and credentials were not read or changed. Because +`workflow_dispatch` must be on the default branch before it can run, this draft cannot dispatch it yet; no merge or dispatch was attempted. No Cloudflare resource or setting was changed, and no smoke version upload was attempted. diff --git a/pm-stack/private-laptop-bridge/bootstrap-smoke.mjs b/pm-stack/private-laptop-bridge/bootstrap-smoke.mjs index 45e348c4ce..ca3a0f2e4b 100644 --- a/pm-stack/private-laptop-bridge/bootstrap-smoke.mjs +++ b/pm-stack/private-laptop-bridge/bootstrap-smoke.mjs @@ -17,12 +17,26 @@ export const CREATE_BODY = Object.freeze({ function fail(message) { throw new Error(message); } -export function validateInputs({ accountId, writeToken, readToken }) { - if (!/^[a-f0-9]{32}$/i.test(accountId ?? '') || !accountId.toLowerCase().endsWith(ACCOUNT_SUFFIX)) { - fail('bootstrap account ID is missing or not the approved account'); +function parseExpectedZoneIds(value) { + let ids = value; + if (typeof ids === 'string') { + try { ids = JSON.parse(ids); } catch { fail('approved zone inventory configuration is invalid'); } + } + if (!Array.isArray(ids) || ids.some(id => typeof id !== 'string' || !/^[a-f0-9]{32}$/i.test(id))) { + fail('approved zone inventory configuration is missing or invalid'); + } + if (new Set(ids.map(id => id.toLowerCase())).size !== ids.length) fail('approved zone inventory contains duplicate IDs'); + return ids.map(id => id.toLowerCase()).sort(); +} + +export function validateInputs({ approvedAccountId, writeToken, readToken, expectedZoneIds }) { + if (!/^[a-f0-9]{32}$/i.test(approvedAccountId ?? '') || !approvedAccountId.toLowerCase().endsWith(ACCOUNT_SUFFIX)) { + fail('approved account configuration is missing or invalid'); } if (typeof writeToken !== 'string' || writeToken.length < 20) fail('bootstrap write credential is missing'); if (typeof readToken !== 'string' || readToken.length < 20) fail('bootstrap read-only credential is missing'); + if (writeToken === readToken) fail('bootstrap read and write credentials must be distinct'); + return { approvedAccountId, expectedZoneIds: parseExpectedZoneIds(expectedZoneIds) }; } function parseEnvelope(response, payload) { @@ -58,8 +72,8 @@ async function requestWithInfo(fetchImpl, url, token, { method = 'GET', body, al let payload; try { payload = await response.json(); } catch { fail(`Cloudflare returned invalid JSON (HTTP ${response.status})`); } if (response.status === 404 && allowWorkerNotFound) { - if (payload?.success === false && Array.isArray(payload.errors) && payload.errors.length > 0 && - payload.errors.every(e => typeof e?.code === 'number' && /not found|does not exist|unknown worker/i.test(String(e.message)))) { + if (payload?.success === false && Array.isArray(payload.errors) && payload.errors.length === 1 && + payload.errors[0]?.code === 10007 && /^worker not found\.?$/i.test(String(payload.errors[0].message))) { return { absent: true, resultInfo: payload.result_info }; } } @@ -104,9 +118,10 @@ async function listAll(fetchImpl, accountId, readToken, pathname, pageSize, para fail('Cloudflare pagination exceeded the hard page bound'); } -async function listZones(fetchImpl, accountId, readToken) { +async function listZones(fetchImpl, accountId, readToken, expectedZoneIds) { const all = []; let expectedTotal; + let expectedPages; for (let page = 1; page <= 100; page += 1) { const query = new URLSearchParams({ 'account.id': accountId, @@ -118,14 +133,30 @@ async function listZones(fetchImpl, accountId, readToken) { const url = `${API}/zones?${query}`; const { result, resultInfo } = await requestWithInfo(fetchImpl, url, readToken); if (!Array.isArray(result)) fail('Cloudflare zone response was not an array'); + if (result.length > PAGE_SIZE) fail('Cloudflare zone page exceeded the requested bound'); + const pageIds = new Set(all.map(zone => zone.id.toLowerCase())); + for (const zone of result) { + if (typeof zone?.id !== 'string' || !/^[a-f0-9]{32}$/i.test(zone.id) || zone?.account?.id?.toLowerCase() !== accountId.toLowerCase()) { + fail('Cloudflare zone inventory contains an invalid owner or ID'); + } + const id = zone.id.toLowerCase(); + if (pageIds.has(id)) { + fail('Cloudflare zone inventory contains a duplicate ID'); + } + pageIds.add(id); + } all.push(...result); - if (!resultInfo || !Number.isInteger(resultInfo.total_pages) || resultInfo.total_pages < 0 || resultInfo.total_pages > 100 || - !Number.isInteger(resultInfo.total_count) || resultInfo.total_count < 0) { + if (!resultInfo || resultInfo.page !== page || resultInfo.per_page !== PAGE_SIZE || + !Number.isInteger(resultInfo.total_pages) || resultInfo.total_pages < 0 || resultInfo.total_pages > 100 || + !Number.isInteger(resultInfo.total_count) || resultInfo.total_count !== expectedZoneIds.length || + (resultInfo.total_count > 0 && resultInfo.total_pages !== Math.ceil(resultInfo.total_count / PAGE_SIZE)) || + (resultInfo.count !== undefined && resultInfo.count !== result.length)) { fail('Cloudflare zone pagination metadata is missing or invalid'); } if (expectedTotal === undefined) expectedTotal = resultInfo.total_count; - if (resultInfo.total_count !== expectedTotal) fail('Cloudflare zone inventory changed during pagination'); - if (resultInfo.total_pages === 0 && page === 1 && expectedTotal === 0 && all.length === 0) return all; + if (expectedPages === undefined) expectedPages = resultInfo.total_pages; + if (resultInfo.total_count !== expectedTotal || resultInfo.total_pages !== expectedPages) fail('Cloudflare zone inventory changed during pagination'); + if ((resultInfo.total_pages === 0 || resultInfo.total_pages === 1) && page === 1 && expectedTotal === 0 && all.length === 0) return all; if (resultInfo.total_pages < page) fail('Cloudflare zone pagination metadata is missing or invalid'); if (page >= resultInfo.total_pages) { if (all.length !== expectedTotal) fail('Cloudflare zone inventory is incomplete'); @@ -135,21 +166,33 @@ async function listZones(fetchImpl, accountId, readToken) { fail('Cloudflare zone pagination exceeded the hard page bound'); } -async function assertNoRoutes(fetchImpl, accountId, readToken) { - const zones = await listZones(fetchImpl, accountId, readToken); +async function assertNoRoutes(fetchImpl, accountId, readToken, expectedZoneIds) { + const zones = await listZones(fetchImpl, accountId, readToken, expectedZoneIds); + const seen = new Set(); for (const zone of zones) { - if (typeof zone?.id !== 'string' || !zone.id) fail('Cloudflare zone inventory contains an invalid zone ID'); + if (typeof zone?.id !== 'string' || !/^[a-f0-9]{32}$/i.test(zone.id) || zone?.account?.id?.toLowerCase() !== accountId.toLowerCase()) { + fail('Cloudflare zone inventory contains an invalid owner or ID'); + } + const zoneId = zone.id.toLowerCase(); + if (seen.has(zoneId)) fail('Cloudflare zone inventory contains a duplicate ID'); + seen.add(zoneId); const { result } = await requestWithInfo(fetchImpl, `${API}/zones/${encodeURIComponent(zone.id)}/workers/routes`, readToken); if (!Array.isArray(result)) fail('Cloudflare route response was not an array'); if (result.some(route => route?.script === WORKER_NAME)) fail('A Cloudflare route already targets the smoke Worker'); } + const actualIds = [...seen].sort(); + if (actualIds.length !== expectedZoneIds.length || actualIds.some((id, index) => id !== expectedZoneIds[index])) { + fail('Cloudflare zone inventory does not match the approved full-account inventory'); + } } async function assertNoVersionsAndDeployments(fetchImpl, accountId, readToken, workerId) { const versions = await listAll(fetchImpl, accountId, readToken, `/workers/workers/${encodeURIComponent(workerId)}/versions`, VERSION_PAGE_SIZE); if (versions.length !== 0) fail('Smoke Worker already has a version; no upload or deployment was attempted'); const { result, resultInfo } = await request(fetchImpl, accountId, readToken, `/workers/scripts/${encodeURIComponent(WORKER_NAME)}/deployments?page=1&per_page=100`); - if (!result || !Array.isArray(result.deployments) || result.deployments.length !== 0 || resultInfo?.total_count !== 0) { + if (!result || typeof result !== 'object' || Array.isArray(result) || !Object.hasOwn(result, 'deployments') || + !Array.isArray(result.deployments) || result.deployments.length !== 0 || + (resultInfo?.total_count !== undefined && resultInfo.total_count !== 0)) { fail('Smoke Worker deployment history is non-empty or unverifiable'); } } @@ -159,26 +202,27 @@ async function readWorker(fetchImpl, accountId, readToken) { return response.absent ? null : assertWorker(response.result); } -export async function bootstrapSmoke({ accountId, writeToken, readToken, fetchImpl = fetch }) { - validateInputs({ accountId, writeToken, readToken }); +export async function bootstrapSmoke({ approvedAccountId, writeToken, readToken, expectedZoneIds, fetchImpl = fetch }) { + const approved = validateInputs({ approvedAccountId, writeToken, readToken, expectedZoneIds }); + const accountId = approved.approvedAccountId; const before = await readWorker(fetchImpl, accountId, readToken); if (before) { - await assertNoRoutes(fetchImpl, accountId, readToken); + await assertNoRoutes(fetchImpl, accountId, readToken, approved.expectedZoneIds); await assertNoVersionsAndDeployments(fetchImpl, accountId, readToken, before.id); return 'already-present'; } // The complete account route inventory is checked immediately before the // only write. Any read/scope/pagination error exits before creation. - await assertNoRoutes(fetchImpl, accountId, readToken); + await assertNoRoutes(fetchImpl, accountId, readToken, approved.expectedZoneIds); const created = await request(fetchImpl, accountId, writeToken, '/workers/workers', { method: 'POST', body: CREATE_BODY }); assertWorker(created.result); // Re-read using the read-only token, never the create credential. const after = await readWorker(fetchImpl, accountId, readToken); if (!after || after.id !== created.result.id) fail('Created Worker identity does not match read-only provider readback'); - await assertNoRoutes(fetchImpl, accountId, readToken); + await assertNoRoutes(fetchImpl, accountId, readToken, approved.expectedZoneIds); await assertNoVersionsAndDeployments(fetchImpl, accountId, readToken, after.id); return 'created'; } @@ -186,7 +230,8 @@ export async function bootstrapSmoke({ accountId, writeToken, readToken, fetchIm if (process.argv[1] && new URL(import.meta.url).pathname === process.argv[1]) { try { const status = await bootstrapSmoke({ - accountId: process.env.CF_SMOKE_INIT_ACCOUNT_ID, + approvedAccountId: process.env.CF_SMOKE_INIT_APPROVED_ACCOUNT_ID, + expectedZoneIds: process.env.CF_SMOKE_INIT_EXPECTED_ZONE_IDS, writeToken: process.env.CF_SMOKE_INIT_WRITE_TOKEN, readToken: process.env.CF_SMOKE_INIT_READ_TOKEN, }); diff --git a/pm-stack/private-laptop-bridge/bootstrap-smoke.test.mjs b/pm-stack/private-laptop-bridge/bootstrap-smoke.test.mjs index e065c8a670..447a7e378d 100644 --- a/pm-stack/private-laptop-bridge/bootstrap-smoke.test.mjs +++ b/pm-stack/private-laptop-bridge/bootstrap-smoke.test.mjs @@ -3,6 +3,8 @@ import assert from 'node:assert/strict'; import { bootstrapSmoke, CREATE_BODY, WORKER_NAME } from './bootstrap-smoke.mjs'; const accountId = `${'a'.repeat(28)}cbfa`; +const zoneId = '1'.repeat(32); +const expectedZoneIds = [zoneId]; const writeToken = 'synthetic-write-token-000000'; const readToken = 'synthetic-read-token-0000000'; const workerId = '0123456789abcdef0123456789abcdef'; @@ -16,11 +18,13 @@ const safeWorker = () => ({ references: { domains: [] }, }); const ok = (result, result_info = { total_pages: 1, page: 1, per_page: 50, total_count: Array.isArray(result) ? result.length : 0 }) => - new Response(JSON.stringify({ success: true, result, result_info }), { status: 200 }); -const missing = () => new Response(JSON.stringify({ success: false, errors: [{ code: 10007, message: 'Worker not found' }] }), { status: 404 }); + new Response(JSON.stringify({ success: true, result, ...(result_info === undefined ? {} : { result_info }) }), { status: 200 }); +const okNoInfo = result => new Response(JSON.stringify({ success: true, result }), { status: 200 }); +const missing = (code = 10007, message = 'Worker not found.') => + new Response(JSON.stringify({ success: false, errors: [{ code, message }] }), { status: 404 }); -function fixture({ worker = null, createdWorker = safeWorker(), route = null, zones = [{ id: 'z'.repeat(32) }], zoneResultInfo, versions = [], versionResultInfo, deployments = [], createResult = null, authFailure = false, writeAuthFailure = false } = {}) { - const state = { worker, createdWorker, route, zones, zoneResultInfo, versions, versionResultInfo, deployments, createResult, authFailure, writeAuthFailure, calls: [] }; +function fixture({ worker = null, createdWorker = safeWorker(), route = null, zones = [{ id: zoneId, account: { id: accountId } }], zoneResultInfo, zonePages, versions = [], versionResultInfo, deployments = [], deploymentResultInfo, deploymentNoInfo = false, createResult = null, authFailure = false, writeAuthFailure = false, missingCode = 10007, missingMessage = 'Worker not found.' } = {}) { + const state = { worker, createdWorker, route, zones, zoneResultInfo, zonePages, versions, versionResultInfo, deployments, deploymentResultInfo, deploymentNoInfo, createResult, authFailure, writeAuthFailure, missingCode, missingMessage, calls: [] }; const fetchImpl = async (url, init = {}) => { const parsed = new URL(url); const method = init.method ?? 'GET'; @@ -32,27 +36,39 @@ function fixture({ worker = null, createdWorker = safeWorker(), route = null, zo if (state.writeAuthFailure && method === 'POST' && token === `Bearer ${writeToken}`) { return new Response(JSON.stringify({ success: false, errors: [{ code: 10000, message: 'Authentication error' }] }), { status: 403 }); } - if (parsed.pathname === '/client/v4/zones') return ok(state.zones, state.zoneResultInfo ?? undefined); + if (parsed.pathname === '/client/v4/zones') { + if (state.zonePages) { + const page = Number(parsed.searchParams.get('page')); + const result = state.zonePages[page - 1] ?? []; + return ok(result, { total_pages: state.zonePages.length, page, per_page: 50, total_count: state.zonePages.flat().length, count: result.length }); + } + return ok(state.zones, state.zoneResultInfo); + } if (parsed.pathname.endsWith('/workers/routes')) return ok(state.route ? [state.route] : []); if (parsed.pathname.endsWith(`/workers/workers/${WORKER_NAME}`) && method === 'GET') { - return state.worker ? ok(state.worker, undefined) : missing(); + return state.worker ? ok(state.worker, undefined) : missing(state.missingCode, state.missingMessage); } if (parsed.pathname.endsWith('/workers/workers') && method === 'POST') { state.worker = state.createdWorker; return ok(state.createResult ?? state.createdWorker, undefined); } - if (parsed.pathname.endsWith(`/workers/workers/${workerId}/versions`)) return ok(state.versions, state.versionResultInfo ?? undefined); + if (parsed.pathname.endsWith(`/workers/workers/${workerId}/versions`)) return ok(state.versions, state.versionResultInfo); if (parsed.pathname.endsWith(`/workers/scripts/${WORKER_NAME}/deployments`)) { - return ok({ deployments: state.deployments }, { total_pages: 1, page: 1, per_page: 100, total_count: state.deployments.length }); + if (state.deploymentNoInfo) return okNoInfo({ deployments: state.deployments }); + return ok({ deployments: state.deployments }, state.deploymentResultInfo ?? { total_pages: 1, page: 1, per_page: 100, total_count: state.deployments.length }); } throw new Error(`unexpected synthetic request ${method} ${parsed.pathname}`); }; return { state, fetchImpl }; } -test('missing target gets exactly one metadata-only create, then read-only no-exposure proof', async () => { +function run({ fetchImpl, ...overrides }) { + return bootstrapSmoke({ approvedAccountId: accountId, expectedZoneIds, writeToken, readToken, fetchImpl, ...overrides }); +} + +test('missing target creates exactly one metadata-only Worker and verifies exposure read-only', async () => { const { state, fetchImpl } = fixture(); - assert.equal(await bootstrapSmoke({ accountId, writeToken, readToken, fetchImpl }), 'created'); + assert.equal(await run({ fetchImpl }), 'created'); const writes = state.calls.filter(call => call.method !== 'GET'); assert.equal(writes.length, 1); assert.equal(writes[0].method, 'POST'); @@ -62,46 +78,96 @@ test('missing target gets exactly one metadata-only create, then read-only no-ex assert.equal(state.calls.some(call => call.url.pathname.includes('/scripts/') && call.method !== 'GET'), false); }); -test('provider zero-page pagination is accepted only with an explicit zero item count', async () => { - const { state, fetchImpl } = fixture({ - zones: [], - zoneResultInfo: { total_pages: 0, page: 1, per_page: 50, total_count: 0 }, +test('same protected configuration is idempotent for an existing safe target', async () => { + const { state, fetchImpl } = fixture({ worker: safeWorker() }); + assert.equal(await run({ fetchImpl }), 'already-present'); + assert.equal(state.calls.some(call => call.method === 'POST'), false); +}); + +test('full account identity and expected zone inventory are mandatory protected config', async () => { + const { state, fetchImpl } = fixture(); + const wrongAccount = `${'b'.repeat(28)}beef`; + await assert.rejects(run({ fetchImpl, approvedAccountId: wrongAccount }), error => { + assert.match(error.message, /approved account configuration/); + assert.equal(error.message.includes(wrongAccount), false); + return true; }); - assert.equal(await bootstrapSmoke({ accountId, writeToken, readToken, fetchImpl }), 'created'); - assert.equal(state.calls.some(call => call.method === 'POST'), true); + await assert.rejects(run({ fetchImpl, expectedZoneIds: undefined }), /approved zone inventory/); + await assert.rejects(run({ fetchImpl, expectedZoneIds: 'not-json' }), /approved zone inventory/); + assert.equal(state.calls.length, 0); }); -test('already existing safe target is idempotent and is never overwritten', async () => { - const { state, fetchImpl } = fixture({ worker: safeWorker() }); - assert.equal(await bootstrapSmoke({ accountId, writeToken, readToken, fetchImpl }), 'already-present'); - assert.equal(state.calls.some(call => call.method === 'POST'), false); +test('read and write credentials must be different before any request', async () => { + const { state, fetchImpl } = fixture(); + await assert.rejects(run({ fetchImpl, readToken: writeToken }), /must be distinct/); + assert.equal(state.calls.length, 0); }); -test('wrong account suffix and wrong returned target fail closed', async () => { +test('missing credentials fail before any network request', async () => { const { state, fetchImpl } = fixture(); - await assert.rejects(bootstrapSmoke({ accountId: `${'b'.repeat(28)}beef`, writeToken, readToken, fetchImpl }), /not the approved account/); + await assert.rejects(run({ fetchImpl, writeToken: '' }), /write credential is missing/); + await assert.rejects(run({ fetchImpl, readToken: '' }), /read-only credential is missing/); assert.equal(state.calls.length, 0); +}); - const wrong = safeWorker(); wrong.name = 'some-other-worker'; - const existing = fixture({ worker: wrong }); - await assert.rejects(bootstrapSmoke({ accountId, writeToken, readToken, fetchImpl: existing.fetchImpl }), /identity does not match/); - assert.equal(existing.state.calls.some(call => call.method === 'POST'), false); +test('only the documented Worker-specific 404 means absent', async () => { + const generic = fixture({ missingCode: 10000, missingMessage: 'Resource not found' }); + await assert.rejects(run({ fetchImpl: generic.fetchImpl }), /API request failed/); + assert.equal(generic.state.calls.some(call => call.method === 'POST'), false); + + const wrongMessage = fixture({ missingCode: 10007, missingMessage: 'Not found' }); + await assert.rejects(run({ fetchImpl: wrongMessage.fetchImpl }), /API request failed/); + assert.equal(wrongMessage.state.calls.some(call => call.method === 'POST'), false); }); -test('read authorization failure is not mistaken for an absent Worker', async () => { - const { state, fetchImpl } = fixture({ authFailure: true }); - await assert.rejects(bootstrapSmoke({ accountId, writeToken, readToken, fetchImpl }), /authorization denied/); - assert.equal(state.calls.some(call => call.method === 'POST'), false); +test('read and create authorization failures stop without retry', async () => { + const deniedRead = fixture({ authFailure: true }); + await assert.rejects(run({ fetchImpl: deniedRead.fetchImpl }), /authorization denied/); + assert.equal(deniedRead.state.calls.some(call => call.method === 'POST'), false); + + const deniedWrite = fixture({ writeAuthFailure: true }); + await assert.rejects(run({ fetchImpl: deniedWrite.fetchImpl }), /authorization denied/); + assert.equal(deniedWrite.state.calls.filter(call => call.method === 'POST').length, 1); +}); + +test('zone scan requires owner, unique IDs and exact full-account inventory', async t => { + const cases = [ + { zones: [{ id: zoneId, account: { id: 'f'.repeat(32) } }], expected: /owner or ID/ }, + { zones: [{ id: zoneId, account: { id: accountId } }, { id: zoneId, account: { id: accountId } }], expected: /duplicate ID/ }, + { zones: [], expected: /pagination metadata/ }, + { zones: [{ id: zoneId, account: { id: accountId } }], zoneResultInfo: { total_pages: 1, page: 2, per_page: 50, total_count: 1 }, expected: /pagination metadata/ }, + { zones: [{ id: '2'.repeat(32), account: { id: accountId } }], expected: /does not match the approved/ }, + ]; + for (const item of cases) { + await t.test(item.expected.source, async () => { + const f = fixture({ zones: item.zones, zoneResultInfo: item.zoneResultInfo }); + await assert.rejects(run({ fetchImpl: f.fetchImpl }), item.expected); + assert.equal(f.state.calls.some(call => call.method === 'POST'), false); + }); + } }); -test('create authorization failure is bounded to one denied create attempt', async () => { - const { state, fetchImpl } = fixture({ writeAuthFailure: true }); - await assert.rejects(bootstrapSmoke({ accountId, writeToken, readToken, fetchImpl }), /authorization denied/); - assert.equal(state.calls.filter(call => call.method === 'POST').length, 1); - assert.equal(state.calls.filter(call => call.method !== 'GET').length, 1); +test('complete multi-page route inventory is compared to protected zone IDs', async () => { + const ids = Array.from({ length: 51 }, (_, index) => index.toString(16).padStart(32, '0')); + const zones = ids.map(id => ({ id, account: { id: accountId } })); + const f = fixture({ zonePages: [zones.slice(0, 50), zones.slice(50)] }); + assert.equal(await run({ fetchImpl: f.fetchImpl, expectedZoneIds: ids }), 'created'); + const zoneRequests = f.state.calls.filter(call => call.url.pathname === '/client/v4/zones'); + assert.equal(zoneRequests.length, 4); // two complete scans: before and after create }); -test('pre-existing public Worker fails closed without edits', async t => { +test('known zero-zone inventory is accepted only when explicitly configured', async () => { + const f = fixture({ zones: [], zoneResultInfo: { total_pages: 0, page: 1, per_page: 50, total_count: 0 } }); + assert.equal(await bootstrapSmoke({ approvedAccountId: accountId, expectedZoneIds: [], writeToken, readToken, fetchImpl: f.fetchImpl }), 'created'); + assert.equal(f.state.calls.some(call => call.method === 'POST'), true); +}); + +test('wrong target or unsafe existing Worker fails without edits', async t => { + const wrong = safeWorker(); wrong.name = 'some-other-worker'; + const badTarget = fixture({ worker: wrong }); + await assert.rejects(run({ fetchImpl: badTarget.fetchImpl }), /identity does not match/); + assert.equal(badTarget.state.calls.some(call => call.method === 'POST'), false); + for (const change of [ w => { w.subdomain.enabled = true; }, w => { w.subdomain.previews_enabled = true; }, @@ -109,48 +175,62 @@ test('pre-existing public Worker fails closed without edits', async t => { w => { w.references.domains = [{ hostname: 'example.invalid' }]; }, ]) { const worker = safeWorker(); change(worker); - const { state, fetchImpl } = fixture({ worker }); - await t.test('unsafe existing state', async () => { - await assert.rejects(bootstrapSmoke({ accountId, writeToken, readToken, fetchImpl })); - assert.equal(state.calls.some(call => call.method === 'POST'), false); + const f = fixture({ worker }); + await t.test('unsafe Worker state', async () => { + await assert.rejects(run({ fetchImpl: f.fetchImpl })); + assert.equal(f.state.calls.some(call => call.method === 'POST'), false); }); } }); -test('a route already pointing at the fixed name blocks creation', async () => { - const { state, fetchImpl } = fixture({ zones: [{ id: 'z'.repeat(32) }], route: { id: 'synthetic-route', pattern: 'example.invalid/*', script: WORKER_NAME } }); - await assert.rejects(bootstrapSmoke({ accountId, writeToken, readToken, fetchImpl }), /route already targets/); - assert.equal(state.calls.some(call => call.method === 'POST'), false); -}); +test('route conflict and incomplete pagination block creation', async () => { + const routed = fixture({ route: { id: 'route', pattern: 'example.invalid/*', script: WORKER_NAME } }); + await assert.rejects(run({ fetchImpl: routed.fetchImpl }), /route already targets/); + assert.equal(routed.state.calls.some(call => call.method === 'POST'), false); -test('incomplete account route inventory blocks creation', async () => { - const { state, fetchImpl } = fixture({ zoneResultInfo: { total_pages: 1, page: 1, per_page: 50, total_count: 2 } }); - await assert.rejects(bootstrapSmoke({ accountId, writeToken, readToken, fetchImpl }), /inventory is incomplete/); - assert.equal(state.calls.some(call => call.method === 'POST'), false); + const incomplete = fixture({ zoneResultInfo: { total_pages: 1, page: 1, per_page: 50, total_count: 2 } }); + await assert.rejects(run({ fetchImpl: incomplete.fetchImpl }), /pagination metadata/); + assert.equal(incomplete.state.calls.some(call => call.method === 'POST'), false); }); -test('create response identity mismatch fails without follow-up mutation', async () => { +test('create response identity mismatch stops after its single write', async () => { const mismatch = safeWorker(); mismatch.id = 'ffffffffffffffffffffffffffffffff'; - const { state, fetchImpl } = fixture({ createResult: mismatch, createdWorker: safeWorker() }); - await assert.rejects(bootstrapSmoke({ accountId, writeToken, readToken, fetchImpl }), /Created Worker identity/); - assert.equal(state.calls.filter(call => call.method === 'POST').length, 1); + const f = fixture({ createResult: mismatch, createdWorker: safeWorker() }); + await assert.rejects(run({ fetchImpl: f.fetchImpl }), /Created Worker identity/); + assert.equal(f.state.calls.filter(call => call.method === 'POST').length, 1); +}); + +test('empty deployment list is explicit evidence; missing list or conflicting metadata is denied', async t => { + const empty = fixture({ worker: safeWorker(), deploymentNoInfo: true }); + assert.equal(await run({ fetchImpl: empty.fetchImpl }), 'already-present'); + + for (const response of [ + { result: {}, result_info: { total_count: 0 } }, + { result: { deployments: [] }, result_info: { total_count: 1 } }, + { result: { deployments: [{ id: 'deployed' }] }, result_info: undefined }, + ]) { + await t.test('non-empty or unverifiable deployment history', async () => { + const f = fixture({ worker: safeWorker() }); + const original = f.fetchImpl; + f.fetchImpl = async (url, init) => { + if (new URL(url).pathname.endsWith(`/workers/scripts/${WORKER_NAME}/deployments`)) { + return response.result_info === undefined ? okNoInfo(response.result) : ok(response.result, response.result_info); + } + return original(url, init); + }; + await assert.rejects(run({ fetchImpl: f.fetchImpl }), /deployment history/); + assert.equal(f.state.calls.some(call => call.method === 'POST'), false); + }); + } }); -test('zero versions and zero deployments are required; any deployment blocks', async t => { +test('zero versions and deployment history are required', async () => { const { state, fetchImpl } = fixture({ worker: safeWorker() }); - assert.equal(await bootstrapSmoke({ accountId, writeToken, readToken, fetchImpl }), 'already-present'); + assert.equal(await run({ fetchImpl }), 'already-present'); assert.ok(state.calls.some(call => call.url.pathname.endsWith('/versions'))); assert.ok(state.calls.some(call => call.url.pathname.endsWith('/deployments'))); - const deployed = fixture({ worker: safeWorker(), deployments: [{ id: 'synthetic-deployment' }] }); - await t.test('non-empty deployment history is denied', async () => { - await assert.rejects(bootstrapSmoke({ accountId, writeToken, readToken, fetchImpl: deployed.fetchImpl }), /deployment history/); - assert.equal(deployed.state.calls.some(call => call.method === 'POST'), false); - }); -}); - -test('missing read-only credential fails before any API call', async () => { - const { state, fetchImpl } = fixture(); - await assert.rejects(bootstrapSmoke({ accountId, writeToken, readToken: '', fetchImpl }), /read-only credential is missing/); - assert.equal(state.calls.length, 0); + const withVersion = fixture({ worker: safeWorker(), versions: [{ id: 'synthetic-version' }] }); + await assert.rejects(run({ fetchImpl: withVersion.fetchImpl }), /already has a version/); + assert.equal(withVersion.state.calls.some(call => call.method === 'POST'), false); }); From 05cd2063e1330fc37b8c1b63bf8e1d4012e702ce Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 06:17:26 +0000 Subject: [PATCH 16/33] Record latest main reconciliation evidence --- pm-stack/private-laptop-bridge/VERIFICATION.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pm-stack/private-laptop-bridge/VERIFICATION.md b/pm-stack/private-laptop-bridge/VERIFICATION.md index 8873ccef97..d70597d850 100644 --- a/pm-stack/private-laptop-bridge/VERIFICATION.md +++ b/pm-stack/private-laptop-bridge/VERIFICATION.md @@ -247,7 +247,7 @@ from a synthetic API fixture. ## Main reconciliation checkpoint — 2026-11-23 -The bridge draft was reconciled against `main` at `40e0c2ac4418ecb4ecca021f809b87544aeabad0`. The smoke init workflow and its receipt verifier now match `main`; the smoke upload workflow and its active review paths were left exactly as on `main`. The bridge release workflow is now bridge-only, so smoke provisioning/upload remains in its separate main workflows. +The bridge draft was reconciled against `main` at `438f7ad38bacd8c9f04952a6abf9c1cfc1066c0b` (including the intermediate reconciliation at `40e0c2ac4418ecb4ecca021f809b87544aeabad0`). The smoke init workflow and its receipt verifier now match `main`; the smoke upload workflow and its active review paths were left exactly as on `main`. The bridge release workflow is now bridge-only, so smoke provisioning/upload remains in its separate main workflows. Focused local verification on the reconciled tree: From c20f3d96a7d7f4b469aaf38f16184aa3e6d7ceae Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 06:18:57 +0000 Subject: [PATCH 17/33] Format bridge lifecycle notes --- pm-stack/private-laptop-bridge/README.md | 14 ++++++++++---- .../private-laptop-bridge/cloudflare.config.ts | 3 ++- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/pm-stack/private-laptop-bridge/README.md b/pm-stack/private-laptop-bridge/README.md index 697f421ff6..f1e84e6cea 100644 --- a/pm-stack/private-laptop-bridge/README.md +++ b/pm-stack/private-laptop-bridge/README.md @@ -208,10 +208,16 @@ local temporary database fixtures are removed after tests. The unit/property and state-machine tests complement this runtime evidence. No test deploys a Worker, connects to AMD, reads live credentials or installs a service. -`check:staging` runs the pinned `cf` Build Output v1 build, Versions dry run, and effective payload validator, not a deployment. `cloudflare.config.ts` in `bridge` mode is the sole real staging lifecycle definition; `wrangler.staging.jsonc` and `wrangler.jsonc` are parity fixtures tested against it, never release inputs. The smoke Worker is owned by the separate smoke init/upload workflows on `main` and is not selectable in the bridge release workflow. The deployed -candidate's default HTTP handler always denies; only the Gateway RPC entrypoint -can reach the signed bridge, after trusted-context checks. The real Gateway DNS, -device enrollment and TLS-trust path still requires the approval packet's smoke. +`check:staging` runs the pinned `cf` Build Output v1 build, Versions dry run, +and effective payload validator, not a deployment. `cloudflare.config.ts` in +`bridge` mode is the sole real staging lifecycle definition; +`wrangler.staging.jsonc` and `wrangler.jsonc` are parity fixtures tested against +it, never release inputs. The smoke Worker is owned by the separate smoke +init/upload workflows on `main` and is not selectable in the bridge release +workflow. The deployed candidate's default HTTP handler always denies; only the +Gateway RPC entrypoint can reach the signed bridge, after trusted-context +checks. The real Gateway DNS, device enrollment and TLS-trust path still requires +the approval packet's smoke. No automatic PR CI or active schedule is added. The merged smoke init/upload workflows are manual; this branch retains a separate manual bridge release path diff --git a/pm-stack/private-laptop-bridge/cloudflare.config.ts b/pm-stack/private-laptop-bridge/cloudflare.config.ts index 70c1f010cb..4ff736527a 100644 --- a/pm-stack/private-laptop-bridge/cloudflare.config.ts +++ b/pm-stack/private-laptop-bridge/cloudflare.config.ts @@ -12,7 +12,8 @@ const isolated = () => ({ }); // The bridge mode is the sole real staging release definition. It remains disabled -// until owner-approved account, namespace, Gateway, and laptop preflight is complete. +// until owner-approved account, namespace, Gateway, and laptop preflight is +// complete. // The default mode exists only for the separately managed synthetic smoke Worker. export default defineConfig(({mode}) => mode === 'bridge' ? ({ worker: { From f1460a9f53b8dfd11b45ab3a2e3a082c7aabfbe3 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 06:44:59 +0000 Subject: [PATCH 18/33] Use one declarative bridge lifecycle and preflight plan --- pm-stack/private-laptop-bridge/DISCOVERY.md | 67 ++++++------ pm-stack/private-laptop-bridge/README.md | 7 +- pm-stack/private-laptop-bridge/STAGING.md | 102 +++++++++++++++--- .../private-laptop-bridge/VERIFICATION.md | 36 ++++--- .../deployment-config.test.mjs | 30 ++---- .../release-artifact.mjs | 7 +- .../release-contract.mjs | 17 +-- .../release-contract.test.mjs | 49 ++++++--- .../staging-preflight.json | 71 ++++++++++-- pm-stack/private-laptop-bridge/wrangler.jsonc | 12 --- .../wrangler.smoke.jsonc | 18 ---- .../wrangler.staging.jsonc | 22 ---- 12 files changed, 266 insertions(+), 172 deletions(-) delete mode 100644 pm-stack/private-laptop-bridge/wrangler.jsonc delete mode 100644 pm-stack/private-laptop-bridge/wrangler.smoke.jsonc delete mode 100644 pm-stack/private-laptop-bridge/wrangler.staging.jsonc diff --git a/pm-stack/private-laptop-bridge/DISCOVERY.md b/pm-stack/private-laptop-bridge/DISCOVERY.md index 4cf2e64954..1eb6f8b76c 100644 --- a/pm-stack/private-laptop-bridge/DISCOVERY.md +++ b/pm-stack/private-laptop-bridge/DISCOVERY.md @@ -46,7 +46,7 @@ or implemented here. A successful owner-run smoke alone does not make Aster read ## Separate smoke implementation `smoke.mjs` exports `GatewayMiddleware` for trusted Gateway RPC and denies ordinary -HTTP. `wrangler.smoke.jsonc` is disabled with blank IDs and `.invalid` hostname; +HTTP. `cloudflare.config.ts` default mode is disabled with blank IDs and an `.invalid` hostname; no public routes, workers.dev, preview URLs, DO, secrets, storage, service bindings, observability or upstream are configured. It accepts only `GET /smoke/v1` at the pinned HTTPS host, from the pinned Gateway account/policy context, during an @@ -68,7 +68,8 @@ Offline reproduction (Node 24, from this directory): ```sh npm ci node --test smoke.test.mjs -WRANGLER_SEND_METRICS=false npx wrangler deploy --dry-run --config wrangler.smoke.jsonc --outdir .wrangler/smoke-dry-run +cf build +cf workers versions create --worker private-laptop-bridge-smoke --tag offline --message offline --prebuilt --dry-run npm run rehearse ``` @@ -175,8 +176,7 @@ an explicit promotion of a recorded known-good retained UUID. Fix-forward upload a new version and separately promotes it. These actions do not apply Gateway routes, Workers routes/domains, DNS, TLS settings or access policies. -**Target existence is not verified.** The tracked Wrangler configs and `cf` -config give only the proposed names `private-laptop-bridge-smoke` and +**Target existence is not verified.** The tracked `cf` config gives only the proposed names `private-laptop-bridge-smoke` and `private-laptop-bridge-staging`; they prove neither is present in Cloudflare. No current account ID or live metadata was obtained. The first workflow step calls `cf workers get` and fails closed if the selected exact target is absent; it never bootstraps, creates @@ -250,31 +250,33 @@ Versions upload cold-start path. That compatibility remains a separate check: `cf` can be run only after the init action has successfully completed, and this work did not dispatch either action or access Cloudflare. -The real bridge has an additional Versions API constraint. Its Build Output -declares `PrivateLaptopBridge` as a new SQLite Durable Object export and binds -`BRIDGE` to that export. The pinned upload helper rejects pending Durable Object -migrations because Versions upload cannot apply them. It also handles -`ACTOR_BINDING_DEPENDS_ON_EXPORT_CODE` with the explicit explanation that -declarative exports are reconciled only when a version is deployed, so a -namespace for an unprovisioned export cannot exist at upload time. Therefore -the bridge can use this Versions-only release path only if an owner has already -verified that the exact existing `private-laptop-bridge-staging` Worker owns a -created SQLite `PrivateLaptopBridge` namespace and has completed the `v1` -migration, with no pending migration. The `BRIDGE` binding namespace ID must -match that same Worker namespace. The smoke Worker has no Durable Object and -still must already exist. - -`staging-preflight.json` is currently intentionally unverified and empty. CI -checks only validate a future owner-supplied read-only snapshot; the new contract -tests reject a missing Worker, mismatched namespace/class/Worker, an uncreated -export, a different migration tag, and pending migrations. An offline `cf -workers versions create --prebuilt --dry-run` does not exercise these remote -checks: the pinned helper skips API preflight on dry-run, and dry-run builds can -prove only the local Build Output. No live Worker, namespace, migration, route, -Gateway, or Cloudflare account was queried in this session. If the exact target -or completed namespace state is absent or cannot be proven, this workflow has -no allowed path forward; stop for Drew to decide whether the release scope -should change. +The real bridge has a separate initial-deployment constraint. The current config +uses `exports.durableObject({storage: "sqlite"})`, Cloudflare's declarative +Durable Object lifecycle. The pinned `cf workers versions create` path is only +for an existing Worker whose namespace is already provisioned; it cannot create +the first Worker or apply a new export lifecycle. Official `cf` docs direct the +initial deployment and new export creation through `cf deploy`. The first deploy +therefore needs a separately reviewed, one-time manual owner path using the same +`cloudflare.config.ts` Build Output; it must not add a Beta API create, raw PUT, +Wrangler deploy, or legacy `migrations` fallback. + +That first deploy is not authorized or runnable yet. It must be preceded and +followed by a fresh independent read-only inventory proving the exact account, +fixed Worker name, complete zone/route inventory, Worker domains, workers.dev +and preview flags, Gateway rules/callers, bindings, versions/deployment, and +Durable Object namespace/export. It must refuse an existing Worker before the +write, deploy with `ENABLED=false`, empty registry/Gateway identifiers, no +runtime secrets, no routes/domains/triggers, `workersDev:false`, and +`previewUrls:false`, then verify the same SQLite namespace ID from both the +Worker binding and account namespace listing. Any unexpected resource, route, +preview, binding, export, or deployment state stops the sequence; no automatic +delete or fallback is allowed. + +The existing routine Versions-only release must stay blocked until the post-first +deploy readback is independently recorded as a fresh owner proof and the +protected environment and token scopes are actually established. The current +`staging-preflight.json` remains `verified:false`; no live Worker, namespace, +route, Gateway or account state was read in this session. Do not create or store a Workers-product/whole-account token in GitHub. If the required targets and bridge namespace are already in place and independently @@ -289,9 +291,10 @@ Offline results on the current follow-up commit (recorded in the PR): Node 24.22 `cf workers versions create --prebuilt --dry-run`. The bridge dry-run reports only the DO namespace binding `BRIDGE -> PrivateLaptopBridge`, disabled `ENABLED=false`, placeholder Gateway identifiers and empty registry; it creates -nothing. `deployment-config.test.mjs` compares the local/staging Wrangler DO -class and SQLite migration declarations against the cf config. Gateway runtime -unit tests and smoke tests pass. These results prove local Build Output and +nothing. `deployment-config.test.mjs` verifies that the `cf` config is the sole +declarative DO lifecycle source and contains the expected SQLite export. It +does not prove provider state. Gateway runtime unit tests and smoke tests pass. +These results prove local Build Output and configuration consistency, not Cloudflare account reachability, live target existence, deployment, Gateway routing or laptop readiness. diff --git a/pm-stack/private-laptop-bridge/README.md b/pm-stack/private-laptop-bridge/README.md index f1e84e6cea..5506e34cbf 100644 --- a/pm-stack/private-laptop-bridge/README.md +++ b/pm-stack/private-laptop-bridge/README.md @@ -210,10 +210,9 @@ connects to AMD, reads live credentials or installs a service. `check:staging` runs the pinned `cf` Build Output v1 build, Versions dry run, and effective payload validator, not a deployment. `cloudflare.config.ts` in -`bridge` mode is the sole real staging lifecycle definition; -`wrangler.staging.jsonc` and `wrangler.jsonc` are parity fixtures tested against -it, never release inputs. The smoke Worker is owned by the separate smoke -init/upload workflows on `main` and is not selectable in the bridge release +`bridge` mode is the sole real staging lifecycle definition. No Wrangler JSONC +deployment or migration fallback is kept. The smoke Worker is owned by the +separate smoke init/upload workflows on `main` and is not selectable in the bridge release workflow. The deployed candidate's default HTTP handler always denies; only the Gateway RPC entrypoint can reach the signed bridge, after trusted-context checks. The real Gateway DNS, device enrollment and TLS-trust path still requires diff --git a/pm-stack/private-laptop-bridge/STAGING.md b/pm-stack/private-laptop-bridge/STAGING.md index bfa253e770..da17f02656 100644 --- a/pm-stack/private-laptop-bridge/STAGING.md +++ b/pm-stack/private-laptop-bridge/STAGING.md @@ -16,28 +16,106 @@ artifact and then serves it only after explicit promotion. There is no cold Worker/bootstrap fallback in this release path. The already-merged `private-laptop-bridge-smoke-init.yml` and `private-laptop-bridge-smoke-upload.yml` are a separate synthetic smoke lifecycle and do not select or provision the -bridge target. The `wrangler*.jsonc` files remain parity fixtures for offline -contract tests; they are not release inputs. +bridge target. `cloudflare.config.ts` is the only deployment lifecycle source; +no Wrangler JSONC deployment or migration fallback is kept. The bridge config currently has `ENABLED=false`, empty registry and Gateway placeholders, no routes/domains/triggers, workers.dev and preview URLs disabled, 10 ms CPU limit, and observability/logging/traces off. It binds the staging -Worker to its own SQLite `PrivateLaptopBridge` Durable Object export. The -tracked `staging-preflight.json` remains `verified:false`, `exists:false`, with +Worker to its own declarative SQLite `PrivateLaptopBridge` Durable Object +export. The tracked `staging-preflight.json` remains `verified:false`, `exists:false`, with empty account, namespace and evidence IDs. Local config/build tests prove only that this disabled artifact is internally shaped as expected; they do not prove a live Worker or namespace exists, that Gateway cannot reach it, or that the route is private. No staging Worker was provisioned and no activation was approved or attempted. -Before any bridge upload or promotion, an owner must supply reviewed protected -environment evidence for the exact account/Worker, existing same-Worker SQLite -namespace and completed migration, disabled/no-public resource inventory, -Gateway caller inventory, protected-main/environment rules, and approved -credential scope. Before enablement, Drew must separately approve the specific -activation permissions and the credential-free private transport check must -pass from the intended Aster runner and AMD laptop. Keep the fallback until the -end-to-end authorized Fleet operations pass on Drew's laptop. +The candidate handoff receipt is schema 2 and carries an account-ID SHA-256 +digest instead of the account ID itself. The protected proof still checks the +full ID inside the gated environment; this redaction does not weaken target +matching. Schema 1 receipts are rejected. + +### First disabled deployment plan + +Routine releases remain versions-only and must refuse an absent Worker or +Durable Object namespace. A one-time first deployment, if later authorized, +must use the same `cloudflare.config.ts` `bridge` mode and pinned `cf` Build +Output. Cloudflare's `cf` guidance uses `cf deploy` to create the initial +Worker and apply the declarative DO export lifecycle; this is the initial +deployment step, not a second configuration or a legacy migration fallback. +[cf project deploy](https://developers.cloudflare.com/cf/projects/) · +[cf and Durable Object lifecycle](https://developers.cloudflare.com/cf/wrangler/reference/#convert-durable-object-migrations) + +The only proposed command sequence is a manual owner-controlled procedure, not +a GitHub workflow: + +```sh +npm ci --ignore-scripts --no-audit --no-fund +./node_modules/.bin/cf build --mode bridge +./node_modules/.bin/cf deploy --mode bridge --prebuilt --dry-run +# Only after the separate approval and all preflight gates: +./node_modules/.bin/cf deploy --mode bridge --prebuilt +``` + +The final command writes a deployment and provisions the `PrivateLaptopBridge` +SQLite export. It must run only with `ENABLED=false`, empty Gateway IDs and +registry, no runtime secrets, no routes/domains/triggers, `workersDev:false`, +`previewUrls:false`, logs/traces off, and the 10 ms CPU limit from the reviewed +build. Do not pass `--force`, `--secrets-file`, or `--dispatch-namespace`. A +successful local `--dry-run` proves config shape only; it is not permission to +run the write. + +Before the write, a separately authenticated read-only reviewer must confirm the +exact account and that the exact Worker name is absent; inventory every account +zone and its routes; list account Worker domains; read Gateway rules and callers; +and verify there is no name collision or existing binding to the class. Record +complete pagination and timestamps. If the Worker exists, an API response is +ambiguous, any pagination is incomplete, or any route/domain/Gateway path could +reach the target, stop without changing it. + +Immediately after the write, independently repeat the full inventory and verify +the same Worker identity and account, no routes/domains/triggers or Gateway +caller/Forward rule, workers.dev and preview URLs disabled, no runtime secrets, +and the exact disabled variables and resource limits. Verify the Worker's +declarative export is `PrivateLaptopBridge` with `state=created` and +`storage=sqlite`; verify the `BRIDGE` binding's namespace ID matches exactly one +account namespace whose script is `private-laptop-bridge-staging`, class is +`PrivateLaptopBridge`, and `use_sqlite=true`; then verify the returned version +and deployment readback. The official APIs expose these fields through [Worker +metadata and script settings](https://developers.cloudflare.com/api/resources/workers/), +[Worker subdomain settings](https://developers.cloudflare.com/api/resources/workers/subresources/scripts/subresources/subdomain/), +[Worker domains](https://developers.cloudflare.com/api/resources/workers/subresources/domains/), +[zone routes](https://developers.cloudflare.com/api/resources/workers/subresources/routes/), +[Durable Object namespaces](https://developers.cloudflare.com/api/resources/durable_objects/subresources/namespaces/), +and [Gateway rules](https://developers.cloudflare.com/api/resources/zero_trust/subresources/gateway/subresources/rules/). +Any mismatch means stop and keep the Worker disabled and unrouted; do not +automatically delete it, retry deployment, or create a replacement namespace. + +No automated first-deploy workflow is prepared yet. The `cloudflare-staging` +GitHub environment is absent; GitHub creates an unconfigured environment when a +workflow references a missing one, so no new workflow may reference it until a +repository admin creates and verifies its protection rules. The tracked proof +fixture records branch protection/reviews and environment reviewers as false. +The read-only branch-protection API request returned HTTP 403 for this GitHub +integration, so this session could not independently inspect the live branch +rule. Before a workflow exists, repository settings must require a fresh PR +approval on `main`, prevent admin bypass and force pushes, and configure a +dedicated `cloudflare-staging-bootstrap` environment with required reviewers, +self-review disabled, only `main` allowed, and an environment-only short-lived +deployment credential. Then configure a separate `cloudflare-staging` +environment for routine versions upload/promotion. GitHub's docs confirm that +missing environments are automatically created without protection rules. +[GitHub protected branches](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-protected-branches/about-protected-branches) · +[GitHub environments](https://docs.github.com/en/actions/how-tos/deploy/configure-and-manage-deployments/manage-environments) + +Fresh provider readback cannot currently run in Actions: there is no protected +environment or independently scoped read-only credential. The eventual audit +credential needs Worker metadata read, complete zone/route read, and Zero Trust +read scopes, separated from the one-time deployment credential. The existing +Individual Worker Editor release token does not establish account-wide route or +Gateway state. Keep uploads and promotion blocked until this independent readback +is available, and keep the fallback until Drew separately approves bridge +activation and end-to-end authorized Fleet operations pass on his laptop. ## Selected ingress and the remaining feasibility gate diff --git a/pm-stack/private-laptop-bridge/VERIFICATION.md b/pm-stack/private-laptop-bridge/VERIFICATION.md index d70597d850..40074c3cfa 100644 --- a/pm-stack/private-laptop-bridge/VERIFICATION.md +++ b/pm-stack/private-laptop-bridge/VERIFICATION.md @@ -97,8 +97,9 @@ header denials, and disabled/invalid/expired/future/overlong-window denials. The test oracle is the fixed response or exact denial status. It never calls AMD, Cloudflare or an origin. Independent review corrected the exported entrypoint to Cloudflare's required `GatewayMiddleware` and added rejection of accidental -bridge credential headers. `wrangler.smoke.jsonc` dry run bundles 1.96 KiB -(0.98 KiB gzip), with only disabled non-secret configuration variables. +bridge credential headers. The historical smoke bundle dry run bundled 1.96 KiB (0.98 KiB gzip), with only +disabled non-secret configuration variables. Its separate Wrangler JSONC fixture +has since been removed; `cloudflare.config.ts` is now the sole config source. The final commit is tested again after committing; exact SHA and command results are recorded in the draft PR checkpoint to avoid a self-referential commit hash. @@ -132,13 +133,13 @@ not evidence of target existence or a live Cloudflare deployment. The lockfile pins `cf@1.0.0-rc.1`. Its installed package metadata records `@cloudflare/deploy-helpers@0.27.2`, and its bundled Versions upload code -contains the missing-Worker rejection, the pending-DO-migration rejection, and +contains the missing-Worker rejection, legacy pending-migration rejection, and the API error handler for a binding to an export that has not yet been -provisioned. It states that declarative exports are reconciled when the version -is deployed. Cloudflare's [deployment management docs](https://developers.cloudflare.com/workers/versions-and-deployments/deployment-management/) -also require a deploy command for the first upload and for lifecycle-changing -DO exports/migrations. Current scope permits only Versions uploads, so the -workflow has no first-Worker bootstrap fallback and refuses absent Workers. +provisioned. The helper rejects missing Workers and refuses to apply Durable Object lifecycle +changes during Versions upload. Cloudflare documents `cf deploy` for the initial +deployment and for declarative DO export creation; ordinary releases continue to +use Versions upload plus explicit promotion. The bridge release workflow refuses +absent Workers and has no automatic first-deployment fallback. The pinned `cf workers versions create` record is written to `WRANGLER_OUTPUT_FILE_PATH`, not stdout; the workflow sets that path, clears it @@ -150,11 +151,13 @@ provenance digest on that exact UUID's version annotations in the exact Worker version list. The separate `Versions release proof` test accepts a synthetic snapshot only -when the bridge Worker already exists and its `BRIDGE` binding matches the same -Worker's created SQLite `PrivateLaptopBridge` namespace at completed migration -`v1`. It separately rejects absent Workers, namespace/class/Worker mismatches, -an uncreated export, a different migration tag, and pending migrations. The -smoke preflight requires its existing Worker but no DO. The tracked staging +when the bridge Worker already exists, its declarative export says +`PrivateLaptopBridge: created/sqlite`, its `BRIDGE` binding references the same +Worker namespace, and the account namespace readback agrees on script, class, and +SQLite storage. It rejects missing Workers, wrong exports, storage types, binding +IDs, or namespace ownership. This contract follows `cloudflare.config.ts`; it does +not use legacy migration tags. The +Smoke preflight requires its existing Worker but no DO. The tracked staging proof remains `verified: false`; these tests validate the fail-closed gate and do not assert live account state. @@ -162,8 +165,9 @@ Owner evidence is supplied only through separate protected environment secrets: `CF_BRIDGE_ACCOUNT_ID`, `CF_BRIDGE_API_TOKEN`, `CF_BRIDGE_OWNER_PROOF_JSON` or their `CF_SMOKE_*` equivalents. No generic repository secret fallback is used. The public fixture contains no reviewer -email or account/namespace identifiers; the private proof requires an opaque -evidence reference, not a person's email. Promotion re-parses and revalidates +email or account/namespace identifiers; candidate handoff receipts use schema 2 +and carry only a SHA-256 digest of the account ID. The private proof requires an opaque evidence +reference, not a person's email. Promotion re-parses and revalidates the current private proof immediately before creating a deployment and requires its digest to equal the candidate's protected proof digest. @@ -266,7 +270,7 @@ bridge payload's fixed target, disabled flags, absent routes/previews/triggers, CPU/observability limits, and SQLite Durable Object binding. No Cloudflare credentials were supplied and no API write or live provider read was made. `staging-preflight.json` remains `verified:false` and the target remains recorded -as absent; same-Worker namespace/migration, account ownership, no-public-route, +as absent; same-Worker declarative export/namespace, account ownership, no-public-route, Gateway caller inventory, and protected environment evidence are still required before upload/promotion. No deployment, Gateway change, laptop change, traffic, or cutover was attempted. `actionlint` was unavailable locally, and the repo's diff --git a/pm-stack/private-laptop-bridge/deployment-config.test.mjs b/pm-stack/private-laptop-bridge/deployment-config.test.mjs index 43a7a48034..bcab05662b 100644 --- a/pm-stack/private-laptop-bridge/deployment-config.test.mjs +++ b/pm-stack/private-laptop-bridge/deployment-config.test.mjs @@ -1,30 +1,10 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import {readFile} from 'node:fs/promises'; +import {readdir, readFile} from 'node:fs/promises'; const read = name => readFile(new URL(name, import.meta.url), 'utf8'); -function parseJsonc(source) { - // These repository configs use line comments only and do not contain URLs - // in JSON strings with //; keep this helper deliberately limited. - return JSON.parse(source.split('\n').filter(line => !line.trimStart().startsWith('//')).join('\n')); -} -test('Wrangler local and staging definitions preserve the same DO class and SQLite migration', async () => { - const local = parseJsonc(await read('./wrangler.jsonc')); - const staging = parseJsonc(await read('./wrangler.staging.jsonc')); - for (const config of [local, staging]) { - assert.equal(config.name, 'private-laptop-bridge-staging'); - assert.equal(config.compatibility_date, '2026-07-30'); - assert.equal(config.workers_dev, false); - assert.equal(config.preview_urls, false); - assert.deepEqual(config.durable_objects.bindings, [{name:'BRIDGE',class_name:'PrivateLaptopBridge'}]); - assert.deepEqual(config.migrations, [{tag:'v1',new_sqlite_classes:['PrivateLaptopBridge']}]); - } - assert.equal(local.main, 'worker.mjs'); - assert.equal(staging.main, 'gateway.mjs'); -}); - -test('cf release config matches the reviewed private bridge resources and remains disabled', async () => { +test('cf declarative bridge config is the sole lifecycle source and remains disabled', async () => { const config = await read('./cloudflare.config.ts'); assert.match(config, /name:\s*'private-laptop-bridge-staging'/); assert.match(config, /mode\s*===\s*'bridge'/); @@ -34,9 +14,13 @@ test('cf release config matches the reviewed private bridge resources and remain assert.match(config, /ENABLED:\s*bindings\.text\('false'\)/); assert.match(config, /GATEWAY_HOST:\s*bindings\.text\('private-bridge-staging\.invalid'\)/); assert.match(config, /BRIDGE_REGISTRY:\s*bindings\.text\(''\)/); + assert.doesNotMatch(config, /migrations|new_sqlite_classes/); + + const files = await readdir(new URL('.', import.meta.url)); + assert.equal(files.some(name => /^wrangler(?:\.staging|\.smoke)?\.jsonc$/.test(name)), false); }); -test('pinned cf release and Wrangler producer satisfy the documented Build Output v1 pair', async () => { +test('pinned cf producer and Build Output consumer are the documented v1 pair', async () => { const pkg = JSON.parse(await read('./package.json')); const lock = JSON.parse(await read('./package-lock.json')); assert.equal(pkg.devDependencies.cf, '1.0.0-rc.1'); diff --git a/pm-stack/private-laptop-bridge/release-artifact.mjs b/pm-stack/private-laptop-bridge/release-artifact.mjs index bf116dc253..1488289e51 100644 --- a/pm-stack/private-laptop-bridge/release-artifact.mjs +++ b/pm-stack/private-laptop-bridge/release-artifact.mjs @@ -8,6 +8,7 @@ const required=(name)=>{const value=process.env[name];if(!value)throw new Error( const json=async path=>JSON.parse(await readFile(path,'utf8')); const privateProof=()=>{try{return JSON.parse(required('OWNER_PROOF_JSON'));}catch{throw new Error('OWNER_PROOF_JSON is missing or invalid JSON');}}; const proofDigest=()=>createHash('sha256').update(required('OWNER_PROOF_JSON')).digest('hex'); +const accountDigest=account=>createHash('sha256').update(account).digest('hex'); const write=(path,value)=>writeFile(path,JSON.stringify(value,null,2)+'\n',{mode:0o600}); const root=process.cwd(); @@ -42,12 +43,12 @@ if(action==='preflight') { if(!handoffPath||!runPath||!jobsPath) throw new Error('usage: provenance '); const artifact=await json(handoffPath),run=await json(runPath),jobs=await json(jobsPath),worker=required('TARGET_WORKER'),environment=required('TARGET_ENV'),account=required('CF_ACCOUNT_ID'),mode=required('TARGET_MODE'); const expectedMode=worker==='private-laptop-bridge-staging'?'bridge':worker==='private-laptop-bridge-smoke'?'default':null; - if(!expectedMode||artifact.worker!==worker||artifact.environment!==environment||artifact.account_id!==account||artifact.mode!==expectedMode||mode!==expectedMode) throw new Error('upload artifact target/environment/account/mode mismatch'); + if(!expectedMode||artifact.worker!==worker||artifact.environment!==environment||artifact.account_id_sha256!==accountDigest(account)||artifact.mode!==expectedMode||mode!==expectedMode) throw new Error('upload artifact target/environment/account/mode mismatch'); assertUploadRun(run,jobs,artifact); console.log(artifact.source_sha); } else if(action==='current-proof') { const [handoffPath]=args; if(!handoffPath) throw new Error('usage: current-proof '); const artifact=await json(handoffPath),account=required('CF_ACCOUNT_ID'),worker=required('TARGET_WORKER'),environment=required('TARGET_ENV'); - if(artifact.account_id!==account||artifact.worker!==worker||artifact.environment!==environment) throw new Error('current owner proof target differs from upload artifact'); + if(artifact.account_id_sha256!==accountDigest(account)||artifact.worker!==worker||artifact.environment!==environment) throw new Error('current owner proof target differs from upload artifact'); const proof=privateProof(); assertPreflight(proof,{accountId:account,worker,environment}); const preflight_digest=proofDigest(); if(preflight_digest!==artifact.preflight_digest) throw new Error('current main owner proof changed since upload; upload a new candidate'); @@ -57,7 +58,7 @@ if(action==='preflight') { if(!handoffPath||!runPath||!jobsPath||!versionsPath||!deployablePath) throw new Error('usage: verify-handoff '); const artifact=await json(handoffPath), run=await json(runPath),jobs=await json(jobsPath), target=required('TARGET_WORKER'), account=required('CF_ACCOUNT_ID'), env=required('TARGET_ENV'), mode=required('TARGET_MODE'); const expectedMode=target==='private-laptop-bridge-staging'?'bridge':'default'; - if(artifact.worker!==target||artifact.account_id!==account||artifact.environment!==env||artifact.mode!==expectedMode||mode!==expectedMode) throw new Error('promotion target/environment/account/mode differs from handoff'); + if(artifact.worker!==target||artifact.account_id_sha256!==accountDigest(account)||artifact.environment!==env||artifact.mode!==expectedMode||mode!==expectedMode) throw new Error('promotion target/environment/account/mode differs from handoff'); assertUploadRun(run,jobs,artifact); const proof=privateProof(); assertPreflight(proof,{accountId:account,worker:target,environment:env}); const config_digest=await digestFiles(root),preflight_digest=proofDigest(),build_digest=await digestTree(resolve(root,'.cloudflare/output/v1')); diff --git a/pm-stack/private-laptop-bridge/release-contract.mjs b/pm-stack/private-laptop-bridge/release-contract.mjs index 9c7c21003d..7ff737203d 100644 --- a/pm-stack/private-laptop-bridge/release-contract.mjs +++ b/pm-stack/private-laptop-bridge/release-contract.mjs @@ -7,7 +7,7 @@ const SHA=/^[0-9a-f]{40}$/; const DIGEST=/^[0-9a-f]{64}$/; const NAMESPACE=/^(?:[0-9a-f]{32}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/; const WORKFLOW='.github/workflows/private-laptop-bridge-release.yml'; -export const releaseConfigFiles=['cloudflare.config.ts','wrangler.jsonc','wrangler.staging.jsonc','wrangler.smoke.jsonc','package.json','package-lock.json','staging-preflight.json']; +export const releaseConfigFiles=['cloudflare.config.ts','package.json','package-lock.json','staging-preflight.json']; const fail=(message)=>{throw new Error(message);}; const digest=(bytes)=>createHash('sha256').update(bytes).digest('hex'); const stable=(value)=>Array.isArray(value)?value.map(stable):value&&typeof value==='object'?Object.fromEntries(Object.keys(value).sort().map(key=>[key,stable(value[key])])):value; @@ -74,24 +74,27 @@ export function assertExactVersion({stdout,versionsJson,worker,sourceSha,configD return id; } -const HANDOFF_KEYS=['schema','action','repository','workflow','upload_run_id','upload_run_attempt','source_sha','worker','environment','account_id','mode','version_id','tag','config_digest','build_digest','preflight_digest','provenance_digest','expected_disabled']; +const HANDOFF_KEYS=['schema','action','repository','workflow','upload_run_id','upload_run_attempt','source_sha','worker','environment','account_id_sha256','mode','version_id','tag','config_digest','build_digest','preflight_digest','provenance_digest','expected_disabled']; export function makeHandoff(fields) { - const handoff={schema:1,action:'upload',...fields}; + const {account_id,...safeFields}=fields; + if(typeof account_id!=='string'||!/^[0-9a-f]{32}$/.test(account_id)) fail('handoff account identity is invalid'); + const handoff={schema:2,action:'upload',...safeFields,account_id_sha256:digest(account_id)}; validateHandoffShape(handoff); return Object.fromEntries(HANDOFF_KEYS.map(k=>[k,handoff[k]])); } function validateHandoffShape(h) { if(!h||typeof h!=='object'||Array.isArray(h)||Object.keys(h).sort().join(',')!==[...HANDOFF_KEYS].sort().join(',')) fail('handoff fields are missing or unexpected'); - if(h.schema!==1||h.action!=='upload'||h.workflow!==WORKFLOW||!/^\d+$/.test(String(h.upload_run_id))||!Number.isInteger(h.upload_run_attempt)||h.upload_run_attempt<1||!SHA.test(h.source_sha)||!UUID.test(h.version_id)||!DIGEST.test(h.config_digest)||!DIGEST.test(h.build_digest)||!DIGEST.test(h.preflight_digest)||!DIGEST.test(h.provenance_digest)||h.provenance_digest!==provenanceDigest({worker:h.worker,sourceSha:h.source_sha,configDigest:h.config_digest,buildDigest:h.build_digest,preflightDigest:h.preflight_digest})||h.expected_disabled!==true) fail('handoff has invalid provenance or digest fields'); + if(h.schema!==2||h.action!=='upload'||h.workflow!==WORKFLOW||!/^\d+$/.test(String(h.upload_run_id))||!Number.isInteger(h.upload_run_attempt)||h.upload_run_attempt<1||!SHA.test(h.source_sha)||!UUID.test(h.version_id)||!DIGEST.test(h.account_id_sha256)||!DIGEST.test(h.config_digest)||!DIGEST.test(h.build_digest)||!DIGEST.test(h.preflight_digest)||!DIGEST.test(h.provenance_digest)||h.provenance_digest!==provenanceDigest({worker:h.worker,sourceSha:h.source_sha,configDigest:h.config_digest,buildDigest:h.build_digest,preflightDigest:h.preflight_digest})||h.expected_disabled!==true) fail('handoff has invalid provenance or digest fields'); if(h.repository!=='developing-today/code') fail('handoff repository mismatch'); const target=h.worker==='private-laptop-bridge-staging'?'cloudflare-staging':h.worker==='private-laptop-bridge-smoke'?'cloudflare-staging-smoke':null; if(!target||h.environment!==target) fail('handoff Worker/environment mismatch'); const mode=h.worker==='private-laptop-bridge-staging'?'bridge':'default'; - if(h.mode!==mode||h.tag!==h.source_sha||! /^[0-9a-f]{32}$/.test(h.account_id)) fail('handoff target/account/source mismatch'); + if(h.mode!==mode||h.tag!==h.source_sha) fail('handoff target/account/source mismatch'); } export function verifyPromotionProvenance(handoff, expected) { validateHandoffShape(handoff); - for(const key of ['repository','workflow','upload_run_id','upload_run_attempt','source_sha','worker','environment','account_id','mode','version_id','config_digest','build_digest','preflight_digest','provenance_digest']) { + if(typeof expected.account_id!=='string'||!/^[0-9a-f]{32}$/.test(expected.account_id)||handoff.account_id_sha256!==digest(expected.account_id)) fail('promotion provenance mismatch: account identity'); + for(const key of ['repository','workflow','upload_run_id','upload_run_attempt','source_sha','worker','environment','mode','version_id','config_digest','build_digest','preflight_digest','provenance_digest']) { if(handoff[key]!==expected[key]) fail(`promotion provenance mismatch: ${key}`); } if(expected.action!=='upload'||expected.event!=='workflow_dispatch'||expected.branch!=='main'||expected.status!=='completed'||expected.conclusion!=='success'||expected.workflow_path!==WORKFLOW||expected.head_sha!==handoff.source_sha||expected.run_attempt!==handoff.upload_run_attempt||expected.repository!==handoff.repository) fail('upload run is not a successful trusted main-branch upload run'); @@ -159,7 +162,7 @@ export function assertPreflight(proof,{accountId,worker,environment,now=Date.now const target=proof.targets?.[worker]; const expectedVars=worker==='private-laptop-bridge-staging'?{ENABLED:'false',GATEWAY_HOST:'private-bridge-staging.invalid',GATEWAY_ACCOUNT_ID:'',GATEWAY_POLICY_ID:'',GATEWAY_IDENTITY_EMAIL:'',GATEWAY_POSTURE_ID:'',BRIDGE_REGISTRY:''}:{ENABLED:'false',GATEWAY_HOST:'private-bridge-smoke.invalid',GATEWAY_ACCOUNT_ID:'',GATEWAY_POLICY_ID:'',START_MS:'',END_MS:''}; if(!target||target.environment!==environment||target.exists!==true||target.script_id!==worker||target.account_id!==accountId||target.workers_dev!==false||target.preview_urls!==false||!Array.isArray(target.routes)||target.routes.length!==0||!Array.isArray(target.custom_domains)||target.custom_domains.length!==0||target.application_enabled!==false||target.observability?.enabled!==false||target.observability?.logs!==false||target.observability?.traces!==false||target.limits?.cpu_ms!==10||!Array.isArray(target.gateway_forward_policy_ids)||target.gateway_forward_policy_ids.length!==0||!Array.isArray(target.gateway_caller_ids)||target.gateway_caller_ids.length!==0||JSON.stringify(Object.fromEntries(Object.entries(target.variables??{}).sort()))!==JSON.stringify(Object.fromEntries(Object.entries(expectedVars).sort()))||!Array.isArray(target.bindings)) fail('owner read-only proof does not verify the exact private disabled target'); - if(worker==='private-laptop-bridge-staging'&&(target.bindings.length!==1||target.bindings[0]?.name!=='BRIDGE'||target.bindings[0]?.type!=='durable_object_namespace'||target.bindings[0]?.class_name!=='PrivateLaptopBridge'||target.bindings[0]?.namespace_id!==target.do?.namespace_id||target.do?.worker_name!==worker||target.do?.class_name!=='PrivateLaptopBridge'||target.do?.storage!=='sqlite'||target.do?.export_state!=='created'||target.do?.migration_tag!=='v1'||target.do?.pending_migrations!==false||!NAMESPACE.test(target.do?.namespace_id??''))) fail('owner read-only proof does not verify the same-Worker SQLite Durable Object namespace and completed v1 migration state'); + if(worker==='private-laptop-bridge-staging'&&(target.bindings.length!==1||target.bindings[0]?.name!=='BRIDGE'||target.bindings[0]?.type!=='durable_object_namespace'||target.bindings[0]?.class_name!=='PrivateLaptopBridge'||target.bindings[0]?.namespace_id!==target.do?.id||!same(target.declarative_exports,{PrivateLaptopBridge:{state:'created',storage:'sqlite'}})||target.do?.script!==worker||target.do?.class!=='PrivateLaptopBridge'||target.do?.use_sqlite!==true||!NAMESPACE.test(target.do?.id??''))) fail('owner read-only proof does not verify the same-Worker SQLite Durable Object export and namespace'); if(worker==='private-laptop-bridge-smoke'&&(target.bindings.length!==0||target.do!==null)) fail('smoke target unexpectedly has a Durable Object namespace or binding'); return true; } diff --git a/pm-stack/private-laptop-bridge/release-contract.test.mjs b/pm-stack/private-laptop-bridge/release-contract.test.mjs index ca8fb9b235..7454c5bcad 100644 --- a/pm-stack/private-laptop-bridge/release-contract.test.mjs +++ b/pm-stack/private-laptop-bridge/release-contract.test.mjs @@ -1,6 +1,7 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import {readFile} from 'node:fs/promises'; +import {createHash} from 'node:crypto'; import {assertDeployable,assertDeploymentCreated,assertDryRunPayload,assertEffectivePayload,assertExactVersion,assertLatestServing,assertPreflight,assertUploadRun,assertVersionStillMatches,makeHandoff,provenanceDigest,verifyPromotionProvenance} from './release-contract.mjs'; const uuid='01234567-89ab-cdef-0123-456789abcdef', old='11111111-2222-3333-4444-555555555555'; @@ -27,11 +28,14 @@ test('exact version must bind full SHA, exact config and actual Build Output dig for(const v of [{...version,annotations:{...version.annotations,'workers/tag':sha.slice(0,12)}},{...version,annotations:{...version.annotations,'workers/message':`release provenance=${'e'.repeat(64)}`}},{...version,annotations:{...version.annotations,'workers/message':`release provenance=${'e'.repeat(64)}`}}]) assert.throws(()=>assertExactVersion({stdout:cfVersionResponse(),versionsJson:list([v]),worker:'private-laptop-bridge-staging',sourceSha:sha,configDigest:cd,buildDigest:bd,preflightDigest:pd})); }); -test('promotion handoff binds exact source, Worker, environment, account, upload run and attempt',()=>{ +test('promotion handoff binds exact source, Worker, environment, account digest, upload run and attempt',()=>{ const h=handoff(); + assert.equal(h.schema,2); assert.equal(h.account_id_sha256,createHash('sha256').update(acct).digest('hex')); assert.equal('account_id' in h,false); assert.equal(JSON.stringify(h).includes(acct),false); const base={repository:'developing-today/code',workflow:'.github/workflows/private-laptop-bridge-release.yml',upload_run_id:'501',upload_run_attempt:1,source_sha:sha,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',account_id:acct,mode:'bridge',version_id:uuid,config_digest:cd,build_digest:bd,preflight_digest:pd,provenance_digest:proof,action:'upload',event:'workflow_dispatch',branch:'main',status:'completed',conclusion:'success',workflow_path:'.github/workflows/private-laptop-bridge-release.yml',head_sha:sha,run_attempt:1}; assert.equal(verifyPromotionProvenance(h,base),true); - for(const [key,value] of [['upload_run_id','502'],['worker','private-laptop-bridge-smoke'],['environment','cloudflare-staging-smoke'],['account_id','e'.repeat(32)],['config_digest','f'.repeat(64)],['build_digest','f'.repeat(64)],['preflight_digest','f'.repeat(64)],['provenance_digest','f'.repeat(64)],['upload_run_attempt',2],['event','pull_request'],['branch','feature'],['status','in_progress'],['conclusion','failure'],['head_sha','f'.repeat(40)],['workflow_path','other.yml']]) assert.throws(()=>verifyPromotionProvenance(h,{...base,[key]:value}),undefined,key); + for(const [key,value] of [['upload_run_id','502'],['worker','private-laptop-bridge-smoke'],['environment','cloudflare-staging-smoke'],['config_digest','f'.repeat(64)],['build_digest','f'.repeat(64)],['preflight_digest','f'.repeat(64)],['provenance_digest','f'.repeat(64)],['upload_run_attempt',2],['event','pull_request'],['branch','feature'],['status','in_progress'],['conclusion','failure'],['head_sha','f'.repeat(40)],['workflow_path','other.yml']]) assert.throws(()=>verifyPromotionProvenance(h,{...base,[key]:value}),undefined,key); + assert.throws(()=>verifyPromotionProvenance({...h,account_id_sha256:'f'.repeat(64)},base),/account identity/); + assert.throws(()=>verifyPromotionProvenance({...h,schema:1},base),/invalid provenance/); const bad={...h,expected_disabled:false}; assert.throws(()=>verifyPromotionProvenance(bad,base),/invalid provenance/); }); @@ -80,14 +84,33 @@ test('deployment create response must return the exact 100 percent deployment id test('read-only owner proof fails closed for missing, stale, public or unexpected callers',()=>{ const now=Date.parse('2026-11-22T12:00:00Z'); - const good={schema:1,verified:true,account_id:acct,verified_at:'2026-11-22T11:00:00Z',expires_at:'2026-11-22T13:00:00Z',evidence_ref:'review-1',release_policy:{repository:'developing-today/code',branch:'main',branch_protected:true,required_pull_request_reviews:true,force_push_disabled:true,admin_bypass_disabled:true,environment_reviewers_required:{'cloudflare-staging':true,'cloudflare-staging-smoke':true},self_review_disabled:{'cloudflare-staging':true,'cloudflare-staging-smoke':true},allowed_environment_branches:{'cloudflare-staging':['main'],'cloudflare-staging-smoke':['main']},evidence_ref:'policy-review-1'},targets:{'private-laptop-bridge-staging':{environment:'cloudflare-staging',exists:true,script_id:'private-laptop-bridge-staging',account_id:acct,application_enabled:false,workers_dev:false,preview_urls:false,routes:[],custom_domains:[],observability:{enabled:false,logs:false,traces:false},limits:{cpu_ms:10},gateway_forward_policy_ids:[],gateway_caller_ids:[],variables:{ENABLED:'false',GATEWAY_HOST:'private-bridge-staging.invalid',GATEWAY_ACCOUNT_ID:'',GATEWAY_POLICY_ID:'',GATEWAY_IDENTITY_EMAIL:'',GATEWAY_POSTURE_ID:'',BRIDGE_REGISTRY:''},bindings:[{name:'BRIDGE',type:'durable_object_namespace',class_name:'PrivateLaptopBridge',namespace_id:'1'.repeat(32)}],do:{worker_name:'private-laptop-bridge-staging',class_name:'PrivateLaptopBridge',storage:'sqlite',export_state:'created',migration_tag:'v1',pending_migrations:false,namespace_id:'1'.repeat(32)}}}}; + const good={schema:1,verified:true,account_id:acct,verified_at:'2026-11-22T11:00:00Z',expires_at:'2026-11-22T13:00:00Z',evidence_ref:'review-1',release_policy:{repository:'developing-today/code',branch:'main',branch_protected:true,required_pull_request_reviews:true,force_push_disabled:true,admin_bypass_disabled:true,environment_reviewers_required:{'cloudflare-staging':true,'cloudflare-staging-smoke':true},self_review_disabled:{'cloudflare-staging':true,'cloudflare-staging-smoke':true},allowed_environment_branches:{'cloudflare-staging':['main'],'cloudflare-staging-smoke':['main']},evidence_ref:'policy-review-1'},targets:{'private-laptop-bridge-staging':{environment:'cloudflare-staging',exists:true,script_id:'private-laptop-bridge-staging',account_id:acct,application_enabled:false,workers_dev:false,preview_urls:false,routes:[],custom_domains:[],observability:{enabled:false,logs:false,traces:false},limits:{cpu_ms:10},gateway_forward_policy_ids:[],gateway_caller_ids:[],variables:{ENABLED:'false',GATEWAY_HOST:'private-bridge-staging.invalid',GATEWAY_ACCOUNT_ID:'',GATEWAY_POLICY_ID:'',GATEWAY_IDENTITY_EMAIL:'',GATEWAY_POSTURE_ID:'',BRIDGE_REGISTRY:''},bindings:[{name:'BRIDGE',type:'durable_object_namespace',class_name:'PrivateLaptopBridge',namespace_id:'1'.repeat(32)}],declarative_exports:{PrivateLaptopBridge:{state:'created',storage:'sqlite'}},do:{id:'1'.repeat(32),class:'PrivateLaptopBridge',script:'private-laptop-bridge-staging',use_sqlite:true}}}}; assert.equal(assertPreflight(good,{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now}),true); assert.throws(()=>assertPreflight({...good,verified:false},{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now}),/absent, expired, or invalid/); assert.throws(()=>assertPreflight({...good,expires_at:'2026-11-22T11:59:59Z'},{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now}),/absent, expired, or invalid/); assert.throws(()=>assertPreflight({...good,evidence_ref:''},{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now}),/absent, expired, or invalid/); assert.throws(()=>assertPreflight({...good,release_policy:{...good.release_policy,branch_protected:false}},{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now}),/protected-main/); assert.throws(()=>assertPreflight({...good,release_policy:{...good.release_policy,environment_reviewers_required:{'cloudflare-staging':false}}},{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now}),/protected-main/); - for(const change of [{gateway_caller_ids:['unexpected-caller']},{routes:['https://public.example/*']},{custom_domains:['public.example']},{workers_dev:true},{preview_urls:true},{gateway_forward_policy_ids:['unexpected-policy']},{observability:{enabled:false,logs:true,traces:false}},{limits:{cpu_ms:50}},{application_enabled:true},{variables:{...good.targets['private-laptop-bridge-staging'].variables,ENABLED:'true'}},{bindings:[]},{do:{...good.targets['private-laptop-bridge-staging'].do,worker_name:'other-worker'}},{do:{...good.targets['private-laptop-bridge-staging'].do,export_state:'pending'}},{do:{...good.targets['private-laptop-bridge-staging'].do,migration_tag:'v0'}},{do:{...good.targets['private-laptop-bridge-staging'].do,pending_migrations:true}}]) { + for(const change of [ + {gateway_caller_ids:['unexpected-caller']}, + {routes:['https://public.example/*']}, + {custom_domains:['public.example']}, + {workers_dev:true}, + {preview_urls:true}, + {gateway_forward_policy_ids:['unexpected-policy']}, + {observability:{enabled:false,logs:true,traces:false}}, + {limits:{cpu_ms:50}}, + {application_enabled:true}, + {variables:{...good.targets['private-laptop-bridge-staging'].variables,ENABLED:'true'}}, + {bindings:[]}, + {do:{...good.targets['private-laptop-bridge-staging'].do,script:'other-worker'}}, + {do:{...good.targets['private-laptop-bridge-staging'].do,class:'OtherClass'}}, + {do:{...good.targets['private-laptop-bridge-staging'].do,use_sqlite:false}}, + {do:{...good.targets['private-laptop-bridge-staging'].do,id:''}}, + {declarative_exports:{PrivateLaptopBridge:{state:'deleted',storage:'sqlite'}}}, + {declarative_exports:{PrivateLaptopBridge:{state:'created',storage:'legacy-kv'}}}, + {declarative_exports:{PrivateLaptopBridge:{state:'created',storage:'sqlite'},Unexpected:{state:'created',storage:'sqlite'}}}, + ]) { const target={...good.targets['private-laptop-bridge-staging'],...change}; assert.throws(()=>assertPreflight({...good,targets:{...good.targets,'private-laptop-bridge-staging':target}},{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now})); } @@ -98,20 +121,22 @@ test('read-only owner proof fails closed for missing, stale, public or unexpecte test('Versions release proof separately requires an existing Worker and its ready same-Worker DO namespace',()=>{ const now=Date.parse('2026-11-22T12:00:00Z'); const policy={repository:'developing-today/code',branch:'main',branch_protected:true,required_pull_request_reviews:true,force_push_disabled:true,admin_bypass_disabled:true,environment_reviewers_required:{'cloudflare-staging':true},self_review_disabled:{'cloudflare-staging':true},allowed_environment_branches:{'cloudflare-staging':['main']},evidence_ref:'policy-review-1'}; - const bridge={environment:'cloudflare-staging',exists:true,script_id:'private-laptop-bridge-staging',account_id:acct,application_enabled:false,workers_dev:false,preview_urls:false,routes:[],custom_domains:[],observability:{enabled:false,logs:false,traces:false},limits:{cpu_ms:10},gateway_forward_policy_ids:[],gateway_caller_ids:[],variables:{ENABLED:'false',GATEWAY_HOST:'private-bridge-staging.invalid',GATEWAY_ACCOUNT_ID:'',GATEWAY_POLICY_ID:'',GATEWAY_IDENTITY_EMAIL:'',GATEWAY_POSTURE_ID:'',BRIDGE_REGISTRY:''},bindings:[{name:'BRIDGE',type:'durable_object_namespace',class_name:'PrivateLaptopBridge',namespace_id:'1'.repeat(32)}],do:{worker_name:'private-laptop-bridge-staging',class_name:'PrivateLaptopBridge',storage:'sqlite',export_state:'created',migration_tag:'v1',pending_migrations:false,namespace_id:'1'.repeat(32)}}; + const bridge={environment:'cloudflare-staging',exists:true,script_id:'private-laptop-bridge-staging',account_id:acct,application_enabled:false,workers_dev:false,preview_urls:false,routes:[],custom_domains:[],observability:{enabled:false,logs:false,traces:false},limits:{cpu_ms:10},gateway_forward_policy_ids:[],gateway_caller_ids:[],variables:{ENABLED:'false',GATEWAY_HOST:'private-bridge-staging.invalid',GATEWAY_ACCOUNT_ID:'',GATEWAY_POLICY_ID:'',GATEWAY_IDENTITY_EMAIL:'',GATEWAY_POSTURE_ID:'',BRIDGE_REGISTRY:''},bindings:[{name:'BRIDGE',type:'durable_object_namespace',class_name:'PrivateLaptopBridge',namespace_id:'1'.repeat(32)}],declarative_exports:{PrivateLaptopBridge:{state:'created',storage:'sqlite'}},do:{id:'1'.repeat(32),class:'PrivateLaptopBridge',script:'private-laptop-bridge-staging',use_sqlite:true}}; const makeProof=(target=bridge)=>({schema:1,verified:true,account_id:acct,verified_at:'2026-11-22T11:00:00Z',expires_at:'2026-11-22T13:00:00Z',evidence_ref:'worker-review-1',release_policy:policy,targets:{'private-laptop-bridge-staging':target}}); const check=(proof)=>assertPreflight(proof,{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now}); assert.equal(check(makeProof()),true); assert.throws(()=>check(makeProof({...bridge,exists:false})),/exact private disabled target/); for(const change of [ - {do:{...bridge.do,worker_name:'private-laptop-bridge-smoke'}}, - {do:{...bridge.do,export_state:'missing'}}, - {do:{...bridge.do,migration_tag:'v0'}}, - {do:{...bridge.do,pending_migrations:true}}, - {do:{...bridge.do,namespace_id:''}}, + {do:{...bridge.do,script:'private-laptop-bridge-smoke'}}, + {do:{...bridge.do,class:'OtherClass'}}, + {do:{...bridge.do,use_sqlite:false}}, + {do:{...bridge.do,id:''}}, + {declarative_exports:{PrivateLaptopBridge:{state:'deleted',storage:'sqlite'}}}, + {declarative_exports:{PrivateLaptopBridge:{state:'created',storage:'legacy-kv'}}}, + {declarative_exports:{PrivateLaptopBridge:{state:'created',storage:'sqlite'},Unexpected:{state:'created',storage:'sqlite'}}}, {bindings:[{...bridge.bindings[0],namespace_id:'2'.repeat(32)}]}, {bindings:[{...bridge.bindings[0],class_name:'OtherClass'}]}, - ]) assert.throws(()=>check(makeProof({...bridge,...change})),/same-Worker SQLite Durable Object namespace and completed v1 migration state/); + ]) assert.throws(()=>check(makeProof({...bridge,...change})),/same-Worker SQLite Durable Object export and namespace/); }); test('tracked preflight fixture is redacted and never substitutes for private owner proof',async()=>{ @@ -122,7 +147,7 @@ test('tracked preflight fixture is redacted and never substitutes for private ow assert.doesNotMatch(text,/@/); for(const target of Object.values(fixture.targets)) { assert.equal(target.account_id,''); - assert.equal(target.do?.namespace_id??'',''); + assert.equal(target.do?.id??'',''); assert.ok(target.bindings.every(binding=>binding.namespace_id==='')); } }); diff --git a/pm-stack/private-laptop-bridge/staging-preflight.json b/pm-stack/private-laptop-bridge/staging-preflight.json index 2ec0e3ca34..72ee303417 100644 --- a/pm-stack/private-laptop-bridge/staging-preflight.json +++ b/pm-stack/private-laptop-bridge/staging-preflight.json @@ -12,9 +12,18 @@ "required_pull_request_reviews": false, "force_push_disabled": false, "admin_bypass_disabled": false, - "environment_reviewers_required": {"cloudflare-staging": false, "cloudflare-staging-smoke": false}, - "self_review_disabled": {"cloudflare-staging": false, "cloudflare-staging-smoke": false}, - "allowed_environment_branches": {"cloudflare-staging": [], "cloudflare-staging-smoke": []}, + "environment_reviewers_required": { + "cloudflare-staging": false, + "cloudflare-staging-smoke": false + }, + "self_review_disabled": { + "cloudflare-staging": false, + "cloudflare-staging-smoke": false + }, + "allowed_environment_branches": { + "cloudflare-staging": [], + "cloudflare-staging-smoke": [] + }, "evidence_ref": "" }, "targets": { @@ -28,11 +37,24 @@ "preview_urls": false, "routes": [], "custom_domains": [], - "observability": {"enabled": false, "logs": false, "traces": false}, - "limits": {"cpu_ms": 10}, + "observability": { + "enabled": false, + "logs": false, + "traces": false + }, + "limits": { + "cpu_ms": 10 + }, "gateway_forward_policy_ids": [], "gateway_caller_ids": [], - "variables": {"ENABLED": "false", "GATEWAY_HOST": "private-bridge-smoke.invalid", "GATEWAY_ACCOUNT_ID": "", "GATEWAY_POLICY_ID": "", "START_MS": "", "END_MS": ""}, + "variables": { + "ENABLED": "false", + "GATEWAY_HOST": "private-bridge-smoke.invalid", + "GATEWAY_ACCOUNT_ID": "", + "GATEWAY_POLICY_ID": "", + "START_MS": "", + "END_MS": "" + }, "bindings": [], "do": null }, @@ -46,13 +68,40 @@ "preview_urls": false, "routes": [], "custom_domains": [], - "observability": {"enabled": false, "logs": false, "traces": false}, - "limits": {"cpu_ms": 10}, + "observability": { + "enabled": false, + "logs": false, + "traces": false + }, + "limits": { + "cpu_ms": 10 + }, "gateway_forward_policy_ids": [], "gateway_caller_ids": [], - "variables": {"ENABLED": "false", "GATEWAY_HOST": "private-bridge-staging.invalid", "GATEWAY_ACCOUNT_ID": "", "GATEWAY_POLICY_ID": "", "GATEWAY_IDENTITY_EMAIL": "", "GATEWAY_POSTURE_ID": "", "BRIDGE_REGISTRY": ""}, - "bindings": [{"name": "BRIDGE", "type": "durable_object_namespace", "class_name": "PrivateLaptopBridge", "namespace_id": ""}], - "do": {"worker_name": "private-laptop-bridge-staging", "class_name": "PrivateLaptopBridge", "storage": "sqlite", "export_state": "", "migration_tag": "", "pending_migrations": false, "namespace_id": ""} + "variables": { + "ENABLED": "false", + "GATEWAY_HOST": "private-bridge-staging.invalid", + "GATEWAY_ACCOUNT_ID": "", + "GATEWAY_POLICY_ID": "", + "GATEWAY_IDENTITY_EMAIL": "", + "GATEWAY_POSTURE_ID": "", + "BRIDGE_REGISTRY": "" + }, + "bindings": [ + { + "name": "BRIDGE", + "type": "durable_object_namespace", + "class_name": "PrivateLaptopBridge", + "namespace_id": "" + } + ], + "do": { + "id": "", + "class": "PrivateLaptopBridge", + "script": "private-laptop-bridge-staging", + "use_sqlite": false + }, + "declarative_exports": {} } } } diff --git a/pm-stack/private-laptop-bridge/wrangler.jsonc b/pm-stack/private-laptop-bridge/wrangler.jsonc deleted file mode 100644 index 863dfd2f05..0000000000 --- a/pm-stack/private-laptop-bridge/wrangler.jsonc +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "private-laptop-bridge-staging", - "main": "worker.mjs", - "compatibility_date": "2026-07-30", - "workers_dev": false, - "preview_urls": false, - "limits": {"cpu_ms": 10}, - "observability": {"enabled": false}, - "vars": {"ENABLED": "false"}, - "durable_objects": {"bindings": [{"name": "BRIDGE", "class_name": "PrivateLaptopBridge"}]}, - "migrations": [{"tag": "v1", "new_sqlite_classes": ["PrivateLaptopBridge"]}] -} diff --git a/pm-stack/private-laptop-bridge/wrangler.smoke.jsonc b/pm-stack/private-laptop-bridge/wrangler.smoke.jsonc deleted file mode 100644 index 47d1de24ab..0000000000 --- a/pm-stack/private-laptop-bridge/wrangler.smoke.jsonc +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "private-laptop-bridge-smoke", - "main": "smoke.mjs", - "compatibility_date": "2026-07-30", - "workers_dev": false, - "preview_urls": false, - "routes": [], - "observability": {"enabled": false}, - "limits": {"cpu_ms": 10}, - "vars": { - "ENABLED": "false", - "GATEWAY_HOST": "private-bridge-smoke.invalid", - "GATEWAY_ACCOUNT_ID": "", - "GATEWAY_POLICY_ID": "", - "START_MS": "", - "END_MS": "" - } -} diff --git a/pm-stack/private-laptop-bridge/wrangler.staging.jsonc b/pm-stack/private-laptop-bridge/wrangler.staging.jsonc deleted file mode 100644 index b719a7a624..0000000000 --- a/pm-stack/private-laptop-bridge/wrangler.staging.jsonc +++ /dev/null @@ -1,22 +0,0 @@ -{ - // A reviewable deployment candidate only. No credentials, live IDs or routes. - // Gateway Forward must invoke GatewayMiddleware by RPC after explicit approval. - "name": "private-laptop-bridge-staging", - "main": "gateway.mjs", - "compatibility_date": "2026-07-30", - "workers_dev": false, - "preview_urls": false, - "limits": {"cpu_ms": 10}, - "observability": {"enabled": false}, - "routes": [], - "vars": { - "ENABLED": "false", - "GATEWAY_HOST": "private-bridge-staging.invalid", - "GATEWAY_ACCOUNT_ID": "", - "GATEWAY_POLICY_ID": "", - "GATEWAY_IDENTITY_EMAIL": "", - "GATEWAY_POSTURE_ID": "" - }, - "durable_objects": {"bindings": [{"name": "BRIDGE", "class_name": "PrivateLaptopBridge"}]}, - "migrations": [{"tag": "v1", "new_sqlite_classes": ["PrivateLaptopBridge"]}] -} From bb492320e02dfb7c17d109646296603c3ab16a1d Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 06:48:30 +0000 Subject: [PATCH 19/33] Document protected source pin alternative --- pm-stack/private-laptop-bridge/STAGING.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/pm-stack/private-laptop-bridge/STAGING.md b/pm-stack/private-laptop-bridge/STAGING.md index da17f02656..21c9482d05 100644 --- a/pm-stack/private-laptop-bridge/STAGING.md +++ b/pm-stack/private-laptop-bridge/STAGING.md @@ -108,6 +108,18 @@ missing environments are automatically created without protection rules. [GitHub protected branches](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-protected-branches/about-protected-branches) · [GitHub environments](https://docs.github.com/en/actions/how-tos/deploy/configure-and-manage-deployments/manage-environments) +If repository-wide main protection cannot be established, do not mark the +current policy proof as protected. A separate protected-source path would need +an environment-owned exact approved full commit SHA, no workflow ref/target +inputs, a `main`-only dispatch, an independent required reviewer who checks the +workflow and exact source diff at that SHA, and a separate gated write job that +checks out only that SHA. The approval record and protected SHA setting must be +retained as evidence; changing the pin requires the same independent review. +The environment must not expose its credential to a validation job. This +fallback is a proposal only: no environment, source pin, workflow, or reviewer +rule has been created or verified, so the existing release policy remains +fail-closed until one of the protected paths is actually evidenced. + Fresh provider readback cannot currently run in Actions: there is no protected environment or independently scoped read-only credential. The eventual audit credential needs Worker metadata read, complete zone/route read, and Zero Trust From c9beac893ca0ed8579abd57179f7e2272f4d373e Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 06:50:14 +0000 Subject: [PATCH 20/33] Clarify rehearsal and deployment plan evidence --- pm-stack/private-laptop-bridge/DISCOVERY.md | 12 ++++++------ pm-stack/private-laptop-bridge/STAGING.md | 6 ++++-- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/pm-stack/private-laptop-bridge/DISCOVERY.md b/pm-stack/private-laptop-bridge/DISCOVERY.md index 1eb6f8b76c..a2e3295179 100644 --- a/pm-stack/private-laptop-bridge/DISCOVERY.md +++ b/pm-stack/private-laptop-bridge/DISCOVERY.md @@ -286,12 +286,12 @@ bridge use separate GitHub environments/tokens. The bridge environment cannot modify Gateway policies; those use a separate approval and administrative path. -Offline results on the current follow-up commit (recorded in the PR): Node 24.22.0 + cf 1.0.0-rc.1 + Wrangler -4.166.0; both smoke and `--mode bridge` pass `cf build` and the corresponding -`cf workers versions create --prebuilt --dry-run`. The bridge dry-run reports -only the DO namespace binding `BRIDGE -> PrivateLaptopBridge`, disabled -`ENABLED=false`, placeholder Gateway identifiers and empty registry; it creates -nothing. `deployment-config.test.mjs` verifies that the `cf` config is the sole +A prior pinned CLI rehearsal on `c20f3d96` (recorded in the PR) used Node +24.22.0, cf 1.0.0-rc.1 and Wrangler 4.166.0; smoke and bridge both passed +`cf build` and `cf workers versions create --prebuilt --dry-run`. The bridge +dry-run reported only `BRIDGE -> PrivateLaptopBridge`, disabled `ENABLED=false`, +placeholder Gateway identifiers and empty registry; it created nothing. This +turn did not rerun the CLI because the checkout has no installed `cf` binary. `deployment-config.test.mjs` verifies that the `cf` config is the sole declarative DO lifecycle source and contains the expected SQLite export. It does not prove provider state. Gateway runtime unit tests and smoke tests pass. These results prove local Build Output and diff --git a/pm-stack/private-laptop-bridge/STAGING.md b/pm-stack/private-laptop-bridge/STAGING.md index 21c9482d05..ccd2e07d88 100644 --- a/pm-stack/private-laptop-bridge/STAGING.md +++ b/pm-stack/private-laptop-bridge/STAGING.md @@ -46,8 +46,10 @@ deployment step, not a second configuration or a legacy migration fallback. [cf project deploy](https://developers.cloudflare.com/cf/projects/) · [cf and Durable Object lifecycle](https://developers.cloudflare.com/cf/wrangler/reference/#convert-durable-object-migrations) -The only proposed command sequence is a manual owner-controlled procedure, not -a GitHub workflow: +The proposed command sequence is a manual owner-controlled procedure, not a +GitHub workflow. It has not been run in this turn; first validate the pinned +CLI syntax/build with no credentials and stop if the pinned release differs +from current Cloudflare documentation: ```sh npm ci --ignore-scripts --no-audit --no-fund From ca9c3f40a4c1c4afa77a22dfc467a86b7b6bf13d Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 07:21:32 +0000 Subject: [PATCH 21/33] feat(fleet): draft gated disabled bridge bootstrap --- pm-stack/private-laptop-bridge/DISCOVERY.md | 43 ++- pm-stack/private-laptop-bridge/README.md | 6 + pm-stack/private-laptop-bridge/STAGING.md | 137 +++++-- .../private-laptop-bridge/VERIFICATION.md | 47 +++ ...ge-staging-bootstrap.workflow.yml.disabled | 109 ++++++ .../staging-bootstrap.mjs | 362 ++++++++++++++++++ .../staging-bootstrap.test.mjs | 154 ++++++++ 7 files changed, 802 insertions(+), 56 deletions(-) create mode 100644 pm-stack/private-laptop-bridge/private-laptop-bridge-staging-bootstrap.workflow.yml.disabled create mode 100644 pm-stack/private-laptop-bridge/staging-bootstrap.mjs create mode 100644 pm-stack/private-laptop-bridge/staging-bootstrap.test.mjs diff --git a/pm-stack/private-laptop-bridge/DISCOVERY.md b/pm-stack/private-laptop-bridge/DISCOVERY.md index a2e3295179..08daac0b16 100644 --- a/pm-stack/private-laptop-bridge/DISCOVERY.md +++ b/pm-stack/private-laptop-bridge/DISCOVERY.md @@ -255,25 +255,30 @@ uses `exports.durableObject({storage: "sqlite"})`, Cloudflare's declarative Durable Object lifecycle. The pinned `cf workers versions create` path is only for an existing Worker whose namespace is already provisioned; it cannot create the first Worker or apply a new export lifecycle. Official `cf` docs direct the -initial deployment and new export creation through `cf deploy`. The first deploy -therefore needs a separately reviewed, one-time manual owner path using the same -`cloudflare.config.ts` Build Output; it must not add a Beta API create, raw PUT, -Wrangler deploy, or legacy `migrations` fallback. - -That first deploy is not authorized or runnable yet. It must be preceded and -followed by a fresh independent read-only inventory proving the exact account, -fixed Worker name, complete zone/route inventory, Worker domains, workers.dev -and preview flags, Gateway rules/callers, bindings, versions/deployment, and -Durable Object namespace/export. It must refuse an existing Worker before the -write, deploy with `ENABLED=false`, empty registry/Gateway identifiers, no -runtime secrets, no routes/domains/triggers, `workersDev:false`, and -`previewUrls:false`, then verify the same SQLite namespace ID from both the -Worker binding and account namespace listing. Any unexpected resource, route, -preview, binding, export, or deployment state stops the sequence; no automatic +initial deployment and new export creation through `cf deploy`. A manual-only +first-deployment draft now uses that same pinned, declarative +`cloudflare.config.ts` Build Output; it adds no Beta API create, raw PUT, +Wrangler deploy, or legacy `migrations` fallback. The draft is stored outside +`.github/workflows` with a `.disabled` suffix and is not registered by GitHub. + +The draft is reviewable but cannot run in the current repository state. It +requires a pre-existing, verified `cloudflare-staging-bootstrap` environment, +an environment-owned source SHA and independent reviewer, complete account +zone/route and Worker/namespace read permission, and separate narrowly scoped +read and one-time write credentials. It first checks environment protections in +a no-secret job before assigning the deploy job to the environment, so a missing +environment cannot be auto-created without protection. Its provider preflight +refuses an existing Worker, namespace collision, public route/domain, incomplete +inventory, or unsafe config. The pinned deployment has `ENABLED=false`, empty +registry/Gateway identifiers, no runtime secrets, routes/domains/schedules, +`workersDev:false`, and `previewUrls:false`; independent readback checks the same +SQLite namespace ID in the binding and account namespace list. Account-level +Gateway rules are not modified or inventoried by this dormant initialization; +their separate review is required before any later enablement. No automatic delete or fallback is allowed. The existing routine Versions-only release must stay blocked until the post-first -deploy readback is independently recorded as a fresh owner proof and the +deploy readback is independently recorded as a fresh owner proof and its protected environment and token scopes are actually established. The current `staging-preflight.json` remains `verified:false`; no live Worker, namespace, route, Gateway or account state was read in this session. @@ -290,8 +295,10 @@ A prior pinned CLI rehearsal on `c20f3d96` (recorded in the PR) used Node 24.22.0, cf 1.0.0-rc.1 and Wrangler 4.166.0; smoke and bridge both passed `cf build` and `cf workers versions create --prebuilt --dry-run`. The bridge dry-run reported only `BRIDGE -> PrivateLaptopBridge`, disabled `ENABLED=false`, -placeholder Gateway identifiers and empty registry; it created nothing. This -turn did not rerun the CLI because the checkout has no installed `cf` binary. `deployment-config.test.mjs` verifies that the `cf` config is the sole +placeholder Gateway identifiers and empty registry; it created nothing. At that +earlier checkpoint the CLI was not installed in the checkout. The current +bootstrap draft has since rerun the pinned build and `cf deploy --dry-run`; +current exact output is recorded in `VERIFICATION.md`. `deployment-config.test.mjs` verifies that the `cf` config is the sole declarative DO lifecycle source and contains the expected SQLite export. It does not prove provider state. Gateway runtime unit tests and smoke tests pass. These results prove local Build Output and diff --git a/pm-stack/private-laptop-bridge/README.md b/pm-stack/private-laptop-bridge/README.md index 5506e34cbf..6b2ee87e91 100644 --- a/pm-stack/private-laptop-bridge/README.md +++ b/pm-stack/private-laptop-bridge/README.md @@ -218,6 +218,12 @@ Gateway RPC entrypoint can reach the signed bridge, after trusted-context checks. The real Gateway DNS, device enrollment and TLS-trust path still requires the approval packet's smoke. +The one-time disabled first-deployment workflow is a reviewed template with a +`.disabled` suffix outside `.github/workflows`; GitHub does not register it. +It remains dormant until the exact protected environment, reviewer policy, +source pin, and narrowly scoped read/write credentials are independently +verified. See [STAGING.md](STAGING.md) for its fixed target and gates. + No automatic PR CI or active schedule is added. The merged smoke init/upload workflows are manual; this branch retains a separate manual bridge release path that fails closed on missing owner proof. The optional process interval remains diff --git a/pm-stack/private-laptop-bridge/STAGING.md b/pm-stack/private-laptop-bridge/STAGING.md index ccd2e07d88..9c8f0cd0bd 100644 --- a/pm-stack/private-laptop-bridge/STAGING.md +++ b/pm-stack/private-laptop-bridge/STAGING.md @@ -35,7 +35,7 @@ digest instead of the account ID itself. The protected proof still checks the full ID inside the gated environment; this redaction does not weaken target matching. Schema 1 receipts are rejected. -### First disabled deployment plan +### First disabled deployment workflow draft Routine releases remain versions-only and must refuse an absent Worker or Durable Object namespace. A one-time first deployment, if later authorized, @@ -46,17 +46,58 @@ deployment step, not a second configuration or a legacy migration fallback. [cf project deploy](https://developers.cloudflare.com/cf/projects/) · [cf and Durable Object lifecycle](https://developers.cloudflare.com/cf/wrangler/reference/#convert-durable-object-migrations) -The proposed command sequence is a manual owner-controlled procedure, not a -GitHub workflow. It has not been run in this turn; first validate the pinned -CLI syntax/build with no credentials and stop if the pinned release differs -from current Cloudflare documentation: +The repository now contains a manual-only workflow template at +`private-laptop-bridge-staging-bootstrap.workflow.yml.disabled` and a +read-only gate/verification program in `staging-bootstrap.mjs`. The `.disabled` +file is deliberately outside `.github/workflows`; GitHub does not register it +and merging it cannot create or run a first-deploy job. It is a reviewable draft, +not an active or completed deployment. It has no caller-supplied target, input, +schedule, route, public hostname, Gateway policy, or runtime secret. + +If enabled after all listed prerequisites are independently established, the +workflow accepts only a manual dispatch from `main` in `developing-today/code`. +Its initial no-secret job reads the exact `cloudflare-staging-bootstrap` +environment and branch policy and checks the reviewer set and source SHA. Only +that successful check emits the fixed environment name for the later deploy job; +this prevents GitHub from auto-creating a missing, unprotected environment when +a job is assigned to it. The protected environment must require an independent +reviewer, disallow self-review, allow only `main`, and pin the exact reviewed +full source SHA. The template fails closed if any part is missing or differs. + +The deploy job runs the local build and pinned `cf deploy --dry-run`, verifies +the effective disabled Build Output, then uses separate read-only and +write-only credentials. Before its only possible provider write, read-only +checks inventory the full account zone set and every zone's Worker routes, +account Worker domains, the fixed Worker and SQLite namespace, schedules, +subdomain/preview flags, settings, versions and deployments. It refuses an +unknown or partial inventory, any route/domain, an orphan namespace, an +unexpected existing Worker, shared read/write tokens, or any effective config +that differs from the disabled artifact. Only when the Worker is absent and the +namespace is absent does the gated step run the pinned declarative +`cf deploy --mode bridge --prebuilt --provision` lifecycle. A second +read-only pass checks the exact serving version, single 100-percent deployment, +source-SHA tag, disabled settings, no ingress, and the same SQLite namespace +ID in the export and account inventory. It never changes Gateway or routes. + +The checked-in template has not been registered, dispatched, or run against +Cloudflare. The current protected environment, reviewer IDs, exact account and +zone inventory, and the separate read/write credentials are not available in +this checkout. Their secret values were not accessed. Cloudflare's narrowest +write scope for first creation of this absent Worker still needs an owner-side +permission review; do not silently broaden it or use a Workers-product token. +The read credential needs complete account zone/route inventory, Worker +metadata/settings/versions/deployments/domains, and Durable Object namespace +read. If those exact read scopes or an individual Worker write scope cannot be +provided, the workflow remains dormant and no provider change is allowed. + +The offline command sequence the workflow will use is: ```sh npm ci --ignore-scripts --no-audit --no-fund ./node_modules/.bin/cf build --mode bridge ./node_modules/.bin/cf deploy --mode bridge --prebuilt --dry-run -# Only after the separate approval and all preflight gates: -./node_modules/.bin/cf deploy --mode bridge --prebuilt +# The live command exists only in the dormant, environment-gated workflow. +# Never run it from a developer checkout. ``` The final command writes a deployment and provisions the `PrivateLaptopBridge` @@ -67,18 +108,24 @@ build. Do not pass `--force`, `--secrets-file`, or `--dispatch-namespace`. A successful local `--dry-run` proves config shape only; it is not permission to run the write. -Before the write, a separately authenticated read-only reviewer must confirm the -exact account and that the exact Worker name is absent; inventory every account -zone and its routes; list account Worker domains; read Gateway rules and callers; -and verify there is no name collision or existing binding to the class. Record -complete pagination and timestamps. If the Worker exists, an API response is -ambiguous, any pagination is incomplete, or any route/domain/Gateway path could -reach the target, stop without changing it. - -Immediately after the write, independently repeat the full inventory and verify -the same Worker identity and account, no routes/domains/triggers or Gateway -caller/Forward rule, workers.dev and preview URLs disabled, no runtime secrets, -and the exact disabled variables and resource limits. Verify the Worker's +Before the write, the protected workflow's separate read-only credential must +confirm the exact account and that the exact Worker name is absent; inventory +every account zone and its routes; list account Worker domains; and verify there +is no namespace collision or existing binding to the class. It records no +provider data in a public artifact. The declarative build contains no Gateway +binding, Gateway identifiers, or external service binding. This preflight does +not inventory account-level Gateway rules; those remain unconfigured by this +workflow and must receive a separate read-only review before any later attempt +to enable the bridge. If the Worker exists, an API response is ambiguous, any +pagination is incomplete, or any route/domain can reach the target, stop without +changing it. + +Immediately after the write, independently repeat the full zone/route and +Worker inventory and verify the same Worker identity and account, no +routes/domains/schedules, no Gateway binding, workers.dev and preview URLs +disabled, no runtime secrets, and the exact disabled variables and resource +limits. This is not proof about account-level Gateway rules or caller identity. +Verify the Worker's declarative export is `PrivateLaptopBridge` with `state=created` and `storage=sqlite`; verify the `BRIDGE` binding's namespace ID matches exactly one account namespace whose script is `private-laptop-bridge-staging`, class is @@ -93,20 +140,18 @@ and [Gateway rules](https://developers.cloudflare.com/api/resources/zero_trust/s Any mismatch means stop and keep the Worker disabled and unrouted; do not automatically delete it, retry deployment, or create a replacement namespace. -No automated first-deploy workflow is prepared yet. The `cloudflare-staging` -GitHub environment is absent; GitHub creates an unconfigured environment when a -workflow references a missing one, so no new workflow may reference it until a -repository admin creates and verifies its protection rules. The tracked proof -fixture records branch protection/reviews and environment reviewers as false. -The read-only branch-protection API request returned HTTP 403 for this GitHub -integration, so this session could not independently inspect the live branch -rule. Before a workflow exists, repository settings must require a fresh PR -approval on `main`, prevent admin bypass and force pushes, and configure a -dedicated `cloudflare-staging-bootstrap` environment with required reviewers, -self-review disabled, only `main` allowed, and an environment-only short-lived -deployment credential. Then configure a separate `cloudflare-staging` -environment for routine versions upload/promotion. GitHub's docs confirm that -missing environments are automatically created without protection rules. +`cloudflare-staging` remains absent, and the template uses the separate exact +`cloudflare-staging-bootstrap` environment for its one-time first deployment. +That bootstrap environment is also not verified as present or protected. The +tracked proof fixture still records branch protection/reviews and environment +reviewers as false. The read-only branch-protection API request returned HTTP +403 for this GitHub integration, so this session could not independently inspect +the live branch rule. Do not register the template until an authorized +repository administrator creates and independently verifies the bootstrap +environment and its protection. Routine `cloudflare-staging` versions upload +and promotion stay separately gated. GitHub creates an unconfigured environment +when a workflow references a missing one; the no-secret pre-job gate must stay +before environment assignment. [GitHub protected branches](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-protected-branches/about-protected-branches) · [GitHub environments](https://docs.github.com/en/actions/how-tos/deploy/configure-and-manage-deployments/manage-environments) @@ -162,10 +207,11 @@ laptop reach a private Worker. Service bindings likewise do not supply a laptop transport. No Workers VPC binding, Tunnel, public route, or generic network proxy is proposed. [Workers VPC services](https://developers.cloudflare.com/workers-vpc/configuration/vpc-services/) -**DNS/on-ramp gate is unresolved, not papered over.** Proposed host is -`private-bridge-staging.security.cab`, subject to confirming owner control and -absence of an existing record/wildcard route. Do not point it at `pm.security.cab` -or any real application. The intended arrangement has no public A/AAAA/CNAME and +**DNS/on-ramp gate is unresolved, not papered over.** The previously proposed +`private-bridge-staging.security.cab` is rejected: it matches an existing public +wildcard. Do not use or change it. Neither AMD nor the Aster caller has a +verified Gateway path. No replacement hostname is selected. The eventual +arrangement must have no public A/AAAA/CNAME and an exact-host Gateway DNS override to the non-serving documentation address `192.0.2.1` (proposed, not yet tested), with a 60-second DNS TTL where supported. No server or tunnel is attached to that address; confirm no local route repurposes it. @@ -230,6 +276,20 @@ failed lookup must deny. Gateway identity is an additional gate, never a replacement for the independently pinned caller/device signing keys. [Available context](https://developers.cloudflare.com/cloudflare-one/traffic-controls/integrate-workers/available-context/) +The existing credential-free Gateway smoke does not call `identity()` or +`devicePosture()`. It proves handler behavior for synthetic trusted context only. +The real `gateway.mjs` requires the configured exact email from +`identity().email` and the configured posture UUID in +`devicePosture().checks.passed`; an unregistered or unavailable posture check is +empty and must deny. Browser login, a DNS resolution, or a synthetic smoke does +not satisfy runtime acceptance. Before enabling any bridge reads, prove the +Gateway Forward call separately from each actual AMD and Aster Node process, +with each process's own identity and posture checks, and prove there is no +normal public URL or fallback route. Acceptance requires a successful direct +broker health/queue observation through the authorized path. A client-side +user/session-proxy queue timeout or synthetic empty snapshot is not evidence of +a successful direct broker check and cannot be reported as an idle queue. + Deploy using the owner's existing approved short-lived administrative mechanism. Runtime principals need **no Cloudflare API permissions**. The deployment actor needs Workers script deployment permissions for the chosen account; an owner @@ -241,7 +301,8 @@ minting a general automation token. No DNS-zone write permission is needed for the proposed Gateway-only override. No Access service token or Tunnel token is needed. [Gateway rule API](https://developers.cloudflare.com/api/go/resources/zero_trust/subresources/gateway/subresources/rules/methods/create/) -Review-only Forward request shape (not executed; placeholders must be resolved, +Historical review-only Forward request shape (rejected hostname; not executable +or approved; a replacement hostname and all placeholders must be resolved, precedence compared against existing rules, then the exact diff approved): ```json diff --git a/pm-stack/private-laptop-bridge/VERIFICATION.md b/pm-stack/private-laptop-bridge/VERIFICATION.md index 40074c3cfa..b3ff0d920d 100644 --- a/pm-stack/private-laptop-bridge/VERIFICATION.md +++ b/pm-stack/private-laptop-bridge/VERIFICATION.md @@ -275,3 +275,50 @@ Gateway caller inventory, and protected environment evidence are still required before upload/promotion. No deployment, Gateway change, laptop change, traffic, or cutover was attempted. `actionlint` was unavailable locally, and the repo's automatic PR CI is disabled; these are local results, not hosted checks. + +## Disabled first-deployment workflow draft — 2026-11-23 + +Added `staging-bootstrap.mjs` with synthetic provider and GitHub environment +gates, and `private-laptop-bridge-staging-bootstrap.workflow.yml.disabled`. +The template is outside `.github/workflows`, so it is not registered. Its +no-secret pre-job verifies the exact existing protected +`cloudflare-staging-bootstrap` environment and `main`-only branch policy before +the deploy job receives the environment assignment. There are no workflow +inputs or public URLs. The write step can only run the pinned declarative bridge +`cf deploy --mode bridge --prebuilt --provision` after complete read-only zone, +route, Worker-domain, target and namespace checks; postflight independently +checks the exact disabled version, deployment, no-public-ingress settings and +SQLite namespace binding. Existing served versions must carry the exact +environment-pinned source SHA to pass the idempotent path. The preflight step +receives only the read credential; the write credential is injected only into +the conditional deploy step and checked for distinctness immediately before the +write. Gateway rules are neither changed nor claimed as account-level verified +by this initialization draft. + +Verification on this source state: + +| Check | Result | +| --- | --- | +| `node --test staging-bootstrap.test.mjs deployment-config.test.mjs release-contract.test.mjs` | 19 passed, including missing/existing Worker, exact source-SHA and workflow-boundary fixtures | +| `npm test` from this package | 133 passed, 0 failed | +| `cf build --mode bridge` with Node 24.19.0 and pinned `cf@1.0.0-rc.1` | Passed; 17.84 KiB upload, 5.31 KiB gzip | +| `node staging-bootstrap.mjs validate-build` | Passed against the effective Build Output | +| `cf deploy --mode bridge --prebuilt --dry-run` | Passed; output showed only the disabled vars and `BRIDGE -> PrivateLaptopBridge`; dry-run exited before upload | +| Workflow YAML parse | Passed with Python PyYAML; expected two jobs found | +| `actionlint` | Not installed in this environment | +| `git diff --check` | Passed | + +The GitHub environment `cloudflare-staging-bootstrap`, its independent reviewer +IDs and source SHA, exact account/zone inventory, and separate protected read +and write credentials are not available or verified here. The required scope +for first creation of this Worker also remains an owner-side permission review. +No provider state was queried, no secret value was accessed, no workflow was +registered or dispatched, and no Cloudflare write occurred. The draft must stay +dormant until these exact prerequisites are independently established. The +separate runtime acceptance still needs real Gateway `identity()` and +`devicePosture()` checks from each AMD and Aster Node process; browser/DNS and +credential-free synthetic smoke results are insufficient. See +[`STAGING.md`](STAGING.md) for the direct-broker and no-fallback acceptance gate. +The previously proposed `private-bridge-staging.security.cab` hostname is +rejected because it matches an existing public wildcard; no replacement host +or AMD/Aster Gateway path is verified. diff --git a/pm-stack/private-laptop-bridge/private-laptop-bridge-staging-bootstrap.workflow.yml.disabled b/pm-stack/private-laptop-bridge/private-laptop-bridge-staging-bootstrap.workflow.yml.disabled new file mode 100644 index 0000000000..9cf5636cac --- /dev/null +++ b/pm-stack/private-laptop-bridge/private-laptop-bridge-staging-bootstrap.workflow.yml.disabled @@ -0,0 +1,109 @@ +# Dormant reviewed template. GitHub ignores this non-workflow extension. +# Enable only after `cloudflare-staging-bootstrap` exists with reviewers, +# prevent_self_review=true, a main-only branch policy and the exact source pin. +name: Private laptop bridge disabled staging bootstrap + +on: + workflow_dispatch: + +permissions: + actions: read + contents: read + +concurrency: + group: private-laptop-bridge-staging-bootstrap + cancel-in-progress: false + +jobs: + verify-environment-before-assignment: + if: github.repository == 'developing-today/code' && github.ref == 'refs/heads/main' && github.event_name == 'workflow_dispatch' + runs-on: ubuntu-24.04 + timeout-minutes: 5 + outputs: + environment: ${{ steps.gate.outputs.environment }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.sha }} + fetch-depth: 1 + persist-credentials: false + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + with: + node-version: 24.22.0 + - name: Verify existing protected environment without assigning it + id: gate + working-directory: pm-stack/private-laptop-bridge + env: + GH_TOKEN: ${{ github.token }} + GITHUB_API_URL: ${{ github.api_url }} + CF_BRIDGE_BOOTSTRAP_REVIEWER_IDS: ${{ vars.CF_BRIDGE_BOOTSTRAP_REVIEWER_IDS }} + run: node staging-bootstrap.mjs github-environment + + deploy-disabled-bridge: + needs: verify-environment-before-assignment + if: needs.verify-environment-before-assignment.result == 'success' && needs.verify-environment-before-assignment.outputs.environment == 'cloudflare-staging-bootstrap' + environment: + name: ${{ needs.verify-environment-before-assignment.outputs.environment }} + runs-on: ubuntu-24.04 + timeout-minutes: 25 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.sha }} + fetch-depth: 1 + persist-credentials: false + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + with: + node-version: 24.22.0 + cache: npm + cache-dependency-path: pm-stack/private-laptop-bridge/package-lock.json + - name: Require the exact environment-approved source SHA + env: + APPROVED_SOURCE_SHA: ${{ vars.CF_BRIDGE_BOOTSTRAP_APPROVED_SHA }} + run: | + set -euo pipefail + [[ "$GITHUB_REPOSITORY" == developing-today/code ]] + [[ "$GITHUB_REF" == refs/heads/main ]] + [[ "$GITHUB_EVENT_NAME" == workflow_dispatch ]] + [[ "$APPROVED_SOURCE_SHA" =~ ^[0-9a-f]{40}$ && "$APPROVED_SOURCE_SHA" == "$GITHUB_SHA" ]] + - name: Install locked dependencies + working-directory: pm-stack/private-laptop-bridge + run: npm ci --ignore-scripts --no-audit --no-fund + - name: Verify disabled bridge build and deploy dry run + working-directory: pm-stack/private-laptop-bridge + run: | + set -euo pipefail + node --test deployment-config.test.mjs release-contract.test.mjs staging-bootstrap.test.mjs + ./node_modules/.bin/cf build --mode bridge + ./node_modules/.bin/cf deploy --mode bridge --prebuilt --dry-run > "$RUNNER_TEMP/bridge-deploy-dry-run.log" 2>&1 + node staging-bootstrap.mjs validate-build + - name: Read current provider state and require absence or exact inert namespace + id: provider + working-directory: pm-stack/private-laptop-bridge + env: + CF_BRIDGE_BOOTSTRAP_ACCOUNT_ID: ${{ secrets.CF_BRIDGE_BOOTSTRAP_ACCOUNT_ID }} + CF_BRIDGE_BOOTSTRAP_ZONE_IDS: ${{ secrets.CF_BRIDGE_BOOTSTRAP_ZONE_IDS }} + CF_BRIDGE_BOOTSTRAP_READ_TOKEN: ${{ secrets.CF_BRIDGE_BOOTSTRAP_READ_TOKEN }} + GITHUB_SHA: ${{ github.sha }} + run: node staging-bootstrap.mjs preflight + - name: Deploy only the pinned disabled declarative Worker and SQLite export + if: steps.provider.outputs.status == 'deploy' + working-directory: pm-stack/private-laptop-bridge + env: + CF_BRIDGE_BOOTSTRAP_READ_TOKEN: ${{ secrets.CF_BRIDGE_BOOTSTRAP_READ_TOKEN }} + CF_BRIDGE_BOOTSTRAP_WRITE_TOKEN: ${{ secrets.CF_BRIDGE_BOOTSTRAP_WRITE_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CF_BRIDGE_BOOTSTRAP_ACCOUNT_ID }} + CLOUDFLARE_API_TOKEN: ${{ secrets.CF_BRIDGE_BOOTSTRAP_WRITE_TOKEN }} + run: | + set -euo pipefail + node staging-bootstrap.mjs assert-distinct-credentials + ./node_modules/.bin/cf deploy --mode bridge --prebuilt --provision --tag "$GITHUB_SHA" --message "disabled bridge first deployment $GITHUB_SHA" > "$RUNNER_TEMP/bridge-deploy.log" 2>&1 + - name: Independently verify no ingress and exact serving namespace + if: steps.provider.outputs.status == 'deploy' + working-directory: pm-stack/private-laptop-bridge + env: + CF_BRIDGE_BOOTSTRAP_ACCOUNT_ID: ${{ secrets.CF_BRIDGE_BOOTSTRAP_ACCOUNT_ID }} + CF_BRIDGE_BOOTSTRAP_ZONE_IDS: ${{ secrets.CF_BRIDGE_BOOTSTRAP_ZONE_IDS }} + CF_BRIDGE_BOOTSTRAP_READ_TOKEN: ${{ secrets.CF_BRIDGE_BOOTSTRAP_READ_TOKEN }} + GITHUB_SHA: ${{ github.sha }} + run: node staging-bootstrap.mjs postflight diff --git a/pm-stack/private-laptop-bridge/staging-bootstrap.mjs b/pm-stack/private-laptop-bridge/staging-bootstrap.mjs new file mode 100644 index 0000000000..f6f1d24d3c --- /dev/null +++ b/pm-stack/private-laptop-bridge/staging-bootstrap.mjs @@ -0,0 +1,362 @@ +#!/usr/bin/env node +// Read-only gates for the dormant fixed-target bridge bootstrap workflow. +// This program never writes to Cloudflare. Only the separate reviewed workflow +// may invoke pinned `cf deploy` after these checks pass. +import {createHash} from 'node:crypto'; +import {readFile, writeFile} from 'node:fs/promises'; +import {assertEffectivePayload} from './release-contract.mjs'; + +export const CLOUDFLARE_API = 'https://api.cloudflare.com/client/v4'; +export const GITHUB_REPOSITORY = 'developing-today/code'; +export const ENVIRONMENT_NAME = 'cloudflare-staging-bootstrap'; +export const WORKER_NAME = 'private-laptop-bridge-staging'; +export const DO_CLASS = 'PrivateLaptopBridge'; +const PAGE_SIZE = 100; +const ZONE_PAGE_SIZE = 50; +const HASH = /^[a-f0-9]{64}$/; +const ID = /^[a-f0-9]{32}$/i; +const UUID = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i; +const fail = message => { throw new Error(message); }; + +function parseIds(value, label) { + let ids; + try { ids = typeof value === 'string' ? JSON.parse(value) : value; } + catch { fail(`${label} is invalid`); } + if (!Array.isArray(ids) || ids.some(id => typeof id !== 'string' || !ID.test(id))) fail(`${label} is missing or invalid`); + const normalized = ids.map(id => id.toLowerCase()).sort(); + if (new Set(normalized).size !== normalized.length) fail(`${label} contains duplicates`); + return normalized; +} + +function parseReviewerIds(value) { + let ids; + try { ids = typeof value === 'string' ? JSON.parse(value) : value; } + catch { fail('expected independent reviewer IDs are invalid'); } + if (!Array.isArray(ids) || ids.length === 0 || ids.some(id => !(Number.isInteger(id) && id > 0) && !(typeof id === 'string' && /^[1-9][0-9]{0,19}$/.test(id)))) { + fail('expected independent reviewer IDs are missing or invalid'); + } + const normalized = ids.map(String).sort(); + if (new Set(normalized).size !== normalized.length) fail('expected independent reviewer IDs contain duplicates'); + return normalized; +} + +export function verifyEnvironmentProtection({environment, branchPolicies, expectedReviewerIds}) { + if (!environment || environment.name !== ENVIRONMENT_NAME || !Array.isArray(environment.protection_rules)) { + fail('the exact protected staging environment is absent or unverifiable'); + } + const expected = parseReviewerIds(expectedReviewerIds); + const rules = environment.protection_rules; + const reviewers = rules.filter(rule => rule?.type === 'required_reviewers'); + if (reviewers.length !== 1 || reviewers[0].prevent_self_review !== true || !Array.isArray(reviewers[0].reviewers)) { + fail('staging environment reviewer protection is absent or allows self-review'); + } + const actual = reviewers[0].reviewers.map(item => item?.reviewer?.id).filter(Number.isInteger).map(String).sort(); + if (actual.length !== expected.length || actual.some((id, index) => id !== expected[index])) { + fail('staging environment reviewers do not match the independently approved set'); + } + const branch = environment.deployment_branch_policy; + if (branch?.protected_branches !== false || branch?.custom_branch_policies !== true) { + fail('staging environment is not restricted by an explicit branch policy'); + } + const rows = branchPolicies?.branch_policies; + if (!Array.isArray(rows) || branchPolicies.total_count !== rows.length || rows.length !== 1 || rows[0]?.name !== 'main') { + fail('staging environment deployment policy must allow only main'); + } + return {environment: ENVIRONMENT_NAME}; +} + +async function apiRequest(fetchImpl, url, token) { + let response; + try { + response = await fetchImpl(url, { + method: 'GET', + headers: {authorization: `Bearer ${token}`, accept: 'application/json'}, + redirect: 'error', + signal: AbortSignal.timeout(15_000), + }); + } catch { fail('read-only provider request failed before a verified response'); } + let body; + try { body = await response.json(); } + catch { fail(`read-only provider returned invalid JSON (HTTP ${response.status})`); } + return {response, body}; +} + +async function cfRequest(fetchImpl, accountId, token, path, {allowMissingWorker = false} = {}) { + const url = `${CLOUDFLARE_API}/accounts/${encodeURIComponent(accountId)}${path}`; + const {response, body} = await apiRequest(fetchImpl, url, token); + if (allowMissingWorker && response.status === 404) { + const parsed = new URL(url); + const exact = parsed.origin === new URL(CLOUDFLARE_API).origin && parsed.pathname === `${new URL(CLOUDFLARE_API).pathname}/accounts/${accountId}/workers/workers/${WORKER_NAME}` && parsed.search === ''; + if (exact && body?.success === false && (body.result === null || !Object.hasOwn(body, 'result')) && + Array.isArray(body.errors) && body.errors.length === 1 && body.errors[0]?.code === 10007) return null; + } + if (!response.ok || body?.success !== true || !Object.hasOwn(body, 'result')) { + fail(`read-only provider response was denied or incomplete (HTTP ${response.status})`); + } + return {result: body.result, resultInfo: body.result_info}; +} + +function rowsOf(value, label) { + const rows = Array.isArray(value) ? value : value?.items; + if (!Array.isArray(rows)) fail(`${label} returned no verifiable list`); + return rows; +} + +async function listPages(fetchImpl, accountId, token, path, {params = {}, pageSize = PAGE_SIZE, resultPath} = {}) { + const all = []; + let totalCount, totalPages; + for (let page = 1; page <= 100; page += 1) { + const query = new URLSearchParams({...params, page: String(page), per_page: String(pageSize)}); + let response; + if (path === '/zones') { + const url = `${CLOUDFLARE_API}${path}?${query}`; + const raw = await apiRequest(fetchImpl, url, token); + if (!raw.response.ok || raw.body?.success !== true || !Object.hasOwn(raw.body, 'result')) fail(`zone list is unavailable (HTTP ${raw.response.status})`); + response = {result: raw.body.result, resultInfo: raw.body.result_info}; + } else { + response = await cfRequest(fetchImpl, accountId, token, `${path}?${query}`); + } + const listValue = resultPath ? response.result?.[resultPath] : response.result; + const rows = rowsOf(listValue, 'provider list'); + all.push(...rows); + const info = response.resultInfo; + if (info !== undefined) { + if (!info || typeof info !== 'object' || Array.isArray(info)) fail('provider pagination metadata is malformed'); + if (info.page !== undefined && info.page !== page) fail('provider pagination page did not match the request'); + if (info.per_page !== undefined && info.per_page !== pageSize) fail('provider pagination size did not match the request'); + if (info.total_count !== undefined) { + if (!Number.isInteger(info.total_count) || info.total_count < 0) fail('provider pagination total is malformed'); + if (totalCount === undefined) totalCount = info.total_count; + if (totalCount !== info.total_count) fail('provider list changed while paging'); + } + if (info.total_pages !== undefined) { + if (!Number.isInteger(info.total_pages) || info.total_pages < 0 || info.total_pages > 100) fail('provider page total is malformed'); + if (totalPages === undefined) totalPages = info.total_pages; + if (totalPages !== info.total_pages) fail('provider list changed while paging'); + } + } + const byPages = totalPages !== undefined && (totalPages === 0 ? page === 1 && all.length === 0 : page >= totalPages); + const byCount = totalCount !== undefined && all.length === totalCount; + const byShortPage = info === undefined && rows.length < pageSize; + if (byPages || byCount || byShortPage) { + if (totalCount !== undefined && all.length !== totalCount) fail('provider list is incomplete'); + return all; + } + if (rows.length < pageSize) fail('provider list ended before its pagination total'); + } + fail('provider pagination exceeded the hard bound'); +} + +async function readZones(fetchImpl, accountId, token, expectedZoneIds) { + const zones = await listPages(fetchImpl, accountId, token, '/zones', { + params: {'account.id': accountId, type: 'full,partial,secondary,internal'}, pageSize: ZONE_PAGE_SIZE, + }); + const found = []; + for (const zone of zones) { + if (!ID.test(zone?.id ?? '') || zone?.account?.id?.toLowerCase() !== accountId.toLowerCase()) fail('account zone inventory has an invalid owner or ID'); + found.push(zone.id.toLowerCase()); + } + found.sort(); + if (found.length !== expectedZoneIds.length || found.some((id, index) => id !== expectedZoneIds[index])) { + fail('full account zone inventory differs from the protected expected inventory'); + } + return zones; +} + +async function readRoutes(fetchImpl, accountId, token, zones) { + const routes = []; + for (const zone of zones) { + const url = `${CLOUDFLARE_API}/zones/${encodeURIComponent(zone.id)}/workers/routes`; + const {response, body} = await apiRequest(fetchImpl, url, token); + if (!response.ok || body?.success !== true || !Array.isArray(body.result)) fail('zone Worker route inventory is unavailable or malformed'); + routes.push(...body.result); + } + if (routes.some(route => route?.script === WORKER_NAME)) fail('a zone route already targets the fixed staging Worker'); + return routes; +} + +function verifyVersion(version, namespaceId) { + if (!version || !Array.isArray(version.resources?.bindings) || !version.exports || typeof version.exports !== 'object') { + fail('deployed Worker version lacks independently readable bindings or declarative exports'); + } + const expectedVars = { + ENABLED: 'false', GATEWAY_HOST: 'private-bridge-staging.invalid', GATEWAY_ACCOUNT_ID: '', + GATEWAY_POLICY_ID: '', GATEWAY_IDENTITY_EMAIL: '', GATEWAY_POSTURE_ID: '', BRIDGE_REGISTRY: '', + }; + const bindings = version.resources.bindings; + const vars = bindings.filter(binding => binding?.type === 'plain_text'); + const actualVars = Object.fromEntries(vars.map(binding => [binding.name, binding.text ?? binding.value])); + if (JSON.stringify(Object.entries(actualVars).sort()) !== JSON.stringify(Object.entries(expectedVars).sort())) { + fail('deployed Worker variables are not the fixed disabled configuration'); + } + const durable = bindings.filter(binding => binding?.type === 'durable_object_namespace'); + if (bindings.length !== Object.keys(expectedVars).length + 1 || durable.length !== 1 || durable[0]?.name !== 'BRIDGE' || + durable[0]?.class_name !== DO_CLASS || durable[0]?.namespace_id !== namespaceId) { + fail('deployed Worker has an unexpected binding or the BRIDGE namespace differs'); + } + const exportValue = version.exports[DO_CLASS]; + const exportKeys = Object.keys(version.exports).sort(); + if (exportKeys.length !== 1 || exportKeys[0] !== DO_CLASS || exportValue?.type !== 'durable-object' || + exportValue?.storage !== 'sqlite' || (exportValue?.state !== undefined && exportValue.state !== 'created')) { + fail('deployed Worker does not declare exactly the expected SQLite export'); + } + if (version.limits?.cpu_ms !== 10 || version.hasPreview === true) fail('deployed Worker limits or preview state differ from the disabled build'); + return true; +} + +function verifyWorkerMetadata(worker) { + if (!worker || worker.name !== WORKER_NAME || !ID.test(worker.id ?? '') || worker.logpush !== false || + worker.observability?.enabled !== false || !worker.references || !Array.isArray(worker.references.domains) || + worker.references.domains.length !== 0) fail('Worker metadata is missing or exposes unexpected domains or telemetry'); + return worker.id; +} + +async function readSnapshot({accountId, token, expectedZoneIds, fetchImpl = fetch}) { + const zones = await readZones(fetchImpl, accountId, token, expectedZoneIds); + await readRoutes(fetchImpl, accountId, token, zones); + const allDomains = await listPages(fetchImpl, accountId, token, '/workers/domains'); + if (allDomains.some(domain => domain?.service === WORKER_NAME)) fail('fixed staging Worker has an attached domain'); + const allNamespaces = await listPages(fetchImpl, accountId, token, '/workers/durable_objects/namespaces', {pageSize: 1000}); + const namespaces = allNamespaces.filter(item => item?.script === WORKER_NAME); + const worker = await cfRequest(fetchImpl, accountId, token, `/workers/workers/${WORKER_NAME}`, {allowMissingWorker: true}); + if (!worker) return {worker: null, namespaces, domains: [], zoneIds: zones.map(zone => zone.id.toLowerCase()).sort()}; + const workerId = verifyWorkerMetadata(worker.result); + const subdomain = await cfRequest(fetchImpl, accountId, token, `/workers/scripts/${WORKER_NAME}/subdomain`); + if (subdomain.result?.enabled !== false || subdomain.result?.previews_enabled !== false) fail('Worker subdomain or preview ingress is enabled'); + const settings = await cfRequest(fetchImpl, accountId, token, `/workers/scripts/${WORKER_NAME}/script-settings`); + if (settings.result?.logpush !== false || settings.result?.observability?.enabled !== false || + !Array.isArray(settings.result?.tail_consumers) || settings.result.tail_consumers.length !== 0) { + fail('Worker logging, observability, or tail consumer settings are not explicitly disabled'); + } + const schedules = await cfRequest(fetchImpl, accountId, token, `/workers/scripts/${WORKER_NAME}/schedules`); + if (!Array.isArray(schedules.result?.schedules) || schedules.result.schedules.length !== 0) fail('Worker schedules are missing or non-empty'); + const versions = await listPages(fetchImpl, accountId, token, `/workers/workers/${workerId}/versions`); + const deployResponse = await cfRequest(fetchImpl, accountId, token, `/workers/scripts/${WORKER_NAME}/deployments?page=1&per_page=100`, { }); + const deployments = deployResponse.result?.deployments; + if (!Array.isArray(deployments)) fail('Worker deployment readback is missing'); + return {worker: worker.result, workerId, subdomain: subdomain.result, settings: settings.result, + schedules: schedules.result.schedules, namespaces, domains: [], versions, deployments, + zoneIds: zones.map(zone => zone.id.toLowerCase()).sort()}; +} + +export function verifyProviderState(snapshot, {phase, expectedZoneIds, sourceSha}) { + if (!['preflight', 'postflight'].includes(phase)) fail('provider verification phase is invalid'); + const expected = parseIds(expectedZoneIds, 'approved zone inventory'); + if (!snapshot || !Array.isArray(snapshot.namespaces) || !Array.isArray(snapshot.domains) || !Array.isArray(snapshot.zoneIds) || + snapshot.zoneIds.length !== expected.length || snapshot.zoneIds.some((id, index) => id !== expected[index])) fail('provider inventory snapshot is incomplete or has the wrong account zones'); + if (!snapshot.worker) { + if (phase === 'postflight') fail('Worker is still absent after pinned deploy'); + if (snapshot.namespaces.length !== 0 || snapshot.domains.length !== 0) fail('an orphan namespace or domain exists for the absent Worker'); + return 'deploy'; + } + const id = verifyWorkerMetadata(snapshot.worker); + if (snapshot.workerId !== id || snapshot.subdomain?.enabled !== false || snapshot.subdomain?.previews_enabled !== false || + !Array.isArray(snapshot.schedules) || snapshot.schedules.length !== 0 || !Array.isArray(snapshot.versions) || + !Array.isArray(snapshot.deployments) || snapshot.deployments.length === 0 || snapshot.settings?.logpush !== false || + snapshot.settings?.observability?.enabled !== false || !Array.isArray(snapshot.settings?.tail_consumers) || snapshot.settings.tail_consumers.length !== 0) { + fail('existing Worker is not fully verified as disabled and serving safely'); + } + if (snapshot.domains.length !== 0 || snapshot.namespaces.length !== 1) fail('existing Worker domain or SQLite namespace inventory is unexpected'); + const namespace = snapshot.namespaces[0]; + if (!ID.test(namespace?.id ?? '') && !UUID.test(namespace?.id ?? '')) fail('Durable Object namespace ID is invalid'); + if (namespace.script !== WORKER_NAME || namespace.class !== DO_CLASS || namespace.use_sqlite !== true) fail('Durable Object namespace owner, class, or SQLite mode is unexpected'); + const deployment = snapshot.deployments[0]; + if (!deployment || !UUID.test(deployment.id ?? '') || !Array.isArray(deployment.versions) || deployment.versions.length !== 1 || + deployment.versions[0]?.percentage !== 100 || !UUID.test(deployment.versions[0]?.version_id ?? '')) fail('latest serving deployment is not an exact 100 percent single-version deployment'); + const versions = snapshot.versions.filter(version => version.id === deployment.versions[0].version_id); + if (versions.length !== 1) fail('latest serving deployment version is absent or ambiguous'); + verifyVersion(versions[0], namespace.id); + if (!/^[a-f0-9]{40}$/.test(sourceSha ?? '') || versions[0].annotations?.['workers/tag'] !== sourceSha) { + fail('latest serving version is not tagged to this exact reviewed source SHA'); + } + return phase === 'preflight' ? 'already-ready' : 'verified'; +} + +export async function verifyBootstrapPreflight({accountId, readToken, expectedZoneIds, sourceSha, fetchImpl = fetch}) { + if (!ID.test(accountId ?? '') || typeof readToken !== 'string' || readToken.length < 20) fail('protected bootstrap account or read-only credential is missing'); + const zones = parseIds(expectedZoneIds, 'approved zone inventory'); + const snapshot = await readSnapshot({accountId, token: readToken, expectedZoneIds: zones, fetchImpl}); + return verifyProviderState(snapshot, {phase: 'preflight', expectedZoneIds: zones, sourceSha}); +} + +export function verifyDistinctWriteCredential(readToken, writeToken) { + if (typeof readToken !== 'string' || readToken.length < 20 || typeof writeToken !== 'string' || + writeToken.length < 20 || readToken === writeToken) fail('protected read and write credentials must be separate'); + return true; +} + +export async function verifyBootstrapPostflight({accountId, readToken, expectedZoneIds, sourceSha, fetchImpl = fetch}) { + if (!ID.test(accountId ?? '') || typeof readToken !== 'string' || readToken.length < 20) fail('protected read-only provider identity is missing'); + const zones = parseIds(expectedZoneIds, 'approved zone inventory'); + const snapshot = await readSnapshot({accountId, token: readToken, expectedZoneIds: zones, fetchImpl}); + return verifyProviderState(snapshot, {phase: 'postflight', expectedZoneIds: zones, sourceSha}); +} + +export async function validateLocalBuild({buildOutput, mode = 'bridge'}) { + const {readFile} = await import('node:fs/promises'); + const root = buildOutput.replace(/\/$/, ''); + const metadata = JSON.parse(await readFile(`${root}/config.json`, 'utf8')); + if (metadata.producer?.name !== 'wrangler' || metadata.producer?.version !== '4.166.0' || metadata.buildContext?.mode !== mode) { + fail('local Build Output producer or mode is not pinned'); + } + const config = JSON.parse(await readFile(`${root}/workers/default/worker.config.json`, 'utf8')); + assertEffectivePayload(config, {worker: WORKER_NAME, mode}); + return true; +} + +async function githubEnvironmentGate() { + const token = process.env.GH_TOKEN; + const api = process.env.GITHUB_API_URL; + if (!token || !api || process.env.GITHUB_REPOSITORY !== GITHUB_REPOSITORY || process.env.GITHUB_EVENT_NAME !== 'workflow_dispatch' || + process.env.GITHUB_REF !== 'refs/heads/main' || !/^[a-f0-9]{40}$/.test(process.env.GITHUB_SHA ?? '')) { + fail('bootstrap dispatch is not from the fixed repository and main source'); + } + const base = `${api.replace(/\/$/, '')}/repos/${GITHUB_REPOSITORY}/environments/${ENVIRONMENT_NAME}`; + const headers = {authorization: `Bearer ${token}`, accept: 'application/vnd.github+json', 'x-github-api-version': '2022-11-28'}; + const envResponse = await fetch(`${base}`, {headers, redirect: 'error', signal: AbortSignal.timeout(15_000)}); + if (!envResponse.ok) fail('protected bootstrap environment does not exist or cannot be read; deployment job was not admitted'); + const environment = await envResponse.json(); + const policyResponse = await fetch(`${base}/deployment-branch-policies?per_page=100&page=1`, {headers, redirect: 'error', signal: AbortSignal.timeout(15_000)}); + if (!policyResponse.ok) fail('protected bootstrap branch policy cannot be read'); + const policies = await policyResponse.json(); + const expected = process.env.CF_BRIDGE_BOOTSTRAP_REVIEWER_IDS; + const result = verifyEnvironmentProtection({environment, branchPolicies: policies, expectedReviewerIds: expected}); + const outputPath = process.env.GITHUB_OUTPUT; + if (!outputPath) fail('workflow output channel is unavailable'); + await writeFile(outputPath, `environment=${result.environment}\n`, {flag: 'a', mode: 0o600}); + console.log('existing protected environment verified; deployment job may be assigned'); +} + +async function providerCheck(phase) { + const path = process.env.GITHUB_OUTPUT; + const result = phase === 'preflight' + ? await verifyBootstrapPreflight({accountId: process.env.CF_BRIDGE_BOOTSTRAP_ACCOUNT_ID, + readToken: process.env.CF_BRIDGE_BOOTSTRAP_READ_TOKEN, + expectedZoneIds: process.env.CF_BRIDGE_BOOTSTRAP_ZONE_IDS, sourceSha: process.env.GITHUB_SHA}) + : await verifyBootstrapPostflight({accountId: process.env.CF_BRIDGE_BOOTSTRAP_ACCOUNT_ID, + readToken: process.env.CF_BRIDGE_BOOTSTRAP_READ_TOKEN, expectedZoneIds: process.env.CF_BRIDGE_BOOTSTRAP_ZONE_IDS, + sourceSha: process.env.GITHUB_SHA}); + if (phase === 'preflight') { + if (!path) fail('workflow output channel is unavailable'); + await writeFile(path, `status=${result}\n`, {flag: 'a', mode: 0o600}); + } + console.log(phase === 'preflight' ? `read-only preflight passed (${result})` : 'independent no-ingress postflight passed'); +} + +async function main() { + const [command, ...args] = process.argv.slice(2); + if (args.length !== 0) fail(`usage: staging-bootstrap.mjs `); + if (command === 'github-environment') await githubEnvironmentGate(); + else if (command === 'preflight') await providerCheck('preflight'); + else if (command === 'postflight') await providerCheck('postflight'); + else if (command === 'assert-distinct-credentials') { + verifyDistinctWriteCredential(process.env.CF_BRIDGE_BOOTSTRAP_READ_TOKEN, process.env.CF_BRIDGE_BOOTSTRAP_WRITE_TOKEN); + console.log('separate read and write credentials verified'); + } + else if (command === 'validate-build') await validateLocalBuild({buildOutput: process.env.BUILD_OUTPUT ?? '.cloudflare/output/v1'}); + else fail('usage: staging-bootstrap.mjs '); +} + +if (process.argv[1] && new URL(import.meta.url).pathname === process.argv[1]) { + main().catch(error => { console.error(error instanceof Error ? error.message : 'staging bootstrap failed'); process.exitCode = 1; }); +} diff --git a/pm-stack/private-laptop-bridge/staging-bootstrap.test.mjs b/pm-stack/private-laptop-bridge/staging-bootstrap.test.mjs new file mode 100644 index 0000000000..07a553653f --- /dev/null +++ b/pm-stack/private-laptop-bridge/staging-bootstrap.test.mjs @@ -0,0 +1,154 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {readFile} from 'node:fs/promises'; +import {resolve} from 'node:path'; +import {verifyBootstrapPostflight, verifyBootstrapPreflight, verifyDistinctWriteCredential, verifyEnvironmentProtection, verifyProviderState, ENVIRONMENT_NAME, WORKER_NAME, DO_CLASS} from './staging-bootstrap.mjs'; + +const accountId = 'a'.repeat(32); +const zoneId = '1'.repeat(32); +const workerId = '2'.repeat(32); +const namespaceId = '3'.repeat(32); +const sha = 'b'.repeat(40); +const versionId = '01234567-89ab-cdef-0123-456789abcdef'; +const deploymentId = '11111111-2222-3333-4444-555555555555'; +const readToken = 'synthetic-read-token-long-enough'; +const writeToken = 'synthetic-write-token-long-enough'; +const worker = {id:workerId,name:WORKER_NAME,logpush:false,observability:{enabled:false},references:{domains:[]}}; +const version = () => ({ + id:versionId, + annotations:{'workers/tag':sha}, + limits:{cpu_ms:10}, + exports:{[DO_CLASS]:{type:'durable-object',storage:'sqlite',state:'created'}}, + resources:{bindings:[ + {name:'ENABLED',type:'plain_text',text:'false'}, + {name:'GATEWAY_HOST',type:'plain_text',text:'private-bridge-staging.invalid'}, + {name:'GATEWAY_ACCOUNT_ID',type:'plain_text',text:''}, + {name:'GATEWAY_POLICY_ID',type:'plain_text',text:''}, + {name:'GATEWAY_IDENTITY_EMAIL',type:'plain_text',text:''}, + {name:'GATEWAY_POSTURE_ID',type:'plain_text',text:''}, + {name:'BRIDGE_REGISTRY',type:'plain_text',text:''}, + {name:'BRIDGE',type:'durable_object_namespace',class_name:DO_CLASS,namespace_id:namespaceId}, + ]}, +}); +const deployment = () => ({id:deploymentId,versions:[{version_id:versionId,percentage:100}]}); +const ns = () => ({id:namespaceId,script:WORKER_NAME,class:DO_CLASS,use_sqlite:true}); +const snapshot = () => ({ + zoneIds:[zoneId],worker,workerId,subdomain:{enabled:false,previews_enabled:false}, + settings:{logpush:false,observability:{enabled:false},tail_consumers:[]},schedules:[], + namespaces:[ns()],domains:[],versions:[version()],deployments:[deployment()], +}); + +test('first-deploy workflow remains dormant, fixed-target, and checks protection before environment assignment', async()=>{ + const workflowPath=resolve('private-laptop-bridge-staging-bootstrap.workflow.yml.disabled'); + const workflow=await readFile(workflowPath,'utf8'); + assert.equal(workflowPath.includes('/.github/workflows/'),false); + assert.match(workflow,/workflow_dispatch:/); + assert.doesNotMatch(workflow,/^\s+inputs:/m); + assert.match(workflow,/if: github\.repository == 'developing-today\/code' && github\.ref == 'refs\/heads\/main' && github\.event_name == 'workflow_dispatch'/); + assert.match(workflow,/name: \$\{\{ needs\.verify-environment-before-assignment\.outputs\.environment \}\}/); + assert.match(workflow,/needs: verify-environment-before-assignment/); + assert.match(workflow,/CF_BRIDGE_BOOTSTRAP_REVIEWER_IDS: \$\{\{ vars\.CF_BRIDGE_BOOTSTRAP_REVIEWER_IDS \}\}/); + const gate=workflow.split(' deploy-disabled-bridge:',1)[0]; + assert.doesNotMatch(gate,/secrets\./); + const provider=workflow.split(' - name: Read current provider state')[1].split(' - name: Deploy only')[0]; + assert.match(provider,/CF_BRIDGE_BOOTSTRAP_READ_TOKEN/); + assert.doesNotMatch(provider,/CF_BRIDGE_BOOTSTRAP_WRITE_TOKEN/); + assert.match(workflow,/staging-bootstrap\.mjs assert-distinct-credentials/); + assert.match(workflow,/cf deploy --mode bridge --prebuilt --provision --tag "\$GITHUB_SHA"/); + assert.doesNotMatch(workflow,/wrangler deploy|workers versions (create|deploy)|--dispatch-namespace/); + for(const fixed of [WORKER_NAME,'CF_BRIDGE_BOOTSTRAP_ACCOUNT_ID','CF_BRIDGE_BOOTSTRAP_ZONE_IDS',ENVIRONMENT_NAME]) assert.ok(workflow.includes(fixed)); +}); + +function response(result, {status=200,resultInfo={page:1,per_page:100,total_count:Array.isArray(result)?result.length:0,total_pages:1},success=true,errors=[]}={}) { + return new Response(JSON.stringify({success,result,errors,...(resultInfo === undefined ? {} : {result_info:resultInfo})}),{status}); +} + +function cloudflareFixture({target='absent', zones=[{id:zoneId,account:{id:accountId}}], zoneInfo, route=[], domains=[], namespaces=[], workerRecord=worker, versions=[version()], deployments=[deployment()], overrides={}}={}) { + const calls=[]; + const fetchImpl=async (url,init={})=>{ + const parsed=new URL(url), method=init.method??'GET'; + calls.push({url:parsed,method,token:init.headers?.authorization}); + if(method!=='GET') return new Response('{}',{status:405}); + if(parsed.pathname==='/client/v4/zones') return response(zones,{resultInfo:zoneInfo??{page:1,per_page:50,total_count:zones.length,total_pages:zones.length?1:0}}); + if(parsed.pathname===`/client/v4/zones/${zoneId}/workers/routes`) return response(route,{resultInfo:undefined}); + if(parsed.pathname==='/client/v4/accounts/'+accountId+'/workers/domains') return response(domains); + if(parsed.pathname==='/client/v4/accounts/'+accountId+'/workers/durable_objects/namespaces') return response(namespaces,{resultInfo:{page:1,per_page:1000,total_count:namespaces.length,total_pages:namespaces.length?1:0}}); + if(parsed.pathname===`/client/v4/accounts/${accountId}/workers/workers/${WORKER_NAME}`) { + if(target==='absent') return response(null,{status:404,success:false,resultInfo:undefined,errors:[{code:10007}]}); + return response(workerRecord,{resultInfo:undefined}); + } + if(parsed.pathname.endsWith(`/workers/scripts/${WORKER_NAME}/subdomain`)) return response({enabled:false,previews_enabled:false}); + if(parsed.pathname.endsWith(`/workers/scripts/${WORKER_NAME}/script-settings`)) return response({logpush:false,observability:{enabled:false},tail_consumers:[]}); + if(parsed.pathname.endsWith(`/workers/scripts/${WORKER_NAME}/schedules`)) return response({schedules:[]}); + if(parsed.pathname.endsWith(`/workers/workers/${workerId}/versions`)) return response(versions); + if(parsed.pathname.endsWith(`/workers/scripts/${WORKER_NAME}/deployments`)) return response({deployments}); + const replacement=overrides[parsed.pathname]; + if(replacement) return replacement; + throw new Error(`unexpected synthetic request ${method} ${parsed.pathname}`); + }; + return {fetchImpl,calls}; +} + +test('GitHub dispatch gate requires the existing exact environment, exact independent reviewer set, no self-approval and main only',()=>{ + const environment={name:ENVIRONMENT_NAME,protection_rules:[{type:'required_reviewers',prevent_self_review:true,reviewers:[{type:'User',reviewer:{id:71}}]}],deployment_branch_policy:{protected_branches:false,custom_branch_policies:true}}; + const branchPolicies={total_count:1,branch_policies:[{name:'main'}]}; + assert.deepEqual(verifyEnvironmentProtection({environment,branchPolicies,expectedReviewerIds:'[71]'}),{environment:ENVIRONMENT_NAME}); + for(const change of [ + {environment:null}, + {environment:{...environment,name:'cloudflare-staging'}}, + {environment:{...environment,protection_rules:[{type:'required_reviewers',prevent_self_review:false,reviewers:[{type:'User',reviewer:{id:71}}]}]}}, + {environment:{...environment,protection_rules:[{type:'required_reviewers',prevent_self_review:true,reviewers:[{type:'User',reviewer:{id:72}}]}]}}, + {branchPolicies:{total_count:2,branch_policies:[{name:'main'},{name:'release/*'}]}}, + {branchPolicies:{total_count:1,branch_policies:[{name:'*'}]}}, + ]) assert.throws(()=>verifyEnvironmentProtection({environment:Object.hasOwn(change,'environment')?change.environment:environment,branchPolicies:change.branchPolicies??branchPolicies,expectedReviewerIds:'[71]'})); + assert.throws(()=>verifyEnvironmentProtection({environment,branchPolicies,expectedReviewerIds:''})); +}); + +test('missing Worker is deployable only after complete read-only account inventory; all provider calls are GET',async()=>{ + const f=cloudflareFixture({target:'absent'}); + const status=await verifyBootstrapPreflight({accountId,readToken,expectedZoneIds:[zoneId],sourceSha:sha,fetchImpl:f.fetchImpl}); + assert.equal(status,'deploy'); + assert.ok(f.calls.every(call=>call.method==='GET'&&call.token===`Bearer ${readToken}`)); + assert.ok(f.calls.some(call=>call.url.pathname===`/client/v4/zones/${zoneId}/workers/routes`)); + for(const bad of [ + cloudflareFixture({target:'absent',zones:[]}), + cloudflareFixture({target:'absent',route:[{id:'route',pattern:'*',script:WORKER_NAME}]}), + cloudflareFixture({target:'absent',domains:[{service:WORKER_NAME,hostname:'unsafe.example'}]}), + cloudflareFixture({target:'absent',namespaces:[ns()]}), + cloudflareFixture({target:'absent',zoneInfo:{page:2,per_page:50,total_count:1,total_pages:1}}), + ]) await assert.rejects(verifyBootstrapPreflight({accountId,readToken,expectedZoneIds:[zoneId],sourceSha:sha,fetchImpl:bad.fetchImpl})); + assert.equal(verifyDistinctWriteCredential(readToken,writeToken),true); + assert.throws(()=>verifyDistinctWriteCredential(readToken,readToken),/separate/); +}); + +test('existing Worker is a no-op only when disabled ingress, exact SQLite namespace, binding and serving version agree',()=>{ + const good={...snapshot(),domains:[]}; + assert.equal(verifyProviderState(good,{phase:'preflight',expectedZoneIds:[zoneId],sourceSha:sha}),'already-ready'); + assert.equal(verifyProviderState(good,{phase:'postflight',expectedZoneIds:[zoneId],sourceSha:sha}),'verified'); + assert.throws(()=>verifyProviderState(good,{phase:'preflight',expectedZoneIds:[zoneId],sourceSha:'c'.repeat(40)}),/exact reviewed source SHA/); + for(const mutate of [ + s=>{s.zoneIds=[];}, + s=>{s.subdomain.enabled=true;}, + s=>{s.subdomain.previews_enabled=true;}, + s=>{s.schedules=[{cron:'* * * * *'}];}, + s=>{s.settings.logpush=true;}, + s=>{s.settings.tail_consumers=[{}];}, + s=>{s.domains=[{hostname:'unsafe.example'}];}, + s=>{s.namespaces[0].script='other-worker';}, + s=>{s.namespaces[0].use_sqlite=false;}, + s=>{s.deployments[0].versions[0].percentage=50;}, + s=>{s.versions[0].resources.bindings[0].text='true';}, + s=>{s.versions[0].resources.bindings.push({name:'OUTSIDE',type:'service'});}, + s=>{s.versions[0].exports[DO_CLASS].storage='legacy-kv';}, + s=>{s.versions[0].limits.cpu_ms=50;}, + ]) { const bad=snapshot(); mutate(bad); assert.throws(()=>verifyProviderState(bad,{phase:'preflight',expectedZoneIds:[zoneId],sourceSha:sha})); } + assert.throws(()=>verifyProviderState(good,{phase:'postflight',expectedZoneIds:[zoneId],sourceSha:'c'.repeat(40)}),/exact reviewed source SHA/); +}); + +test('postflight readback verifies deployed identity via independent API data and never writes',async()=>{ + const f=cloudflareFixture({target:'existing',namespaces:[ns()]}); + assert.equal(await verifyBootstrapPostflight({accountId,readToken,expectedZoneIds:[zoneId],sourceSha:sha,fetchImpl:f.fetchImpl}),'verified'); + assert.ok(f.calls.every(call=>call.method==='GET'&&call.token===`Bearer ${readToken}`)); + const bad=cloudflareFixture({target:'existing',namespaces:[ns()],versions:[{...version(),annotations:{'workers/tag':'c'.repeat(40)}}]}); + await assert.rejects(verifyBootstrapPostflight({accountId,readToken,expectedZoneIds:[zoneId],sourceSha:sha,fetchImpl:bad.fetchImpl}),/exact reviewed source SHA/); +}); From 5a50a38a614a1691e617f86a2cb4ec51fc7bc2ab Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 07:22:52 +0000 Subject: [PATCH 22/33] docs(fleet): refresh bridge bootstrap verification --- pm-stack/private-laptop-bridge/VERIFICATION.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pm-stack/private-laptop-bridge/VERIFICATION.md b/pm-stack/private-laptop-bridge/VERIFICATION.md index b3ff0d920d..f8082f57d7 100644 --- a/pm-stack/private-laptop-bridge/VERIFICATION.md +++ b/pm-stack/private-laptop-bridge/VERIFICATION.md @@ -300,7 +300,7 @@ Verification on this source state: | Check | Result | | --- | --- | | `node --test staging-bootstrap.test.mjs deployment-config.test.mjs release-contract.test.mjs` | 19 passed, including missing/existing Worker, exact source-SHA and workflow-boundary fixtures | -| `npm test` from this package | 133 passed, 0 failed | +| `npm test` from this package | 134 passed, 0 failed | | `cf build --mode bridge` with Node 24.19.0 and pinned `cf@1.0.0-rc.1` | Passed; 17.84 KiB upload, 5.31 KiB gzip | | `node staging-bootstrap.mjs validate-build` | Passed against the effective Build Output | | `cf deploy --mode bridge --prebuilt --dry-run` | Passed; output showed only the disabled vars and `BRIDGE -> PrivateLaptopBridge`; dry-run exited before upload | From 20f00149a1ff8d8f90e7eb6a875b0650fd35425a Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 08:28:40 +0000 Subject: [PATCH 23/33] feat(fleet): add Access-authenticated bridge ingress --- .../private-laptop-bridge-release.yml | 47 +++- pm-stack/private-laptop-bridge/.gitignore | 1 + .../private-laptop-bridge/ACCESS-STAGING.md | 136 ++++++++++ pm-stack/private-laptop-bridge/README.md | 39 +-- pm-stack/private-laptop-bridge/STAGING.md | 95 ++++--- .../private-laptop-bridge/VERIFICATION.md | 56 +++++ .../private-laptop-bridge/access-auth.mjs | 91 +++++++ .../access-auth.test.mjs | 108 ++++++++ pm-stack/private-laptop-bridge/aster.mjs | 3 +- pm-stack/private-laptop-bridge/aster.test.mjs | 13 +- pm-stack/private-laptop-bridge/caller.mjs | 13 +- pm-stack/private-laptop-bridge/client.mjs | 15 +- .../private-laptop-bridge/client.test.mjs | 7 +- .../cloudflare.config.ts | 5 + .../private-laptop-bridge/control.test.mjs | 22 +- .../private-laptop-bridge/freshness.test.mjs | 6 +- pm-stack/private-laptop-bridge/gateway.mjs | 9 +- .../private-laptop-bridge/gateway.test.mjs | 6 +- pm-stack/private-laptop-bridge/model.test.mjs | 6 +- ...ge-staging-bootstrap.workflow.yml.disabled | 47 ++-- .../release-contract.mjs | 36 ++- .../release-contract.test.mjs | 38 +-- .../private-laptop-bridge/review.test.mjs | 16 +- .../runtime-test-entry.mjs | 9 + .../private-laptop-bridge/runtime.test.mjs | 17 +- .../staging-bootstrap.mjs | 233 +++++++++++++----- .../staging-bootstrap.test.mjs | 129 ++++++---- .../staging-preflight.json | 9 +- pm-stack/private-laptop-bridge/worker.mjs | 33 ++- 29 files changed, 982 insertions(+), 263 deletions(-) create mode 100644 pm-stack/private-laptop-bridge/ACCESS-STAGING.md create mode 100644 pm-stack/private-laptop-bridge/access-auth.mjs create mode 100644 pm-stack/private-laptop-bridge/access-auth.test.mjs create mode 100644 pm-stack/private-laptop-bridge/runtime-test-entry.mjs diff --git a/.github/workflows/private-laptop-bridge-release.yml b/.github/workflows/private-laptop-bridge-release.yml index 32b1962182..e1c5fbcb54 100644 --- a/.github/workflows/private-laptop-bridge-release.yml +++ b/.github/workflows/private-laptop-bridge-release.yml @@ -27,9 +27,46 @@ concurrency: cancel-in-progress: false jobs: + verify-release-environment: + if: github.repository == 'developing-today/code' && github.ref == 'refs/heads/main' && github.event_name == 'workflow_dispatch' + runs-on: ubuntu-24.04 + timeout-minutes: 5 + outputs: + environment: ${{ steps.gate.outputs.environment }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.sha }} + fetch-depth: 1 + persist-credentials: false + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + with: + node-version: 24.22.0 + - name: Validate fixed request and existing protected environment before assignment + id: gate + working-directory: pm-stack/private-laptop-bridge + env: + ACTION_KIND: ${{ inputs.action }} + WORKER_KIND: ${{ inputs.worker }} + UPLOAD_RUN_ID: ${{ inputs.upload_run_id }} + GH_TOKEN: ${{ github.token }} + GITHUB_API_URL: ${{ github.api_url }} + GITHUB_ACTOR_ID: ${{ github.actor_id }} + CF_BRIDGE_RELEASE_REVIEWER_IDS: ${{ vars.CF_BRIDGE_RELEASE_REVIEWER_IDS }} + run: | + set -euo pipefail + [[ "$ACTION_KIND" == upload && -z "$UPLOAD_RUN_ID" || "$ACTION_KIND" == promote && "$UPLOAD_RUN_ID" =~ ^[0-9]{1,20}$ ]] + [[ "$WORKER_KIND" == bridge ]] + node staging-bootstrap.mjs github-environment-release + release: - if: github.repository == 'developing-today/code' && github.ref == 'refs/heads/main' && inputs.worker == 'bridge' - environment: cloudflare-staging + needs: verify-release-environment + if: needs.verify-release-environment.result == 'success' && needs.verify-release-environment.outputs.environment == 'cloudflare-staging' && github.repository == 'developing-today/code' && github.ref == 'refs/heads/main' && inputs.worker == 'bridge' + environment: + name: ${{ needs.verify-release-environment.outputs.environment }} + env: + CF_BRIDGE_ACCESS_ISSUER: ${{ vars.CF_BRIDGE_ACCESS_ISSUER }} + CF_BRIDGE_ACCESS_AUDIENCE: ${{ vars.CF_BRIDGE_ACCESS_AUDIENCE }} runs-on: ubuntu-24.04 timeout-minutes: 25 steps: @@ -159,6 +196,8 @@ jobs: working-directory: pm-stack/private-laptop-bridge env: TARGET_MODE: ${{ steps.target.outputs.mode }} + CF_BRIDGE_ACCESS_ISSUER: ${{ vars.CF_BRIDGE_ACCESS_ISSUER }} + CF_BRIDGE_ACCESS_AUDIENCE: ${{ vars.CF_BRIDGE_ACCESS_AUDIENCE }} run: | set -euo pipefail if [[ "$TARGET_MODE" == bridge ]]; then npx --no-install cf build --mode bridge; else npx --no-install cf build; fi @@ -172,6 +211,8 @@ jobs: env: TARGET_WORKER: ${{ steps.target.outputs.worker }} TARGET_MODE: ${{ steps.target.outputs.mode }} + CF_BRIDGE_ACCESS_ISSUER: ${{ vars.CF_BRIDGE_ACCESS_ISSUER }} + CF_BRIDGE_ACCESS_AUDIENCE: ${{ vars.CF_BRIDGE_ACCESS_AUDIENCE }} DRY_RUN_OUTPUT: ${{ runner.temp }}/cf-version-dry-run.txt run: | set -euo pipefail @@ -187,6 +228,8 @@ jobs: CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CF_BRIDGE_ACCOUNT_ID }} CLOUDFLARE_API_TOKEN: ${{ secrets.CF_BRIDGE_API_TOKEN }} CF_ACCOUNT_ID: ${{ secrets.CF_BRIDGE_ACCOUNT_ID }} + CF_BRIDGE_ACCESS_ISSUER: ${{ vars.CF_BRIDGE_ACCESS_ISSUER }} + CF_BRIDGE_ACCESS_AUDIENCE: ${{ vars.CF_BRIDGE_ACCESS_AUDIENCE }} OWNER_PROOF_JSON: ${{ secrets.CF_BRIDGE_OWNER_PROOF_JSON }} TARGET_WORKER: ${{ steps.target.outputs.worker }} TARGET_ENV: ${{ steps.target.outputs.environment }} diff --git a/pm-stack/private-laptop-bridge/.gitignore b/pm-stack/private-laptop-bridge/.gitignore index 0dcc8a4190..97ef33beaa 100644 --- a/pm-stack/private-laptop-bridge/.gitignore +++ b/pm-stack/private-laptop-bridge/.gitignore @@ -1,2 +1,3 @@ node_modules/ .wrangler/ +.cloudflare/ diff --git a/pm-stack/private-laptop-bridge/ACCESS-STAGING.md b/pm-stack/private-laptop-bridge/ACCESS-STAGING.md new file mode 100644 index 0000000000..d5ccb2cc12 --- /dev/null +++ b/pm-stack/private-laptop-bridge/ACCESS-STAGING.md @@ -0,0 +1,136 @@ +# No-WARP Cloudflare Access path + +This is the selected source design for the fixed staging bridge. It replaces +the earlier Gateway/WARP and Tunnel sketches in `STAGING.md`; those sketches +are historical and must not be followed for this deployment. The two clients +make outbound HTTPS polling requests to one Cloudflare Access protected Worker +custom hostname. There is no listener on the AMD laptop and no generic proxy. + +```text +Aster caller runner -- outbound HTTPS + Access service token + Ed25519 --> + fixed Access hostname --> Worker default fetch --> + SQLite Durable Object +AMD non-root client -- outbound HTTPS + Access service token + Ed25519 --> +``` + +Proposed fixed host: `laptop-bridge-staging.security.cab`. This differs from +the rejected `private-bridge-staging.security.cab`. Root must independently +verify exact hostname ownership, DNS/wildcard behavior, and the Access app +target before any provider configuration. No wildcard or unrelated DNS record +is to be changed. This draft does not prove that the hostname is available or +that an Access application already exists. + +## Two independent authentication checks + +Each request must pass both layers: + +1. Cloudflare Access accepts one of two separate Service Auth credentials: one + held by the approved Aster runner, one by the AMD client. No browser or + identity-provider policy is included. Keep strict service-token + authentication enabled. Do not share or log either Client Secret. +2. The Worker verifies `Cf-Access-Jwt-Assertion` itself. It pins the exact + `https://.cloudflareaccess.com` issuer, exact app audience, `RS256`, + `kid`, fetched JWKS, `type=app`, `sub=""`, `common_name`, `iat`, `exp`, and + optional `nbf`. The verified `common_name` must match both the incoming + `CF-Access-Client-Id` and exactly one unrevoked principal in the Worker + registry. A token for one service cannot assume the other principal's role. + JWKS are fetched only from the exact configured issuer, redirects are + rejected, cache lifetime is five minutes, and an unknown key or failed + refresh after expiry fails closed. The accepted JWT lifetime is at most 15 + minutes. +3. The existing bridge check remains independent: Ed25519 signs the request + method, exact path, body, audience, principal, timestamp, and nonce. The + Durable Object checks role, device, operation scope, quota, replay, lease, + source freshness and revocation. Access authentication does not grant a + bridge operation. + +Before forwarding to the Durable Object, the Worker removes all `cf-access-*` +headers, `Cookie`, and `Authorization`. It never uses caller-supplied identity +headers. Denial logs contain only fixed status and reason codes. + +The default Worker fetch rejects a missing or mismatched exact HTTPS hostname, +port, route or query; rejects missing, malformed, forged, wrong-issuer, +wrong-audience, expired, cross-client, stale-key, or wrong-algorithm tokens; +and fails closed when the auth configuration or JWKS are unavailable. Redirects +are not followed by either client. The deployment must keep `workers_dev` and +preview URLs disabled and bind only the approved custom hostname. Do not create +additional custom domains, routes, Worker aliases, public management endpoints, +or a direct Worker origin. Cloudflare Access must be configured for the exact +hostname before it is attached to the Worker. The Worker-side JWT validation +is also required because the edge Access rule alone does not prove that no +alternate path can reach the code. + +The custom hostname will resolve through Cloudflare; “private” here means +service-authenticated and operation-limited, not a DNS-hidden service. No +WARP, Cloudflare Tunnel, Gateway rule, inbound laptop port, or host network +change is part of this design. A Tunnel would expose a local origin and add a +different route, so it is not used for this Worker control plane. + +## Resource and identity checklist + +- Worker: `private-laptop-bridge-staging`; fixed hostname above, Access app + restricted to service-token authentication, `workers_dev=false`, previews + false, no schedules or other routes/domains. +- Access issuer and audience: provisioned for that exact app, stored as + non-secret Worker configuration from protected environment variables + `CF_BRIDGE_ACCESS_ISSUER` and `CF_BRIDGE_ACCESS_AUDIENCE`. They are required + by the build/readback contract and are not yet verified or set here. +- Access identities: two separately named Service Auth credentials with + independent expiration and revocation; Aster caller and AMD device. Keep + their IDs in the role registry and each Client Secret only in that client's + owner-only config. No secret is stored in Cloudflare Worker variables. +- Bridge principals: distinct Ed25519 public keys and unique Access Client IDs; + caller scopes only the four read operations; device scopes only approved + operations for device `amd`. Revoke by disabling the Access token and + revoking its Worker principal. Never extend either identity beyond the + approved one-hour pilot without a new review. +- Runtime: outbound HTTPS only from both processes. Aster's Node runtime and + AMD's non-root client use the fixed origin and no redirects. Their local + Access service credentials and Ed25519 private halves remain on their own + hosts. Never share a signing key, Access Secret, token-bearing logs, or + `.env` artifact. + +## Verification gates + +Before attaching the hostname or enabling the Worker, an owner must review the +exact account and Access app, confirm the service-token policy includes only +the two approved credentials, verify no conflicting wildcard/custom-domain +mapping, and read back the Worker name and immutable ID. The release environment +must pin that ID; a same-name Worker with another ID fails. Do not infer +protection from DNS, a browser login, or a successful synthetic request. + +The private owner proof consumed by the release gate must record the Access app +ID, exact hostname/issuer/audience, service-token-only mode, disabled browser +login, zero bypass/non-service allow rules, and exactly two distinct approved +service-token client IDs. It contains IDs, never Client Secrets. The owner must +independently derive that normalized record from the Access app and policy +readback; a manually asserted proof without that readback is not valid. + +Offline tests cover valid RS256/JWKS verification, forged signatures, wrong +issuer/audience/client, cross-role ID, wrong host, expiry, stale/unknown keys, +failed JWKS refresh, Access header stripping, principal revocation, replay, +scopes, and denied operations. Add a credential-free hosted smoke against the +exact Access app only after its host and audience are reviewed. Then prove a +separate real Node process on each approved runner can call health and obtain a +fresh queue snapshot. A user/session-proxy queue timeout or synthetic empty +snapshot is not a valid idle result. + +## Current stop conditions + +The source has no verified Access issuer, audience, service-token Client IDs, +Access policies, exact hostname ownership, or deployed Worker. The protected +Access variables have no verified values and the bridge is disabled. No +credential, DNS, Worker, Access app, or client state was changed. The first +Worker must be created locally by an account owner as a metadata-only disabled +object; Actions must use only its pre-pinned Individual Workers Editor scope. +The pinned `cf deploy --provision` behavior for an empty SQLite Durable Object +binding, exact Worker Editor permissions, and preservation of disabled ingress +has not been proven against Cloudflare. Do not call it compatible until that +provider contract is independently verified. See the dormant bootstrap source +and the staging approval packet for the separate release and rollback gates. + +Cloudflare documents service token JWT `common_name` as the Client ID and +requires signature, issuer, audience, and time validation at an origin: +[Application token](https://developers.cloudflare.com/cloudflare-one/access-controls/applications/http-apps/authorization-cookie/application-token/), +[Validate JWTs](https://developers.cloudflare.com/cloudflare-one/access-controls/applications/http-apps/authorization-cookie/validating-json/), +[Service tokens](https://developers.cloudflare.com/cloudflare-one/access-controls/service-credentials/service-tokens/). diff --git a/pm-stack/private-laptop-bridge/README.md b/pm-stack/private-laptop-bridge/README.md index 6b2ee87e91..6201e74f6b 100644 --- a/pm-stack/private-laptop-bridge/README.md +++ b/pm-stack/private-laptop-bridge/README.md @@ -1,8 +1,11 @@ # Private laptop bridge — offline candidate **Not deployed; not a replacement-ready cutover.** Desktop Commander remains the -fallback. [The staging approval packet](STAGING.md) specifies private Gateway -ingress, resources, identities, costs, installation and rollback. This package +fallback. The current proposed transport is documented in +[ACCESS-STAGING.md](ACCESS-STAGING.md): no-WARP outbound HTTPS through a fixed +Cloudflare Access service-authenticated hostname, with independent Worker JWT +and Ed25519 checks. `STAGING.md` retains a clearly marked historical Gateway +sketch. This package implements bounded Fleet reads, not a shell. Aster still needs an approved caller integration, a privately reachable control plane, and verified enrollment on Drew's AMD NixOS laptop before relying on it. @@ -16,8 +19,8 @@ existing Turso-backed queue. No endpoint claims, dispatches, changes tasks, restarts services, reads arbitrary files, fetches arbitrary URLs, executes a command, or accepts scripts. Builds/tests are deliberately outside this version. -The Worker is default-disabled, has no routes, workers.dev or preview URLs, and -contains no private keys. Device and caller identities are independently pinned +The Worker is default-disabled, has only the proposed fixed custom hostname, +workers.dev and preview URLs disabled, and contains no private keys. Device and caller identities are independently pinned public keys with separate roles, device binding, operation scopes, expiration and revocation. Possession of a device key does not grant caller permissions. A request signature covers its audience, endpoint, method, timestamp, nonce and @@ -213,16 +216,19 @@ and effective payload validator, not a deployment. `cloudflare.config.ts` in `bridge` mode is the sole real staging lifecycle definition. No Wrangler JSONC deployment or migration fallback is kept. The smoke Worker is owned by the separate smoke init/upload workflows on `main` and is not selectable in the bridge release -workflow. The deployed candidate's default HTTP handler always denies; only the -Gateway RPC entrypoint can reach the signed bridge, after trusted-context -checks. The real Gateway DNS, device enrollment and TLS-trust path still requires -the approval packet's smoke. +workflow. Default HTTP fetch requires an exact-host Cloudflare Access service +JWT, maps its signed client ID to one principal, then forwards the independently +signed request to the bridge. The earlier Gateway path is historical only; see +[ACCESS-STAGING.md](ACCESS-STAGING.md) for the current no-WARP design. The one-time disabled first-deployment workflow is a reviewed template with a `.disabled` suffix outside `.github/workflows`; GitHub does not register it. It remains dormant until the exact protected environment, reviewer policy, -source pin, and narrowly scoped read/write credentials are independently -verified. See [STAGING.md](STAGING.md) for its fixed target and gates. +source pin, immutable owner-created Worker ID, exact Access app and narrowly +scoped read/write credentials are independently verified. The pinned +`cf deploy --provision`/Individual Workers Editor contract for the SQLite +namespace is still unverified. See [STAGING.md](STAGING.md) for its fixed target +and gates. No automatic PR CI or active schedule is added. The merged smoke init/upload workflows are manual; this branch retains a separate manual bridge release path @@ -233,10 +239,10 @@ sandbox validation remain separate from the focused snapshot tests. ## Caller integration checkpoint -`caller.mjs` exports `createCaller({origin, audience, principal, device, privateKey})`. -An approved caller supplies its own Ed25519 CryptoKey and fixed HTTPS origin; the -SDK does not load files, discover credentials, enroll identities, or install an -Aster connector. Its four methods return accepted handles. `read(handle)` checks +`caller.mjs` exports `createCaller({origin, audience, principal, device, privateKey, accessClientId, accessClientSecret})`. +An approved caller supplies its own Ed25519 CryptoKey, fixed HTTPS origin, and +owner-provisioned Cloudflare Access service token. The SDK does not load files, +discover credentials, enroll identities, or install an Aster connector. Its four methods return accepted handles. `read(handle)` checks once; `wait(handle)` polls for at most the request lifetime. A failed read retains the handle for explicit resumption. An uncertain submit is never retried automatically because its acknowledgement may have been lost after acceptance. @@ -248,8 +254,9 @@ const observation = await fleet.wait(handle); The device CLI accepts only `--config ABSOLUTE_PATH` or `--help`. The approved configuration must be an owner-only regular file containing exactly `origin`, -`audience`, `principal`, and an externally provisioned Ed25519 private JWK -(`kty`, `crv`, `x`, `d`). No example contains key material. The CLI refuses root, +`audience`, `principal`, `accessClientId`, `accessClientSecret`, and an externally +provisioned Ed25519 private JWK (`kty`, `crv`, `x`, `d`). No example contains key +material. The CLI refuses root, follows no redirects, stops on authorization denial, and reconnects with bounded backoff after transport failure. The supplied service file is a review template with placeholder executable paths and no installation target. diff --git a/pm-stack/private-laptop-bridge/STAGING.md b/pm-stack/private-laptop-bridge/STAGING.md index 9c8f0cd0bd..41c63301f0 100644 --- a/pm-stack/private-laptop-bridge/STAGING.md +++ b/pm-stack/private-laptop-bridge/STAGING.md @@ -20,8 +20,10 @@ bridge target. `cloudflare.config.ts` is the only deployment lifecycle source; no Wrangler JSONC deployment or migration fallback is kept. The bridge config currently has `ENABLED=false`, empty registry and Gateway -placeholders, no routes/domains/triggers, workers.dev and preview URLs disabled, -10 ms CPU limit, and observability/logging/traces off. It binds the staging +placeholders, exactly one proposed Access hostname (`laptop-bridge-staging.security.cab`), +no routes or triggers, workers.dev and preview URLs disabled, 10 ms CPU limit, +and observability/logging/traces off. Access issuer/audience remain blank until +the exact app is independently verified. It binds the staging Worker to its own declarative SQLite `PrivateLaptopBridge` Durable Object export. The tracked `staging-preflight.json` remains `verified:false`, `exists:false`, with empty account, namespace and evidence IDs. Local config/build tests prove only @@ -38,11 +40,12 @@ matching. Schema 1 receipts are rejected. ### First disabled deployment workflow draft Routine releases remain versions-only and must refuse an absent Worker or -Durable Object namespace. A one-time first deployment, if later authorized, -must use the same `cloudflare.config.ts` `bridge` mode and pinned `cf` Build -Output. Cloudflare's `cf` guidance uses `cf deploy` to create the initial -Worker and apply the declarative DO export lifecycle; this is the initial -deployment step, not a second configuration or a legacy migration fallback. +Durable Object namespace. For first activation, the owner must first create +only the fixed metadata-only Worker locally, read its immutable ID, and pin that +ID in the protected `cloudflare-staging` environment. Actions must reject an +absent Worker and any same-name/different-ID takeover; it must not receive +account-wide create permission. Only then could the same `cloudflare.config.ts` +`bridge` mode and pinned `cf` Build Output initialize the SQLite export. [cf project deploy](https://developers.cloudflare.com/cf/projects/) · [cf and Durable Object lifecycle](https://developers.cloudflare.com/cf/wrangler/reference/#convert-durable-object-migrations) @@ -56,35 +59,40 @@ schedule, route, public hostname, Gateway policy, or runtime secret. If enabled after all listed prerequisites are independently established, the workflow accepts only a manual dispatch from `main` in `developing-today/code`. -Its initial no-secret job reads the exact `cloudflare-staging-bootstrap` -environment and branch policy and checks the reviewer set and source SHA. Only -that successful check emits the fixed environment name for the later deploy job; +Its initial no-secret job reads the exact existing `cloudflare-staging` +environment and branch policy and checks the typed reviewer set. Only that +successful check emits the fixed environment name for the later deploy job; this prevents GitHub from auto-creating a missing, unprotected environment when a job is assigned to it. The protected environment must require an independent reviewer, disallow self-review, allow only `main`, and pin the exact reviewed -full source SHA. The template fails closed if any part is missing or differs. +full source SHA and immutable Worker ID. The template fails closed if any part +is missing or differs. The deploy job runs the local build and pinned `cf deploy --dry-run`, verifies the effective disabled Build Output, then uses separate read-only and write-only credentials. Before its only possible provider write, read-only checks inventory the full account zone set and every zone's Worker routes, -account Worker domains, the fixed Worker and SQLite namespace, schedules, +account Worker domains, the pinned Worker ID and SQLite namespace, schedules, subdomain/preview flags, settings, versions and deployments. It refuses an -unknown or partial inventory, any route/domain, an orphan namespace, an -unexpected existing Worker, shared read/write tokens, or any effective config -that differs from the disabled artifact. Only when the Worker is absent and the -namespace is absent does the gated step run the pinned declarative -`cf deploy --mode bridge --prebuilt --provision` lifecycle. A second -read-only pass checks the exact serving version, single 100-percent deployment, -source-SHA tag, disabled settings, no ingress, and the same SQLite namespace -ID in the export and account inventory. It never changes Gateway or routes. +unknown or partial inventory, any unexpected route/domain, an orphan namespace, +an absent or mismatched Worker ID, shared read/write tokens, or any effective +config that differs from the disabled artifact. Only an exact, precreated +metadata-only Worker with zero deployments and no domain/namespace can proceed. +A second read-only pass checks the exact serving version, single 100-percent +deployment, source-SHA tag, disabled settings, the sole approved host with +preview routing off, and the same SQLite namespace ID in the export and account +inventory. It never changes Gateway or routes. The checked-in template has not been registered, dispatched, or run against -Cloudflare. The current protected environment, reviewer IDs, exact account and -zone inventory, and the separate read/write credentials are not available in -this checkout. Their secret values were not accessed. Cloudflare's narrowest -write scope for first creation of this absent Worker still needs an owner-side -permission review; do not silently broaden it or use a Workers-product token. +Cloudflare. The current protected environment, reviewer IDs, exact account, +zone inventory and Worker ID, and separate read/write credentials are not +available in this checkout. Their secret values were not accessed. The pinned +`cf deploy --provision` behavior for adding the SQLite namespace to a precreated +Worker, and whether an Individual Workers Editor can perform that exact +operation without changing other state, have not been verified against +Cloudflare. Do not claim compatibility or enable the workflow until that exact +provider contract is confirmed. It has no fallback that creates a Worker or +silently changes its identity. The read credential needs complete account zone/route inventory, Worker metadata/settings/versions/deployments/domains, and Durable Object namespace read. If those exact read scopes or an individual Worker write scope cannot be @@ -100,9 +108,10 @@ npm ci --ignore-scripts --no-audit --no-fund # Never run it from a developer checkout. ``` -The final command writes a deployment and provisions the `PrivateLaptopBridge` -SQLite export. It must run only with `ENABLED=false`, empty Gateway IDs and -registry, no runtime secrets, no routes/domains/triggers, `workersDev:false`, +The final command writes a deployment, may attach the exact approved custom +hostname, and provisions the `PrivateLaptopBridge` SQLite export. It must run +only with `ENABLED=false`, empty Gateway IDs and registry, no runtime secrets, +no routes or extra domains/triggers, `workersDev:false`, `previewUrls:false`, logs/traces off, and the 10 ms CPU limit from the reviewed build. Do not pass `--force`, `--secrets-file`, or `--dispatch-namespace`. A successful local `--dry-run` proves config shape only; it is not permission to @@ -122,9 +131,10 @@ changing it. Immediately after the write, independently repeat the full zone/route and Worker inventory and verify the same Worker identity and account, no -routes/domains/schedules, no Gateway binding, workers.dev and preview URLs -disabled, no runtime secrets, and the exact disabled variables and resource -limits. This is not proof about account-level Gateway rules or caller identity. +routes/schedules, only the exact approved custom domain with previews disabled, +no Gateway binding, workers.dev and preview URLs disabled, no runtime secrets, +and the exact disabled variables and resource limits. This is not proof about +account-level Gateway rules or caller identity. Verify the Worker's declarative export is `PrivateLaptopBridge` with `state=created` and `storage=sqlite`; verify the `BRIDGE` binding's namespace ID matches exactly one @@ -140,14 +150,12 @@ and [Gateway rules](https://developers.cloudflare.com/api/resources/zero_trust/s Any mismatch means stop and keep the Worker disabled and unrouted; do not automatically delete it, retry deployment, or create a replacement namespace. -`cloudflare-staging` remains absent, and the template uses the separate exact -`cloudflare-staging-bootstrap` environment for its one-time first deployment. -That bootstrap environment is also not verified as present or protected. The -tracked proof fixture still records branch protection/reviews and environment -reviewers as false. The read-only branch-protection API request returned HTTP -403 for this GitHub integration, so this session could not independently inspect -the live branch rule. Do not register the template until an authorized -repository administrator creates and independently verifies the bootstrap +`cloudflare-staging` remains absent and is the only proposed bridge workflow +environment. The tracked proof fixture still records branch protection/reviews +and environment reviewers as false. The read-only branch-protection API request +returned HTTP 403 for this GitHub integration, so this session could not +independently inspect the live branch rule. Do not register the template until +an authorized repository administrator creates and independently verifies that environment and its protection. Routine `cloudflare-staging` versions upload and promotion stay separately gated. GitHub creates an unconfigured environment when a workflow references a missing one; the no-secret pre-job gate must stay @@ -176,7 +184,14 @@ Gateway state. Keep uploads and promotion blocked until this independent readbac is available, and keep the fallback until Drew separately approves bridge activation and end-to-end authorized Fleet operations pass on his laptop. -## Selected ingress and the remaining feasibility gate +## Superseded Gateway ingress sketch (historical only) + +**Do not follow this section or its Gateway/WARP steps.** Drew selected the +no-WARP Cloudflare Access service-authentication path in +[ACCESS-STAGING.md](ACCESS-STAGING.md). That document is the current ingress +design; this section remains only to preserve the earlier review history. + +## Historical Gateway sketch Use **Cloudflare Gateway Forward**, not a public Worker URL. The official guide supports a Worker with no public route, `workers_dev:false`, diff --git a/pm-stack/private-laptop-bridge/VERIFICATION.md b/pm-stack/private-laptop-bridge/VERIFICATION.md index f8082f57d7..7253c59a7e 100644 --- a/pm-stack/private-laptop-bridge/VERIFICATION.md +++ b/pm-stack/private-laptop-bridge/VERIFICATION.md @@ -322,3 +322,59 @@ credential-free synthetic smoke results are insufficient. See The previously proposed `private-bridge-staging.security.cab` hostname is rejected because it matches an existing public wildcard; no replacement host or AMD/Aster Gateway path is verified. + +## Access path and immutable precreated Worker contract — 2026-11-23 + +The current source design is the fixed no-WARP Cloudflare Access path in +[`ACCESS-STAGING.md`](ACCESS-STAGING.md), not the earlier Gateway plan above. +The proposed hostname is `laptop-bridge-staging.security.cab`; its DNS/zone +ownership and Access application remain unverified. The Worker now rejects +requests unless the origin verifies Cloudflare's RS256 Access JWT for the +configured exact issuer, audience, hostname and client ID, then independently +checks the existing Ed25519 principal signature. It strips Access credentials +before forwarding. Both protected environment variables are required to +validate a deployable bridge Build Output. + +The bootstrap preflight now requires an owner-created metadata-only +`private-laptop-bridge-staging` Worker and the protected immutable +`CF_BRIDGE_WORKER_ID`. A missing Worker, same-name/different-ID Worker, any +prior version/deployment, unexpected binding/namespace/route/domain, or unknown +zone/Gateway inventory fails closed. The initial empty Worker must have no +custom domain or namespace; deployed readback requires only the exact proposed +host with preview routing disabled and the same immutable Worker ID. CI has no +account-wide create credential. + +Current local checks on this working tree: + +```text +npm test +138 passed, 0 failed + +node --test staging-bootstrap.test.mjs release-contract.test.mjs access-auth.test.mjs +21 passed, 0 failed + +CF_BRIDGE_ACCESS_ISSUER=https://staging.cloudflareaccess.com \ +CF_BRIDGE_ACCESS_AUDIENCE=synthetic-audience-value-00000001 \ +cf build --mode bridge +node staging-bootstrap.mjs validate-build +cf workers versions create --worker private-laptop-bridge-staging \ + --tag --message 'offline synthetic validation' \ + --prebuilt --dry-run --mode bridge +release-artifact.mjs dry-run +``` + +The pinned `cf@1.0.0-rc.1` dry-run produced the disabled DO binding, fixed host, +synthetic issuer/audience and `ENABLED=false`, then exited before upload. +These are synthetic/offline checks. No Cloudflare state, DNS, Access app, +GitHub environment, credential, laptop setting or workflow was changed or +dispatched. The bootstrap file remains outside `.github/workflows`. + +Two exact provider behaviors remain unverified: whether the pinned +`cf deploy --provision` can initialize the SQLite Durable Object on this +precreated Worker, and whether the proposed Individual Workers Editor grant can +perform that operation without unrelated permissions. Therefore this source +does not claim the first deployment is executable in production. The actual +Access application, two service identities, public-key registry, exact +hostname, protected environment/reviewer set, and laptop/Aster network/runtime +path also remain owner-side prerequisites. Keep all workflows dormant until +these are independently verified. diff --git a/pm-stack/private-laptop-bridge/access-auth.mjs b/pm-stack/private-laptop-bridge/access-auth.mjs new file mode 100644 index 0000000000..22a77fcdd2 --- /dev/null +++ b/pm-stack/private-laptop-bridge/access-auth.mjs @@ -0,0 +1,91 @@ +// Verify Cloudflare Access service-token JWTs at the Worker origin. +// The caller still needs its independent Ed25519 bridge signature. +const MAX_JWT_LENGTH = 16_384; +const MAX_KEYS_BYTES = 32_768; +const SKEW_SECONDS = 30; +const MAX_TOKEN_AGE_SECONDS = 15 * 60; +const KEY_CACHE_MS = 5 * 60_000; +const keyCache = new Map(); +export const BRIDGE_HOST = 'laptop-bridge-staging.security.cab'; +export const BRIDGE_ORIGIN = `https://${BRIDGE_HOST}`; + +const fail = () => { throw new Error('access-denied'); }; +const decodeBytes = value => { + if (typeof value !== 'string' || !/^[A-Za-z0-9_-]+$/.test(value) || value.length % 4 === 1) fail(); + const bytes = Uint8Array.from(atob(value.replaceAll('-', '+').replaceAll('_', '/') + '='.repeat((4 - value.length % 4) % 4)), c => c.charCodeAt(0)); + const canonical = btoa(String.fromCharCode(...bytes)).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, ''); + if (canonical !== value) fail(); + return bytes; +}; +const decodePart = value => { + return JSON.parse(new TextDecoder('utf-8', {fatal: true}).decode(decodeBytes(value))); +}; + +function accessConfig(env) { + const {ACCESS_ISSUER: issuer, ACCESS_AUDIENCE: audience, BRIDGE_HOST: host} = env; + let parsed; + try { parsed = new URL(issuer); } catch { fail(); } + if (parsed.protocol !== 'https:' || parsed.origin !== issuer || parsed.pathname !== '/' || parsed.search || parsed.hash || + !/^[a-z0-9-]+\.cloudflareaccess\.com$/.test(parsed.hostname) || + typeof audience !== 'string' || !/^[A-Za-z0-9_-]{20,128}$/.test(audience) || + host !== BRIDGE_HOST) fail(); + return {issuer, audience, host, certsUrl: `${issuer}/cdn-cgi/access/certs`}; +} + +async function accessKeys({issuer, certsUrl}, fetchImpl, now) { + const cached = keyCache.get(issuer); + if (cached && cached.expiresAt > now) return cached.keys; + let response, text, body; + try { + response = await fetchImpl(certsUrl, {method: 'GET', redirect: 'error', signal: AbortSignal.timeout(3000)}); + if (!response.ok || response.redirected) fail(); + text = await response.text(); + if (text.length > MAX_KEYS_BYTES) fail(); + body = JSON.parse(text); + } catch { fail(); } + if (!body || !Array.isArray(body.keys) || body.keys.length < 1 || body.keys.length > 4) fail(); + const keys = new Map(); + for (const jwk of body.keys) { + if (!jwk || jwk.kty !== 'RSA' || jwk.alg !== 'RS256' || jwk.use !== 'sig' || + typeof jwk.kid !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(jwk.kid) || keys.has(jwk.kid) || + typeof jwk.n !== 'string' || typeof jwk.e !== 'string') fail(); + try { keys.set(jwk.kid, await crypto.subtle.importKey('jwk', jwk, {name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256'}, false, ['verify'])); } + catch { fail(); } + } + keyCache.set(issuer, {keys, expiresAt: now + KEY_CACHE_MS}); + return keys; +} + +/** Return the verified service-token Client ID. Never trusts caller-supplied + * identity fields or Access headers without the signed JWT and exact config. */ +export async function verifyAccessServiceToken(request, env, {fetchImpl = fetch, nowMs = Date.now()} = {}) { + const cfg = accessConfig(env); + const url = new URL(request.url); + if (request.method !== 'POST' || url.protocol !== 'https:' || url.hostname !== cfg.host || url.port || url.username || url.password || url.search || url.hash) fail(); + const token = request.headers.get('cf-access-jwt-assertion'); + const clientId = request.headers.get('cf-access-client-id'); + if (!token || token.length > MAX_JWT_LENGTH || !clientId || !/^[A-Za-z0-9._-]{8,128}$/.test(clientId)) fail(); + const parts = token.split('.'); + if (parts.length !== 3) fail(); + const [header, claims] = [decodePart(parts[0]), decodePart(parts[1])]; + if (!header || header.alg !== 'RS256' || header.typ !== 'JWT' || typeof header.kid !== 'string' || + !claims || claims.type !== 'app' || claims.iss !== cfg.issuer || claims.sub !== '' || + !Array.isArray(claims.aud) || claims.aud.length < 1 || !claims.aud.includes(cfg.audience) || + claims.common_name !== clientId || !Number.isSafeInteger(claims.exp) || !Number.isSafeInteger(claims.iat) || + claims.exp <= Math.floor(nowMs / 1000) - SKEW_SECONDS || claims.iat > Math.floor(nowMs / 1000) + SKEW_SECONDS || + claims.exp <= claims.iat || claims.exp - claims.iat > MAX_TOKEN_AGE_SECONDS || + (claims.nbf !== undefined && (!Number.isSafeInteger(claims.nbf) || claims.nbf > Math.floor(nowMs / 1000) + SKEW_SECONDS))) fail(); + const keys = await accessKeys(cfg, fetchImpl, nowMs); + const key = keys.get(header.kid); + if (!key) fail(); + let valid = false; + try { + valid = await crypto.subtle.verify('RSASSA-PKCS1-v1_5', key, + decodeBytes(parts[2]), + new TextEncoder().encode(`${parts[0]}.${parts[1]}`)); + } catch { fail(); } + if (!valid) fail(); + return clientId; +} + +export function clearAccessKeyCacheForTests() { keyCache.clear(); } diff --git a/pm-stack/private-laptop-bridge/access-auth.test.mjs b/pm-stack/private-laptop-bridge/access-auth.test.mjs new file mode 100644 index 0000000000..cbd1c5ca57 --- /dev/null +++ b/pm-stack/private-laptop-bridge/access-auth.test.mjs @@ -0,0 +1,108 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {clearAccessKeyCacheForTests, verifyAccessServiceToken, BRIDGE_HOST} from './access-auth.mjs'; +import worker from './worker.mjs'; +import {b64url, operations} from './protocol.mjs'; + +const now = 1_800_000_000_000; +const issuer = 'https://fleet-team.cloudflareaccess.com'; +const audience = 'bridge-access-audience-1234567890'; +const clientId = 'amd-client-123456'; +const env = {ACCESS_ISSUER:issuer,ACCESS_AUDIENCE:audience,BRIDGE_HOST}; +const encode = value => Buffer.from(JSON.stringify(value)).toString('base64url'); +async function fixture() { + const pair = await crypto.subtle.generateKey({name:'RSASSA-PKCS1-v1_5',modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:'SHA-256'},true,['sign','verify']); + const jwk = await crypto.subtle.exportKey('jwk',pair.publicKey); + Object.assign(jwk,{kid:'key-current',alg:'RS256',use:'sig'}); + const fetchImpl = async url => { + assert.equal(url,`${issuer}/cdn-cgi/access/certs`); + return Response.json({keys:[jwk]}); + }; + const token = async (changes={}, signingPair=pair, baseNow=now) => { + const head = encode({alg:'RS256',typ:'JWT',kid:'key-current'}); + const baseSeconds=Math.floor(baseNow/1000); + const claims = encode({type:'app',aud:[audience],exp:baseSeconds+300,iat:baseSeconds-1,iss:issuer,common_name:clientId,sub:'',...changes}); + const input = `${head}.${claims}`; + const signature = Buffer.from(await crypto.subtle.sign('RSASSA-PKCS1-v1_5',signingPair.privateKey,new TextEncoder().encode(input))).toString('base64url'); + return `${input}.${signature}`; + }; + const request = async (claims={}, {host=BRIDGE_HOST, fetch=fetchImpl, id=clientId, tokenOverride, signingPair, nowMs=now}={}) => { + const jwt = tokenOverride ?? await token(claims,signingPair,nowMs); + const req = new Request(`https://${host}/v1/poll`,{method:'POST',headers:{'cf-access-client-id':id,'cf-access-client-secret':'synthetic-secret-not-live','cf-access-jwt-assertion':jwt}}); + return verifyAccessServiceToken(req,env,{fetchImpl:fetch,nowMs}); + }; + return {pair,fetchImpl,token,request}; +} + +test('Access service token validates signature, issuer, audience, short lifetime, exact hostname and client ID',async()=>{ + clearAccessKeyCacheForTests(); + const f=await fixture(); + assert.equal(await f.request(),clientId); + for(const claims of [ + {iss:'https://attacker.cloudflareaccess.com'}, + {aud:['another-audience']}, + {exp:now/1000-1}, + {iat:now/1000+31}, + {iat:now/1000-901}, + {common_name:'other-client'}, + {sub:'nonempty'}, + {type:'org'}, + ]) await assert.rejects(f.request(claims),/access-denied/); + await assert.rejects(f.request({}, {host:'other.security.cab'}),/access-denied/); + await assert.rejects(f.request({}, {id:'other-client'}),/access-denied/); +}); + +test('forged signatures, unsupported algorithms, unknown keys and unavailable/stale JWKS deny',async()=>{ + clearAccessKeyCacheForTests(); + const f=await fixture(); + const good=await f.token(); + const [head,payload,sig]=good.split('.'); + const forged=`${head}.${payload}.${Buffer.alloc(256,7).toString('base64url')}`; + await assert.rejects(f.request({}, {tokenOverride:forged}),/access-denied/); + const badAlg=`${encode({alg:'HS256',typ:'JWT',kid:'key-current'})}.${payload}.${sig}`; + await assert.rejects(f.request({}, {tokenOverride:badAlg}),/access-denied/); + const unknown=`${encode({alg:'RS256',typ:'JWT',kid:'revoked-key'})}.${payload}.${sig}`; + await assert.rejects(f.request({}, {tokenOverride:unknown}),/access-denied/); + clearAccessKeyCacheForTests(); + await assert.rejects(f.request({}, {fetch:async()=>new Response('redirect',{status:302,headers:{location:'https://attacker.invalid'}})}),/access-denied/); + clearAccessKeyCacheForTests(); + await f.request(); // populate bounded key cache + clearAccessKeyCacheForTests(); + await assert.rejects(f.request({}, {fetch:async()=>new Response('unavailable',{status:503})}),/access-denied/); +}); + +test('deployed fetch binds Access client identity to one principal and strips all edge credentials before DO',async()=>{ + clearAccessKeyCacheForTests(); + const f=await fixture(); + const ed=await crypto.subtle.generateKey('Ed25519',true,['sign','verify']); + const edCaller=await crypto.subtle.generateKey('Ed25519',true,['sign','verify']); + const principal={id:'amd-device',role:'device',device:'amd',publicKey:b64url(await crypto.subtle.exportKey('raw',ed.publicKey)), + accessClientId:clientId,scopes:[...operations],issuedAt:Date.now()-1000,expiresAt:Date.now()+600000,revoked:false}; + const caller={...principal,id:'aster-caller',role:'caller',publicKey:b64url(await crypto.subtle.exportKey('raw',edCaller.publicKey)),accessClientId:'aster-client-123456'}; + let received; + const workerEnv={...env,ENABLED:'true',BRIDGE_REGISTRY:JSON.stringify({audience:'bridge-signing-audience',principals:[principal,caller]}), + BRIDGE:{idFromName:id=>id,get:()=>({fetch:async req=>{received=req;return Response.json({ok:true});}})}}; + const currentNow=Date.now(); + const jwt=await f.token({},undefined,currentNow); + const req=new Request(`https://${BRIDGE_HOST}/v1/poll`,{method:'POST',body:'{}',headers:{ + 'content-type':'application/json','x-bridge-principal':'amd-device','x-bridge-timestamp':String(currentNow),'x-bridge-nonce':'nonce-test', + 'x-bridge-signature':'synthetic-signature','cf-access-client-id':clientId,'cf-access-client-secret':'synthetic-secret', + 'cf-access-jwt-assertion':jwt,'cf-access-authenticated-user-email':'forged@example.invalid',cookie:'CF_Authorization=synthetic',authorization:'Bearer synthetic', + }}); + assert.equal(await verifyAccessServiceToken(req,workerEnv,{nowMs:currentNow,fetchImpl:f.fetchImpl}),clientId); + const result=await worker.fetch(req,workerEnv); + assert.equal(result.status,200); + assert.equal(received.headers.get('cf-access-jwt-assertion'),null); + assert.equal(received.headers.get('cf-access-client-secret'),null); + assert.equal(received.headers.get('cf-access-authenticated-user-email'),null); + assert.equal(received.headers.get('cookie'),null); + assert.equal(received.headers.get('authorization'),null); + assert.equal(received.headers.get('x-bridge-signature'),'synthetic-signature'); + received=null; + const forged=new Request(`https://${BRIDGE_HOST}/v1/poll`,{method:'POST',body:'{}',headers:{'cf-access-client-id':'other-client','cf-access-jwt-assertion':jwt}}); + assert.equal((await worker.fetch(forged,workerEnv)).status,401); + assert.equal(received,null); + principal.revoked=true; + workerEnv.BRIDGE_REGISTRY=JSON.stringify({audience:'bridge-signing-audience',principals:[principal,caller]}); + assert.equal((await worker.fetch(req,workerEnv)).status,401); +}); diff --git a/pm-stack/private-laptop-bridge/aster.mjs b/pm-stack/private-laptop-bridge/aster.mjs index e7607c80f0..cbbfdef45a 100644 --- a/pm-stack/private-laptop-bridge/aster.mjs +++ b/pm-stack/private-laptop-bridge/aster.mjs @@ -63,7 +63,8 @@ export async function runAster(argv, { loadConfig = readConfig, importKey = impo requireNonRoot(getuid); const config = await loadConfig(command.config, getuid); const privateKey = await importKey(config.privateKey); - const caller = callerFactory({ origin: config.origin, audience: config.audience, principal: config.principal, privateKey, device: 'amd' }); + const caller = callerFactory({ origin: config.origin, audience: config.audience, principal: config.principal, privateKey, + accessClientId: config.accessClientId, accessClientSecret: config.accessClientSecret, device: 'amd' }); const deadline = signal ? AbortSignal.any([signal, AbortSignal.timeout(65000)]) : AbortSignal.timeout(65000); const options = { signal: deadline }; const handle = command.command === 'queue-list' diff --git a/pm-stack/private-laptop-bridge/aster.test.mjs b/pm-stack/private-laptop-bridge/aster.test.mjs index bcb6550d5f..46f287481d 100644 --- a/pm-stack/private-laptop-bridge/aster.test.mjs +++ b/pm-stack/private-laptop-bridge/aster.test.mjs @@ -15,7 +15,8 @@ const samples = { }; function fixtures(overrides = {}) { const stdout = [], stderr = [], activity = []; - const config = { origin: 'https://bridge.invalid', audience: 'aster-test', principal: 'aster-caller', privateKey: { sensitive: 'never-print' } }; + const config = { origin: 'https://laptop-bridge-staging.security.cab', audience: 'aster-test', principal: 'aster-caller', privateKey: { sensitive: 'never-print' }, + accessClientId:'synthetic-caller-client',accessClientSecret:'synthetic-access-secret-that-is-never-live' }; const methods = { fleetQueueList: 'fleet.queue.list', fleetQueueHealth: 'fleet.queue.health', laptopHealth: 'laptop.health', laptopDiagnostics: 'laptop.diagnostics' }; const caller = Object.fromEntries(Object.entries(methods).map(([method, operation]) => [method, async (...args) => { activity.push({ method, args }); @@ -124,16 +125,16 @@ test('Aster: real CLI -> signed caller SDK -> workerd -> device -> projected out const { createClient } = await import('./client.mjs'); const { b64url, operations } = await import('./protocol.mjs'); const { fileURLToPath } = await import('node:url'); - const origin = 'https://aster-bridge.invalid', audience = 'aster-offline'; + const origin = 'https://laptop-bridge-staging.security.cab', audience = 'aster-offline'; const keys = {}, principals = []; const at = Date.now(); for (const [id, role] of [['aster','caller'], ['amd-device','device']]) { keys[id] = await crypto.subtle.generateKey('Ed25519', true, ['sign','verify']); - principals.push({ id, role, device: 'amd', publicKey: b64url(await crypto.subtle.exportKey('raw', keys[id].publicKey)), + principals.push({ id, role, device: 'amd', publicKey: b64url(await crypto.subtle.exportKey('raw', keys[id].publicKey)),accessClientId:id==='aster'?'synthetic-caller-client':'synthetic-device-client', issuedAt: at - 1000, expiresAt: at + 120000, revoked: false, scopes: [...operations] }); } const mf = new Miniflare({ name: 'aster-cli-offline', host: '127.0.0.1', modules: true, - scriptPath: fileURLToPath(new URL('./worker.mjs', import.meta.url)), modulesRules: [{ type: 'ESModule', include: ['**/*.mjs'] }], + scriptPath: fileURLToPath(new URL('./runtime-test-entry.mjs', import.meta.url)), modulesRules: [{ type: 'ESModule', include: ['**/*.mjs'] }], compatibilityDate: '2026-07-30', bindings: { ENABLED: 'true', BRIDGE_REGISTRY: JSON.stringify({ audience, principals }) }, durableObjects: { BRIDGE: { className: 'PrivateLaptopBridge', useSQLite: true } }, durableObjectsPersist: false, outboundService: () => new Response('offline only', { status: 599 }), @@ -145,9 +146,11 @@ test('Aster: real CLI -> signed caller SDK -> workerd -> device -> projected out return mf.dispatchFetch(request.url, { method: request.method, headers: Object.fromEntries(request.headers), body: await request.text() }); }; const device = createClient({ origin, audience, principal: 'amd-device', privateKey: keys['amd-device'].privateKey, + accessClientId:'synthetic-device-client',accessClientSecret:'synthetic-access-secret-that-is-never-live', getuid: () => 1000, fetch: dispatch, execute: async operation => samples[operation] }); const jwk = await crypto.subtle.exportKey('jwk', keys.aster.privateKey); - const config = { origin, audience, principal: 'aster', privateKey: Object.fromEntries(['kty','crv','x','d'].map(k => [k,jwk[k]])) }; + const config = { origin, audience, principal: 'aster', privateKey: Object.fromEntries(['kty','crv','x','d'].map(k => [k,jwk[k]])), + accessClientId:'synthetic-caller-client',accessClientSecret:'synthetic-access-secret-that-is-never-live' }; const commands = [['queue-list','--limit','1','--status','queued'], ['queue-health'], ['laptop-health'], ['laptop-diagnostics']]; for (const command of commands) { const stdout = [], stderr = []; diff --git a/pm-stack/private-laptop-bridge/caller.mjs b/pm-stack/private-laptop-bridge/caller.mjs index e051caf367..807d784f2d 100644 --- a/pm-stack/private-laptop-bridge/caller.mjs +++ b/pm-stack/private-laptop-bridge/caller.mjs @@ -1,6 +1,7 @@ // Caller SDK: four named reads, an explicit accepted handle, and bounded polling. // Keys are supplied by an approved caller integration; no enrollment or files. import { exact, identifier, validateOperation, validateResult, signRequest } from './protocol.mjs'; +import { BRIDGE_ORIGIN } from './access-auth.mjs'; export class CallerError extends Error { constructor(code, handle) { @@ -18,12 +19,14 @@ function validHandle(handle) { && validateOperation(handle.operation, handle.args) && Number.isSafeInteger(handle.expiresAt); } -export function createCaller({ origin, audience, principal, device, privateKey, fetch: fetchFn = globalThis.fetch, +export function createCaller({ origin, audience, principal, device, privateKey, accessClientId, accessClientSecret, fetch: fetchFn = globalThis.fetch, now = Date.now, requestTimeoutMs = 3000 }) { let url; try { url = new URL(origin); } catch { throw new CallerError('invalid-config'); } - if (url.protocol !== 'https:' || url.origin !== origin || url.username || url.password + if (url.protocol !== 'https:' || url.origin !== origin || url.origin !== BRIDGE_ORIGIN || url.username || url.password || !identifier(audience) || !identifier(principal) || !identifier(device) + || typeof accessClientId !== 'string' || !/^[A-Za-z0-9._-]{8,128}$/.test(accessClientId) + || typeof accessClientSecret !== 'string' || accessClientSecret.length < 32 || accessClientSecret.length > 256 || !privateKey || privateKey.type !== 'private' || privateKey.algorithm?.name !== 'Ed25519' || !Number.isInteger(requestTimeoutMs) || requestTimeoutMs < 1 || requestTimeoutMs > 3000) throw new CallerError('invalid-config'); @@ -44,7 +47,11 @@ export function createCaller({ origin, audience, principal, device, privateKey, try { const work = async () => { controller.signal.throwIfAborted(); - const request = await signRequest({ origin, audience, principal, privateKey, path, body, now: startedAt }); + const signed = await signRequest({ origin, audience, principal, privateKey, path, body, now: startedAt }); + const headers = new Headers(signed.headers); + headers.set('cf-access-client-id', accessClientId); + headers.set('cf-access-client-secret', accessClientSecret); + const request = new Request(signed, {headers}); controller.signal.throwIfAborted(); response = await fetchFn(request, { redirect: 'error', signal: controller.signal }); if (controller.signal.aborted) { void response.body?.cancel().catch(() => {}); controller.signal.throwIfAborted(); } diff --git a/pm-stack/private-laptop-bridge/client.mjs b/pm-stack/private-laptop-bridge/client.mjs index ddca5068cd..586411e896 100644 --- a/pm-stack/private-laptop-bridge/client.mjs +++ b/pm-stack/private-laptop-bridge/client.mjs @@ -6,6 +6,7 @@ import { pathToFileURL } from 'node:url'; import { setTimeout as delay } from 'node:timers/promises'; import { signRequest, validateOperation, validateResult, identifier } from './protocol.mjs'; import { createAdapters } from './adapters.mjs'; +import { BRIDGE_ORIGIN } from './access-auth.mjs'; const exact = (v, list) => v && typeof v === 'object' && !Array.isArray(v) && Object.keys(v).length === list.length && list.every(k => Object.hasOwn(v, k)); const id = identifier; @@ -19,9 +20,9 @@ export function requireNonRoot(getuid = process.getuid) { if (typeof getuid !== 'function' || !Number.isInteger(getuid()) || getuid() <= 0) throw new Error('non-root-required'); } export function validateConfig(config) { - if (!exact(config, ['origin','audience','principal','privateKey'])) throw new Error('invalid-config'); + if (!exact(config, ['origin','audience','principal','privateKey','accessClientId','accessClientSecret'])) throw new Error('invalid-config'); const origin = new URL(config.origin); - if (origin.protocol !== 'https:' || origin.origin !== config.origin || origin.username || origin.password || !id(config.principal) || typeof config.audience !== 'string' || config.audience.length < 1 || config.audience.length > 200) throw new Error('invalid-config'); + if (origin.protocol !== 'https:' || origin.origin !== config.origin || origin.origin !== BRIDGE_ORIGIN || origin.username || origin.password || !id(config.principal) || typeof config.audience !== 'string' || config.audience.length < 1 || config.audience.length > 200 || typeof config.accessClientId !== 'string' || !/^[A-Za-z0-9._-]{8,128}$/.test(config.accessClientId) || typeof config.accessClientSecret !== 'string' || config.accessClientSecret.length < 32 || config.accessClientSecret.length > 256) throw new Error('invalid-config'); if (!exact(config.privateKey, ['kty','crv','x','d']) || config.privateKey.kty !== 'OKP' || config.privateKey.crv !== 'Ed25519' || !/^[A-Za-z0-9_-]{43}$/.test(config.privateKey.x) || !/^[A-Za-z0-9_-]{43}$/.test(config.privateKey.d)) throw new Error('invalid-config'); return config; } @@ -56,14 +57,18 @@ async function readResponse(response, signal) { return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks))); } finally { signal.removeEventListener('abort', abort); void reader.cancel().catch(() => {}); reader.releaseLock(); } } -export function createClient({ origin, audience, principal, privateKey, fetch: fetchFn = globalThis.fetch, execute = createAdapters(), now = Date.now, sleep = delay, getuid = process.getuid, requestTimeoutMs = 5000 }) { +export function createClient({ origin, audience, principal, privateKey, accessClientId, accessClientSecret, fetch: fetchFn = globalThis.fetch, execute = createAdapters(), now = Date.now, sleep = delay, getuid = process.getuid, requestTimeoutMs = 5000 }) { requireNonRoot(getuid); const url = new URL(origin); - if (url.protocol !== 'https:' || url.origin !== origin || !id(principal) || typeof audience !== 'string' || !audience) throw new Error('invalid-config'); + if (url.protocol !== 'https:' || url.origin !== origin || url.origin !== BRIDGE_ORIGIN || !id(principal) || typeof audience !== 'string' || !audience || typeof accessClientId !== 'string' || !/^[A-Za-z0-9._-]{8,128}$/.test(accessClientId) || typeof accessClientSecret !== 'string' || accessClientSecret.length < 32 || accessClientSecret.length > 256) throw new Error('invalid-config'); async function send(path, body, signal) { const bounded = signal ? AbortSignal.any([signal, AbortSignal.timeout(requestTimeoutMs)]) : AbortSignal.timeout(requestTimeoutMs); const startedAt = now(); - const request = await signRequest({ origin, audience, principal, privateKey, path, body, now: startedAt }); + const signed = await signRequest({ origin, audience, principal, privateKey, path, body, now: startedAt }); + const headers = new Headers(signed.headers); + headers.set('cf-access-client-id', accessClientId); + headers.set('cf-access-client-secret', accessClientSecret); + const request = new Request(signed, {headers}); const response = await fetchFn(request, { redirect: 'error', signal: bounded }); if ([401,403,410].includes(response.status)) { void response.body?.cancel().catch(() => {}); throw new BridgeDenied(); } if (!response.ok || response.redirected) { void response.body?.cancel().catch(() => {}); throw new Error('bridge-unavailable'); } diff --git a/pm-stack/private-laptop-bridge/client.test.mjs b/pm-stack/private-laptop-bridge/client.test.mjs index 3d0701f31b..ddb94ab831 100644 --- a/pm-stack/private-laptop-bridge/client.test.mjs +++ b/pm-stack/private-laptop-bridge/client.test.mjs @@ -11,7 +11,8 @@ const now = 1800000000000; const snapshot = () => ({ version:1, fetchedAt:now, available:true, stale:false, complete:false, total:null, tasks: [{id:1,status:'queued',priority:0},{id:2,status:'cancelled',priority:null}], counts:Object.fromEntries(statuses.map(s => [s, s === 'queued' ? 1 : 0])) }); const json = body => new Response(JSON.stringify(body), { headers:{'content-type':'application/json'} }); const keys = await crypto.subtle.generateKey('Ed25519', true, ['sign','verify']); -const base = { origin:'https://bridge.invalid', audience:'test-bridge', principal:'amd-device', privateKey:keys.privateKey, now:()=>now, getuid:()=>1000 }; +const base = { origin:'https://laptop-bridge-staging.security.cab', audience:'test-bridge', principal:'amd-device', privateKey:keys.privateKey, + accessClientId:'synthetic-device-client',accessClientSecret:'synthetic-access-secret-that-is-never-live',now:()=>now,getuid:()=>1000 }; const job = (overrides = {}) => ({ id:'job-1', lease:'lease-1', operation:'laptop.health', args:{}, expiresAt:now+60000, leaseExpiresAt:now+15000, serverNow:now, ...overrides }); test('oracle: CLI grammar rejects every undeclared argument before activity', () => { @@ -26,13 +27,13 @@ test('oracle: non-root gate runs before network and invalid origins cannot be co let calls=0; assert.throws(()=>createClient({...base,getuid:()=>0,fetch:()=>calls++}), /non-root/); assert.equal(calls,0); - for (const origin of ['http://bridge.invalid','https://bridge.invalid/path','https://user:pass@bridge.invalid','https://bridge.invalid/']) assert.throws(()=>createClient({...base,origin})); + for (const origin of ['http://bridge.invalid','https://laptop-bridge-staging.security.cab/path','https://user:pass@bridge.invalid','https://laptop-bridge-staging.security.cab/']) assert.throws(()=>createClient({...base,origin})); }); test('oracle: configuration contains exactly owner provisioned Ed25519 identity', async () => { const exported=await crypto.subtle.exportKey('jwk', keys.privateKey); const privateKey=Object.fromEntries(['kty','crv','x','d'].map(k=>[k,exported[k]])); - const config={origin:base.origin,audience:base.audience,principal:base.principal,privateKey}; + const config={origin:base.origin,audience:base.audience,principal:base.principal,privateKey,accessClientId:base.accessClientId,accessClientSecret:base.accessClientSecret}; assert.equal(validateConfig(config),config); assert.throws(()=>validateConfig({...config,shell:'/bin/sh'})); assert.throws(()=>validateConfig({...config,privateKey:{...privateKey,kty:'RSA'}})); diff --git a/pm-stack/private-laptop-bridge/cloudflare.config.ts b/pm-stack/private-laptop-bridge/cloudflare.config.ts index 4ff736527a..d5747182bd 100644 --- a/pm-stack/private-laptop-bridge/cloudflare.config.ts +++ b/pm-stack/private-laptop-bridge/cloudflare.config.ts @@ -1,6 +1,7 @@ import {bindings, defineConfig, exports} from 'cf/config'; import * as smoke from './smoke.mjs' with {type:'cf-worker'}; import * as bridge from './gateway.mjs' with {type:'cf-worker'}; +import {BRIDGE_HOST} from './access-auth.mjs'; const isolated = () => ({ workersDev: false, @@ -18,6 +19,7 @@ const isolated = () => ({ export default defineConfig(({mode}) => mode === 'bridge' ? ({ worker: { ...isolated(), + domains: [BRIDGE_HOST], name: 'private-laptop-bridge-staging', compatibilityDate: '2026-07-30', entrypoint: bridge, @@ -27,6 +29,9 @@ export default defineConfig(({mode}) => mode === 'bridge' ? ({ GATEWAY_HOST: bindings.text('private-bridge-staging.invalid'), GATEWAY_ACCOUNT_ID: bindings.text(''), GATEWAY_POLICY_ID: bindings.text(''), GATEWAY_IDENTITY_EMAIL: bindings.text(''), GATEWAY_POSTURE_ID: bindings.text(''), + BRIDGE_HOST: bindings.text(BRIDGE_HOST), + ACCESS_ISSUER: bindings.text(process.env.CF_BRIDGE_ACCESS_ISSUER ?? ''), + ACCESS_AUDIENCE: bindings.text(process.env.CF_BRIDGE_ACCESS_AUDIENCE ?? ''), BRIDGE_REGISTRY: bindings.text(''), BRIDGE: bindings.durableObject({worker: 'private-laptop-bridge-staging', exportName: 'PrivateLaptopBridge'}), }, diff --git a/pm-stack/private-laptop-bridge/control.test.mjs b/pm-stack/private-laptop-bridge/control.test.mjs index fa8761592c..b420a37222 100644 --- a/pm-stack/private-laptop-bridge/control.test.mjs +++ b/pm-stack/private-laptop-bridge/control.test.mjs @@ -20,17 +20,17 @@ async function setup() { const keys = {}, principals = []; for (const [id, role] of [['alice', 'caller'], ['bob', 'caller'], ['laptop', 'device']]) { keys[id] = await crypto.subtle.generateKey('Ed25519', true, ['sign', 'verify']); - principals.push({id, role, device: 'amd', publicKey: b64url(await crypto.subtle.exportKey('raw', keys[id].publicKey)), scopes: [...operations], issuedAt: Date.now() - 1000, expiresAt: Date.now() + 1800000, revoked: false}); + principals.push({id, role, device: 'amd', publicKey: b64url(await crypto.subtle.exportKey('raw', keys[id].publicKey)), accessClientId:`synthetic-${id}-client`,scopes: [...operations], issuedAt: Date.now() - 1000, expiresAt: Date.now() + 1800000, revoked: false}); } const registry = {audience: 'offline-test', principals}; const env = {ENABLED: 'true', BRIDGE_REGISTRY: JSON.stringify(registry)}; const storage = new Storage(); let object = new PrivateLaptopBridge({storage}, env); env.BRIDGE = {idFromName: x => x, get: () => ({fetch: req => object.fetch(req)})}; - const request = (id, path, body, options = {}) => signRequest({origin: 'https://bridge.invalid', audience: registry.audience, principal: id, privateKey: keys[id].privateKey, path, body, ...options}); - const call = async (id, path, body, options) => { const r = await worker.fetch(await request(id, path, body, options), env); return {status: r.status, body: await r.json()}; }; + const request = (id, path, body, options = {}) => signRequest({origin: 'https://laptop-bridge-staging.security.cab', audience: registry.audience, principal: id, privateKey: keys[id].privateKey, path, body, ...options}); + const call = async (id, path, body, options) => { const r = await object.fetch(await request(id, path, body, options)); return {status: r.status, body: await r.json()}; }; const update = fn => { fn(registry); env.BRIDGE_REGISTRY = JSON.stringify(registry); }; const start = (id = 'alice', operation = 'laptop.health', args = {}) => call(id, '/v1/call', {device: 'amd', operation, args}); - return {env, storage, request, call, update, start, restart: () => { object = new PrivateLaptopBridge({storage}, env); }, alarm: () => object.alarm()}; + return {env, storage, request, call, update, start, get object(){return object;}, restart: () => { object = new PrivateLaptopBridge({storage}, env); }, alarm: () => object.alarm()}; } const okHealth = {ok: true, data: {queueBroker: 'up'}}; @@ -50,9 +50,9 @@ test('signature binds audience, principal, exact method/path/body; unknown or ex assert.equal((await h.start('alice')).status, 202); // positive control for (const options of [{audience: 'other'}, {now: Date.now() - 31000}, {now: Date.now() + 31000}]) assert.equal((await h.call('alice', '/v1/poll', {}, options)).status, 401); const req = await h.request('alice', '/v1/poll', {}); - assert.equal((await worker.fetch(new Request(req.url, {method: 'POST', headers: req.headers, body: '{"extra":1}'}), h.env)).status, 401); + assert.equal((await h.object.fetch(new Request(req.url, {method: 'POST', headers: req.headers, body: '{"extra":1}'}))).status, 401); const r2 = await h.request('alice', '/v1/poll', {}); - assert.equal((await worker.fetch(new Request('https://bridge.invalid/v1/read', {method: 'POST', headers: r2.headers, body: '{}'}), h.env)).status, 401); + assert.equal((await h.object.fetch(new Request('https://laptop-bridge-staging.security.cab/v1/read', {method: 'POST', headers: r2.headers, body: '{}'}))).status, 401); h.update(r => { r.principals[0].revoked = true; }); assert.equal((await h.call('alice', '/v1/poll', {})).status, 401); }); @@ -69,9 +69,9 @@ test('role, scope, operation schema and forbidden argument corpus fail closed', test('replay is durable, concurrent duplicates execute once, rejected requests consume quota', async () => { const h = await setup(); const nonce = 'fixed-nonce'; const req = await h.request('alice', '/v1/call', {device: 'amd', operation: 'laptop.health', args: {}}, {nonce}); - const results = await Promise.all(Array.from({length: 12}, () => worker.fetch(req.clone(), h.env))); + const results = await Promise.all(Array.from({length: 12}, () => h.object.fetch(req.clone()))); assert.equal(results.filter(r => r.status === 202).length, 1); assert.equal(results.filter(r => r.status === 409).length, 11); - h.restart(); assert.equal((await worker.fetch(req.clone(), h.env)).status, 409); + h.restart(); assert.equal((await h.object.fetch(req.clone())).status, 409); for (let n = 13; n < 60; n++) assert.equal((await h.call('alice', '/v1/poll', {})).status, 403); assert.equal((await h.call('alice', '/v1/poll', {})).status, 429); assert.equal(Object.keys(h.storage.value.jobs).length, 1); @@ -146,13 +146,13 @@ test('body size, streaming deadline and header limits reject before dispatch', a await assert.rejects(boundedText(new ReadableStream({}), 8192, 5), /timeout/); const h = await setup(); const large = await h.request('alice', '/v1/poll', {data: 'x'.repeat(8192)}); - assert.equal((await worker.fetch(large, h.env)).status, 413); + assert.equal((await h.object.fetch(large)).status, 413); const req = await h.request('alice', '/v1/poll', {}); req.headers.set('content-length', '90000000000'); - assert.equal((await worker.fetch(req, h.env)).status, 413); + assert.equal((await h.object.fetch(req)).status, 413); const bad = await h.request('alice', '/v1/poll', {}); bad.headers.set('x-bridge-signature', 'x'.repeat(9000)); - assert.equal((await worker.fetch(bad, h.env)).status, 401); + assert.equal((await h.object.fetch(bad)).status, 401); assert.equal(h.storage.value, undefined); }); diff --git a/pm-stack/private-laptop-bridge/freshness.test.mjs b/pm-stack/private-laptop-bridge/freshness.test.mjs index bda2bb69be..431bddc283 100644 --- a/pm-stack/private-laptop-bridge/freshness.test.mjs +++ b/pm-stack/private-laptop-bridge/freshness.test.mjs @@ -36,14 +36,14 @@ async function harness(t) { const keys = {}, principals = []; for (const [id, role] of [['owner','caller'], ['laptop','device']]) { keys[id] = await crypto.subtle.generateKey('Ed25519', true, ['sign','verify']); - principals.push({ id, role, device:'amd', publicKey:b64url(await crypto.subtle.exportKey('raw', keys[id].publicKey)), scopes:[...operations], issuedAt:NOW-1000, expiresAt:NOW+1800000, revoked:false }); + principals.push({ id, role, device:'amd', publicKey:b64url(await crypto.subtle.exportKey('raw', keys[id].publicKey)), accessClientId:`synthetic-${id}-client`, scopes:[...operations], issuedAt:NOW-1000, expiresAt:NOW+1800000, revoked:false }); } const env = { ENABLED:'true', BRIDGE_REGISTRY:JSON.stringify({ audience:'freshness-test', principals }) }; const object = new PrivateLaptopBridge({ storage:new Storage() }, env); env.BRIDGE = { idFromName:x=>x, get:()=>({ fetch:r=>object.fetch(r) }) }; - const fetch = request => worker.fetch(request, env); + const fetch = request => object.fetch(request); const execute = createAdapters({ readSnapshot:()=>readQueueSnapshot(home), clock:()=>clock }); - const config = { origin:'https://bridge.invalid', audience:'freshness-test', fetch, now:()=>clock }; + const config = { origin:'https://laptop-bridge-staging.security.cab', audience:'freshness-test', accessClientId:'synthetic-client-id',accessClientSecret:'synthetic-access-secret-that-is-never-live',fetch,now:()=>clock }; const client = createClient({ ...config, principal:'laptop', privateKey:keys.laptop.privateKey, execute, getuid:()=>1000 }); const caller = createCaller({ ...config, principal:'owner', device:'amd', privateKey:keys.owner.privateKey }); const collect = (health={ok:true,rows:[rawIdle()]}, list={ok:true,rows:[]}, fetchedAt=clock) => fetchQueueSnapshot('http://synthetic.invalid', 'synthetic-not-a-secret', async url=>({ ok:true,status:200,json:async()=>url.endsWith('/health')?health:list }), ()=>fetchedAt); diff --git a/pm-stack/private-laptop-bridge/gateway.mjs b/pm-stack/private-laptop-bridge/gateway.mjs index 3e48509e5f..8fb75b175f 100644 --- a/pm-stack/private-laptop-bridge/gateway.mjs +++ b/pm-stack/private-laptop-bridge/gateway.mjs @@ -1,7 +1,7 @@ // Private Gateway Forward RPC ingress. No public HTTP management entrypoint. // Context contract: https://developers.cloudflare.com/cloudflare-one/traffic-controls/integrate-workers/available-context/ import { WorkerEntrypoint } from 'cloudflare:workers'; -import bridge from './worker.mjs'; +import bridge, {dispatchSignedRequest} from './worker.mjs'; export { PrivateLaptopBridge } from './worker.mjs'; const paths = new Set(['/v1/call', '/v1/poll', '/v1/result', '/v1/read']); @@ -45,8 +45,11 @@ export class GatewayMiddleware extends WorkerEntrypoint { } catch { return deny(503, 'gateway-context-unavailable'); } // Independent signed caller/device authentication, replay and scope checks // still run inside the existing Durable Object control plane. - return bridge.fetch(request, this.env); + return dispatchSignedRequest(request, this.env); } } -export default {fetch() { return deny(403, 'private-rpc-only'); }}; +// The fixed custom hostname enters the Worker directly, but only after the +// Worker validates Access's signed service-token JWT and the DO independently +// validates the Ed25519 request. No proxy fallback or origin fetch exists. +export default {fetch(request, env) { return bridge.fetch(request, env); }}; diff --git a/pm-stack/private-laptop-bridge/gateway.test.mjs b/pm-stack/private-laptop-bridge/gateway.test.mjs index 47a57c7604..3f37c4f08e 100644 --- a/pm-stack/private-laptop-bridge/gateway.test.mjs +++ b/pm-stack/private-laptop-bridge/gateway.test.mjs @@ -44,7 +44,7 @@ async function harness(t, overrides = {}) { const keys = {}, principals = []; for (const [id, role] of [['caller','caller'], ['device','device']]) { keys[id] = await crypto.subtle.generateKey('Ed25519', true, ['sign','verify']); - principals.push({id, role, device:'amd', publicKey:b64url(await crypto.subtle.exportKey('raw', keys[id].publicKey)), scopes:[...operations], issuedAt:Date.now()-1000, expiresAt:Date.now()+120000, revoked:false}); + principals.push({id, role, device:'amd', publicKey:b64url(await crypto.subtle.exportKey('raw', keys[id].publicKey)), accessClientId:`synthetic-${id}-client`,scopes:[...operations], issuedAt:Date.now()-1000, expiresAt:Date.now()+120000, revoked:false}); } const mf = new Miniflare({host:'127.0.0.1', workers:[ {name:'gateway-harness', modules:true, script:harnessSource, compatibilityDate:'2026-07-30', serviceBindings:{PRIVATE:{name:'private-bridge',entrypoint:'GatewayMiddleware'}}, outboundService:() => {throw new Error('outbound forbidden');}}, @@ -62,7 +62,7 @@ async function harness(t, overrides = {}) { return {mf,send,keys}; } -test('private Gateway RPC reaches signed DO normal flow; ordinary HTTP is always denied',async t=>{ +test('Gateway RPC contract and direct Access HTTP gate are independent; ordinary HTTP is denied without Access config',async t=>{ const h=await harness(t); const submitted=await h.send('caller','/v1/call',{device:'amd',operation:'laptop.health',args:{}}); assert.equal(submitted.status,202,JSON.stringify(submitted)); @@ -74,7 +74,7 @@ test('private Gateway RPC reaches signed DO normal flow; ordinary HTTP is always const direct=await h.mf.getWorker('private-bridge'); const signed=await signRequest({origin:`https://${host}`,audience:'gateway-offline',principal:'caller',privateKey:h.keys.caller.privateKey,path:'/v1/call',body:{device:'amd',operation:'laptop.health',args:{}}}); const response=await direct.fetch(signed.url,{method:'POST',headers:Object.fromEntries(signed.headers),body:await signed.text()}); - assert.equal(response.status,403);assert.deepEqual(await response.json(),{error:'private-rpc-only'}); + assert.equal(response.status,401);assert.deepEqual(await response.json(),{error:'access-authentication'}); }); test('private Gateway RPC rejects route and trusted-context mismatches without next',async t=>{ diff --git a/pm-stack/private-laptop-bridge/model.test.mjs b/pm-stack/private-laptop-bridge/model.test.mjs index bfaa860892..7f50f17f27 100644 --- a/pm-stack/private-laptop-bridge/model.test.mjs +++ b/pm-stack/private-laptop-bridge/model.test.mjs @@ -26,7 +26,7 @@ test('model: 50 seeded call/poll/lease/replay/revoke/reconnect traces preserve a const keys = {}, definitions = []; for (const [id, role] of [['alice','caller'], ['bob','caller'], ['laptop','device']]) { keys[id] = await crypto.subtle.generateKey('Ed25519', true, ['sign','verify']); - definitions.push({id, role, device:'amd', publicKey:b64url(await crypto.subtle.exportKey('raw',keys[id].publicKey)), scopes:['laptop.health'], issuedAt:start-1000, expiresAt:start+3599000, revoked:false}); + definitions.push({id, role, device:'amd', publicKey:b64url(await crypto.subtle.exportKey('raw',keys[id].publicKey)), accessClientId:`synthetic-${id}-client`,scopes:['laptop.health'], issuedAt:start-1000, expiresAt:start+3599000, revoked:false}); } const coverage={accepted:0,leased:0,completed:0,staleLeaseDenied:0,replayDenied:0,completeRead:0,ownerDenied:0}; for (let seed=1; seed<=50; seed++) { @@ -40,8 +40,8 @@ test('model: 50 seeded call/poll/lease/replay/revoke/reconnect traces preserve a const revoked={alice:false,bob:false,laptop:false}; const jobs=new Map(), leases=[], replays=[]; let nextNonce=0; - const make=(principal,path,body)=>signRequest({origin:'https://bridge.invalid',audience:'model-test',principal,privateKey:keys[principal].privateKey,path,body,now,nonce:`seed-${seed}-${nextNonce++}`}); - const send=async request=>{const response=await worker.fetch(request.clone(),env);return {status:response.status,body:await response.json()};}; + const make=(principal,path,body)=>signRequest({origin:'https://laptop-bridge-staging.security.cab',audience:'model-test',principal,privateKey:keys[principal].privateKey,path,body,now,nonce:`seed-${seed}-${nextNonce++}`}); + const send=async request=>{const response=await object.fetch(request.clone());return {status:response.status,body:await response.json()};}; const gc=()=>{for(const [id,j] of jobs)if(j.retainUntil<=now)jobs.delete(id);}; const live=j=>j && j.expiresAt>now && !revoked.alice; const check=(got,want,step,action)=>assert.equal(got,want,`seed=${seed} step=${step} action=${action}`); diff --git a/pm-stack/private-laptop-bridge/private-laptop-bridge-staging-bootstrap.workflow.yml.disabled b/pm-stack/private-laptop-bridge/private-laptop-bridge-staging-bootstrap.workflow.yml.disabled index 9cf5636cac..7fed390a92 100644 --- a/pm-stack/private-laptop-bridge/private-laptop-bridge-staging-bootstrap.workflow.yml.disabled +++ b/pm-stack/private-laptop-bridge/private-laptop-bridge-staging-bootstrap.workflow.yml.disabled @@ -1,5 +1,6 @@ # Dormant reviewed template. GitHub ignores this non-workflow extension. -# Enable only after `cloudflare-staging-bootstrap` exists with reviewers, +# The owner creates the exact metadata-only Worker locally and pins its ID before CI. +# Enable only after `cloudflare-staging` exists with reviewers, # prevent_self_review=true, a main-only branch policy and the exact source pin. name: Private laptop bridge disabled staging bootstrap @@ -36,14 +37,18 @@ jobs: env: GH_TOKEN: ${{ github.token }} GITHUB_API_URL: ${{ github.api_url }} - CF_BRIDGE_BOOTSTRAP_REVIEWER_IDS: ${{ vars.CF_BRIDGE_BOOTSTRAP_REVIEWER_IDS }} - run: node staging-bootstrap.mjs github-environment + GITHUB_ACTOR_ID: ${{ github.actor_id }} + CF_BRIDGE_RELEASE_REVIEWER_IDS: ${{ vars.CF_BRIDGE_RELEASE_REVIEWER_IDS }} + run: node staging-bootstrap.mjs github-environment-bootstrap deploy-disabled-bridge: needs: verify-environment-before-assignment - if: needs.verify-environment-before-assignment.result == 'success' && needs.verify-environment-before-assignment.outputs.environment == 'cloudflare-staging-bootstrap' + if: needs.verify-environment-before-assignment.result == 'success' && needs.verify-environment-before-assignment.outputs.environment == 'cloudflare-staging' environment: name: ${{ needs.verify-environment-before-assignment.outputs.environment }} + env: + CF_BRIDGE_ACCESS_ISSUER: ${{ vars.CF_BRIDGE_ACCESS_ISSUER }} + CF_BRIDGE_ACCESS_AUDIENCE: ${{ vars.CF_BRIDGE_ACCESS_AUDIENCE }} runs-on: ubuntu-24.04 timeout-minutes: 25 steps: @@ -71,6 +76,9 @@ jobs: run: npm ci --ignore-scripts --no-audit --no-fund - name: Verify disabled bridge build and deploy dry run working-directory: pm-stack/private-laptop-bridge + env: + CF_BRIDGE_ACCESS_ISSUER: ${{ vars.CF_BRIDGE_ACCESS_ISSUER }} + CF_BRIDGE_ACCESS_AUDIENCE: ${{ vars.CF_BRIDGE_ACCESS_AUDIENCE }} run: | set -euo pipefail node --test deployment-config.test.mjs release-contract.test.mjs staging-bootstrap.test.mjs @@ -81,19 +89,26 @@ jobs: id: provider working-directory: pm-stack/private-laptop-bridge env: - CF_BRIDGE_BOOTSTRAP_ACCOUNT_ID: ${{ secrets.CF_BRIDGE_BOOTSTRAP_ACCOUNT_ID }} - CF_BRIDGE_BOOTSTRAP_ZONE_IDS: ${{ secrets.CF_BRIDGE_BOOTSTRAP_ZONE_IDS }} - CF_BRIDGE_BOOTSTRAP_READ_TOKEN: ${{ secrets.CF_BRIDGE_BOOTSTRAP_READ_TOKEN }} + CF_BRIDGE_ACCOUNT_ID: ${{ secrets.CF_BRIDGE_ACCOUNT_ID }} + CF_BRIDGE_WORKER_ID: ${{ vars.CF_BRIDGE_WORKER_ID }} + CF_BRIDGE_ZONE_IDS: ${{ secrets.CF_BRIDGE_ZONE_IDS }} + CF_BRIDGE_READ_TOKEN: ${{ secrets.CF_BRIDGE_READ_TOKEN }} + CF_BRIDGE_GATEWAY_READ_TOKEN: ${{ secrets.CF_BRIDGE_GATEWAY_READ_TOKEN }} + CF_BRIDGE_ACCESS_ISSUER: ${{ vars.CF_BRIDGE_ACCESS_ISSUER }} + CF_BRIDGE_ACCESS_AUDIENCE: ${{ vars.CF_BRIDGE_ACCESS_AUDIENCE }} GITHUB_SHA: ${{ github.sha }} run: node staging-bootstrap.mjs preflight - name: Deploy only the pinned disabled declarative Worker and SQLite export if: steps.provider.outputs.status == 'deploy' working-directory: pm-stack/private-laptop-bridge env: - CF_BRIDGE_BOOTSTRAP_READ_TOKEN: ${{ secrets.CF_BRIDGE_BOOTSTRAP_READ_TOKEN }} - CF_BRIDGE_BOOTSTRAP_WRITE_TOKEN: ${{ secrets.CF_BRIDGE_BOOTSTRAP_WRITE_TOKEN }} - CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CF_BRIDGE_BOOTSTRAP_ACCOUNT_ID }} - CLOUDFLARE_API_TOKEN: ${{ secrets.CF_BRIDGE_BOOTSTRAP_WRITE_TOKEN }} + CF_BRIDGE_READ_TOKEN: ${{ secrets.CF_BRIDGE_READ_TOKEN }} + CF_BRIDGE_GATEWAY_READ_TOKEN: ${{ secrets.CF_BRIDGE_GATEWAY_READ_TOKEN }} + CF_BRIDGE_API_TOKEN: ${{ secrets.CF_BRIDGE_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CF_BRIDGE_ACCOUNT_ID }} + CLOUDFLARE_API_TOKEN: ${{ secrets.CF_BRIDGE_API_TOKEN }} + CF_BRIDGE_ACCESS_ISSUER: ${{ vars.CF_BRIDGE_ACCESS_ISSUER }} + CF_BRIDGE_ACCESS_AUDIENCE: ${{ vars.CF_BRIDGE_ACCESS_AUDIENCE }} run: | set -euo pipefail node staging-bootstrap.mjs assert-distinct-credentials @@ -102,8 +117,12 @@ jobs: if: steps.provider.outputs.status == 'deploy' working-directory: pm-stack/private-laptop-bridge env: - CF_BRIDGE_BOOTSTRAP_ACCOUNT_ID: ${{ secrets.CF_BRIDGE_BOOTSTRAP_ACCOUNT_ID }} - CF_BRIDGE_BOOTSTRAP_ZONE_IDS: ${{ secrets.CF_BRIDGE_BOOTSTRAP_ZONE_IDS }} - CF_BRIDGE_BOOTSTRAP_READ_TOKEN: ${{ secrets.CF_BRIDGE_BOOTSTRAP_READ_TOKEN }} + CF_BRIDGE_ACCOUNT_ID: ${{ secrets.CF_BRIDGE_ACCOUNT_ID }} + CF_BRIDGE_WORKER_ID: ${{ vars.CF_BRIDGE_WORKER_ID }} + CF_BRIDGE_ZONE_IDS: ${{ secrets.CF_BRIDGE_ZONE_IDS }} + CF_BRIDGE_READ_TOKEN: ${{ secrets.CF_BRIDGE_READ_TOKEN }} + CF_BRIDGE_GATEWAY_READ_TOKEN: ${{ secrets.CF_BRIDGE_GATEWAY_READ_TOKEN }} + CF_BRIDGE_ACCESS_ISSUER: ${{ vars.CF_BRIDGE_ACCESS_ISSUER }} + CF_BRIDGE_ACCESS_AUDIENCE: ${{ vars.CF_BRIDGE_ACCESS_AUDIENCE }} GITHUB_SHA: ${{ github.sha }} run: node staging-bootstrap.mjs postflight diff --git a/pm-stack/private-laptop-bridge/release-contract.mjs b/pm-stack/private-laptop-bridge/release-contract.mjs index 7ff737203d..bcf14a0fd8 100644 --- a/pm-stack/private-laptop-bridge/release-contract.mjs +++ b/pm-stack/private-laptop-bridge/release-contract.mjs @@ -1,6 +1,7 @@ import {createHash} from 'node:crypto'; import {lstat, readFile, readdir} from 'node:fs/promises'; import {join, relative, resolve, sep} from 'node:path'; +import {BRIDGE_HOST} from './access-auth.mjs'; const UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; const SHA=/^[0-9a-f]{40}$/; @@ -12,6 +13,11 @@ const fail=(message)=>{throw new Error(message);}; const digest=(bytes)=>createHash('sha256').update(bytes).digest('hex'); const stable=(value)=>Array.isArray(value)?value.map(stable):value&&typeof value==='object'?Object.fromEntries(Object.keys(value).sort().map(key=>[key,stable(value[key])])):value; const same=(a,b)=>JSON.stringify(stable(a))===JSON.stringify(stable(b)); +const validAccess=(issuerValue,audience)=>{ + let issuer; try {issuer=new URL(issuerValue);} catch {return false;} + return issuer.protocol==='https:'&&issuer.origin===issuerValue&&issuer.pathname==='/'&&!issuer.search&&!issuer.hash&& + /^[a-z0-9-]+\.cloudflareaccess\.com$/.test(issuer.hostname)&&/^[A-Za-z0-9_-]{20,128}$/.test(audience??''); +}; export function extractServerVersionId(stdout,{worker}={}) { let value; try {value=JSON.parse(stdout);} catch {fail('cf versions create did not return JSON; refusing to infer a version id');} @@ -155,13 +161,30 @@ export function assertUploadRun(run,jobsResponse,handoff) { return true; } -export function assertPreflight(proof,{accountId,worker,environment,now=Date.now()}) { +export function assertPreflight(proof,{accountId,worker,environment,now=Date.now(),accessIssuer=process.env.CF_BRIDGE_ACCESS_ISSUER??'',accessAudience=process.env.CF_BRIDGE_ACCESS_AUDIENCE??''}) { if(!proof||proof.schema!==1||proof.verified!==true||proof.account_id!==accountId||typeof proof.evidence_ref!=='string'||proof.evidence_ref.trim().length<3||!Number.isFinite(Date.parse(proof.verified_at))||!Number.isFinite(Date.parse(proof.expires_at))||Date.parse(proof.verified_at)>now||Date.parse(proof.expires_at)<=now||Date.parse(proof.expires_at)-Date.parse(proof.verified_at)>24*3600000) fail('owner read-only staging proof is absent, expired, or invalid'); const release=proof.release_policy,allowedRefs=release?.allowed_environment_branches?.[environment]; if(release?.repository!=='developing-today/code'||release?.branch!=='main'||release?.branch_protected!==true||release?.required_pull_request_reviews!==true||release?.force_push_disabled!==true||release?.admin_bypass_disabled!==true||release?.environment_reviewers_required?.[environment]!==true||release?.self_review_disabled?.[environment]!==true||!Array.isArray(allowedRefs)||!same(allowedRefs,['main'])||typeof release?.evidence_ref!=='string'||release.evidence_ref.trim().length<3) fail('trusted protected-main or deployment-environment approval proof is absent or invalid'); const target=proof.targets?.[worker]; - const expectedVars=worker==='private-laptop-bridge-staging'?{ENABLED:'false',GATEWAY_HOST:'private-bridge-staging.invalid',GATEWAY_ACCOUNT_ID:'',GATEWAY_POLICY_ID:'',GATEWAY_IDENTITY_EMAIL:'',GATEWAY_POSTURE_ID:'',BRIDGE_REGISTRY:''}:{ENABLED:'false',GATEWAY_HOST:'private-bridge-smoke.invalid',GATEWAY_ACCOUNT_ID:'',GATEWAY_POLICY_ID:'',START_MS:'',END_MS:''}; - if(!target||target.environment!==environment||target.exists!==true||target.script_id!==worker||target.account_id!==accountId||target.workers_dev!==false||target.preview_urls!==false||!Array.isArray(target.routes)||target.routes.length!==0||!Array.isArray(target.custom_domains)||target.custom_domains.length!==0||target.application_enabled!==false||target.observability?.enabled!==false||target.observability?.logs!==false||target.observability?.traces!==false||target.limits?.cpu_ms!==10||!Array.isArray(target.gateway_forward_policy_ids)||target.gateway_forward_policy_ids.length!==0||!Array.isArray(target.gateway_caller_ids)||target.gateway_caller_ids.length!==0||JSON.stringify(Object.fromEntries(Object.entries(target.variables??{}).sort()))!==JSON.stringify(Object.fromEntries(Object.entries(expectedVars).sort()))||!Array.isArray(target.bindings)) fail('owner read-only proof does not verify the exact private disabled target'); + if(worker==='private-laptop-bridge-staging') { + if(target?.variables?.ACCESS_ISSUER!==accessIssuer||target?.variables?.ACCESS_AUDIENCE!==accessAudience) fail('owner proof Access issuer/audience differ from the protected build configuration'); + if(!validAccess(accessIssuer,accessAudience)) fail('owner proof does not identify a valid exact Access application issuer and audience'); + } + const expectedVars=worker==='private-laptop-bridge-staging'?{ENABLED:'false',GATEWAY_HOST:'private-bridge-staging.invalid',GATEWAY_ACCOUNT_ID:'',GATEWAY_POLICY_ID:'',GATEWAY_IDENTITY_EMAIL:'',GATEWAY_POSTURE_ID:'',BRIDGE_HOST,ACCESS_ISSUER:accessIssuer,ACCESS_AUDIENCE:accessAudience,BRIDGE_REGISTRY:''}:{ENABLED:'false',GATEWAY_HOST:'private-bridge-smoke.invalid',GATEWAY_ACCOUNT_ID:'',GATEWAY_POLICY_ID:'',START_MS:'',END_MS:''}; + const expectedDomains=worker==='private-laptop-bridge-staging'?[BRIDGE_HOST]:[]; + if(!target||target.environment!==environment||target.exists!==true||target.script_id!==worker||target.account_id!==accountId||target.workers_dev!==false||target.preview_urls!==false||!Array.isArray(target.routes)||target.routes.length!==0||!same(target.custom_domains,expectedDomains)||target.application_enabled!==false||target.observability?.enabled!==false||target.observability?.logs!==false||target.observability?.traces!==false||target.limits?.cpu_ms!==10||!Array.isArray(target.gateway_forward_policy_ids)||target.gateway_forward_policy_ids.length!==0||!Array.isArray(target.gateway_caller_ids)||target.gateway_caller_ids.length!==0||JSON.stringify(Object.fromEntries(Object.entries(target.variables??{}).sort()))!==JSON.stringify(Object.fromEntries(Object.entries(expectedVars).sort()))||!Array.isArray(target.bindings)) fail('owner read-only proof does not verify the exact private disabled target'); + if(worker==='private-laptop-bridge-staging') { + const app=target.access_app, clientIds=app?.allowed_client_ids; + const expiryIds=Object.keys(app?.client_expires_at??{}).sort(); + const issuedAt=Date.parse(proof.verified_at), expires=clientIds?.map(id=>Date.parse(app?.client_expires_at?.[id])); + if(!app||typeof app.application_id!=='string'||app.application_id.length<8||app.hostname!==BRIDGE_HOST|| + app.issuer!==accessIssuer||app.audience!==accessAudience||app.enabled!==true||app.mode!=='service-token-only'|| + app.browser_login!==false||app.bypass_policy_count!==0||app.non_service_allow_count!==0|| + !Array.isArray(clientIds)||clientIds.length!==2||clientIds.some(id=>typeof id!=='string'||!/^[A-Za-z0-9._-]{8,128}$/.test(id))||new Set(clientIds).size!==2|| + !same(expiryIds,[...clientIds].sort())||expires.some(value=>!Number.isFinite(value)||value<=now||value>issuedAt+3600000)) { + fail('owner proof does not verify one Access application restricted to the two approved service identities'); + } + } if(worker==='private-laptop-bridge-staging'&&(target.bindings.length!==1||target.bindings[0]?.name!=='BRIDGE'||target.bindings[0]?.type!=='durable_object_namespace'||target.bindings[0]?.class_name!=='PrivateLaptopBridge'||target.bindings[0]?.namespace_id!==target.do?.id||!same(target.declarative_exports,{PrivateLaptopBridge:{state:'created',storage:'sqlite'}})||target.do?.script!==worker||target.do?.class!=='PrivateLaptopBridge'||target.do?.use_sqlite!==true||!NAMESPACE.test(target.do?.id??''))) fail('owner read-only proof does not verify the same-Worker SQLite Durable Object export and namespace'); if(worker==='private-laptop-bridge-smoke'&&(target.bindings.length!==0||target.do!==null)) fail('smoke target unexpectedly has a Durable Object namespace or binding'); return true; @@ -177,14 +200,15 @@ export function assertDryRunPayload(text,{worker,mode}) { return true; } -export function assertEffectivePayload(config,{worker,mode}) { +export function assertEffectivePayload(config,{worker,mode,accessIssuer=process.env.CF_BRIDGE_ACCESS_ISSUER??'',accessAudience=process.env.CF_BRIDGE_ACCESS_AUDIENCE??''}) { const bridge=worker==='private-laptop-bridge-staging'; const smoke=worker==='private-laptop-bridge-smoke'; if((!bridge&&!smoke)||(bridge&&mode!=='bridge')||(smoke&&mode!=='default')) fail('Build Output mode does not match the fixed target'); + if(bridge&&!validAccess(accessIssuer,accessAudience)) fail('bridge Build Output requires the exact protected Access issuer and audience'); const common={ name:worker, compatibilityDate:'2026-07-30', - domains:[], + domains:bridge?[BRIDGE_HOST]:[], triggers:[], limits:{cpuMs:10}, observability:{enabled:false,logs:{enabled:false},traces:{enabled:false}}, @@ -193,7 +217,7 @@ export function assertEffectivePayload(config,{worker,mode}) { }; const variables=bridge?{ ENABLED:'false',GATEWAY_HOST:'private-bridge-staging.invalid',GATEWAY_ACCOUNT_ID:'',GATEWAY_POLICY_ID:'', - GATEWAY_IDENTITY_EMAIL:'',GATEWAY_POSTURE_ID:'',BRIDGE_REGISTRY:'', + GATEWAY_IDENTITY_EMAIL:'',GATEWAY_POSTURE_ID:'',BRIDGE_HOST,ACCESS_ISSUER:accessIssuer,ACCESS_AUDIENCE:accessAudience,BRIDGE_REGISTRY:'', }:{ ENABLED:'false',GATEWAY_HOST:'private-bridge-smoke.invalid',GATEWAY_ACCOUNT_ID:'',GATEWAY_POLICY_ID:'',START_MS:'',END_MS:'', }; diff --git a/pm-stack/private-laptop-bridge/release-contract.test.mjs b/pm-stack/private-laptop-bridge/release-contract.test.mjs index 7454c5bcad..e5dcad9f80 100644 --- a/pm-stack/private-laptop-bridge/release-contract.test.mjs +++ b/pm-stack/private-laptop-bridge/release-contract.test.mjs @@ -2,8 +2,11 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import {readFile} from 'node:fs/promises'; import {createHash} from 'node:crypto'; +import {BRIDGE_HOST} from './access-auth.mjs'; import {assertDeployable,assertDeploymentCreated,assertDryRunPayload,assertEffectivePayload,assertExactVersion,assertLatestServing,assertPreflight,assertUploadRun,assertVersionStillMatches,makeHandoff,provenanceDigest,verifyPromotionProvenance} from './release-contract.mjs'; +const accessConfig={accessIssuer:'https://team.cloudflareaccess.com',accessAudience:'audience-with-exact-length-012345'}; +const accessApp={application_id:'synthetic-app-id-123',hostname:'laptop-bridge-staging.security.cab',issuer:accessConfig.accessIssuer,audience:accessConfig.accessAudience,enabled:true,mode:'service-token-only',browser_login:false,bypass_policy_count:0,non_service_allow_count:0,allowed_client_ids:['aster-client-123','amd-client-123'],client_expires_at:{'aster-client-123':'2026-11-22T12:30:00Z','amd-client-123':'2026-11-22T12:30:00Z'}}; const uuid='01234567-89ab-cdef-0123-456789abcdef', old='11111111-2222-3333-4444-555555555555'; const sha='a'.repeat(40), cd='b'.repeat(64), bd='c'.repeat(64), pd='e'.repeat(64), acct='d'.repeat(32); const proof=provenanceDigest({worker:'private-laptop-bridge-staging',sourceSha:sha,configDigest:cd,buildDigest:bd,preflightDigest:pd}); @@ -84,17 +87,22 @@ test('deployment create response must return the exact 100 percent deployment id test('read-only owner proof fails closed for missing, stale, public or unexpected callers',()=>{ const now=Date.parse('2026-11-22T12:00:00Z'); - const good={schema:1,verified:true,account_id:acct,verified_at:'2026-11-22T11:00:00Z',expires_at:'2026-11-22T13:00:00Z',evidence_ref:'review-1',release_policy:{repository:'developing-today/code',branch:'main',branch_protected:true,required_pull_request_reviews:true,force_push_disabled:true,admin_bypass_disabled:true,environment_reviewers_required:{'cloudflare-staging':true,'cloudflare-staging-smoke':true},self_review_disabled:{'cloudflare-staging':true,'cloudflare-staging-smoke':true},allowed_environment_branches:{'cloudflare-staging':['main'],'cloudflare-staging-smoke':['main']},evidence_ref:'policy-review-1'},targets:{'private-laptop-bridge-staging':{environment:'cloudflare-staging',exists:true,script_id:'private-laptop-bridge-staging',account_id:acct,application_enabled:false,workers_dev:false,preview_urls:false,routes:[],custom_domains:[],observability:{enabled:false,logs:false,traces:false},limits:{cpu_ms:10},gateway_forward_policy_ids:[],gateway_caller_ids:[],variables:{ENABLED:'false',GATEWAY_HOST:'private-bridge-staging.invalid',GATEWAY_ACCOUNT_ID:'',GATEWAY_POLICY_ID:'',GATEWAY_IDENTITY_EMAIL:'',GATEWAY_POSTURE_ID:'',BRIDGE_REGISTRY:''},bindings:[{name:'BRIDGE',type:'durable_object_namespace',class_name:'PrivateLaptopBridge',namespace_id:'1'.repeat(32)}],declarative_exports:{PrivateLaptopBridge:{state:'created',storage:'sqlite'}},do:{id:'1'.repeat(32),class:'PrivateLaptopBridge',script:'private-laptop-bridge-staging',use_sqlite:true}}}}; - assert.equal(assertPreflight(good,{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now}),true); - assert.throws(()=>assertPreflight({...good,verified:false},{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now}),/absent, expired, or invalid/); - assert.throws(()=>assertPreflight({...good,expires_at:'2026-11-22T11:59:59Z'},{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now}),/absent, expired, or invalid/); - assert.throws(()=>assertPreflight({...good,evidence_ref:''},{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now}),/absent, expired, or invalid/); - assert.throws(()=>assertPreflight({...good,release_policy:{...good.release_policy,branch_protected:false}},{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now}),/protected-main/); - assert.throws(()=>assertPreflight({...good,release_policy:{...good.release_policy,environment_reviewers_required:{'cloudflare-staging':false}}},{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now}),/protected-main/); + const good={schema:1,verified:true,account_id:acct,verified_at:'2026-11-22T11:30:00Z',expires_at:'2026-11-22T13:00:00Z',evidence_ref:'review-1',release_policy:{repository:'developing-today/code',branch:'main',branch_protected:true,required_pull_request_reviews:true,force_push_disabled:true,admin_bypass_disabled:true,environment_reviewers_required:{'cloudflare-staging':true,'cloudflare-staging-smoke':true},self_review_disabled:{'cloudflare-staging':true,'cloudflare-staging-smoke':true},allowed_environment_branches:{'cloudflare-staging':['main'],'cloudflare-staging-smoke':['main']},evidence_ref:'policy-review-1'},targets:{'private-laptop-bridge-staging':{environment:'cloudflare-staging',exists:true,script_id:'private-laptop-bridge-staging',account_id:acct,application_enabled:false,workers_dev:false,preview_urls:false,routes:[],custom_domains:[BRIDGE_HOST],access_app:accessApp,observability:{enabled:false,logs:false,traces:false},limits:{cpu_ms:10},gateway_forward_policy_ids:[],gateway_caller_ids:[],variables:{ENABLED:'false',GATEWAY_HOST:'private-bridge-staging.invalid',GATEWAY_ACCOUNT_ID:'',GATEWAY_POLICY_ID:'',GATEWAY_IDENTITY_EMAIL:'',GATEWAY_POSTURE_ID:'',BRIDGE_HOST,ACCESS_ISSUER:'https://team.cloudflareaccess.com',ACCESS_AUDIENCE:'audience-with-exact-length-012345',BRIDGE_REGISTRY:''},bindings:[{name:'BRIDGE',type:'durable_object_namespace',class_name:'PrivateLaptopBridge',namespace_id:'1'.repeat(32)}],declarative_exports:{PrivateLaptopBridge:{state:'created',storage:'sqlite'}},do:{id:'1'.repeat(32),class:'PrivateLaptopBridge',script:'private-laptop-bridge-staging',use_sqlite:true}}}}; + assert.equal(assertPreflight(good,{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now,...accessConfig}),true); + assert.throws(()=>assertPreflight(good,{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now,accessIssuer:'',accessAudience:''}),/differ from the protected build configuration/); + assert.throws(()=>assertPreflight({...good,verified:false},{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now,...accessConfig}),/absent, expired, or invalid/); + assert.throws(()=>assertPreflight({...good,expires_at:'2026-11-22T11:59:59Z'},{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now,...accessConfig}),/absent, expired, or invalid/); + assert.throws(()=>assertPreflight({...good,evidence_ref:''},{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now,...accessConfig}),/absent, expired, or invalid/); + assert.throws(()=>assertPreflight({...good,release_policy:{...good.release_policy,branch_protected:false}},{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now,...accessConfig}),/protected-main/); + assert.throws(()=>assertPreflight({...good,release_policy:{...good.release_policy,environment_reviewers_required:{'cloudflare-staging':false}}},{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now,...accessConfig}),/protected-main/); for(const change of [ {gateway_caller_ids:['unexpected-caller']}, {routes:['https://public.example/*']}, {custom_domains:['public.example']}, + {access_app:{...accessApp,bypass_policy_count:1}}, + {access_app:{...accessApp,allowed_client_ids:['aster-client-123']}}, + {access_app:{...accessApp,allowed_client_ids:['aster-client-123','aster-client-123']}}, + {access_app:{...accessApp,client_expires_at:{...accessApp.client_expires_at,'amd-client-123':'2026-11-22T13:00:00Z'}}}, {workers_dev:true}, {preview_urls:true}, {gateway_forward_policy_ids:['unexpected-policy']}, @@ -112,7 +120,7 @@ test('read-only owner proof fails closed for missing, stale, public or unexpecte {declarative_exports:{PrivateLaptopBridge:{state:'created',storage:'sqlite'},Unexpected:{state:'created',storage:'sqlite'}}}, ]) { const target={...good.targets['private-laptop-bridge-staging'],...change}; - assert.throws(()=>assertPreflight({...good,targets:{...good.targets,'private-laptop-bridge-staging':target}},{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now})); + assert.throws(()=>assertPreflight({...good,targets:{...good.targets,'private-laptop-bridge-staging':target}},{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now,...accessConfig})); } const smokeTarget={environment:'cloudflare-staging-smoke',exists:true,script_id:'private-laptop-bridge-smoke',account_id:acct,application_enabled:false,workers_dev:false,preview_urls:false,routes:[],custom_domains:[],observability:{enabled:false,logs:false,traces:false},limits:{cpu_ms:10},gateway_forward_policy_ids:[],gateway_caller_ids:[],variables:{ENABLED:'false',GATEWAY_HOST:'private-bridge-smoke.invalid',GATEWAY_ACCOUNT_ID:'',GATEWAY_POLICY_ID:'',START_MS:'',END_MS:''},bindings:[],do:null}; assert.equal(assertPreflight({...good,targets:{'private-laptop-bridge-smoke':smokeTarget}},{accountId:acct,worker:'private-laptop-bridge-smoke',environment:'cloudflare-staging-smoke',now}),true); @@ -121,9 +129,9 @@ test('read-only owner proof fails closed for missing, stale, public or unexpecte test('Versions release proof separately requires an existing Worker and its ready same-Worker DO namespace',()=>{ const now=Date.parse('2026-11-22T12:00:00Z'); const policy={repository:'developing-today/code',branch:'main',branch_protected:true,required_pull_request_reviews:true,force_push_disabled:true,admin_bypass_disabled:true,environment_reviewers_required:{'cloudflare-staging':true},self_review_disabled:{'cloudflare-staging':true},allowed_environment_branches:{'cloudflare-staging':['main']},evidence_ref:'policy-review-1'}; - const bridge={environment:'cloudflare-staging',exists:true,script_id:'private-laptop-bridge-staging',account_id:acct,application_enabled:false,workers_dev:false,preview_urls:false,routes:[],custom_domains:[],observability:{enabled:false,logs:false,traces:false},limits:{cpu_ms:10},gateway_forward_policy_ids:[],gateway_caller_ids:[],variables:{ENABLED:'false',GATEWAY_HOST:'private-bridge-staging.invalid',GATEWAY_ACCOUNT_ID:'',GATEWAY_POLICY_ID:'',GATEWAY_IDENTITY_EMAIL:'',GATEWAY_POSTURE_ID:'',BRIDGE_REGISTRY:''},bindings:[{name:'BRIDGE',type:'durable_object_namespace',class_name:'PrivateLaptopBridge',namespace_id:'1'.repeat(32)}],declarative_exports:{PrivateLaptopBridge:{state:'created',storage:'sqlite'}},do:{id:'1'.repeat(32),class:'PrivateLaptopBridge',script:'private-laptop-bridge-staging',use_sqlite:true}}; - const makeProof=(target=bridge)=>({schema:1,verified:true,account_id:acct,verified_at:'2026-11-22T11:00:00Z',expires_at:'2026-11-22T13:00:00Z',evidence_ref:'worker-review-1',release_policy:policy,targets:{'private-laptop-bridge-staging':target}}); - const check=(proof)=>assertPreflight(proof,{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now}); + const bridge={environment:'cloudflare-staging',exists:true,script_id:'private-laptop-bridge-staging',account_id:acct,application_enabled:false,workers_dev:false,preview_urls:false,routes:[],custom_domains:[BRIDGE_HOST],access_app:accessApp,observability:{enabled:false,logs:false,traces:false},limits:{cpu_ms:10},gateway_forward_policy_ids:[],gateway_caller_ids:[],variables:{ENABLED:'false',GATEWAY_HOST:'private-bridge-staging.invalid',GATEWAY_ACCOUNT_ID:'',GATEWAY_POLICY_ID:'',GATEWAY_IDENTITY_EMAIL:'',GATEWAY_POSTURE_ID:'',BRIDGE_HOST,ACCESS_ISSUER:'https://team.cloudflareaccess.com',ACCESS_AUDIENCE:'audience-with-exact-length-012345',BRIDGE_REGISTRY:''},bindings:[{name:'BRIDGE',type:'durable_object_namespace',class_name:'PrivateLaptopBridge',namespace_id:'1'.repeat(32)}],declarative_exports:{PrivateLaptopBridge:{state:'created',storage:'sqlite'}},do:{id:'1'.repeat(32),class:'PrivateLaptopBridge',script:'private-laptop-bridge-staging',use_sqlite:true}}; + const makeProof=(target=bridge)=>({schema:1,verified:true,account_id:acct,verified_at:'2026-11-22T11:30:00Z',expires_at:'2026-11-22T13:00:00Z',evidence_ref:'worker-review-1',release_policy:policy,targets:{'private-laptop-bridge-staging':target}}); + const check=(proof)=>assertPreflight(proof,{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now,...accessConfig}); assert.equal(check(makeProof()),true); assert.throws(()=>check(makeProof({...bridge,exists:false})),/exact private disabled target/); for(const change of [ @@ -161,10 +169,12 @@ test('CI dry-run verifies the effective private Build Output but does not claim }); test('effective Build Output explicitly fixes CPU, observability, routes, preview, flags, variables and resource bindings',()=>{ - const base={name:'private-laptop-bridge-staging',compatibilityDate:'2026-07-30',domains:[],triggers:[],limits:{cpuMs:10},observability:{enabled:false,logs:{enabled:false},traces:{enabled:false}},workersDev:false,previewUrls:false,env:{ENABLED:{type:'text',value:'false'},GATEWAY_HOST:{type:'text',value:'private-bridge-staging.invalid'},GATEWAY_ACCOUNT_ID:{type:'text',value:''},GATEWAY_POLICY_ID:{type:'text',value:''},GATEWAY_IDENTITY_EMAIL:{type:'text',value:''},GATEWAY_POSTURE_ID:{type:'text',value:''},BRIDGE_REGISTRY:{type:'text',value:''},BRIDGE:{type:'durable-object',worker:'private-laptop-bridge-staging',exportName:'PrivateLaptopBridge'}},exports:{PrivateLaptopBridge:{type:'durable-object',storage:'sqlite'}},manifest:{type:'complete',mainModule:'gateway.js',modules:{'gateway.js':{type:'esm'},'gateway.js.map':{type:'sourcemap'}}}}; - assert.equal(assertEffectivePayload(base,{worker:'private-laptop-bridge-staging',mode:'bridge'}),true); + const base={name:'private-laptop-bridge-staging',compatibilityDate:'2026-07-30',domains:[BRIDGE_HOST],triggers:[],limits:{cpuMs:10},observability:{enabled:false,logs:{enabled:false},traces:{enabled:false}},workersDev:false,previewUrls:false,env:{ENABLED:{type:'text',value:'false'},GATEWAY_HOST:{type:'text',value:'private-bridge-staging.invalid'},GATEWAY_ACCOUNT_ID:{type:'text',value:''},GATEWAY_POLICY_ID:{type:'text',value:''},GATEWAY_IDENTITY_EMAIL:{type:'text',value:''},GATEWAY_POSTURE_ID:{type:'text',value:''},BRIDGE_HOST:{type:'text',value:BRIDGE_HOST},ACCESS_ISSUER:{type:'text',value:'https://team.cloudflareaccess.com'},ACCESS_AUDIENCE:{type:'text',value:'audience-with-exact-length-012345'},BRIDGE_REGISTRY:{type:'text',value:''},BRIDGE:{type:'durable-object',worker:'private-laptop-bridge-staging',exportName:'PrivateLaptopBridge'}},exports:{PrivateLaptopBridge:{type:'durable-object',storage:'sqlite'}},manifest:{type:'complete',mainModule:'gateway.js',modules:{'gateway.js':{type:'esm'},'gateway.js.map':{type:'sourcemap'}}}}; + const bridgeArgs={worker:'private-laptop-bridge-staging',mode:'bridge',accessIssuer:'https://team.cloudflareaccess.com',accessAudience:'audience-with-exact-length-012345'}; + assert.equal(assertEffectivePayload(base,bridgeArgs),true); + assert.throws(()=>assertEffectivePayload(base,{...bridgeArgs,accessIssuer:'',accessAudience:''}),/requires the exact protected Access issuer and audience/); for(const mutation of [x=>x.limits.cpuMs=30,x=>x.observability.enabled=true,x=>x.workersDev=true,x=>x.previewUrls=true,x=>x.domains.push('public.example'),x=>x.triggers.push({route:'public.example/*'}),x=>x.env.ENABLED.value='true',x=>x.env.EXTRA={type:'text',value:'secret'},x=>x.env.BRIDGE.worker='other-worker',x=>x.exports.PrivateLaptopBridge.storage='kv',x=>x.forwardPolicies=['unexpected']]) { - const mutated=structuredClone(base); mutation(mutated); assert.throws(()=>assertEffectivePayload(mutated,{worker:'private-laptop-bridge-staging',mode:'bridge'})); + const mutated=structuredClone(base); mutation(mutated); assert.throws(()=>assertEffectivePayload(mutated,bridgeArgs)); } const smoke={name:'private-laptop-bridge-smoke',compatibilityDate:'2026-07-30',domains:[],triggers:[],limits:{cpuMs:10},observability:{enabled:false,logs:{enabled:false},traces:{enabled:false}},workersDev:false,previewUrls:false,env:{ENABLED:{type:'text',value:'false'},GATEWAY_HOST:{type:'text',value:'private-bridge-smoke.invalid'},GATEWAY_ACCOUNT_ID:{type:'text',value:''},GATEWAY_POLICY_ID:{type:'text',value:''},START_MS:{type:'text',value:''},END_MS:{type:'text',value:''}},manifest:{type:'complete',mainModule:'smoke.js',modules:{'smoke.js':{type:'esm'},'smoke.js.map':{type:'sourcemap'}}}}; assert.equal(assertEffectivePayload(smoke,{worker:'private-laptop-bridge-smoke',mode:'default'}),true); diff --git a/pm-stack/private-laptop-bridge/review.test.mjs b/pm-stack/private-laptop-bridge/review.test.mjs index fc0d2ba96e..507ef3440b 100644 --- a/pm-stack/private-laptop-bridge/review.test.mjs +++ b/pm-stack/private-laptop-bridge/review.test.mjs @@ -7,7 +7,7 @@ import {b64url,boundedText} from './protocol.mjs'; const NOW=1800000000000; const keys={caller:await crypto.subtle.generateKey('Ed25519',true,['sign','verify']),device:await crypto.subtle.generateKey('Ed25519',true,['sign','verify'])}; -const origin='https://bridge.invalid',audience='review-test'; +const origin='https://laptop-bridge-staging.security.cab',audience='review-test'; const result={ok:true,data:{queueBroker:'up'}}; class Storage { value; @@ -17,12 +17,12 @@ async function harness(t,offset=0) { let clock=NOW; t.mock.method(Date,'now',()=>clock); const principals=[]; - for(const [id,role] of [['caller','caller'],['device','device']])principals.push({id,role,device:'amd',publicKey:b64url(await crypto.subtle.exportKey('raw',keys[id].publicKey)),scopes:['laptop.health'],issuedAt:NOW-60000,expiresAt:NOW+1800000,revoked:false}); + for(const [id,role] of [['caller','caller'],['device','device']])principals.push({id,role,device:'amd',publicKey:b64url(await crypto.subtle.exportKey('raw',keys[id].publicKey)),accessClientId:`synthetic-${id}-client`,scopes:['laptop.health'],issuedAt:NOW-60000,expiresAt:NOW+1800000,revoked:false}); const env={ENABLED:'true',BRIDGE_REGISTRY:JSON.stringify({audience,principals})}; const object=new PrivateLaptopBridge({storage:new Storage()},env); env.BRIDGE={idFromName:x=>x,get:()=>({fetch:req=>object.fetch(req)})}; - const dispatch=req=>worker.fetch(req,env); - const config={origin,audience,now:()=>clock-offset,fetch:dispatch}; + const dispatch=req=>object.fetch(req); + const config={origin,audience,now:()=>clock-offset,fetch:dispatch,accessClientId:'synthetic-client-id',accessClientSecret:'synthetic-access-secret-that-is-never-live'}; const caller=createCaller({...config,principal:'caller',device:'amd',privateKey:keys.caller.privateKey}); const deviceConfig={...config,principal:'device',privateKey:keys.device.privateKey,getuid:()=>1000,execute:async()=>result}; return {caller,deviceConfig,dispatch,advance:ms=>{clock+=ms;},localNow:()=>clock-offset}; @@ -51,7 +51,7 @@ for(const offset of [-29000,29000])test(`deadline oracle: actual lease expiratio test('deadline oracle: delayed call acknowledgement is never exposed as a fresh handle',async t=>{ const h=await harness(t,500); - const caller=createCaller({origin,audience,principal:'caller',device:'amd',privateKey:keys.caller.privateKey,now:h.localNow,fetch:async request=>{const response=await h.dispatch(request);h.advance(60000);return response;}}); + const caller=createCaller({origin,audience,principal:'caller',device:'amd',privateKey:keys.caller.privateKey,accessClientId:'synthetic-client-id',accessClientSecret:'synthetic-access-secret-that-is-never-live',now:h.localNow,fetch:async request=>{const response=await h.dispatch(request);h.advance(60000);return response;}}); await assert.rejects(caller.laptopHealth(),{code:'submit-outcome-unknown'}); }); @@ -59,17 +59,17 @@ test('schema oracle: inconsistent server deadlines and excessive skew are reject const base={id:'job',lease:'lease',operation:'laptop.health',args:{},serverNow:NOW,expiresAt:NOW+60000,leaseExpiresAt:NOW+15000}; const bad=[{...base,serverNow:NOW+30001},{...base,serverNow:NOW-30001},{...base,expiresAt:NOW+60001},{...base,leaseExpiresAt:NOW+15001},{...base,leaseExpiresAt:NOW},{...base,expiresAt:NOW+1000,leaseExpiresAt:NOW+2000},{...base,serverNow:undefined}]; let executed=0; - for(const job of bad){const client=createClient({origin,audience,principal:'device',privateKey:keys.device.privateKey,now:()=>NOW,getuid:()=>1000,execute:async()=>{executed++;return result;},fetch:async()=>Response.json({job})});await assert.rejects(client.step(),/invalid-job/);} + for(const job of bad){const client=createClient({origin,audience,principal:'device',privateKey:keys.device.privateKey,accessClientId:'synthetic-client-id',accessClientSecret:'synthetic-access-secret-that-is-never-live',now:()=>NOW,getuid:()=>1000,execute:async()=>{executed++;return result;},fetch:async()=>Response.json({job})});await assert.rejects(client.step(),/invalid-job/);} assert.equal(executed,0); for(const body of [{id:'job',serverNow:NOW+30001,expiresAt:NOW+60000},{id:'job',serverNow:NOW,expiresAt:NOW+60001},{id:'job',expiresAt:NOW+60000}]){ - const caller=createCaller({origin,audience,principal:'caller',device:'amd',privateKey:keys.caller.privateKey,now:()=>NOW,fetch:async()=>Response.json(body,{status:202})}); + const caller=createCaller({origin,audience,principal:'caller',device:'amd',privateKey:keys.caller.privateKey,accessClientId:'synthetic-client-id',accessClientSecret:'synthetic-access-secret-that-is-never-live',now:()=>NOW,fetch:async()=>Response.json(body,{status:202})}); await assert.rejects(caller.laptopHealth(),{code:'submit-outcome-unknown'}); } }); test('cleanup oracle: denial is immediate even when stream cancellation stalls or rejects',async()=>{ for(const status of [401,403,410,503])for(const cancel of [()=>new Promise(()=>{}),()=>Promise.reject(new Error('private cancellation detail'))]){ - const client=createClient({origin,audience,principal:'device',privateKey:keys.device.privateKey,getuid:()=>1000,requestTimeoutMs:5,fetch:async()=>new Response(new ReadableStream({cancel}),{status})}); + const client=createClient({origin,audience,principal:'device',privateKey:keys.device.privateKey,accessClientId:'synthetic-client-id',accessClientSecret:'synthetic-access-secret-that-is-never-live',getuid:()=>1000,requestTimeoutMs:5,fetch:async()=>new Response(new ReadableStream({cancel}),{status})}); let timer; try { const got=await Promise.race([client.step().then(()=>null,error=>error),new Promise(resolve=>{timer=setTimeout(()=>resolve('stalled'),100);})]); diff --git a/pm-stack/private-laptop-bridge/runtime-test-entry.mjs b/pm-stack/private-laptop-bridge/runtime-test-entry.mjs new file mode 100644 index 0000000000..426cd8adf8 --- /dev/null +++ b/pm-stack/private-laptop-bridge/runtime-test-entry.mjs @@ -0,0 +1,9 @@ +// Test-only Miniflare entrypoint: exercises the real SQLite DO and its signed +// protocol without simulating Cloudflare Access. Production config points at +// gateway.mjs, whose default path validates Access before invoking the DO. +export {PrivateLaptopBridge} from './worker.mjs'; +export default { + fetch(request, env) { + return env.BRIDGE.get(env.BRIDGE.idFromName('owner-v1')).fetch(request); + }, +}; diff --git a/pm-stack/private-laptop-bridge/runtime.test.mjs b/pm-stack/private-laptop-bridge/runtime.test.mjs index 881bd8cb6c..fdb0f9a79d 100644 --- a/pm-stack/private-laptop-bridge/runtime.test.mjs +++ b/pm-stack/private-laptop-bridge/runtime.test.mjs @@ -15,8 +15,9 @@ const here = dirname(fileURLToPath(import.meta.url)); const source = here; const clientSource = here; const { signRequest, b64url, operations } = await import(pathToFileURL(join(source, 'protocol.mjs'))); -const origin = 'https://private-bridge.invalid'; +const origin = 'https://laptop-bridge-staging.security.cab'; const audience = 'offline-acceptance'; +const testAccess = {accessClientId:'synthetic-client-id',accessClientSecret:'synthetic-access-secret-that-is-never-live'}; const result = { ok: true, data: { queueBroker: 'up' } }; async function harness(t) { @@ -26,7 +27,7 @@ async function harness(t) { const now = Date.now(); for (const [id, role, device] of [['caller','caller','amd'], ['other','caller','amd'], ['device','device','amd'], ['wrong-device','device','other']]) { keys[id] = await crypto.subtle.generateKey('Ed25519', true, ['sign','verify']); - principals.push({ id, role, device, publicKey: b64url(await crypto.subtle.exportKey('raw', keys[id].publicKey)), scopes: [...operations], issuedAt: now - 1000, expiresAt: now + 120000, revoked: false }); + principals.push({ id, role, device, publicKey: b64url(await crypto.subtle.exportKey('raw', keys[id].publicKey)), accessClientId:`access-${id}-client`, scopes: [...operations], issuedAt: now - 1000, expiresAt: now + 120000, revoked: false }); } const registry = { audience, principals }; let mf; @@ -34,7 +35,7 @@ async function harness(t) { name: 'private-laptop-bridge-offline', host: '127.0.0.1', modules: true, - scriptPath: join(source, 'worker.mjs'), + scriptPath: join(source, 'runtime-test-entry.mjs'), modulesRules: [{ type: 'ESModule', include: ['**/*.mjs'] }], compatibilityDate: '2026-07-30', bindings: { ENABLED: 'true', BRIDGE_REGISTRY: JSON.stringify(registry) }, @@ -209,11 +210,11 @@ test('workerd: actual non-root laptop client completes each named read through W }; const seen = []; const adapters = createAdapters({ readSnapshot: () => readQueueSnapshot(home), probe: () => queueBrokerAlive(home), diagnostics: () => samples['laptop.diagnostics'].data }); - const client = createClient({ origin, audience, principal: 'device', privateKey: h.keys.device.privateKey, getuid: () => 1000, + const client = createClient({ origin, audience, principal: 'device', privateKey: h.keys.device.privateKey, accessClientId:'access-device-client',accessClientSecret:'synthetic-runtime-access-secret-never-live',getuid: () => 1000, fetch: async (request, init) => { assert.equal(init.redirect, 'error'); return h.dispatch(request); }, execute: async (operation, args) => { seen.push({ operation, args }); return adapters(operation, args); }, }); - const caller = createCaller({ origin, audience, principal: 'caller', device: 'amd', privateKey: h.keys.caller.privateKey, fetch: request => h.dispatch(request) }); + const caller = createCaller({ origin, audience, principal: 'caller', device: 'amd', privateKey: h.keys.caller.privateKey, accessClientId:'access-caller-client',accessClientSecret:'synthetic-runtime-access-secret-never-live',fetch: request => h.dispatch(request) }); const methods = { 'fleet.queue.list': 'fleetQueueList', 'fleet.queue.health': 'fleetQueueHealth', 'laptop.health': 'laptopHealth', 'laptop.diagnostics': 'laptopDiagnostics' }; for (const operation of operations) { const args = operation === 'fleet.queue.list' ? { limit: 1, status: 'queued' } : {}; @@ -229,7 +230,7 @@ test('workerd: actual non-root laptop client completes each named read through W test('caller SDK: validates before I/O and never retries uncertain submissions', async () => { const { createCaller, CallerError } = await import('./caller.mjs'); const keys = await crypto.subtle.generateKey('Ed25519', true, ['sign','verify']); - const base = { origin, audience, principal: 'caller', device: 'amd', privateKey: keys.privateKey }; + const base = { origin, audience, principal: 'caller', device: 'amd', privateKey: keys.privateKey, ...testAccess }; assert.throws(() => createCaller({ ...base, origin: 'http://localhost' }), /invalid-config/); let calls = 0; const caller = createCaller({ ...base, fetch: async () => { calls++; throw new Error('secret-bearing transport detail'); } }); @@ -246,7 +247,7 @@ test('caller SDK: uncertain reads preserve accepted handle and malformed results const keys = await crypto.subtle.generateKey('Ed25519', true, ['sign','verify']); const handle = { id: 'test-id', operation: 'laptop.health', expiresAt: Date.now() + 60000, args: {} }; let mode = 'failed'; - const caller = createCaller({ origin, audience, principal: 'caller', device: 'amd', privateKey: keys.privateKey, + const caller = createCaller({ origin, audience, principal: 'caller', device: 'amd', privateKey: keys.privateKey,...testAccess, fetch: async () => { if (mode === 'failed') throw new Error('private stack trace'); if (mode === 'extra') return Response.json({ status: 'complete', result: { ok: true, data: { queueBroker: 'up', raw: 'forbidden' } } }); @@ -264,7 +265,7 @@ test('caller SDK: uncertain reads preserve accepted handle and malformed results test('caller SDK: transport and streamed response deadlines are bounded', async () => { const { createCaller } = await import('./caller.mjs'); const keys = await crypto.subtle.generateKey('Ed25519', true, ['sign','verify']); - const base = { origin, audience, principal: 'caller', device: 'amd', privateKey: keys.privateKey, requestTimeoutMs: 30 }; + const base = { origin, audience, principal: 'caller', device: 'amd', privateKey: keys.privateKey, ...testAccess,requestTimeoutMs: 30 }; const silent = createCaller({ ...base, fetch: async () => new Promise(() => {}) }); await assert.rejects(silent.laptopHealth(), { code: 'submit-outcome-unknown' }); let cancelled = false; diff --git a/pm-stack/private-laptop-bridge/staging-bootstrap.mjs b/pm-stack/private-laptop-bridge/staging-bootstrap.mjs index f6f1d24d3c..d39680e38c 100644 --- a/pm-stack/private-laptop-bridge/staging-bootstrap.mjs +++ b/pm-stack/private-laptop-bridge/staging-bootstrap.mjs @@ -8,9 +8,13 @@ import {assertEffectivePayload} from './release-contract.mjs'; export const CLOUDFLARE_API = 'https://api.cloudflare.com/client/v4'; export const GITHUB_REPOSITORY = 'developing-today/code'; -export const ENVIRONMENT_NAME = 'cloudflare-staging-bootstrap'; +export const RELEASE_ENVIRONMENT = 'cloudflare-staging'; +export const BOOTSTRAP_ENVIRONMENT = RELEASE_ENVIRONMENT; +export const ENVIRONMENT_NAME = BOOTSTRAP_ENVIRONMENT; export const WORKER_NAME = 'private-laptop-bridge-staging'; export const DO_CLASS = 'PrivateLaptopBridge'; +export const BOOTSTRAP_WORKER_ID_VARIABLE = 'CF_BRIDGE_WORKER_ID'; +export const BRIDGE_HOST = 'laptop-bridge-staging.security.cab'; const PAGE_SIZE = 100; const ZONE_PAGE_SIZE = 50; const HASH = /^[a-f0-9]{64}$/; @@ -28,29 +32,42 @@ function parseIds(value, label) { return normalized; } -function parseReviewerIds(value) { - let ids; - try { ids = typeof value === 'string' ? JSON.parse(value) : value; } +function parseReviewerIdentities(value) { + let reviewers; + try { reviewers = typeof value === 'string' ? JSON.parse(value) : value; } catch { fail('expected independent reviewer IDs are invalid'); } - if (!Array.isArray(ids) || ids.length === 0 || ids.some(id => !(Number.isInteger(id) && id > 0) && !(typeof id === 'string' && /^[1-9][0-9]{0,19}$/.test(id)))) { - fail('expected independent reviewer IDs are missing or invalid'); + if (!Array.isArray(reviewers) || reviewers.length === 0 || reviewers.some(item => + !item || !['User', 'Team'].includes(item.type) || !Number.isSafeInteger(item.id) || item.id <= 0)) { + fail('expected typed independent reviewer IDs are missing or invalid'); } - const normalized = ids.map(String).sort(); - if (new Set(normalized).size !== normalized.length) fail('expected independent reviewer IDs contain duplicates'); + const normalized = reviewers.map(item => `${item.type}:${item.id}`).sort(); + if (new Set(normalized).size !== normalized.length) fail('expected typed independent reviewer IDs contain duplicates'); return normalized; } -export function verifyEnvironmentProtection({environment, branchPolicies, expectedReviewerIds}) { - if (!environment || environment.name !== ENVIRONMENT_NAME || !Array.isArray(environment.protection_rules)) { +export function verifyEnvironmentProtection({environment, branchPolicies, expectedReviewerIds, expectedEnvironmentName = ENVIRONMENT_NAME, dispatcherId}) { + if (!environment || environment.name !== expectedEnvironmentName || !Array.isArray(environment.protection_rules)) { fail('the exact protected staging environment is absent or unverifiable'); } - const expected = parseReviewerIds(expectedReviewerIds); + if (environment.can_admins_bypass !== false) fail('environment API did not prove administrator bypass is disabled'); + const expected = parseReviewerIdentities(expectedReviewerIds); + if (!Number.isSafeInteger(dispatcherId) || dispatcherId <= 0) fail('workflow dispatcher identity is unavailable'); + if (expected.length === 1 && expected[0] === `User:${dispatcherId}`) { + fail('the workflow dispatcher is the only eligible environment reviewer'); + } const rules = environment.protection_rules; const reviewers = rules.filter(rule => rule?.type === 'required_reviewers'); if (reviewers.length !== 1 || reviewers[0].prevent_self_review !== true || !Array.isArray(reviewers[0].reviewers)) { fail('staging environment reviewer protection is absent or allows self-review'); } - const actual = reviewers[0].reviewers.map(item => item?.reviewer?.id).filter(Number.isInteger).map(String).sort(); + const actual = reviewers[0].reviewers.map(item => { + const type = item?.type; + const id = item?.reviewer?.id; + if (!['User', 'Team'].includes(type) || !Number.isSafeInteger(id) || id <= 0) { + fail('environment API did not return typed reviewer identities'); + } + return `${type}:${id}`; + }).sort(); if (actual.length !== expected.length || actual.some((id, index) => id !== expected[index])) { fail('staging environment reviewers do not match the independently approved set'); } @@ -59,10 +76,11 @@ export function verifyEnvironmentProtection({environment, branchPolicies, expect fail('staging environment is not restricted by an explicit branch policy'); } const rows = branchPolicies?.branch_policies; - if (!Array.isArray(rows) || branchPolicies.total_count !== rows.length || rows.length !== 1 || rows[0]?.name !== 'main') { - fail('staging environment deployment policy must allow only main'); + if (!Array.isArray(rows) || branchPolicies.total_count !== rows.length || rows.length !== 1 || + rows[0]?.name !== 'main' || rows[0]?.type !== 'branch') { + fail('staging environment API must prove exactly one branch-only main deployment rule'); } - return {environment: ENVIRONMENT_NAME}; + return {environment: expectedEnvironmentName}; } async function apiRequest(fetchImpl, url, token) { @@ -175,17 +193,22 @@ async function readRoutes(fetchImpl, accountId, token, zones) { return routes; } -function verifyVersion(version, namespaceId) { - if (!version || !Array.isArray(version.resources?.bindings) || !version.exports || typeof version.exports !== 'object') { - fail('deployed Worker version lacks independently readable bindings or declarative exports'); +function verifyVersion(version, namespaceId, expectedVersionId) { + if (!version || version.id !== expectedVersionId || !Array.isArray(version.bindings) || !version.env || + typeof version.env !== 'object' || Array.isArray(version.env) || !version.exports || + typeof version.exports !== 'object' || !Array.isArray(version.urls)) { + fail('exact Beta Worker version lacks its documented ID, bindings, env, exports, or URL fields'); } const expectedVars = { ENABLED: 'false', GATEWAY_HOST: 'private-bridge-staging.invalid', GATEWAY_ACCOUNT_ID: '', - GATEWAY_POLICY_ID: '', GATEWAY_IDENTITY_EMAIL: '', GATEWAY_POSTURE_ID: '', BRIDGE_REGISTRY: '', + GATEWAY_POLICY_ID: '', GATEWAY_IDENTITY_EMAIL: '', GATEWAY_POSTURE_ID: '', + BRIDGE_HOST, ACCESS_ISSUER: process.env.CF_BRIDGE_ACCESS_ISSUER ?? '', + ACCESS_AUDIENCE: process.env.CF_BRIDGE_ACCESS_AUDIENCE ?? '', BRIDGE_REGISTRY: '', }; - const bindings = version.resources.bindings; - const vars = bindings.filter(binding => binding?.type === 'plain_text'); - const actualVars = Object.fromEntries(vars.map(binding => [binding.name, binding.text ?? binding.value])); + const bindings = version.bindings; + if (bindings.some(binding => !binding || typeof binding.name !== 'string') || + new Set(bindings.map(binding => binding.name)).size !== bindings.length) fail('Beta version bindings are malformed or duplicated'); + const actualVars = Object.fromEntries(bindings.filter(binding => binding?.type === 'plain_text').map(binding => [binding.name, binding.text])); if (JSON.stringify(Object.entries(actualVars).sort()) !== JSON.stringify(Object.entries(expectedVars).sort())) { fail('deployed Worker variables are not the fixed disabled configuration'); } @@ -194,33 +217,82 @@ function verifyVersion(version, namespaceId) { durable[0]?.class_name !== DO_CLASS || durable[0]?.namespace_id !== namespaceId) { fail('deployed Worker has an unexpected binding or the BRIDGE namespace differs'); } + const expectedNames = [...Object.keys(expectedVars), 'BRIDGE'].sort(); + if (bindings.length !== expectedNames.length || bindings.map(binding => binding.name).sort().some((name, index) => name !== expectedNames[index]) || + Object.keys(version.env).sort().some((name, index) => name !== expectedNames[index]) || Object.keys(version.env).length !== expectedNames.length) { + fail('Beta version bindings and env aliases do not have the exact expected names'); + } + for (const binding of bindings) { + const alias = version.env[binding.name]; + if (!alias || alias.type !== binding.type) fail('Beta version env alias disagrees with its binding'); + for (const [key, value] of Object.entries(alias)) { + if (key === 'name' || binding[key] !== value) fail('Beta version env alias carries conflicting binding data'); + } + if (binding.type === 'plain_text' && Object.hasOwn(alias, 'text') && alias.text !== binding.text) { + fail('Beta version env text differs from the binding value'); + } + } const exportValue = version.exports[DO_CLASS]; const exportKeys = Object.keys(version.exports).sort(); if (exportKeys.length !== 1 || exportKeys[0] !== DO_CLASS || exportValue?.type !== 'durable-object' || exportValue?.storage !== 'sqlite' || (exportValue?.state !== undefined && exportValue.state !== 'created')) { fail('deployed Worker does not declare exactly the expected SQLite export'); } - if (version.limits?.cpu_ms !== 10 || version.hasPreview === true) fail('deployed Worker limits or preview state differ from the disabled build'); + if (version.limits?.cpu_ms !== 10 || Object.keys(version.limits ?? {}).some(key => key !== 'cpu_ms')) fail('deployed Worker CPU limits differ from the disabled build'); + if (version.urls.length !== 0) fail('exact serving version advertises a routable URL'); return true; } function verifyWorkerMetadata(worker) { if (!worker || worker.name !== WORKER_NAME || !ID.test(worker.id ?? '') || worker.logpush !== false || - worker.observability?.enabled !== false || !worker.references || !Array.isArray(worker.references.domains) || - worker.references.domains.length !== 0) fail('Worker metadata is missing or exposes unexpected domains or telemetry'); + worker.observability?.enabled !== false || !worker.references || !Array.isArray(worker.references.domains)) { + fail('Worker metadata is missing or its domain or telemetry state is unverifiable'); + } return worker.id; } -async function readSnapshot({accountId, token, expectedZoneIds, fetchImpl = fetch}) { +function exactBridgeDomains(domains, {deployed, zoneIds}) { + if (!Array.isArray(domains)) fail('Worker domain inventory is unavailable'); + const related = domains.filter(domain => domain?.service === WORKER_NAME || domain?.hostname === BRIDGE_HOST); + if (!deployed) { + if (related.length !== 0) fail('empty Worker already has a custom domain or hostname collision'); + return true; + } + if (related.length !== 1) fail('deployed Worker must have exactly one approved custom hostname'); + const [domain] = related; + if (domain?.service !== WORKER_NAME || domain?.hostname !== BRIDGE_HOST || domain.enabled !== true || + domain.previews_enabled !== false || !ID.test(domain.zone_id ?? '') || + !zoneIds.includes(domain.zone_id.toLowerCase())) { + fail('Worker custom hostname, zone, or preview state is not the exact approved Access host'); + } + return true; +} + +function verifyNoGatewayAssociation(rules, workerId = null) { + if (!Array.isArray(rules)) fail('account Gateway rule inventory is unavailable'); + for (const rule of rules) { + if (!rule || typeof rule.action !== 'string' || typeof rule.enabled !== 'boolean') fail('account Gateway rule inventory contains an unverifiable entry'); + if (rule.action !== 'forward') continue; + const worker = rule.rule_settings?.forward?.worker_id; + if (typeof worker !== 'string' || worker.length === 0) fail('Gateway Forward rule lacks a verifiable Worker association'); + if (worker === WORKER_NAME || (workerId && worker === workerId)) fail('an account Gateway Forward rule targets the fixed staging Worker'); + } + return true; +} + +async function readSnapshot({accountId, token, gatewayToken, expectedZoneIds, fetchImpl = fetch}) { const zones = await readZones(fetchImpl, accountId, token, expectedZoneIds); await readRoutes(fetchImpl, accountId, token, zones); + const gatewayRules = await listPages(fetchImpl, accountId, gatewayToken, '/gateway/rules', {pageSize: 100}); + verifyNoGatewayAssociation(gatewayRules); const allDomains = await listPages(fetchImpl, accountId, token, '/workers/domains'); - if (allDomains.some(domain => domain?.service === WORKER_NAME)) fail('fixed staging Worker has an attached domain'); const allNamespaces = await listPages(fetchImpl, accountId, token, '/workers/durable_objects/namespaces', {pageSize: 1000}); const namespaces = allNamespaces.filter(item => item?.script === WORKER_NAME); const worker = await cfRequest(fetchImpl, accountId, token, `/workers/workers/${WORKER_NAME}`, {allowMissingWorker: true}); - if (!worker) return {worker: null, namespaces, domains: [], zoneIds: zones.map(zone => zone.id.toLowerCase()).sort()}; + if (!worker) return {worker: null, namespaces, domains: allDomains, gatewayRules, + zoneIds: zones.map(zone => zone.id.toLowerCase()).sort()}; const workerId = verifyWorkerMetadata(worker.result); + verifyNoGatewayAssociation(gatewayRules, workerId); const subdomain = await cfRequest(fetchImpl, accountId, token, `/workers/scripts/${WORKER_NAME}/subdomain`); if (subdomain.result?.enabled !== false || subdomain.result?.previews_enabled !== false) fail('Worker subdomain or preview ingress is enabled'); const settings = await cfRequest(fetchImpl, accountId, token, `/workers/scripts/${WORKER_NAME}/script-settings`); @@ -230,66 +302,88 @@ async function readSnapshot({accountId, token, expectedZoneIds, fetchImpl = fetc } const schedules = await cfRequest(fetchImpl, accountId, token, `/workers/scripts/${WORKER_NAME}/schedules`); if (!Array.isArray(schedules.result?.schedules) || schedules.result.schedules.length !== 0) fail('Worker schedules are missing or non-empty'); - const versions = await listPages(fetchImpl, accountId, token, `/workers/workers/${workerId}/versions`); const deployResponse = await cfRequest(fetchImpl, accountId, token, `/workers/scripts/${WORKER_NAME}/deployments?page=1&per_page=100`, { }); const deployments = deployResponse.result?.deployments; if (!Array.isArray(deployments)) fail('Worker deployment readback is missing'); + if (deployments.length === 0) return {worker: worker.result, workerId, subdomain: subdomain.result, settings: settings.result, + schedules: schedules.result.schedules, namespaces, domains: allDomains, gatewayRules, version: null, deployments, + zoneIds: zones.map(zone => zone.id.toLowerCase()).sort()}; + const latest = deployments[0]; + const servingVersions = latest?.versions; + if (!Array.isArray(servingVersions) || servingVersions.length !== 1 || !UUID.test(servingVersions[0]?.version_id ?? '') || + servingVersions[0]?.percentage !== 100) fail('latest deployment does not identify one exact 100 percent version'); + const exactVersionId = servingVersions[0].version_id; + const exactVersion = await cfRequest(fetchImpl, accountId, token, + `/workers/workers/${workerId}/versions/${encodeURIComponent(exactVersionId)}`); + if (exactVersion.result?.id !== exactVersionId) fail('Beta Worker version GET returned a different version ID'); return {worker: worker.result, workerId, subdomain: subdomain.result, settings: settings.result, - schedules: schedules.result.schedules, namespaces, domains: [], versions, deployments, + schedules: schedules.result.schedules, namespaces, domains: allDomains, gatewayRules, version: exactVersion.result, deployments, zoneIds: zones.map(zone => zone.id.toLowerCase()).sort()}; } -export function verifyProviderState(snapshot, {phase, expectedZoneIds, sourceSha}) { +export function verifyProviderState(snapshot, {phase, expectedZoneIds, sourceSha, expectedWorkerId}) { if (!['preflight', 'postflight'].includes(phase)) fail('provider verification phase is invalid'); const expected = parseIds(expectedZoneIds, 'approved zone inventory'); if (!snapshot || !Array.isArray(snapshot.namespaces) || !Array.isArray(snapshot.domains) || !Array.isArray(snapshot.zoneIds) || snapshot.zoneIds.length !== expected.length || snapshot.zoneIds.some((id, index) => id !== expected[index])) fail('provider inventory snapshot is incomplete or has the wrong account zones'); - if (!snapshot.worker) { - if (phase === 'postflight') fail('Worker is still absent after pinned deploy'); - if (snapshot.namespaces.length !== 0 || snapshot.domains.length !== 0) fail('an orphan namespace or domain exists for the absent Worker'); + verifyNoGatewayAssociation(snapshot.gatewayRules, snapshot.worker?.id ?? null); + if (!snapshot.worker) fail('the fixed Worker must be created locally by an owner before CI may proceed'); + const id = verifyWorkerMetadata(snapshot.worker); + if (!ID.test(expectedWorkerId ?? '') || id !== expectedWorkerId.toLowerCase()) fail('Worker ID differs from the independently pinned environment identity'); + if (Array.isArray(snapshot.deployments) && snapshot.deployments.length === 0) { + exactBridgeDomains(snapshot.domains, {deployed: false, zoneIds: expected}); + if (phase !== 'preflight' || snapshot.namespaces.length !== 0 || + snapshot.subdomain?.enabled !== false || snapshot.subdomain?.previews_enabled !== false || + !Array.isArray(snapshot.schedules) || snapshot.schedules.length !== 0 || !snapshot.settings || + snapshot.settings.logpush !== false || snapshot.settings.observability?.enabled !== false || + !Array.isArray(snapshot.settings.tail_consumers) || snapshot.settings.tail_consumers.length !== 0) { + fail('only the exact empty disabled locally created Worker may enter first CI deployment'); + } return 'deploy'; } - const id = verifyWorkerMetadata(snapshot.worker); if (snapshot.workerId !== id || snapshot.subdomain?.enabled !== false || snapshot.subdomain?.previews_enabled !== false || - !Array.isArray(snapshot.schedules) || snapshot.schedules.length !== 0 || !Array.isArray(snapshot.versions) || + !Array.isArray(snapshot.schedules) || snapshot.schedules.length !== 0 || !snapshot.version || !Array.isArray(snapshot.deployments) || snapshot.deployments.length === 0 || snapshot.settings?.logpush !== false || snapshot.settings?.observability?.enabled !== false || !Array.isArray(snapshot.settings?.tail_consumers) || snapshot.settings.tail_consumers.length !== 0) { fail('existing Worker is not fully verified as disabled and serving safely'); } - if (snapshot.domains.length !== 0 || snapshot.namespaces.length !== 1) fail('existing Worker domain or SQLite namespace inventory is unexpected'); + exactBridgeDomains(snapshot.domains, {deployed: true, zoneIds: expected}); + if (snapshot.namespaces.length !== 1) fail('existing Worker SQLite namespace inventory is unexpected'); const namespace = snapshot.namespaces[0]; if (!ID.test(namespace?.id ?? '') && !UUID.test(namespace?.id ?? '')) fail('Durable Object namespace ID is invalid'); if (namespace.script !== WORKER_NAME || namespace.class !== DO_CLASS || namespace.use_sqlite !== true) fail('Durable Object namespace owner, class, or SQLite mode is unexpected'); const deployment = snapshot.deployments[0]; if (!deployment || !UUID.test(deployment.id ?? '') || !Array.isArray(deployment.versions) || deployment.versions.length !== 1 || deployment.versions[0]?.percentage !== 100 || !UUID.test(deployment.versions[0]?.version_id ?? '')) fail('latest serving deployment is not an exact 100 percent single-version deployment'); - const versions = snapshot.versions.filter(version => version.id === deployment.versions[0].version_id); - if (versions.length !== 1) fail('latest serving deployment version is absent or ambiguous'); - verifyVersion(versions[0], namespace.id); - if (!/^[a-f0-9]{40}$/.test(sourceSha ?? '') || versions[0].annotations?.['workers/tag'] !== sourceSha) { + if (!snapshot.version || snapshot.version.id !== deployment.versions[0].version_id) fail('exact Beta Worker version does not match the latest deployment UUID'); + verifyVersion(snapshot.version, namespace.id, deployment.versions[0].version_id); + if (!/^[a-f0-9]{40}$/.test(sourceSha ?? '') || snapshot.version.annotations?.['workers/tag'] !== sourceSha) { fail('latest serving version is not tagged to this exact reviewed source SHA'); } return phase === 'preflight' ? 'already-ready' : 'verified'; } -export async function verifyBootstrapPreflight({accountId, readToken, expectedZoneIds, sourceSha, fetchImpl = fetch}) { - if (!ID.test(accountId ?? '') || typeof readToken !== 'string' || readToken.length < 20) fail('protected bootstrap account or read-only credential is missing'); +export async function verifyBootstrapPreflight({accountId, workerId, readToken, gatewayToken, expectedZoneIds, sourceSha, fetchImpl = fetch}) { + if (!ID.test(accountId ?? '') || typeof readToken !== 'string' || readToken.length < 20 || + typeof gatewayToken !== 'string' || gatewayToken.length < 20 || readToken === gatewayToken) fail('protected bootstrap account or separate read-only credentials are missing'); const zones = parseIds(expectedZoneIds, 'approved zone inventory'); - const snapshot = await readSnapshot({accountId, token: readToken, expectedZoneIds: zones, fetchImpl}); - return verifyProviderState(snapshot, {phase: 'preflight', expectedZoneIds: zones, sourceSha}); + const snapshot = await readSnapshot({accountId, token: readToken, gatewayToken, expectedZoneIds: zones, fetchImpl}); + return verifyProviderState(snapshot, {phase: 'preflight', expectedZoneIds: zones, sourceSha, expectedWorkerId: workerId}); } -export function verifyDistinctWriteCredential(readToken, writeToken) { +export function verifyDistinctWriteCredential(readToken, gatewayToken, writeToken) { if (typeof readToken !== 'string' || readToken.length < 20 || typeof writeToken !== 'string' || - writeToken.length < 20 || readToken === writeToken) fail('protected read and write credentials must be separate'); + writeToken.length < 20 || typeof gatewayToken !== 'string' || gatewayToken.length < 20 || + new Set([readToken, gatewayToken, writeToken]).size !== 3) fail('protected Worker-read, Gateway-read, and write credentials must be separate'); return true; } -export async function verifyBootstrapPostflight({accountId, readToken, expectedZoneIds, sourceSha, fetchImpl = fetch}) { - if (!ID.test(accountId ?? '') || typeof readToken !== 'string' || readToken.length < 20) fail('protected read-only provider identity is missing'); +export async function verifyBootstrapPostflight({accountId, workerId, readToken, gatewayToken, expectedZoneIds, sourceSha, fetchImpl = fetch}) { + if (!ID.test(accountId ?? '') || typeof readToken !== 'string' || readToken.length < 20 || + typeof gatewayToken !== 'string' || gatewayToken.length < 20 || readToken === gatewayToken) fail('protected read-only provider identities are missing'); const zones = parseIds(expectedZoneIds, 'approved zone inventory'); - const snapshot = await readSnapshot({accountId, token: readToken, expectedZoneIds: zones, fetchImpl}); - return verifyProviderState(snapshot, {phase: 'postflight', expectedZoneIds: zones, sourceSha}); + const snapshot = await readSnapshot({accountId, token: readToken, gatewayToken, expectedZoneIds: zones, fetchImpl}); + return verifyProviderState(snapshot, {phase: 'postflight', expectedZoneIds: zones, sourceSha, expectedWorkerId: workerId}); } export async function validateLocalBuild({buildOutput, mode = 'bridge'}) { @@ -304,14 +398,20 @@ export async function validateLocalBuild({buildOutput, mode = 'bridge'}) { return true; } -async function githubEnvironmentGate() { +async function githubEnvironmentGate(target) { + const targets = { + bootstrap: {name: BOOTSTRAP_ENVIRONMENT, reviewersVariable: 'CF_BRIDGE_RELEASE_REVIEWER_IDS'}, + release: {name: RELEASE_ENVIRONMENT, reviewersVariable: 'CF_BRIDGE_RELEASE_REVIEWER_IDS'}, + }; + const selected = targets[target]; + if (!selected) fail('environment gate target is invalid'); const token = process.env.GH_TOKEN; const api = process.env.GITHUB_API_URL; if (!token || !api || process.env.GITHUB_REPOSITORY !== GITHUB_REPOSITORY || process.env.GITHUB_EVENT_NAME !== 'workflow_dispatch' || process.env.GITHUB_REF !== 'refs/heads/main' || !/^[a-f0-9]{40}$/.test(process.env.GITHUB_SHA ?? '')) { fail('bootstrap dispatch is not from the fixed repository and main source'); } - const base = `${api.replace(/\/$/, '')}/repos/${GITHUB_REPOSITORY}/environments/${ENVIRONMENT_NAME}`; + const base = `${api.replace(/\/$/, '')}/repos/${GITHUB_REPOSITORY}/environments/${encodeURIComponent(selected.name)}`; const headers = {authorization: `Bearer ${token}`, accept: 'application/vnd.github+json', 'x-github-api-version': '2022-11-28'}; const envResponse = await fetch(`${base}`, {headers, redirect: 'error', signal: AbortSignal.timeout(15_000)}); if (!envResponse.ok) fail('protected bootstrap environment does not exist or cannot be read; deployment job was not admitted'); @@ -319,8 +419,9 @@ async function githubEnvironmentGate() { const policyResponse = await fetch(`${base}/deployment-branch-policies?per_page=100&page=1`, {headers, redirect: 'error', signal: AbortSignal.timeout(15_000)}); if (!policyResponse.ok) fail('protected bootstrap branch policy cannot be read'); const policies = await policyResponse.json(); - const expected = process.env.CF_BRIDGE_BOOTSTRAP_REVIEWER_IDS; - const result = verifyEnvironmentProtection({environment, branchPolicies: policies, expectedReviewerIds: expected}); + const expected = process.env[selected.reviewersVariable]; + const result = verifyEnvironmentProtection({environment, branchPolicies: policies, expectedReviewerIds: expected, + expectedEnvironmentName: selected.name, dispatcherId: Number(process.env.GITHUB_ACTOR_ID)}); const outputPath = process.env.GITHUB_OUTPUT; if (!outputPath) fail('workflow output channel is unavailable'); await writeFile(outputPath, `environment=${result.environment}\n`, {flag: 'a', mode: 0o600}); @@ -330,11 +431,13 @@ async function githubEnvironmentGate() { async function providerCheck(phase) { const path = process.env.GITHUB_OUTPUT; const result = phase === 'preflight' - ? await verifyBootstrapPreflight({accountId: process.env.CF_BRIDGE_BOOTSTRAP_ACCOUNT_ID, - readToken: process.env.CF_BRIDGE_BOOTSTRAP_READ_TOKEN, - expectedZoneIds: process.env.CF_BRIDGE_BOOTSTRAP_ZONE_IDS, sourceSha: process.env.GITHUB_SHA}) - : await verifyBootstrapPostflight({accountId: process.env.CF_BRIDGE_BOOTSTRAP_ACCOUNT_ID, - readToken: process.env.CF_BRIDGE_BOOTSTRAP_READ_TOKEN, expectedZoneIds: process.env.CF_BRIDGE_BOOTSTRAP_ZONE_IDS, + ? await verifyBootstrapPreflight({accountId: process.env.CF_BRIDGE_ACCOUNT_ID, workerId: process.env.CF_BRIDGE_WORKER_ID, + readToken: process.env.CF_BRIDGE_READ_TOKEN, + gatewayToken: process.env.CF_BRIDGE_GATEWAY_READ_TOKEN, + expectedZoneIds: process.env.CF_BRIDGE_ZONE_IDS, sourceSha: process.env.GITHUB_SHA}) + : await verifyBootstrapPostflight({accountId: process.env.CF_BRIDGE_ACCOUNT_ID, workerId: process.env.CF_BRIDGE_WORKER_ID, + readToken: process.env.CF_BRIDGE_READ_TOKEN, gatewayToken: process.env.CF_BRIDGE_GATEWAY_READ_TOKEN, + expectedZoneIds: process.env.CF_BRIDGE_ZONE_IDS, sourceSha: process.env.GITHUB_SHA}); if (phase === 'preflight') { if (!path) fail('workflow output channel is unavailable'); @@ -345,16 +448,18 @@ async function providerCheck(phase) { async function main() { const [command, ...args] = process.argv.slice(2); - if (args.length !== 0) fail(`usage: staging-bootstrap.mjs `); - if (command === 'github-environment') await githubEnvironmentGate(); + if (args.length !== 0) fail(`usage: staging-bootstrap.mjs `); + if (command === 'github-environment-bootstrap') await githubEnvironmentGate('bootstrap'); + else if (command === 'github-environment-release') await githubEnvironmentGate('release'); else if (command === 'preflight') await providerCheck('preflight'); else if (command === 'postflight') await providerCheck('postflight'); else if (command === 'assert-distinct-credentials') { - verifyDistinctWriteCredential(process.env.CF_BRIDGE_BOOTSTRAP_READ_TOKEN, process.env.CF_BRIDGE_BOOTSTRAP_WRITE_TOKEN); + verifyDistinctWriteCredential(process.env.CF_BRIDGE_READ_TOKEN, process.env.CF_BRIDGE_GATEWAY_READ_TOKEN, + process.env.CF_BRIDGE_API_TOKEN); console.log('separate read and write credentials verified'); } else if (command === 'validate-build') await validateLocalBuild({buildOutput: process.env.BUILD_OUTPUT ?? '.cloudflare/output/v1'}); - else fail('usage: staging-bootstrap.mjs '); + else fail('usage: staging-bootstrap.mjs '); } if (process.argv[1] && new URL(import.meta.url).pathname === process.argv[1]) { diff --git a/pm-stack/private-laptop-bridge/staging-bootstrap.test.mjs b/pm-stack/private-laptop-bridge/staging-bootstrap.test.mjs index 07a553653f..c89f085526 100644 --- a/pm-stack/private-laptop-bridge/staging-bootstrap.test.mjs +++ b/pm-stack/private-laptop-bridge/staging-bootstrap.test.mjs @@ -11,31 +11,36 @@ const namespaceId = '3'.repeat(32); const sha = 'b'.repeat(40); const versionId = '01234567-89ab-cdef-0123-456789abcdef'; const deploymentId = '11111111-2222-3333-4444-555555555555'; +const domainId = '22222222-3333-4444-5555-666666666666'; const readToken = 'synthetic-read-token-long-enough'; const writeToken = 'synthetic-write-token-long-enough'; +const gatewayToken = 'synthetic-gateway-read-token-long-enough'; const worker = {id:workerId,name:WORKER_NAME,logpush:false,observability:{enabled:false},references:{domains:[]}}; -const version = () => ({ - id:versionId, - annotations:{'workers/tag':sha}, - limits:{cpu_ms:10}, - exports:{[DO_CLASS]:{type:'durable-object',storage:'sqlite',state:'created'}}, - resources:{bindings:[ +const bindings = () => [ {name:'ENABLED',type:'plain_text',text:'false'}, {name:'GATEWAY_HOST',type:'plain_text',text:'private-bridge-staging.invalid'}, {name:'GATEWAY_ACCOUNT_ID',type:'plain_text',text:''}, {name:'GATEWAY_POLICY_ID',type:'plain_text',text:''}, {name:'GATEWAY_IDENTITY_EMAIL',type:'plain_text',text:''}, {name:'GATEWAY_POSTURE_ID',type:'plain_text',text:''}, + {name:'BRIDGE_HOST',type:'plain_text',text:'laptop-bridge-staging.security.cab'}, + {name:'ACCESS_ISSUER',type:'plain_text',text:''}, + {name:'ACCESS_AUDIENCE',type:'plain_text',text:''}, {name:'BRIDGE_REGISTRY',type:'plain_text',text:''}, {name:'BRIDGE',type:'durable_object_namespace',class_name:DO_CLASS,namespace_id:namespaceId}, - ]}, + ]; +const version = () => ({ + id:versionId,annotations:{'workers/tag':sha},limits:{cpu_ms:10},urls:[],bindings:bindings(), + env:Object.fromEntries(bindings().map(({name,type,class_name,namespace_id})=>[name,{type,...(class_name?{class_name,namespace_id}:{})}])), + exports:{[DO_CLASS]:{type:'durable-object',storage:'sqlite',state:'created'}}, }); const deployment = () => ({id:deploymentId,versions:[{version_id:versionId,percentage:100}]}); +const domain = (fields={}) => ({id:domainId,service:WORKER_NAME,hostname:'laptop-bridge-staging.security.cab',enabled:true,previews_enabled:false,zone_id:zoneId,...fields}); const ns = () => ({id:namespaceId,script:WORKER_NAME,class:DO_CLASS,use_sqlite:true}); const snapshot = () => ({ zoneIds:[zoneId],worker,workerId,subdomain:{enabled:false,previews_enabled:false}, settings:{logpush:false,observability:{enabled:false},tail_consumers:[]},schedules:[], - namespaces:[ns()],domains:[],versions:[version()],deployments:[deployment()], + namespaces:[ns()],domains:[domain()],gatewayRules:[],version:version(),deployments:[deployment()], }); test('first-deploy workflow remains dormant, fixed-target, and checks protection before environment assignment', async()=>{ @@ -47,23 +52,41 @@ test('first-deploy workflow remains dormant, fixed-target, and checks protection assert.match(workflow,/if: github\.repository == 'developing-today\/code' && github\.ref == 'refs\/heads\/main' && github\.event_name == 'workflow_dispatch'/); assert.match(workflow,/name: \$\{\{ needs\.verify-environment-before-assignment\.outputs\.environment \}\}/); assert.match(workflow,/needs: verify-environment-before-assignment/); - assert.match(workflow,/CF_BRIDGE_BOOTSTRAP_REVIEWER_IDS: \$\{\{ vars\.CF_BRIDGE_BOOTSTRAP_REVIEWER_IDS \}\}/); + assert.match(workflow,/CF_BRIDGE_RELEASE_REVIEWER_IDS: \$\{\{ vars\.CF_BRIDGE_RELEASE_REVIEWER_IDS \}\}/); + assert.match(workflow,/CF_BRIDGE_WORKER_ID: \$\{\{ vars\.CF_BRIDGE_WORKER_ID \}\}/); + assert.match(workflow,/CF_BRIDGE_ACCESS_ISSUER: \$\{\{ vars\.CF_BRIDGE_ACCESS_ISSUER \}\}/); + assert.match(workflow,/CF_BRIDGE_ACCESS_AUDIENCE: \$\{\{ vars\.CF_BRIDGE_ACCESS_AUDIENCE \}\}/); const gate=workflow.split(' deploy-disabled-bridge:',1)[0]; assert.doesNotMatch(gate,/secrets\./); const provider=workflow.split(' - name: Read current provider state')[1].split(' - name: Deploy only')[0]; - assert.match(provider,/CF_BRIDGE_BOOTSTRAP_READ_TOKEN/); - assert.doesNotMatch(provider,/CF_BRIDGE_BOOTSTRAP_WRITE_TOKEN/); + assert.match(provider,/CF_BRIDGE_READ_TOKEN/); + assert.match(provider,/CF_BRIDGE_WORKER_ID: \$\{\{ vars\.CF_BRIDGE_WORKER_ID \}\}/); + assert.doesNotMatch(workflow,/CF_BRIDGE_BOOTSTRAP_WRITE_TOKEN|CF_BRIDGE_BOOTSTRAP_ACCOUNT_ID/); assert.match(workflow,/staging-bootstrap\.mjs assert-distinct-credentials/); assert.match(workflow,/cf deploy --mode bridge --prebuilt --provision --tag "\$GITHUB_SHA"/); assert.doesNotMatch(workflow,/wrangler deploy|workers versions (create|deploy)|--dispatch-namespace/); - for(const fixed of [WORKER_NAME,'CF_BRIDGE_BOOTSTRAP_ACCOUNT_ID','CF_BRIDGE_BOOTSTRAP_ZONE_IDS',ENVIRONMENT_NAME]) assert.ok(workflow.includes(fixed)); + for(const fixed of [WORKER_NAME,'CF_BRIDGE_ACCOUNT_ID','CF_BRIDGE_ZONE_IDS',ENVIRONMENT_NAME]) assert.ok(workflow.includes(fixed)); +}); + +test('ordinary release gate verifies before dynamic environment assignment',async()=>{ + const workflow=await readFile(resolve('../../.github/workflows/private-laptop-bridge-release.yml'),'utf8'); + const [prejob,release]=workflow.split(' release:'); + assert.match(workflow,/verify-release-environment:/); + assert.match(release,/needs: verify-release-environment/); + assert.match(release,/name: \$\{\{ needs\.verify-release-environment\.outputs\.environment \}\}/); + assert.doesNotMatch(release,/environment: cloudflare-staging/); + assert.doesNotMatch(prejob,/secrets\./); + assert.match(prejob,/CF_BRIDGE_RELEASE_REVIEWER_IDS: \$\{\{ vars\.CF_BRIDGE_RELEASE_REVIEWER_IDS \}\}/); + assert.match(release,/CF_BRIDGE_ACCESS_ISSUER: \$\{\{ vars\.CF_BRIDGE_ACCESS_ISSUER \}\}/); + assert.match(release,/CF_BRIDGE_ACCESS_AUDIENCE: \$\{\{ vars\.CF_BRIDGE_ACCESS_AUDIENCE \}\}/); + assert.match(prejob,/staging-bootstrap\.mjs github-environment-release/); }); function response(result, {status=200,resultInfo={page:1,per_page:100,total_count:Array.isArray(result)?result.length:0,total_pages:1},success=true,errors=[]}={}) { return new Response(JSON.stringify({success,result,errors,...(resultInfo === undefined ? {} : {result_info:resultInfo})}),{status}); } -function cloudflareFixture({target='absent', zones=[{id:zoneId,account:{id:accountId}}], zoneInfo, route=[], domains=[], namespaces=[], workerRecord=worker, versions=[version()], deployments=[deployment()], overrides={}}={}) { +function cloudflareFixture({target='absent', zones=[{id:zoneId,account:{id:accountId}}], zoneInfo, route=[], domains=[], namespaces=[], workerRecord=worker, versionRecord=version(), gatewayRules=[], deployments=[deployment()], overrides={}}={}) { const calls=[]; const fetchImpl=async (url,init={})=>{ const parsed=new URL(url), method=init.method??'GET'; @@ -72,6 +95,7 @@ function cloudflareFixture({target='absent', zones=[{id:zoneId,account:{id:accou if(parsed.pathname==='/client/v4/zones') return response(zones,{resultInfo:zoneInfo??{page:1,per_page:50,total_count:zones.length,total_pages:zones.length?1:0}}); if(parsed.pathname===`/client/v4/zones/${zoneId}/workers/routes`) return response(route,{resultInfo:undefined}); if(parsed.pathname==='/client/v4/accounts/'+accountId+'/workers/domains') return response(domains); + if(parsed.pathname==='/client/v4/accounts/'+accountId+'/gateway/rules') return response(gatewayRules); if(parsed.pathname==='/client/v4/accounts/'+accountId+'/workers/durable_objects/namespaces') return response(namespaces,{resultInfo:{page:1,per_page:1000,total_count:namespaces.length,total_pages:namespaces.length?1:0}}); if(parsed.pathname===`/client/v4/accounts/${accountId}/workers/workers/${WORKER_NAME}`) { if(target==='absent') return response(null,{status:404,success:false,resultInfo:undefined,errors:[{code:10007}]}); @@ -80,8 +104,8 @@ function cloudflareFixture({target='absent', zones=[{id:zoneId,account:{id:accou if(parsed.pathname.endsWith(`/workers/scripts/${WORKER_NAME}/subdomain`)) return response({enabled:false,previews_enabled:false}); if(parsed.pathname.endsWith(`/workers/scripts/${WORKER_NAME}/script-settings`)) return response({logpush:false,observability:{enabled:false},tail_consumers:[]}); if(parsed.pathname.endsWith(`/workers/scripts/${WORKER_NAME}/schedules`)) return response({schedules:[]}); - if(parsed.pathname.endsWith(`/workers/workers/${workerId}/versions`)) return response(versions); if(parsed.pathname.endsWith(`/workers/scripts/${WORKER_NAME}/deployments`)) return response({deployments}); + if(parsed.pathname.endsWith(`/workers/workers/${workerId}/versions/${versionId}`)) return response(versionRecord); const replacement=overrides[parsed.pathname]; if(replacement) return replacement; throw new Error(`unexpected synthetic request ${method} ${parsed.pathname}`); @@ -89,43 +113,54 @@ function cloudflareFixture({target='absent', zones=[{id:zoneId,account:{id:accou return {fetchImpl,calls}; } -test('GitHub dispatch gate requires the existing exact environment, exact independent reviewer set, no self-approval and main only',()=>{ - const environment={name:ENVIRONMENT_NAME,protection_rules:[{type:'required_reviewers',prevent_self_review:true,reviewers:[{type:'User',reviewer:{id:71}}]}],deployment_branch_policy:{protected_branches:false,custom_branch_policies:true}}; - const branchPolicies={total_count:1,branch_policies:[{name:'main'}]}; - assert.deepEqual(verifyEnvironmentProtection({environment,branchPolicies,expectedReviewerIds:'[71]'}),{environment:ENVIRONMENT_NAME}); +test('GitHub dispatch gate proves no admin bypass, typed independent reviewers, and branch-only main',()=>{ + const environment={name:ENVIRONMENT_NAME,can_admins_bypass:false,protection_rules:[{type:'required_reviewers',prevent_self_review:true,reviewers:[{type:'User',reviewer:{id:71}}]}],deployment_branch_policy:{protected_branches:false,custom_branch_policies:true}}; + const branchPolicies={total_count:1,branch_policies:[{name:'main',type:'branch'}]}; + const expectedReviewerIds='[{"type":"User","id":71}]'; + assert.deepEqual(verifyEnvironmentProtection({environment,branchPolicies,expectedReviewerIds,dispatcherId:99}),{environment:ENVIRONMENT_NAME}); + assert.throws(()=>verifyEnvironmentProtection({environment:{...environment,can_admins_bypass:true},branchPolicies,expectedReviewerIds,dispatcherId:99}),/administrator bypass/); + assert.throws(()=>verifyEnvironmentProtection({environment:{...environment,can_admins_bypass:undefined},branchPolicies,expectedReviewerIds,dispatcherId:99}),/did not prove administrator bypass/); + assert.throws(()=>verifyEnvironmentProtection({environment,branchPolicies:{total_count:1,branch_policies:[{name:'main'}]},expectedReviewerIds,dispatcherId:99}),/branch-only main/); + assert.throws(()=>verifyEnvironmentProtection({environment,branchPolicies:{total_count:1,branch_policies:[{name:'main',type:'tag'}]},expectedReviewerIds,dispatcherId:99}),/branch-only main/); + assert.throws(()=>verifyEnvironmentProtection({environment,branchPolicies,expectedReviewerIds:'[{"type":"User","id":71}]',dispatcherId:71}),/only eligible/); for(const change of [ {environment:null}, - {environment:{...environment,name:'cloudflare-staging'}}, + {environment:{...environment,name:'cloudflare-staging-other'}}, {environment:{...environment,protection_rules:[{type:'required_reviewers',prevent_self_review:false,reviewers:[{type:'User',reviewer:{id:71}}]}]}}, {environment:{...environment,protection_rules:[{type:'required_reviewers',prevent_self_review:true,reviewers:[{type:'User',reviewer:{id:72}}]}]}}, + {environment:{...environment,protection_rules:[{type:'required_reviewers',prevent_self_review:true,reviewers:[{type:'User',reviewer:{id:71}},{type:'Team',reviewer:{id:72}}]}]}}, {branchPolicies:{total_count:2,branch_policies:[{name:'main'},{name:'release/*'}]}}, {branchPolicies:{total_count:1,branch_policies:[{name:'*'}]}}, - ]) assert.throws(()=>verifyEnvironmentProtection({environment:Object.hasOwn(change,'environment')?change.environment:environment,branchPolicies:change.branchPolicies??branchPolicies,expectedReviewerIds:'[71]'})); - assert.throws(()=>verifyEnvironmentProtection({environment,branchPolicies,expectedReviewerIds:''})); + ]) assert.throws(()=>verifyEnvironmentProtection({environment:Object.hasOwn(change,'environment')?change.environment:environment,branchPolicies:change.branchPolicies??branchPolicies,expectedReviewerIds,dispatcherId:99})); + assert.throws(()=>verifyEnvironmentProtection({environment,branchPolicies,expectedReviewerIds:'',dispatcherId:99})); }); -test('missing Worker is deployable only after complete read-only account inventory; all provider calls are GET',async()=>{ - const f=cloudflareFixture({target:'absent'}); - const status=await verifyBootstrapPreflight({accountId,readToken,expectedZoneIds:[zoneId],sourceSha:sha,fetchImpl:f.fetchImpl}); +test('exact empty locally created Worker is the only first-deploy candidate; all provider calls are GET',async()=>{ + const f=cloudflareFixture({target:'empty',deployments:[],domains:[]}); + const status=await verifyBootstrapPreflight({accountId,workerId,readToken,gatewayToken,expectedZoneIds:[zoneId],sourceSha:sha,fetchImpl:f.fetchImpl}); assert.equal(status,'deploy'); - assert.ok(f.calls.every(call=>call.method==='GET'&&call.token===`Bearer ${readToken}`)); + assert.ok(f.calls.every(call=>call.method==='GET'&&call.token===`Bearer ${call.url.pathname.endsWith('/gateway/rules')?gatewayToken:readToken}`)); assert.ok(f.calls.some(call=>call.url.pathname===`/client/v4/zones/${zoneId}/workers/routes`)); + await assert.rejects(verifyBootstrapPreflight({accountId,workerId,readToken,gatewayToken,expectedZoneIds:[zoneId],sourceSha:sha,fetchImpl:cloudflareFixture({target:'absent'}).fetchImpl}),/created locally by an owner/); for(const bad of [ cloudflareFixture({target:'absent',zones:[]}), cloudflareFixture({target:'absent',route:[{id:'route',pattern:'*',script:WORKER_NAME}]}), cloudflareFixture({target:'absent',domains:[{service:WORKER_NAME,hostname:'unsafe.example'}]}), cloudflareFixture({target:'absent',namespaces:[ns()]}), cloudflareFixture({target:'absent',zoneInfo:{page:2,per_page:50,total_count:1,total_pages:1}}), - ]) await assert.rejects(verifyBootstrapPreflight({accountId,readToken,expectedZoneIds:[zoneId],sourceSha:sha,fetchImpl:bad.fetchImpl})); - assert.equal(verifyDistinctWriteCredential(readToken,writeToken),true); - assert.throws(()=>verifyDistinctWriteCredential(readToken,readToken),/separate/); + cloudflareFixture({target:'absent',gatewayRules:[{action:'forward',enabled:true,rule_settings:{forward:{worker_id:WORKER_NAME}}}]}), + ]) await assert.rejects(verifyBootstrapPreflight({accountId,workerId,readToken,gatewayToken,expectedZoneIds:[zoneId],sourceSha:sha,fetchImpl:bad.fetchImpl})); + const takeover=cloudflareFixture({target:'empty',deployments:[],domains:[],workerRecord:{...worker,id:'4'.repeat(32)}}); + await assert.rejects(verifyBootstrapPreflight({accountId,workerId,readToken,gatewayToken,expectedZoneIds:[zoneId],sourceSha:sha,fetchImpl:takeover.fetchImpl}),/Worker ID differs/); + assert.equal(verifyDistinctWriteCredential(readToken,gatewayToken,writeToken),true); + assert.throws(()=>verifyDistinctWriteCredential(readToken,gatewayToken,gatewayToken),/separate/); }); test('existing Worker is a no-op only when disabled ingress, exact SQLite namespace, binding and serving version agree',()=>{ - const good={...snapshot(),domains:[]}; - assert.equal(verifyProviderState(good,{phase:'preflight',expectedZoneIds:[zoneId],sourceSha:sha}),'already-ready'); - assert.equal(verifyProviderState(good,{phase:'postflight',expectedZoneIds:[zoneId],sourceSha:sha}),'verified'); - assert.throws(()=>verifyProviderState(good,{phase:'preflight',expectedZoneIds:[zoneId],sourceSha:'c'.repeat(40)}),/exact reviewed source SHA/); + const good=snapshot(); + assert.equal(verifyProviderState(good,{phase:'preflight',expectedZoneIds:[zoneId],sourceSha:sha,expectedWorkerId:workerId}),'already-ready'); + assert.equal(verifyProviderState(good,{phase:'postflight',expectedZoneIds:[zoneId],sourceSha:sha,expectedWorkerId:workerId}),'verified'); + assert.throws(()=>verifyProviderState(good,{phase:'preflight',expectedZoneIds:[zoneId],sourceSha:'c'.repeat(40),expectedWorkerId:workerId}),/exact reviewed source SHA/); for(const mutate of [ s=>{s.zoneIds=[];}, s=>{s.subdomain.enabled=true;}, @@ -133,22 +168,28 @@ test('existing Worker is a no-op only when disabled ingress, exact SQLite namesp s=>{s.schedules=[{cron:'* * * * *'}];}, s=>{s.settings.logpush=true;}, s=>{s.settings.tail_consumers=[{}];}, - s=>{s.domains=[{hostname:'unsafe.example'}];}, + s=>{s.domains=[domain({hostname:'unsafe.example'})];}, + s=>{s.domains=[domain({service:'other-worker'})];}, + s=>{s.domains=[domain({previews_enabled:true})];}, + s=>{s.domains=[domain({enabled:false})];}, + s=>{s.deployments=[];}, s=>{s.namespaces[0].script='other-worker';}, s=>{s.namespaces[0].use_sqlite=false;}, s=>{s.deployments[0].versions[0].percentage=50;}, - s=>{s.versions[0].resources.bindings[0].text='true';}, - s=>{s.versions[0].resources.bindings.push({name:'OUTSIDE',type:'service'});}, - s=>{s.versions[0].exports[DO_CLASS].storage='legacy-kv';}, - s=>{s.versions[0].limits.cpu_ms=50;}, - ]) { const bad=snapshot(); mutate(bad); assert.throws(()=>verifyProviderState(bad,{phase:'preflight',expectedZoneIds:[zoneId],sourceSha:sha})); } - assert.throws(()=>verifyProviderState(good,{phase:'postflight',expectedZoneIds:[zoneId],sourceSha:'c'.repeat(40)}),/exact reviewed source SHA/); + s=>{s.version.bindings[0].text='true';}, + s=>{s.version.bindings.push({name:'OUTSIDE',type:'service'});}, + s=>{s.version.exports[DO_CLASS].storage='legacy-kv';}, + s=>{s.version.limits.cpu_ms=50;}, + s=>{s.version.env.ENABLED.text='true';}, + s=>{s.version.urls=['https://preview.example'];}, + ]) { const bad=snapshot(); mutate(bad); assert.throws(()=>verifyProviderState(bad,{phase:'preflight',expectedZoneIds:[zoneId],sourceSha:sha,expectedWorkerId:workerId})); } + assert.throws(()=>verifyProviderState(good,{phase:'postflight',expectedZoneIds:[zoneId],sourceSha:'c'.repeat(40),expectedWorkerId:workerId}),/exact reviewed source SHA/); }); test('postflight readback verifies deployed identity via independent API data and never writes',async()=>{ - const f=cloudflareFixture({target:'existing',namespaces:[ns()]}); - assert.equal(await verifyBootstrapPostflight({accountId,readToken,expectedZoneIds:[zoneId],sourceSha:sha,fetchImpl:f.fetchImpl}),'verified'); - assert.ok(f.calls.every(call=>call.method==='GET'&&call.token===`Bearer ${readToken}`)); - const bad=cloudflareFixture({target:'existing',namespaces:[ns()],versions:[{...version(),annotations:{'workers/tag':'c'.repeat(40)}}]}); - await assert.rejects(verifyBootstrapPostflight({accountId,readToken,expectedZoneIds:[zoneId],sourceSha:sha,fetchImpl:bad.fetchImpl}),/exact reviewed source SHA/); + const f=cloudflareFixture({target:'existing',namespaces:[ns()],domains:[domain()]}); + assert.equal(await verifyBootstrapPostflight({accountId,workerId,readToken,gatewayToken,expectedZoneIds:[zoneId],sourceSha:sha,fetchImpl:f.fetchImpl}),'verified'); + assert.ok(f.calls.every(call=>call.method==='GET'&&call.token===`Bearer ${call.url.pathname.endsWith('/gateway/rules')?gatewayToken:readToken}`)); + const bad=cloudflareFixture({target:'existing',namespaces:[ns()],domains:[domain()],versionRecord:{...version(),annotations:{'workers/tag':'c'.repeat(40)}}}); + await assert.rejects(verifyBootstrapPostflight({accountId,workerId,readToken,gatewayToken,expectedZoneIds:[zoneId],sourceSha:sha,fetchImpl:bad.fetchImpl}),/exact reviewed source SHA/); }); diff --git a/pm-stack/private-laptop-bridge/staging-preflight.json b/pm-stack/private-laptop-bridge/staging-preflight.json index 72ee303417..f6b5fd9ac2 100644 --- a/pm-stack/private-laptop-bridge/staging-preflight.json +++ b/pm-stack/private-laptop-bridge/staging-preflight.json @@ -67,7 +67,9 @@ "workers_dev": false, "preview_urls": false, "routes": [], - "custom_domains": [], + "custom_domains": [ + "laptop-bridge-staging.security.cab" + ], "observability": { "enabled": false, "logs": false, @@ -85,7 +87,10 @@ "GATEWAY_POLICY_ID": "", "GATEWAY_IDENTITY_EMAIL": "", "GATEWAY_POSTURE_ID": "", - "BRIDGE_REGISTRY": "" + "BRIDGE_REGISTRY": "", + "BRIDGE_HOST": "laptop-bridge-staging.security.cab", + "ACCESS_ISSUER": "", + "ACCESS_AUDIENCE": "" }, "bindings": [ { diff --git a/pm-stack/private-laptop-bridge/worker.mjs b/pm-stack/private-laptop-bridge/worker.mjs index dad53bdafd..325c27098c 100644 --- a/pm-stack/private-laptop-bridge/worker.mjs +++ b/pm-stack/private-laptop-bridge/worker.mjs @@ -1,4 +1,5 @@ import {operations, exact, identifier, unbase64, signingBytes, boundedText, validateOperation, validateResult} from './protocol.mjs'; +import {verifyAccessServiceToken} from './access-auth.mjs'; const nextExpiry = s => Math.min(...Object.values(s.nonces), ...Object.values(s.quotas).map(q => q.end), ...Object.values(s.jobs).map(j => j.retainUntil), ...s.audit.map(e => e.at + 180000)); const paths = ['/v1/call', '/v1/poll', '/v1/result', '/v1/read']; @@ -16,10 +17,11 @@ function registry(raw) { if (typeof raw !== 'string' || raw.length > 16384) throw new Error('config'); const r = JSON.parse(raw); if (!exact(r, ['audience', 'principals']) || !identifier(r.audience) || !Array.isArray(r.principals) || r.principals.length < 2 || r.principals.length > 16) throw new Error('config'); - const ids = new Set(), keys = new Set(), principals = {}; + const ids = new Set(), keys = new Set(), accessIds = new Set(), principals = {}; for (const p of r.principals) { - if (!exact(p, ['id', 'role', 'device', 'publicKey', 'scopes', 'issuedAt', 'expiresAt', 'revoked']) || !identifier(p.id) || !identifier(p.device) || !['caller', 'device'].includes(p.role) || typeof p.revoked !== 'boolean' || !Number.isSafeInteger(p.issuedAt) || !Number.isSafeInteger(p.expiresAt) || p.expiresAt <= p.issuedAt || p.expiresAt - p.issuedAt > 3600000 || !Array.isArray(p.scopes) || p.scopes.length < 1 || p.scopes.length > operations.length || new Set(p.scopes).size !== p.scopes.length || !p.scopes.every(s => operations.includes(s)) || ids.has(p.id) || keys.has(p.publicKey) || unbase64(p.publicKey).length !== 32) throw new Error('config'); - ids.add(p.id); keys.add(p.publicKey); principals[p.id] = p; + if (!exact(p, ['id', 'role', 'device', 'publicKey', 'accessClientId', 'scopes', 'issuedAt', 'expiresAt', 'revoked']) || !identifier(p.id) || !identifier(p.device) || !['caller', 'device'].includes(p.role) || typeof p.accessClientId !== 'string' || !/^[A-Za-z0-9._-]{8,128}$/.test(p.accessClientId) || typeof p.revoked !== 'boolean' || !Number.isSafeInteger(p.issuedAt) || !Number.isSafeInteger(p.expiresAt) || p.expiresAt <= p.issuedAt || p.expiresAt - p.issuedAt > 3600000 || !Array.isArray(p.scopes) || p.scopes.length < 1 || p.scopes.length > operations.length || new Set(p.scopes).size !== p.scopes.length || !p.scopes.every(s => operations.includes(s)) || ids.has(p.id) || keys.has(p.publicKey) || unbase64(p.publicKey).length !== 32) throw new Error('config'); + if (accessIds.has(p.accessClientId)) throw new Error('config'); + ids.add(p.id); keys.add(p.publicKey); accessIds.add(p.accessClientId); principals[p.id] = p; } return {audience: r.audience, principals}; } @@ -134,10 +136,31 @@ export class PrivateLaptopBridge { } } +// Internal-only invocation shared with the trusted Gateway RPC entrypoint. +// Public HTTP must use the default export below, which verifies Access first. +export async function dispatchSignedRequest(request, env) { + if (env.ENABLED !== 'true' || !env.BRIDGE) return response(503, {error: 'disabled'}); + try { return await env.BRIDGE.get(env.BRIDGE.idFromName('owner-v1')).fetch(request); } + catch { return response(503, {error: 'storage'}); } +} + export default { async fetch(request, env) { if (env.ENABLED !== 'true' || !env.BRIDGE) return response(503, {error: 'disabled'}); - try { return await env.BRIDGE.get(env.BRIDGE.idFromName('owner-v1')).fetch(request); } - catch { return response(503, {error: 'storage'}); } + let config; + try { config = registry(env.BRIDGE_REGISTRY); } catch { return response(503, {error: 'configuration'}); } + let clientId; + try { clientId = await verifyAccessServiceToken(request, env); } + catch { return response(401, {error: 'access-authentication'}); } + const principal = Object.values(config.principals).find(p => p.accessClientId === clientId); + if (!principal || !active(principal, Date.now())) return response(401, {error: 'access-principal'}); + // Never forward Access credentials or edge identity headers into the DO. + const headers = new Headers(request.headers); + for (const name of [...headers.keys()]) { + const lower = name.toLowerCase(); + if (lower.startsWith('cf-access-') || lower === 'cookie' || lower === 'authorization') headers.delete(name); + } + const sanitized = new Request(request, {headers}); + return dispatchSignedRequest(sanitized, env); }, }; From aa91c16f2f2c2e24ba6376f281f19fedc880f40d Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 09:14:35 +0000 Subject: [PATCH 24/33] fix(bridge): bind Access context and principal roles --- .../private-laptop-bridge/ACCESS-STAGING.md | 22 +++++--- .../private-laptop-bridge/access-auth.mjs | 24 ++++---- .../access-auth.test.mjs | 55 +++++++++++++++---- pm-stack/private-laptop-bridge/worker.mjs | 12 +++- 4 files changed, 80 insertions(+), 33 deletions(-) diff --git a/pm-stack/private-laptop-bridge/ACCESS-STAGING.md b/pm-stack/private-laptop-bridge/ACCESS-STAGING.md index d5ccb2cc12..f6df521fcb 100644 --- a/pm-stack/private-laptop-bridge/ACCESS-STAGING.md +++ b/pm-stack/private-laptop-bridge/ACCESS-STAGING.md @@ -31,13 +31,19 @@ Each request must pass both layers: 2. The Worker verifies `Cf-Access-Jwt-Assertion` itself. It pins the exact `https://.cloudflareaccess.com` issuer, exact app audience, `RS256`, `kid`, fetched JWKS, `type=app`, `sub=""`, `common_name`, `iat`, `exp`, and - optional `nbf`. The verified `common_name` must match both the incoming - `CF-Access-Client-Id` and exactly one unrevoked principal in the Worker - registry. A token for one service cannot assume the other principal's role. + optional `nbf`. The Worker also requires the runtime-verified + `ctx.access.aud` to match the configured audience. The signed `common_name` + selects exactly one unrevoked principal; the request's + `x-bridge-principal` must equal that principal's ID before forwarding. The + Worker does not rely on the original `CF-Access-Client-Id` header, which is + not guaranteed to reach the Worker. A token for one service cannot assume + the other principal's role. JWKS are fetched only from the exact configured issuer, redirects are rejected, cache lifetime is five minutes, and an unknown key or failed - refresh after expiry fails closed. The accepted JWT lifetime is at most 15 - minutes. + refresh after expiry fails closed. `exp` must be strictly in the future; + `iat` cannot be more than 30 seconds in the future, and optional `nbf` uses + the same bounded future skew. No undocumented maximum `exp - iat` is + assumed; Access policy token lifetime must be reviewed independently. 3. The existing bridge check remains independent: Ed25519 signs the request method, exact path, body, audience, principal, timestamp, and nonce. The Durable Object checks role, device, operation scope, quota, replay, lease, @@ -49,8 +55,10 @@ headers, `Cookie`, and `Authorization`. It never uses caller-supplied identity headers. Denial logs contain only fixed status and reason codes. The default Worker fetch rejects a missing or mismatched exact HTTPS hostname, -port, route or query; rejects missing, malformed, forged, wrong-issuer, -wrong-audience, expired, cross-client, stale-key, or wrong-algorithm tokens; +port, route or query and Upgrade requests before JWKS or Durable Object calls; +rejects missing runtime Access context, mismatched context audience, malformed, +forged, wrong-issuer, wrong-audience, expired, cross-client, stale-key, or +wrong-algorithm tokens; and fails closed when the auth configuration or JWKS are unavailable. Redirects are not followed by either client. The deployment must keep `workers_dev` and preview URLs disabled and bind only the approved custom hostname. Do not create diff --git a/pm-stack/private-laptop-bridge/access-auth.mjs b/pm-stack/private-laptop-bridge/access-auth.mjs index 22a77fcdd2..1c34272067 100644 --- a/pm-stack/private-laptop-bridge/access-auth.mjs +++ b/pm-stack/private-laptop-bridge/access-auth.mjs @@ -3,9 +3,9 @@ const MAX_JWT_LENGTH = 16_384; const MAX_KEYS_BYTES = 32_768; const SKEW_SECONDS = 30; -const MAX_TOKEN_AGE_SECONDS = 15 * 60; const KEY_CACHE_MS = 5 * 60_000; const keyCache = new Map(); +const ACCESS_PATHS = new Set(['/v1/call', '/v1/poll', '/v1/result', '/v1/read']); export const BRIDGE_HOST = 'laptop-bridge-staging.security.cab'; export const BRIDGE_ORIGIN = `https://${BRIDGE_HOST}`; @@ -56,24 +56,26 @@ async function accessKeys({issuer, certsUrl}, fetchImpl, now) { return keys; } -/** Return the verified service-token Client ID. Never trusts caller-supplied - * identity fields or Access headers without the signed JWT and exact config. */ -export async function verifyAccessServiceToken(request, env, {fetchImpl = fetch, nowMs = Date.now()} = {}) { +/** Return the signed service-token common_name. The original service-token + * client-ID header is not part of the identity decision; Cloudflare's direct + * Access invocation context independently proves the configured audience. */ +export async function verifyAccessServiceToken(request, env, ctx, {fetchImpl = fetch, nowMs = Date.now()} = {}) { const cfg = accessConfig(env); const url = new URL(request.url); - if (request.method !== 'POST' || url.protocol !== 'https:' || url.hostname !== cfg.host || url.port || url.username || url.password || url.search || url.hash) fail(); + if (request.method !== 'POST' || request.headers.has('upgrade') || url.protocol !== 'https:' || url.hostname !== cfg.host || url.port || url.username || url.password || url.search || url.hash || !ACCESS_PATHS.has(url.pathname)) fail(); + if (!ctx?.access || ctx.access.aud !== cfg.audience) fail(); const token = request.headers.get('cf-access-jwt-assertion'); - const clientId = request.headers.get('cf-access-client-id'); - if (!token || token.length > MAX_JWT_LENGTH || !clientId || !/^[A-Za-z0-9._-]{8,128}$/.test(clientId)) fail(); + if (!token || token.length > MAX_JWT_LENGTH) fail(); const parts = token.split('.'); if (parts.length !== 3) fail(); const [header, claims] = [decodePart(parts[0]), decodePart(parts[1])]; if (!header || header.alg !== 'RS256' || header.typ !== 'JWT' || typeof header.kid !== 'string' || !claims || claims.type !== 'app' || claims.iss !== cfg.issuer || claims.sub !== '' || !Array.isArray(claims.aud) || claims.aud.length < 1 || !claims.aud.includes(cfg.audience) || - claims.common_name !== clientId || !Number.isSafeInteger(claims.exp) || !Number.isSafeInteger(claims.iat) || - claims.exp <= Math.floor(nowMs / 1000) - SKEW_SECONDS || claims.iat > Math.floor(nowMs / 1000) + SKEW_SECONDS || - claims.exp <= claims.iat || claims.exp - claims.iat > MAX_TOKEN_AGE_SECONDS || + typeof claims.common_name !== 'string' || !/^[A-Za-z0-9._-]{8,128}$/.test(claims.common_name) || + !Number.isSafeInteger(claims.exp) || !Number.isSafeInteger(claims.iat) || + claims.exp <= Math.floor(nowMs / 1000) || claims.iat > Math.floor(nowMs / 1000) + SKEW_SECONDS || + claims.exp <= claims.iat || (claims.nbf !== undefined && (!Number.isSafeInteger(claims.nbf) || claims.nbf > Math.floor(nowMs / 1000) + SKEW_SECONDS))) fail(); const keys = await accessKeys(cfg, fetchImpl, nowMs); const key = keys.get(header.kid); @@ -85,7 +87,7 @@ export async function verifyAccessServiceToken(request, env, {fetchImpl = fetch, new TextEncoder().encode(`${parts[0]}.${parts[1]}`)); } catch { fail(); } if (!valid) fail(); - return clientId; + return claims.common_name; } export function clearAccessKeyCacheForTests() { keyCache.clear(); } diff --git a/pm-stack/private-laptop-bridge/access-auth.test.mjs b/pm-stack/private-laptop-bridge/access-auth.test.mjs index cbd1c5ca57..64130c3434 100644 --- a/pm-stack/private-laptop-bridge/access-auth.test.mjs +++ b/pm-stack/private-laptop-bridge/access-auth.test.mjs @@ -26,30 +26,36 @@ async function fixture() { const signature = Buffer.from(await crypto.subtle.sign('RSASSA-PKCS1-v1_5',signingPair.privateKey,new TextEncoder().encode(input))).toString('base64url'); return `${input}.${signature}`; }; - const request = async (claims={}, {host=BRIDGE_HOST, fetch=fetchImpl, id=clientId, tokenOverride, signingPair, nowMs=now}={}) => { + const request = async (claims={}, {host=BRIDGE_HOST, fetch=fetchImpl, id=clientId, tokenOverride, signingPair, nowMs=now, access=audience, includeClientId=true}={}) => { const jwt = tokenOverride ?? await token(claims,signingPair,nowMs); - const req = new Request(`https://${host}/v1/poll`,{method:'POST',headers:{'cf-access-client-id':id,'cf-access-client-secret':'synthetic-secret-not-live','cf-access-jwt-assertion':jwt}}); - return verifyAccessServiceToken(req,env,{fetchImpl:fetch,nowMs}); + const headers = {'cf-access-client-secret':'synthetic-secret-not-live','cf-access-jwt-assertion':jwt}; + if(includeClientId) headers['cf-access-client-id']=id; + const req = new Request(`https://${host}/v1/poll`,{method:'POST',headers}); + return verifyAccessServiceToken(req,env,{access:access===null?undefined:{aud:access}},{fetchImpl:fetch,nowMs}); }; return {pair,fetchImpl,token,request}; } -test('Access service token validates signature, issuer, audience, short lifetime, exact hostname and client ID',async()=>{ +test('Access service token validates signature, issuer, claim and context audiences, common_name, times and exact hostname',async()=>{ clearAccessKeyCacheForTests(); const f=await fixture(); assert.equal(await f.request(),clientId); + assert.equal(await f.request({}, {includeClientId:false}),clientId); + // The edge-provided header is not authoritative; only the signed common_name selects identity. + assert.equal(await f.request({}, {id:'different-untrusted-client'}),clientId); + assert.equal(await f.request({exp:now/1000+3600,iat:now/1000-1800}),clientId); for(const claims of [ {iss:'https://attacker.cloudflareaccess.com'}, {aud:['another-audience']}, - {exp:now/1000-1}, + {exp:now/1000-1,iat:now/1000-100}, {iat:now/1000+31}, - {iat:now/1000-901}, {common_name:'other-client'}, {sub:'nonempty'}, {type:'org'}, ]) await assert.rejects(f.request(claims),/access-denied/); + await assert.rejects(f.request({}, {access:'wrong-access-context-audience'}),/access-denied/); + await assert.rejects(f.request({}, {access:null}),/access-denied/); await assert.rejects(f.request({}, {host:'other.security.cab'}),/access-denied/); - await assert.rejects(f.request({}, {id:'other-client'}),/access-denied/); }); test('forged signatures, unsupported algorithms, unknown keys and unavailable/stale JWKS deny',async()=>{ @@ -71,7 +77,7 @@ test('forged signatures, unsupported algorithms, unknown keys and unavailable/st await assert.rejects(f.request({}, {fetch:async()=>new Response('unavailable',{status:503})}),/access-denied/); }); -test('deployed fetch binds Access client identity to one principal and strips all edge credentials before DO',async()=>{ +test('deployed fetch binds signed Access identity to the same Ed25519 principal and strips edge credentials before DO',async()=>{ clearAccessKeyCacheForTests(); const f=await fixture(); const ed=await crypto.subtle.generateKey('Ed25519',true,['sign','verify']); @@ -89,8 +95,9 @@ test('deployed fetch binds Access client identity to one principal and strips al 'x-bridge-signature':'synthetic-signature','cf-access-client-id':clientId,'cf-access-client-secret':'synthetic-secret', 'cf-access-jwt-assertion':jwt,'cf-access-authenticated-user-email':'forged@example.invalid',cookie:'CF_Authorization=synthetic',authorization:'Bearer synthetic', }}); - assert.equal(await verifyAccessServiceToken(req,workerEnv,{nowMs:currentNow,fetchImpl:f.fetchImpl}),clientId); - const result=await worker.fetch(req,workerEnv); + assert.equal(await verifyAccessServiceToken(req,workerEnv,{access:{aud:audience}},{nowMs:currentNow,fetchImpl:f.fetchImpl}),clientId); + const accessContext={access:{aud:audience}}; + const result=await worker.fetch(req,workerEnv,accessContext); assert.equal(result.status,200); assert.equal(received.headers.get('cf-access-jwt-assertion'),null); assert.equal(received.headers.get('cf-access-client-secret'),null); @@ -100,9 +107,33 @@ test('deployed fetch binds Access client identity to one principal and strips al assert.equal(received.headers.get('x-bridge-signature'),'synthetic-signature'); received=null; const forged=new Request(`https://${BRIDGE_HOST}/v1/poll`,{method:'POST',body:'{}',headers:{'cf-access-client-id':'other-client','cf-access-jwt-assertion':jwt}}); - assert.equal((await worker.fetch(forged,workerEnv)).status,401); + assert.equal((await worker.fetch(forged,workerEnv,accessContext)).status,401); + assert.equal(received,null); + const crossRole=new Request(`https://${BRIDGE_HOST}/v1/poll`,{method:'POST',body:'{}',headers:{'x-bridge-principal':'aster-caller','cf-access-jwt-assertion':jwt}}); + assert.equal((await worker.fetch(crossRole,workerEnv,accessContext)).status,401); assert.equal(received,null); principal.revoked=true; workerEnv.BRIDGE_REGISTRY=JSON.stringify({audience:'bridge-signing-audience',principals:[principal,caller]}); - assert.equal((await worker.fetch(req,workerEnv)).status,401); + assert.equal((await worker.fetch(req,workerEnv,accessContext)).status,401); +}); + +test('default fetch rejects nonexact routes and upgrades before JWKS or Durable Object access',async()=>{ + clearAccessKeyCacheForTests(); + const f=await fixture(); + const ed=await crypto.subtle.generateKey('Ed25519',true,['sign','verify']); + const edCaller=await crypto.subtle.generateKey('Ed25519',true,['sign','verify']); + const principal={id:'amd-device',role:'device',device:'amd',publicKey:b64url(await crypto.subtle.exportKey('raw',ed.publicKey)),accessClientId:clientId,scopes:[...operations],issuedAt:Date.now()-1000,expiresAt:Date.now()+600000,revoked:false}; + const caller={...principal,id:'aster-caller',role:'caller',publicKey:b64url(await crypto.subtle.exportKey('raw',edCaller.publicKey)),accessClientId:'aster-client-123456'}; + let doCalls=0; + const workerEnv={...env,ENABLED:'true',BRIDGE_REGISTRY:JSON.stringify({audience:'bridge-signing-audience',principals:[principal,caller]}), + BRIDGE:{idFromName:id=>id,get:()=>({fetch:async()=>{doCalls++;return Response.json({ok:true});}})}}; + const jwt=await f.token({},undefined,Date.now()); + const ignoredFetch=async()=>{throw new Error('JWKS must not be fetched for rejected routes');}; + const invalidRoute=new Request(`https://${BRIDGE_HOST}/v1/unknown`,{method:'POST',headers:{'cf-access-jwt-assertion':jwt}}); + const upgrade=new Request(`https://${BRIDGE_HOST}/v1/poll`,{method:'POST',headers:{'cf-access-jwt-assertion':jwt,upgrade:'websocket'}}); + assert.equal((await worker.fetch(invalidRoute,workerEnv,{access:{aud:audience}})).status,404); + assert.equal((await worker.fetch(upgrade,workerEnv,{access:{aud:audience}})).status,404); + await assert.rejects(verifyAccessServiceToken(invalidRoute,workerEnv,{access:{aud:audience}},{fetchImpl:ignoredFetch}),/access-denied/); + await assert.rejects(verifyAccessServiceToken(upgrade,workerEnv,{access:{aud:audience}},{fetchImpl:ignoredFetch}),/access-denied/); + assert.equal(doCalls,0); }); diff --git a/pm-stack/private-laptop-bridge/worker.mjs b/pm-stack/private-laptop-bridge/worker.mjs index 325c27098c..ccd42fa7ef 100644 --- a/pm-stack/private-laptop-bridge/worker.mjs +++ b/pm-stack/private-laptop-bridge/worker.mjs @@ -1,5 +1,5 @@ import {operations, exact, identifier, unbase64, signingBytes, boundedText, validateOperation, validateResult} from './protocol.mjs'; -import {verifyAccessServiceToken} from './access-auth.mjs'; +import {BRIDGE_HOST, verifyAccessServiceToken} from './access-auth.mjs'; const nextExpiry = s => Math.min(...Object.values(s.nonces), ...Object.values(s.quotas).map(q => q.end), ...Object.values(s.jobs).map(j => j.retainUntil), ...s.audit.map(e => e.at + 180000)); const paths = ['/v1/call', '/v1/poll', '/v1/result', '/v1/read']; @@ -145,15 +145,21 @@ export async function dispatchSignedRequest(request, env) { } export default { - async fetch(request, env) { + async fetch(request, env, ctx) { if (env.ENABLED !== 'true' || !env.BRIDGE) return response(503, {error: 'disabled'}); let config; try { config = registry(env.BRIDGE_REGISTRY); } catch { return response(503, {error: 'configuration'}); } + const url = new URL(request.url); + // Reject non-bridge traffic before fetching Access keys or touching the DO. + if (request.method !== 'POST' || request.headers.has('upgrade') || url.protocol !== 'https:' || url.hostname !== BRIDGE_HOST || url.port || url.username || url.password || url.search || url.hash || !paths.includes(url.pathname)) return response(404, {error: 'route'}); let clientId; - try { clientId = await verifyAccessServiceToken(request, env); } + try { clientId = await verifyAccessServiceToken(request, env, ctx); } catch { return response(401, {error: 'access-authentication'}); } const principal = Object.values(config.principals).find(p => p.accessClientId === clientId); if (!principal || !active(principal, Date.now())) return response(401, {error: 'access-principal'}); + // The role selected by signed Access common_name must be the same role + // whose Ed25519 key signs this request; never pair the two identities. + if (request.headers.get('x-bridge-principal') !== principal.id) return response(401, {error: 'principal-binding'}); // Never forward Access credentials or edge identity headers into the DO. const headers = new Headers(request.headers); for (const name of [...headers.keys()]) { From b58e91a345d738a3c364c7adb8fbc1852312d067 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 09:23:12 +0000 Subject: [PATCH 25/33] fix(bridge): preserve Access context at Gateway entrypoint --- .../access-auth.test.mjs | 5 +++ .../private-laptop-bridge/gateway-fetch.mjs | 5 +++ pm-stack/private-laptop-bridge/gateway.mjs | 3 +- .../private-laptop-bridge/gateway.test.mjs | 31 +++++++++++++++++++ 4 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 pm-stack/private-laptop-bridge/gateway-fetch.mjs diff --git a/pm-stack/private-laptop-bridge/access-auth.test.mjs b/pm-stack/private-laptop-bridge/access-auth.test.mjs index 64130c3434..9b040ba098 100644 --- a/pm-stack/private-laptop-bridge/access-auth.test.mjs +++ b/pm-stack/private-laptop-bridge/access-auth.test.mjs @@ -112,6 +112,11 @@ test('deployed fetch binds signed Access identity to the same Ed25519 principal const crossRole=new Request(`https://${BRIDGE_HOST}/v1/poll`,{method:'POST',body:'{}',headers:{'x-bridge-principal':'aster-caller','cf-access-jwt-assertion':jwt}}); assert.equal((await worker.fetch(crossRole,workerEnv,accessContext)).status,401); assert.equal(received,null); + const unknownJwt=await f.token({common_name:'unknown-client-123'},undefined,currentNow); + assert.equal(await verifyAccessServiceToken(new Request(`https://${BRIDGE_HOST}/v1/poll`,{method:'POST',headers:{'cf-access-jwt-assertion':unknownJwt}}),workerEnv,accessContext,{nowMs:currentNow,fetchImpl:f.fetchImpl}),'unknown-client-123'); + const unknownPrincipal=new Request(`https://${BRIDGE_HOST}/v1/poll`,{method:'POST',body:'{}',headers:{'x-bridge-principal':'unknown-principal','cf-access-jwt-assertion':unknownJwt}}); + assert.equal((await worker.fetch(unknownPrincipal,workerEnv,accessContext)).status,401); + assert.equal(received,null); principal.revoked=true; workerEnv.BRIDGE_REGISTRY=JSON.stringify({audience:'bridge-signing-audience',principals:[principal,caller]}); assert.equal((await worker.fetch(req,workerEnv,accessContext)).status,401); diff --git a/pm-stack/private-laptop-bridge/gateway-fetch.mjs b/pm-stack/private-laptop-bridge/gateway-fetch.mjs new file mode 100644 index 0000000000..fa31b4a971 --- /dev/null +++ b/pm-stack/private-laptop-bridge/gateway-fetch.mjs @@ -0,0 +1,5 @@ +// Keep the direct Access-authenticated Worker entrypoint's execution context. +// Cloudflare attaches ctx.access only to the directly authenticated invocation. +export async function gatewayFetch(bridge, request, env, ctx) { + return bridge.fetch(request, env, ctx); +} diff --git a/pm-stack/private-laptop-bridge/gateway.mjs b/pm-stack/private-laptop-bridge/gateway.mjs index 8fb75b175f..a8534d3043 100644 --- a/pm-stack/private-laptop-bridge/gateway.mjs +++ b/pm-stack/private-laptop-bridge/gateway.mjs @@ -2,6 +2,7 @@ // Context contract: https://developers.cloudflare.com/cloudflare-one/traffic-controls/integrate-workers/available-context/ import { WorkerEntrypoint } from 'cloudflare:workers'; import bridge, {dispatchSignedRequest} from './worker.mjs'; +import {gatewayFetch} from './gateway-fetch.mjs'; export { PrivateLaptopBridge } from './worker.mjs'; const paths = new Set(['/v1/call', '/v1/poll', '/v1/result', '/v1/read']); @@ -52,4 +53,4 @@ export class GatewayMiddleware extends WorkerEntrypoint { // The fixed custom hostname enters the Worker directly, but only after the // Worker validates Access's signed service-token JWT and the DO independently // validates the Ed25519 request. No proxy fallback or origin fetch exists. -export default {fetch(request, env) { return bridge.fetch(request, env); }}; +export default {fetch(request, env, ctx) { return gatewayFetch(bridge, request, env, ctx); }}; diff --git a/pm-stack/private-laptop-bridge/gateway.test.mjs b/pm-stack/private-laptop-bridge/gateway.test.mjs index 3f37c4f08e..99cc0c7a43 100644 --- a/pm-stack/private-laptop-bridge/gateway.test.mjs +++ b/pm-stack/private-laptop-bridge/gateway.test.mjs @@ -2,14 +2,45 @@ // is synthetic; these tests do not prove Cloudflare Gateway/WARP/DNS enrollment. import test from 'node:test'; import assert from 'node:assert/strict'; +import {readFile} from 'node:fs/promises'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { Miniflare } from 'miniflare'; import { b64url, operations, signRequest } from './protocol.mjs'; +import bridgeWorker from './worker.mjs'; +import {gatewayFetch} from './gateway-fetch.mjs'; +import {BRIDGE_HOST,clearAccessKeyCacheForTests,verifyAccessServiceToken} from './access-auth.mjs'; const here = dirname(fileURLToPath(import.meta.url)); const host = 'private-bridge-staging.invalid'; const account = 'a'.repeat(32), policy = '11111111-1111-1111-1111-111111111111', posture = '22222222-2222-2222-2222-222222222222'; const email = 'synthetic-owner@example.invalid'; + +test('configured gateway direct-fetch adapter preserves the Cloudflare Access context',async()=>{ + const entrypoint=await readFile(new URL('./gateway.mjs',import.meta.url),'utf8'); + assert.match(entrypoint,/fetch\(request, env, ctx\)\s*\{\s*return gatewayFetch\(bridge, request, env, ctx\);/); + clearAccessKeyCacheForTests(); + const issuer='https://gateway-test.cloudflareaccess.com',audience='gateway-access-audience-1234567890'; + const clientId='gateway-caller-client',nowMs=Date.now(),seconds=Math.floor(nowMs/1000); + const rsa=await crypto.subtle.generateKey({name:'RSASSA-PKCS1-v1_5',modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:'SHA-256'},true,['sign','verify']); + const jwk=await crypto.subtle.exportKey('jwk',rsa.publicKey);Object.assign(jwk,{kid:'gateway-key',alg:'RS256',use:'sig'}); + const encode=value=>Buffer.from(JSON.stringify(value)).toString('base64url'); + const head=encode({alg:'RS256',typ:'JWT',kid:'gateway-key'}); + const claims=encode({type:'app',aud:[audience],exp:seconds+300,iat:seconds-1,iss:issuer,common_name:clientId,sub:''}); + const input=`${head}.${claims}`; + const signature=Buffer.from(await crypto.subtle.sign('RSASSA-PKCS1-v1_5',rsa.privateKey,new TextEncoder().encode(input))).toString('base64url'); + const request=new Request(`https://${BRIDGE_HOST}/v1/read`,{method:'POST',headers:{'cf-access-jwt-assertion':`${input}.${signature}`,'x-bridge-principal':'caller'}}); + const ed=await crypto.subtle.generateKey('Ed25519',true,['sign','verify']); + const principal={id:'caller',role:'caller',device:'amd',publicKey:b64url(await crypto.subtle.exportKey('raw',ed.publicKey)),accessClientId:clientId,scopes:[...operations],issuedAt:nowMs-1000,expiresAt:nowMs+600000,revoked:false}; + let received; + const env={ENABLED:'true',BRIDGE_HOST,ACCESS_ISSUER:issuer,ACCESS_AUDIENCE:audience,BRIDGE_REGISTRY:JSON.stringify({audience:'bridge-signing-audience',principals:[principal,{...principal,id:'device',role:'device',accessClientId:'gateway-device-client',publicKey:b64url(await crypto.subtle.exportKey('raw',(await crypto.subtle.generateKey('Ed25519',true,['sign','verify'])).publicKey))}]}),BRIDGE:{idFromName:id=>id,get:()=>({fetch:async req=>{received=req;return Response.json({ok:true});}})}}; + const ctx={access:{aud:audience}}; + await verifyAccessServiceToken(request,env,ctx,{fetchImpl:async()=>Response.json({keys:[jwk]}),nowMs}); + const response=await gatewayFetch(bridgeWorker,request,env,ctx); + assert.equal(response.status,200); + assert.equal(received.headers.get('x-bridge-principal'),'caller'); + assert.equal(received.headers.get('cf-access-jwt-assertion'),null); + assert.equal((await response.json()).ok,true); +}); const harnessSource = ` export default { async fetch(request, env) { From f1a6b9eaa6e965bfbb5777e187bfe77060b7bbd7 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 09:36:22 +0000 Subject: [PATCH 26/33] fix(bridge): make first deploy strictly unrouted --- .../private-laptop-bridge/ACCESS-STAGING.md | 6 +- pm-stack/private-laptop-bridge/README.md | 11 ++- pm-stack/private-laptop-bridge/STAGING.md | 72 +++++++++++-------- .../private-laptop-bridge/VERIFICATION.md | 20 +++++- .../cloudflare.config.ts | 10 +-- .../deployment-config.test.mjs | 4 +- ...ge-staging-bootstrap.workflow.yml.disabled | 22 ++---- .../release-artifact.mjs | 2 +- .../release-contract.mjs | 12 ++-- .../release-contract.test.mjs | 9 +++ .../staging-bootstrap.mjs | 22 +++--- .../staging-bootstrap.test.mjs | 20 ++++-- .../staging-preflight.json | 4 +- 13 files changed, 135 insertions(+), 79 deletions(-) diff --git a/pm-stack/private-laptop-bridge/ACCESS-STAGING.md b/pm-stack/private-laptop-bridge/ACCESS-STAGING.md index f6df521fcb..9e9d96fa6d 100644 --- a/pm-stack/private-laptop-bridge/ACCESS-STAGING.md +++ b/pm-stack/private-laptop-bridge/ACCESS-STAGING.md @@ -76,9 +76,13 @@ different route, so it is not used for this Worker control plane. ## Resource and identity checklist -- Worker: `private-laptop-bridge-staging`; fixed hostname above, Access app +- Routed Worker: `private-laptop-bridge-staging`; fixed hostname above, Access app restricted to service-token authentication, `workers_dev=false`, previews false, no schedules or other routes/domains. +- First `bridge-init` deployment has no custom hostname and blank Access + issuer/audience. Attaching the routed `bridge` configuration is a later + separately reviewed action after Access is configured and independently read + back. - Access issuer and audience: provisioned for that exact app, stored as non-secret Worker configuration from protected environment variables `CF_BRIDGE_ACCESS_ISSUER` and `CF_BRIDGE_ACCESS_AUDIENCE`. They are required diff --git a/pm-stack/private-laptop-bridge/README.md b/pm-stack/private-laptop-bridge/README.md index 6201e74f6b..000008211d 100644 --- a/pm-stack/private-laptop-bridge/README.md +++ b/pm-stack/private-laptop-bridge/README.md @@ -19,8 +19,10 @@ existing Turso-backed queue. No endpoint claims, dispatches, changes tasks, restarts services, reads arbitrary files, fetches arbitrary URLs, executes a command, or accepts scripts. Builds/tests are deliberately outside this version. -The Worker is default-disabled, has only the proposed fixed custom hostname, -workers.dev and preview URLs disabled, and contains no private keys. Device and caller identities are independently pinned +The routed `bridge` mode is default-disabled, has only the proposed fixed +custom hostname, and keeps workers.dev and preview URLs disabled. The separate +`bridge-init` mode has no ingress while the SQLite namespace is initialized. +Neither mode contains private keys. Device and caller identities are independently pinned public keys with separate roles, device binding, operation scopes, expiration and revocation. Possession of a device key does not grant caller permissions. A request signature covers its audience, endpoint, method, timestamp, nonce and @@ -221,7 +223,10 @@ JWT, maps its signed client ID to one principal, then forwards the independently signed request to the bridge. The earlier Gateway path is historical only; see [ACCESS-STAGING.md](ACCESS-STAGING.md) for the current no-WARP design. -The one-time disabled first-deployment workflow is a reviewed template with a +The one-time disabled first-deployment workflow uses the strict `bridge-init` +configuration mode: disabled SQLite initialization, no custom domain, blank +Access config, no routes or public previews. The routed `bridge` mode is a +separate Access-reviewed phase. The workflow is a reviewed template with a `.disabled` suffix outside `.github/workflows`; GitHub does not register it. It remains dormant until the exact protected environment, reviewer policy, source pin, immutable owner-created Worker ID, exact Access app and narrowly diff --git a/pm-stack/private-laptop-bridge/STAGING.md b/pm-stack/private-laptop-bridge/STAGING.md index 41c63301f0..2a5e76873c 100644 --- a/pm-stack/private-laptop-bridge/STAGING.md +++ b/pm-stack/private-laptop-bridge/STAGING.md @@ -19,11 +19,14 @@ are a separate synthetic smoke lifecycle and do not select or provision the bridge target. `cloudflare.config.ts` is the only deployment lifecycle source; no Wrangler JSONC deployment or migration fallback is kept. -The bridge config currently has `ENABLED=false`, empty registry and Gateway -placeholders, exactly one proposed Access hostname (`laptop-bridge-staging.security.cab`), -no routes or triggers, workers.dev and preview URLs disabled, 10 ms CPU limit, -and observability/logging/traces off. Access issuer/audience remain blank until -the exact app is independently verified. It binds the staging +The routed `bridge` config has `ENABLED=false`, empty registry and Gateway +placeholders, exactly one proposed Access hostname +(`laptop-bridge-staging.security.cab`), no routes or triggers, workers.dev and +preview URLs disabled, 10 ms CPU limit, and observability/logging/traces off. +The new `bridge-init` config instead has no custom hostname and blank Access +issuer/audience; it exists only for the separately gated SQLite first deploy. +Access issuer/audience in `bridge` remain blank until the exact app is +independently verified. Both modes bind the staging Worker to its own declarative SQLite `PrivateLaptopBridge` Durable Object export. The tracked `staging-preflight.json` remains `verified:false`, `exists:false`, with empty account, namespace and evidence IDs. Local config/build tests prove only @@ -44,8 +47,14 @@ Durable Object namespace. For first activation, the owner must first create only the fixed metadata-only Worker locally, read its immutable ID, and pin that ID in the protected `cloudflare-staging` environment. Actions must reject an absent Worker and any same-name/different-ID takeover; it must not receive -account-wide create permission. Only then could the same `cloudflare.config.ts` -`bridge` mode and pinned `cf` Build Output initialize the SQLite export. +account-wide create permission. The first SQLite initialization now has its +own `bridge-init` mode in `cloudflare.config.ts`: it keeps the disabled Worker +and SQLite export but renders `domains: []`, blank Access issuer/audience, +`workersDev:false`, preview URLs off, no routes/triggers, and no telemetry. The +separate `bridge` mode retains the proposed custom hostname and requires the +reviewed Access configuration. No initialization run may attach the hostname; +Access setup and any later hostname association require a separate reviewed +phase. This init object is not an Aster endpoint. [cf project deploy](https://developers.cloudflare.com/cf/projects/) · [cf and Durable Object lifecycle](https://developers.cloudflare.com/cf/wrangler/reference/#convert-durable-object-migrations) @@ -68,20 +77,20 @@ reviewer, disallow self-review, allow only `main`, and pin the exact reviewed full source SHA and immutable Worker ID. The template fails closed if any part is missing or differs. -The deploy job runs the local build and pinned `cf deploy --dry-run`, verifies -the effective disabled Build Output, then uses separate read-only and -write-only credentials. Before its only possible provider write, read-only +The deploy job runs the `bridge-init` build and pinned `cf deploy --dry-run`, +verifies the effective disabled, no-domain Build Output, then uses separate +read-only and write-only credentials. Before its only possible provider write, read-only checks inventory the full account zone set and every zone's Worker routes, account Worker domains, the pinned Worker ID and SQLite namespace, schedules, subdomain/preview flags, settings, versions and deployments. It refuses an unknown or partial inventory, any unexpected route/domain, an orphan namespace, an absent or mismatched Worker ID, shared read/write tokens, or any effective config that differs from the disabled artifact. Only an exact, precreated -metadata-only Worker with zero deployments and no domain/namespace can proceed. -A second read-only pass checks the exact serving version, single 100-percent -deployment, source-SHA tag, disabled settings, the sole approved host with -preview routing off, and the same SQLite namespace ID in the export and account -inventory. It never changes Gateway or routes. +metadata-only Worker with zero deployments, zero domain references, and no +namespace can proceed. A second read-only pass proves that the deployment is +disabled, has the exact source-SHA version and SQLite namespace binding, and +still has zero custom domains and reverse domain references. It never changes +Gateway or routes. The checked-in template has not been registered, dispatched, or run against Cloudflare. The current protected environment, reviewer IDs, exact account, @@ -91,8 +100,10 @@ available in this checkout. Their secret values were not accessed. The pinned Worker, and whether an Individual Workers Editor can perform that exact operation without changing other state, have not been verified against Cloudflare. Do not claim compatibility or enable the workflow until that exact -provider contract is confirmed. It has no fallback that creates a Worker or -silently changes its identity. +provider contract is confirmed. The no-domain payload only closes the initial +ingress gap; it does not create the Access app or provide a later domain-attach +workflow. It has no fallback that creates a Worker or silently changes its +identity. The read credential needs complete account zone/route inventory, Worker metadata/settings/versions/deployments/domains, and Durable Object namespace read. If those exact read scopes or an individual Worker write scope cannot be @@ -102,20 +113,23 @@ The offline command sequence the workflow will use is: ```sh npm ci --ignore-scripts --no-audit --no-fund -./node_modules/.bin/cf build --mode bridge -./node_modules/.bin/cf deploy --mode bridge --prebuilt --dry-run +./node_modules/.bin/cf build --mode bridge-init +./node_modules/.bin/cf deploy --mode bridge-init --prebuilt --dry-run # The live command exists only in the dormant, environment-gated workflow. # Never run it from a developer checkout. ``` -The final command writes a deployment, may attach the exact approved custom -hostname, and provisions the `PrivateLaptopBridge` SQLite export. It must run -only with `ENABLED=false`, empty Gateway IDs and registry, no runtime secrets, -no routes or extra domains/triggers, `workersDev:false`, +The dormant first-deploy workflow instead uses `cf build --mode bridge-init` +and `cf deploy --mode bridge-init --prebuilt --provision`. This writes a +disabled, unrouted version and provisions the `PrivateLaptopBridge` SQLite +export without a custom hostname. It must run only with `ENABLED=false`, empty +Access and Gateway configuration, empty registry, no runtime secrets, no routes, +domains, or triggers, `workersDev:false`, `previewUrls:false`, logs/traces off, and the 10 ms CPU limit from the reviewed -build. Do not pass `--force`, `--secrets-file`, or `--dispatch-namespace`. A -successful local `--dry-run` proves config shape only; it is not permission to -run the write. +build. The separate `bridge` mode is reserved for a later phase after Access +policy and the custom hostname have been independently verified. Do not pass +`--force`, `--secrets-file`, or `--dispatch-namespace`. A successful local +`--dry-run` proves config shape only; it is not permission to run the write. Before the write, the protected workflow's separate read-only credential must confirm the exact account and that the exact Worker name is absent; inventory @@ -131,9 +145,9 @@ changing it. Immediately after the write, independently repeat the full zone/route and Worker inventory and verify the same Worker identity and account, no -routes/schedules, only the exact approved custom domain with previews disabled, -no Gateway binding, workers.dev and preview URLs disabled, no runtime secrets, -and the exact disabled variables and resource limits. This is not proof about +routes/schedules, no custom domain or Worker domain reference, no Gateway +binding, workers.dev and preview URLs disabled, no runtime secrets, and the +exact disabled variables and resource limits. This is not proof about account-level Gateway rules or caller identity. Verify the Worker's declarative export is `PrivateLaptopBridge` with `state=created` and diff --git a/pm-stack/private-laptop-bridge/VERIFICATION.md b/pm-stack/private-laptop-bridge/VERIFICATION.md index 7253c59a7e..65562ff407 100644 --- a/pm-stack/private-laptop-bridge/VERIFICATION.md +++ b/pm-stack/private-laptop-bridge/VERIFICATION.md @@ -344,7 +344,8 @@ custom domain or namespace; deployed readback requires only the exact proposed host with preview routing disabled and the same immutable Worker ID. CI has no account-wide create credential. -Current local checks on this working tree: +Historical local checks from the earlier bridge-mode draft (not evidence for the +current source head): ```text npm test @@ -378,3 +379,20 @@ Access application, two service identities, public-key registry, exact hostname, protected environment/reviewer set, and laptop/Aster network/runtime path also remain owner-side prerequisites. Keep all workflows dormant until these are independently verified. + +## Follow-up: no-ingress first-deploy mode — 2026-11-23 + +The first-deploy template now uses a separate `bridge-init` mode. Its rendered +Worker payload must have `domains: []`, blank Access issuer/audience, disabled +service, no routes/triggers, workers.dev/previews off, and the declared SQLite +export. The init postflight requires zero account domains and Worker reverse +domain references, plus the exact disabled source-tagged version and namespace. +The routed `bridge` mode remains separate; no Access setup or hostname attach +workflow was added. `private-laptop-bridge-staging-bootstrap.workflow.yml.disabled` +remains outside `.github/workflows` and was not dispatched. + +This source update has not been tested locally. The hosted `npm test` run for +the preceding Gateway-context revision `b58e91a345d738a3c364c7adb8fbc1852312d067` +failed at its execute step; the run log endpoint returned 403, so the exact test +failure is not known. It does not verify this follow-up source. A distinct +remote-only guard test/build is required on the eventual pushed head. diff --git a/pm-stack/private-laptop-bridge/cloudflare.config.ts b/pm-stack/private-laptop-bridge/cloudflare.config.ts index d5747182bd..22363a89d3 100644 --- a/pm-stack/private-laptop-bridge/cloudflare.config.ts +++ b/pm-stack/private-laptop-bridge/cloudflare.config.ts @@ -16,10 +16,12 @@ const isolated = () => ({ // until owner-approved account, namespace, Gateway, and laptop preflight is // complete. // The default mode exists only for the separately managed synthetic smoke Worker. -export default defineConfig(({mode}) => mode === 'bridge' ? ({ +export default defineConfig(({mode}) => mode === 'bridge' || mode === 'bridge-init' ? ({ worker: { ...isolated(), - domains: [BRIDGE_HOST], + // The first SQLite namespace initialization must have no custom hostname. + // `bridge` is reserved for the separately Access-reviewed routed release. + domains: mode === 'bridge-init' ? [] : [BRIDGE_HOST], name: 'private-laptop-bridge-staging', compatibilityDate: '2026-07-30', entrypoint: bridge, @@ -30,8 +32,8 @@ export default defineConfig(({mode}) => mode === 'bridge' ? ({ GATEWAY_ACCOUNT_ID: bindings.text(''), GATEWAY_POLICY_ID: bindings.text(''), GATEWAY_IDENTITY_EMAIL: bindings.text(''), GATEWAY_POSTURE_ID: bindings.text(''), BRIDGE_HOST: bindings.text(BRIDGE_HOST), - ACCESS_ISSUER: bindings.text(process.env.CF_BRIDGE_ACCESS_ISSUER ?? ''), - ACCESS_AUDIENCE: bindings.text(process.env.CF_BRIDGE_ACCESS_AUDIENCE ?? ''), + ACCESS_ISSUER: bindings.text(mode === 'bridge-init' ? '' : process.env.CF_BRIDGE_ACCESS_ISSUER ?? ''), + ACCESS_AUDIENCE: bindings.text(mode === 'bridge-init' ? '' : process.env.CF_BRIDGE_ACCESS_AUDIENCE ?? ''), BRIDGE_REGISTRY: bindings.text(''), BRIDGE: bindings.durableObject({worker: 'private-laptop-bridge-staging', exportName: 'PrivateLaptopBridge'}), }, diff --git a/pm-stack/private-laptop-bridge/deployment-config.test.mjs b/pm-stack/private-laptop-bridge/deployment-config.test.mjs index bcab05662b..5ca9f6115e 100644 --- a/pm-stack/private-laptop-bridge/deployment-config.test.mjs +++ b/pm-stack/private-laptop-bridge/deployment-config.test.mjs @@ -7,7 +7,9 @@ const read = name => readFile(new URL(name, import.meta.url), 'utf8'); test('cf declarative bridge config is the sole lifecycle source and remains disabled', async () => { const config = await read('./cloudflare.config.ts'); assert.match(config, /name:\s*'private-laptop-bridge-staging'/); - assert.match(config, /mode\s*===\s*'bridge'/); + assert.match(config, /mode\s*===\s*'bridge'\s*\|\|\s*mode\s*===\s*'bridge-init'/); + assert.match(config, /domains:\s*mode\s*===\s*'bridge-init'\s*\?\s*\[\]\s*:\s*\[BRIDGE_HOST\]/); + assert.match(config, /ACCESS_ISSUER:\s*bindings\.text\(mode\s*===\s*'bridge-init'\s*\?\s*''/); assert.match(config, /entrypoint:\s*bridge/); assert.match(config, /PrivateLaptopBridge:\s*exports\.durableObject\(\{storage:\s*'sqlite'\}\)/); assert.match(config, /BRIDGE:\s*bindings\.durableObject\(\{worker:\s*'private-laptop-bridge-staging',\s*exportName:\s*'PrivateLaptopBridge'\}\)/); diff --git a/pm-stack/private-laptop-bridge/private-laptop-bridge-staging-bootstrap.workflow.yml.disabled b/pm-stack/private-laptop-bridge/private-laptop-bridge-staging-bootstrap.workflow.yml.disabled index 7fed390a92..cb288f4853 100644 --- a/pm-stack/private-laptop-bridge/private-laptop-bridge-staging-bootstrap.workflow.yml.disabled +++ b/pm-stack/private-laptop-bridge/private-laptop-bridge-staging-bootstrap.workflow.yml.disabled @@ -46,9 +46,6 @@ jobs: if: needs.verify-environment-before-assignment.result == 'success' && needs.verify-environment-before-assignment.outputs.environment == 'cloudflare-staging' environment: name: ${{ needs.verify-environment-before-assignment.outputs.environment }} - env: - CF_BRIDGE_ACCESS_ISSUER: ${{ vars.CF_BRIDGE_ACCESS_ISSUER }} - CF_BRIDGE_ACCESS_AUDIENCE: ${{ vars.CF_BRIDGE_ACCESS_AUDIENCE }} runs-on: ubuntu-24.04 timeout-minutes: 25 steps: @@ -76,15 +73,12 @@ jobs: run: npm ci --ignore-scripts --no-audit --no-fund - name: Verify disabled bridge build and deploy dry run working-directory: pm-stack/private-laptop-bridge - env: - CF_BRIDGE_ACCESS_ISSUER: ${{ vars.CF_BRIDGE_ACCESS_ISSUER }} - CF_BRIDGE_ACCESS_AUDIENCE: ${{ vars.CF_BRIDGE_ACCESS_AUDIENCE }} run: | set -euo pipefail node --test deployment-config.test.mjs release-contract.test.mjs staging-bootstrap.test.mjs - ./node_modules/.bin/cf build --mode bridge - ./node_modules/.bin/cf deploy --mode bridge --prebuilt --dry-run > "$RUNNER_TEMP/bridge-deploy-dry-run.log" 2>&1 - node staging-bootstrap.mjs validate-build + ./node_modules/.bin/cf build --mode bridge-init + ./node_modules/.bin/cf deploy --mode bridge-init --prebuilt --dry-run > "$RUNNER_TEMP/bridge-init-dry-run.log" 2>&1 + BUILD_MODE=bridge-init node staging-bootstrap.mjs validate-build - name: Read current provider state and require absence or exact inert namespace id: provider working-directory: pm-stack/private-laptop-bridge @@ -94,8 +88,6 @@ jobs: CF_BRIDGE_ZONE_IDS: ${{ secrets.CF_BRIDGE_ZONE_IDS }} CF_BRIDGE_READ_TOKEN: ${{ secrets.CF_BRIDGE_READ_TOKEN }} CF_BRIDGE_GATEWAY_READ_TOKEN: ${{ secrets.CF_BRIDGE_GATEWAY_READ_TOKEN }} - CF_BRIDGE_ACCESS_ISSUER: ${{ vars.CF_BRIDGE_ACCESS_ISSUER }} - CF_BRIDGE_ACCESS_AUDIENCE: ${{ vars.CF_BRIDGE_ACCESS_AUDIENCE }} GITHUB_SHA: ${{ github.sha }} run: node staging-bootstrap.mjs preflight - name: Deploy only the pinned disabled declarative Worker and SQLite export @@ -107,12 +99,10 @@ jobs: CF_BRIDGE_API_TOKEN: ${{ secrets.CF_BRIDGE_API_TOKEN }} CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CF_BRIDGE_ACCOUNT_ID }} CLOUDFLARE_API_TOKEN: ${{ secrets.CF_BRIDGE_API_TOKEN }} - CF_BRIDGE_ACCESS_ISSUER: ${{ vars.CF_BRIDGE_ACCESS_ISSUER }} - CF_BRIDGE_ACCESS_AUDIENCE: ${{ vars.CF_BRIDGE_ACCESS_AUDIENCE }} run: | set -euo pipefail node staging-bootstrap.mjs assert-distinct-credentials - ./node_modules/.bin/cf deploy --mode bridge --prebuilt --provision --tag "$GITHUB_SHA" --message "disabled bridge first deployment $GITHUB_SHA" > "$RUNNER_TEMP/bridge-deploy.log" 2>&1 + ./node_modules/.bin/cf deploy --mode bridge-init --prebuilt --provision --tag "$GITHUB_SHA" --message "disabled bridge no-ingress initialization $GITHUB_SHA" > "$RUNNER_TEMP/bridge-init-deploy.log" 2>&1 - name: Independently verify no ingress and exact serving namespace if: steps.provider.outputs.status == 'deploy' working-directory: pm-stack/private-laptop-bridge @@ -122,7 +112,5 @@ jobs: CF_BRIDGE_ZONE_IDS: ${{ secrets.CF_BRIDGE_ZONE_IDS }} CF_BRIDGE_READ_TOKEN: ${{ secrets.CF_BRIDGE_READ_TOKEN }} CF_BRIDGE_GATEWAY_READ_TOKEN: ${{ secrets.CF_BRIDGE_GATEWAY_READ_TOKEN }} - CF_BRIDGE_ACCESS_ISSUER: ${{ vars.CF_BRIDGE_ACCESS_ISSUER }} - CF_BRIDGE_ACCESS_AUDIENCE: ${{ vars.CF_BRIDGE_ACCESS_AUDIENCE }} GITHUB_SHA: ${{ github.sha }} - run: node staging-bootstrap.mjs postflight + run: node staging-bootstrap.mjs init-postflight diff --git a/pm-stack/private-laptop-bridge/release-artifact.mjs b/pm-stack/private-laptop-bridge/release-artifact.mjs index 1488289e51..7f42ac20d3 100644 --- a/pm-stack/private-laptop-bridge/release-artifact.mjs +++ b/pm-stack/private-laptop-bridge/release-artifact.mjs @@ -24,7 +24,7 @@ if(action==='preflight') { const worker=required('TARGET_WORKER'), mode=required('TARGET_MODE'); assertDryRunPayload(await readFile(required('DRY_RUN_OUTPUT'),'utf8'),{worker,mode}); const metadata=await json(resolve(root,'.cloudflare/output/v1/config.json')); - if(metadata.producer?.name!=='wrangler'||metadata.producer?.version!=='4.166.0'||metadata.buildContext?.mode!==(mode==='bridge'?'bridge':undefined)) throw new Error('Build Output producer or mode does not match pinned release'); + if(metadata.producer?.name!=='wrangler'||metadata.producer?.version!=='4.166.0'||metadata.buildContext?.mode!==(mode==='default'?undefined:mode)) throw new Error('Build Output producer or mode does not match pinned release'); const payload=await json(resolve(root,'.cloudflare/output/v1/workers/default/worker.config.json')); assertEffectivePayload(payload,{worker,mode}); console.log('effective Build Output validated for '+worker); diff --git a/pm-stack/private-laptop-bridge/release-contract.mjs b/pm-stack/private-laptop-bridge/release-contract.mjs index bcf14a0fd8..1bedfde434 100644 --- a/pm-stack/private-laptop-bridge/release-contract.mjs +++ b/pm-stack/private-laptop-bridge/release-contract.mjs @@ -193,7 +193,7 @@ export function assertPreflight(proof,{accountId,worker,environment,now=Date.now export function assertDryRunPayload(text,{worker,mode}) { if(typeof text!=='string'||!text.includes('--dry-run: exiting now.')) fail('cf prebuilt dry-run did not complete successfully'); if(worker==='private-laptop-bridge-staging') { - if(mode!=='bridge'||!text.includes('env.BRIDGE (PrivateLaptopBridge')||!text.includes('env.ENABLED ("false")')||!text.includes('env.BRIDGE_REGISTRY ("")')) fail('effective bridge Build Output does not match disabled DO target'); + if(!['bridge','bridge-init'].includes(mode)||!text.includes('env.BRIDGE (PrivateLaptopBridge')||!text.includes('env.ENABLED ("false")')||!text.includes('env.BRIDGE_REGISTRY ("")')) fail('effective bridge Build Output does not match disabled DO target'); } else if(worker==='private-laptop-bridge-smoke') { if(mode!=='default'||!text.includes('env.ENABLED ("false")')||!text.includes('env.GATEWAY_HOST ("private-bridge-smoke.invalid")')) fail('effective smoke Build Output does not match disabled target'); } else fail('unknown Worker in Build Output verification'); @@ -202,13 +202,15 @@ export function assertDryRunPayload(text,{worker,mode}) { export function assertEffectivePayload(config,{worker,mode,accessIssuer=process.env.CF_BRIDGE_ACCESS_ISSUER??'',accessAudience=process.env.CF_BRIDGE_ACCESS_AUDIENCE??''}) { const bridge=worker==='private-laptop-bridge-staging'; + const bridgeInit=bridge&&mode==='bridge-init'; const smoke=worker==='private-laptop-bridge-smoke'; - if((!bridge&&!smoke)||(bridge&&mode!=='bridge')||(smoke&&mode!=='default')) fail('Build Output mode does not match the fixed target'); - if(bridge&&!validAccess(accessIssuer,accessAudience)) fail('bridge Build Output requires the exact protected Access issuer and audience'); + if((!bridge&&!smoke)||(bridge&&!['bridge','bridge-init'].includes(mode))||(smoke&&mode!=='default')) fail('Build Output mode does not match the fixed target'); + if(bridge&&!bridgeInit&&!validAccess(accessIssuer,accessAudience)) fail('bridge Build Output requires the exact protected Access issuer and audience'); + if(bridgeInit&&(accessIssuer!==''||accessAudience!=='')) fail('first-deploy Build Output must not contain Access configuration before ingress is separately approved'); const common={ name:worker, compatibilityDate:'2026-07-30', - domains:bridge?[BRIDGE_HOST]:[], + domains:bridge&&!bridgeInit?[BRIDGE_HOST]:[], triggers:[], limits:{cpuMs:10}, observability:{enabled:false,logs:{enabled:false},traces:{enabled:false}}, @@ -217,7 +219,7 @@ export function assertEffectivePayload(config,{worker,mode,accessIssuer=process. }; const variables=bridge?{ ENABLED:'false',GATEWAY_HOST:'private-bridge-staging.invalid',GATEWAY_ACCOUNT_ID:'',GATEWAY_POLICY_ID:'', - GATEWAY_IDENTITY_EMAIL:'',GATEWAY_POSTURE_ID:'',BRIDGE_HOST,ACCESS_ISSUER:accessIssuer,ACCESS_AUDIENCE:accessAudience,BRIDGE_REGISTRY:'', + GATEWAY_IDENTITY_EMAIL:'',GATEWAY_POSTURE_ID:'',BRIDGE_HOST,ACCESS_ISSUER:bridgeInit?'':accessIssuer,ACCESS_AUDIENCE:bridgeInit?'':accessAudience,BRIDGE_REGISTRY:'', }:{ ENABLED:'false',GATEWAY_HOST:'private-bridge-smoke.invalid',GATEWAY_ACCOUNT_ID:'',GATEWAY_POLICY_ID:'',START_MS:'',END_MS:'', }; diff --git a/pm-stack/private-laptop-bridge/release-contract.test.mjs b/pm-stack/private-laptop-bridge/release-contract.test.mjs index e5dcad9f80..6657b167bd 100644 --- a/pm-stack/private-laptop-bridge/release-contract.test.mjs +++ b/pm-stack/private-laptop-bridge/release-contract.test.mjs @@ -163,6 +163,7 @@ test('tracked preflight fixture is redacted and never substitutes for private ow test('CI dry-run verifies the effective private Build Output but does not claim account route proof',()=>{ const bridge='env.BRIDGE (PrivateLaptopBridge, defined in private-laptop-bridge-staging)\nenv.ENABLED ("false")\nenv.BRIDGE_REGISTRY ("")\n--dry-run: exiting now.'; assert.equal(assertDryRunPayload(bridge,{worker:'private-laptop-bridge-staging',mode:'bridge'}),true); + assert.equal(assertDryRunPayload(bridge,{worker:'private-laptop-bridge-staging',mode:'bridge-init'}),true); assert.throws(()=>assertDryRunPayload(bridge.replace('env.ENABLED ("false")','env.ENABLED ("true")'),{worker:'private-laptop-bridge-staging',mode:'bridge'})); assert.throws(()=>assertDryRunPayload(bridge.replace('env.BRIDGE (','env.OTHER ('),{worker:'private-laptop-bridge-staging',mode:'bridge'})); assert.throws(()=>assertDryRunPayload('no output',{worker:'private-laptop-bridge-staging',mode:'bridge'})); @@ -176,6 +177,14 @@ test('effective Build Output explicitly fixes CPU, observability, routes, previe for(const mutation of [x=>x.limits.cpuMs=30,x=>x.observability.enabled=true,x=>x.workersDev=true,x=>x.previewUrls=true,x=>x.domains.push('public.example'),x=>x.triggers.push({route:'public.example/*'}),x=>x.env.ENABLED.value='true',x=>x.env.EXTRA={type:'text',value:'secret'},x=>x.env.BRIDGE.worker='other-worker',x=>x.exports.PrivateLaptopBridge.storage='kv',x=>x.forwardPolicies=['unexpected']]) { const mutated=structuredClone(base); mutation(mutated); assert.throws(()=>assertEffectivePayload(mutated,bridgeArgs)); } + const bridgeInit=structuredClone(base); + bridgeInit.domains=[]; + bridgeInit.env.ACCESS_ISSUER.value=''; + bridgeInit.env.ACCESS_AUDIENCE.value=''; + assert.equal(assertEffectivePayload(bridgeInit,{worker:'private-laptop-bridge-staging',mode:'bridge-init',accessIssuer:'',accessAudience:''}),true); + for(const mutation of [x=>x.domains.push(BRIDGE_HOST),x=>x.workersDev=true,x=>x.previewUrls=true,x=>x.env.ENABLED.value='true',x=>x.env.ACCESS_ISSUER.value='https://team.cloudflareaccess.com',x=>x.env.ACCESS_AUDIENCE.value='audience-with-exact-length-012345',x=>x.triggers.push({route:'public.example/*'})]) { + const mutated=structuredClone(bridgeInit);mutation(mutated);assert.throws(()=>assertEffectivePayload(mutated,{worker:'private-laptop-bridge-staging',mode:'bridge-init',accessIssuer:'',accessAudience:''})); + } const smoke={name:'private-laptop-bridge-smoke',compatibilityDate:'2026-07-30',domains:[],triggers:[],limits:{cpuMs:10},observability:{enabled:false,logs:{enabled:false},traces:{enabled:false}},workersDev:false,previewUrls:false,env:{ENABLED:{type:'text',value:'false'},GATEWAY_HOST:{type:'text',value:'private-bridge-smoke.invalid'},GATEWAY_ACCOUNT_ID:{type:'text',value:''},GATEWAY_POLICY_ID:{type:'text',value:''},START_MS:{type:'text',value:''},END_MS:{type:'text',value:''}},manifest:{type:'complete',mainModule:'smoke.js',modules:{'smoke.js':{type:'esm'},'smoke.js.map':{type:'sourcemap'}}}}; assert.equal(assertEffectivePayload(smoke,{worker:'private-laptop-bridge-smoke',mode:'default'}),true); for(const mutated of [{...smoke,exports:{}},{...smoke,env:{...smoke.env,BRIDGE:{type:'durable-object'}}},{...smoke,observability:{enabled:true}}]) assert.throws(()=>assertEffectivePayload(mutated,{worker:'private-laptop-bridge-smoke',mode:'default'})); diff --git a/pm-stack/private-laptop-bridge/staging-bootstrap.mjs b/pm-stack/private-laptop-bridge/staging-bootstrap.mjs index d39680e38c..1b012e2504 100644 --- a/pm-stack/private-laptop-bridge/staging-bootstrap.mjs +++ b/pm-stack/private-laptop-bridge/staging-bootstrap.mjs @@ -322,7 +322,7 @@ async function readSnapshot({accountId, token, gatewayToken, expectedZoneIds, fe } export function verifyProviderState(snapshot, {phase, expectedZoneIds, sourceSha, expectedWorkerId}) { - if (!['preflight', 'postflight'].includes(phase)) fail('provider verification phase is invalid'); + if (!['preflight', 'init-postflight', 'postflight'].includes(phase)) fail('provider verification phase is invalid'); const expected = parseIds(expectedZoneIds, 'approved zone inventory'); if (!snapshot || !Array.isArray(snapshot.namespaces) || !Array.isArray(snapshot.domains) || !Array.isArray(snapshot.zoneIds) || snapshot.zoneIds.length !== expected.length || snapshot.zoneIds.some((id, index) => id !== expected[index])) fail('provider inventory snapshot is incomplete or has the wrong account zones'); @@ -333,6 +333,7 @@ export function verifyProviderState(snapshot, {phase, expectedZoneIds, sourceSha if (Array.isArray(snapshot.deployments) && snapshot.deployments.length === 0) { exactBridgeDomains(snapshot.domains, {deployed: false, zoneIds: expected}); if (phase !== 'preflight' || snapshot.namespaces.length !== 0 || + snapshot.worker.references.domains.length !== 0 || snapshot.subdomain?.enabled !== false || snapshot.subdomain?.previews_enabled !== false || !Array.isArray(snapshot.schedules) || snapshot.schedules.length !== 0 || !snapshot.settings || snapshot.settings.logpush !== false || snapshot.settings.observability?.enabled !== false || @@ -347,7 +348,9 @@ export function verifyProviderState(snapshot, {phase, expectedZoneIds, sourceSha snapshot.settings?.observability?.enabled !== false || !Array.isArray(snapshot.settings?.tail_consumers) || snapshot.settings.tail_consumers.length !== 0) { fail('existing Worker is not fully verified as disabled and serving safely'); } - exactBridgeDomains(snapshot.domains, {deployed: true, zoneIds: expected}); + const noIngress=phase==='init-postflight'||phase==='preflight'; + exactBridgeDomains(snapshot.domains, {deployed: !noIngress, zoneIds: expected}); + if(noIngress&&snapshot.worker.references.domains.length!==0) fail('no-ingress Worker still has a reverse domain reference'); if (snapshot.namespaces.length !== 1) fail('existing Worker SQLite namespace inventory is unexpected'); const namespace = snapshot.namespaces[0]; if (!ID.test(namespace?.id ?? '') && !UUID.test(namespace?.id ?? '')) fail('Durable Object namespace ID is invalid'); @@ -360,7 +363,7 @@ export function verifyProviderState(snapshot, {phase, expectedZoneIds, sourceSha if (!/^[a-f0-9]{40}$/.test(sourceSha ?? '') || snapshot.version.annotations?.['workers/tag'] !== sourceSha) { fail('latest serving version is not tagged to this exact reviewed source SHA'); } - return phase === 'preflight' ? 'already-ready' : 'verified'; + return phase === 'preflight' ? 'already-initialized-no-ingress' : noIngress ? 'verified-no-ingress' : 'verified'; } export async function verifyBootstrapPreflight({accountId, workerId, readToken, gatewayToken, expectedZoneIds, sourceSha, fetchImpl = fetch}) { @@ -378,12 +381,12 @@ export function verifyDistinctWriteCredential(readToken, gatewayToken, writeToke return true; } -export async function verifyBootstrapPostflight({accountId, workerId, readToken, gatewayToken, expectedZoneIds, sourceSha, fetchImpl = fetch}) { +export async function verifyBootstrapPostflight({accountId, workerId, readToken, gatewayToken, expectedZoneIds, sourceSha, phase='postflight', fetchImpl = fetch}) { if (!ID.test(accountId ?? '') || typeof readToken !== 'string' || readToken.length < 20 || typeof gatewayToken !== 'string' || gatewayToken.length < 20 || readToken === gatewayToken) fail('protected read-only provider identities are missing'); const zones = parseIds(expectedZoneIds, 'approved zone inventory'); const snapshot = await readSnapshot({accountId, token: readToken, gatewayToken, expectedZoneIds: zones, fetchImpl}); - return verifyProviderState(snapshot, {phase: 'postflight', expectedZoneIds: zones, sourceSha, expectedWorkerId: workerId}); + return verifyProviderState(snapshot, {phase, expectedZoneIds: zones, sourceSha, expectedWorkerId: workerId}); } export async function validateLocalBuild({buildOutput, mode = 'bridge'}) { @@ -438,7 +441,7 @@ async function providerCheck(phase) { : await verifyBootstrapPostflight({accountId: process.env.CF_BRIDGE_ACCOUNT_ID, workerId: process.env.CF_BRIDGE_WORKER_ID, readToken: process.env.CF_BRIDGE_READ_TOKEN, gatewayToken: process.env.CF_BRIDGE_GATEWAY_READ_TOKEN, expectedZoneIds: process.env.CF_BRIDGE_ZONE_IDS, - sourceSha: process.env.GITHUB_SHA}); + sourceSha: process.env.GITHUB_SHA,phase}); if (phase === 'preflight') { if (!path) fail('workflow output channel is unavailable'); await writeFile(path, `status=${result}\n`, {flag: 'a', mode: 0o600}); @@ -448,18 +451,19 @@ async function providerCheck(phase) { async function main() { const [command, ...args] = process.argv.slice(2); - if (args.length !== 0) fail(`usage: staging-bootstrap.mjs `); + if (args.length !== 0) fail(`usage: staging-bootstrap.mjs `); if (command === 'github-environment-bootstrap') await githubEnvironmentGate('bootstrap'); else if (command === 'github-environment-release') await githubEnvironmentGate('release'); else if (command === 'preflight') await providerCheck('preflight'); + else if (command === 'init-postflight') await providerCheck('init-postflight'); else if (command === 'postflight') await providerCheck('postflight'); else if (command === 'assert-distinct-credentials') { verifyDistinctWriteCredential(process.env.CF_BRIDGE_READ_TOKEN, process.env.CF_BRIDGE_GATEWAY_READ_TOKEN, process.env.CF_BRIDGE_API_TOKEN); console.log('separate read and write credentials verified'); } - else if (command === 'validate-build') await validateLocalBuild({buildOutput: process.env.BUILD_OUTPUT ?? '.cloudflare/output/v1'}); - else fail('usage: staging-bootstrap.mjs '); + else if (command === 'validate-build') await validateLocalBuild({buildOutput: process.env.BUILD_OUTPUT ?? '.cloudflare/output/v1',mode:process.env.BUILD_MODE??'bridge'}); + else fail('usage: staging-bootstrap.mjs '); } if (process.argv[1] && new URL(import.meta.url).pathname === process.argv[1]) { diff --git a/pm-stack/private-laptop-bridge/staging-bootstrap.test.mjs b/pm-stack/private-laptop-bridge/staging-bootstrap.test.mjs index c89f085526..44c0cc9ce9 100644 --- a/pm-stack/private-laptop-bridge/staging-bootstrap.test.mjs +++ b/pm-stack/private-laptop-bridge/staging-bootstrap.test.mjs @@ -54,8 +54,6 @@ test('first-deploy workflow remains dormant, fixed-target, and checks protection assert.match(workflow,/needs: verify-environment-before-assignment/); assert.match(workflow,/CF_BRIDGE_RELEASE_REVIEWER_IDS: \$\{\{ vars\.CF_BRIDGE_RELEASE_REVIEWER_IDS \}\}/); assert.match(workflow,/CF_BRIDGE_WORKER_ID: \$\{\{ vars\.CF_BRIDGE_WORKER_ID \}\}/); - assert.match(workflow,/CF_BRIDGE_ACCESS_ISSUER: \$\{\{ vars\.CF_BRIDGE_ACCESS_ISSUER \}\}/); - assert.match(workflow,/CF_BRIDGE_ACCESS_AUDIENCE: \$\{\{ vars\.CF_BRIDGE_ACCESS_AUDIENCE \}\}/); const gate=workflow.split(' deploy-disabled-bridge:',1)[0]; assert.doesNotMatch(gate,/secrets\./); const provider=workflow.split(' - name: Read current provider state')[1].split(' - name: Deploy only')[0]; @@ -63,7 +61,11 @@ test('first-deploy workflow remains dormant, fixed-target, and checks protection assert.match(provider,/CF_BRIDGE_WORKER_ID: \$\{\{ vars\.CF_BRIDGE_WORKER_ID \}\}/); assert.doesNotMatch(workflow,/CF_BRIDGE_BOOTSTRAP_WRITE_TOKEN|CF_BRIDGE_BOOTSTRAP_ACCOUNT_ID/); assert.match(workflow,/staging-bootstrap\.mjs assert-distinct-credentials/); - assert.match(workflow,/cf deploy --mode bridge --prebuilt --provision --tag "\$GITHUB_SHA"/); + assert.match(workflow,/cf build --mode bridge-init/); + assert.match(workflow,/cf deploy --mode bridge-init --prebuilt --provision --tag "\$GITHUB_SHA"/); + assert.match(workflow,/node staging-bootstrap\.mjs init-postflight/); + assert.doesNotMatch(workflow,/cf deploy --mode bridge --prebuilt --provision/); + assert.doesNotMatch(workflow,/CF_BRIDGE_ACCESS_ISSUER|CF_BRIDGE_ACCESS_AUDIENCE/); assert.doesNotMatch(workflow,/wrangler deploy|workers versions (create|deploy)|--dispatch-namespace/); for(const fixed of [WORKER_NAME,'CF_BRIDGE_ACCOUNT_ID','CF_BRIDGE_ZONE_IDS',ENVIRONMENT_NAME]) assert.ok(workflow.includes(fixed)); }); @@ -156,10 +158,16 @@ test('exact empty locally created Worker is the only first-deploy candidate; all assert.throws(()=>verifyDistinctWriteCredential(readToken,gatewayToken,gatewayToken),/separate/); }); -test('existing Worker is a no-op only when disabled ingress, exact SQLite namespace, binding and serving version agree',()=>{ +test('bootstrap only accepts disabled no-ingress state; routed postflight verifies the Access-host phase',()=>{ const good=snapshot(); - assert.equal(verifyProviderState(good,{phase:'preflight',expectedZoneIds:[zoneId],sourceSha:sha,expectedWorkerId:workerId}),'already-ready'); + assert.throws(()=>verifyProviderState(good,{phase:'preflight',expectedZoneIds:[zoneId],sourceSha:sha,expectedWorkerId:workerId}),/empty Worker already has a custom domain/); assert.equal(verifyProviderState(good,{phase:'postflight',expectedZoneIds:[zoneId],sourceSha:sha,expectedWorkerId:workerId}),'verified'); + const noIngress=snapshot();noIngress.domains=[]; + assert.equal(verifyProviderState(noIngress,{phase:'preflight',expectedZoneIds:[zoneId],sourceSha:sha,expectedWorkerId:workerId}),'already-initialized-no-ingress'); + assert.equal(verifyProviderState(noIngress,{phase:'init-postflight',expectedZoneIds:[zoneId],sourceSha:sha,expectedWorkerId:workerId}),'verified-no-ingress'); + assert.throws(()=>verifyProviderState(good,{phase:'init-postflight',expectedZoneIds:[zoneId],sourceSha:sha,expectedWorkerId:workerId}),/empty Worker already has a custom domain/); + const reverseRef=snapshot();reverseRef.domains=[];reverseRef.worker=structuredClone(worker);reverseRef.worker.references.domains=[{hostname:'private-laptop-bridge-staging.security.cab'}]; + assert.throws(()=>verifyProviderState(reverseRef,{phase:'init-postflight',expectedZoneIds:[zoneId],sourceSha:sha,expectedWorkerId:workerId}),/reverse domain reference/); assert.throws(()=>verifyProviderState(good,{phase:'preflight',expectedZoneIds:[zoneId],sourceSha:'c'.repeat(40),expectedWorkerId:workerId}),/exact reviewed source SHA/); for(const mutate of [ s=>{s.zoneIds=[];}, @@ -189,6 +197,8 @@ test('existing Worker is a no-op only when disabled ingress, exact SQLite namesp test('postflight readback verifies deployed identity via independent API data and never writes',async()=>{ const f=cloudflareFixture({target:'existing',namespaces:[ns()],domains:[domain()]}); assert.equal(await verifyBootstrapPostflight({accountId,workerId,readToken,gatewayToken,expectedZoneIds:[zoneId],sourceSha:sha,fetchImpl:f.fetchImpl}),'verified'); + const init=cloudflareFixture({target:'existing',namespaces:[ns()],domains:[]}); + assert.equal(await verifyBootstrapPostflight({accountId,workerId,readToken,gatewayToken,expectedZoneIds:[zoneId],sourceSha:sha,phase:'init-postflight',fetchImpl:init.fetchImpl}),'verified-no-ingress'); assert.ok(f.calls.every(call=>call.method==='GET'&&call.token===`Bearer ${call.url.pathname.endsWith('/gateway/rules')?gatewayToken:readToken}`)); const bad=cloudflareFixture({target:'existing',namespaces:[ns()],domains:[domain()],versionRecord:{...version(),annotations:{'workers/tag':'c'.repeat(40)}}}); await assert.rejects(verifyBootstrapPostflight({accountId,workerId,readToken,gatewayToken,expectedZoneIds:[zoneId],sourceSha:sha,fetchImpl:bad.fetchImpl}),/exact reviewed source SHA/); diff --git a/pm-stack/private-laptop-bridge/staging-preflight.json b/pm-stack/private-laptop-bridge/staging-preflight.json index f6b5fd9ac2..e4ffc8ef54 100644 --- a/pm-stack/private-laptop-bridge/staging-preflight.json +++ b/pm-stack/private-laptop-bridge/staging-preflight.json @@ -67,9 +67,7 @@ "workers_dev": false, "preview_urls": false, "routes": [], - "custom_domains": [ - "laptop-bridge-staging.security.cab" - ], + "custom_domains": [], "observability": { "enabled": false, "logs": false, From 7b1976a187b0f39d6a0159458bdf4aa0eff7866b Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 09:44:57 +0000 Subject: [PATCH 27/33] fix(bridge): verify empty and sole init version state --- pm-stack/private-laptop-bridge/STAGING.md | 12 +++++++----- pm-stack/private-laptop-bridge/VERIFICATION.md | 5 +++-- pm-stack/private-laptop-bridge/staging-bootstrap.mjs | 12 +++++++++--- .../private-laptop-bridge/staging-bootstrap.test.mjs | 11 +++++++++-- 4 files changed, 28 insertions(+), 12 deletions(-) diff --git a/pm-stack/private-laptop-bridge/STAGING.md b/pm-stack/private-laptop-bridge/STAGING.md index 2a5e76873c..b6f5be37ee 100644 --- a/pm-stack/private-laptop-bridge/STAGING.md +++ b/pm-stack/private-laptop-bridge/STAGING.md @@ -79,18 +79,20 @@ is missing or differs. The deploy job runs the `bridge-init` build and pinned `cf deploy --dry-run`, verifies the effective disabled, no-domain Build Output, then uses separate -read-only and write-only credentials. Before its only possible provider write, read-only +read-only and write-only credentials. Before its only possible provider write, +read-only checks inventory the full account zone set and every zone's Worker routes, account Worker domains, the pinned Worker ID and SQLite namespace, schedules, subdomain/preview flags, settings, versions and deployments. It refuses an unknown or partial inventory, any unexpected route/domain, an orphan namespace, an absent or mismatched Worker ID, shared read/write tokens, or any effective config that differs from the disabled artifact. Only an exact, precreated -metadata-only Worker with zero deployments, zero domain references, and no -namespace can proceed. A second read-only pass proves that the deployment is +metadata-only Worker with zero legacy versions and deployments, zero domain +references, and no namespace can proceed. A second read-only pass proves that the deployment is disabled, has the exact source-SHA version and SQLite namespace binding, and -still has zero custom domains and reverse domain references. It never changes -Gateway or routes. +has exactly one version matching its sole serving deployment while retaining +zero custom domains and reverse domain references. It never changes Gateway +or routes. The checked-in template has not been registered, dispatched, or run against Cloudflare. The current protected environment, reviewer IDs, exact account, diff --git a/pm-stack/private-laptop-bridge/VERIFICATION.md b/pm-stack/private-laptop-bridge/VERIFICATION.md index 65562ff407..6d2b07d5ba 100644 --- a/pm-stack/private-laptop-bridge/VERIFICATION.md +++ b/pm-stack/private-laptop-bridge/VERIFICATION.md @@ -386,8 +386,9 @@ The first-deploy template now uses a separate `bridge-init` mode. Its rendered Worker payload must have `domains: []`, blank Access issuer/audience, disabled service, no routes/triggers, workers.dev/previews off, and the declared SQLite export. The init postflight requires zero account domains and Worker reverse -domain references, plus the exact disabled source-tagged version and namespace. -The routed `bridge` mode remains separate; no Access setup or hostname attach +domain references, zero prior versions before the write, and exactly one +source-tagged disabled version matching its sole deployment afterward. The +routed `bridge` mode remains separate; no Access setup or hostname attach workflow was added. `private-laptop-bridge-staging-bootstrap.workflow.yml.disabled` remains outside `.github/workflows` and was not dispatched. diff --git a/pm-stack/private-laptop-bridge/staging-bootstrap.mjs b/pm-stack/private-laptop-bridge/staging-bootstrap.mjs index 1b012e2504..3b153b3748 100644 --- a/pm-stack/private-laptop-bridge/staging-bootstrap.mjs +++ b/pm-stack/private-laptop-bridge/staging-bootstrap.mjs @@ -305,9 +305,13 @@ async function readSnapshot({accountId, token, gatewayToken, expectedZoneIds, fe const deployResponse = await cfRequest(fetchImpl, accountId, token, `/workers/scripts/${WORKER_NAME}/deployments?page=1&per_page=100`, { }); const deployments = deployResponse.result?.deployments; if (!Array.isArray(deployments)) fail('Worker deployment readback is missing'); - if (deployments.length === 0) return {worker: worker.result, workerId, subdomain: subdomain.result, settings: settings.result, - schedules: schedules.result.schedules, namespaces, domains: allDomains, gatewayRules, version: null, deployments, - zoneIds: zones.map(zone => zone.id.toLowerCase()).sort()}; + const versions=await listPages(fetchImpl,accountId,token,`/workers/scripts/${encodeURIComponent(WORKER_NAME)}/versions`,{resultPath:'items'}); + if(versions.some(version=>!version||typeof version!=='object'||!UUID.test(version.id??''))) fail('legacy Scripts version inventory contains a malformed version ID'); + if (deployments.length === 0) { + return {worker: worker.result, workerId, subdomain: subdomain.result, settings: settings.result, + schedules: schedules.result.schedules, namespaces, domains: allDomains, gatewayRules, version: null, versions, deployments, + zoneIds: zones.map(zone => zone.id.toLowerCase()).sort()}; + } const latest = deployments[0]; const servingVersions = latest?.versions; if (!Array.isArray(servingVersions) || servingVersions.length !== 1 || !UUID.test(servingVersions[0]?.version_id ?? '') || @@ -333,6 +337,7 @@ export function verifyProviderState(snapshot, {phase, expectedZoneIds, sourceSha if (Array.isArray(snapshot.deployments) && snapshot.deployments.length === 0) { exactBridgeDomains(snapshot.domains, {deployed: false, zoneIds: expected}); if (phase !== 'preflight' || snapshot.namespaces.length !== 0 || + !Array.isArray(snapshot.versions) || snapshot.versions.length !== 0 || snapshot.worker.references.domains.length !== 0 || snapshot.subdomain?.enabled !== false || snapshot.subdomain?.previews_enabled !== false || !Array.isArray(snapshot.schedules) || snapshot.schedules.length !== 0 || !snapshot.settings || @@ -351,6 +356,7 @@ export function verifyProviderState(snapshot, {phase, expectedZoneIds, sourceSha const noIngress=phase==='init-postflight'||phase==='preflight'; exactBridgeDomains(snapshot.domains, {deployed: !noIngress, zoneIds: expected}); if(noIngress&&snapshot.worker.references.domains.length!==0) fail('no-ingress Worker still has a reverse domain reference'); + if(noIngress&&(!Array.isArray(snapshot.versions)||snapshot.versions.length!==1||snapshot.versions[0]?.id!==snapshot.deployments[0]?.versions?.[0]?.version_id)) fail('no-ingress initialization must have exactly one version matching its sole deployment'); if (snapshot.namespaces.length !== 1) fail('existing Worker SQLite namespace inventory is unexpected'); const namespace = snapshot.namespaces[0]; if (!ID.test(namespace?.id ?? '') && !UUID.test(namespace?.id ?? '')) fail('Durable Object namespace ID is invalid'); diff --git a/pm-stack/private-laptop-bridge/staging-bootstrap.test.mjs b/pm-stack/private-laptop-bridge/staging-bootstrap.test.mjs index 44c0cc9ce9..ef3aeaef8a 100644 --- a/pm-stack/private-laptop-bridge/staging-bootstrap.test.mjs +++ b/pm-stack/private-laptop-bridge/staging-bootstrap.test.mjs @@ -40,7 +40,7 @@ const ns = () => ({id:namespaceId,script:WORKER_NAME,class:DO_CLASS,use_sqlite:t const snapshot = () => ({ zoneIds:[zoneId],worker,workerId,subdomain:{enabled:false,previews_enabled:false}, settings:{logpush:false,observability:{enabled:false},tail_consumers:[]},schedules:[], - namespaces:[ns()],domains:[domain()],gatewayRules:[],version:version(),deployments:[deployment()], + namespaces:[ns()],domains:[domain()],gatewayRules:[],version:version(),versions:[{id:versionId,metadata:{},number:1}],deployments:[deployment()], }); test('first-deploy workflow remains dormant, fixed-target, and checks protection before environment assignment', async()=>{ @@ -88,8 +88,9 @@ function response(result, {status=200,resultInfo={page:1,per_page:100,total_coun return new Response(JSON.stringify({success,result,errors,...(resultInfo === undefined ? {} : {result_info:resultInfo})}),{status}); } -function cloudflareFixture({target='absent', zones=[{id:zoneId,account:{id:accountId}}], zoneInfo, route=[], domains=[], namespaces=[], workerRecord=worker, versionRecord=version(), gatewayRules=[], deployments=[deployment()], overrides={}}={}) { +function cloudflareFixture({target='absent', zones=[{id:zoneId,account:{id:accountId}}], zoneInfo, route=[], domains=[], namespaces=[], workerRecord=worker, versionRecord=version(), gatewayRules=[], deployments=[deployment()], legacyVersions=null, overrides={}}={}) { const calls=[]; + const versionsList=legacyVersions??(deployments.length?[{id:versionId,metadata:{},number:1}]:[]); const fetchImpl=async (url,init={})=>{ const parsed=new URL(url), method=init.method??'GET'; calls.push({url:parsed,method,token:init.headers?.authorization}); @@ -99,6 +100,7 @@ function cloudflareFixture({target='absent', zones=[{id:zoneId,account:{id:accou if(parsed.pathname==='/client/v4/accounts/'+accountId+'/workers/domains') return response(domains); if(parsed.pathname==='/client/v4/accounts/'+accountId+'/gateway/rules') return response(gatewayRules); if(parsed.pathname==='/client/v4/accounts/'+accountId+'/workers/durable_objects/namespaces') return response(namespaces,{resultInfo:{page:1,per_page:1000,total_count:namespaces.length,total_pages:namespaces.length?1:0}}); + if(parsed.pathname===`/client/v4/accounts/${accountId}/workers/scripts/${WORKER_NAME}/versions`) return response({items:versionsList},{resultInfo:{page:1,per_page:100,count:versionsList.length,total_count:versionsList.length,total_pages:versionsList.length?1:0}}); if(parsed.pathname===`/client/v4/accounts/${accountId}/workers/workers/${WORKER_NAME}`) { if(target==='absent') return response(null,{status:404,success:false,resultInfo:undefined,errors:[{code:10007}]}); return response(workerRecord,{resultInfo:undefined}); @@ -143,6 +145,7 @@ test('exact empty locally created Worker is the only first-deploy candidate; all assert.equal(status,'deploy'); assert.ok(f.calls.every(call=>call.method==='GET'&&call.token===`Bearer ${call.url.pathname.endsWith('/gateway/rules')?gatewayToken:readToken}`)); assert.ok(f.calls.some(call=>call.url.pathname===`/client/v4/zones/${zoneId}/workers/routes`)); + assert.ok(f.calls.some(call=>call.url.pathname===`/client/v4/accounts/${accountId}/workers/scripts/${WORKER_NAME}/versions`)); await assert.rejects(verifyBootstrapPreflight({accountId,workerId,readToken,gatewayToken,expectedZoneIds:[zoneId],sourceSha:sha,fetchImpl:cloudflareFixture({target:'absent'}).fetchImpl}),/created locally by an owner/); for(const bad of [ cloudflareFixture({target:'absent',zones:[]}), @@ -152,6 +155,8 @@ test('exact empty locally created Worker is the only first-deploy candidate; all cloudflareFixture({target:'absent',zoneInfo:{page:2,per_page:50,total_count:1,total_pages:1}}), cloudflareFixture({target:'absent',gatewayRules:[{action:'forward',enabled:true,rule_settings:{forward:{worker_id:WORKER_NAME}}}]}), ]) await assert.rejects(verifyBootstrapPreflight({accountId,workerId,readToken,gatewayToken,expectedZoneIds:[zoneId],sourceSha:sha,fetchImpl:bad.fetchImpl})); + const unservedVersion=cloudflareFixture({target:'empty',deployments:[],legacyVersions:[{id:versionId,metadata:{},number:1}]}); + await assert.rejects(verifyBootstrapPreflight({accountId,workerId,readToken,gatewayToken,expectedZoneIds:[zoneId],sourceSha:sha,fetchImpl:unservedVersion.fetchImpl}),/only the exact empty disabled locally created Worker/); const takeover=cloudflareFixture({target:'empty',deployments:[],domains:[],workerRecord:{...worker,id:'4'.repeat(32)}}); await assert.rejects(verifyBootstrapPreflight({accountId,workerId,readToken,gatewayToken,expectedZoneIds:[zoneId],sourceSha:sha,fetchImpl:takeover.fetchImpl}),/Worker ID differs/); assert.equal(verifyDistinctWriteCredential(readToken,gatewayToken,writeToken),true); @@ -165,6 +170,8 @@ test('bootstrap only accepts disabled no-ingress state; routed postflight verifi const noIngress=snapshot();noIngress.domains=[]; assert.equal(verifyProviderState(noIngress,{phase:'preflight',expectedZoneIds:[zoneId],sourceSha:sha,expectedWorkerId:workerId}),'already-initialized-no-ingress'); assert.equal(verifyProviderState(noIngress,{phase:'init-postflight',expectedZoneIds:[zoneId],sourceSha:sha,expectedWorkerId:workerId}),'verified-no-ingress'); + const extraVersion=structuredClone(noIngress);extraVersion.versions.push({id:'22222222-3333-4444-5555-666666666666',metadata:{},number:2}); + assert.throws(()=>verifyProviderState(extraVersion,{phase:'init-postflight',expectedZoneIds:[zoneId],sourceSha:sha,expectedWorkerId:workerId}),/exactly one version/); assert.throws(()=>verifyProviderState(good,{phase:'init-postflight',expectedZoneIds:[zoneId],sourceSha:sha,expectedWorkerId:workerId}),/empty Worker already has a custom domain/); const reverseRef=snapshot();reverseRef.domains=[];reverseRef.worker=structuredClone(worker);reverseRef.worker.references.domains=[{hostname:'private-laptop-bridge-staging.security.cab'}]; assert.throws(()=>verifyProviderState(reverseRef,{phase:'init-postflight',expectedZoneIds:[zoneId],sourceSha:sha,expectedWorkerId:workerId}),/reverse domain reference/); From be7bba58affd20e94ec0ee0ba6bdd4693e18c8c2 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 09:50:00 +0000 Subject: [PATCH 28/33] fix(bridge): correct hosted access and bootstrap contracts --- pm-stack/private-laptop-bridge/access-auth.test.mjs | 1 - pm-stack/private-laptop-bridge/gateway.test.mjs | 2 +- pm-stack/private-laptop-bridge/staging-bootstrap.mjs | 2 +- pm-stack/private-laptop-bridge/staging-bootstrap.test.mjs | 2 +- 4 files changed, 3 insertions(+), 4 deletions(-) diff --git a/pm-stack/private-laptop-bridge/access-auth.test.mjs b/pm-stack/private-laptop-bridge/access-auth.test.mjs index 9b040ba098..413950211a 100644 --- a/pm-stack/private-laptop-bridge/access-auth.test.mjs +++ b/pm-stack/private-laptop-bridge/access-auth.test.mjs @@ -49,7 +49,6 @@ test('Access service token validates signature, issuer, claim and context audien {aud:['another-audience']}, {exp:now/1000-1,iat:now/1000-100}, {iat:now/1000+31}, - {common_name:'other-client'}, {sub:'nonempty'}, {type:'org'}, ]) await assert.rejects(f.request(claims),/access-denied/); diff --git a/pm-stack/private-laptop-bridge/gateway.test.mjs b/pm-stack/private-laptop-bridge/gateway.test.mjs index 99cc0c7a43..d05eb07357 100644 --- a/pm-stack/private-laptop-bridge/gateway.test.mjs +++ b/pm-stack/private-laptop-bridge/gateway.test.mjs @@ -103,7 +103,7 @@ test('Gateway RPC contract and direct Access HTTP gate are independent; ordinary assert.equal((await h.send('device','/v1/result',{id:job.id,lease:job.lease,result})).status,200); assert.deepEqual((await h.send('caller','/v1/read',{id:job.id})).body,{status:'complete',result}); const direct=await h.mf.getWorker('private-bridge'); - const signed=await signRequest({origin:`https://${host}`,audience:'gateway-offline',principal:'caller',privateKey:h.keys.caller.privateKey,path:'/v1/call',body:{device:'amd',operation:'laptop.health',args:{}}}); + const signed=await signRequest({origin:`https://${BRIDGE_HOST}`,audience:'gateway-offline',principal:'caller',privateKey:h.keys.caller.privateKey,path:'/v1/call',body:{device:'amd',operation:'laptop.health',args:{}}}); const response=await direct.fetch(signed.url,{method:'POST',headers:Object.fromEntries(signed.headers),body:await signed.text()}); assert.equal(response.status,401);assert.deepEqual(await response.json(),{error:'access-authentication'}); }); diff --git a/pm-stack/private-laptop-bridge/staging-bootstrap.mjs b/pm-stack/private-laptop-bridge/staging-bootstrap.mjs index 3b153b3748..aaa667349e 100644 --- a/pm-stack/private-laptop-bridge/staging-bootstrap.mjs +++ b/pm-stack/private-laptop-bridge/staging-bootstrap.mjs @@ -321,7 +321,7 @@ async function readSnapshot({accountId, token, gatewayToken, expectedZoneIds, fe `/workers/workers/${workerId}/versions/${encodeURIComponent(exactVersionId)}`); if (exactVersion.result?.id !== exactVersionId) fail('Beta Worker version GET returned a different version ID'); return {worker: worker.result, workerId, subdomain: subdomain.result, settings: settings.result, - schedules: schedules.result.schedules, namespaces, domains: allDomains, gatewayRules, version: exactVersion.result, deployments, + schedules: schedules.result.schedules, namespaces, domains: allDomains, gatewayRules, version: exactVersion.result, versions, deployments, zoneIds: zones.map(zone => zone.id.toLowerCase()).sort()}; } diff --git a/pm-stack/private-laptop-bridge/staging-bootstrap.test.mjs b/pm-stack/private-laptop-bridge/staging-bootstrap.test.mjs index ef3aeaef8a..f95c8a7461 100644 --- a/pm-stack/private-laptop-bridge/staging-bootstrap.test.mjs +++ b/pm-stack/private-laptop-bridge/staging-bootstrap.test.mjs @@ -175,7 +175,7 @@ test('bootstrap only accepts disabled no-ingress state; routed postflight verifi assert.throws(()=>verifyProviderState(good,{phase:'init-postflight',expectedZoneIds:[zoneId],sourceSha:sha,expectedWorkerId:workerId}),/empty Worker already has a custom domain/); const reverseRef=snapshot();reverseRef.domains=[];reverseRef.worker=structuredClone(worker);reverseRef.worker.references.domains=[{hostname:'private-laptop-bridge-staging.security.cab'}]; assert.throws(()=>verifyProviderState(reverseRef,{phase:'init-postflight',expectedZoneIds:[zoneId],sourceSha:sha,expectedWorkerId:workerId}),/reverse domain reference/); - assert.throws(()=>verifyProviderState(good,{phase:'preflight',expectedZoneIds:[zoneId],sourceSha:'c'.repeat(40),expectedWorkerId:workerId}),/exact reviewed source SHA/); + assert.throws(()=>verifyProviderState(noIngress,{phase:'preflight',expectedZoneIds:[zoneId],sourceSha:'c'.repeat(40),expectedWorkerId:workerId}),/exact reviewed source SHA/); for(const mutate of [ s=>{s.zoneIds=[];}, s=>{s.subdomain.enabled=true;}, From a43f5d933270428a4a3dfabd9155e7ba1099ecf0 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 10:12:52 +0000 Subject: [PATCH 29/33] fix(bridge): bind release proof to immutable target --- .../private-laptop-bridge-release.yml | 5 + pm-stack/private-laptop-bridge/STAGING.md | 41 +++++++++ .../bridge-pilot-request.example.json | 56 ++++++++++++ .../bridge-pilot-request.schema.json | 91 +++++++++++++++++++ .../release-artifact.mjs | 6 +- .../release-contract.mjs | 8 +- .../release-contract.test.mjs | 32 ++++--- .../staging-bootstrap.mjs | 49 +++++++--- .../staging-bootstrap.test.mjs | 36 +++++--- 9 files changed, 277 insertions(+), 47 deletions(-) create mode 100644 pm-stack/private-laptop-bridge/bridge-pilot-request.example.json create mode 100644 pm-stack/private-laptop-bridge/bridge-pilot-request.schema.json diff --git a/.github/workflows/private-laptop-bridge-release.yml b/.github/workflows/private-laptop-bridge-release.yml index e1c5fbcb54..8253e7a920 100644 --- a/.github/workflows/private-laptop-bridge-release.yml +++ b/.github/workflows/private-laptop-bridge-release.yml @@ -138,6 +138,7 @@ jobs: env: CF_ACCOUNT_ID: ${{ secrets.CF_BRIDGE_ACCOUNT_ID }} OWNER_PROOF_JSON: ${{ secrets.CF_BRIDGE_OWNER_PROOF_JSON }} + EXPECTED_WORKER_ID: ${{ vars.CF_BRIDGE_WORKER_ID }} TARGET_WORKER: ${{ steps.target.outputs.worker }} TARGET_ENV: ${{ steps.target.outputs.environment }} SOURCE_SHA: ${{ steps.provenance.outputs.source_sha }} @@ -171,6 +172,7 @@ jobs: env: CF_ACCOUNT_ID: ${{ secrets.CF_BRIDGE_ACCOUNT_ID }} OWNER_PROOF_JSON: ${{ secrets.CF_BRIDGE_OWNER_PROOF_JSON }} + EXPECTED_WORKER_ID: ${{ vars.CF_BRIDGE_WORKER_ID }} TARGET_WORKER: ${{ steps.target.outputs.worker }} TARGET_ENV: ${{ steps.target.outputs.environment }} run: node release-artifact.mjs preflight @@ -231,6 +233,7 @@ jobs: CF_BRIDGE_ACCESS_ISSUER: ${{ vars.CF_BRIDGE_ACCESS_ISSUER }} CF_BRIDGE_ACCESS_AUDIENCE: ${{ vars.CF_BRIDGE_ACCESS_AUDIENCE }} OWNER_PROOF_JSON: ${{ secrets.CF_BRIDGE_OWNER_PROOF_JSON }} + EXPECTED_WORKER_ID: ${{ vars.CF_BRIDGE_WORKER_ID }} TARGET_WORKER: ${{ steps.target.outputs.worker }} TARGET_ENV: ${{ steps.target.outputs.environment }} TARGET_MODE: ${{ steps.target.outputs.mode }} @@ -269,6 +272,7 @@ jobs: OWNER_PROOF_JSON: ${{ secrets.CF_BRIDGE_OWNER_PROOF_JSON }} CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CF_BRIDGE_ACCOUNT_ID }} CLOUDFLARE_API_TOKEN: ${{ secrets.CF_BRIDGE_API_TOKEN }} + EXPECTED_WORKER_ID: ${{ vars.CF_BRIDGE_WORKER_ID }} TARGET_WORKER: ${{ steps.target.outputs.worker }} TARGET_ENV: ${{ steps.target.outputs.environment }} TARGET_MODE: ${{ steps.target.outputs.mode }} @@ -291,6 +295,7 @@ jobs: env: CF_ACCOUNT_ID: ${{ secrets.CF_BRIDGE_ACCOUNT_ID }} OWNER_PROOF_JSON: ${{ secrets.CF_BRIDGE_OWNER_PROOF_JSON }} + EXPECTED_WORKER_ID: ${{ vars.CF_BRIDGE_WORKER_ID }} TARGET_WORKER: ${{ steps.target.outputs.worker }} TARGET_ENV: ${{ steps.target.outputs.environment }} SOURCE_SHA: ${{ steps.provenance.outputs.source_sha }} diff --git a/pm-stack/private-laptop-bridge/STAGING.md b/pm-stack/private-laptop-bridge/STAGING.md index b6f5be37ee..0f33f683f6 100644 --- a/pm-stack/private-laptop-bridge/STAGING.md +++ b/pm-stack/private-laptop-bridge/STAGING.md @@ -505,3 +505,44 @@ starting with the credential-free network smoke; do not request blanket access. Read-only account/runner discovery and the separate smoke approval gate are in [DISCOVERY.md](DISCOVERY.md). + +## Review-only bounded pilot request (new) + +`bridge-pilot-request.schema.json` and `bridge-pilot-request.example.json` +define a review packet, not an executable deployment or runtime config. The +schema only admits `enabled:false`, `live_enable_approval:false`, one exact +32-hex Worker ID, the four read-only operations, and exactly two ordered roles: +the Aster caller and the AMD device. It has no secret fields; the client IDs +and Ed25519 public keys are identity metadata, never private keys or service +tokens. Any future pilot needs a separately reviewed change to executable +configuration and a separate protected activation step. The present +`bridge-init` and `bridge` configs remain disabled and cannot consume this file. + +The proposed pilot hostname is `laptop-bridge-pilot.security.cab`; its DNS +ownership, wildcard interactions, Access application, issuer/audience, and +Worker custom-domain availability have not been verified. It must not be +attached based on this request template. A future request is limited to one +UTC window of at most 60 minutes, two independently reviewed service identities, +the exact Access application and audience, no browser login or bypass policy, +and an owner-operated kill switch that disables the Worker, revokes both +service tokens, and removes the hostname association. Expiration of the window +must fail closed. The request itself contains no values that enable the pilot. + +The latest release guard also binds the short-lived owner proof to the protected +`CF_BRIDGE_WORKER_ID` environment variable and the Beta API's immutable Worker +ID. The proof must have been produced within 15 minutes and expires within 15 +minutes of its verification timestamp. It checks the exact stage's route, +custom-domain and Access posture immediately before upload/promotion; a +name-only `cf workers get` response is not an identity proof. + +Cloudflare's Worker metadata readback checks the complete `references` object +for `workers`, `dispatch_namespace_outbounds`, `durable_objects`, `queues`, and +`domains` against the phase-specific expected sets and exact Worker ID. Before +and after no-ingress initialization, all five sets must be empty; after the +separately reviewed routed phase, only the exact approved domain reference may +appear. `subdomain.previews_enabled=false` and empty version `urls` are checked +as configuration/version facts. They are not a separate inventory of Preview +objects: the available official Worker API does not define a distinct +Preview-list endpoint. Any requirement to prove such an inventory needs a +separate supported owner-side check; these flags are not presented as that +proof. diff --git a/pm-stack/private-laptop-bridge/bridge-pilot-request.example.json b/pm-stack/private-laptop-bridge/bridge-pilot-request.example.json new file mode 100644 index 0000000000..eba8c402a2 --- /dev/null +++ b/pm-stack/private-laptop-bridge/bridge-pilot-request.example.json @@ -0,0 +1,56 @@ +{ + "schema_version": 1, + "status": "request-only", + "request_id": "REPLACE_WITH_REVIEWED_REQUEST_ID", + "source_sha": "", + "target": { + "worker": "private-laptop-bridge-staging", + "worker_id": "" + }, + "host": "laptop-bridge-pilot.security.cab", + "access": { + "issuer": "", + "audience": "", + "application_id": "", + "service_token_only": true, + "browser_login": false, + "bypass_count": 0 + }, + "window": { + "starts_at": "", + "ends_at": "", + "max_duration_minutes": 60 + }, + "enabled": false, + "kill_switch": { + "enabled_by_default": false, + "disable_on": "window_end", + "revoke_access_tokens": true, + "remove_host_association": true + }, + "principals": [ + { + "role": "aster-caller", + "principal_id": "", + "access_client_id": "", + "ed25519_public_key": "" + }, + { + "role": "amd-device", + "principal_id": "", + "access_client_id": "", + "ed25519_public_key": "" + } + ], + "operations": [ + "fleet.queue.list", + "fleet.queue.health", + "laptop.health", + "laptop.diagnostics" + ], + "review": { + "independent_source_reviewer": "", + "identity_reviewer": "", + "live_enable_approval": false + } +} diff --git a/pm-stack/private-laptop-bridge/bridge-pilot-request.schema.json b/pm-stack/private-laptop-bridge/bridge-pilot-request.schema.json new file mode 100644 index 0000000000..e8dd14a3b3 --- /dev/null +++ b/pm-stack/private-laptop-bridge/bridge-pilot-request.schema.json @@ -0,0 +1,91 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://developing.today/schemas/private-laptop-bridge-pilot-request.schema.json", + "title": "Private Laptop Bridge bounded pilot request", + "description": "Review-only request format. It is not consumed by a Worker or deployment workflow and cannot activate a pilot.", + "type": "object", + "additionalProperties": false, + "required": ["schema_version", "status", "request_id", "source_sha", "target", "host", "access", "window", "enabled", "kill_switch", "principals", "operations", "review"], + "properties": { + "schema_version": { "const": 1 }, + "status": { "const": "request-only" }, + "request_id": { "type": "string", "pattern": "^[A-Za-z0-9._-]{8,80}$" }, + "source_sha": { "type": "string", "pattern": "^[a-f0-9]{40}$" }, + "target": { + "type": "object", "additionalProperties": false, + "required": ["worker", "worker_id"], + "properties": { + "worker": { "const": "private-laptop-bridge-staging" }, + "worker_id": { "type": "string", "pattern": "^[0-9a-fA-F]{32}$" } + } + }, + "host": { "const": "laptop-bridge-pilot.security.cab" }, + "access": { + "type": "object", "additionalProperties": false, + "required": ["issuer", "audience", "application_id", "service_token_only", "browser_login", "bypass_count"], + "properties": { + "issuer": { "type": "string", "pattern": "^https://[a-z0-9-]+\\.cloudflareaccess\\.com$" }, + "audience": { "type": "string", "pattern": "^[A-Za-z0-9_-]{20,128}$" }, + "application_id": { "type": "string", "pattern": "^[A-Za-z0-9_-]{8,80}$" }, + "service_token_only": { "const": true }, + "browser_login": { "const": false }, + "bypass_count": { "const": 0 } + } + }, + "window": { + "type": "object", "additionalProperties": false, + "required": ["starts_at", "ends_at", "max_duration_minutes"], + "properties": { + "starts_at": { "type": "string", "format": "date-time" }, + "ends_at": { "type": "string", "format": "date-time" }, + "max_duration_minutes": { "const": 60 } + } + }, + "enabled": { "const": false }, + "kill_switch": { + "type": "object", "additionalProperties": false, + "required": ["enabled_by_default", "disable_on", "revoke_access_tokens", "remove_host_association"], + "properties": { + "enabled_by_default": { "const": false }, + "disable_on": { "enum": ["window_end", "any_identity_or_posture_failure", "owner_request"] }, + "revoke_access_tokens": { "const": true }, + "remove_host_association": { "const": true } + } + }, + "principals": { + "type": "array", "minItems": 2, "maxItems": 2, + "prefixItems": [{ + "type": "object", "additionalProperties": false, + "required": ["role", "principal_id", "access_client_id", "ed25519_public_key"], + "properties": { + "role": { "const": "aster-caller" }, + "principal_id": { "type": "string", "pattern": "^[A-Za-z0-9._-]{8,128}$" }, + "access_client_id": { "type": "string", "pattern": "^[A-Za-z0-9._-]{8,128}$" }, + "ed25519_public_key": { "type": "string", "pattern": "^[A-Za-z0-9_-]{43}$" } + } + }, { + "type": "object", "additionalProperties": false, + "required": ["role", "principal_id", "access_client_id", "ed25519_public_key"], + "properties": { + "role": { "const": "amd-device" }, + "principal_id": { "type": "string", "pattern": "^[A-Za-z0-9._-]{8,128}$" }, + "access_client_id": { "type": "string", "pattern": "^[A-Za-z0-9._-]{8,128}$" }, + "ed25519_public_key": { "type": "string", "pattern": "^[A-Za-z0-9_-]{43}$" } + } + }], + "items": false + }, + "operations": { + "const": ["fleet.queue.list", "fleet.queue.health", "laptop.health", "laptop.diagnostics"] + }, + "review": { + "type": "object", "additionalProperties": false, + "required": ["independent_source_reviewer", "identity_reviewer", "live_enable_approval"], + "properties": { + "independent_source_reviewer": { "type": "string", "minLength": 3 }, + "identity_reviewer": { "type": "string", "minLength": 3 }, + "live_enable_approval": { "const": false } + } + } + } +} diff --git a/pm-stack/private-laptop-bridge/release-artifact.mjs b/pm-stack/private-laptop-bridge/release-artifact.mjs index 7f42ac20d3..934d9287f2 100644 --- a/pm-stack/private-laptop-bridge/release-artifact.mjs +++ b/pm-stack/private-laptop-bridge/release-artifact.mjs @@ -15,7 +15,7 @@ const root=process.cwd(); if(action==='preflight') { const worker=required('TARGET_WORKER'), environment=required('TARGET_ENV'), accountId=required('CF_ACCOUNT_ID'); const proof=privateProof(); - assertPreflight(proof,{accountId,worker,environment}); + assertPreflight(proof,{accountId,worker,environment,expectedWorkerId:required('EXPECTED_WORKER_ID')}); console.log('owner read-only staging proof valid for '+worker); } else if(action==='digest') { const config_digest=await digestFiles(root), preflight_digest=proofDigest(), build_digest=await digestTree(resolve(root,'.cloudflare/output/v1')); @@ -49,7 +49,7 @@ if(action==='preflight') { const [handoffPath]=args; if(!handoffPath) throw new Error('usage: current-proof '); const artifact=await json(handoffPath),account=required('CF_ACCOUNT_ID'),worker=required('TARGET_WORKER'),environment=required('TARGET_ENV'); if(artifact.account_id_sha256!==accountDigest(account)||artifact.worker!==worker||artifact.environment!==environment) throw new Error('current owner proof target differs from upload artifact'); - const proof=privateProof(); assertPreflight(proof,{accountId:account,worker,environment}); + const proof=privateProof(); assertPreflight(proof,{accountId:account,worker,environment,expectedWorkerId:required('EXPECTED_WORKER_ID')}); const preflight_digest=proofDigest(); if(preflight_digest!==artifact.preflight_digest) throw new Error('current main owner proof changed since upload; upload a new candidate'); console.log('current main owner proof matches uploaded candidate'); @@ -60,7 +60,7 @@ if(action==='preflight') { const expectedMode=target==='private-laptop-bridge-staging'?'bridge':'default'; if(artifact.worker!==target||artifact.account_id_sha256!==accountDigest(account)||artifact.environment!==env||artifact.mode!==expectedMode||mode!==expectedMode) throw new Error('promotion target/environment/account/mode differs from handoff'); assertUploadRun(run,jobs,artifact); - const proof=privateProof(); assertPreflight(proof,{accountId:account,worker:target,environment:env}); + const proof=privateProof(); assertPreflight(proof,{accountId:account,worker:target,environment:env,expectedWorkerId:required('EXPECTED_WORKER_ID')}); const config_digest=await digestFiles(root),preflight_digest=proofDigest(),build_digest=await digestTree(resolve(root,'.cloudflare/output/v1')); const head=required('CHECKED_OUT_SHA'); if(head!==artifact.source_sha||config_digest!==artifact.config_digest||preflight_digest!==artifact.preflight_digest||build_digest!==artifact.build_digest) throw new Error('checked-out source/config/build/preflight digest does not equal uploaded artifact'); diff --git a/pm-stack/private-laptop-bridge/release-contract.mjs b/pm-stack/private-laptop-bridge/release-contract.mjs index 1bedfde434..3c10d08052 100644 --- a/pm-stack/private-laptop-bridge/release-contract.mjs +++ b/pm-stack/private-laptop-bridge/release-contract.mjs @@ -7,6 +7,7 @@ const UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; const SHA=/^[0-9a-f]{40}$/; const DIGEST=/^[0-9a-f]{64}$/; const NAMESPACE=/^(?:[0-9a-f]{32}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/; +const WORKER_ID=/^[0-9a-f]{32}$/i; const WORKFLOW='.github/workflows/private-laptop-bridge-release.yml'; export const releaseConfigFiles=['cloudflare.config.ts','package.json','package-lock.json','staging-preflight.json']; const fail=(message)=>{throw new Error(message);}; @@ -161,8 +162,9 @@ export function assertUploadRun(run,jobsResponse,handoff) { return true; } -export function assertPreflight(proof,{accountId,worker,environment,now=Date.now(),accessIssuer=process.env.CF_BRIDGE_ACCESS_ISSUER??'',accessAudience=process.env.CF_BRIDGE_ACCESS_AUDIENCE??''}) { - if(!proof||proof.schema!==1||proof.verified!==true||proof.account_id!==accountId||typeof proof.evidence_ref!=='string'||proof.evidence_ref.trim().length<3||!Number.isFinite(Date.parse(proof.verified_at))||!Number.isFinite(Date.parse(proof.expires_at))||Date.parse(proof.verified_at)>now||Date.parse(proof.expires_at)<=now||Date.parse(proof.expires_at)-Date.parse(proof.verified_at)>24*3600000) fail('owner read-only staging proof is absent, expired, or invalid'); +export function assertPreflight(proof,{accountId,worker,environment,expectedWorkerId,now=Date.now(),accessIssuer=process.env.CF_BRIDGE_ACCESS_ISSUER??'',accessAudience=process.env.CF_BRIDGE_ACCESS_AUDIENCE??''}) { + const verifiedAt=Date.parse(proof?.verified_at), expiresAt=Date.parse(proof?.expires_at); + if(!proof||proof.schema!==1||proof.verified!==true||proof.account_id!==accountId||typeof proof.evidence_ref!=='string'||proof.evidence_ref.trim().length<3||!WORKER_ID.test(expectedWorkerId??'')||!Number.isFinite(verifiedAt)||!Number.isFinite(expiresAt)||verifiedAt>now||now-verifiedAt>15*60000||expiresAt<=now||expiresAt-verifiedAt>15*60000) fail('owner read-only staging proof is absent, expired, older than fifteen minutes, or invalid'); const release=proof.release_policy,allowedRefs=release?.allowed_environment_branches?.[environment]; if(release?.repository!=='developing-today/code'||release?.branch!=='main'||release?.branch_protected!==true||release?.required_pull_request_reviews!==true||release?.force_push_disabled!==true||release?.admin_bypass_disabled!==true||release?.environment_reviewers_required?.[environment]!==true||release?.self_review_disabled?.[environment]!==true||!Array.isArray(allowedRefs)||!same(allowedRefs,['main'])||typeof release?.evidence_ref!=='string'||release.evidence_ref.trim().length<3) fail('trusted protected-main or deployment-environment approval proof is absent or invalid'); const target=proof.targets?.[worker]; @@ -172,7 +174,7 @@ export function assertPreflight(proof,{accountId,worker,environment,now=Date.now } const expectedVars=worker==='private-laptop-bridge-staging'?{ENABLED:'false',GATEWAY_HOST:'private-bridge-staging.invalid',GATEWAY_ACCOUNT_ID:'',GATEWAY_POLICY_ID:'',GATEWAY_IDENTITY_EMAIL:'',GATEWAY_POSTURE_ID:'',BRIDGE_HOST,ACCESS_ISSUER:accessIssuer,ACCESS_AUDIENCE:accessAudience,BRIDGE_REGISTRY:''}:{ENABLED:'false',GATEWAY_HOST:'private-bridge-smoke.invalid',GATEWAY_ACCOUNT_ID:'',GATEWAY_POLICY_ID:'',START_MS:'',END_MS:''}; const expectedDomains=worker==='private-laptop-bridge-staging'?[BRIDGE_HOST]:[]; - if(!target||target.environment!==environment||target.exists!==true||target.script_id!==worker||target.account_id!==accountId||target.workers_dev!==false||target.preview_urls!==false||!Array.isArray(target.routes)||target.routes.length!==0||!same(target.custom_domains,expectedDomains)||target.application_enabled!==false||target.observability?.enabled!==false||target.observability?.logs!==false||target.observability?.traces!==false||target.limits?.cpu_ms!==10||!Array.isArray(target.gateway_forward_policy_ids)||target.gateway_forward_policy_ids.length!==0||!Array.isArray(target.gateway_caller_ids)||target.gateway_caller_ids.length!==0||JSON.stringify(Object.fromEntries(Object.entries(target.variables??{}).sort()))!==JSON.stringify(Object.fromEntries(Object.entries(expectedVars).sort()))||!Array.isArray(target.bindings)) fail('owner read-only proof does not verify the exact private disabled target'); + if(!target||target.environment!==environment||target.exists!==true||target.script_id!==worker||target.worker_id?.toLowerCase()!==expectedWorkerId.toLowerCase()||target.account_id!==accountId||target.workers_dev!==false||target.preview_urls!==false||!Array.isArray(target.routes)||target.routes.length!==0||!same(target.custom_domains,expectedDomains)||target.application_enabled!==false||target.observability?.enabled!==false||target.observability?.logs!==false||target.observability?.traces!==false||target.limits?.cpu_ms!==10||!Array.isArray(target.gateway_forward_policy_ids)||target.gateway_forward_policy_ids.length!==0||!Array.isArray(target.gateway_caller_ids)||target.gateway_caller_ids.length!==0||JSON.stringify(Object.fromEntries(Object.entries(target.variables??{}).sort()))!==JSON.stringify(Object.fromEntries(Object.entries(expectedVars).sort()))||!Array.isArray(target.bindings)) fail('owner read-only proof does not verify the exact private disabled target and pinned immutable Worker ID'); if(worker==='private-laptop-bridge-staging') { const app=target.access_app, clientIds=app?.allowed_client_ids; const expiryIds=Object.keys(app?.client_expires_at??{}).sort(); diff --git a/pm-stack/private-laptop-bridge/release-contract.test.mjs b/pm-stack/private-laptop-bridge/release-contract.test.mjs index 6657b167bd..1d70b0281e 100644 --- a/pm-stack/private-laptop-bridge/release-contract.test.mjs +++ b/pm-stack/private-laptop-bridge/release-contract.test.mjs @@ -7,7 +7,7 @@ import {assertDeployable,assertDeploymentCreated,assertDryRunPayload,assertEffec const accessConfig={accessIssuer:'https://team.cloudflareaccess.com',accessAudience:'audience-with-exact-length-012345'}; const accessApp={application_id:'synthetic-app-id-123',hostname:'laptop-bridge-staging.security.cab',issuer:accessConfig.accessIssuer,audience:accessConfig.accessAudience,enabled:true,mode:'service-token-only',browser_login:false,bypass_policy_count:0,non_service_allow_count:0,allowed_client_ids:['aster-client-123','amd-client-123'],client_expires_at:{'aster-client-123':'2026-11-22T12:30:00Z','amd-client-123':'2026-11-22T12:30:00Z'}}; -const uuid='01234567-89ab-cdef-0123-456789abcdef', old='11111111-2222-3333-4444-555555555555'; +const uuid='01234567-89ab-cdef-0123-456789abcdef', old='11111111-2222-3333-4444-555555555555', workerId='fedcba9876543210fedcba9876543210', otherWorkerId='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; const sha='a'.repeat(40), cd='b'.repeat(64), bd='c'.repeat(64), pd='e'.repeat(64), acct='d'.repeat(32); const proof=provenanceDigest({worker:'private-laptop-bridge-staging',sourceSha:sha,configDigest:cd,buildDigest:bd,preflightDigest:pd}); const version={id:uuid,annotations:{'workers/tag':sha,'workers/message':`release provenance=${proof}`}}; @@ -87,14 +87,16 @@ test('deployment create response must return the exact 100 percent deployment id test('read-only owner proof fails closed for missing, stale, public or unexpected callers',()=>{ const now=Date.parse('2026-11-22T12:00:00Z'); - const good={schema:1,verified:true,account_id:acct,verified_at:'2026-11-22T11:30:00Z',expires_at:'2026-11-22T13:00:00Z',evidence_ref:'review-1',release_policy:{repository:'developing-today/code',branch:'main',branch_protected:true,required_pull_request_reviews:true,force_push_disabled:true,admin_bypass_disabled:true,environment_reviewers_required:{'cloudflare-staging':true,'cloudflare-staging-smoke':true},self_review_disabled:{'cloudflare-staging':true,'cloudflare-staging-smoke':true},allowed_environment_branches:{'cloudflare-staging':['main'],'cloudflare-staging-smoke':['main']},evidence_ref:'policy-review-1'},targets:{'private-laptop-bridge-staging':{environment:'cloudflare-staging',exists:true,script_id:'private-laptop-bridge-staging',account_id:acct,application_enabled:false,workers_dev:false,preview_urls:false,routes:[],custom_domains:[BRIDGE_HOST],access_app:accessApp,observability:{enabled:false,logs:false,traces:false},limits:{cpu_ms:10},gateway_forward_policy_ids:[],gateway_caller_ids:[],variables:{ENABLED:'false',GATEWAY_HOST:'private-bridge-staging.invalid',GATEWAY_ACCOUNT_ID:'',GATEWAY_POLICY_ID:'',GATEWAY_IDENTITY_EMAIL:'',GATEWAY_POSTURE_ID:'',BRIDGE_HOST,ACCESS_ISSUER:'https://team.cloudflareaccess.com',ACCESS_AUDIENCE:'audience-with-exact-length-012345',BRIDGE_REGISTRY:''},bindings:[{name:'BRIDGE',type:'durable_object_namespace',class_name:'PrivateLaptopBridge',namespace_id:'1'.repeat(32)}],declarative_exports:{PrivateLaptopBridge:{state:'created',storage:'sqlite'}},do:{id:'1'.repeat(32),class:'PrivateLaptopBridge',script:'private-laptop-bridge-staging',use_sqlite:true}}}}; - assert.equal(assertPreflight(good,{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now,...accessConfig}),true); - assert.throws(()=>assertPreflight(good,{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now,accessIssuer:'',accessAudience:''}),/differ from the protected build configuration/); - assert.throws(()=>assertPreflight({...good,verified:false},{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now,...accessConfig}),/absent, expired, or invalid/); - assert.throws(()=>assertPreflight({...good,expires_at:'2026-11-22T11:59:59Z'},{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now,...accessConfig}),/absent, expired, or invalid/); - assert.throws(()=>assertPreflight({...good,evidence_ref:''},{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now,...accessConfig}),/absent, expired, or invalid/); - assert.throws(()=>assertPreflight({...good,release_policy:{...good.release_policy,branch_protected:false}},{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now,...accessConfig}),/protected-main/); - assert.throws(()=>assertPreflight({...good,release_policy:{...good.release_policy,environment_reviewers_required:{'cloudflare-staging':false}}},{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now,...accessConfig}),/protected-main/); + const good={schema:1,verified:true,account_id:acct,verified_at:'2026-11-22T11:58:00Z',expires_at:'2026-11-22T12:10:00Z',evidence_ref:'review-1',release_policy:{repository:'developing-today/code',branch:'main',branch_protected:true,required_pull_request_reviews:true,force_push_disabled:true,admin_bypass_disabled:true,environment_reviewers_required:{'cloudflare-staging':true,'cloudflare-staging-smoke':true},self_review_disabled:{'cloudflare-staging':true,'cloudflare-staging-smoke':true},allowed_environment_branches:{'cloudflare-staging':['main'],'cloudflare-staging-smoke':['main']},evidence_ref:'policy-review-1'},targets:{'private-laptop-bridge-staging':{environment:'cloudflare-staging',exists:true,script_id:'private-laptop-bridge-staging',worker_id:workerId,account_id:acct,application_enabled:false,workers_dev:false,preview_urls:false,routes:[],custom_domains:[BRIDGE_HOST],access_app:accessApp,observability:{enabled:false,logs:false,traces:false},limits:{cpu_ms:10},gateway_forward_policy_ids:[],gateway_caller_ids:[],variables:{ENABLED:'false',GATEWAY_HOST:'private-bridge-staging.invalid',GATEWAY_ACCOUNT_ID:'',GATEWAY_POLICY_ID:'',GATEWAY_IDENTITY_EMAIL:'',GATEWAY_POSTURE_ID:'',BRIDGE_HOST,ACCESS_ISSUER:'https://team.cloudflareaccess.com',ACCESS_AUDIENCE:'audience-with-exact-length-012345',BRIDGE_REGISTRY:''},bindings:[{name:'BRIDGE',type:'durable_object_namespace',class_name:'PrivateLaptopBridge',namespace_id:'1'.repeat(32)}],declarative_exports:{PrivateLaptopBridge:{state:'created',storage:'sqlite'}},do:{id:'1'.repeat(32),class:'PrivateLaptopBridge',script:'private-laptop-bridge-staging',use_sqlite:true}}}}; + assert.equal(assertPreflight(good,{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',expectedWorkerId:workerId,now,...accessConfig}),true); + assert.throws(()=>assertPreflight(good,{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',expectedWorkerId:workerId,now,accessIssuer:'',accessAudience:''}),/differ from the protected build configuration/); + assert.throws(()=>assertPreflight({...good,verified:false},{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',expectedWorkerId:workerId,now,...accessConfig}),/absent, expired, older than fifteen minutes, or invalid/); + assert.throws(()=>assertPreflight({...good,verified_at:'2026-11-22T11:44:59Z'},{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',expectedWorkerId:workerId,now,...accessConfig}),/older than fifteen minutes/); + assert.throws(()=>assertPreflight({...good,expires_at:'2026-11-22T12:14:00Z'},{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',expectedWorkerId:workerId,now,...accessConfig}),/absent, expired, older than fifteen minutes, or invalid/); + assert.throws(()=>assertPreflight({...good,evidence_ref:''},{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',expectedWorkerId:workerId,now,...accessConfig}),/absent, expired, older than fifteen minutes, or invalid/); + assert.throws(()=>assertPreflight(good,{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',expectedWorkerId:otherWorkerId,now,...accessConfig}),/pinned immutable Worker ID/); + assert.throws(()=>assertPreflight({...good,release_policy:{...good.release_policy,branch_protected:false}},{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',expectedWorkerId:workerId,now,...accessConfig}),/protected-main/); + assert.throws(()=>assertPreflight({...good,release_policy:{...good.release_policy,environment_reviewers_required:{'cloudflare-staging':false}}},{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',expectedWorkerId:workerId,now,...accessConfig}),/protected-main/); for(const change of [ {gateway_caller_ids:['unexpected-caller']}, {routes:['https://public.example/*']}, @@ -120,18 +122,18 @@ test('read-only owner proof fails closed for missing, stale, public or unexpecte {declarative_exports:{PrivateLaptopBridge:{state:'created',storage:'sqlite'},Unexpected:{state:'created',storage:'sqlite'}}}, ]) { const target={...good.targets['private-laptop-bridge-staging'],...change}; - assert.throws(()=>assertPreflight({...good,targets:{...good.targets,'private-laptop-bridge-staging':target}},{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now,...accessConfig})); + assert.throws(()=>assertPreflight({...good,targets:{...good.targets,'private-laptop-bridge-staging':target}},{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',expectedWorkerId:workerId,now,...accessConfig})); } - const smokeTarget={environment:'cloudflare-staging-smoke',exists:true,script_id:'private-laptop-bridge-smoke',account_id:acct,application_enabled:false,workers_dev:false,preview_urls:false,routes:[],custom_domains:[],observability:{enabled:false,logs:false,traces:false},limits:{cpu_ms:10},gateway_forward_policy_ids:[],gateway_caller_ids:[],variables:{ENABLED:'false',GATEWAY_HOST:'private-bridge-smoke.invalid',GATEWAY_ACCOUNT_ID:'',GATEWAY_POLICY_ID:'',START_MS:'',END_MS:''},bindings:[],do:null}; - assert.equal(assertPreflight({...good,targets:{'private-laptop-bridge-smoke':smokeTarget}},{accountId:acct,worker:'private-laptop-bridge-smoke',environment:'cloudflare-staging-smoke',now}),true); + const smokeTarget={environment:'cloudflare-staging-smoke',exists:true,script_id:'private-laptop-bridge-smoke',worker_id:workerId,account_id:acct,application_enabled:false,workers_dev:false,preview_urls:false,routes:[],custom_domains:[],observability:{enabled:false,logs:false,traces:false},limits:{cpu_ms:10},gateway_forward_policy_ids:[],gateway_caller_ids:[],variables:{ENABLED:'false',GATEWAY_HOST:'private-bridge-smoke.invalid',GATEWAY_ACCOUNT_ID:'',GATEWAY_POLICY_ID:'',START_MS:'',END_MS:''},bindings:[],do:null}; + assert.equal(assertPreflight({...good,targets:{'private-laptop-bridge-smoke':smokeTarget}},{accountId:acct,worker:'private-laptop-bridge-smoke',environment:'cloudflare-staging-smoke',expectedWorkerId:workerId,now}),true); }); test('Versions release proof separately requires an existing Worker and its ready same-Worker DO namespace',()=>{ const now=Date.parse('2026-11-22T12:00:00Z'); const policy={repository:'developing-today/code',branch:'main',branch_protected:true,required_pull_request_reviews:true,force_push_disabled:true,admin_bypass_disabled:true,environment_reviewers_required:{'cloudflare-staging':true},self_review_disabled:{'cloudflare-staging':true},allowed_environment_branches:{'cloudflare-staging':['main']},evidence_ref:'policy-review-1'}; - const bridge={environment:'cloudflare-staging',exists:true,script_id:'private-laptop-bridge-staging',account_id:acct,application_enabled:false,workers_dev:false,preview_urls:false,routes:[],custom_domains:[BRIDGE_HOST],access_app:accessApp,observability:{enabled:false,logs:false,traces:false},limits:{cpu_ms:10},gateway_forward_policy_ids:[],gateway_caller_ids:[],variables:{ENABLED:'false',GATEWAY_HOST:'private-bridge-staging.invalid',GATEWAY_ACCOUNT_ID:'',GATEWAY_POLICY_ID:'',GATEWAY_IDENTITY_EMAIL:'',GATEWAY_POSTURE_ID:'',BRIDGE_HOST,ACCESS_ISSUER:'https://team.cloudflareaccess.com',ACCESS_AUDIENCE:'audience-with-exact-length-012345',BRIDGE_REGISTRY:''},bindings:[{name:'BRIDGE',type:'durable_object_namespace',class_name:'PrivateLaptopBridge',namespace_id:'1'.repeat(32)}],declarative_exports:{PrivateLaptopBridge:{state:'created',storage:'sqlite'}},do:{id:'1'.repeat(32),class:'PrivateLaptopBridge',script:'private-laptop-bridge-staging',use_sqlite:true}}; - const makeProof=(target=bridge)=>({schema:1,verified:true,account_id:acct,verified_at:'2026-11-22T11:30:00Z',expires_at:'2026-11-22T13:00:00Z',evidence_ref:'worker-review-1',release_policy:policy,targets:{'private-laptop-bridge-staging':target}}); - const check=(proof)=>assertPreflight(proof,{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',now,...accessConfig}); + const bridge={environment:'cloudflare-staging',exists:true,script_id:'private-laptop-bridge-staging',worker_id:workerId,account_id:acct,application_enabled:false,workers_dev:false,preview_urls:false,routes:[],custom_domains:[BRIDGE_HOST],access_app:accessApp,observability:{enabled:false,logs:false,traces:false},limits:{cpu_ms:10},gateway_forward_policy_ids:[],gateway_caller_ids:[],variables:{ENABLED:'false',GATEWAY_HOST:'private-bridge-staging.invalid',GATEWAY_ACCOUNT_ID:'',GATEWAY_POLICY_ID:'',GATEWAY_IDENTITY_EMAIL:'',GATEWAY_POSTURE_ID:'',BRIDGE_HOST,ACCESS_ISSUER:'https://team.cloudflareaccess.com',ACCESS_AUDIENCE:'audience-with-exact-length-012345',BRIDGE_REGISTRY:''},bindings:[{name:'BRIDGE',type:'durable_object_namespace',class_name:'PrivateLaptopBridge',namespace_id:'1'.repeat(32)}],declarative_exports:{PrivateLaptopBridge:{state:'created',storage:'sqlite'}},do:{id:'1'.repeat(32),class:'PrivateLaptopBridge',script:'private-laptop-bridge-staging',use_sqlite:true}}; + const makeProof=(target=bridge)=>({schema:1,verified:true,account_id:acct,verified_at:'2026-11-22T11:58:00Z',expires_at:'2026-11-22T12:10:00Z',evidence_ref:'worker-review-1',release_policy:policy,targets:{'private-laptop-bridge-staging':target}}); + const check=(proof)=>assertPreflight(proof,{accountId:acct,worker:'private-laptop-bridge-staging',environment:'cloudflare-staging',expectedWorkerId:workerId,now,...accessConfig}); assert.equal(check(makeProof()),true); assert.throws(()=>check(makeProof({...bridge,exists:false})),/exact private disabled target/); for(const change of [ diff --git a/pm-stack/private-laptop-bridge/staging-bootstrap.mjs b/pm-stack/private-laptop-bridge/staging-bootstrap.mjs index aaa667349e..436ddb7d71 100644 --- a/pm-stack/private-laptop-bridge/staging-bootstrap.mjs +++ b/pm-stack/private-laptop-bridge/staging-bootstrap.mjs @@ -243,14 +243,32 @@ function verifyVersion(version, namespaceId, expectedVersionId) { return true; } -function verifyWorkerMetadata(worker) { +function verifyWorkerMetadata(worker, expectedWorkerId) { if (!worker || worker.name !== WORKER_NAME || !ID.test(worker.id ?? '') || worker.logpush !== false || - worker.observability?.enabled !== false || !worker.references || !Array.isArray(worker.references.domains)) { + worker.id.toLowerCase() !== expectedWorkerId.toLowerCase() || worker.observability?.enabled !== false || !worker.references || + !['dispatch_namespace_outbounds','domains','durable_objects','queues','workers'].every(key => Array.isArray(worker.references[key]))) { fail('Worker metadata is missing or its domain or telemetry state is unverifiable'); } return worker.id; } +function verifyWorkerReferences(worker, domains, {routed, zoneIds}) { + const refs=worker.references; + for(const kind of ['dispatch_namespace_outbounds','durable_objects','queues','workers']) { + if(refs[kind].length!==0) fail(`staging Worker has unexpected reverse ${kind} references`); + } + const referencedDomains=refs.domains; + const expected=routed?domains.filter(domain=>domain?.service===WORKER_NAME&&domain?.hostname===BRIDGE_HOST):[]; + if(expected.length!==(routed?1:0)||referencedDomains.length!==expected.length) fail('Worker reverse domain references do not match the stage ingress state'); + for(const ref of referencedDomains) { + if(!ref||typeof ref!=='object'||!ID.test(ref.id??'')||ref.hostname!==BRIDGE_HOST||!ID.test(ref.zone_id??'')|| + !zoneIds.includes(ref.zone_id.toLowerCase())||!expected.some(domain=>domain.id===ref.id&&domain.zone_id===ref.zone_id&&domain.hostname===ref.hostname)) { + fail('Worker reverse domain reference does not match the exact approved account domain'); + } + } + return true; +} + function exactBridgeDomains(domains, {deployed, zoneIds}) { if (!Array.isArray(domains)) fail('Worker domain inventory is unavailable'); const related = domains.filter(domain => domain?.service === WORKER_NAME || domain?.hostname === BRIDGE_HOST); @@ -280,7 +298,7 @@ function verifyNoGatewayAssociation(rules, workerId = null) { return true; } -async function readSnapshot({accountId, token, gatewayToken, expectedZoneIds, fetchImpl = fetch}) { +async function readSnapshot({accountId, token, gatewayToken, expectedZoneIds, expectedWorkerId, phase, fetchImpl = fetch}) { const zones = await readZones(fetchImpl, accountId, token, expectedZoneIds); await readRoutes(fetchImpl, accountId, token, zones); const gatewayRules = await listPages(fetchImpl, accountId, gatewayToken, '/gateway/rules', {pageSize: 100}); @@ -288,10 +306,13 @@ async function readSnapshot({accountId, token, gatewayToken, expectedZoneIds, fe const allDomains = await listPages(fetchImpl, accountId, token, '/workers/domains'); const allNamespaces = await listPages(fetchImpl, accountId, token, '/workers/durable_objects/namespaces', {pageSize: 1000}); const namespaces = allNamespaces.filter(item => item?.script === WORKER_NAME); - const worker = await cfRequest(fetchImpl, accountId, token, `/workers/workers/${WORKER_NAME}`, {allowMissingWorker: true}); - if (!worker) return {worker: null, namespaces, domains: allDomains, gatewayRules, - zoneIds: zones.map(zone => zone.id.toLowerCase()).sort()}; - const workerId = verifyWorkerMetadata(worker.result); + const workers = await listPages(fetchImpl, accountId, token, '/workers/workers', {params:{order_by:'name',order:'asc'}}); + if(workers.some(item=>!item||typeof item!=='object'||typeof item.name!=='string'||!ID.test(item.id??''))) fail('Beta Worker inventory contains malformed identity metadata'); + const named=workers.filter(item=>item.name===WORKER_NAME); + if(named.length!==1||named[0]?.id?.toLowerCase()!==expectedWorkerId?.toLowerCase()) fail('owner-created Worker is missing or differs from its pinned Beta identity'); + const worker = await cfRequest(fetchImpl, accountId, token, `/workers/workers/${encodeURIComponent(expectedWorkerId)}`); + const workerId = verifyWorkerMetadata(worker.result, expectedWorkerId); + verifyWorkerReferences(worker.result,allDomains,{routed:phase==='postflight',zoneIds:zones.map(zone=>zone.id.toLowerCase())}); verifyNoGatewayAssociation(gatewayRules, workerId); const subdomain = await cfRequest(fetchImpl, accountId, token, `/workers/scripts/${WORKER_NAME}/subdomain`); if (subdomain.result?.enabled !== false || subdomain.result?.previews_enabled !== false) fail('Worker subdomain or preview ingress is enabled'); @@ -328,12 +349,12 @@ async function readSnapshot({accountId, token, gatewayToken, expectedZoneIds, fe export function verifyProviderState(snapshot, {phase, expectedZoneIds, sourceSha, expectedWorkerId}) { if (!['preflight', 'init-postflight', 'postflight'].includes(phase)) fail('provider verification phase is invalid'); const expected = parseIds(expectedZoneIds, 'approved zone inventory'); - if (!snapshot || !Array.isArray(snapshot.namespaces) || !Array.isArray(snapshot.domains) || !Array.isArray(snapshot.zoneIds) || + if (!snapshot || !snapshot.worker || !snapshot.worker.references || !Array.isArray(snapshot.namespaces) || !Array.isArray(snapshot.domains) || !Array.isArray(snapshot.zoneIds) || snapshot.zoneIds.length !== expected.length || snapshot.zoneIds.some((id, index) => id !== expected[index])) fail('provider inventory snapshot is incomplete or has the wrong account zones'); - verifyNoGatewayAssociation(snapshot.gatewayRules, snapshot.worker?.id ?? null); - if (!snapshot.worker) fail('the fixed Worker must be created locally by an owner before CI may proceed'); - const id = verifyWorkerMetadata(snapshot.worker); - if (!ID.test(expectedWorkerId ?? '') || id !== expectedWorkerId.toLowerCase()) fail('Worker ID differs from the independently pinned environment identity'); + verifyNoGatewayAssociation(snapshot.gatewayRules, snapshot.worker.id); + if (!ID.test(expectedWorkerId ?? '')) fail('Worker ID is not independently pinned in the protected environment'); + const id = verifyWorkerMetadata(snapshot.worker, expectedWorkerId); + verifyWorkerReferences(snapshot.worker,snapshot.domains,{routed:phase==='postflight',zoneIds:expected}); if (Array.isArray(snapshot.deployments) && snapshot.deployments.length === 0) { exactBridgeDomains(snapshot.domains, {deployed: false, zoneIds: expected}); if (phase !== 'preflight' || snapshot.namespaces.length !== 0 || @@ -376,7 +397,7 @@ export async function verifyBootstrapPreflight({accountId, workerId, readToken, if (!ID.test(accountId ?? '') || typeof readToken !== 'string' || readToken.length < 20 || typeof gatewayToken !== 'string' || gatewayToken.length < 20 || readToken === gatewayToken) fail('protected bootstrap account or separate read-only credentials are missing'); const zones = parseIds(expectedZoneIds, 'approved zone inventory'); - const snapshot = await readSnapshot({accountId, token: readToken, gatewayToken, expectedZoneIds: zones, fetchImpl}); + const snapshot = await readSnapshot({accountId, token: readToken, gatewayToken, expectedZoneIds: zones, expectedWorkerId:workerId, phase:'preflight', fetchImpl}); return verifyProviderState(snapshot, {phase: 'preflight', expectedZoneIds: zones, sourceSha, expectedWorkerId: workerId}); } @@ -391,7 +412,7 @@ export async function verifyBootstrapPostflight({accountId, workerId, readToken, if (!ID.test(accountId ?? '') || typeof readToken !== 'string' || readToken.length < 20 || typeof gatewayToken !== 'string' || gatewayToken.length < 20 || readToken === gatewayToken) fail('protected read-only provider identities are missing'); const zones = parseIds(expectedZoneIds, 'approved zone inventory'); - const snapshot = await readSnapshot({accountId, token: readToken, gatewayToken, expectedZoneIds: zones, fetchImpl}); + const snapshot = await readSnapshot({accountId, token: readToken, gatewayToken, expectedZoneIds: zones, expectedWorkerId:workerId, phase, fetchImpl}); return verifyProviderState(snapshot, {phase, expectedZoneIds: zones, sourceSha, expectedWorkerId: workerId}); } diff --git a/pm-stack/private-laptop-bridge/staging-bootstrap.test.mjs b/pm-stack/private-laptop-bridge/staging-bootstrap.test.mjs index f95c8a7461..8e47201b5d 100644 --- a/pm-stack/private-laptop-bridge/staging-bootstrap.test.mjs +++ b/pm-stack/private-laptop-bridge/staging-bootstrap.test.mjs @@ -15,7 +15,7 @@ const domainId = '22222222-3333-4444-5555-666666666666'; const readToken = 'synthetic-read-token-long-enough'; const writeToken = 'synthetic-write-token-long-enough'; const gatewayToken = 'synthetic-gateway-read-token-long-enough'; -const worker = {id:workerId,name:WORKER_NAME,logpush:false,observability:{enabled:false},references:{domains:[]}}; +const worker = {id:workerId,name:WORKER_NAME,logpush:false,observability:{enabled:false},references:{domains:[],workers:[],durable_objects:[],dispatch_namespace_outbounds:[],queues:[]}}; const bindings = () => [ {name:'ENABLED',type:'plain_text',text:'false'}, {name:'GATEWAY_HOST',type:'plain_text',text:'private-bridge-staging.invalid'}, @@ -38,7 +38,7 @@ const deployment = () => ({id:deploymentId,versions:[{version_id:versionId,perce const domain = (fields={}) => ({id:domainId,service:WORKER_NAME,hostname:'laptop-bridge-staging.security.cab',enabled:true,previews_enabled:false,zone_id:zoneId,...fields}); const ns = () => ({id:namespaceId,script:WORKER_NAME,class:DO_CLASS,use_sqlite:true}); const snapshot = () => ({ - zoneIds:[zoneId],worker,workerId,subdomain:{enabled:false,previews_enabled:false}, + zoneIds:[zoneId],worker:{...worker,references:{...worker.references,domains:[{id:domainId,hostname:'laptop-bridge-staging.security.cab',zone_id:zoneId}]}},workerId,subdomain:{enabled:false,previews_enabled:false}, settings:{logpush:false,observability:{enabled:false},tail_consumers:[]},schedules:[], namespaces:[ns()],domains:[domain()],gatewayRules:[],version:version(),versions:[{id:versionId,metadata:{},number:1}],deployments:[deployment()], }); @@ -88,9 +88,10 @@ function response(result, {status=200,resultInfo={page:1,per_page:100,total_coun return new Response(JSON.stringify({success,result,errors,...(resultInfo === undefined ? {} : {result_info:resultInfo})}),{status}); } -function cloudflareFixture({target='absent', zones=[{id:zoneId,account:{id:accountId}}], zoneInfo, route=[], domains=[], namespaces=[], workerRecord=worker, versionRecord=version(), gatewayRules=[], deployments=[deployment()], legacyVersions=null, overrides={}}={}) { +function cloudflareFixture({target='absent', zones=[{id:zoneId,account:{id:accountId}}], zoneInfo, route=[], domains=[], namespaces=[], workerRecord=null, versionRecord=version(), gatewayRules=[], deployments=[deployment()], legacyVersions=null, overrides={}}={}) { const calls=[]; const versionsList=legacyVersions??(deployments.length?[{id:versionId,metadata:{},number:1}]:[]); + const effectiveWorkerRecord=workerRecord??{...worker,references:{...worker.references,domains:domains.filter(domain=>domain?.service===WORKER_NAME).map(domain=>({id:domain.id,hostname:domain.hostname,zone_id:domain.zone_id}))}}; const fetchImpl=async (url,init={})=>{ const parsed=new URL(url), method=init.method??'GET'; calls.push({url:parsed,method,token:init.headers?.authorization}); @@ -101,9 +102,10 @@ function cloudflareFixture({target='absent', zones=[{id:zoneId,account:{id:accou if(parsed.pathname==='/client/v4/accounts/'+accountId+'/gateway/rules') return response(gatewayRules); if(parsed.pathname==='/client/v4/accounts/'+accountId+'/workers/durable_objects/namespaces') return response(namespaces,{resultInfo:{page:1,per_page:1000,total_count:namespaces.length,total_pages:namespaces.length?1:0}}); if(parsed.pathname===`/client/v4/accounts/${accountId}/workers/scripts/${WORKER_NAME}/versions`) return response({items:versionsList},{resultInfo:{page:1,per_page:100,count:versionsList.length,total_count:versionsList.length,total_pages:versionsList.length?1:0}}); - if(parsed.pathname===`/client/v4/accounts/${accountId}/workers/workers/${WORKER_NAME}`) { + if(parsed.pathname===`/client/v4/accounts/${accountId}/workers/workers`) return response(target==='absent'?[]:[effectiveWorkerRecord],{resultInfo:{page:1,per_page:100,total_count:target==='absent'?0:1,total_pages:target==='absent'?0:1}}); + if(parsed.pathname===`/client/v4/accounts/${accountId}/workers/workers/${workerId}`) { if(target==='absent') return response(null,{status:404,success:false,resultInfo:undefined,errors:[{code:10007}]}); - return response(workerRecord,{resultInfo:undefined}); + return response(effectiveWorkerRecord,{resultInfo:undefined}); } if(parsed.pathname.endsWith(`/workers/scripts/${WORKER_NAME}/subdomain`)) return response({enabled:false,previews_enabled:false}); if(parsed.pathname.endsWith(`/workers/scripts/${WORKER_NAME}/script-settings`)) return response({logpush:false,observability:{enabled:false},tail_consumers:[]}); @@ -146,7 +148,7 @@ test('exact empty locally created Worker is the only first-deploy candidate; all assert.ok(f.calls.every(call=>call.method==='GET'&&call.token===`Bearer ${call.url.pathname.endsWith('/gateway/rules')?gatewayToken:readToken}`)); assert.ok(f.calls.some(call=>call.url.pathname===`/client/v4/zones/${zoneId}/workers/routes`)); assert.ok(f.calls.some(call=>call.url.pathname===`/client/v4/accounts/${accountId}/workers/scripts/${WORKER_NAME}/versions`)); - await assert.rejects(verifyBootstrapPreflight({accountId,workerId,readToken,gatewayToken,expectedZoneIds:[zoneId],sourceSha:sha,fetchImpl:cloudflareFixture({target:'absent'}).fetchImpl}),/created locally by an owner/); + await assert.rejects(verifyBootstrapPreflight({accountId,workerId,readToken,gatewayToken,expectedZoneIds:[zoneId],sourceSha:sha,fetchImpl:cloudflareFixture({target:'absent'}).fetchImpl}),/owner-created Worker is missing/); for(const bad of [ cloudflareFixture({target:'absent',zones:[]}), cloudflareFixture({target:'absent',route:[{id:'route',pattern:'*',script:WORKER_NAME}]}), @@ -158,23 +160,33 @@ test('exact empty locally created Worker is the only first-deploy candidate; all const unservedVersion=cloudflareFixture({target:'empty',deployments:[],legacyVersions:[{id:versionId,metadata:{},number:1}]}); await assert.rejects(verifyBootstrapPreflight({accountId,workerId,readToken,gatewayToken,expectedZoneIds:[zoneId],sourceSha:sha,fetchImpl:unservedVersion.fetchImpl}),/only the exact empty disabled locally created Worker/); const takeover=cloudflareFixture({target:'empty',deployments:[],domains:[],workerRecord:{...worker,id:'4'.repeat(32)}}); - await assert.rejects(verifyBootstrapPreflight({accountId,workerId,readToken,gatewayToken,expectedZoneIds:[zoneId],sourceSha:sha,fetchImpl:takeover.fetchImpl}),/Worker ID differs/); + await assert.rejects(verifyBootstrapPreflight({accountId,workerId,readToken,gatewayToken,expectedZoneIds:[zoneId],sourceSha:sha,fetchImpl:takeover.fetchImpl}),/pinned Beta identity/); assert.equal(verifyDistinctWriteCredential(readToken,gatewayToken,writeToken),true); assert.throws(()=>verifyDistinctWriteCredential(readToken,gatewayToken,gatewayToken),/separate/); }); test('bootstrap only accepts disabled no-ingress state; routed postflight verifies the Access-host phase',()=>{ const good=snapshot(); - assert.throws(()=>verifyProviderState(good,{phase:'preflight',expectedZoneIds:[zoneId],sourceSha:sha,expectedWorkerId:workerId}),/empty Worker already has a custom domain/); + assert.throws(()=>verifyProviderState(good,{phase:'preflight',expectedZoneIds:[zoneId],sourceSha:sha,expectedWorkerId:workerId}),/reverse domain references/); assert.equal(verifyProviderState(good,{phase:'postflight',expectedZoneIds:[zoneId],sourceSha:sha,expectedWorkerId:workerId}),'verified'); - const noIngress=snapshot();noIngress.domains=[]; + const noIngress=snapshot();noIngress.domains=[];noIngress.worker.references.domains=[]; assert.equal(verifyProviderState(noIngress,{phase:'preflight',expectedZoneIds:[zoneId],sourceSha:sha,expectedWorkerId:workerId}),'already-initialized-no-ingress'); assert.equal(verifyProviderState(noIngress,{phase:'init-postflight',expectedZoneIds:[zoneId],sourceSha:sha,expectedWorkerId:workerId}),'verified-no-ingress'); + for(const kind of ['workers','durable_objects','dispatch_namespace_outbounds','queues']) { + const referenced=structuredClone(noIngress);referenced.worker.references[kind]=[{id:workerId,name:'unexpected-worker'}]; + assert.throws(()=>verifyProviderState(referenced,{phase:'preflight',expectedZoneIds:[zoneId],sourceSha:sha,expectedWorkerId:workerId}),new RegExp(`reverse ${kind}`)); + } + const incompleteRefs=structuredClone(noIngress);delete incompleteRefs.worker.references.queues; + assert.throws(()=>verifyProviderState(incompleteRefs,{phase:'preflight',expectedZoneIds:[zoneId],sourceSha:sha,expectedWorkerId:workerId}),/metadata is missing/); + const wrongBetaId=structuredClone(noIngress);wrongBetaId.worker.id='4'.repeat(32); + assert.throws(()=>verifyProviderState(wrongBetaId,{phase:'preflight',expectedZoneIds:[zoneId],sourceSha:sha,expectedWorkerId:workerId}),/pinned Beta identity/); + const unexpectedDomain=structuredClone(noIngress);unexpectedDomain.worker.references.domains=[{id:'33333333-4444-5555-6666-777777777777',hostname:'other.example',zone_id:zoneId}]; + assert.throws(()=>verifyProviderState(unexpectedDomain,{phase:'init-postflight',expectedZoneIds:[zoneId],sourceSha:sha,expectedWorkerId:workerId}),/reverse domain references/); const extraVersion=structuredClone(noIngress);extraVersion.versions.push({id:'22222222-3333-4444-5555-666666666666',metadata:{},number:2}); assert.throws(()=>verifyProviderState(extraVersion,{phase:'init-postflight',expectedZoneIds:[zoneId],sourceSha:sha,expectedWorkerId:workerId}),/exactly one version/); - assert.throws(()=>verifyProviderState(good,{phase:'init-postflight',expectedZoneIds:[zoneId],sourceSha:sha,expectedWorkerId:workerId}),/empty Worker already has a custom domain/); - const reverseRef=snapshot();reverseRef.domains=[];reverseRef.worker=structuredClone(worker);reverseRef.worker.references.domains=[{hostname:'private-laptop-bridge-staging.security.cab'}]; - assert.throws(()=>verifyProviderState(reverseRef,{phase:'init-postflight',expectedZoneIds:[zoneId],sourceSha:sha,expectedWorkerId:workerId}),/reverse domain reference/); + assert.throws(()=>verifyProviderState(good,{phase:'init-postflight',expectedZoneIds:[zoneId],sourceSha:sha,expectedWorkerId:workerId}),/reverse domain references/); + const reverseRef=snapshot();reverseRef.domains=[];reverseRef.worker=structuredClone(worker);reverseRef.worker.references.domains=[{id:domainId,hostname:'laptop-bridge-staging.security.cab',zone_id:zoneId}]; + assert.throws(()=>verifyProviderState(reverseRef,{phase:'init-postflight',expectedZoneIds:[zoneId],sourceSha:sha,expectedWorkerId:workerId}),/reverse domain references/); assert.throws(()=>verifyProviderState(noIngress,{phase:'preflight',expectedZoneIds:[zoneId],sourceSha:'c'.repeat(40),expectedWorkerId:workerId}),/exact reviewed source SHA/); for(const mutate of [ s=>{s.zoneIds=[];}, From 4fb2ce2c25db793fc88cf651889897c475117d5a Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 10:15:54 +0000 Subject: [PATCH 30/33] fix(bridge): accept Cloudflare domain UUIDs in references --- pm-stack/private-laptop-bridge/staging-bootstrap.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pm-stack/private-laptop-bridge/staging-bootstrap.mjs b/pm-stack/private-laptop-bridge/staging-bootstrap.mjs index 436ddb7d71..08dd8f4881 100644 --- a/pm-stack/private-laptop-bridge/staging-bootstrap.mjs +++ b/pm-stack/private-laptop-bridge/staging-bootstrap.mjs @@ -261,7 +261,7 @@ function verifyWorkerReferences(worker, domains, {routed, zoneIds}) { const expected=routed?domains.filter(domain=>domain?.service===WORKER_NAME&&domain?.hostname===BRIDGE_HOST):[]; if(expected.length!==(routed?1:0)||referencedDomains.length!==expected.length) fail('Worker reverse domain references do not match the stage ingress state'); for(const ref of referencedDomains) { - if(!ref||typeof ref!=='object'||!ID.test(ref.id??'')||ref.hostname!==BRIDGE_HOST||!ID.test(ref.zone_id??'')|| + if(!ref||typeof ref!=='object'||!(ID.test(ref.id??'')||UUID.test(ref.id??''))||ref.hostname!==BRIDGE_HOST||!ID.test(ref.zone_id??'')|| !zoneIds.includes(ref.zone_id.toLowerCase())||!expected.some(domain=>domain.id===ref.id&&domain.zone_id===ref.zone_id&&domain.hostname===ref.hostname)) { fail('Worker reverse domain reference does not match the exact approved account domain'); } From cb833bed6b74968a3d1a989a58a943feb627618c Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 10:18:10 +0000 Subject: [PATCH 31/33] fix(bridge): report Beta identity mismatch clearly --- pm-stack/private-laptop-bridge/staging-bootstrap.mjs | 9 ++++++--- .../private-laptop-bridge/staging-bootstrap.test.mjs | 2 +- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/pm-stack/private-laptop-bridge/staging-bootstrap.mjs b/pm-stack/private-laptop-bridge/staging-bootstrap.mjs index 08dd8f4881..d07b012805 100644 --- a/pm-stack/private-laptop-bridge/staging-bootstrap.mjs +++ b/pm-stack/private-laptop-bridge/staging-bootstrap.mjs @@ -244,10 +244,13 @@ function verifyVersion(version, namespaceId, expectedVersionId) { } function verifyWorkerMetadata(worker, expectedWorkerId) { - if (!worker || worker.name !== WORKER_NAME || !ID.test(worker.id ?? '') || worker.logpush !== false || - worker.id.toLowerCase() !== expectedWorkerId.toLowerCase() || worker.observability?.enabled !== false || !worker.references || + if (!worker || worker.name !== WORKER_NAME || !ID.test(worker.id ?? '')) { + fail('Worker identity metadata is missing or malformed'); + } + if (worker.id.toLowerCase() !== expectedWorkerId.toLowerCase()) fail('Worker immutable ID does not match the protected Beta identity'); + if (worker.logpush !== false || worker.observability?.enabled !== false || !worker.references || !['dispatch_namespace_outbounds','domains','durable_objects','queues','workers'].every(key => Array.isArray(worker.references[key]))) { - fail('Worker metadata is missing or its domain or telemetry state is unverifiable'); + fail('Worker reverse references or telemetry state are missing or unverifiable'); } return worker.id; } diff --git a/pm-stack/private-laptop-bridge/staging-bootstrap.test.mjs b/pm-stack/private-laptop-bridge/staging-bootstrap.test.mjs index 8e47201b5d..1d993dcfea 100644 --- a/pm-stack/private-laptop-bridge/staging-bootstrap.test.mjs +++ b/pm-stack/private-laptop-bridge/staging-bootstrap.test.mjs @@ -179,7 +179,7 @@ test('bootstrap only accepts disabled no-ingress state; routed postflight verifi const incompleteRefs=structuredClone(noIngress);delete incompleteRefs.worker.references.queues; assert.throws(()=>verifyProviderState(incompleteRefs,{phase:'preflight',expectedZoneIds:[zoneId],sourceSha:sha,expectedWorkerId:workerId}),/metadata is missing/); const wrongBetaId=structuredClone(noIngress);wrongBetaId.worker.id='4'.repeat(32); - assert.throws(()=>verifyProviderState(wrongBetaId,{phase:'preflight',expectedZoneIds:[zoneId],sourceSha:sha,expectedWorkerId:workerId}),/pinned Beta identity/); + assert.throws(()=>verifyProviderState(wrongBetaId,{phase:'preflight',expectedZoneIds:[zoneId],sourceSha:sha,expectedWorkerId:workerId}),/immutable ID does not match/); const unexpectedDomain=structuredClone(noIngress);unexpectedDomain.worker.references.domains=[{id:'33333333-4444-5555-6666-777777777777',hostname:'other.example',zone_id:zoneId}]; assert.throws(()=>verifyProviderState(unexpectedDomain,{phase:'init-postflight',expectedZoneIds:[zoneId],sourceSha:sha,expectedWorkerId:workerId}),/reverse domain references/); const extraVersion=structuredClone(noIngress);extraVersion.versions.push({id:'22222222-3333-4444-5555-666666666666',metadata:{},number:2}); From 5c70786eea3e0efc92984409e3caf46fd7676f74 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 10:20:21 +0000 Subject: [PATCH 32/33] test(bridge): assert incomplete reference metadata denial --- pm-stack/private-laptop-bridge/staging-bootstrap.test.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pm-stack/private-laptop-bridge/staging-bootstrap.test.mjs b/pm-stack/private-laptop-bridge/staging-bootstrap.test.mjs index 1d993dcfea..dcfef43c60 100644 --- a/pm-stack/private-laptop-bridge/staging-bootstrap.test.mjs +++ b/pm-stack/private-laptop-bridge/staging-bootstrap.test.mjs @@ -177,7 +177,7 @@ test('bootstrap only accepts disabled no-ingress state; routed postflight verifi assert.throws(()=>verifyProviderState(referenced,{phase:'preflight',expectedZoneIds:[zoneId],sourceSha:sha,expectedWorkerId:workerId}),new RegExp(`reverse ${kind}`)); } const incompleteRefs=structuredClone(noIngress);delete incompleteRefs.worker.references.queues; - assert.throws(()=>verifyProviderState(incompleteRefs,{phase:'preflight',expectedZoneIds:[zoneId],sourceSha:sha,expectedWorkerId:workerId}),/metadata is missing/); + assert.throws(()=>verifyProviderState(incompleteRefs,{phase:'preflight',expectedZoneIds:[zoneId],sourceSha:sha,expectedWorkerId:workerId}),/reverse references or telemetry state are missing/); const wrongBetaId=structuredClone(noIngress);wrongBetaId.worker.id='4'.repeat(32); assert.throws(()=>verifyProviderState(wrongBetaId,{phase:'preflight',expectedZoneIds:[zoneId],sourceSha:sha,expectedWorkerId:workerId}),/immutable ID does not match/); const unexpectedDomain=structuredClone(noIngress);unexpectedDomain.worker.references.domains=[{id:'33333333-4444-5555-6666-777777777777',hostname:'other.example',zone_id:zoneId}]; From 7f7c2e9317d3ce8e3e44d252f2434d5c6398b526 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 10:23:39 +0000 Subject: [PATCH 33/33] docs(bridge): bound pilot request and expiry controls --- pm-stack/private-laptop-bridge/STAGING.md | 2 ++ .../bridge-pilot-request.example.json | 8 +++++++- .../bridge-pilot-request.schema.json | 8 +++++--- 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/pm-stack/private-laptop-bridge/STAGING.md b/pm-stack/private-laptop-bridge/STAGING.md index 0f33f683f6..ce277af06a 100644 --- a/pm-stack/private-laptop-bridge/STAGING.md +++ b/pm-stack/private-laptop-bridge/STAGING.md @@ -517,6 +517,8 @@ and Ed25519 public keys are identity metadata, never private keys or service tokens. Any future pilot needs a separately reviewed change to executable configuration and a separate protected activation step. The present `bridge-init` and `bridge` configs remain disabled and cannot consume this file. +Each service-token expiry is explicit and must be no later than the pilot +window's end; the three kill conditions are fixed in the schema, not optional. The proposed pilot hostname is `laptop-bridge-pilot.security.cab`; its DNS ownership, wildcard interactions, Access application, issuer/audience, and diff --git a/pm-stack/private-laptop-bridge/bridge-pilot-request.example.json b/pm-stack/private-laptop-bridge/bridge-pilot-request.example.json index eba8c402a2..2b969b7b39 100644 --- a/pm-stack/private-laptop-bridge/bridge-pilot-request.example.json +++ b/pm-stack/private-laptop-bridge/bridge-pilot-request.example.json @@ -24,7 +24,11 @@ "enabled": false, "kill_switch": { "enabled_by_default": false, - "disable_on": "window_end", + "disable_on": [ + "window_end", + "any_identity_or_posture_failure", + "owner_request" + ], "revoke_access_tokens": true, "remove_host_association": true }, @@ -33,12 +37,14 @@ "role": "aster-caller", "principal_id": "", "access_client_id": "", + "access_token_expires_at": "", "ed25519_public_key": "" }, { "role": "amd-device", "principal_id": "", "access_client_id": "", + "access_token_expires_at": "", "ed25519_public_key": "" } ], diff --git a/pm-stack/private-laptop-bridge/bridge-pilot-request.schema.json b/pm-stack/private-laptop-bridge/bridge-pilot-request.schema.json index e8dd14a3b3..562268e1e0 100644 --- a/pm-stack/private-laptop-bridge/bridge-pilot-request.schema.json +++ b/pm-stack/private-laptop-bridge/bridge-pilot-request.schema.json @@ -47,7 +47,7 @@ "required": ["enabled_by_default", "disable_on", "revoke_access_tokens", "remove_host_association"], "properties": { "enabled_by_default": { "const": false }, - "disable_on": { "enum": ["window_end", "any_identity_or_posture_failure", "owner_request"] }, + "disable_on": { "const": ["window_end", "any_identity_or_posture_failure", "owner_request"] }, "revoke_access_tokens": { "const": true }, "remove_host_association": { "const": true } } @@ -56,20 +56,22 @@ "type": "array", "minItems": 2, "maxItems": 2, "prefixItems": [{ "type": "object", "additionalProperties": false, - "required": ["role", "principal_id", "access_client_id", "ed25519_public_key"], + "required": ["role", "principal_id", "access_client_id", "access_token_expires_at", "ed25519_public_key"], "properties": { "role": { "const": "aster-caller" }, "principal_id": { "type": "string", "pattern": "^[A-Za-z0-9._-]{8,128}$" }, "access_client_id": { "type": "string", "pattern": "^[A-Za-z0-9._-]{8,128}$" }, + "access_token_expires_at": { "type": "string", "format": "date-time" }, "ed25519_public_key": { "type": "string", "pattern": "^[A-Za-z0-9_-]{43}$" } } }, { "type": "object", "additionalProperties": false, - "required": ["role", "principal_id", "access_client_id", "ed25519_public_key"], + "required": ["role", "principal_id", "access_client_id", "access_token_expires_at", "ed25519_public_key"], "properties": { "role": { "const": "amd-device" }, "principal_id": { "type": "string", "pattern": "^[A-Za-z0-9._-]{8,128}$" }, "access_client_id": { "type": "string", "pattern": "^[A-Za-z0-9._-]{8,128}$" }, + "access_token_expires_at": { "type": "string", "format": "date-time" }, "ed25519_public_key": { "type": "string", "pattern": "^[A-Za-z0-9_-]{43}$" } } }],