import { WorkerEntrypoint } from "cloudflare:workers"; import { p256 } from "@noble/curves/nist.js"; import { secp256k1 } from "@noble/curves/secp256k1.js"; import { atprotoKey, resolveDid } from "./identity"; import { isDid, isObject, rateLimit, XrpcError } from "./xrpc"; export interface Claims { iss: string; aud: string; exp: number; lxm: string | undefined; jti: string | undefined; act: string | undefined; } interface Jwt { alg: string; claims: Claims; signingInput: Uint8Array; signature: Uint8Array; } export interface PublicKey { curve: "secp256k1" | "p256"; bytes: Uint8Array; } const leewaySeconds = 5; function invalid(message: string): XrpcError { return new XrpcError(401, "InvalidToken", message); } function decodeJson(text: string): unknown { return JSON.parse( new TextDecoder().decode(Uint8Array.fromBase64(text, { alphabet: "base64url" })), ); } export function parseJwt(token: string): Jwt { const parts = token.split("."); const [header = "", payload = "", signature = ""] = parts; let head: unknown; let body: unknown; let sig: Uint8Array; try { head = decodeJson(header); body = decodeJson(payload); sig = Uint8Array.fromBase64(signature, { alphabet: "base64url" }); } catch { throw invalid("token is not a JWT"); } if (parts.length !== 3 || !isObject(head) || !isObject(body)) { throw invalid("token is not a JWT"); } const { alg } = head; const { iss, aud, exp, lxm, jti, act } = body; if (typeof alg !== "string" || typeof iss !== "string" || typeof aud !== "string") { throw invalid("token has no alg, iss, or aud"); } if (typeof exp !== "number") { throw invalid("token has no expiry"); } return { alg, claims: { iss, aud, exp, lxm: typeof lxm === "string" ? lxm : undefined, jti: typeof jti === "string" ? jti : undefined, act: isObject(act) && isDid(act["sub"]) ? act["sub"] : undefined, }, signingInput: new TextEncoder().encode(`${header}.${payload}`), signature: sig, }; } export function checkClaims( claims: Claims, expected: { audience: string; method: string; now: number }, ): void { if (claims.exp + leewaySeconds < expected.now) { throw invalid("token is expired"); } if (claims.aud !== expected.audience) { throw invalid("token is meant for another audience"); } if (claims.lxm !== expected.method) { throw invalid(`token is not bound to ${expected.method}`); } } const base58Alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; function base58(text: string): Uint8Array { let n = 0n; for (const c of text) { const digit = base58Alphabet.indexOf(c); if (digit < 0) { throw invalid("issuer key is not base58"); } n = n * 58n + BigInt(digit); } const bytes: number[] = []; for (; n > 0n; n /= 256n) { bytes.unshift(Number(n % 256n)); } for (const c of text) { if (c !== "1") { break; } bytes.unshift(0); } return Uint8Array.from(bytes); } export function decodeMultikey(multibase: string): PublicKey { if (!multibase.startsWith("z")) { throw invalid("issuer key is not base58btc multibase"); } const bytes = base58(multibase.slice(1)); const bytesAfter = bytes.subarray(2); if (bytes[0] === 0xe7 && bytes[1] === 0x01) { return { curve: "secp256k1", bytes: bytesAfter }; } if (bytes[0] === 0x80 && bytes[1] === 0x24) { return { curve: "p256", bytes: bytesAfter }; } throw invalid("issuer key is neither secp256k1 nor P-256"); } export function verifySignature( key: PublicKey, jwt: Pick, ): boolean { const curve = { secp256k1: { alg: "ES256K", impl: secp256k1 }, p256: { alg: "ES256", impl: p256 }, }[key.curve]; if (jwt.alg !== curve.alg) { return false; } try { return curve.impl.verify(jwt.signature, jwt.signingInput, key.bytes, { lowS: false }); } catch { return false; } } // Only cache misses count against the client IP. export class Did extends WorkerEntrypoint { override async fetch(request: Request): Promise { try { await rateLimit(request, this.env.XRPC_LIMIT, "auth:"); const doc = await resolveDid(this.ctx.props.did); // A failed refresh must not keep serving a key that may be revoked. return Response.json(doc, { headers: { "Cache-Control": "max-age=300, must-revalidate" }, }); } catch (error) { if (!(error instanceof XrpcError)) { throw error; } return Response.json( { error: error.error, message: error.message }, { status: error.status, headers: { "Cache-Control": "no-store" } }, ); } } } async function issuerDocument( request: Request, exports: Cloudflare.Exports, did: string, ): Promise> { const ip = request.headers.get("CF-Connecting-IP"); const response = await exports.Did({ props: { did } }).fetch("https://did/", { headers: ip === null ? {} : { "CF-Connecting-IP": ip }, }); const body = await response.json>(); if (!response.ok) { throw new XrpcError(response.status, String(body["error"]), String(body["message"])); } return body; } export async function authenticate( request: Request, env: Env, exports: Cloudflare.Exports, method: string, ): Promise { const header = request.headers.get("Authorization"); if (header?.startsWith("Bearer ") !== true) { throw new XrpcError(401, "AuthRequired", "service auth token is required"); } const jwt = parseJwt(header.slice("Bearer ".length)); checkClaims(jwt.claims, { audience: `did:web:${env.HOSTNAME}`, method, now: Date.now() / 1000, }); if (!/^did:(?:plc:|web:[a-zA-Z0-9.-]+$)/.test(jwt.claims.iss)) { throw invalid("token issuer is not a did:plc or a did:web without a port"); } const multikey = atprotoKey(await issuerDocument(request, exports, jwt.claims.iss)); if (multikey === undefined || !verifySignature(decodeMultikey(multikey), jwt)) { throw invalid("signature verification failed"); } return jwt.claims; }