@atproto/lex-password-session 0.0.3 → 0.0.5
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 +26 -0
- package/README.md +187 -167
- package/dist/error.d.ts +51 -4
- package/dist/error.d.ts.map +1 -1
- package/dist/error.js +54 -4
- package/dist/error.js.map +1 -1
- package/dist/lexicons/com/atproto/server/createAccount.defs.d.ts +28 -28
- package/dist/lexicons/com/atproto/server/createSession.defs.d.ts +28 -28
- package/dist/lexicons/com/atproto/server/getSession.defs.d.ts +16 -16
- package/dist/lexicons/com/atproto/server/refreshSession.defs.d.ts +20 -20
- package/dist/password-session.d.ts +199 -20
- package/dist/password-session.d.ts.map +1 -1
- package/dist/password-session.js +192 -28
- package/dist/password-session.js.map +1 -1
- package/dist/util.d.ts +0 -1
- package/dist/util.d.ts.map +1 -1
- package/dist/util.js +1 -4
- package/dist/util.js.map +1 -1
- package/package.json +6 -6
- package/src/error.ts +54 -8
- package/src/password-session.test.ts +17 -16
- package/src/password-session.ts +236 -34
- package/src/util.ts +2 -4
package/dist/password-session.js
CHANGED
|
@@ -5,6 +5,44 @@ const lex_client_1 = require("@atproto/lex-client");
|
|
|
5
5
|
const error_js_1 = require("./error.js");
|
|
6
6
|
const index_js_1 = require("./lexicons/index.js");
|
|
7
7
|
const util_js_1 = require("./util.js");
|
|
8
|
+
/**
|
|
9
|
+
* Password-based authentication session for AT Protocol services.
|
|
10
|
+
*
|
|
11
|
+
* This class provides session management for CLI tools, scripts, and bots that
|
|
12
|
+
* need to authenticate with AT Protocol services using password credentials.
|
|
13
|
+
* It implements the {@link Agent} interface, allowing it to be used directly
|
|
14
|
+
* with AT Protocol clients.
|
|
15
|
+
*
|
|
16
|
+
* **Security Warning:** It is strongly recommended to use app passwords instead
|
|
17
|
+
* of main account credentials. App passwords provide limited access and can be
|
|
18
|
+
* revoked independently without compromising your main account. For browser-based
|
|
19
|
+
* applications, use OAuth-based authentication instead.
|
|
20
|
+
*
|
|
21
|
+
* @example Basic usage with app password
|
|
22
|
+
* ```ts
|
|
23
|
+
* const session = await PasswordSession.login({
|
|
24
|
+
* service: 'https://bsky.social',
|
|
25
|
+
* identifier: 'alice.bsky.social',
|
|
26
|
+
* password: 'xxxx-xxxx-xxxx-xxxx', // App password
|
|
27
|
+
* onUpdated: (data) => saveToStorage(data),
|
|
28
|
+
* onDeleted: (data) => clearStorage(data.did),
|
|
29
|
+
* })
|
|
30
|
+
*
|
|
31
|
+
* const client = new Client(session)
|
|
32
|
+
* // Use client to make authenticated requests
|
|
33
|
+
* ```
|
|
34
|
+
*
|
|
35
|
+
* @example Resuming a persisted session
|
|
36
|
+
* ```ts
|
|
37
|
+
* const savedData = JSON.parse(fs.readFileSync('session.json', 'utf8'))
|
|
38
|
+
* const session = await PasswordSession.resume(savedData, {
|
|
39
|
+
* onUpdated: (data) => saveToStorage(data),
|
|
40
|
+
* onDeleted: (data) => clearStorage(data.did),
|
|
41
|
+
* })
|
|
42
|
+
* ```
|
|
43
|
+
*
|
|
44
|
+
* @implements {Agent}
|
|
45
|
+
*/
|
|
8
46
|
class PasswordSession {
|
|
9
47
|
options;
|
|
10
48
|
/**
|
|
@@ -14,7 +52,7 @@ class PasswordSession {
|
|
|
14
52
|
#serviceAgent;
|
|
15
53
|
#sessionData;
|
|
16
54
|
#sessionPromise;
|
|
17
|
-
constructor(sessionData, options) {
|
|
55
|
+
constructor(sessionData, options = {}) {
|
|
18
56
|
this.options = options;
|
|
19
57
|
this.#serviceAgent = (0, lex_client_1.buildAgent)({
|
|
20
58
|
service: sessionData.service,
|
|
@@ -23,20 +61,56 @@ class PasswordSession {
|
|
|
23
61
|
this.#sessionData = sessionData;
|
|
24
62
|
this.#sessionPromise = Promise.resolve(this.#sessionData);
|
|
25
63
|
}
|
|
64
|
+
/**
|
|
65
|
+
* The DID (Decentralized Identifier) of the authenticated account.
|
|
66
|
+
*
|
|
67
|
+
* @throws {Error} If the session has been destroyed (logged out).
|
|
68
|
+
*/
|
|
26
69
|
get did() {
|
|
27
70
|
return this.session.did;
|
|
28
71
|
}
|
|
72
|
+
/**
|
|
73
|
+
* The handle (username) of the authenticated account.
|
|
74
|
+
*
|
|
75
|
+
* @throws {Error} If the session has been destroyed (logged out).
|
|
76
|
+
*/
|
|
29
77
|
get handle() {
|
|
30
78
|
return this.session.handle;
|
|
31
79
|
}
|
|
80
|
+
/**
|
|
81
|
+
* The current session data containing authentication credentials.
|
|
82
|
+
*
|
|
83
|
+
* @throws {Error} If the session has been destroyed (logged out).
|
|
84
|
+
*/
|
|
32
85
|
get session() {
|
|
33
86
|
if (this.#sessionData)
|
|
34
87
|
return this.#sessionData;
|
|
35
|
-
throw new
|
|
88
|
+
throw new Error('Logged out');
|
|
36
89
|
}
|
|
90
|
+
/**
|
|
91
|
+
* Whether this session has been destroyed (logged out).
|
|
92
|
+
*
|
|
93
|
+
* Once destroyed, this session instance can no longer be used for
|
|
94
|
+
* authenticated requests. Create a new session via {@link PasswordSession.login}
|
|
95
|
+
* or {@link PasswordSession.resume}.
|
|
96
|
+
*/
|
|
37
97
|
get destroyed() {
|
|
38
98
|
return this.#sessionData === null;
|
|
39
99
|
}
|
|
100
|
+
/**
|
|
101
|
+
* Handles authenticated fetch requests to the user's PDS.
|
|
102
|
+
*
|
|
103
|
+
* This method implements the {@link Agent} interface and is called by
|
|
104
|
+
* AT Protocol clients to make authenticated requests. It automatically:
|
|
105
|
+
* - Adds the access token to request headers
|
|
106
|
+
* - Detects expired tokens and triggers refresh
|
|
107
|
+
* - Retries requests after successful token refresh
|
|
108
|
+
*
|
|
109
|
+
* @param path - The request path (will be resolved against the PDS URL)
|
|
110
|
+
* @param init - Standard fetch RequestInit options (headers, body, etc.)
|
|
111
|
+
* @returns The fetch Response from the PDS
|
|
112
|
+
* @throws {TypeError} If an 'authorization' header is already set in init
|
|
113
|
+
*/
|
|
40
114
|
async fetchHandler(path, init) {
|
|
41
115
|
const headers = new Headers(init.headers);
|
|
42
116
|
if (headers.has('authorization')) {
|
|
@@ -88,17 +162,36 @@ class PasswordSession {
|
|
|
88
162
|
headers.set('authorization', `Bearer ${newSessionData.accessJwt}`);
|
|
89
163
|
return fetch(fetchUrl(newSessionData, path), { ...init, headers });
|
|
90
164
|
}
|
|
165
|
+
/**
|
|
166
|
+
* Refreshes the session by obtaining new access and refresh tokens.
|
|
167
|
+
*
|
|
168
|
+
* This method is automatically called by {@link fetchHandler} when the access
|
|
169
|
+
* token expires. You can also call it manually to proactively refresh tokens.
|
|
170
|
+
*
|
|
171
|
+
* On success, the {@link PasswordSessionOptions.onUpdated} callback is invoked
|
|
172
|
+
* with the new session data. On expected failures (invalid session), the
|
|
173
|
+
* {@link PasswordSessionOptions.onDeleted} callback is invoked. On unexpected
|
|
174
|
+
* failures (network issues), the {@link PasswordSessionOptions.onUpdateFailure}
|
|
175
|
+
* callback is invoked and the existing session data is preserved.
|
|
176
|
+
*
|
|
177
|
+
* @returns The refreshed session data
|
|
178
|
+
* @throws {RefreshFailure} If the session is no longer valid (triggers onDeleted)
|
|
179
|
+
*/
|
|
91
180
|
async refresh() {
|
|
92
181
|
this.#sessionPromise = this.#sessionPromise.then(async (sessionData) => {
|
|
93
182
|
const response = await (0, lex_client_1.xrpcSafe)(this.#serviceAgent, index_js_1.com.atproto.server.refreshSession.main, { headers: { Authorization: `Bearer ${sessionData.refreshJwt}` } });
|
|
94
183
|
if (!response.success && response.matchesSchema()) {
|
|
95
184
|
// Expected errors that indicate the session is no longer valid
|
|
96
|
-
await this.options.onDeleted
|
|
185
|
+
await this.options.onDeleted?.call(this, sessionData);
|
|
97
186
|
// Update the session promise to a rejected state
|
|
98
187
|
this.#sessionData = null;
|
|
99
188
|
throw response;
|
|
100
189
|
}
|
|
101
190
|
if (!response.success) {
|
|
191
|
+
response.error;
|
|
192
|
+
if (response.matchesSchema()) {
|
|
193
|
+
response.error;
|
|
194
|
+
}
|
|
102
195
|
// We failed to refresh the token, assume the session might still be
|
|
103
196
|
// valid by returning the existing session.
|
|
104
197
|
await this.options.onUpdateFailure?.call(this, sessionData, response);
|
|
@@ -120,20 +213,35 @@ class PasswordSession {
|
|
|
120
213
|
...data,
|
|
121
214
|
service: sessionData.service,
|
|
122
215
|
};
|
|
123
|
-
await this.options.onUpdated
|
|
216
|
+
await this.options.onUpdated?.call(this, newSession);
|
|
124
217
|
return (this.#sessionData = newSession);
|
|
125
218
|
});
|
|
126
219
|
return this.#sessionPromise;
|
|
127
220
|
}
|
|
221
|
+
/**
|
|
222
|
+
* Logs out by deleting the session on the server.
|
|
223
|
+
*
|
|
224
|
+
* This method invalidates both the access and refresh tokens on the server,
|
|
225
|
+
* preventing any further use of this session. After successful logout, the
|
|
226
|
+
* session is marked as destroyed and the {@link PasswordSessionOptions.onDeleted}
|
|
227
|
+
* callback is invoked.
|
|
228
|
+
*
|
|
229
|
+
* If the logout request fails due to network issues or server unavailability,
|
|
230
|
+
* the {@link PasswordSessionOptions.onDeleteFailure} callback is invoked and
|
|
231
|
+
* the session remains active locally. In this case, you should retry the
|
|
232
|
+
* logout later to ensure the session is properly invalidated on the server.
|
|
233
|
+
*
|
|
234
|
+
* @throws {DeleteFailure} If the logout request fails due to unexpected errors
|
|
235
|
+
*/
|
|
128
236
|
async logout() {
|
|
129
237
|
let reason = null;
|
|
130
238
|
this.#sessionPromise = this.#sessionPromise.then(async (sessionData) => {
|
|
131
239
|
const result = await (0, lex_client_1.xrpcSafe)(this.#serviceAgent, index_js_1.com.atproto.server.deleteSession.main, { headers: { Authorization: `Bearer ${sessionData.refreshJwt}` } });
|
|
132
240
|
if (result.success || result.matchesSchema()) {
|
|
133
|
-
await this.options.onDeleted
|
|
241
|
+
await this.options.onDeleted?.call(this, sessionData);
|
|
134
242
|
// Update the session promise to a rejected state
|
|
135
243
|
this.#sessionData = null;
|
|
136
|
-
throw new
|
|
244
|
+
throw new Error('Logged out');
|
|
137
245
|
}
|
|
138
246
|
else {
|
|
139
247
|
// Capture the reason for the failure to re-throw in the outer promise
|
|
@@ -153,34 +261,94 @@ class PasswordSession {
|
|
|
153
261
|
});
|
|
154
262
|
}
|
|
155
263
|
/**
|
|
156
|
-
*
|
|
157
|
-
* account credentials. Instead, it is strongly advised to use OAuth based
|
|
158
|
-
* authentication for main username/password credentials and use
|
|
159
|
-
* {@link PasswordSession} with an app-password, for bots, scripts, or similar
|
|
160
|
-
* use-cases.
|
|
264
|
+
* Creates a new account and returns an authenticated session.
|
|
161
265
|
*
|
|
162
|
-
*
|
|
163
|
-
*
|
|
164
|
-
* `AuthFactorTokenRequired` error code will be thrown.
|
|
266
|
+
* This static method registers a new account on the specified service and
|
|
267
|
+
* automatically creates an authenticated session for it.
|
|
165
268
|
*
|
|
269
|
+
* @param body - Account creation parameters (handle, email, password, etc.)
|
|
270
|
+
* @param options - Session options including the service URL
|
|
271
|
+
* @returns A new PasswordSession for the created account
|
|
272
|
+
* @throws If account creation fails (e.g., handle taken, invalid invite code)
|
|
166
273
|
*
|
|
167
|
-
* @example
|
|
274
|
+
* @example
|
|
275
|
+
* ```ts
|
|
276
|
+
* const session = await PasswordSession.createAccount(
|
|
277
|
+
* {
|
|
278
|
+
* handle: 'alice.bsky.social',
|
|
279
|
+
* email: 'alice@example.com',
|
|
280
|
+
* password: 'secure-password',
|
|
281
|
+
* },
|
|
282
|
+
* {
|
|
283
|
+
* service: 'https://bsky.social',
|
|
284
|
+
* onUpdated: (data) => saveToStorage(data),
|
|
285
|
+
* }
|
|
286
|
+
* )
|
|
287
|
+
* ```
|
|
288
|
+
*/
|
|
289
|
+
static async createAccount(body, { service, headers, ...options }) {
|
|
290
|
+
const response = await (0, lex_client_1.xrpc)((0, lex_client_1.buildAgent)({ service, headers, fetch: options.fetch }), index_js_1.com.atproto.server.createAccount.main, { body });
|
|
291
|
+
const data = {
|
|
292
|
+
...response.body,
|
|
293
|
+
service: String(service),
|
|
294
|
+
};
|
|
295
|
+
const agent = new PasswordSession(data, options);
|
|
296
|
+
await options.onUpdated?.call(agent, data);
|
|
297
|
+
return agent;
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* Creates a new authenticated session using password credentials.
|
|
301
|
+
*
|
|
302
|
+
* This static method authenticates with the specified service and returns
|
|
303
|
+
* a new PasswordSession instance that can be used for authenticated requests.
|
|
304
|
+
*
|
|
305
|
+
* **Security Warning:** It is strongly recommended to use app passwords instead
|
|
306
|
+
* of main account credentials. App passwords can be created in your account
|
|
307
|
+
* settings and provide limited access that can be revoked independently. For
|
|
308
|
+
* browser-based applications, use OAuth-based authentication instead.
|
|
309
|
+
*
|
|
310
|
+
* @param options - Login options including service URL, identifier, and password
|
|
311
|
+
* @param options.service - The AT Protocol service URL (e.g., 'https://bsky.social')
|
|
312
|
+
* @param options.identifier - The user's handle or DID
|
|
313
|
+
* @param options.password - The user's password or app password
|
|
314
|
+
* @param options.allowTakendown - If true, allow login to takendown accounts
|
|
315
|
+
* @param options.authFactorToken - 2FA token if required by the server
|
|
316
|
+
* @returns A new authenticated PasswordSession
|
|
317
|
+
* @throws {LexAuthFactorError} If the server requires a 2FA token
|
|
318
|
+
* @throws If authentication fails (invalid credentials, etc.)
|
|
168
319
|
*
|
|
320
|
+
* @example Basic login with app password
|
|
321
|
+
* ```ts
|
|
322
|
+
* const session = await PasswordSession.login({
|
|
323
|
+
* service: 'https://bsky.social',
|
|
324
|
+
* identifier: 'alice.bsky.social',
|
|
325
|
+
* password: 'xxxx-xxxx-xxxx-xxxx', // App password
|
|
326
|
+
* onUpdated: (data) => saveToStorage(data),
|
|
327
|
+
* })
|
|
328
|
+
* ```
|
|
329
|
+
*
|
|
330
|
+
* @example Handling 2FA requirement
|
|
169
331
|
* ```ts
|
|
170
332
|
* try {
|
|
171
|
-
* const session = await PasswordSession.
|
|
172
|
-
* service: 'https://
|
|
173
|
-
* identifier: 'alice',
|
|
174
|
-
* password: '
|
|
333
|
+
* const session = await PasswordSession.login({
|
|
334
|
+
* service: 'https://bsky.social',
|
|
335
|
+
* identifier: 'alice.bsky.social',
|
|
336
|
+
* password: 'xxxx-xxxx-xxxx-xxxx',
|
|
175
337
|
* })
|
|
176
338
|
* } catch (err) {
|
|
177
|
-
* if (err instanceof
|
|
178
|
-
*
|
|
339
|
+
* if (err instanceof LexAuthFactorError) {
|
|
340
|
+
* const token = await promptUser('Enter 2FA code:')
|
|
341
|
+
* const session = await PasswordSession.login({
|
|
342
|
+
* service: 'https://bsky.social',
|
|
343
|
+
* identifier: 'alice.bsky.social',
|
|
344
|
+
* password: 'xxxx-xxxx-xxxx-xxxx',
|
|
345
|
+
* authFactorToken: token,
|
|
346
|
+
* })
|
|
179
347
|
* }
|
|
180
348
|
* }
|
|
181
349
|
* ```
|
|
182
350
|
*/
|
|
183
|
-
static async
|
|
351
|
+
static async login({ service, identifier, password, allowTakendown, authFactorToken, ...options }) {
|
|
184
352
|
const xrpcAgent = (0, lex_client_1.buildAgent)({
|
|
185
353
|
service,
|
|
186
354
|
fetch: options.fetch,
|
|
@@ -197,7 +365,7 @@ class PasswordSession {
|
|
|
197
365
|
service: String(service),
|
|
198
366
|
};
|
|
199
367
|
const agent = new PasswordSession(data, options);
|
|
200
|
-
await options.onUpdated
|
|
368
|
+
await options.onUpdated?.call(agent, data);
|
|
201
369
|
return agent;
|
|
202
370
|
}
|
|
203
371
|
/**
|
|
@@ -226,11 +394,7 @@ class PasswordSession {
|
|
|
226
394
|
* meaning that the session may still be valid.
|
|
227
395
|
*/
|
|
228
396
|
static async delete(data, options) {
|
|
229
|
-
const agent = new PasswordSession(data,
|
|
230
|
-
...options,
|
|
231
|
-
onUpdated: options?.onUpdated ?? util_js_1.noop,
|
|
232
|
-
onDeleted: options?.onDeleted ?? util_js_1.noop,
|
|
233
|
-
});
|
|
397
|
+
const agent = new PasswordSession(data, options);
|
|
234
398
|
await agent.logout();
|
|
235
399
|
}
|
|
236
400
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"password-session.js","sourceRoot":"","sources":["../src/password-session.ts"],"names":[],"mappings":";;;AAAA,o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wTC;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 XrpcError,\n XrpcFailure,\n buildAgent,\n xrpcSafe,\n} from '@atproto/lex-client'\nimport { LexAuthFactorError } from './error.js'\nimport { com } from './lexicons/index.js'\nimport { extractPdsUrl, extractXrpcErrorCode, noop } from './util.js'\n\nexport type RefreshFailure = XrpcFailure<\n typeof com.atproto.server.refreshSession.main\n>\n\nexport type DeleteFailure = XrpcFailure<\n typeof com.atproto.server.deleteSession.main\n>\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\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 get did() {\n return this.session.did\n }\n\n get handle() {\n return this.session.handle\n }\n\n get session() {\n if (this.#sessionData) return this.#sessionData\n throw new XrpcError('AuthenticationRequired', 'Logged out')\n }\n\n get destroyed(): boolean {\n return this.#sessionData === null\n }\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 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 // 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 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 XrpcError('AuthenticationRequired', '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 * @note It is **not** recommended to use {@link PasswordSession} with main\n * account credentials. Instead, it is strongly advised to use OAuth based\n * authentication for main username/password credentials and use\n * {@link PasswordSession} with an app-password, for bots, scripts, or similar\n * use-cases.\n *\n * @throws If unable to create a session. In particular, if the server\n * requires a 2FA token, a {@link XrpcResponseError} with the\n * `AuthFactorTokenRequired` error code will be thrown.\n *\n *\n * @example Handling 2FA errors\n *\n * ```ts\n * try {\n * const session = await PasswordSession.create({\n * service: 'https://example.com',\n * identifier: 'alice',\n * password: 'correct horse battery staple',\n * })\n * } catch (err) {\n * if (err instanceof XrpcResponseError && err.error === 'AuthFactorTokenRequired') {\n * // Prompt user for 2FA token and re-attempt session creation\n * }\n * }\n * ```\n */\n static async create({\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?: Partial<PasswordSessionOptions>,\n ): Promise<void> {\n const agent = new PasswordSession(data, {\n ...options,\n onUpdated: options?.onUpdated ?? noop,\n onDeleted: options?.onDeleted ?? noop,\n })\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,u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AAC,QAAQ,CAAC,CAAA;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"]}
|
package/dist/util.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { LexMap } from '@atproto/lex-client';
|
|
2
|
-
export declare const noop: () => void;
|
|
3
2
|
export declare function extractXrpcErrorCode(response: Response): Promise<string | null>;
|
|
4
3
|
export declare function extractPdsUrl(didDoc?: LexMap): string | null;
|
|
5
4
|
//# sourceMappingURL=util.d.ts.map
|
package/dist/util.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"util.d.ts","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAY,MAAM,qBAAqB,CAAA;AAGtD,
|
|
1
|
+
{"version":3,"file":"util.d.ts","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAY,MAAM,qBAAqB,CAAA;AAGtD,wBAAsB,oBAAoB,CACxC,QAAQ,EAAE,QAAQ,GACjB,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAKxB;AA4BD,wBAAgB,aAAa,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAM5D"}
|
package/dist/util.js
CHANGED
|
@@ -1,16 +1,13 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.noop = void 0;
|
|
4
3
|
exports.extractXrpcErrorCode = extractXrpcErrorCode;
|
|
5
4
|
exports.extractPdsUrl = extractPdsUrl;
|
|
6
5
|
const lex_schema_1 = require("@atproto/lex-schema");
|
|
7
|
-
const noop = () => { };
|
|
8
|
-
exports.noop = noop;
|
|
9
6
|
async function extractXrpcErrorCode(response) {
|
|
10
7
|
const json = await peekJson(response, 10 * 1024); // Avoid reading large bodies
|
|
11
8
|
if (json === undefined)
|
|
12
9
|
return null;
|
|
13
|
-
if (!lex_schema_1.
|
|
10
|
+
if (!lex_schema_1.lexErrorDataSchema.matches(json))
|
|
14
11
|
return null;
|
|
15
12
|
return json.error;
|
|
16
13
|
}
|
package/dist/util.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"util.js","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"util.js","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":";;AAGA,oDAOC;AA4BD,sCAMC;AA3CD,oDAAwD;AAEjD,KAAK,UAAU,oBAAoB,CACxC,QAAkB;IAElB,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,QAAQ,EAAE,EAAE,GAAG,IAAI,CAAC,CAAA,CAAC,6BAA6B;IAC9E,IAAI,IAAI,KAAK,SAAS;QAAE,OAAO,IAAI,CAAA;IACnC,IAAI,CAAC,+BAAkB,CAAC,OAAO,CAAC,IAAI,CAAC;QAAE,OAAO,IAAI,CAAA;IAClD,OAAO,IAAI,CAAC,KAAK,CAAA;AACnB,CAAC;AAED,KAAK,UAAU,QAAQ,CACrB,QAAkB,EAClB,OAAO,GAAG,QAAQ;IAElB,MAAM,IAAI,GAAG,WAAW,CAAC,QAAQ,CAAC,CAAA;IAClC,IAAI,IAAI,KAAK,kBAAkB;QAAE,OAAO,SAAS,CAAA;IACjD,MAAM,MAAM,GAAG,aAAa,CAAC,QAAQ,CAAC,CAAA;IACtC,IAAI,MAAM,IAAI,IAAI,IAAI,MAAM,GAAG,OAAO;QAAE,OAAO,SAAS,CAAA;IAExD,IAAI,CAAC;QACH,OAAO,CAAC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,CAAC,CAAC,SAAS,CAIlB,CAAA","sourcesContent":["import { LexMap, LexValue } from '@atproto/lex-client'\nimport { lexErrorDataSchema } from '@atproto/lex-schema'\n\nexport async function extractXrpcErrorCode(\n response: Response,\n): Promise<string | null> {\n const json = await peekJson(response, 10 * 1024) // Avoid reading large bodies\n if (json === undefined) return null\n if (!lexErrorDataSchema.matches(json)) return null\n return json.error\n}\n\nasync function peekJson(\n response: Response,\n maxSize = Infinity,\n): Promise<undefined | LexValue> {\n const type = extractType(response)\n if (type !== 'application/json') return undefined\n const length = extractLength(response)\n if (length != null && length > maxSize) return undefined\n\n try {\n return (await response.clone().json()) as Promise<LexValue>\n } catch {\n return undefined\n }\n}\n\nfunction extractLength({ headers }: Response) {\n return headers.get('Content-Length')\n ? Number(headers.get('Content-Length'))\n : undefined\n}\n\nfunction extractType({ headers }: Response) {\n return headers.get('Content-Type')?.split(';')[0]?.trim().toLowerCase()\n}\n\nexport function extractPdsUrl(didDoc?: LexMap): string | null {\n const pdsService = ifArray(didDoc?.service)?.find((service) =>\n ifString((service as any)?.id)?.endsWith('#atproto_pds'),\n )\n const pdsEndpoint = ifString((pdsService as any)?.serviceEndpoint)\n return pdsEndpoint && URL.canParse(pdsEndpoint) ? pdsEndpoint : null\n}\n\nconst ifString = <T>(v: T) =>\n (typeof v === 'string' ? v : undefined) as unknown extends T\n ? undefined | string\n : T extends string\n ? string\n : undefined\n\nconst ifArray = <T>(v: T) =>\n (Array.isArray(v) ? v : undefined) as unknown extends T\n ? undefined | unknown[]\n : T extends unknown[]\n ? Extract<T, unknown[]>\n : undefined\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@atproto/lex-password-session",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.5",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"description": "Password based client authentication for AT Lexicons",
|
|
6
6
|
"keywords": [
|
|
@@ -31,18 +31,18 @@
|
|
|
31
31
|
"types": "./dist/index.d.ts",
|
|
32
32
|
"browser": "./dist/index.js",
|
|
33
33
|
"import": "./dist/index.js",
|
|
34
|
-
"
|
|
34
|
+
"default": "./dist/index.js"
|
|
35
35
|
}
|
|
36
36
|
},
|
|
37
37
|
"dependencies": {
|
|
38
38
|
"tslib": "^2.8.1",
|
|
39
|
-
"@atproto/lex-client": "0.0.
|
|
40
|
-
"@atproto/lex-schema": "0.0.
|
|
39
|
+
"@atproto/lex-client": "^0.0.12",
|
|
40
|
+
"@atproto/lex-schema": "^0.0.12"
|
|
41
41
|
},
|
|
42
42
|
"devDependencies": {
|
|
43
43
|
"vitest": "^4.0.16",
|
|
44
|
-
"@atproto/lex-builder": "0.0.
|
|
45
|
-
"@atproto/lex-server": "0.0.
|
|
44
|
+
"@atproto/lex-builder": "^0.0.14",
|
|
45
|
+
"@atproto/lex-server": "^0.0.9"
|
|
46
46
|
},
|
|
47
47
|
"scripts": {
|
|
48
48
|
"prebuild": "node ./scripts/lex-build.mjs",
|
package/src/error.ts
CHANGED
|
@@ -1,14 +1,60 @@
|
|
|
1
|
-
import { LexError,
|
|
2
|
-
import { com } from './lexicons'
|
|
1
|
+
import { LexError, XrpcFailure } from '@atproto/lex-client'
|
|
3
2
|
|
|
3
|
+
/**
|
|
4
|
+
* Error thrown when two-factor authentication (2FA) is required.
|
|
5
|
+
*
|
|
6
|
+
* This error is thrown by {@link PasswordSession.login} when the server
|
|
7
|
+
* requires an additional authentication factor (e.g., email code). Catch this
|
|
8
|
+
* error to prompt the user for their 2FA code and retry the login with the
|
|
9
|
+
* `authFactorToken` parameter.
|
|
10
|
+
*
|
|
11
|
+
* @example Handling 2FA requirement
|
|
12
|
+
* ```ts
|
|
13
|
+
* import { PasswordSession, LexAuthFactorError } from '@atproto/lex-password-session'
|
|
14
|
+
*
|
|
15
|
+
* try {
|
|
16
|
+
* const session = await PasswordSession.login({
|
|
17
|
+
* service: 'https://bsky.social',
|
|
18
|
+
* identifier: 'alice.bsky.social',
|
|
19
|
+
* password: 'xxxx-xxxx-xxxx-xxxx',
|
|
20
|
+
* })
|
|
21
|
+
* } catch (err) {
|
|
22
|
+
* if (err instanceof LexAuthFactorError) {
|
|
23
|
+
* // Prompt user for 2FA code
|
|
24
|
+
* const token = await promptUser('Enter 2FA code from email:')
|
|
25
|
+
*
|
|
26
|
+
* // Retry with the 2FA token
|
|
27
|
+
* const session = await PasswordSession.login({
|
|
28
|
+
* service: 'https://bsky.social',
|
|
29
|
+
* identifier: 'alice.bsky.social',
|
|
30
|
+
* password: 'xxxx-xxxx-xxxx-xxxx',
|
|
31
|
+
* authFactorToken: token,
|
|
32
|
+
* })
|
|
33
|
+
* }
|
|
34
|
+
* }
|
|
35
|
+
* ```
|
|
36
|
+
*
|
|
37
|
+
* @extends LexError
|
|
38
|
+
*/
|
|
4
39
|
export class LexAuthFactorError extends LexError {
|
|
5
40
|
name = 'LexAuthFactorError'
|
|
6
41
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
42
|
+
/**
|
|
43
|
+
* Creates a new LexAuthFactorError.
|
|
44
|
+
*
|
|
45
|
+
* @param cause - The underlying XRPC failure response from the server
|
|
46
|
+
*/
|
|
47
|
+
constructor(readonly cause: XrpcFailure) {
|
|
48
|
+
super(cause.error, cause.message ?? 'Auth factor token required', { cause })
|
|
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 })
|
|
13
59
|
}
|
|
14
60
|
}
|