Something went wrong. Try again.
Monorepo for Tangled tangled.org
Something went wrong. Try again.
TypeScript
1234567891011121314151617181920212223242526272829303132333435363738394041424344// 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 tokenexport interface Env { EMAIL_DID: KVNamespace; EMAIL_DID_TOKEN?: string;}
export interface EmailDidStore { get(key: string): Promise<string | null>;}
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<Record<string, string | null>> => { // 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<Env>;