@atproto/lex-password-session 0.0.6 → 0.0.8

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,24 @@
1
1
  # @atproto/lex-password-session
2
2
 
3
+ ## 0.0.8
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [[`52834ab`](https://github.com/bluesky-social/atproto/commit/52834aba182da8df3611fd9dff924e6c6a3973a7), [`f7c2610`](https://github.com/bluesky-social/atproto/commit/f7c26103a6d4e24e5bedbb6fd908be140420e0dd), [`52834ab`](https://github.com/bluesky-social/atproto/commit/52834aba182da8df3611fd9dff924e6c6a3973a7), [`52834ab`](https://github.com/bluesky-social/atproto/commit/52834aba182da8df3611fd9dff924e6c6a3973a7), [`52834ab`](https://github.com/bluesky-social/atproto/commit/52834aba182da8df3611fd9dff924e6c6a3973a7), [`52834ab`](https://github.com/bluesky-social/atproto/commit/52834aba182da8df3611fd9dff924e6c6a3973a7), [`52834ab`](https://github.com/bluesky-social/atproto/commit/52834aba182da8df3611fd9dff924e6c6a3973a7), [`52834ab`](https://github.com/bluesky-social/atproto/commit/52834aba182da8df3611fd9dff924e6c6a3973a7)]:
8
+ - @atproto/lex-schema@0.0.14
9
+ - @atproto/lex-client@0.0.15
10
+
11
+ ## 0.0.7
12
+
13
+ ### Patch Changes
14
+
15
+ - [#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
16
+
17
+ - [#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
18
+
19
+ - Updated dependencies [[`38852f0`](https://github.com/bluesky-social/atproto/commit/38852f0ddfa9fbce8036233dc6af87614e9ae4b2)]:
20
+ - @atproto/lex-client@0.0.14
21
+
3
22
  ## 0.0.6
4
23
 
5
24
  ### Patch Changes
package/dist/error.d.ts CHANGED
@@ -44,12 +44,5 @@ export declare class LexAuthFactorError extends LexError {
44
44
  * @param cause - The underlying XRPC failure response from the server
45
45
  */
46
46
  constructor(cause: XrpcFailure);
47
- /**
48
- * Converts this error to an HTTP Response.
49
- *
50
- * @returns A 500 Internal Server Error response (2FA errors should not be
51
- * exposed to end users in server contexts)
52
- */
53
- toResponse(): Response;
54
47
  }
55
48
  //# sourceMappingURL=error.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"error.d.ts","sourceRoot":"","sources":["../src/error.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAA;AAE3D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,qBAAa,kBAAmB,SAAQ,QAAQ;IAQlC,QAAQ,CAAC,KAAK,EAAE,WAAW;IAPvC,IAAI,SAAuB;IAE3B;;;;OAIG;gBACkB,KAAK,EAAE,WAAW;IAIvC;;;;;OAKG;IACM,UAAU,IAAI,QAAQ;CAGhC"}
1
+ {"version":3,"file":"error.d.ts","sourceRoot":"","sources":["../src/error.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAA;AAE3D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,qBAAa,kBAAmB,SAAQ,QAAQ;IAQlC,QAAQ,CAAC,KAAK,EAAE,WAAW;IAPvC,IAAI,SAAuB;IAE3B;;;;OAIG;gBACkB,KAAK,EAAE,WAAW;CAGxC"}
package/dist/error.js CHANGED
@@ -50,15 +50,6 @@ class LexAuthFactorError extends lex_client_1.LexError {
50
50
  super(cause.error, cause.message ?? 'Auth factor token required', { cause });
51
51
  this.cause = cause;
52
52
  }
53
- /**
54
- * Converts this error to an HTTP Response.
55
- *
56
- * @returns A 500 Internal Server Error response (2FA errors should not be
57
- * exposed to end users in server contexts)
58
- */
59
- toResponse() {
60
- return Response.json({ error: 'InternalServerError' }, { status: 500 });
61
- }
62
53
  }
63
54
  exports.LexAuthFactorError = LexAuthFactorError;
64
55
  //# sourceMappingURL=error.js.map
package/dist/error.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"error.js","sourceRoot":"","sources":["../src/error.ts"],"names":[],"mappings":";;;AAAA,oDAA2D;AAE3D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,MAAa,kBAAmB,SAAQ,qBAAQ;IAQzB;IAPrB,IAAI,GAAG,oBAAoB,CAAA;IAE3B;;;;OAIG;IACH,YAAqB,KAAkB;QACrC,KAAK,CAAC,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,OAAO,IAAI,4BAA4B,EAAE,EAAE,KAAK,EAAE,CAAC,CAAA;QADzD,UAAK,GAAL,KAAK,CAAa;IAEvC,CAAC;IAED;;;;;OAKG;IACM,UAAU;QACjB,OAAO,QAAQ,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,qBAAqB,EAAE,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,CAAA;IACzE,CAAC;CACF;AArBD,gDAqBC","sourcesContent":["import { LexError, XrpcFailure } from '@atproto/lex-client'\n\n/**\n * Error thrown when two-factor authentication (2FA) is required.\n *\n * This error is thrown by {@link PasswordSession.login} when the server\n * requires an additional authentication factor (e.g., email code). Catch this\n * error to prompt the user for their 2FA code and retry the login with the\n * `authFactorToken` parameter.\n *\n * @example Handling 2FA requirement\n * ```ts\n * import { PasswordSession, LexAuthFactorError } from '@atproto/lex-password-session'\n *\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 * // Prompt user for 2FA code\n * const token = await promptUser('Enter 2FA code from email:')\n *\n * // Retry with the 2FA token\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 * @extends LexError\n */\nexport class LexAuthFactorError extends LexError {\n name = 'LexAuthFactorError'\n\n /**\n * Creates a new LexAuthFactorError.\n *\n * @param cause - The underlying XRPC failure response from the server\n */\n constructor(readonly cause: XrpcFailure) {\n super(cause.error, cause.message ?? 'Auth factor token required', { cause })\n }\n\n /**\n * Converts this error to an HTTP Response.\n *\n * @returns A 500 Internal Server Error response (2FA errors should not be\n * exposed to end users in server contexts)\n */\n override toResponse(): Response {\n return Response.json({ error: 'InternalServerError' }, { status: 500 })\n }\n}\n"]}
1
+ {"version":3,"file":"error.js","sourceRoot":"","sources":["../src/error.ts"],"names":[],"mappings":";;;AAAA,oDAA2D;AAE3D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,MAAa,kBAAmB,SAAQ,qBAAQ;IAQzB;IAPrB,IAAI,GAAG,oBAAoB,CAAA;IAE3B;;;;OAIG;IACH,YAAqB,KAAkB;QACrC,KAAK,CAAC,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,OAAO,IAAI,4BAA4B,EAAE,EAAE,KAAK,EAAE,CAAC,CAAA;QADzD,UAAK,GAAL,KAAK,CAAa;IAEvC,CAAC;CACF;AAXD,gDAWC","sourcesContent":["import { LexError, XrpcFailure } from '@atproto/lex-client'\n\n/**\n * Error thrown when two-factor authentication (2FA) is required.\n *\n * This error is thrown by {@link PasswordSession.login} when the server\n * requires an additional authentication factor (e.g., email code). Catch this\n * error to prompt the user for their 2FA code and retry the login with the\n * `authFactorToken` parameter.\n *\n * @example Handling 2FA requirement\n * ```ts\n * import { PasswordSession, LexAuthFactorError } from '@atproto/lex-password-session'\n *\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 * // Prompt user for 2FA code\n * const token = await promptUser('Enter 2FA code from email:')\n *\n * // Retry with the 2FA token\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 * @extends LexError\n */\nexport class LexAuthFactorError extends LexError {\n name = 'LexAuthFactorError'\n\n /**\n * Creates a new LexAuthFactorError.\n *\n * @param cause - The underlying XRPC failure response from the server\n */\n constructor(readonly cause: XrpcFailure) {\n super(cause.error, cause.message ?? 'Auth factor token required', { cause })\n }\n}\n"]}
@@ -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,EAAE,eAAe,EAAE,IAAI,EAAE,WAAW,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IAE9E;;;;;;;OAOG;IACH,eAAe,CAAC,EAAE,CAChB,IAAI,EAAE,eAAe,EACrB,IAAI,EAAE,WAAW,EACjB,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AIjB"}
@@ -180,7 +180,7 @@ class PasswordSession {
180
180
  async refresh() {
181
181
  this.#sessionPromise = this.#sessionPromise.then(async (sessionData) => {
182
182
  const response = await (0, lex_client_1.xrpcSafe)(this.#serviceAgent, index_js_1.com.atproto.server.refreshSession.main, { headers: { Authorization: `Bearer ${sessionData.refreshJwt}` } });
183
- if (!response.success && response.matchesSchema()) {
183
+ if (!response.success && response.matchesSchemaErrors()) {
184
184
  // Expected errors that indicate the session is no longer valid
185
185
  await this.options.onDeleted?.call(this, sessionData);
186
186
  // Update the session promise to a rejected state
@@ -188,10 +188,6 @@ class PasswordSession {
188
188
  throw response;
189
189
  }
190
190
  if (!response.success) {
191
- response.error;
192
- if (response.matchesSchema()) {
193
- response.error;
194
- }
195
191
  // We failed to refresh the token, assume the session might still be
196
192
  // valid by returning the existing session.
197
193
  await this.options.onUpdateFailure?.call(this, sessionData, response);
@@ -237,7 +233,7 @@ class PasswordSession {
237
233
  let reason = null;
238
234
  this.#sessionPromise = this.#sessionPromise.then(async (sessionData) => {
239
235
  const result = await (0, lex_client_1.xrpcSafe)(this.#serviceAgent, index_js_1.com.atproto.server.deleteSession.main, { headers: { Authorization: `Bearer ${sessionData.refreshJwt}` } });
240
- if (result.success || result.matchesSchema()) {
236
+ if (result.success || result.matchesSchemaErrors()) {
241
237
  await this.options.onDeleted?.call(this, sessionData);
242
238
  // Update the session promise to a rejected state
243
239
  this.#sessionData = null;
@@ -260,6 +256,9 @@ class PasswordSession {
260
256
  // Successful logout
261
257
  });
262
258
  }
259
+ async [Symbol.asyncDispose]() {
260
+ await this.logout();
261
+ }
263
262
  /**
264
263
  * Creates a new account and returns an authenticated session.
265
264
  *
@@ -317,23 +316,42 @@ class PasswordSession {
317
316
  * @throws {LexAuthFactorError} If the server requires a 2FA token
318
317
  * @throws If authentication fails (invalid credentials, etc.)
319
318
  *
320
- * @example Basic login with app password
319
+ * **Basic login with app password in script**
320
+ * @example
321
+ * ```ts
322
+ * // .env
323
+ * // APP_PASSWORD_CREDENTIALS="https://<handle>:<app-password>@<pds-hosting-provider>"
324
+ *
325
+ * // Make sure to dispose (or logout) the session when done to avoid leaking
326
+ * // resources and leaving orphaned sessions on the server
327
+ * await using session = await PasswordSession.login(process.env.APP_PASSWORD_CREDENTIALS)
328
+ *
329
+ * // Use session to make authenticated requests
330
+ * ```
331
+ *
332
+ * **Basic login with user password (not recommended!!!)**
333
+ * @example
321
334
  * ```ts
322
335
  * const session = await PasswordSession.login({
323
336
  * service: 'https://bsky.social',
324
337
  * identifier: 'alice.bsky.social',
325
- * password: 'xxxx-xxxx-xxxx-xxxx', // App password
338
+ * password: 'xxxx',
326
339
  * onUpdated: (data) => saveToStorage(data),
340
+ * onDeleted: (data) => clearStorage(data.did),
327
341
  * })
342
+ *
343
+ * // Next time, use resume with the persisted session data to avoid storing
344
+ * // user credentials.
328
345
  * ```
329
346
  *
330
- * @example Handling 2FA requirement
347
+ * **Handling 2FA requirement**
348
+ * @example
331
349
  * ```ts
332
350
  * try {
333
351
  * const session = await PasswordSession.login({
334
352
  * service: 'https://bsky.social',
335
353
  * identifier: 'alice.bsky.social',
336
- * password: 'xxxx-xxxx-xxxx-xxxx',
354
+ * password: 'xxxx',
337
355
  * })
338
356
  * } catch (err) {
339
357
  * if (err instanceof LexAuthFactorError) {
@@ -341,14 +359,17 @@ class PasswordSession {
341
359
  * const session = await PasswordSession.login({
342
360
  * service: 'https://bsky.social',
343
361
  * identifier: 'alice.bsky.social',
344
- * password: 'xxxx-xxxx-xxxx-xxxx',
362
+ * password: 'xxxx',
345
363
  * authFactorToken: token,
346
364
  * })
347
365
  * }
348
366
  * }
349
367
  * ```
350
368
  */
351
- static async login({ service, identifier, password, allowTakendown, authFactorToken, ...options }) {
369
+ static async login(input) {
370
+ const { service, identifier, password, allowTakendown, authFactorToken, ...options } = typeof input === 'string' || input instanceof URL
371
+ ? parseLoginUrl(input)
372
+ : input;
352
373
  const xrpcAgent = (0, lex_client_1.buildAgent)({
353
374
  service,
354
375
  fetch: options.fetch,
@@ -403,4 +424,24 @@ function fetchUrl(sessionData, path) {
403
424
  const pdsUrl = (0, util_js_1.extractPdsUrl)(sessionData.didDoc);
404
425
  return new URL(path, pdsUrl ?? sessionData.service);
405
426
  }
427
+ function parseLoginUrl(input) {
428
+ const url = typeof input === 'string' ? new URL(input) : input;
429
+ if (url.pathname !== '/') {
430
+ throw new TypeError('Invalid login URL: unexpected pathname');
431
+ }
432
+ if (url.hash) {
433
+ throw new TypeError('Invalid login URL: unexpected hash');
434
+ }
435
+ if (url.search) {
436
+ throw new TypeError('Invalid login URL: unexpected search parameters');
437
+ }
438
+ if (!url.username || !url.password) {
439
+ throw new TypeError('Invalid login URL: missing identifier or password');
440
+ }
441
+ return {
442
+ service: url.origin,
443
+ identifier: url.username,
444
+ password: url.password,
445
+ };
446
+ }
406
447
  //# 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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,I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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,C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AI,GAAG,CAAC,QAAQ,KAAK,GAAG,EAAE,CAAC;QACzB,MAAM,IAAI,SAAS,CAAC,wCAAwC,CAAC,CAAA;IAC/D,CAAC;IACD,IAAI,GAAG,CAAC,IAAI,EAAE,CAAC;QACb,MAAM,IAAI,SAAS,CAAC,oCAAoC,CAAC,CAAA;IAC3D,CAAC;IACD,IAAI,GAAG,CAAC,MAAM,EAAE,CAAC;QACf,MAAM,IAAI,SAAS,CAAC,iDAAiD,CAAC,CAAA;IACxE,CAAC;IACD,IAAI,CAAC,GAAG,CAAC,QAAQ,IAAI,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC;QACnC,MAAM,IAAI,SAAS,CAAC,mDAAmD,CAAC,CAAA;IAC1E,CAAC;IACD,OAAO;QACL,OAAO,EAAE,GAAG,CAAC,MAAM;QACnB,UAAU,EAAE,GAAG,CAAC,QAAQ;QACxB,QAAQ,EAAE,GAAG,CAAC,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.matchesSchemaErrors()) {\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 // 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.matchesSchemaErrors()) {\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.8",
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.15",
40
+ "@atproto/lex-schema": "^0.0.14"
41
41
  },
42
42
  "devDependencies": {
43
43
  "vitest": "^4.0.16",
44
- "@atproto/lex-builder": "^0.0.16",
45
- "@atproto/lex-server": "^0.0.10"
44
+ "@atproto/lex-builder": "^0.0.17",
45
+ "@atproto/lex-server": "^0.0.12"
46
46
  },
47
47
  "scripts": {
48
48
  "prebuild": "node ./scripts/lex-build.mjs",
package/src/error.ts CHANGED
@@ -47,14 +47,4 @@ export class LexAuthFactorError extends LexError {
47
47
  constructor(readonly cause: XrpcFailure) {
48
48
  super(cause.error, cause.message ?? 'Auth factor token required', { cause })
49
49
  }
50
-
51
- /**
52
- * Converts this error to an HTTP Response.
53
- *
54
- * @returns A 500 Internal Server Error response (2FA errors should not be
55
- * exposed to end users in server contexts)
56
- */
57
- override toResponse(): Response {
58
- return Response.json({ error: 'InternalServerError' }, { status: 500 })
59
- }
60
50
  }
@@ -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.
@@ -308,7 +316,7 @@ export class PasswordSession implements Agent {
308
316
  { headers: { Authorization: `Bearer ${sessionData.refreshJwt}` } },
309
317
  )
310
318
 
311
- if (!response.success && response.matchesSchema()) {
319
+ if (!response.success && response.matchesSchemaErrors()) {
312
320
  // Expected errors that indicate the session is no longer valid
313
321
  await this.options.onDeleted?.call(this, sessionData)
314
322
 
@@ -318,10 +326,6 @@ export class PasswordSession implements Agent {
318
326
  }
319
327
 
320
328
  if (!response.success) {
321
- response.error
322
- if (response.matchesSchema()) {
323
- response.error
324
- }
325
329
  // We failed to refresh the token, assume the session might still be
326
330
  // valid by returning the existing session.
327
331
  await this.options.onUpdateFailure?.call(this, sessionData, response)
@@ -385,7 +389,7 @@ export class PasswordSession implements Agent {
385
389
  { headers: { Authorization: `Bearer ${sessionData.refreshJwt}` } },
386
390
  )
387
391
 
388
- if (result.success || result.matchesSchema()) {
392
+ if (result.success || result.matchesSchemaErrors()) {
389
393
  await this.options.onDeleted?.call(this, sessionData)
390
394
 
391
395
  // Update the session promise to a rejected state
@@ -415,6 +419,10 @@ export class PasswordSession implements Agent {
415
419
  )
416
420
  }
417
421
 
422
+ async [Symbol.asyncDispose]() {
423
+ await this.logout()
424
+ }
425
+
418
426
  /**
419
427
  * Creates a new account and returns an authenticated session.
420
428
  *
@@ -489,23 +497,42 @@ export class PasswordSession implements Agent {
489
497
  * @throws {LexAuthFactorError} If the server requires a 2FA token
490
498
  * @throws If authentication fails (invalid credentials, etc.)
491
499
  *
492
- * @example Basic login with app password
500
+ * **Basic login with app password in script**
501
+ * @example
502
+ * ```ts
503
+ * // .env
504
+ * // APP_PASSWORD_CREDENTIALS="https://<handle>:<app-password>@<pds-hosting-provider>"
505
+ *
506
+ * // Make sure to dispose (or logout) the session when done to avoid leaking
507
+ * // resources and leaving orphaned sessions on the server
508
+ * await using session = await PasswordSession.login(process.env.APP_PASSWORD_CREDENTIALS)
509
+ *
510
+ * // Use session to make authenticated requests
511
+ * ```
512
+ *
513
+ * **Basic login with user password (not recommended!!!)**
514
+ * @example
493
515
  * ```ts
494
516
  * const session = await PasswordSession.login({
495
517
  * service: 'https://bsky.social',
496
518
  * identifier: 'alice.bsky.social',
497
- * password: 'xxxx-xxxx-xxxx-xxxx', // App password
519
+ * password: 'xxxx',
498
520
  * onUpdated: (data) => saveToStorage(data),
521
+ * onDeleted: (data) => clearStorage(data.did),
499
522
  * })
523
+ *
524
+ * // Next time, use resume with the persisted session data to avoid storing
525
+ * // user credentials.
500
526
  * ```
501
527
  *
502
- * @example Handling 2FA requirement
528
+ * **Handling 2FA requirement**
529
+ * @example
503
530
  * ```ts
504
531
  * try {
505
532
  * const session = await PasswordSession.login({
506
533
  * service: 'https://bsky.social',
507
534
  * identifier: 'alice.bsky.social',
508
- * password: 'xxxx-xxxx-xxxx-xxxx',
535
+ * password: 'xxxx',
509
536
  * })
510
537
  * } catch (err) {
511
538
  * if (err instanceof LexAuthFactorError) {
@@ -513,27 +540,28 @@ export class PasswordSession implements Agent {
513
540
  * const session = await PasswordSession.login({
514
541
  * service: 'https://bsky.social',
515
542
  * identifier: 'alice.bsky.social',
516
- * password: 'xxxx-xxxx-xxxx-xxxx',
543
+ * password: 'xxxx',
517
544
  * authFactorToken: token,
518
545
  * })
519
546
  * }
520
547
  * }
521
548
  * ```
522
549
  */
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> {
550
+ static async login(
551
+ input: string | URL | LoginOptions,
552
+ ): Promise<PasswordSession> {
553
+ const {
554
+ service,
555
+ identifier,
556
+ password,
557
+ allowTakendown,
558
+ authFactorToken,
559
+ ...options
560
+ } =
561
+ typeof input === 'string' || input instanceof URL
562
+ ? parseLoginUrl(input)
563
+ : input
564
+
537
565
  const xrpcAgent = buildAgent({
538
566
  service,
539
567
  fetch: options.fetch,
@@ -604,3 +632,24 @@ function fetchUrl(sessionData: SessionData, path: string): URL {
604
632
  const pdsUrl = extractPdsUrl(sessionData.didDoc)
605
633
  return new URL(path, pdsUrl ?? sessionData.service)
606
634
  }
635
+
636
+ function parseLoginUrl(input: string | URL): LoginOptions {
637
+ const url = typeof input === 'string' ? new URL(input) : input
638
+ if (url.pathname !== '/') {
639
+ throw new TypeError('Invalid login URL: unexpected pathname')
640
+ }
641
+ if (url.hash) {
642
+ throw new TypeError('Invalid login URL: unexpected hash')
643
+ }
644
+ if (url.search) {
645
+ throw new TypeError('Invalid login URL: unexpected search parameters')
646
+ }
647
+ if (!url.username || !url.password) {
648
+ throw new TypeError('Invalid login URL: missing identifier or password')
649
+ }
650
+ return {
651
+ service: url.origin,
652
+ identifier: url.username,
653
+ password: url.password,
654
+ }
655
+ }