// Per-user progress sync. Cloudflare Access signs the user in and sends a signed // JWT (Cf-Access-Jwt-Assertion). We verify its signature against the team's keys // and use the verified email as the only key, so one user cannot read another's data. // Storage: KV namespace bound as PROGRESS (set in the Pages project settings). const TEAM = "https://YOUR-TEAM.cloudflareaccess.com"; const MAX_BYTES = 5 * 1024 * 1024; let keyCache = { at: 0, keys: null }; const json = (obj, status = 200) => new Response(JSON.stringify(obj), { status, headers: { "Content-Type": "application/json", "Cache-Control": "no-store" }, }); const bytes = s => Uint8Array.from(atob(s.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(s.length / 4) * 4, "=")), c => c.charCodeAt(0)); const text = b => new TextDecoder().decode(b); async function verifiedEmail(request) { const token = request.headers.get("Cf-Access-Jwt-Assertion"); if (!token) return null; const parts = token.split("."); if (parts.length !== 3) return null; const header = JSON.parse(text(bytes(parts[0]))); const payload = JSON.parse(text(bytes(parts[1]))); if (header.alg !== "RS256" || payload.iss !== TEAM) return null; if (!payload.exp || payload.exp * 1000 < Date.now() || !payload.email) return null; if (!keyCache.keys || Date.now() - keyCache.at > 3600e3) { const r = await fetch(TEAM + "/cdn-cgi/access/certs"); keyCache = { at: Date.now(), keys: (await r.json()).keys || [] }; } const jwk = keyCache.keys.find(k => k.kid === header.kid); if (!jwk) return null; const key = await crypto.subtle.importKey("jwk", jwk, { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["verify"]); const ok = await crypto.subtle.verify( "RSASSA-PKCS1-v1_5", key, bytes(parts[2]), new TextEncoder().encode(parts[0] + "." + parts[1]) ); return ok ? payload.email : null; } export async function onRequest({ request, env }) { let email; try { email = await verifiedEmail(request); } catch (e) { email = null; } if (!email) return json({ error: "Sign in required" }, 401); if (!env.PROGRESS) return json({ error: "Storage not configured" }, 500); const key = "progress:" + email.trim().toLowerCase(); if (request.method === "GET") { const raw = await env.PROGRESS.get(key); return raw ? json(JSON.parse(raw)) : json({ data: null, savedAt: 0 }); } if (request.method === "PUT") { const body_text = await request.text(); if (body_text.length > MAX_BYTES) return json({ error: "Too large" }, 413); let body; try { body = JSON.parse(body_text); } catch (e) { return json({ error: "Bad JSON" }, 400); } if (!body || typeof body !== "object" || typeof body.cards !== "object") { return json({ error: "Not a progress file" }, 400); } const savedAt = Number(body.savedAt) || Date.now(); await env.PROGRESS.put(key, JSON.stringify({ data: body, savedAt })); return json({ ok: true, savedAt }); } return json({ error: "Method not allowed" }, 405); }