import { parseDidKey, verifySignature } from "@atproto/crypto"; export type HostResolver = (host: string) => Promise; export interface IdentityOptions { plcUrl: string; networkOrigins?: string[]; insecureLoopback: boolean; fetchTimeoutMs?: number; resolveHost?: HostResolver; } interface DidDoc { id?: string; service?: { id?: string; type?: string; serviceEndpoint?: unknown }[]; } export interface ServiceAuthCheck { aud: string; lxm: string; maxLifetimeS: number; skewS: number; } export interface ServiceAuthClaims { iss: string; jti: string; exp: number; } export interface PostedSession { userDid: string; pds: string; accessJwt: string; dpopPublicJwk: Record; dpopPrivateJwk: Record; } export interface VerifiedSession { did: string; handle: string; } const MAX_BODY_BYTES = 64 * 1024; const CACHE_TTL_MS = 5 * 60 * 1000; const NEGATIVE_TTL_MS = 60 * 1000; const CACHE_MAX = 2000; const MAX_INFLIGHT = 32; const PLC_DID = /^did:plc:[a-z2-7]{24}$/; const WEB_DID = /^did:web:([A-Za-z0-9.-]+)$/; const DNS_NAME = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z0-9-]{0,61}[a-z0-9]$/; const JTI = /^[\x21-\x7e]{8,256}$/; export class IdentityError extends Error {} function decodeB64url(b64: string): Uint8Array { const padded = b64.replace(/-/g, "+").replace(/_/g, "/"); const pad = (4 - (padded.length % 4)) % 4; return Uint8Array.from(atob(padded + "=".repeat(pad)), (c) => c.charCodeAt(0)); } function encodeB64url(bytes: Uint8Array): string { let s = ""; for (const b of bytes) s += String.fromCharCode(b); return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); } function decodeJson(part: string): Record { let value: unknown; try { value = JSON.parse(new TextDecoder().decode(decodeB64url(part))); } catch { throw new IdentityError("malformed JWT"); } if (!value || typeof value !== "object" || Array.isArray(value)) throw new IdentityError("malformed JWT"); return value as Record; } function trimSlash(s: string): string { return s.replace(/\/+$/, ""); } export function normalizeHost(raw: string): string | null { const host = raw.toLowerCase().replace(/\.$/, ""); if (!DNS_NAME.test(host)) return null; if (host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal")) return null; return host; } function v4Private(ip: string): boolean { const o = ip.split(".").map(Number); if (o.length !== 4 || o.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return true; const [a, b] = o; return a === 0 || a === 10 || a === 127 || a >= 224 || (a === 100 && b >= 64 && b < 128) || (a === 169 && b === 254) || (a === 172 && b >= 16 && b < 32) || (a === 192 && b === 168) || (a === 192 && b === 0 && o[2] === 0) || (a === 198 && (b === 18 || b === 19)); } function expandV6(ip: string): number[] | null { const [head, tail, extra] = ip.toLowerCase().split("::"); if (extra !== undefined) return null; const parse = (s: string) => (s ? s.split(":") : []); let h = parse(head); let t = tail === undefined ? [] : parse(tail); const last = (tail === undefined ? h : t).at(-1) ?? ""; if (last.includes(".")) { const o = last.split(".").map(Number); if (o.length !== 4) return null; const words = [((o[0] << 8) | o[1]).toString(16), ((o[2] << 8) | o[3]).toString(16)]; if (tail === undefined) h = [...h.slice(0, -1), ...words]; else t = [...t.slice(0, -1), ...words]; } const fill = tail === undefined ? 0 : 8 - h.length - t.length; if (fill < 0) return null; const all = [...h, ...Array(fill).fill("0"), ...t].map((x) => parseInt(x, 16)); return all.length === 8 && all.every((n) => Number.isInteger(n) && n >= 0 && n <= 0xffff) ? all : null; } export function addressPrivate(ip: string): boolean { if (!ip.includes(":")) return v4Private(ip); const w = expandV6(ip); if (!w) return true; if (w.every((n, i) => n === 0 || (i === 7 && n === 1))) return true; if (w.slice(0, 5).every((n) => n === 0) && (w[5] === 0xffff || w[5] === 0)) { return v4Private(`${w[6] >> 8}.${w[6] & 255}.${w[7] >> 8}.${w[7] & 255}`); } if (w[0] === 0x64 && w[1] === 0xff9b) return true; if ((w[0] & 0xfe00) === 0xfc00 || (w[0] & 0xffc0) === 0xfe80 || (w[0] & 0xff00) === 0xff00) return true; if (w[0] === 0x2001 && w[1] === 0x0db8) return true; return false; } async function systemResolve(host: string): Promise { const out: string[] = []; for (const type of ["A", "AAAA"] as const) { try { out.push(...await Deno.resolveDns(host, type)); } catch { continue; } } return out; } export class Identity { #opts: IdentityOptions; #plcOrigin: string; #networkOrigins: Set; #cache = new Map(); #inflight = new Map>(); constructor(opts: IdentityOptions) { this.#opts = opts; this.#plcOrigin = new URL(opts.plcUrl).origin; this.#networkOrigins = new Set((opts.networkOrigins ?? []).map((o) => new URL(o).origin)); } async checkUrl(raw: string): Promise { let url: URL; try { url = new URL(raw); } catch { throw new IdentityError("not a URL"); } if (url.username || url.password) throw new IdentityError("URL carries credentials"); if (this.#opts.insecureLoopback) { if (url.protocol !== "https:" && url.protocol !== "http:") throw new IdentityError("not an http URL"); return url; } if (url.protocol !== "https:" || (url.port && url.port !== "443")) throw new IdentityError("not an https URL on 443"); if (url.origin === this.#plcOrigin || this.#networkOrigins.has(url.origin)) return url; const host = normalizeHost(url.hostname); if (!host) throw new IdentityError("refused host"); const addrs = await this.#cached(`dns:${host}`, async () => { const found = await (this.#opts.resolveHost ?? systemResolve)(host); if (found.length === 0) throw new IdentityError("host does not resolve"); if (found.some(addressPrivate)) throw new IdentityError("host resolves to a private address"); return found; }); if (addrs.length === 0) throw new IdentityError("host does not resolve"); url.hostname = host; return url; } async #fetchJson(raw: string, init?: RequestInit): Promise<{ status: number; headers: Headers; body: unknown }> { const url = await this.checkUrl(raw); const res = await fetch(url, { ...init, redirect: "error", signal: AbortSignal.timeout(this.#opts.fetchTimeoutMs ?? 5000), }); const reader = res.body?.getReader(); const chunks: Uint8Array[] = []; let size = 0; while (reader) { const { done, value } = await reader.read(); if (done) break; size += value.length; if (size > MAX_BODY_BYTES) { await reader.cancel(); throw new IdentityError("response too large"); } chunks.push(value); } const bytes = new Uint8Array(size); let off = 0; for (const c of chunks) { bytes.set(c, off); off += c.length; } let body: unknown = null; try { body = JSON.parse(new TextDecoder().decode(bytes)); } catch { body = null; } return { status: res.status, headers: res.headers, body }; } async #cached(key: string, load: () => Promise): Promise { const hit = this.#cache.get(key); if (hit && Date.now() - hit.at < (hit.ok ? CACHE_TTL_MS : NEGATIVE_TTL_MS)) { this.#cache.delete(key); this.#cache.set(key, hit); if (!hit.ok) throw hit.value; return hit.value as T; } const pending = this.#inflight.get(key); if (pending) return await (pending as Promise); if (this.#inflight.size >= MAX_INFLIGHT) throw new IdentityError("identity resolution is busy"); const remember = (ok: boolean, value: unknown) => { this.#cache.delete(key); while (this.#cache.size >= CACHE_MAX) this.#cache.delete(this.#cache.keys().next().value as string); this.#cache.set(key, { at: Date.now(), ok, value }); }; const p = load().then((value) => { remember(true, value); return value; }, (err) => { const e = err instanceof IdentityError ? err : new IdentityError("lookup failed"); remember(false, e); throw e; }).finally(() => this.#inflight.delete(key)); this.#inflight.set(key, p); return await p; } resolveDid(did: string): Promise { let url: string; if (PLC_DID.test(did)) { url = `${trimSlash(this.#opts.plcUrl)}/${did}`; } else { const web = WEB_DID.exec(did); const host = web ? (this.#opts.insecureLoopback ? web[1].toLowerCase() : normalizeHost(web[1])) : null; if (!host) return Promise.reject(new IdentityError("unsupported DID")); url = `https://${host}/.well-known/did.json`; } return this.#cached(`doc:${did}`, async () => { const res = await this.#fetchJson(url); if (res.status !== 200 || !res.body || typeof res.body !== "object") throw new IdentityError("DID resolution failed"); const doc = res.body as DidDoc; if (doc.id !== did) throw new IdentityError("DID document id mismatch"); return doc; }); } async pdsOf(did: string): Promise { const doc = await this.resolveDid(did); const svc = (doc.service || []).find((s) => (s.id === "#atproto_pds" || s.id === `${did}#atproto_pds`) && s.type === "AtprotoPersonalDataServer" ); if (typeof svc?.serviceEndpoint !== "string") throw new IdentityError("no #atproto_pds service"); const url = await this.checkUrl(svc.serviceEndpoint); return trimSlash(url.origin + url.pathname); } authServersOf(pds: string): Promise { return this.#cached(`as:${pds}`, async () => { const res = await this.#fetchJson(`${pds}/.well-known/oauth-protected-resource`); const servers = (res.body as { authorization_servers?: unknown })?.authorization_servers; if (res.status !== 200 || !Array.isArray(servers)) throw new IdentityError("no protected resource metadata"); return servers.filter((s): s is string => typeof s === "string").map(trimSlash); }); } async verifyServiceAuth(token: string, check: ServiceAuthCheck, nowS: number): Promise { const parts = token.split("."); if (parts.length !== 3 || parts.some((p) => !/^[A-Za-z0-9_-]+$/.test(p))) throw new IdentityError("malformed JWT"); const header = decodeJson(parts[0]); const payload = decodeJson(parts[1]); const alg = header.alg; if (alg !== "ES256K" && alg !== "ES256") throw new IdentityError("unsupported JWT alg"); const { iss, aud, lxm, exp, iat, jti } = payload; if (typeof iss !== "string" || !iss.startsWith("did:key:") || iss.length > 256) throw new IdentityError("issuer is not a did:key"); if (aud !== check.aud) throw new IdentityError("aud mismatch"); if (lxm !== check.lxm) throw new IdentityError("lxm mismatch"); if (typeof exp !== "number" || typeof iat !== "number") throw new IdentityError("missing exp or iat"); if (nowS >= exp) throw new IdentityError("token expired"); if (iat > nowS + check.skewS) throw new IdentityError("token issued in the future"); if (exp - iat > check.maxLifetimeS) throw new IdentityError("token lifetime too long"); if (typeof jti !== "string" || !JTI.test(jti)) throw new IdentityError("missing or malformed jti"); let keyAlg: string; try { keyAlg = parseDidKey(iss).jwtAlg; } catch { throw new IdentityError("unparseable did:key"); } if (keyAlg !== alg) throw new IdentityError("JWT alg does not match the did:key"); let valid = false; try { valid = await verifySignature(iss, new TextEncoder().encode(`${parts[0]}.${parts[1]}`), decodeB64url(parts[2])); } catch { valid = false; } if (!valid) throw new IdentityError("invalid JWT signature"); return { iss, jti, exp }; } async verifySession(s: PostedSession): Promise { if (!PLC_DID.test(s.userDid) && !WEB_DID.test(s.userDid)) throw new IdentityError("unsupported account DID"); const pub = s.dpopPublicJwk; const priv = s.dpopPrivateJwk; if (pub?.kty !== "EC" || pub.crv !== "P-256" || priv?.x !== pub.x || priv?.y !== pub.y || typeof priv?.d !== "string") { throw new IdentityError("malformed DPoP key"); } let key: CryptoKey; try { key = await crypto.subtle.importKey( "jwk", { kty: "EC", crv: "P-256", x: priv.x, y: priv.y, d: priv.d }, { name: "ECDSA", namedCurve: "P-256" }, false, ["sign"], ); } catch { throw new IdentityError("malformed DPoP key"); } const pds = await this.pdsOf(s.userDid); const posted = trimSlash(s.pds); if (posted !== pds && !(await this.authServersOf(pds)).includes(posted)) throw new IdentityError("PDS mismatch"); const endpoint = `${pds}/xrpc/com.atproto.server.getSession`; const ath = encodeB64url(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(s.accessJwt)))); const proof = async (nonce: string | null) => { const enc = (v: unknown) => encodeB64url(new TextEncoder().encode(JSON.stringify(v))); const head = enc({ typ: "dpop+jwt", alg: "ES256", jwk: { kty: "EC", crv: "P-256", x: pub.x, y: pub.y } }); const body = enc({ jti: encodeB64url(crypto.getRandomValues(new Uint8Array(16))), htm: "GET", htu: endpoint, iat: Math.floor(Date.now() / 1000), ath, ...(nonce ? { nonce } : {}), }); const sig = await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, key, new TextEncoder().encode(`${head}.${body}`)); return `${head}.${body}.${encodeB64url(new Uint8Array(sig))}`; }; const call = async (nonce: string | null) => this.#fetchJson(endpoint, { headers: { authorization: `DPoP ${s.accessJwt}`, dpop: await proof(nonce) } }); let res = await call(null); const nonce = res.headers.get("dpop-nonce"); if ((res.status === 400 || res.status === 401) && nonce && nonce.length <= 512) res = await call(nonce); if (res.status !== 200) throw new IdentityError("PDS refused the session"); const info = res.body as { did?: unknown; handle?: unknown }; if (info?.did !== s.userDid) throw new IdentityError("session belongs to another account"); return { did: s.userDid, handle: typeof info.handle === "string" && info.handle.length <= 253 ? info.handle : "" }; } }