@atproto/lex-password-session 0.0.6 → 0.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # @atproto/lex-password-session
2
2
 
3
+ ## 0.0.7
4
+
5
+ ### Patch Changes
6
+
7
+ - [#4672](https://github.com/bluesky-social/atproto/pull/4672) [`38852f0`](https://github.com/bluesky-social/atproto/commit/38852f0ddfa9fbce8036233dc6af87614e9ae4b2) Thanks [@matthieusieben](https://github.com/matthieusieben)! - Make `PasswordSession` async disposable for better use with hard coded app passwords
8
+
9
+ - [#4672](https://github.com/bluesky-social/atproto/pull/4672) [`38852f0`](https://github.com/bluesky-social/atproto/commit/38852f0ddfa9fbce8036233dc6af87614e9ae4b2) Thanks [@matthieusieben](https://github.com/matthieusieben)! - Add easy login for app password based bots
10
+
11
+ - Updated dependencies [[`38852f0`](https://github.com/bluesky-social/atproto/commit/38852f0ddfa9fbce8036233dc6af87614e9ae4b2)]:
12
+ - @atproto/lex-client@0.0.14
13
+
3
14
  ## 0.0.6
4
15
 
5
16
  ### Patch Changes
@@ -26,6 +26,13 @@ export type DeleteFailure = XrpcFailure<typeof com.atproto.server.deleteSession.
26
26
  export type SessionData = com.atproto.server.createSession.$OutputBody & {
27
27
  service: string;
28
28
  };
29
+ export type LoginOptions = PasswordSessionOptions & {
30
+ service: string | URL;
31
+ identifier: string;
32
+ password: string;
33
+ allowTakendown?: boolean;
34
+ authFactorToken?: string;
35
+ };
29
36
  export type PasswordSessionOptions = {
30
37
  /**
31
38
  * Custom fetch implementation to use for network requests
@@ -114,7 +121,7 @@ export type PasswordSessionOptions = {
114
121
  *
115
122
  * @implements {Agent}
116
123
  */
117
- export declare class PasswordSession implements Agent {
124
+ export declare class PasswordSession implements Agent, AsyncDisposable {
118
125
  #private;
119
126
  protected readonly options: PasswordSessionOptions;
120
127
  constructor(sessionData: SessionData, options?: PasswordSessionOptions);
@@ -191,6 +198,7 @@ export declare class PasswordSession implements Agent {
191
198
  * @throws {DeleteFailure} If the logout request fails due to unexpected errors
192
199
  */
193
200
  logout(): Promise<void>;
201
+ [Symbol.asyncDispose](): Promise<void>;
194
202
  /**
195
203
  * Creates a new account and returns an authenticated session.
196
204
  *
@@ -242,23 +250,42 @@ export declare class PasswordSession implements Agent {
242
250
  * @throws {LexAuthFactorError} If the server requires a 2FA token
243
251
  * @throws If authentication fails (invalid credentials, etc.)
244
252
  *
245
- * @example Basic login with app password
253
+ * **Basic login with app password in script**
254
+ * @example
255
+ * ```ts
256
+ * // .env
257
+ * // APP_PASSWORD_CREDENTIALS="https://<handle>:<app-password>@<pds-hosting-provider>"
258
+ *
259
+ * // Make sure to dispose (or logout) the session when done to avoid leaking
260
+ * // resources and leaving orphaned sessions on the server
261
+ * await using session = await PasswordSession.login(process.env.APP_PASSWORD_CREDENTIALS)
262
+ *
263
+ * // Use session to make authenticated requests
264
+ * ```
265
+ *
266
+ * **Basic login with user password (not recommended!!!)**
267
+ * @example
246
268
  * ```ts
247
269
  * const session = await PasswordSession.login({
248
270
  * service: 'https://bsky.social',
249
271
  * identifier: 'alice.bsky.social',
250
- * password: 'xxxx-xxxx-xxxx-xxxx', // App password
272
+ * password: 'xxxx',
251
273
  * onUpdated: (data) => saveToStorage(data),
274
+ * onDeleted: (data) => clearStorage(data.did),
252
275
  * })
276
+ *
277
+ * // Next time, use resume with the persisted session data to avoid storing
278
+ * // user credentials.
253
279
  * ```
254
280
  *
255
- * @example Handling 2FA requirement
281
+ * **Handling 2FA requirement**
282
+ * @example
256
283
  * ```ts
257
284
  * try {
258
285
  * const session = await PasswordSession.login({
259
286
  * service: 'https://bsky.social',
260
287
  * identifier: 'alice.bsky.social',
261
- * password: 'xxxx-xxxx-xxxx-xxxx',
288
+ * password: 'xxxx',
262
289
  * })
263
290
  * } catch (err) {
264
291
  * if (err instanceof LexAuthFactorError) {
@@ -266,20 +293,14 @@ export declare class PasswordSession implements Agent {
266
293
  * const session = await PasswordSession.login({
267
294
  * service: 'https://bsky.social',
268
295
  * identifier: 'alice.bsky.social',
269
- * password: 'xxxx-xxxx-xxxx-xxxx',
296
+ * password: 'xxxx',
270
297
  * authFactorToken: token,
271
298
  * })
272
299
  * }
273
300
  * }
274
301
  * ```
275
302
  */
276
- static login({ service, identifier, password, allowTakendown, authFactorToken, ...options }: PasswordSessionOptions & {
277
- service: string | URL;
278
- identifier: string;
279
- password: string;
280
- allowTakendown?: boolean;
281
- authFactorToken?: string;
282
- }): Promise<PasswordSession>;
303
+ static login(input: string | URL | LoginOptions): Promise<PasswordSession>;
283
304
  /**
284
305
  * Resume an existing session, ensuring it is still valid by refreshing it.
285
306
  * Any error thrown here indicates that the session is definitely no longer
@@ -1 +1 @@
1
- {"version":3,"file":"password-session.d.ts","sourceRoot":"","sources":["../src/password-session.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,EACL,WAAW,EAIZ,MAAM,qBAAqB,CAAA;AAE5B,OAAO,EAAE,GAAG,EAAE,MAAM,qBAAqB,CAAA;AAGzC;;;;;;GAMG;AACH,MAAM,MAAM,cAAc,GAAG,WAAW,CACtC,OAAO,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,cAAc,CAAC,IAAI,CAC9C,CAAA;AAED;;;;;;GAMG;AACH,MAAM,MAAM,aAAa,GAAG,WAAW,CACrC,OAAO,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,CAC7C,CAAA;AAED;;;;;;GAMG;AACH,MAAM,MAAM,WAAW,GAAG,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,aAAa,CAAC,WAAW,GAAG;IACvE,OAAO,EAAE,MAAM,CAAA;CAChB,CAAA;AAED,MAAM,MAAM,sBAAsB,GAAG;IACnC;;OAEG;IACH,KAAK,CAAC,EAAE,OAAO,UAAU,CAAC,KAAK,CAAA;IAE/B;;;;;;;;;OASG;IACH,SAAS,CAAC,EAAE,CAAC,IAAI,EA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W,EACjB,OAAO,EAAE,sBAAsB,GAC9B,OAAO,CAAC,eAAe,CAAC;IAM3B;;;;;;OAMG;WACU,MAAM,CACjB,IAAI,EAAE,WAAW,EACjB,OAAO,CAAC,EAAE,sBAAsB,GAC/B,OAAO,CAAC,IAAI,CAAC;CAIjB"}
@@ -260,6 +260,9 @@ class PasswordSession {
260
260
  // Successful logout
261
261
  });
262
262
  }
263
+ async [Symbol.asyncDispose]() {
264
+ await this.logout();
265
+ }
263
266
  /**
264
267
  * Creates a new account and returns an authenticated session.
265
268
  *
@@ -317,23 +320,42 @@ class PasswordSession {
317
320
  * @throws {LexAuthFactorError} If the server requires a 2FA token
318
321
  * @throws If authentication fails (invalid credentials, etc.)
319
322
  *
320
- * @example Basic login with app password
323
+ * **Basic login with app password in script**
324
+ * @example
325
+ * ```ts
326
+ * // .env
327
+ * // APP_PASSWORD_CREDENTIALS="https://<handle>:<app-password>@<pds-hosting-provider>"
328
+ *
329
+ * // Make sure to dispose (or logout) the session when done to avoid leaking
330
+ * // resources and leaving orphaned sessions on the server
331
+ * await using session = await PasswordSession.login(process.env.APP_PASSWORD_CREDENTIALS)
332
+ *
333
+ * // Use session to make authenticated requests
334
+ * ```
335
+ *
336
+ * **Basic login with user password (not recommended!!!)**
337
+ * @example
321
338
  * ```ts
322
339
  * const session = await PasswordSession.login({
323
340
  * service: 'https://bsky.social',
324
341
  * identifier: 'alice.bsky.social',
325
- * password: 'xxxx-xxxx-xxxx-xxxx', // App password
342
+ * password: 'xxxx',
326
343
  * onUpdated: (data) => saveToStorage(data),
344
+ * onDeleted: (data) => clearStorage(data.did),
327
345
  * })
346
+ *
347
+ * // Next time, use resume with the persisted session data to avoid storing
348
+ * // user credentials.
328
349
  * ```
329
350
  *
330
- * @example Handling 2FA requirement
351
+ * **Handling 2FA requirement**
352
+ * @example
331
353
  * ```ts
332
354
  * try {
333
355
  * const session = await PasswordSession.login({
334
356
  * service: 'https://bsky.social',
335
357
  * identifier: 'alice.bsky.social',
336
- * password: 'xxxx-xxxx-xxxx-xxxx',
358
+ * password: 'xxxx',
337
359
  * })
338
360
  * } catch (err) {
339
361
  * if (err instanceof LexAuthFactorError) {
@@ -341,14 +363,17 @@ class PasswordSession {
341
363
  * const session = await PasswordSession.login({
342
364
  * service: 'https://bsky.social',
343
365
  * identifier: 'alice.bsky.social',
344
- * password: 'xxxx-xxxx-xxxx-xxxx',
366
+ * password: 'xxxx',
345
367
  * authFactorToken: token,
346
368
  * })
347
369
  * }
348
370
  * }
349
371
  * ```
350
372
  */
351
- static async login({ service, identifier, password, allowTakendown, authFactorToken, ...options }) {
373
+ static async login(input) {
374
+ const { service, identifier, password, allowTakendown, authFactorToken, ...options } = typeof input === 'string' || input instanceof URL
375
+ ? parseLoginUrl(input)
376
+ : input;
352
377
  const xrpcAgent = (0, lex_client_1.buildAgent)({
353
378
  service,
354
379
  fetch: options.fetch,
@@ -403,4 +428,24 @@ function fetchUrl(sessionData, path) {
403
428
  const pdsUrl = (0, util_js_1.extractPdsUrl)(sessionData.didDoc);
404
429
  return new URL(path, pdsUrl ?? sessionData.service);
405
430
  }
431
+ function parseLoginUrl(input) {
432
+ const url = typeof input === 'string' ? new URL(input) : input;
433
+ if (url.pathname !== '/') {
434
+ throw new TypeError('Invalid login URL: unexpected pathname');
435
+ }
436
+ if (url.hash) {
437
+ throw new TypeError('Invalid login URL: unexpected hash');
438
+ }
439
+ if (url.search) {
440
+ throw new TypeError('Invalid login URL: unexpected search parameters');
441
+ }
442
+ if (!url.username || !url.password) {
443
+ throw new TypeError('Invalid login URL: missing identifier or password');
444
+ }
445
+ return {
446
+ service: url.origin,
447
+ identifier: url.username,
448
+ password: url.password,
449
+ };
450
+ }
406
451
  //# sourceMappingURL=password-session.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"password-session.js","sourceRoot":"","sources":["../src/password-session.ts"],"names":[],"mappings":";;;AAAA,oDAM4B;AAC5B,yCAA+C;AAC/C,kDAAyC;AACzC,uCAA+D;AAkG/D;;;;;;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A;YACxC,CAAC;YACD,MAAM,QAAQ,CAAC,MAAM,CAAA;QACvB,CAAC;QAED,MAAM,IAAI,GAAgB;YACxB,GAAG,QAAQ,CAAC,IAAI;YAChB,OAAO,EAAE,MAAM,CAAC,OAAO,CAAC;SACzB,CAAA;QAED,MAAM,KAAK,GAAG,IAAI,eAAe,CAAC,IAAI,EAAE,OAAO,CAAC,CAAA;QAChD,MAAM,OAAO,CAAC,SAAS,EAAE,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,CAAA;QAC1C,OAAO,KAAK,CAAA;IACd,CAAC;IAED;;;;;;;;;;;;OAYG;IACH,MAAM,CAAC,KAAK,CAAC,MAAM,CACjB,IAAiB,EACjB,OAA+B;QAE/B,MAAM,KAAK,GAAG,IAAI,eAAe,CAAC,IAAI,EAAE,OAAO,CAAC,CAAA;QAChD,MAAM,KAAK,CAAC,OAAO,EAAE,CAAA;QACrB,OAAO,KAAK,CAAA;IACd,CAAC;IAED;;;;;;OAMG;IACH,MAAM,CAAC,KAAK,CAAC,MAAM,CACjB,IAAiB,EACjB,OAAgC;QAEhC,MAAM,KAAK,GAAG,IAAI,eAAe,CAAC,IAAI,EAAE,OAAO,CAAC,CAAA;QAChD,MAAM,KAAK,CAAC,MAAM,EAAE,CAAA;IACtB,CAAC;CACF;AAvcD,0CAucC;AAED,SAAS,QAAQ,CAAC,WAAwB,EAAE,IAAY;IACtD,MAAM,MAAM,GAAG,IAAA,uBAAa,EAAC,WAAW,CAAC,MAAM,CAAC,CAAA;IAChD,OAAO,IAAI,GAAG,CAAC,IAAI,EAAE,MAAM,IAAI,WAAW,CAAC,OAAO,CAAC,CAAA;AACrD,CAAC","sourcesContent":["import {\n Agent,\n XrpcFailure,\n buildAgent,\n xrpc,\n xrpcSafe,\n} from '@atproto/lex-client'\nimport { LexAuthFactorError } from './error.js'\nimport { com } from './lexicons/index.js'\nimport { extractPdsUrl, extractXrpcErrorCode } from './util.js'\n\n/**\n * Represents a failure response when refreshing a session.\n *\n * This type captures the possible error responses from\n * `com.atproto.server.refreshSession`, including both expected errors\n * (e.g., invalid/expired refresh token) and unexpected errors (e.g., network issues).\n */\nexport type RefreshFailure = XrpcFailure<\n typeof com.atproto.server.refreshSession.main\n>\n\n/**\n * Represents a failure response when deleting a session.\n *\n * This type captures the possible error responses from\n * `com.atproto.server.deleteSession`, including both expected errors\n * and unexpected errors (e.g., network issues, server unavailability).\n */\nexport type DeleteFailure = XrpcFailure<\n typeof com.atproto.server.deleteSession.main\n>\n\n/**\n * Persisted session data containing authentication credentials and service information.\n *\n * This type extends the response from `com.atproto.server.createSession` with the\n * service URL used for authentication. Store this data securely to resume sessions\n * later without re-authenticating.\n */\nexport type SessionData = com.atproto.server.createSession.$OutputBody & {\n service: string\n}\n\nexport type PasswordSessionOptions = {\n /**\n * Custom fetch implementation to use for network requests\n */\n fetch?: typeof globalThis.fetch\n\n /**\n * Called whenever the session is successfully created/refreshed, and new\n * credentials have been obtained. Use this hook to persist the updated\n * session information.\n *\n * If this callback returns a promise, this function will never be called\n * again (on the same process) until the promise resolves.\n *\n * @note this function **must** not throw\n */\n onUpdated?: (this: PasswordSession, data: SessionData) => void | Promise<void>\n\n /**\n * Called whenever the session update fails due to an expected error, such as\n * a network issue or server unavailability. This function can be used to log\n * the error or notify the user, but should not assume that the session is\n * invalid.\n *\n * @note this function **must** not throw\n */\n onUpdateFailure?: (\n this: PasswordSession,\n data: SessionData,\n err: RefreshFailure,\n ) => void | Promise<void>\n\n /**\n * Called whenever the session is deleted, either due to an explicit logout or\n * because the refresh operation indicated that the session is no longer\n * valid. Use this hook to clean up any persisted session information and\n * update the application state accordingly.\n *\n * @note this function **must** not throw\n */\n onDeleted?: (this: PasswordSession, data: SessionData) => void | Promise<void>\n\n /**\n * Called whenever a session deletion fails due to an unexpected error, such\n * as a network issue or server unavailability. This function can be used to\n * log the error or notify the user. When this function is called, the session\n * might still be valid on the server. It is up to the implementation to\n * decide whether to retry the deletion or keep the session active. Ignoring\n * these errors is not recommended as it can lead to orphaned sessions on the\n * server, or security issues if the user believes they have logged out when a\n * bad actor is still using the session. The implementation should consider\n * keeping track of failed deletions and retrying them later, until they\n * succeed.\n *\n * @note this function **must** not throw\n */\n onDeleteFailure?: (\n this: PasswordSession,\n data: SessionData,\n err: DeleteFailure,\n ) => void | Promise<void>\n}\n\n/**\n * Password-based authentication session for AT Protocol services.\n *\n * This class provides session management for CLI tools, scripts, and bots that\n * need to authenticate with AT Protocol services using password credentials.\n * It implements the {@link Agent} interface, allowing it to be used directly\n * with AT Protocol clients.\n *\n * **Security Warning:** It is strongly recommended to use app passwords instead\n * of main account credentials. App passwords provide limited access and can be\n * revoked independently without compromising your main account. For browser-based\n * applications, use OAuth-based authentication instead.\n *\n * @example Basic usage with app password\n * ```ts\n * const session = await PasswordSession.login({\n * service: 'https://bsky.social',\n * identifier: 'alice.bsky.social',\n * password: 'xxxx-xxxx-xxxx-xxxx', // App password\n * onUpdated: (data) => saveToStorage(data),\n * onDeleted: (data) => clearStorage(data.did),\n * })\n *\n * const client = new Client(session)\n * // Use client to make authenticated requests\n * ```\n *\n * @example Resuming a persisted session\n * ```ts\n * const savedData = JSON.parse(fs.readFileSync('session.json', 'utf8'))\n * const session = await PasswordSession.resume(savedData, {\n * onUpdated: (data) => saveToStorage(data),\n * onDeleted: (data) => clearStorage(data.did),\n * })\n * ```\n *\n * @implements {Agent}\n */\nexport class PasswordSession implements Agent {\n /**\n * Internal {@link Agent} used for session management towards the\n * authentication service only.\n */\n #serviceAgent: Agent\n\n #sessionData: null | SessionData\n #sessionPromise: Promise<SessionData>\n\n constructor(\n sessionData: SessionData,\n protected readonly options: PasswordSessionOptions = {},\n ) {\n this.#serviceAgent = buildAgent({\n service: sessionData.service,\n fetch: options.fetch,\n })\n\n this.#sessionData = sessionData\n this.#sessionPromise = Promise.resolve(this.#sessionData)\n }\n\n /**\n * The DID (Decentralized Identifier) of the authenticated account.\n *\n * @throws {Error} If the session has been destroyed (logged out).\n */\n get did() {\n return this.session.did\n }\n\n /**\n * The handle (username) of the authenticated account.\n *\n * @throws {Error} If the session has been destroyed (logged out).\n */\n get handle() {\n return this.session.handle\n }\n\n /**\n * The current session data containing authentication credentials.\n *\n * @throws {Error} If the session has been destroyed (logged out).\n */\n get session() {\n if (this.#sessionData) return this.#sessionData\n throw new Error('Logged out')\n }\n\n /**\n * Whether this session has been destroyed (logged out).\n *\n * Once destroyed, this session instance can no longer be used for\n * authenticated requests. Create a new session via {@link PasswordSession.login}\n * or {@link PasswordSession.resume}.\n */\n get destroyed(): boolean {\n return this.#sessionData === null\n }\n\n /**\n * Handles authenticated fetch requests to the user's PDS.\n *\n * This method implements the {@link Agent} interface and is called by\n * AT Protocol clients to make authenticated requests. It automatically:\n * - Adds the access token to request headers\n * - Detects expired tokens and triggers refresh\n * - Retries requests after successful token refresh\n *\n * @param path - The request path (will be resolved against the PDS URL)\n * @param init - Standard fetch RequestInit options (headers, body, etc.)\n * @returns The fetch Response from the PDS\n * @throws {TypeError} If an 'authorization' header is already set in init\n */\n async fetchHandler(path: string, init: RequestInit): Promise<Response> {\n const headers = new Headers(init.headers)\n if (headers.has('authorization')) {\n throw new TypeError(\"Unexpected 'authorization' header set\")\n }\n\n const sessionPromise = this.#sessionPromise\n const sessionData = await sessionPromise\n\n const fetch = this.options.fetch ?? globalThis.fetch\n\n headers.set('authorization', `Bearer ${sessionData.accessJwt}`)\n const initialRes = await fetch(fetchUrl(sessionData, path), {\n ...init,\n headers,\n })\n\n const refreshNeeded =\n initialRes.status === 401 ||\n (initialRes.status === 400 &&\n (await extractXrpcErrorCode(initialRes)) === 'ExpiredToken')\n\n if (!refreshNeeded) {\n return initialRes\n }\n\n // Refresh session (unless it was already refreshed in the meantime)\n const newSessionPromise =\n this.#sessionPromise === sessionPromise\n ? this.refresh()\n : this.#sessionPromise\n\n // Error should have been propagated through hooks\n const newSessionData = await newSessionPromise.catch((_err) => null)\n if (!newSessionData) {\n return initialRes\n }\n\n // refresh silently failed, no point in retrying.\n if (newSessionData.accessJwt === sessionData.accessJwt) {\n return initialRes\n }\n\n if (init?.signal?.aborted) {\n return initialRes\n }\n\n // The stream was already consumed. We cannot retry the request. A solution\n // would be to tee() the input stream but that would bufferize the entire\n // stream in memory which can lead to memory starvation. Instead, we will\n // return the original response and let the calling code handle retries.\n if (ReadableStream && init?.body instanceof ReadableStream) {\n return initialRes\n }\n\n // Make sure the initial request is cancelled to avoid leaking resources\n // (NodeJS 👀): https://undici.nodejs.org/#/?id=garbage-collection\n if (!initialRes.bodyUsed) {\n await initialRes.body?.cancel()\n }\n\n // Finally, retry the request with the new access token\n headers.set('authorization', `Bearer ${newSessionData.accessJwt}`)\n return fetch(fetchUrl(newSessionData, path), { ...init, headers })\n }\n\n /**\n * Refreshes the session by obtaining new access and refresh tokens.\n *\n * This method is automatically called by {@link fetchHandler} when the access\n * token expires. You can also call it manually to proactively refresh tokens.\n *\n * On success, the {@link PasswordSessionOptions.onUpdated} callback is invoked\n * with the new session data. On expected failures (invalid session), the\n * {@link PasswordSessionOptions.onDeleted} callback is invoked. On unexpected\n * failures (network issues), the {@link PasswordSessionOptions.onUpdateFailure}\n * callback is invoked and the existing session data is preserved.\n *\n * @returns The refreshed session data\n * @throws {RefreshFailure} If the session is no longer valid (triggers onDeleted)\n */\n async refresh(): Promise<SessionData> {\n this.#sessionPromise = this.#sessionPromise.then(async (sessionData) => {\n const response = await xrpcSafe(\n this.#serviceAgent,\n com.atproto.server.refreshSession.main,\n { headers: { Authorization: `Bearer ${sessionData.refreshJwt}` } },\n )\n\n if (!response.success && response.matchesSchema()) {\n // Expected errors that indicate the session is no longer valid\n await this.options.onDeleted?.call(this, sessionData)\n\n // Update the session promise to a rejected state\n this.#sessionData = null\n throw response\n }\n\n if (!response.success) {\n response.error\n if (response.matchesSchema()) {\n response.error\n }\n // We failed to refresh the token, assume the session might still be\n // valid by returning the existing session.\n await this.options.onUpdateFailure?.call(this, sessionData, response)\n\n return sessionData\n }\n\n const data = response.body\n\n // Historically, refreshSession did not return all the fields from\n // getSession. In particular, emailConfirmed and didDoc were missing.\n // Similarly, some servers might not return the didDoc in refreshSession.\n // We fetch them via getSession if missing, allowing to ensure that we are\n // always talking with the right PDS.\n if (data.emailConfirmed == null || data.didDoc == null) {\n const extraData = await xrpcSafe(\n this.#serviceAgent,\n com.atproto.server.getSession.main,\n { headers: { Authorization: `Bearer ${data.accessJwt}` } },\n )\n if (extraData.success && extraData.body.did === data.did) {\n Object.assign(data, extraData.body)\n }\n }\n\n const newSession: SessionData = {\n ...data,\n service: sessionData.service,\n }\n\n await this.options.onUpdated?.call(this, newSession)\n\n return (this.#sessionData = newSession)\n })\n\n return this.#sessionPromise\n }\n\n /**\n * Logs out by deleting the session on the server.\n *\n * This method invalidates both the access and refresh tokens on the server,\n * preventing any further use of this session. After successful logout, the\n * session is marked as destroyed and the {@link PasswordSessionOptions.onDeleted}\n * callback is invoked.\n *\n * If the logout request fails due to network issues or server unavailability,\n * the {@link PasswordSessionOptions.onDeleteFailure} callback is invoked and\n * the session remains active locally. In this case, you should retry the\n * logout later to ensure the session is properly invalidated on the server.\n *\n * @throws {DeleteFailure} If the logout request fails due to unexpected errors\n */\n async logout(): Promise<void> {\n let reason: DeleteFailure | null = null\n\n this.#sessionPromise = this.#sessionPromise.then(async (sessionData) => {\n const result = await xrpcSafe(\n this.#serviceAgent,\n com.atproto.server.deleteSession.main,\n { headers: { Authorization: `Bearer ${sessionData.refreshJwt}` } },\n )\n\n if (result.success || result.matchesSchema()) {\n await this.options.onDeleted?.call(this, sessionData)\n\n // Update the session promise to a rejected state\n this.#sessionData = null\n throw new Error('Logged out')\n } else {\n // Capture the reason for the failure to re-throw in the outer promise\n reason = result\n\n // An unknown/unexpected error occurred (network, server down, etc)\n await this.options.onDeleteFailure?.call(this, sessionData, result)\n\n // Keep the session in an active state\n return sessionData\n }\n })\n\n return this.#sessionPromise.then(\n (_session) => {\n // If the promise above resolved, then logout failed. Re-throw the\n // reason captured earlier.\n throw reason!\n },\n (_err) => {\n // Successful logout\n },\n )\n }\n\n /**\n * Creates a new account and returns an authenticated session.\n *\n * This static method registers a new account on the specified service and\n * automatically creates an authenticated session for it.\n *\n * @param body - Account creation parameters (handle, email, password, etc.)\n * @param options - Session options including the service URL\n * @returns A new PasswordSession for the created account\n * @throws If account creation fails (e.g., handle taken, invalid invite code)\n *\n * @example\n * ```ts\n * const session = await PasswordSession.createAccount(\n * {\n * handle: 'alice.bsky.social',\n * email: 'alice@example.com',\n * password: 'secure-password',\n * },\n * {\n * service: 'https://bsky.social',\n * onUpdated: (data) => saveToStorage(data),\n * }\n * )\n * ```\n */\n static async createAccount(\n body: com.atproto.server.createAccount.$InputBody,\n {\n service,\n headers,\n ...options\n }: PasswordSessionOptions & {\n headers?: HeadersInit\n service: string | URL\n },\n ): Promise<PasswordSession> {\n const response = await xrpc(\n buildAgent({ service, headers, fetch: options.fetch }),\n com.atproto.server.createAccount.main,\n { body },\n )\n\n const data: SessionData = {\n ...response.body,\n service: String(service),\n }\n\n const agent = new PasswordSession(data, options)\n await options.onUpdated?.call(agent, data)\n return agent\n }\n\n /**\n * Creates a new authenticated session using password credentials.\n *\n * This static method authenticates with the specified service and returns\n * a new PasswordSession instance that can be used for authenticated requests.\n *\n * **Security Warning:** It is strongly recommended to use app passwords instead\n * of main account credentials. App passwords can be created in your account\n * settings and provide limited access that can be revoked independently. For\n * browser-based applications, use OAuth-based authentication instead.\n *\n * @param options - Login options including service URL, identifier, and password\n * @param options.service - The AT Protocol service URL (e.g., 'https://bsky.social')\n * @param options.identifier - The user's handle or DID\n * @param options.password - The user's password or app password\n * @param options.allowTakendown - If true, allow login to takendown accounts\n * @param options.authFactorToken - 2FA token if required by the server\n * @returns A new authenticated PasswordSession\n * @throws {LexAuthFactorError} If the server requires a 2FA token\n * @throws If authentication fails (invalid credentials, etc.)\n *\n * @example Basic login with app password\n * ```ts\n * const session = await PasswordSession.login({\n * service: 'https://bsky.social',\n * identifier: 'alice.bsky.social',\n * password: 'xxxx-xxxx-xxxx-xxxx', // App password\n * onUpdated: (data) => saveToStorage(data),\n * })\n * ```\n *\n * @example Handling 2FA requirement\n * ```ts\n * try {\n * const session = await PasswordSession.login({\n * service: 'https://bsky.social',\n * identifier: 'alice.bsky.social',\n * password: 'xxxx-xxxx-xxxx-xxxx',\n * })\n * } catch (err) {\n * if (err instanceof LexAuthFactorError) {\n * const token = await promptUser('Enter 2FA code:')\n * const session = await PasswordSession.login({\n * service: 'https://bsky.social',\n * identifier: 'alice.bsky.social',\n * password: 'xxxx-xxxx-xxxx-xxxx',\n * authFactorToken: token,\n * })\n * }\n * }\n * ```\n */\n static async login({\n service,\n identifier,\n password,\n allowTakendown,\n authFactorToken,\n ...options\n }: PasswordSessionOptions & {\n service: string | URL\n identifier: string\n password: string\n allowTakendown?: boolean\n authFactorToken?: string\n }): Promise<PasswordSession> {\n const xrpcAgent = buildAgent({\n service,\n fetch: options.fetch,\n })\n\n const response = await xrpcSafe(\n xrpcAgent,\n com.atproto.server.createSession.main,\n { body: { identifier, password, allowTakendown, authFactorToken } },\n )\n\n if (!response.success) {\n if (response.error === 'AuthFactorTokenRequired') {\n throw new LexAuthFactorError(response)\n }\n throw response.reason\n }\n\n const data: SessionData = {\n ...response.body,\n service: String(service),\n }\n\n const agent = new PasswordSession(data, options)\n await options.onUpdated?.call(agent, data)\n return agent\n }\n\n /**\n * Resume an existing session, ensuring it is still valid by refreshing it.\n * Any error thrown here indicates that the session is definitely no longer\n * valid. Network errors will be propagated through the\n * {@link PasswordSessionOptions.onUpdateFailure} hook, and not re-thrown\n * here. This means that a resolved promise does not necessarily indicate a\n * valid session, only that it's refresh did not definitively fail.\n *\n * This is the same as calling {@link PasswordSession.refresh} after\n * constructing the {@link PasswordSession} manually.\n *\n * @throws If, and only if, the session is definitely no longer valid.\n */\n static async resume(\n data: SessionData,\n options: PasswordSessionOptions,\n ): Promise<PasswordSession> {\n const agent = new PasswordSession(data, options)\n await agent.refresh()\n return agent\n }\n\n /**\n * Delete a session without having to {@link resume resume()} it first, or\n * provide hooks.\n *\n * @throws In case of unexpected error (network issue, server down, etc)\n * meaning that the session may still be valid.\n */\n static async delete(\n data: SessionData,\n options?: PasswordSessionOptions,\n ): Promise<void> {\n const agent = new PasswordSession(data, options)\n await agent.logout()\n }\n}\n\nfunction fetchUrl(sessionData: SessionData, path: string): URL {\n const pdsUrl = extractPdsUrl(sessionData.didDoc)\n return new URL(path, pdsUrl ?? sessionData.service)\n}\n"]}
1
+ {"version":3,"file":"password-session.js","sourceRoot":"","sources":["../src/password-session.ts"],"names":[],"mappings":";;;AAAA,oDAM4B;AAC5B,yCAA+C;AAC/C,kDAAyC;AACzC,uCAA+D;AA0G/D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,MAAa,eAAe;IAYL;IAXrB;;;OAGG;IACH,aAAa,CAAO;IAEpB,YAAY,CAAoB;IAChC,eAAe,CAAsB;IAErC,YACE,WAAwB,EACL,UAAkC,EAAE;QAApC,YAAO,GAAP,OAAO,CAA6B;QAEvD,IAAI,CAAC,aAAa,GAAG,IAAA,uBAAU,EAAC;YAC9B,OAAO,EAAE,WAAW,CAAC,OAAO;YAC5B,KAAK,EAAE,OAAO,CAAC,KAAK;SACrB,CAAC,CAAA;QAEF,IAAI,CAAC,YAAY,GAAG,WAAW,CAAA;QAC/B,IAAI,CAAC,eAAe,GAAG,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,YAAY,CAAC,CAAA;IAC3D,CAAC;IAED;;;;OAIG;IACH,IAAI,GAAG;QACL,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAA;IACzB,CAAC;IAED;;;;OAIG;IACH,IAAI,MAAM;QACR,OAAO,IAAI,CAAC,OAAO,CAAC,MAAM,CAAA;IAC5B,CAAC;IAED;;;;OAIG;IACH,IAAI,OAAO;QACT,IAAI,IAAI,CAAC,YAAY;YAAE,OAAO,IAAI,CAAC,YAAY,CAAA;QAC/C,MAAM,IAAI,KAAK,CAAC,YAAY,CAAC,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QAAQ;KACvB,CAAA;AACH,CAAC","sourcesContent":["import {\n Agent,\n XrpcFailure,\n buildAgent,\n xrpc,\n xrpcSafe,\n} from '@atproto/lex-client'\nimport { LexAuthFactorError } from './error.js'\nimport { com } from './lexicons/index.js'\nimport { extractPdsUrl, extractXrpcErrorCode } from './util.js'\n\n/**\n * Represents a failure response when refreshing a session.\n *\n * This type captures the possible error responses from\n * `com.atproto.server.refreshSession`, including both expected errors\n * (e.g., invalid/expired refresh token) and unexpected errors (e.g., network issues).\n */\nexport type RefreshFailure = XrpcFailure<\n typeof com.atproto.server.refreshSession.main\n>\n\n/**\n * Represents a failure response when deleting a session.\n *\n * This type captures the possible error responses from\n * `com.atproto.server.deleteSession`, including both expected errors\n * and unexpected errors (e.g., network issues, server unavailability).\n */\nexport type DeleteFailure = XrpcFailure<\n typeof com.atproto.server.deleteSession.main\n>\n\n/**\n * Persisted session data containing authentication credentials and service information.\n *\n * This type extends the response from `com.atproto.server.createSession` with the\n * service URL used for authentication. Store this data securely to resume sessions\n * later without re-authenticating.\n */\nexport type SessionData = com.atproto.server.createSession.$OutputBody & {\n service: string\n}\n\nexport type LoginOptions = PasswordSessionOptions & {\n service: string | URL\n identifier: string\n password: string\n allowTakendown?: boolean\n authFactorToken?: string\n}\n\nexport type PasswordSessionOptions = {\n /**\n * Custom fetch implementation to use for network requests\n */\n fetch?: typeof globalThis.fetch\n\n /**\n * Called whenever the session is successfully created/refreshed, and new\n * credentials have been obtained. Use this hook to persist the updated\n * session information.\n *\n * If this callback returns a promise, this function will never be called\n * again (on the same process) until the promise resolves.\n *\n * @note this function **must** not throw\n */\n onUpdated?: (this: PasswordSession, data: SessionData) => void | Promise<void>\n\n /**\n * Called whenever the session update fails due to an expected error, such as\n * a network issue or server unavailability. This function can be used to log\n * the error or notify the user, but should not assume that the session is\n * invalid.\n *\n * @note this function **must** not throw\n */\n onUpdateFailure?: (\n this: PasswordSession,\n data: SessionData,\n err: RefreshFailure,\n ) => void | Promise<void>\n\n /**\n * Called whenever the session is deleted, either due to an explicit logout or\n * because the refresh operation indicated that the session is no longer\n * valid. Use this hook to clean up any persisted session information and\n * update the application state accordingly.\n *\n * @note this function **must** not throw\n */\n onDeleted?: (this: PasswordSession, data: SessionData) => void | Promise<void>\n\n /**\n * Called whenever a session deletion fails due to an unexpected error, such\n * as a network issue or server unavailability. This function can be used to\n * log the error or notify the user. When this function is called, the session\n * might still be valid on the server. It is up to the implementation to\n * decide whether to retry the deletion or keep the session active. Ignoring\n * these errors is not recommended as it can lead to orphaned sessions on the\n * server, or security issues if the user believes they have logged out when a\n * bad actor is still using the session. The implementation should consider\n * keeping track of failed deletions and retrying them later, until they\n * succeed.\n *\n * @note this function **must** not throw\n */\n onDeleteFailure?: (\n this: PasswordSession,\n data: SessionData,\n err: DeleteFailure,\n ) => void | Promise<void>\n}\n\n/**\n * Password-based authentication session for AT Protocol services.\n *\n * This class provides session management for CLI tools, scripts, and bots that\n * need to authenticate with AT Protocol services using password credentials.\n * It implements the {@link Agent} interface, allowing it to be used directly\n * with AT Protocol clients.\n *\n * **Security Warning:** It is strongly recommended to use app passwords instead\n * of main account credentials. App passwords provide limited access and can be\n * revoked independently without compromising your main account. For browser-based\n * applications, use OAuth-based authentication instead.\n *\n * @example Basic usage with app password\n * ```ts\n * const session = await PasswordSession.login({\n * service: 'https://bsky.social',\n * identifier: 'alice.bsky.social',\n * password: 'xxxx-xxxx-xxxx-xxxx', // App password\n * onUpdated: (data) => saveToStorage(data),\n * onDeleted: (data) => clearStorage(data.did),\n * })\n *\n * const client = new Client(session)\n * // Use client to make authenticated requests\n * ```\n *\n * @example Resuming a persisted session\n * ```ts\n * const savedData = JSON.parse(fs.readFileSync('session.json', 'utf8'))\n * const session = await PasswordSession.resume(savedData, {\n * onUpdated: (data) => saveToStorage(data),\n * onDeleted: (data) => clearStorage(data.did),\n * })\n * ```\n *\n * @implements {Agent}\n */\nexport class PasswordSession implements Agent, AsyncDisposable {\n /**\n * Internal {@link Agent} used for session management towards the\n * authentication service only.\n */\n #serviceAgent: Agent\n\n #sessionData: null | SessionData\n #sessionPromise: Promise<SessionData>\n\n constructor(\n sessionData: SessionData,\n protected readonly options: PasswordSessionOptions = {},\n ) {\n this.#serviceAgent = buildAgent({\n service: sessionData.service,\n fetch: options.fetch,\n })\n\n this.#sessionData = sessionData\n this.#sessionPromise = Promise.resolve(this.#sessionData)\n }\n\n /**\n * The DID (Decentralized Identifier) of the authenticated account.\n *\n * @throws {Error} If the session has been destroyed (logged out).\n */\n get did() {\n return this.session.did\n }\n\n /**\n * The handle (username) of the authenticated account.\n *\n * @throws {Error} If the session has been destroyed (logged out).\n */\n get handle() {\n return this.session.handle\n }\n\n /**\n * The current session data containing authentication credentials.\n *\n * @throws {Error} If the session has been destroyed (logged out).\n */\n get session() {\n if (this.#sessionData) return this.#sessionData\n throw new Error('Logged out')\n }\n\n /**\n * Whether this session has been destroyed (logged out).\n *\n * Once destroyed, this session instance can no longer be used for\n * authenticated requests. Create a new session via {@link PasswordSession.login}\n * or {@link PasswordSession.resume}.\n */\n get destroyed(): boolean {\n return this.#sessionData === null\n }\n\n /**\n * Handles authenticated fetch requests to the user's PDS.\n *\n * This method implements the {@link Agent} interface and is called by\n * AT Protocol clients to make authenticated requests. It automatically:\n * - Adds the access token to request headers\n * - Detects expired tokens and triggers refresh\n * - Retries requests after successful token refresh\n *\n * @param path - The request path (will be resolved against the PDS URL)\n * @param init - Standard fetch RequestInit options (headers, body, etc.)\n * @returns The fetch Response from the PDS\n * @throws {TypeError} If an 'authorization' header is already set in init\n */\n async fetchHandler(path: string, init: RequestInit): Promise<Response> {\n const headers = new Headers(init.headers)\n if (headers.has('authorization')) {\n throw new TypeError(\"Unexpected 'authorization' header set\")\n }\n\n const sessionPromise = this.#sessionPromise\n const sessionData = await sessionPromise\n\n const fetch = this.options.fetch ?? globalThis.fetch\n\n headers.set('authorization', `Bearer ${sessionData.accessJwt}`)\n const initialRes = await fetch(fetchUrl(sessionData, path), {\n ...init,\n headers,\n })\n\n const refreshNeeded =\n initialRes.status === 401 ||\n (initialRes.status === 400 &&\n (await extractXrpcErrorCode(initialRes)) === 'ExpiredToken')\n\n if (!refreshNeeded) {\n return initialRes\n }\n\n // Refresh session (unless it was already refreshed in the meantime)\n const newSessionPromise =\n this.#sessionPromise === sessionPromise\n ? this.refresh()\n : this.#sessionPromise\n\n // Error should have been propagated through hooks\n const newSessionData = await newSessionPromise.catch((_err) => null)\n if (!newSessionData) {\n return initialRes\n }\n\n // refresh silently failed, no point in retrying.\n if (newSessionData.accessJwt === sessionData.accessJwt) {\n return initialRes\n }\n\n if (init?.signal?.aborted) {\n return initialRes\n }\n\n // The stream was already consumed. We cannot retry the request. A solution\n // would be to tee() the input stream but that would bufferize the entire\n // stream in memory which can lead to memory starvation. Instead, we will\n // return the original response and let the calling code handle retries.\n if (ReadableStream && init?.body instanceof ReadableStream) {\n return initialRes\n }\n\n // Make sure the initial request is cancelled to avoid leaking resources\n // (NodeJS 👀): https://undici.nodejs.org/#/?id=garbage-collection\n if (!initialRes.bodyUsed) {\n await initialRes.body?.cancel()\n }\n\n // Finally, retry the request with the new access token\n headers.set('authorization', `Bearer ${newSessionData.accessJwt}`)\n return fetch(fetchUrl(newSessionData, path), { ...init, headers })\n }\n\n /**\n * Refreshes the session by obtaining new access and refresh tokens.\n *\n * This method is automatically called by {@link fetchHandler} when the access\n * token expires. You can also call it manually to proactively refresh tokens.\n *\n * On success, the {@link PasswordSessionOptions.onUpdated} callback is invoked\n * with the new session data. On expected failures (invalid session), the\n * {@link PasswordSessionOptions.onDeleted} callback is invoked. On unexpected\n * failures (network issues), the {@link PasswordSessionOptions.onUpdateFailure}\n * callback is invoked and the existing session data is preserved.\n *\n * @returns The refreshed session data\n * @throws {RefreshFailure} If the session is no longer valid (triggers onDeleted)\n */\n async refresh(): Promise<SessionData> {\n this.#sessionPromise = this.#sessionPromise.then(async (sessionData) => {\n const response = await xrpcSafe(\n this.#serviceAgent,\n com.atproto.server.refreshSession.main,\n { headers: { Authorization: `Bearer ${sessionData.refreshJwt}` } },\n )\n\n if (!response.success && response.matchesSchema()) {\n // Expected errors that indicate the session is no longer valid\n await this.options.onDeleted?.call(this, sessionData)\n\n // Update the session promise to a rejected state\n this.#sessionData = null\n throw response\n }\n\n if (!response.success) {\n response.error\n if (response.matchesSchema()) {\n response.error\n }\n // We failed to refresh the token, assume the session might still be\n // valid by returning the existing session.\n await this.options.onUpdateFailure?.call(this, sessionData, response)\n\n return sessionData\n }\n\n const data = response.body\n\n // Historically, refreshSession did not return all the fields from\n // getSession. In particular, emailConfirmed and didDoc were missing.\n // Similarly, some servers might not return the didDoc in refreshSession.\n // We fetch them via getSession if missing, allowing to ensure that we are\n // always talking with the right PDS.\n if (data.emailConfirmed == null || data.didDoc == null) {\n const extraData = await xrpcSafe(\n this.#serviceAgent,\n com.atproto.server.getSession.main,\n { headers: { Authorization: `Bearer ${data.accessJwt}` } },\n )\n if (extraData.success && extraData.body.did === data.did) {\n Object.assign(data, extraData.body)\n }\n }\n\n const newSession: SessionData = {\n ...data,\n service: sessionData.service,\n }\n\n await this.options.onUpdated?.call(this, newSession)\n\n return (this.#sessionData = newSession)\n })\n\n return this.#sessionPromise\n }\n\n /**\n * Logs out by deleting the session on the server.\n *\n * This method invalidates both the access and refresh tokens on the server,\n * preventing any further use of this session. After successful logout, the\n * session is marked as destroyed and the {@link PasswordSessionOptions.onDeleted}\n * callback is invoked.\n *\n * If the logout request fails due to network issues or server unavailability,\n * the {@link PasswordSessionOptions.onDeleteFailure} callback is invoked and\n * the session remains active locally. In this case, you should retry the\n * logout later to ensure the session is properly invalidated on the server.\n *\n * @throws {DeleteFailure} If the logout request fails due to unexpected errors\n */\n async logout(): Promise<void> {\n let reason: DeleteFailure | null = null\n\n this.#sessionPromise = this.#sessionPromise.then(async (sessionData) => {\n const result = await xrpcSafe(\n this.#serviceAgent,\n com.atproto.server.deleteSession.main,\n { headers: { Authorization: `Bearer ${sessionData.refreshJwt}` } },\n )\n\n if (result.success || result.matchesSchema()) {\n await this.options.onDeleted?.call(this, sessionData)\n\n // Update the session promise to a rejected state\n this.#sessionData = null\n throw new Error('Logged out')\n } else {\n // Capture the reason for the failure to re-throw in the outer promise\n reason = result\n\n // An unknown/unexpected error occurred (network, server down, etc)\n await this.options.onDeleteFailure?.call(this, sessionData, result)\n\n // Keep the session in an active state\n return sessionData\n }\n })\n\n return this.#sessionPromise.then(\n (_session) => {\n // If the promise above resolved, then logout failed. Re-throw the\n // reason captured earlier.\n throw reason!\n },\n (_err) => {\n // Successful logout\n },\n )\n }\n\n async [Symbol.asyncDispose]() {\n await this.logout()\n }\n\n /**\n * Creates a new account and returns an authenticated session.\n *\n * This static method registers a new account on the specified service and\n * automatically creates an authenticated session for it.\n *\n * @param body - Account creation parameters (handle, email, password, etc.)\n * @param options - Session options including the service URL\n * @returns A new PasswordSession for the created account\n * @throws If account creation fails (e.g., handle taken, invalid invite code)\n *\n * @example\n * ```ts\n * const session = await PasswordSession.createAccount(\n * {\n * handle: 'alice.bsky.social',\n * email: 'alice@example.com',\n * password: 'secure-password',\n * },\n * {\n * service: 'https://bsky.social',\n * onUpdated: (data) => saveToStorage(data),\n * }\n * )\n * ```\n */\n static async createAccount(\n body: com.atproto.server.createAccount.$InputBody,\n {\n service,\n headers,\n ...options\n }: PasswordSessionOptions & {\n headers?: HeadersInit\n service: string | URL\n },\n ): Promise<PasswordSession> {\n const response = await xrpc(\n buildAgent({ service, headers, fetch: options.fetch }),\n com.atproto.server.createAccount.main,\n { body },\n )\n\n const data: SessionData = {\n ...response.body,\n service: String(service),\n }\n\n const agent = new PasswordSession(data, options)\n await options.onUpdated?.call(agent, data)\n return agent\n }\n\n /**\n * Creates a new authenticated session using password credentials.\n *\n * This static method authenticates with the specified service and returns\n * a new PasswordSession instance that can be used for authenticated requests.\n *\n * **Security Warning:** It is strongly recommended to use app passwords instead\n * of main account credentials. App passwords can be created in your account\n * settings and provide limited access that can be revoked independently. For\n * browser-based applications, use OAuth-based authentication instead.\n *\n * @param options - Login options including service URL, identifier, and password\n * @param options.service - The AT Protocol service URL (e.g., 'https://bsky.social')\n * @param options.identifier - The user's handle or DID\n * @param options.password - The user's password or app password\n * @param options.allowTakendown - If true, allow login to takendown accounts\n * @param options.authFactorToken - 2FA token if required by the server\n * @returns A new authenticated PasswordSession\n * @throws {LexAuthFactorError} If the server requires a 2FA token\n * @throws If authentication fails (invalid credentials, etc.)\n *\n * **Basic login with app password in script**\n * @example\n * ```ts\n * // .env\n * // APP_PASSWORD_CREDENTIALS=\"https://<handle>:<app-password>@<pds-hosting-provider>\"\n *\n * // Make sure to dispose (or logout) the session when done to avoid leaking\n * // resources and leaving orphaned sessions on the server\n * await using session = await PasswordSession.login(process.env.APP_PASSWORD_CREDENTIALS)\n *\n * // Use session to make authenticated requests\n * ```\n *\n * **Basic login with user password (not recommended!!!)**\n * @example\n * ```ts\n * const session = await PasswordSession.login({\n * service: 'https://bsky.social',\n * identifier: 'alice.bsky.social',\n * password: 'xxxx',\n * onUpdated: (data) => saveToStorage(data),\n * onDeleted: (data) => clearStorage(data.did),\n * })\n *\n * // Next time, use resume with the persisted session data to avoid storing\n * // user credentials.\n * ```\n *\n * **Handling 2FA requirement**\n * @example\n * ```ts\n * try {\n * const session = await PasswordSession.login({\n * service: 'https://bsky.social',\n * identifier: 'alice.bsky.social',\n * password: 'xxxx',\n * })\n * } catch (err) {\n * if (err instanceof LexAuthFactorError) {\n * const token = await promptUser('Enter 2FA code:')\n * const session = await PasswordSession.login({\n * service: 'https://bsky.social',\n * identifier: 'alice.bsky.social',\n * password: 'xxxx',\n * authFactorToken: token,\n * })\n * }\n * }\n * ```\n */\n static async login(\n input: string | URL | LoginOptions,\n ): Promise<PasswordSession> {\n const {\n service,\n identifier,\n password,\n allowTakendown,\n authFactorToken,\n ...options\n } =\n typeof input === 'string' || input instanceof URL\n ? parseLoginUrl(input)\n : input\n\n const xrpcAgent = buildAgent({\n service,\n fetch: options.fetch,\n })\n\n const response = await xrpcSafe(\n xrpcAgent,\n com.atproto.server.createSession.main,\n { body: { identifier, password, allowTakendown, authFactorToken } },\n )\n\n if (!response.success) {\n if (response.error === 'AuthFactorTokenRequired') {\n throw new LexAuthFactorError(response)\n }\n throw response.reason\n }\n\n const data: SessionData = {\n ...response.body,\n service: String(service),\n }\n\n const agent = new PasswordSession(data, options)\n await options.onUpdated?.call(agent, data)\n return agent\n }\n\n /**\n * Resume an existing session, ensuring it is still valid by refreshing it.\n * Any error thrown here indicates that the session is definitely no longer\n * valid. Network errors will be propagated through the\n * {@link PasswordSessionOptions.onUpdateFailure} hook, and not re-thrown\n * here. This means that a resolved promise does not necessarily indicate a\n * valid session, only that it's refresh did not definitively fail.\n *\n * This is the same as calling {@link PasswordSession.refresh} after\n * constructing the {@link PasswordSession} manually.\n *\n * @throws If, and only if, the session is definitely no longer valid.\n */\n static async resume(\n data: SessionData,\n options: PasswordSessionOptions,\n ): Promise<PasswordSession> {\n const agent = new PasswordSession(data, options)\n await agent.refresh()\n return agent\n }\n\n /**\n * Delete a session without having to {@link resume resume()} it first, or\n * provide hooks.\n *\n * @throws In case of unexpected error (network issue, server down, etc)\n * meaning that the session may still be valid.\n */\n static async delete(\n data: SessionData,\n options?: PasswordSessionOptions,\n ): Promise<void> {\n const agent = new PasswordSession(data, options)\n await agent.logout()\n }\n}\n\nfunction fetchUrl(sessionData: SessionData, path: string): URL {\n const pdsUrl = extractPdsUrl(sessionData.didDoc)\n return new URL(path, pdsUrl ?? sessionData.service)\n}\n\nfunction parseLoginUrl(input: string | URL): LoginOptions {\n const url = typeof input === 'string' ? new URL(input) : input\n if (url.pathname !== '/') {\n throw new TypeError('Invalid login URL: unexpected pathname')\n }\n if (url.hash) {\n throw new TypeError('Invalid login URL: unexpected hash')\n }\n if (url.search) {\n throw new TypeError('Invalid login URL: unexpected search parameters')\n }\n if (!url.username || !url.password) {\n throw new TypeError('Invalid login URL: missing identifier or password')\n }\n return {\n service: url.origin,\n identifier: url.username,\n password: url.password,\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atproto/lex-password-session",
3
- "version": "0.0.6",
3
+ "version": "0.0.7",
4
4
  "license": "MIT",
5
5
  "description": "Password based client authentication for AT Lexicons",
6
6
  "keywords": [
@@ -36,13 +36,13 @@
36
36
  },
37
37
  "dependencies": {
38
38
  "tslib": "^2.8.1",
39
- "@atproto/lex-schema": "^0.0.13",
40
- "@atproto/lex-client": "^0.0.13"
39
+ "@atproto/lex-client": "^0.0.14",
40
+ "@atproto/lex-schema": "^0.0.13"
41
41
  },
42
42
  "devDependencies": {
43
43
  "vitest": "^4.0.16",
44
44
  "@atproto/lex-builder": "^0.0.16",
45
- "@atproto/lex-server": "^0.0.10"
45
+ "@atproto/lex-server": "^0.0.11"
46
46
  },
47
47
  "scripts": {
48
48
  "prebuild": "node ./scripts/lex-build.mjs",
@@ -42,6 +42,14 @@ export type SessionData = com.atproto.server.createSession.$OutputBody & {
42
42
  service: string
43
43
  }
44
44
 
45
+ export type LoginOptions = PasswordSessionOptions & {
46
+ service: string | URL
47
+ identifier: string
48
+ password: string
49
+ allowTakendown?: boolean
50
+ authFactorToken?: string
51
+ }
52
+
45
53
  export type PasswordSessionOptions = {
46
54
  /**
47
55
  * Custom fetch implementation to use for network requests
@@ -143,7 +151,7 @@ export type PasswordSessionOptions = {
143
151
  *
144
152
  * @implements {Agent}
145
153
  */
146
- export class PasswordSession implements Agent {
154
+ export class PasswordSession implements Agent, AsyncDisposable {
147
155
  /**
148
156
  * Internal {@link Agent} used for session management towards the
149
157
  * authentication service only.
@@ -415,6 +423,10 @@ export class PasswordSession implements Agent {
415
423
  )
416
424
  }
417
425
 
426
+ async [Symbol.asyncDispose]() {
427
+ await this.logout()
428
+ }
429
+
418
430
  /**
419
431
  * Creates a new account and returns an authenticated session.
420
432
  *
@@ -489,23 +501,42 @@ export class PasswordSession implements Agent {
489
501
  * @throws {LexAuthFactorError} If the server requires a 2FA token
490
502
  * @throws If authentication fails (invalid credentials, etc.)
491
503
  *
492
- * @example Basic login with app password
504
+ * **Basic login with app password in script**
505
+ * @example
506
+ * ```ts
507
+ * // .env
508
+ * // APP_PASSWORD_CREDENTIALS="https://<handle>:<app-password>@<pds-hosting-provider>"
509
+ *
510
+ * // Make sure to dispose (or logout) the session when done to avoid leaking
511
+ * // resources and leaving orphaned sessions on the server
512
+ * await using session = await PasswordSession.login(process.env.APP_PASSWORD_CREDENTIALS)
513
+ *
514
+ * // Use session to make authenticated requests
515
+ * ```
516
+ *
517
+ * **Basic login with user password (not recommended!!!)**
518
+ * @example
493
519
  * ```ts
494
520
  * const session = await PasswordSession.login({
495
521
  * service: 'https://bsky.social',
496
522
  * identifier: 'alice.bsky.social',
497
- * password: 'xxxx-xxxx-xxxx-xxxx', // App password
523
+ * password: 'xxxx',
498
524
  * onUpdated: (data) => saveToStorage(data),
525
+ * onDeleted: (data) => clearStorage(data.did),
499
526
  * })
527
+ *
528
+ * // Next time, use resume with the persisted session data to avoid storing
529
+ * // user credentials.
500
530
  * ```
501
531
  *
502
- * @example Handling 2FA requirement
532
+ * **Handling 2FA requirement**
533
+ * @example
503
534
  * ```ts
504
535
  * try {
505
536
  * const session = await PasswordSession.login({
506
537
  * service: 'https://bsky.social',
507
538
  * identifier: 'alice.bsky.social',
508
- * password: 'xxxx-xxxx-xxxx-xxxx',
539
+ * password: 'xxxx',
509
540
  * })
510
541
  * } catch (err) {
511
542
  * if (err instanceof LexAuthFactorError) {
@@ -513,27 +544,28 @@ export class PasswordSession implements Agent {
513
544
  * const session = await PasswordSession.login({
514
545
  * service: 'https://bsky.social',
515
546
  * identifier: 'alice.bsky.social',
516
- * password: 'xxxx-xxxx-xxxx-xxxx',
547
+ * password: 'xxxx',
517
548
  * authFactorToken: token,
518
549
  * })
519
550
  * }
520
551
  * }
521
552
  * ```
522
553
  */
523
- static async login({
524
- service,
525
- identifier,
526
- password,
527
- allowTakendown,
528
- authFactorToken,
529
- ...options
530
- }: PasswordSessionOptions & {
531
- service: string | URL
532
- identifier: string
533
- password: string
534
- allowTakendown?: boolean
535
- authFactorToken?: string
536
- }): Promise<PasswordSession> {
554
+ static async login(
555
+ input: string | URL | LoginOptions,
556
+ ): Promise<PasswordSession> {
557
+ const {
558
+ service,
559
+ identifier,
560
+ password,
561
+ allowTakendown,
562
+ authFactorToken,
563
+ ...options
564
+ } =
565
+ typeof input === 'string' || input instanceof URL
566
+ ? parseLoginUrl(input)
567
+ : input
568
+
537
569
  const xrpcAgent = buildAgent({
538
570
  service,
539
571
  fetch: options.fetch,
@@ -604,3 +636,24 @@ function fetchUrl(sessionData: SessionData, path: string): URL {
604
636
  const pdsUrl = extractPdsUrl(sessionData.didDoc)
605
637
  return new URL(path, pdsUrl ?? sessionData.service)
606
638
  }
639
+
640
+ function parseLoginUrl(input: string | URL): LoginOptions {
641
+ const url = typeof input === 'string' ? new URL(input) : input
642
+ if (url.pathname !== '/') {
643
+ throw new TypeError('Invalid login URL: unexpected pathname')
644
+ }
645
+ if (url.hash) {
646
+ throw new TypeError('Invalid login URL: unexpected hash')
647
+ }
648
+ if (url.search) {
649
+ throw new TypeError('Invalid login URL: unexpected search parameters')
650
+ }
651
+ if (!url.username || !url.password) {
652
+ throw new TypeError('Invalid login URL: missing identifier or password')
653
+ }
654
+ return {
655
+ service: url.origin,
656
+ identifier: url.username,
657
+ password: url.password,
658
+ }
659
+ }