Graphical PDS migrator for AT Protocol
at main 1.9 kB view raw
1import { Agent } from "npm:@atproto/api"; 2import { getIronSession, SessionOptions } from "npm:iron-session"; 3import { oauthClient } from "./client.ts"; 4import { createSessionOptions, OauthSession } from "../types.ts"; 5 6let oauthSessionOptions: SessionOptions; 7 8/** 9 * Get the OAuth session options. 10 * @returns The OAuth session options 11 */ 12async function getOptions() { 13 if (!oauthSessionOptions) { 14 oauthSessionOptions = await createSessionOptions("oauth_sid"); 15 } 16 return oauthSessionOptions; 17} 18 19/** 20 * Get the OAuth session agent for the given request. 21 * @param req - The request object 22 * @returns The OAuth session agent 23 */ 24export async function getOauthSessionAgent( 25 req: Request, 26) { 27 try { 28 console.log("Getting OAuth session..."); 29 const res = new Response(); 30 const options = await getOptions(); 31 const session = await getIronSession<OauthSession>( 32 req, 33 res, 34 options, 35 ); 36 37 console.log("OAuth session state:", { hasDid: !!session.did }); 38 if (!session.did) { 39 console.log("No OAuth session DID found"); 40 return null; 41 } 42 43 try { 44 console.log("Attempting to restore OAuth session..."); 45 const oauthSession = await oauthClient.restore(session.did); 46 console.log("OAuth restore result:", !!oauthSession); 47 return oauthSession ? new Agent(oauthSession) : null; 48 } catch (err) { 49 console.warn({ err }, "oauth restore failed"); 50 session.destroy(); 51 return null; 52 } 53 } catch (err) { 54 console.warn({ err }, "Failed to get OAuth session"); 55 return null; 56 } 57} 58 59/** 60 * Get the OAuth session for the given request. 61 * @param req - The request object 62 * @param res - The response object 63 * @returns The OAuth session 64 */ 65export async function getOauthSession( 66 req: Request, 67 res: Response = new Response(), 68) { 69 const options = await getOptions(); 70 return getIronSession<OauthSession>( 71 req, 72 res, 73 options, 74 ); 75}