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