encodeCursor/decodeCursor/firstSnippet (opensearch) and decodeJwtPayload (verify) become public exports so tests can hit them without round-tripping through fetch.
50 lines
1.5 KiB
TypeScript
50 lines
1.5 KiB
TypeScript
interface JwtPayload {
|
|
sub: string;
|
|
[key: string]: unknown;
|
|
}
|
|
|
|
interface DidDocument {
|
|
service?: { id: string; serviceEndpoint: string }[];
|
|
}
|
|
|
|
export function decodeJwtPayload(token: string): JwtPayload {
|
|
const parts = token.split(".");
|
|
if (parts.length !== 3) throw new Error("Invalid JWT format");
|
|
const payload = parts[1].replace(/-/g, "+").replace(/_/g, "/");
|
|
return JSON.parse(atob(payload));
|
|
}
|
|
|
|
export async function resolvePds(did: string): Promise<string> {
|
|
const res = await fetch(`https://plc.directory/${did}`);
|
|
if (!res.ok) throw new Error(`Failed to resolve DID: ${res.status}`);
|
|
const doc: DidDocument = await res.json();
|
|
const pds = doc.service?.find((s) => s.id === "#atproto_pds");
|
|
if (!pds) throw new Error("No PDS service found in DID document");
|
|
return pds.serviceEndpoint;
|
|
}
|
|
|
|
async function verifySession(
|
|
pdsUrl: string,
|
|
token: string,
|
|
): Promise<string> {
|
|
const res = await fetch(
|
|
`${pdsUrl}/xrpc/com.atproto.server.getSession`,
|
|
{ headers: { Authorization: `Bearer ${token}` } },
|
|
);
|
|
if (!res.ok) throw new Error(`Session verification failed: ${res.status}`);
|
|
const session: { did: string } = await res.json();
|
|
return session.did;
|
|
}
|
|
|
|
export async function authenticateRequest(
|
|
authHeader: string | null,
|
|
): Promise<string> {
|
|
if (!authHeader?.startsWith("Bearer ")) {
|
|
throw new Error("Missing or invalid Authorization header");
|
|
}
|
|
const token = authHeader.slice(7);
|
|
const { sub } = decodeJwtPayload(token);
|
|
const pdsUrl = await resolvePds(sub);
|
|
return await verifySession(pdsUrl, token);
|
|
}
|