this repo has no description
1import { AtpSessionData, CredentialManager, XRPC } from "@atcute/client";
2
3export interface LoginCredentials {
4 /** The URL of the PDS where the account is located. Defaults to "https://bsky.social". */
5 pds?: string | undefined;
6 /** The account identifier; a DID or handle. */
7 identifier: string;
8 /** The account password. */
9 password: string;
10 /** The 2FA code, if 2FA is enabled. */
11 code?: string;
12}
13
14let xrpc: XRPC | undefined;
15let credentialManager: CredentialManager | undefined;
16
17export async function loginAgent(
18 { pds, ...credentials }: LoginCredentials,
19): Promise<{ agent: XRPC; session: AtpSessionData }> {
20 credentialManager ??= new CredentialManager({ service: pds || "https://bsky.social" });
21 xrpc ??= new XRPC({ handler: credentialManager });
22
23 if (
24 credentialManager.session && credentialsMatchSession(credentials, credentialManager.session)
25 ) {
26 return { agent: xrpc, session: credentialManager.session };
27 }
28 const session = await credentialManager.login(credentials);
29 return { agent: xrpc, session };
30}
31
32const credentialsMatchSession = (credentials: LoginCredentials, session: AtpSessionData) =>
33 (!!credentials.pds ? credentials.pds === session.pdsUri : true)
34 && [session.did, session.handle, session.email].includes(credentials.identifier);