Edge Capability Architecture · WebCrypto + SQLite Durable Objects

Keyless Browser Proxy

Browser applications cannot hold static upstream API credentials without exposing them in client bundles and network logs. This prototype keeps zero static keys in browser code or Web Storage, issuing short-TTL, origin-bound HMAC-SHA256 session tokens enforced by an atomic per-session SQLite QuotaLedger Durable Object.

Hypothesis

Origin-verified short-TTL HMAC-SHA256 tokens tracked in an edge SQLite quota ledger allow public pure-frontend web apps to invoke metered capabilities without shipping static secrets in JS or requiring visitors to paste API keys.

Confirm vs. Falsify

Confirm: same-origin calls succeed within quota (200), while missing/mismatched origins (403), tampered tokens (401), or exhausted caps (429) fail closed in QuotaLedger. Falsify: non-browser scripts that forge Origin headers can exhaust anonymous quotas without Turnstile, proof-of-work, or passkey identity binding.

What to try first

Run Try 1 to mint a 3-call token and invoke /api/proxy/infer (200), Try 2 to exhaust the SQLite quota (429), and Try 3 to trigger origin-mismatch (403) and 1-byte signature tamper (401).

3 Things To Try

Ready — click an interactive scenario or configure a custom session below.

1. Mint 3-Call Session & Run Proxy

Mints a 3-call, 120s TTL token bound to this page's Origin, executes an authorized /api/proxy/infer call, and inspects the incremented DO ledger.

2. Exhaust Quota to Trigger HTTP 429

Consumes all remaining calls in the active session (or starts a fresh 3-call session) and fires one extra request to trigger atomic 429 quota_exceeded.

3. Origin Mismatch (403) & Tamper (401)

Mints a token bound to https://evil.example and submits it from here (403 origin_denied), then flips 1 signature byte on a valid token (401 invalid_signature).

Interactive Proxy Workbench

Session Mint & Proxy Controls

Fetch Standard Forbidden Header: Compliant browsers forbid client JavaScript from setting or overriding the HTTP Origin request header inside fetch(). Requests missing both Origin and Referer fail closed with 403 origin_denied.

To inspect origin rejection inside a live browser tab, this workbench mints a token whose signed org claim is bound to https://evil.example (or attaches X-Claimed-Origin), causing /api/proxy/infer to reject with 403 origin_denied. Note the falsify boundary: a non-browser script can still send a forged Origin header over CLI HTTP, so production anonymous quotas require Turnstile, proof-of-work, or passkey identity binding.

Session ID (DO key) —
Bound Origin (org) —
Token ID (jti) —
TTL Remaining —
Quota Consumption 0 / 0 calls

Live QuotaLedger State & Output

No calls yet

Mint a session token or click one of the 3 quick actions above to observe authenticated responses, origin denials, and SQLite quota tracking.

Durable Object SQLite audit_log

0 events
# Status Code Detail
No Durable Object ledger events recorded yet.

Wire & Token Inspector

Live HTTP Request & Response Wire Log
// Waiting for first HTTP request to /api/session/mint or /api/proxy/infer...
Decoded Ephemeral Token (Header · Claims · HMAC-SHA256 Signature)
// No active session token minted yet.
Edge Enforcement Contract (SQLite QuotaLedger Schema & Atomic Debit)
/* Per-session SQLite schema inside QuotaLedger Durable Object */
CREATE TABLE IF NOT EXISTS session_state (
  id INTEGER PRIMARY KEY CHECK (id = 1),
  session_id TEXT NOT NULL,
  hmac_secret TEXT NOT NULL,   -- 256-bit random secret, never returned over HTTP
  allowed_origin TEXT NOT NULL,
  max_calls INTEGER NOT NULL,
  used_calls INTEGER NOT NULL DEFAULT 0,
  ttl_sec INTEGER NOT NULL,
  created_at INTEGER NOT NULL,
  expires_at INTEGER NOT NULL
);

/* Single-statement atomic quota consumption */
UPDATE session_state
SET used_calls = used_calls + 1
WHERE id = 1 AND used_calls < max_calls
RETURNING used_calls, max_calls;

Architecture & Runtime Boundary

Origin verified at edge · HMAC secret locked inside DO SQLite

1. The Problem

Any static API key embedded in browser JavaScript or localStorage is readable via DevTools and replayable from arbitrary scripts via curl, exposing upstream quotas and billing limits outside the application origin.

2. The Goal

Keep the client bundle keyless while restricting every inference request to a verified web Origin, a short-lived signed capability token, and a per-session call ceiling that fails closed on abuse.

3. How It Works

POST /api/session/mint validates the caller Origin against an allowlist and stores a fresh 256-bit HMAC secret in a per-session QuotaLedger Durable Object. POST /api/proxy/infer verifies signature, exp TTL, origin claim, and atomic SQLite quota before running downstream analysis.

Keyless Browser Proxy Architecture Diagram Four-stage request pipeline: Browser Client holds zero static secrets and requests a short-TTL origin-bound token from the Edge Worker, which routes to a per-session QuotaLedger SQLite Durable Object that verifies HMAC-SHA256 signature, expiration, origin match, and remaining quota before invoking the downstream synthetic backend. 1. Browser Client static_api_keys = 0 Sends Origin header Holds ephemeral Bearer token in memory only mint HS256 2. Edge Worker /api/session/mint /api/proxy/infer Validates Origin allowlist Routes sid to DO instance RPC 3. QuotaLedger DO SQLite: session_state hmac_secret (DO-only) Verify sig + exp + org used_calls < max_calls 200 4. Downstream Synthetic Engine Runs only after DO quota commit. 0 LLM keys stored. FAIL-CLOSED REJECTION GATES: 401 missing_token / invalid_signature / token_expired 403 origin_denied (missing/disallowed Origin or org mismatch) 429 quota_exceeded (SQLite atomic cap reached)
Figure 1: Each browser session initializes a dedicated QuotaLedger Durable Object holding an isolated HMAC-SHA256 secret. No long-lived upstream credential reaches browser code or cross-origin callers.
How This Is Set Up · Origin & Quota Contract

