// Shared auth helpers used by both the gate (gate.mjs) and the chat bridge // (server.mjs): chat-token validation and DID -> handle resolution. import { readFileSync } from "node:fs"; const HANDLE_TTL = 5 * 60 * 1000; // ms const handleCache = new Map(); // ---- chat tokens ------------------------------------------------------------ // The gate mints tokens into a JSON file; the bridge reads the same file to // accept a WebSocket join. Format: { token: { did, expires } }. export function loadChatTokens(file = "data/chat/tokens.json") { try { return JSON.parse(readFileSync(file, "utf8")); } catch { return {}; } } export function userForChatToken(token, tokens) { if (!token) return null; const entry = tokens[token]; if (!entry) return null; if (entry.expires < Date.now()) return null; return entry.did; } // ---- DID -> handle resolution (best-effort, cached) ------------------------- // The DID is the stable identifier; the handle is just display and may change, // so it is looked up fresh each time and cached briefly. async function lookupHandle(did) { try { const res = await fetch(`https://plc.directory/${did}`, { headers: { Accept: "application/json" }, signal: AbortSignal.timeout(10_000), }); if (!res.ok) return null; const doc = await res.json(); for (const uri of doc.alsoKnownAs ?? []) { if (uri.startsWith("at://")) return uri.slice(5).split("/")[0] || null; } } catch { /* best-effort */ } return null; } export async function resolveHandle(did) { if (!did) return ""; const hit = handleCache.get(did); if (hit && hit[1] > Date.now()) return hit[0]; const handle = (await lookupHandle(did)) || did; handleCache.set(did, [handle, Date.now() + HANDLE_TTL]); return handle; }