/** ATProto session handling, cached in KV. */ import { xrpc, XrpcError } from './xrpc.js'; import { jwtExpiry } from './util.js'; const ENTRYWAY = 'https://bsky.social'; const SESSION_KEY = 'atproto:session'; /** Used only when the refresh token carries no readable expiry. */ const FALLBACK_TTL = 2592000; // 30 days /** Drop the entry an hour early; a session we would refuse to use is a liability. */ const TTL_MARGIN = 3600; const AUTH_ERRORS = new Set([ 'ExpiredToken', 'InvalidToken', 'AuthMissing', 'AuthenticationRequired', ]); /** The entryway issues the session; the DID document names the real PDS host. */ function pdsFromDidDoc(didDoc) { const service = didDoc?.service?.find((s) => s.id?.endsWith('#atproto_pds')); return service?.serviceEndpoint ?? ENTRYWAY; } function storeable(session) { return { did: session.did, accessJwt: session.accessJwt, refreshJwt: session.refreshJwt, pds: session.pds ?? pdsFromDidDoc(session.didDoc), }; } /** * How long the cached session may live, taken from the refresh token's own * `exp` claim. Deriving it rather than picking a constant is what makes the TTL * safe: the entry can never outlive the credential it holds, and it can never * discard one that is still usable. Every login and every refresh rewrites the * entry, so an active deployment never reaches the expiry at all. */ function sessionTtl(refreshJwt) { const exp = jwtExpiry(refreshJwt); if (!exp) return FALLBACK_TTL; return Math.max(60, Math.floor(exp - Date.now() / 1000) - TTL_MARGIN); } async function store(env, session) { const stored = storeable(session); await env.BRIDGE.put(SESSION_KEY, JSON.stringify(stored), { expirationTtl: sessionTtl(stored.refreshJwt), }); return stored; } function login(env) { return xrpc(ENTRYWAY, 'com.atproto.server.createSession', { method: 'POST', body: { identifier: env.BLUESKY_HANDLE, password: env.BLUESKY_APP_PASSWORD }, }).then((session) => store(env, session)); } function renew(env, session) { return xrpc(session.pds, 'com.atproto.server.refreshSession', { method: 'POST', token: session.refreshJwt, }).then((next) => store(env, { ...next, pds: session.pds })); } function isAuthError(err) { return err instanceof XrpcError && (err.status === 401 || AUTH_ERRORS.has(err.code)); } /** * Run an authenticated call. Reuses the cached session, refreshes it when the * access token expires, and does a full login only as a last resort, because * Bluesky rate-limits session creation. */ export async function withSession(env, run) { let session = (await env.BRIDGE.get(SESSION_KEY, 'json')) ?? (await login(env)); try { return await run(session); } catch (err) { if (!isAuthError(err)) throw err; } session = await renew(env, session).catch(() => login(env)); return run(session); }