import { AuthResult, MethodAuthVerifier, XRPCError, } from "npm:@atproto/xrpc-server"; import * as borrowed from "./auth.borrowed.ts"; export interface AuthConfig { serviceDid: string; } let serviceDid: string; let isInitialized = false; export function setupAuth(config: AuthConfig) { if (!config.serviceDid || !config.serviceDid.startsWith("did:")) { throw new Error("A valid serviceDid must be provided in the auth config."); } serviceDid = config.serviceDid; isInitialized = true; console.log("Authentication module initialized."); } export async function getAuthenticatedDid( req: Request ): Promise { const authHeader = req.headers.get("Authorization"); return await internalGetAuthenticatedDid(authHeader ?? undefined); } async function internalGetAuthenticatedDid( authHeader: string | undefined ): Promise { if (!isInitialized) { console.error( "Authentication module has not been initialized. Call setupAuth() first." ); return null; } if (!authHeader || !authHeader.startsWith("Bearer ")) { return null; } try { // use the verifyJWT function from the borrowed module. // it handles DID resolution and JWT verification internally. // thanks usounds and Skyblur ! const result = await borrowed.verifyJWT(authHeader, serviceDid); if (!result.payload.iss) { throw new Error("Missing issuer (iss) in verified JWT payload"); } return result.payload.iss as string; } catch (err) { console.warn( "JWT verification failed:", err instanceof Error ? err.message : String(err) ); return null; } } /** * @deprecated dont use this use getAuthenticatedDid() instead * @param param0 * @returns */ export const authVerifier: MethodAuthVerifier = async ({ req }) => { //console.log("help us all fuck you",req) console.log("you are doing well") const url = (req as any).url; const params = (req as any).params ?? {}; console.log("Request info:", { url, params }); return { credentials: "did:plc:mn45tewwnse5btfftvd3powc", }; const authHeader = (req as any).headers["authorization"]; const did = await internalGetAuthenticatedDid(authHeader); // throw this later dont do it here // if (!did) { // // i dont know the correct xrpc spec for this // throw new XRPCError(401, 'AuthenticationRequired', 'Invalid or missing authentication token.'); // } console.log(`Successfully authenticated DID: ${did}`); return { credentials: { did: did, }, }; };