a tool for shared writing and social publishing
1import { Agent } from "@atproto/api";
2import { createOauthClient } from "src/atproto-oauth";
3import { getAuthToken } from "src/auth";
4import { supabaseServerClient } from "supabase/serverClient";
5
6export async function getAuthenticatedAgent(): Promise<Agent | null> {
7 try {
8 const authToken = await getAuthToken();
9
10 if (!authToken || authToken === "null") return null;
11
12 const { data } = await supabaseServerClient
13 .from("email_auth_tokens")
14 .select("identities(atp_did)")
15 .eq("id", authToken)
16 .eq("confirmed", true)
17 .single();
18
19 const did = data?.identities?.atp_did;
20 if (!did) return null;
21
22 const oauthClient = await createOauthClient();
23 const session = await oauthClient.restore(did);
24 return new Agent(session);
25 } catch (error) {
26 console.error("Failed to get authenticated agent:", error);
27 return null;
28 }
29}
30
31export async function getAgent(): Promise<Agent> {
32 const agent = await getAuthenticatedAgent();
33 if (agent) return agent;
34
35 return new Agent({
36 service: "https://public.api.bsky.app",
37 });
38}