Code Matching the Live App

Keep static provider secrets out of browser bundles by minting short-lived HMAC-SHA256 session tokens at POST /api/session/mint and enforcing origin allowlists plus atomic SQLite call quotas inside the QuotaLedger Durable Object on every POST /api/proxy/infer call.

Static client key (exposed credential)
// Anti-pattern: embedding static API keys in client JS or requiring pasted secrets
const UPSTREAM_KEY = "sk-live-exposed-in-public-bundle";

export async function runPrompt(prompt) {
  const res = await fetch("https://api.provider.example/v1/infer", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${UPSTREAM_KEY}`, // Extractable from DevTools or JS bundle
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ prompt }),
  });
  return res.json();
}
Origin-bound ephemeral token proxy
// public/app.js — mint origin-bound ephemeral token in memory; zero Web Storage secrets
const minted = await fetch("/api/session/mint", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ maxCalls: 3, ttlSec: 120 }),
}).then((r) => r.json());

// Held only in JS heap state (`state.token`), never written to localStorage
const inferRes = await fetch("/api/proxy/infer", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    Authorization: `Bearer ${minted.token}`,
  },
  body: JSON.stringify({ prompt, mode: "risk-audit" }),
});
Complete Page Setup: HTML Markup, Token Schema & Durable Object Wiring

End-to-end setup linking the mint and inference forms in public/index.html, the KBP+JWT token schema and DEFAULT_ALLOWED_ORIGINS list in src/token-policy.ts, memory-only client fetches in public/app.js, and atomic SQLite QuotaLedger quota decrements in src/worker.ts.

<!-- 1. Page HTML Setup (public/index.html) -->
<form id="mint-form">
  <input id="input-max-calls" name="maxCalls" type="number" min="1" max="25" value="3" required>
  <input id="input-ttl-sec" name="ttlSec" type="number" min="5" max="600" value="120" required>
  <button type="submit" id="btn-mint-custom">Mint Session Token</button>
</form>
<form id="infer-form">
  <select id="select-mode" name="mode"><option value="risk-audit">risk-audit</option></select>
  <textarea id="input-prompt" name="prompt" rows="3" required>Evaluate shipping an API key...</textarea>
  <button type="submit" id="btn-run-infer">Send Proxy Infer (200)</button>
</form>
<script type="module" src="/app.js"></script>

// 2. Ephemeral Token Payload Schema & Origin Policy (src/token-policy.ts)
export const DEFAULT_ALLOWED_ORIGINS = [
  "https://keyless-browser-proxy.kinlan-test.workers.dev",
  "https://aifoc.us", /^https:\/\/[a-z0-9-]+\.aifoc\.us$/,
  /^http:\/\/localhost(?::\d{1,5})?$/, /^http:\/\/127\.0\.0\.1(?::\d{1,5})?$/,
];
const header = { alg: "HS256", typ: "KBP+JWT" };
const payload = {
  jti: crypto.randomUUID(),
  sid: sessionId,
  org: origin,
  max: maxCalls,
  iat: nowSec,
  exp: nowSec + ttlSec,
};

// 3. Page Bootstrap & QuotaLedger Durable Object Wiring (public/app.js + src/worker.ts)
const minted = await fetch("/api/session/mint", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ maxCalls: 3, ttlSec: 120 }),
}).then((r) => r.json());
state.token = minted.token; // Held in JS memory only; zero Web Storage secrets

await fetch("/api/proxy/infer", {
  method: "POST",
  headers: { "Content-Type": "application/json", Authorization: `Bearer ${state.token}` },
  body: JSON.stringify({ prompt, mode: "risk-audit" }),
});
Edge Verification & Atomic SQLite Quota Guard
// src/token-policy.ts + src/worker.ts — verify HMAC-SHA256 & origin, then consume 1 call atomically in QuotaLedger
const requestOrigin = resolveRequestOrigin(request); // null if Origin and Referer are both absent -> 403
const verification = await verifySessionToken({
  token: input.token,
  expectedOrigin: input.requestOrigin, // Returns 403 origin_denied on allowlist or claim mismatch
  hmacSecret: session.hmac_secret,     // 256-bit secret held inside DO SQLite, never sent to client
});
if (!verification.ok) return { ok: false, status: verification.code === "origin_denied" ? 403 : 401 };

const updated = this.ctx.storage.sql
  .exec("UPDATE session_state SET used_calls = used_calls + 1 WHERE id = 1 AND used_calls < max_calls RETURNING used_calls, max_calls")
  .toArray();
if (updated.length === 0) return { ok: false, status: 429, error: "quota_exceeded" };
What disappears

Shipping static upstream API credentials inside frontend JavaScript bundles or forcing visitors to paste personal secrets before running a web app.

What becomes explicit

Server-side DEFAULT_ALLOWED_ORIGINS validation (fail-closed on missing Origin, Vary: Origin), short-TTL KBP+JWT HMAC-SHA256 tokens, and deterministic 401/403/429 rejections in audit_log.

Platform gaps remaining

HTTP Origin headers isolate web origins in compliant browsers but do not authenticate non-browser CLI callers; public keyless endpoints still require Turnstile, proof-of-work, or passkey attestation to bound anonymous minting.