Something went wrong. Try again.
Testing building apps with atproto
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115import { 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<Keyset | undefined> { if (PUBLIC_URL && PRIVATE_KEY) { return new Keyset([await JoseKey.fromJWK(JSON.parse(PRIVATE_KEY))]); } else { return undefined; }}
export async function getOAuthClient(): Promise<NodeOAuthClient> { 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;}