// the verified email → did mapping, loaded once at cutover by cmd/email-did-migrate. // plain git emails resolve to the signup did. only svfe calls this, with the shared token export interface Env { EMAIL_DID: KVNamespace; EMAIL_DID_TOKEN?: string; } export interface EmailDidStore { get(key: string): Promise; } const MAX_LOOKUPS = 250; const encoder = new TextEncoder(); const authorized = (request: Request, token: string | undefined): boolean => { if (!token) return false; const given = encoder.encode(request.headers.get("authorization") ?? ""); const want = encoder.encode(`Bearer ${token}`); return given.byteLength === want.byteLength && crypto.subtle.timingSafeEqual(given, want); }; export const lookup = async (url: URL, store: EmailDidStore): Promise> => { // repeated params rather than a csv: emails may legally contain commas const emails = url.searchParams.getAll("emails").filter(Boolean).slice(0, MAX_LOOKUPS); // keys are lowercased, so each address is read once however the caller cased it const byLower = new Map( await Promise.all( [...new Set(emails.map((email) => email.toLowerCase()))].map( async (key) => [key, await store.get(key).catch(() => null)] as const, ), ), ); return Object.fromEntries(emails.map((email) => [email, byLower.get(email.toLowerCase()) ?? null])); }; export default { fetch: async (request, env) => authorized(request, env.EMAIL_DID_TOKEN) ? Response.json(await lookup(new URL(request.url), env.EMAIL_DID)) : Response.json({ error: "unauthorized" }, { status: 401 }), } satisfies ExportedHandler;