diff --git a/.github/workflows/private-laptop-bridge-release.yml b/.github/workflows/private-laptop-bridge-release.yml new file mode 100644 index 0000000000..8253e7a920 --- /dev/null +++ b/.github/workflows/private-laptop-bridge-release.yml @@ -0,0 +1,332 @@ +name: Private laptop bridge Workers release + +on: + workflow_dispatch: + inputs: + action: + 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; each environment token is scoped to only this Worker + type: choice + required: true + options: [bridge] + 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 }}-release + 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: + 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: + - 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: Validate trusted request and fixed target + id: target + working-directory: pm-stack/private-laptop-bridge + env: + ACTION_KIND: ${{ inputs.action }} + WORKER_KIND: ${{ inputs.worker }} + UPLOAD_RUN_ID: ${{ inputs.upload_run_id }} + run: | + set -euo pipefail + [[ "$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 + [[ "$WORKER_KIND" == bridge ]] + echo "worker=private-laptop-bridge-staging" >> "$GITHUB_OUTPUT" + echo "environment=cloudflare-staging" >> "$GITHUB_OUTPUT" + echo "mode=bridge" >> "$GITHUB_OUTPUT" + - 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: + TARGET_WORKER: ${{ steps.target.outputs.worker }} + TARGET_ENV: ${{ steps.target.outputs.environment }} + TARGET_MODE: ${{ steps.target.outputs.mode }} + CF_ACCOUNT_ID: ${{ secrets.CF_BRIDGE_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_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 }} + 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: 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 + 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_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 + - name: Require existing exact Worker; never bootstrap from CI + working-directory: pm-stack/private-laptop-bridge + env: + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CF_BRIDGE_ACCOUNT_ID }} + CLOUDFLARE_API_TOKEN: ${{ secrets.CF_BRIDGE_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 + [[ "$WORKER_KIND" == bridge ]] + node --test gateway.test.mjs + - 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 }} + 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 + - 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 effective prebuilt upload payload + working-directory: pm-stack/private-laptop-bridge + 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 + 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[@]}" 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_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 }} + 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 }} + 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" + 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" > "$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_BRIDGE_ACCOUNT_ID }} + 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 }} + 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 + 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: Revalidate current private proof immediately before promotion + if: inputs.action == 'promote' + working-directory: pm-stack/private-laptop-bridge + 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 }} + 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_BRIDGE_ACCOUNT_ID }} + CLOUDFLARE_API_TOKEN: ${{ secrets.CF_BRIDGE_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}]" > "$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/doc/fleet-schedule-registry.md b/doc/fleet-schedule-registry.md index 5395d0fe95..b8ebfecbe3 100644 --- a/doc/fleet-schedule-registry.md +++ b/doc/fleet-schedule-registry.md @@ -486,7 +486,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 (5 entries) +## Surface 6 — PM-stack process intervals (6 entries, including one proposed/disabled) Recurring loops owned by PM-stack processes (aggregator, console, dispatch). These are not external scheduler surfaces; this inventory records timers that run only @@ -499,6 +499,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 (3 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 new file mode 100644 index 0000000000..9867511437 --- /dev/null +++ b/pm-stack/aggregator/src/bridge-snapshot.ts @@ -0,0 +1,99 @@ +// 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.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 = { + 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/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 bf89558435..0bd1483602 100644 --- a/pm-stack/aggregator/src/sources/live.ts +++ b/pm-stack/aggregator/src/sources/live.ts @@ -7,6 +7,8 @@ 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 { 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"; @@ -887,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; // C3 health hook (#9571): fired when the laptop's OpenCode session // map cannot be read on an aggregator tick. Fire-and-forget. @@ -1568,10 +1572,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] }; } @@ -1583,6 +1592,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 new file mode 100644 index 0000000000..883348fc0e --- /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 { + 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; +} +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"))')); +}); diff --git a/pm-stack/private-laptop-bridge/.gitignore b/pm-stack/private-laptop-bridge/.gitignore new file mode 100644 index 0000000000..97ef33beaa --- /dev/null +++ b/pm-stack/private-laptop-bridge/.gitignore @@ -0,0 +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..9e9d96fa6d --- /dev/null +++ b/pm-stack/private-laptop-bridge/ACCESS-STAGING.md @@ -0,0 +1,148 @@ +# 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 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. `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, + 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 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 +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 + +- 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 + 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/DISCOVERY.md b/pm-stack/private-laptop-bridge/DISCOVERY.md new file mode 100644 index 0000000000..08daac0b16 --- /dev/null +++ b/pm-stack/private-laptop-bridge/DISCOVERY.md @@ -0,0 +1,311 @@ +# 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) 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 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 + 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. `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 +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 +cf build +cf workers versions create --worker private-laptop-bridge-smoke --tag offline --message offline --prebuilt --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. + +## 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`. 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, 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. + +**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 +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. + +**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 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 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 +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_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 +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/)). 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 +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 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`. 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 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. + +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. + +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. 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 +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/). + +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/README.md b/pm-stack/private-laptop-bridge/README.md new file mode 100644 index 0000000000..000008211d --- /dev/null +++ b/pm-stack/private-laptop-bridge/README.md @@ -0,0 +1,285 @@ +# Private laptop bridge — offline candidate + +**Not deployed; not a replacement-ready cutover.** Desktop Commander remains the +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. + +## 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 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 +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 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 + 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` 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 + 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. 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 +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. + +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, +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 run rehearse +npm run check:staging +``` + +`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. + +`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. 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. 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 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 +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 +that fails closed on missing owner proof. The optional process interval remains +proposed/disabled. The repository disables automatic PR CI, so local checks are +not hosted CI evidence. 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, 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. + +```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`, `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. + +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. + + +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/STAGING.md b/pm-stack/private-laptop-bridge/STAGING.md new file mode 100644 index 0000000000..ce277af06a --- /dev/null +++ b/pm-stack/private-laptop-bridge/STAGING.md @@ -0,0 +1,550 @@ +# 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. + +## Release lifecycle and current disabled preflight + +The real staging release has one definition: `cloudflare.config.ts` with +`cf --mode bridge`, pinned `cf@1.0.0-rc.1` Build Output v1, and the bridge-only +`.github/workflows/private-laptop-bridge-release.yml`. Upload produces an +immutable exact-UUID candidate; a separate gated promotion validates that exact +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. `cloudflare.config.ts` is the only deployment lifecycle source; +no Wrangler JSONC deployment or migration fallback is kept. + +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 +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. + +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 workflow draft + +Routine releases remain versions-only and must refuse an absent Worker or +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. 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) + +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 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 and immutable Worker ID. The template fails closed if any part +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 +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 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 +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, +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. 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 +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-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 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. 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 +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/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 +`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. + +`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 +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) + +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 +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. + +## 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`, +`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.** 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. +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/) + +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 +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/) + +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 +{ + "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. + +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. +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 +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/VERIFICATION.md b/pm-stack/private-laptop-bridge/VERIFICATION.md new file mode 100644 index 0000000000..6d2b07d5ba --- /dev/null +++ b/pm-stack/private-laptop-bridge/VERIFICATION.md @@ -0,0 +1,399 @@ +# 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 +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. + +## 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. 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. +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. + +## 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, legacy pending-migration rejection, and +the API error handler for a binding to an export that has not yet been +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 +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, 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. + +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; 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. + +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 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 +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. + +### 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/). + +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_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. + +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 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. + +## Main reconciliation checkpoint — 2026-11-23 + +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: + +```text +node --test bootstrap-smoke.test.mjs deployment-config.test.mjs release-contract.test.mjs smoke-upload.test.mjs gateway.test.mjs +60 passed, 0 failed +npm run check:staging +cf Build Output v1 bridge build completed; effective Build Output validated for private-laptop-bridge-staging +YAML parse + bash -n for 16 embedded workflow shell blocks; passed +bash -n check-staging.sh; passed +git diff --check; passed +``` + +`check:staging` runs only a local build and `--dry-run`; it validates the built +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 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 +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 | 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 | +| 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. + +## 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. + +Historical local checks from the earlier bridge-mode draft (not evidence for the +current source head): + +```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. + +## 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, 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. + +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/access-auth.mjs b/pm-stack/private-laptop-bridge/access-auth.mjs new file mode 100644 index 0000000000..1c34272067 --- /dev/null +++ b/pm-stack/private-laptop-bridge/access-auth.mjs @@ -0,0 +1,93 @@ +// 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 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}`; + +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 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' || 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'); + 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) || + 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); + 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 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 new file mode 100644 index 0000000000..413950211a --- /dev/null +++ b/pm-stack/private-laptop-bridge/access-auth.test.mjs @@ -0,0 +1,143 @@ +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, access=audience, includeClientId=true}={}) => { + const jwt = tokenOverride ?? await token(claims,signingPair,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, 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,iat:now/1000-100}, + {iat:now/1000+31}, + {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/); +}); + +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 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']); + 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,{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); + 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,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); + 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); +}); + +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/adapters.mjs b/pm-stack/private-laptop-bridge/adapters.mjs new file mode 100644 index 0000000000..30ff036822 --- /dev/null +++ b/pm-stack/private-laptop-bridge/adapters.mjs @@ -0,0 +1,73 @@ +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'; +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()) { + 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 || 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) { + 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]])), 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. +// 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], memoryFreeBytes: 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/aster.mjs b/pm-stack/private-laptop-bridge/aster.mjs new file mode 100644 index 0000000000..cbbfdef45a --- /dev/null +++ b/pm-stack/private-laptop-bridge/aster.mjs @@ -0,0 +1,100 @@ +// 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, + 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' + ? 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..46f287481d --- /dev/null +++ b/pm-stack/private-laptop-bridge/aster.test.mjs @@ -0,0 +1,171 @@ +// 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://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 }); + 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://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)),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('./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 }), + }); + 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, + 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]])), + 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 = []; + 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/bridge-pilot-request.example.json b/pm-stack/private-laptop-bridge/bridge-pilot-request.example.json new file mode 100644 index 0000000000..2b969b7b39 --- /dev/null +++ b/pm-stack/private-laptop-bridge/bridge-pilot-request.example.json @@ -0,0 +1,62 @@ +{ + "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", + "any_identity_or_posture_failure", + "owner_request" + ], + "revoke_access_tokens": true, + "remove_host_association": true + }, + "principals": [ + { + "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": "" + } + ], + "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..562268e1e0 --- /dev/null +++ b/pm-stack/private-laptop-bridge/bridge-pilot-request.schema.json @@ -0,0 +1,93 @@ +{ + "$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": { "const": ["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", "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", "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}$" } + } + }], + "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/caller.mjs b/pm-stack/private-laptop-bridge/caller.mjs new file mode 100644 index 0000000000..807d784f2d --- /dev/null +++ b/pm-stack/private-laptop-bridge/caller.mjs @@ -0,0 +1,156 @@ +// 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) { + 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, 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.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'); + + 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 }); + 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 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(); } + 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, startedAt }; + }; + 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', '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 } = {}) { + 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/check-staging.sh b/pm-stack/private-laptop-bridge/check-staging.sh new file mode 100755 index 0000000000..b8b6448c79 --- /dev/null +++ b/pm-stack/private-laptop-bridge/check-staging.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +set -euo pipefail + +worker=private-laptop-bridge-staging +tmp="$(mktemp -d)" +output="$tmp/dry-run.log" +export XDG_CONFIG_HOME="$tmp/config" +export WRANGLER_SEND_METRICS=false +mkdir -p "$XDG_CONFIG_HOME" +trap 'rm -rf "$tmp"' EXIT + +./node_modules/.bin/cf build --mode bridge +./node_modules/.bin/cf -q workers versions create \ + --worker "$worker" --mode bridge --prebuilt --dry-run >"$output" 2>&1 +TARGET_WORKER="$worker" TARGET_MODE=bridge DRY_RUN_OUTPUT="$output" \ + node release-artifact.mjs dry-run diff --git a/pm-stack/private-laptop-bridge/client.mjs b/pm-stack/private-laptop-bridge/client.mjs new file mode 100644 index 0000000000..586411e896 --- /dev/null +++ b/pm-stack/private-laptop-bridge/client.mjs @@ -0,0 +1,136 @@ +// 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'; +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; +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','accessClientId','accessClientSecret'])) throw new Error('invalid-config'); + const origin = new URL(config.origin); + 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; +} +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, 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 || 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 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'); } + return { body: await readResponse(response, bounded), startedAt }; + } + async function step(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','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, 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 (expiresAt <= now() || leaseExpiresAt <= now()) throw new Error('expired-job'); + if (!validateResult(job.operation, result)) throw new Error('invalid-result'); + 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) { + // 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. + 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..ddb94ab831 --- /dev/null +++ b/pm-stack/private-laptop-bridge/client.test.mjs @@ -0,0 +1,144 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +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'; +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://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', () => { + 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://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,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'}})); +}); + +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({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'}}}}]); +}); + +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,2000]); +}); + +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,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'}]); +}); + +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 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,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); + 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/cloudflare.config.ts b/pm-stack/private-laptop-bridge/cloudflare.config.ts index b65c79d077..22363a89d3 100644 --- a/pm-stack/private-laptop-bridge/cloudflare.config.ts +++ b/pm-stack/private-laptop-bridge/cloudflare.config.ts @@ -1,24 +1,54 @@ -import {bindings, defineConfig} from 'cf/config'; +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'; -export default defineConfig({ +const isolated = () => ({ + workersDev: false, + previewUrls: false, + domains: [], + triggers: [], + limits: {cpuMs: 10}, + observability: {enabled: false, logs: {enabled: false}, traces: {enabled: false}}, +}); + +// The bridge mode is the sole real staging release definition. It remains disabled +// 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' || mode === 'bridge-init' ? ({ worker: { + ...isolated(), + // 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, + 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_HOST: bindings.text(BRIDGE_HOST), + 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'}), + }, + }, +}) : ({ + worker: { + ...isolated(), name: 'private-laptop-bridge-smoke', compatibilityDate: '2026-07-30', - workersDev: false, - previewUrls: false, - domains: [], - triggers: [], - limits: {cpuMs: 10}, - observability: {enabled: false, logs: {enabled: false}, traces: {enabled: false}}, entrypoint: smoke, 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(''), + 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/control.test.mjs b/pm-stack/private-laptop-bridge/control.test.mjs new file mode 100644 index 0000000000..b420a37222 --- /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)), 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://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, get object(){return object;}, 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 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 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); +}); + +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}, () => 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 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); +}); + +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 h.object.fetch(large)).status, 413); + const req = await h.request('alice', '/v1/poll', {}); + req.headers.set('content-length', '90000000000'); + 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 h.object.fetch(bad)).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/deployment-config.test.mjs b/pm-stack/private-laptop-bridge/deployment-config.test.mjs new file mode 100644 index 0000000000..5ca9f6115e --- /dev/null +++ b/pm-stack/private-laptop-bridge/deployment-config.test.mjs @@ -0,0 +1,33 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {readdir, readFile} from 'node:fs/promises'; + +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'\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'\}\)/); + 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 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'); + 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/freshness.test.mjs b/pm-stack/private-laptop-bridge/freshness.test.mjs new file mode 100644 index 0000000000..431bddc283 --- /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)), 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 => object.fetch(request); + const execute = createAdapters({ readSnapshot:()=>readQueueSnapshot(home), clock:()=>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); + 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-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 new file mode 100644 index 0000000000..a8534d3043 --- /dev/null +++ b/pm-stack/private-laptop-bridge/gateway.mjs @@ -0,0 +1,56 @@ +// 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, {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']); +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 dispatchSignedRequest(request, this.env); + } +} + +// 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, 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 new file mode 100644 index 0000000000..d05eb07357 --- /dev/null +++ b/pm-stack/private-laptop-bridge/gateway.test.mjs @@ -0,0 +1,128 @@ +// 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 {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) { + 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)), 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');}}, + {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('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)); + 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://${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'}); +}); + +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/model.test.mjs b/pm-stack/private-laptop-bridge/model.test.mjs new file mode 100644 index 0000000000..7f50f17f27 --- /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)), 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++) { + 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://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}`); + 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 index 06220cd84a..29acd5a41c 100644 --- a/pm-stack/private-laptop-bridge/package-lock.json +++ b/pm-stack/private-laptop-bridge/package-lock.json @@ -1,12 +1,13 @@ { - "name": "private-laptop-bridge-smoke", + "name": "private-laptop-bridge", "lockfileVersion": 3, "requires": true, "packages": { "": { - "name": "private-laptop-bridge-smoke", + "name": "private-laptop-bridge", "devDependencies": { "cf": "1.0.0-rc.1", + "miniflare": "4.20260730.0", "wrangler": "4.166.0" }, "engines": { @@ -139,1406 +140,1593 @@ "node": ">=16" } }, - "node_modules/@cloudflare/runtime-types/node_modules/miniflare": { - "version": "5.20261117.0-beta", - "resolved": "https://registry.npmjs.org/miniflare/-/miniflare-5.20261117.0-beta.tgz", - "integrity": "sha512-D2ygY04wQUmbpwgBhj828piErZoj7UMlXNGr4EWQp/c1PNGHyYOh0dMIyobjwOXiD5Ifl1EaEVAoNuBHK+qtkw==", + "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", - "dependencies": { - "@cspotcode/source-map-support": "0.8.1", - "sharp": "0.35.5", - "undici": "7.30.1", - "workerd": "1.20261117.1", - "ws": "8.21.0", - "youch": "4.1.0-beta.10" - }, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], "engines": { - "node": ">=22.12.0" + "node": ">=20.9.0" }, - "peerDependencies": { - "kerberos": "^2.0.0" + "funding": { + "url": "https://opencollective.com/libvips" }, - "peerDependenciesMeta": { - "kerberos": { - "optional": true - } - } - }, - "node_modules/@cloudflare/runtime-types/node_modules/undici": { - "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": { - "node": ">=20.18.1" + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.3.4" } }, - "node_modules/@cloudflare/runtime-types/node_modules/workerd": { - "version": "1.20261117.1", - "resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20261117.1.tgz", - "integrity": "sha512-iakDbGVtJRiErpWSM5fYT0z3spJ2Mo1x/POsEajBNLqUbTRwm8vMqbB7g8zPN2tzs6eZYNiO5ECyEnAXO9Foxw==", + "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, - "hasInstallScript": true, "license": "Apache-2.0", - "bin": { - "workerd": "bin/workerd" - }, + "optional": true, + "os": [ + "darwin" + ], "engines": { - "node": ">=16" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@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" + "@img/sharp-libvips-darwin-x64": "1.3.4" } }, - "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/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 OR Apache-2.0", - "peerDependencies": { - "unenv": "2.0.0-rc.24", - "workerd": ">1.20260305.0 <2.0.0-0" + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "dependencies": { + "@img/sharp-wasm32": "0.35.5" }, - "peerDependenciesMeta": { - "workerd": { - "optional": true - } + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" } }, - "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==", + "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": [ - "x64" + "arm64" ], "dev": true, - "license": "Apache-2.0", + "license": "LGPL-3.0-or-later", "optional": true, "os": [ "darwin" ], - "engines": { - "node": ">=16" + "funding": { + "url": "https://opencollective.com/libvips" } }, - "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==", + "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": [ - "arm64" + "x64" ], "dev": true, - "license": "Apache-2.0", + "license": "LGPL-3.0-or-later", "optional": true, "os": [ "darwin" ], - "engines": { - "node": ">=16" + "funding": { + "url": "https://opencollective.com/libvips" } }, - "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==", + "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": [ - "x64" + "arm" ], "dev": true, - "license": "Apache-2.0", + "license": "LGPL-3.0-or-later", "optional": true, "os": [ "linux" ], - "engines": { - "node": ">=16" + "funding": { + "url": "https://opencollective.com/libvips" } }, - "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==", + "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": "Apache-2.0", + "license": "LGPL-3.0-or-later", "optional": true, "os": [ "linux" ], - "engines": { - "node": ">=16" + "funding": { + "url": "https://opencollective.com/libvips" } }, - "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==", + "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": "Apache-2.0", + "license": "LGPL-3.0-or-later", "optional": true, "os": [ - "win32" + "linux" ], - "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/@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" + "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-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": [ - "ppc64" + "riscv64" ], "dev": true, - "license": "MIT", + "license": "LGPL-3.0-or-later", "optional": true, "os": [ - "aix" + "linux" ], - "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-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": [ - "arm" + "s390x" ], "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==", - "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==", + "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": [ "x64" ], "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-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": "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-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": "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-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": [ - "freebsd" + "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/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-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": [ - "x64" + "arm64" ], "dev": true, - "license": "MIT", + "license": "Apache-2.0", "optional": true, "os": [ - "freebsd" + "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-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-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": [ - "arm" + "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-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-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": [ - "arm64" + "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-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-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": [ - "ia32" + "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-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-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": [ - "loong64" + "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-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-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": [ - "mips64el" + "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-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-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": [ - "ppc64" + "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/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" - ], + "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": "MIT", + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", "optional": true, - "os": [ - "linux" - ], + "dependencies": { + "@emnapi/runtime": "^1.11.3" + }, "engines": { - "node": ">=18" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" } }, - "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-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": [ - "s390x" + "wasm32" ], "dev": true, - "license": "MIT", + "license": "Apache-2.0", "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" + "dependencies": { + "@img/sharp-wasm32": "0.35.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" } }, - "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-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": [ - "x64" + "arm64" ], "dev": true, - "license": "MIT", + "license": "Apache-2.0 AND LGPL-3.0-or-later", "optional": true, "os": [ - "linux" + "win32" ], "engines": { - "node": ">=18" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" } }, - "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-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": [ - "arm64" + "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/@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-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": "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/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/@cloudflare/runtime-types/node_modules/miniflare": { + "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", - "optional": true, - "os": [ - "openbsd" - ], + "dependencies": { + "@cspotcode/source-map-support": "0.8.1", + "sharp": "0.35.5", + "undici": "7.30.1", + "workerd": "1.20261117.1", + "ws": "8.21.0", + "youch": "4.1.0-beta.10" + }, "engines": { - "node": ">=18" + "node": ">=22.12.0" + }, + "peerDependencies": { + "kerberos": "^2.0.0" + }, + "peerDependenciesMeta": { + "kerberos": { + "optional": true + } } }, - "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/@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.30.1", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.30.1.tgz", + "integrity": "sha512-03KrMbjIFDWQR5RNPrSw3bd1r12JpyFQl9/yxjUbJtqkjmllqC5lFjZh6ujeuJCKr8EOQvRW872Oy/az+nLYxg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.18.1" + } + }, + "node_modules/@cloudflare/runtime-types/node_modules/workerd": { + "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", + "bin": { + "workerd": "bin/workerd" + }, + "engines": { + "node": ">=16" + }, + "optionalDependencies": { + "@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": { + "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": "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/@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": "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/@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": "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/@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": "MIT", + "license": "Apache-2.0", "optional": true, "os": [ - "win32" + "linux" ], "engines": { - "node": ">=18" + "node": ">=16" } }, - "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==", + "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": [ - "ia32" + "x64" ], "dev": true, - "license": "MIT", + "license": "Apache-2.0", "optional": true, "os": [ "win32" ], "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==", - "cpu": [ - "x64" - ], + "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", - "optional": true, - "os": [ - "win32" - ], "engines": { - "node": ">=18" + "node": ">=20.18.1" } }, - "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/@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/@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==", + "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.4" + "node": ">=18" } }, - "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==", + "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.4" + "node": ">=18" } }, - "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==", + "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.5" - }, "engines": { - "node": ">=20.9.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" + "node": ">=18" } }, - "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==", + "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.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==", + "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.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.4.tgz", - "integrity": "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==", + "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.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==", + "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.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==", + "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.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.4.tgz", - "integrity": "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==", + "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.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.4.tgz", - "integrity": "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==", + "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.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.4.tgz", - "integrity": "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==", + "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" - } - }, - "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" + "engines": { + "node": ">=18" } }, - "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==", + "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": [ - "x64" + "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-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==", + "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": [ - "arm" + "ppc64" ], "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.4" + "node": ">=18" } }, - "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==", + "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": [ - "arm64" + "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-arm64": "1.3.4" + "node": ">=18" } }, - "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==", + "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": [ - "ppc64" + "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-ppc64": "1.3.4" + "node": ">=18" } }, - "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==", + "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": [ - "riscv64" + "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": { - "@img/sharp-libvips-linux-riscv64": "1.3.4" + "node": ">=18" } }, - "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==", + "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": [ - "s390x" + "arm64" ], "dev": true, - "license": "Apache-2.0", + "license": "MIT", "optional": true, "os": [ - "linux" + "netbsd" ], "engines": { - "node": ">=20.9.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-linux-s390x": "1.3.4" + "node": ">=18" } }, - "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==", + "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": "Apache-2.0", + "license": "MIT", "optional": true, "os": [ - "linux" + "netbsd" ], "engines": { - "node": ">=20.9.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-linux-x64": "1.3.4" + "node": ">=18" } }, - "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==", + "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": "Apache-2.0", + "license": "MIT", "optional": true, "os": [ - "linux" + "openbsd" ], "engines": { - "node": ">=20.9.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-linuxmusl-arm64": "1.3.4" + "node": ">=18" } }, - "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==", + "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": "Apache-2.0", + "license": "MIT", "optional": true, "os": [ - "linux" + "openbsd" ], "engines": { - "node": ">=20.9.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-linuxmusl-x64": "1.3.4" + "node": ">=18" } }, - "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==", + "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": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "license": "MIT", "optional": true, - "dependencies": { - "@emnapi/runtime": "^1.11.3" - }, + "os": [ + "openharmony" + ], "engines": { - "node": ">=20.9.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" + "node": ">=18" } }, - "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==", + "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": [ - "wasm32" + "x64" ], "dev": true, - "license": "Apache-2.0", + "license": "MIT", "optional": true, - "dependencies": { - "@img/sharp-wasm32": "0.35.5" - }, + "os": [ + "sunos" + ], "engines": { - "node": ">=20.9.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" + "node": ">=18" } }, - "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==", + "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": "Apache-2.0 AND LGPL-3.0-or-later", + "license": "MIT", "optional": true, "os": [ "win32" ], "engines": { - "node": ">=20.9.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" + "node": ">=18" } }, - "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==", + "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": "Apache-2.0 AND LGPL-3.0-or-later", + "license": "MIT", "optional": true, "os": [ "win32" ], "engines": { - "node": "^20.9.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" + "node": ">=18" } }, - "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==", + "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": "Apache-2.0 AND LGPL-3.0-or-later", + "license": "MIT", "optional": true, "os": [ "win32" ], "engines": { - "node": ">=20.9.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" + "node": ">=18" } }, - "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==", + "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": ">=6.0.0" + "node": ">=18" } }, - "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==", + "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": "MIT" + "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/@jridgewell/trace-mapping": { - "version": "0.3.9", - "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", - "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", + "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": "MIT", - "dependencies": { - "@jridgewell/resolve-uri": "^3.0.3", - "@jridgewell/sourcemap-codec": "^1.4.10" + "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/@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/@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": "MIT", + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], "dependencies": { - "kleur": "^4.1.5" + "@img/sharp-wasm32": "0.35.2" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" } }, - "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/@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": "MIT", - "dependencies": { - "@poppinss/colors": "^4.1.5", - "@sindresorhus/is": "^7.0.2", - "supports-color": "^10.0.0" + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" } }, - "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==", + "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": "MIT" + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } }, - "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==", + "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": "MIT", - "engines": { - "node": ">=18" - }, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], "funding": { - "url": "https://github.com/sindresorhus/is?sponsor=1" + "url": "https://opencollective.com/libvips" } }, - "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==", + "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": "CC0-1.0" + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } }, - "node_modules/@types/node": { - "version": "18.19.130", - "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.130.tgz", - "integrity": "sha512-GRaXQx6jGfL8sKfaIDD6OupbIHBr9jv7Jnaml9tB7l4v068PAOXqfcujMMo5PhbIs6ggR1XODELqahT2R8v0fg==", + "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": "MIT", - "dependencies": { - "undici-types": "~5.26.4" + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" } }, - "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==", + "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": "MIT", - "dependencies": { - "@types/node": "*", - "form-data": "^4.0.4" + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" } }, - "node_modules/@types/yargs": { - "version": "17.0.24", - "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.24.tgz", - "integrity": "sha512-6i0aC7jV6QzQB8ne1joVZ0eSFIstHsCrobmOtghM11yGlH0j43FKL2UhWdELkyps0zuf7qVTUVCCR+tgSlyLLw==", + "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": "MIT", - "dependencies": { - "@types/yargs-parser": "*" + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" } }, - "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==", + "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": "MIT" + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } }, - "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==", + "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": "MIT", - "dependencies": { - "event-target-shim": "^5.0.0" - }, - "engines": { - "node": ">=6.5" + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" } }, - "node_modules/agentkeepalive": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/agentkeepalive/-/agentkeepalive-4.6.0.tgz", - "integrity": "sha512-kja8j7PjmncONqaTsB8fQ+wE2mSU2DJ9D4XKoJ5PFWIdRMa6SLSN1ff4mOr4jCbfRSsxR4keIiySJU0N9T5hIQ==", + "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": "MIT", - "dependencies": { - "humanize-ms": "^1.2.1" - }, - "engines": { - "node": ">= 8.0.0" + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" } }, - "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==", + "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": "MIT" + "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/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/@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": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "function-bind": "^1.1.2" - }, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], "engines": { - "node": ">= 0.4" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.3.1" } }, - "node_modules/cf": { - "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==", + "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": "MIT OR Apache-2.0", - "dependencies": { - "@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.20261117.0-beta" + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" }, - "bin": { - "cf": "bin/cf", - "cloudflare": "bin/cf" + "funding": { + "url": "https://opencollective.com/libvips" }, - "engines": { - "node": "^22.23.0 || ^24.22.0 || ^26.12.0" + "optionalDependencies": { + "@img/sharp-libvips-linux-ppc64": "1.3.1" } }, - "node_modules/cf/node_modules/@cloudflare/workerd-darwin-64": { - "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==", + "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": [ - "x64" + "riscv64" ], "dev": true, "license": "Apache-2.0", "optional": true, "os": [ - "darwin" + "linux" ], "engines": { - "node": ">=16" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-riscv64": "1.3.1" } }, - "node_modules/cf/node_modules/@cloudflare/workerd-darwin-arm64": { - "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==", + "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": [ - "arm64" + "s390x" ], "dev": true, "license": "Apache-2.0", "optional": true, "os": [ - "darwin" + "linux" ], "engines": { - "node": ">=16" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.3.1" } }, - "node_modules/cf/node_modules/@cloudflare/workerd-linux-64": { - "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==", + "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" ], @@ -1549,13 +1737,19 @@ "linux" ], "engines": { - "node": ">=16" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.3.1" } }, - "node_modules/cf/node_modules/@cloudflare/workerd-linux-arm64": { - "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==", + "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" ], @@ -1566,13 +1760,19 @@ "linux" ], "engines": { - "node": ">=16" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.3.1" } }, - "node_modules/cf/node_modules/@cloudflare/workerd-windows-64": { - "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==", + "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" ], @@ -1580,502 +1780,2336 @@ "license": "Apache-2.0", "optional": true, "os": [ - "win32" + "linux" ], "engines": { - "node": ">=16" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.3.1" } }, - "node_modules/cf/node_modules/miniflare": { - "version": "5.20261117.0-beta", - "resolved": "https://registry.npmjs.org/miniflare/-/miniflare-5.20261117.0-beta.tgz", - "integrity": "sha512-D2ygY04wQUmbpwgBhj828piErZoj7UMlXNGr4EWQp/c1PNGHyYOh0dMIyobjwOXiD5Ifl1EaEVAoNuBHK+qtkw==", + "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": "MIT", + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "optional": true, "dependencies": { - "@cspotcode/source-map-support": "0.8.1", - "sharp": "0.35.5", - "undici": "7.30.1", - "workerd": "1.20261117.1", - "ws": "8.21.0", - "youch": "4.1.0-beta.10" + "@emnapi/runtime": "^1.11.1" }, "engines": { - "node": ">=22.12.0" - }, - "peerDependencies": { - "kerberos": "^2.0.0" + "node": ">=20.9.0" }, - "peerDependenciesMeta": { - "kerberos": { - "optional": true - } - } - }, - "node_modules/cf/node_modules/undici": { - "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": { - "node": ">=20.18.1" + "funding": { + "url": "https://opencollective.com/libvips" } }, - "node_modules/cf/node_modules/workerd": { - "version": "1.20261117.1", - "resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20261117.1.tgz", - "integrity": "sha512-iakDbGVtJRiErpWSM5fYT0z3spJ2Mo1x/POsEajBNLqUbTRwm8vMqbB7g8zPN2tzs6eZYNiO5ECyEnAXO9Foxw==", + "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, - "hasInstallScript": true, "license": "Apache-2.0", - "bin": { - "workerd": "bin/workerd" + "optional": true, + "dependencies": { + "@img/sharp-wasm32": "0.35.2" }, "engines": { - "node": ">=16" + "node": ">=20.9.0" }, - "optionalDependencies": { - "@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" + "funding": { + "url": "https://opencollective.com/libvips" } }, - "node_modules/chalk": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.3.0.tgz", - "integrity": "sha512-dLitG79d+GV1Nb/VYcCDFivJeK1hiukt9QjRNVOsUtTy1rR1YJsmpGGTZ3qJos+uw7WmWF4wUwBd9jxjocFC2w==", + "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": "MIT", + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], "engines": { - "node": "^12.17.0 || ^14.13 || >=16.0.0" + "node": ">=20.9.0" }, "funding": { - "url": "https://github.com/chalk/chalk?sponsor=1" + "url": "https://opencollective.com/libvips" } }, - "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==", + "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", - "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" + "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/combined-stream": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", - "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "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": "MIT", - "dependencies": { - "delayed-stream": "~1.0.0" - }, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], "engines": { - "node": ">= 0.8" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" } }, - "node_modules/cookie": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz", - "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==", + "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": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" + "node": ">=6.0.0" } }, - "node_modules/delayed-stream": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", - "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "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", - "engines": { - "node": ">=0.4.0" + "dependencies": { + "@jridgewell/resolve-uri": "^3.0.3", + "@jridgewell/sourcemap-codec": "^1.4.10" } }, - "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==", + "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": "Apache-2.0", - "engines": { - "node": ">=8" + "license": "MIT", + "dependencies": { + "kleur": "^4.1.5" } }, - "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==", + "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": "BSD-3-Clause" + "license": "MIT", + "dependencies": { + "@poppinss/colors": "^4.1.5", + "@sindresorhus/is": "^7.0.2", + "supports-color": "^10.0.0" + } }, - "node_modules/dotenv": { - "version": "16.3.1", - "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.3.1.tgz", - "integrity": "sha512-IPzF4w4/Rd94bA9imS68tZBaYyBWSCE47V1RGuMrB94iyTOIEwRmVL2x/4An+6mETpLrKJ5hQkB8W4kFAadeIQ==", + "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": "BSD-2-Clause", + "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": ">=12" + "node": ">=18" }, "funding": { - "url": "https://github.com/motdotla/dotenv?sponsor=1" + "url": "https://github.com/sindresorhus/is?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==", + "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": { - "call-bind-apply-helpers": "^1.0.1", - "es-errors": "^1.3.0", - "gopd": "^1.2.0" - }, - "engines": { - "node": ">= 0.4" + "undici-types": "~5.26.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==", + "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", - "funding": { - "url": "https://github.com/sponsors/antfu" + "dependencies": { + "@types/node": "*", + "form-data": "^4.0.4" } }, - "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==", + "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", - "engines": { - "node": ">= 0.4" + "dependencies": { + "@types/yargs-parser": "*" } }, - "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==", + "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": ">= 0.4" + "node": ">=6.5" } }, - "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==", + "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": { - "es-errors": "^1.3.0" + "humanize-ms": "^1.2.1" }, "engines": { - "node": ">= 0.4" + "node": ">= 8.0.0" } }, - "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==", + "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", - "get-intrinsic": "^1.2.6", - "has-tostringtag": "^1.0.2", - "hasown": "^2.0.2" + "function-bind": "^1.1.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==", + "node_modules/cf": { + "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, - "hasInstallScript": true, - "license": "MIT", + "license": "MIT OR Apache-2.0", + "dependencies": { + "@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.20261117.0-beta" + }, "bin": { - "esbuild": "bin/esbuild" + "cf": "bin/cf", + "cloudflare": "bin/cf" }, "engines": { - "node": ">=18" + "node": "^22.23.0 || ^24.22.0 || ^26.12.0" + } + }, + "node_modules/cf/node_modules/@cloudflare/workerd-darwin-64": { + "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" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/cf/node_modules/@cloudflare/workerd-darwin-arm64": { + "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" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/cf/node_modules/@cloudflare/workerd-linux-64": { + "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" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/cf/node_modules/@cloudflare/workerd-linux-arm64": { + "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" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/cf/node_modules/@cloudflare/workerd-windows-64": { + "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" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16" + } + }, + "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" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" }, "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" + "@img/sharp-libvips-darwin-arm64": "1.3.4" } }, - "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==", + "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" + ], "dev": true, - "license": "MIT", + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], "engines": { - "node": ">=6" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.3.4" } }, - "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==", + "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": "MIT", + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], "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" + "@img/sharp-wasm32": "0.35.5" }, "engines": { - "node": ">= 6" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" } }, - "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==", + "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" + ], "dev": true, - "license": "MIT" + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } }, - "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==", + "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" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "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" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "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" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "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" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "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" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "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" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "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" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "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" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "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" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "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" + ], + "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.4" + } + }, + "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" + ], + "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/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" + ], + "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/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" + ], + "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/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" + ], + "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.4" + } + }, + "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" + ], + "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.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" + ], + "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.4" + } + }, + "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" + ], + "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.4" + } + }, + "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.3" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "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" + ], + "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/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" + ], + "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/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" + ], + "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/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" + ], + "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/cf/node_modules/miniflare": { + "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.30.1", + "workerd": "1.20261117.1", + "ws": "8.21.0", + "youch": "4.1.0-beta.10" + }, + "engines": { + "node": ">=22.12.0" + }, + "peerDependencies": { + "kerberos": "^2.0.0" + }, + "peerDependenciesMeta": { + "kerberos": { + "optional": true + } + } + }, + "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": "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/cf/node_modules/undici": { + "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": { + "node": ">=20.18.1" + } + }, + "node_modules/cf/node_modules/workerd": { + "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", + "bin": { + "workerd": "bin/workerd" + }, + "engines": { + "node": ">=16" + }, + "optionalDependencies": { + "@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": { + "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": "MIT", - "dependencies": { - "node-domexception": "1.0.0", - "web-streams-polyfill": "4.0.0-beta.3" - }, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], "engines": { - "node": ">= 12.20" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.3.4" } }, - "node_modules/fsevents": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", - "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "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, - "hasInstallScript": true, - "license": "MIT", + "license": "Apache-2.0", "optional": true, "os": [ - "darwin" + "linux" ], "engines": { - "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.3.4" } }, - "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==", + "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": "MIT", + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, "funding": { - "url": "https://github.com/sponsors/ljharb" + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-ppc64": "1.3.4" } }, - "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==", + "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": "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" - }, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], "engines": { - "node": ">= 0.4" + "node": ">=20.9.0" }, "funding": { - "url": "https://github.com/sponsors/ljharb" + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-riscv64": "1.3.4" } }, - "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==", + "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" + ], "dev": true, - "license": "MIT", - "dependencies": { - "dunder-proto": "^1.0.1", - "es-object-atoms": "^1.0.0" - }, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], "engines": { - "node": ">= 0.4" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.3.4" } }, - "node_modules/gopd": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", - "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "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" + ], "dev": true, - "license": "MIT", + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], "engines": { - "node": ">= 0.4" + "node": ">=20.9.0" }, "funding": { - "url": "https://github.com/sponsors/ljharb" + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.3.4" } }, - "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==", + "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" + ], "dev": true, - "license": "MIT", + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], "engines": { - "node": ">= 0.4" + "node": ">=20.9.0" }, "funding": { - "url": "https://github.com/sponsors/ljharb" + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4" } }, - "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==", + "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" + ], "dev": true, - "license": "MIT", - "dependencies": { - "has-symbols": "^1.0.3" - }, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], "engines": { - "node": ">= 0.4" + "node": ">=20.9.0" }, "funding": { - "url": "https://github.com/sponsors/ljharb" + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.3.4" } }, - "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==", + "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": "MIT", + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "optional": true, "dependencies": { - "function-bind": "^1.1.2" + "@emnapi/runtime": "^1.11.3" }, "engines": { - "node": ">= 0.4" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" } }, - "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==", + "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" + ], "dev": true, - "license": "MIT", + "license": "Apache-2.0", + "optional": true, "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", + "@img/sharp-wasm32": "0.35.5" + }, "engines": { - "node": ">=6" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" } }, - "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==", + "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" + ], "dev": true, - "license": "MIT", + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], "engines": { - "node": ">= 0.4" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" } }, - "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==", + "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" + ], "dev": true, - "license": "MIT", + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], "engines": { - "node": ">= 0.6" + "node": "^20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" } }, - "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==", + "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" + ], "dev": true, - "license": "MIT", - "dependencies": { - "mime-db": "1.52.0" - }, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], "engines": { - "node": ">= 0.6" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" } }, - "node_modules/miniflare": { + "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==", @@ -2101,83 +4135,7 @@ } } }, - "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": { + "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==", @@ -2227,35 +4185,7 @@ } } }, - "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": { + "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==", @@ -2265,52 +4195,7 @@ "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": { + "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==", @@ -2331,47 +4216,6 @@ "@cloudflare/workerd-windows-64": "1.20261119.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/ws": { "version": "8.21.0", "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz", diff --git a/pm-stack/private-laptop-bridge/package.json b/pm-stack/private-laptop-bridge/package.json index 857d3a763a..b1b2fca72e 100644 --- a/pm-stack/private-laptop-bridge/package.json +++ b/pm-stack/private-laptop-bridge/package.json @@ -1 +1,18 @@ -{"name":"private-laptop-bridge-smoke","private":true,"type":"module","engines":{"node":">=24.22.0"},"devDependencies":{"cf":"1.0.0-rc.1","wrangler":"4.166.0"}} +{ + "name": "private-laptop-bridge", + "private": true, + "type": "module", + "scripts": { + "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": "bash ./check-staging.sh" + }, + "engines": { + "node": ">=24.22.0" + }, + "devDependencies": { + "miniflare": "4.20260730.0", + "wrangler": "4.166.0", + "cf": "1.0.0-rc.1" + } +} 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..cb288f4853 --- /dev/null +++ b/pm-stack/private-laptop-bridge/private-laptop-bridge-staging-bootstrap.workflow.yml.disabled @@ -0,0 +1,116 @@ +# Dormant reviewed template. GitHub ignores this non-workflow extension. +# 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 + +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 }} + 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' + 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-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 + env: + 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 }} + 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_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 }} + run: | + set -euo pipefail + node staging-bootstrap.mjs assert-distinct-credentials + ./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 + env: + 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 }} + GITHUB_SHA: ${{ github.sha }} + run: node staging-bootstrap.mjs init-postflight 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..2f41435276 --- /dev/null +++ b/pm-stack/private-laptop-bridge/private-laptop-bridge.service.example @@ -0,0 +1,33 @@ +# 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 +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. +# No [Install] section: cannot be enabled as distributed. 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/release-artifact.mjs b/pm-stack/private-laptop-bridge/release-artifact.mjs new file mode 100644 index 0000000000..934d9287f2 --- /dev/null +++ b/pm-stack/private-laptop-bridge/release-artifact.mjs @@ -0,0 +1,81 @@ +#!/usr/bin/env node +import {readFile,writeFile} from 'node:fs/promises'; +import {resolve} from 'node:path'; +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 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(); + +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,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')); + 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==='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); +} 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=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}); + 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_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_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,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'); +} 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_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,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'); + 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,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 new file mode 100644 index 0000000000..3c10d08052 --- /dev/null +++ b/pm-stack/private-laptop-bridge/release-contract.mjs @@ -0,0 +1,241 @@ +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}$/; +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);}; +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');} + 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_sha256','mode','version_id','tag','config_digest','build_digest','preflight_digest','provenance_digest','expected_disabled']; +export function makeHandoff(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!==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) fail('handoff target/account/source mismatch'); +} + +export function verifyPromotionProvenance(handoff, expected) { + validateHandoffShape(handoff); + 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'); + 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 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'); + 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(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; +} + +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,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]; + 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.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(); + 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; +} + +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(!['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'); + return true; +} + +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&&!['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&&!bridgeInit?[BRIDGE_HOST]:[], + 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_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:'', + }; + 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..1d70b0281e --- /dev/null +++ b/pm-stack/private-laptop-bridge/release-contract.test.mjs @@ -0,0 +1,193 @@ +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', 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}`}}; +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 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'],['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/); +}); + +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 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,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/*']}, + {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']}, + {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',expectedWorkerId:workerId,now,...accessConfig})); + } + 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',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 [ + {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 export and namespace/); +}); + +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?.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); + 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'})); +}); + +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:[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,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/review.test.mjs b/pm-stack/private-laptop-bridge/review.test.mjs new file mode 100644 index 0000000000..507ef3440b --- /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://laptop-bridge-staging.security.cab',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)),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=>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}; +} + +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,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'}); +}); + +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,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,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,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);})]); + 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-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 new file mode 100644 index 0000000000..fdb0f9a79d --- /dev/null +++ b/pm-stack/private-laptop-bridge/runtime.test.mjs @@ -0,0 +1,276 @@ +// 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://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) { + 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)), accessClientId:`access-${id}-client`, 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, 'runtime-test-entry.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 { 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; + 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, 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, 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' } : {}; + 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, ...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'); } }); + 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,...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' } } }); + 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, ...testAccess,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); +}); 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/staging-bootstrap.mjs b/pm-stack/private-laptop-bridge/staging-bootstrap.mjs new file mode 100644 index 0000000000..d07b012805 --- /dev/null +++ b/pm-stack/private-laptop-bridge/staging-bootstrap.mjs @@ -0,0 +1,501 @@ +#!/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 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}$/; +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 parseReviewerIdentities(value) { + let reviewers; + try { reviewers = typeof value === 'string' ? JSON.parse(value) : value; } + catch { fail('expected independent reviewer IDs are 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 = 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, expectedEnvironmentName = ENVIRONMENT_NAME, dispatcherId}) { + if (!environment || environment.name !== expectedEnvironmentName || !Array.isArray(environment.protection_rules)) { + fail('the exact protected staging environment is absent or unverifiable'); + } + 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 => { + 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'); + } + 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' || rows[0]?.type !== 'branch') { + fail('staging environment API must prove exactly one branch-only main deployment rule'); + } + return {environment: expectedEnvironmentName}; +} + +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, 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_HOST, ACCESS_ISSUER: process.env.CF_BRIDGE_ACCESS_ISSUER ?? '', + ACCESS_AUDIENCE: process.env.CF_BRIDGE_ACCESS_AUDIENCE ?? '', BRIDGE_REGISTRY: '', + }; + 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'); + } + 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 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 || 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, expectedWorkerId) { + 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 reverse references or telemetry state are missing or 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??'')||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'); + } + } + 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); + 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, 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}); + verifyNoGatewayAssociation(gatewayRules); + 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 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'); + 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 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'); + 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 ?? '') || + 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: allDomains, gatewayRules, version: exactVersion.result, versions, deployments, + zoneIds: zones.map(zone => zone.id.toLowerCase()).sort()}; +} + +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 || !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); + 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 || + !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 || + 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'; + } + if (snapshot.workerId !== id || snapshot.subdomain?.enabled !== false || snapshot.subdomain?.previews_enabled !== false || + !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'); + } + 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'); + 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'); + 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-initialized-no-ingress' : noIngress ? 'verified-no-ingress' : 'verified'; +} + +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, gatewayToken, expectedZoneIds: zones, expectedWorkerId:workerId, phase:'preflight', fetchImpl}); + return verifyProviderState(snapshot, {phase: 'preflight', expectedZoneIds: zones, sourceSha, expectedWorkerId: workerId}); +} + +export function verifyDistinctWriteCredential(readToken, gatewayToken, writeToken) { + if (typeof readToken !== 'string' || readToken.length < 20 || typeof writeToken !== 'string' || + 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, 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, expectedWorkerId:workerId, phase, fetchImpl}); + return verifyProviderState(snapshot, {phase, expectedZoneIds: zones, sourceSha, expectedWorkerId: workerId}); +} + +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(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/${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'); + 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[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}); + 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_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,phase}); + 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-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',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]) { + 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..dcfef43c60 --- /dev/null +++ b/pm-stack/private-laptop-bridge/staging-bootstrap.test.mjs @@ -0,0 +1,224 @@ +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 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:[],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'}, + {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:{...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()], +}); + +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_RELEASE_REVIEWER_IDS: \$\{\{ vars\.CF_BRIDGE_RELEASE_REVIEWER_IDS \}\}/); + assert.match(workflow,/CF_BRIDGE_WORKER_ID: \$\{\{ vars\.CF_BRIDGE_WORKER_ID \}\}/); + 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_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 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)); +}); + +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=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}); + 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+'/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`) 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(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:[]}); + if(parsed.pathname.endsWith(`/workers/scripts/${WORKER_NAME}/schedules`)) return response({schedules:[]}); + 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}`); + }; + return {fetchImpl,calls}; +} + +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-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,dispatcherId:99})); + assert.throws(()=>verifyEnvironmentProtection({environment,branchPolicies,expectedReviewerIds:'',dispatcherId:99})); +}); + +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 ${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}),/owner-created Worker is missing/); + 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}}), + 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}),/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}),/reverse domain references/); + assert.equal(verifyProviderState(good,{phase:'postflight',expectedZoneIds:[zoneId],sourceSha:sha,expectedWorkerId:workerId}),'verified'); + 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}),/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}]; + 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}),/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=[];}, + 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=[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.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()],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 new file mode 100644 index 0000000000..e4ffc8ef54 --- /dev/null +++ b/pm-stack/private-laptop-bridge/staging-preflight.json @@ -0,0 +1,110 @@ +{ + "schema": 1, + "verified": false, + "account_id": "", + "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": "", + "BRIDGE_HOST": "laptop-bridge-staging.security.cab", + "ACCESS_ISSUER": "", + "ACCESS_AUDIENCE": "" + }, + "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/worker.mjs b/pm-stack/private-laptop-bridge/worker.mjs new file mode 100644 index 0000000000..ccd42fa7ef --- /dev/null +++ b/pm-stack/private-laptop-bridge/worker.mjs @@ -0,0 +1,172 @@ +import {operations, exact, identifier, unbase64, signingBytes, boundedText, validateOperation, validateResult} from './protocol.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']; +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(), accessIds = new Set(), principals = {}; + for (const p of r.principals) { + 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}; +} + +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, serverNow: now}}; + } + 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, serverNow: now}}}; + } + 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'}}; + } +} + +// 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, 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, 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()]) { + 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); + }, +};