// thesalarybox.com: static pages from ./public, plus two operations and two public read-outs. The protocol is stateless; its only // configuration is GATE_SECRET (32 bytes, base64url), set with `wrangler secret put GATE_SECRET`. // // Requests are form-encoded; responses are JSON. Every failure gets the same 400, so errors teach nothing. // POST /api/listing listingId, ceiling, basis -> { locator, verifyKey } (employers; CORS open) // POST /api/bid locator, minimum -> { ticket } (our frame only; no CORS) // Checking a ticket is not a call to this service. The employer does it with its verifyKey, on its own machine. // GET /api/key -> { keyId } (anyone; the public fingerprint of the secret) // GET /api/stats -> { listings, bids }, or 404 unless STATS is "public" // // Stats are a running tally of demand. They are optional and are set with STATS in wrangler.jsonc. "off" keeps // no tally. "on" keeps the tally for the operator. "public" keeps the tally and publishes it at /api/stats. // The tally is two totals, one for listings created and one for numbers compared, and it counts only requests that // succeeded. That lets us tell real use apart from abuse and noise in the host's request analytics, and plan for // load. It records nothing about any individual request. Each instance counts in memory and writes to one Durable // Object a few seconds later. A count is occasionally lost when a write fails or an instance is cut off first, // so the totals are approximate. The Durable Object's storage survives deploys. STATS_BASE ("l,b") is added to // the totals, so that they can be carried over from another host. import { DurableObject } from "cloudflare:workers"; import { Gate, unb64 } from "./gate"; type Counts = { listings: number; bids: number }; const zero = (): Counts => ({ listings: 0, bids: 0 }); const sum = (c: Counts) => c.listings + c.bids; export class Stats extends DurableObject { async add(d: Counts): Promise { const t = (await this.ctx.storage.get("totals")) ?? zero(); await this.ctx.storage.put("totals", { listings: t.listings + d.listings, bids: t.bids + d.bids }); } async totals(): Promise { return (await this.ctx.storage.get("totals")) ?? zero(); } } interface Env { GATE_SECRET: string; ASSETS: { fetch(req: Request): Promise }; STATS?: string; STATS_BASE?: string; COUNTER?: DurableObjectNamespace; } const json = (body: unknown, status = 200, cors = false, cache = "no-store") => new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json", "Cache-Control": cache, ...(cors ? { "Access-Control-Allow-Origin": "*" } : {}) }, }); // Per-instance batch of counts not yet written back. const pending = zero(); let flushing = false; // a write is already scheduled for this batch const statsOn = (env: Env) => (env.STATS === "on" || env.STATS === "public") && !!env.COUNTER; const statsPublic = (env: Env) => env.STATS === "public" && !!env.COUNTER; const counter = (env: Env) => env.COUNTER!.get(env.COUNTER!.idFromName("global")); async function flush(env: Env) { const d = { ...pending }; pending.listings = pending.bids = 0; flushing = false; if (!sum(d)) return; try { await counter(env).add(d); } catch { pending.listings += d.listings; pending.bids += d.bids; } // try again next time } // Counts are batched in memory and written to the one Durable Object 5 s after the first event of a batch (or at // once at 50), inside waitUntil, so a quiet site doesn't leave counts waiting for a next request that may not come. function count(env: Env, ctx: ExecutionContext, k: keyof Counts) { if (!statsOn(env)) return; pending[k]++; if (sum(pending) >= 50) ctx.waitUntil(flush(env)); else if (!flushing) { flushing = true; ctx.waitUntil(new Promise((r) => setTimeout(r, 5_000)).then(() => flush(env))); } } export default { async fetch(req: Request, env: Env, ctx: ExecutionContext): Promise { const { pathname } = new URL(req.url); if (!pathname.startsWith("/api/")) return env.ASSETS.fetch(req); const cors = pathname !== "/api/bid"; // a bid must come from the frame on this origin, never from an employer's page if (req.method === "OPTIONS" && cors) return new Response(null, { status: 204, headers: { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST", "Access-Control-Allow-Headers": "Content-Type", "Access-Control-Max-Age": "86400", } }); try { if (req.method === "GET") { if (pathname === "/api/key") return json({ keyId: await new Gate(unb64(env.GATE_SECRET)).keyId() }, 200, true, "public, max-age=300"); if (pathname === "/api/stats") { if (!statsPublic(env)) return json({ error: "stats are not published" }, 404, true); const t = await counter(env).totals(); const [bl = 0, bb = 0] = (env.STATS_BASE ?? "").split(",").map((n) => Number(n) || 0); return json({ listings: t.listings + bl, bids: t.bids + bb }, 200, true, "public, max-age=60"); } throw new Error(); } if (req.method !== "POST") throw new Error(); const f = new URLSearchParams(await req.text()); const need = (k: string) => { const v = f.get(k); if (!v) throw new Error(); return v; }; const num = (k: string) => { const s = need(k); if (!/^\d{1,15}$/.test(s)) throw new Error(); return Number(s); }; const gate = new Gate(unb64(env.GATE_SECRET)); switch (pathname) { case "/api/listing": { const r = await gate.listing(need("listingId"), num("ceiling"), need("basis")); count(env, ctx, "listings"); return json(r, 200, true); } case "/api/bid": { const ticket = await gate.bid(need("locator"), num("minimum")); count(env, ctx, "bids"); return json({ ticket }); } } } catch { /* fall through */ } return json({ error: "bad request" }, 400, cors); }, };