import { buildAtprotoLoopbackClientMetadata, JoseKey, Keyset, NodeOAuthClient, } from "@atproto/oauth-client-node"; import type { NodeSavedSession, NodeSavedState, OAuthClientMetadataInput, } from "@atproto/oauth-client-node"; import { db } from "../../db/db"; export const SCOPE = "atproto account:email"; const PUBLIC_URL = process.env.PUBLIC_URL; const PRIVATE_KEY = process.env.PRIVATE_KEY; let client: NodeOAuthClient | null = null; function getClientMetadata(): OAuthClientMetadataInput { if (PUBLIC_URL) { return { client_id: `${PUBLIC_URL}/oauth-client-metadata.json`, client_name: "OAuth Tutorial", client_uri: PUBLIC_URL, redirect_uris: [`${PUBLIC_URL}/oauth/callback`], grant_types: ["authorization_code", "refresh_token"], response_types: ["code"], scope: SCOPE, token_endpoint_auth_method: "private_key_jwt" as const, token_endpoint_auth_signing_alg: "ES256" as const, jwks_uri: `${PUBLIC_URL}/.well-known/jwks.json`, dpop_bound_access_tokens: true, }; } else { return buildAtprotoLoopbackClientMetadata({ scope: SCOPE, redirect_uris: ["http://127.0.0.1:3000/oauth/callback"], }); } } async function getKeyset(): Promise { if (PUBLIC_URL && PRIVATE_KEY) { return new Keyset([await JoseKey.fromJWK(JSON.parse(PRIVATE_KEY))]); } else { return undefined; } } export async function getOAuthClient(): Promise { if (client) return client; client = new NodeOAuthClient({ clientMetadata: getClientMetadata(), keyset: await getKeyset(), stateStore: { async get(key: string) { const stmt = await db.prepare(` SELECT value FROM auth_state WHERE key = ? LIMIT 1; `); const found = await stmt.get(key); return found ? JSON.parse(found.value) : undefined; }, async set(key: string, value: NodeSavedState) { const stmt = await db.prepare(` INSERT INTO auth_state (key, value) VALUES (?, ?) `); await stmt.run(key, JSON.stringify(value)); }, async del(key: string) { await (await db.prepare( `DELETE FROM auth_state WHERE key = ?`, )).run(key); }, }, sessionStore: { async get(key: string) { const stmt = await db.prepare(` SELECT value FROM auth_session WHERE key = ? LIMIT 1; `); const found = await stmt.get(key); return found ? JSON.parse(found.value) : undefined; }, async set(key: string, value: NodeSavedSession) { const stmt = await db.prepare(` INSERT INTO auth_session (key, value) VALUES (?, ?) `); await stmt.run(key, JSON.stringify(value)); }, async del(key: string) { await (await db.prepare( `DELETE FROM auth_session WHERE key = ?`, )).run(key); }, }, }); return client; }