-
Notifications
You must be signed in to change notification settings - Fork 643
/
Copy pathagent.ts
458 lines (418 loc) · 12.4 KB
/
agent.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
import { ErrorResponseBody, errorResponseBody } from '@atproto/xrpc'
import { defaultFetchHandler, XRPCError, ResponseType } from '@atproto/xrpc'
import { isValidDidDoc, getPdsEndpoint } from '@atproto/common-web'
import {
AtpBaseClient,
AtpServiceClient,
ComAtprotoServerCreateAccount,
ComAtprotoServerCreateSession,
ComAtprotoServerGetSession,
ComAtprotoServerRefreshSession,
} from './client'
import {
AtpSessionData,
AtpAgentLoginOpts,
AtpAgentFetchHandler,
AtpAgentFetchHandlerResponse,
AtpAgentGlobalOpts,
AtpPersistSessionHandler,
AtpAgentOpts,
AtprotoServiceType,
} from './types'
import { BSKY_LABELER_DID } from './const'
const MAX_MOD_AUTHORITIES = 3
const MAX_LABELERS = 10
const REFRESH_SESSION = 'com.atproto.server.refreshSession'
/**
* An ATP "Agent"
* Manages session token lifecycles and provides convenience methods.
*/
export class AtpAgent {
service: URL
api: AtpServiceClient
session?: AtpSessionData
labelersHeader: string[] = []
proxyHeader: string | undefined
pdsUrl: URL | undefined // The PDS URL, driven by the did doc. May be undefined.
protected _baseClient: AtpBaseClient
protected _persistSession?: AtpPersistSessionHandler
protected _refreshSessionPromise: Promise<void> | undefined
get com() {
return this.api.com
}
/**
* The `fetch` implementation; must be implemented for your platform.
*/
static fetch: AtpAgentFetchHandler | undefined = defaultFetchHandler
/**
* The labelers to be used across all requests with the takedown capability
*/
static appLabelers: string[] = [BSKY_LABELER_DID]
/**
* Configures the API globally.
*/
static configure(opts: AtpAgentGlobalOpts) {
if (opts.fetch) {
AtpAgent.fetch = opts.fetch
}
if (opts.appLabelers) {
AtpAgent.appLabelers = opts.appLabelers
}
}
constructor(opts: AtpAgentOpts) {
this.service =
opts.service instanceof URL ? opts.service : new URL(opts.service)
this._persistSession = opts.persistSession
// create an ATP client instance for this agent
this._baseClient = new AtpBaseClient()
this._baseClient.xrpc.fetch = this._fetch.bind(this) // patch its fetch implementation
this.api = this._baseClient.service(opts.service)
}
clone() {
const inst = new AtpAgent({
service: this.service,
})
this.copyInto(inst)
return inst
}
copyInto(inst: AtpAgent) {
inst.session = this.session
inst.labelersHeader = this.labelersHeader
inst.proxyHeader = this.proxyHeader
inst.pdsUrl = this.pdsUrl
inst.api.xrpc.uri = this.pdsUrl || this.service
}
withProxy(serviceType: AtprotoServiceType, did: string) {
const inst = this.clone()
inst.configureProxyHeader(serviceType, did)
return inst
}
/**
* Is there any active session?
*/
get hasSession() {
return !!this.session
}
/**
* Sets the "Persist Session" method which can be used to store access tokens
* as they change.
*/
setPersistSessionHandler(handler?: AtpPersistSessionHandler) {
this._persistSession = handler
}
/**
* Configures the moderation services to be applied on requests.
* NOTE: this is called automatically by getPreferences() and the relevant moderation config
* methods in BskyAgent instances.
*/
configureLabelersHeader(labelerDids: string[]) {
this.labelersHeader = labelerDids
}
/**
* Configures the atproto-proxy header to be applied on requests
*/
configureProxyHeader(serviceType: AtprotoServiceType, did: string) {
if (did.startsWith('did:')) {
this.proxyHeader = `${did}#${serviceType}`
}
}
/**
* Create a new account and hydrate its session in this agent.
*/
async createAccount(
opts: ComAtprotoServerCreateAccount.InputSchema,
): Promise<ComAtprotoServerCreateAccount.Response> {
try {
const res = await this.api.com.atproto.server.createAccount(opts)
this.session = {
accessJwt: res.data.accessJwt,
refreshJwt: res.data.refreshJwt,
handle: res.data.handle,
did: res.data.did,
email: opts.email,
emailConfirmed: false,
emailAuthFactor: false,
}
this._updateApiEndpoint(res.data.didDoc)
return res
} catch (e) {
this.session = undefined
throw e
} finally {
if (this.session) {
this._persistSession?.('create', this.session)
} else {
this._persistSession?.('create-failed', undefined)
}
}
}
/**
* Start a new session with this agent.
*/
async login(
opts: AtpAgentLoginOpts,
): Promise<ComAtprotoServerCreateSession.Response> {
try {
const res = await this.api.com.atproto.server.createSession({
identifier: opts.identifier,
password: opts.password,
authFactorToken: opts.authFactorToken,
})
this.session = {
accessJwt: res.data.accessJwt,
refreshJwt: res.data.refreshJwt,
handle: res.data.handle,
did: res.data.did,
email: res.data.email,
emailConfirmed: res.data.emailConfirmed,
emailAuthFactor: res.data.emailAuthFactor,
}
this._updateApiEndpoint(res.data.didDoc)
return res
} catch (e) {
this.session = undefined
throw e
} finally {
if (this.session) {
this._persistSession?.('create', this.session)
} else {
this._persistSession?.('create-failed', undefined)
}
}
}
/**
* Resume a pre-existing session with this agent.
*/
async resumeSession(
session: AtpSessionData,
): Promise<ComAtprotoServerGetSession.Response> {
try {
this.session = session
const res = await this.api.com.atproto.server.getSession()
if (res.data.did !== this.session.did) {
throw new XRPCError(
ResponseType.InvalidRequest,
'Invalid session',
'InvalidDID',
)
}
this.session.email = res.data.email
this.session.handle = res.data.handle
this.session.emailConfirmed = res.data.emailConfirmed
this.session.emailAuthFactor = res.data.emailAuthFactor
this._updateApiEndpoint(res.data.didDoc)
this._persistSession?.('update', this.session)
return res
} catch (e) {
this.session = undefined
if (e instanceof XRPCError) {
/*
* `ExpiredToken` and `InvalidToken` are handled in
* `this_refreshSession`, and emit an `expired` event there.
*
* Everything else is handled here.
*/
if (
[1, 408, 425, 429, 500, 502, 503, 504, 522, 524].includes(e.status)
) {
this._persistSession?.('network-error', undefined)
} else {
this._persistSession?.('expired', undefined)
}
} else {
this._persistSession?.('network-error', undefined)
}
throw e
}
}
/**
* Internal helper to add authorization headers to requests.
*/
private _addHeaders(reqHeaders: Record<string, string>) {
if (!reqHeaders.authorization && this.session?.accessJwt) {
reqHeaders = {
...reqHeaders,
authorization: `Bearer ${this.session.accessJwt}`,
}
}
if (this.proxyHeader) {
reqHeaders = {
...reqHeaders,
'atproto-proxy': this.proxyHeader,
}
}
reqHeaders = {
...reqHeaders,
'atproto-accept-labelers': AtpAgent.appLabelers
.map((str) => `${str};redact`)
.concat(this.labelersHeader.filter((str) => str.startsWith('did:')))
.slice(0, MAX_LABELERS)
.join(', '),
}
return reqHeaders
}
/**
* Internal fetch handler which adds access-token management
*/
private async _fetch(
reqUri: string,
reqMethod: string,
reqHeaders: Record<string, string>,
reqBody: any,
): Promise<AtpAgentFetchHandlerResponse> {
if (!AtpAgent.fetch) {
throw new Error('AtpAgent fetch() method not configured')
}
// wait for any active session-refreshes to finish
await this._refreshSessionPromise
// send the request
let res = await AtpAgent.fetch(
reqUri,
reqMethod,
this._addHeaders(reqHeaders),
reqBody,
)
// handle session-refreshes as needed
if (isErrorResponse(res, ['ExpiredToken']) && this.session?.refreshJwt) {
// attempt refresh
await this.refreshSession()
// resend the request with the new access token
res = await AtpAgent.fetch(
reqUri,
reqMethod,
this._addHeaders(reqHeaders),
reqBody,
)
}
return res
}
/**
* Internal helper to refresh sessions
* - Wraps the actual implementation in a promise-guard to ensure only
* one refresh is attempted at a time.
*/
async refreshSession() {
if (this._refreshSessionPromise) {
return this._refreshSessionPromise
}
this._refreshSessionPromise = this._refreshSessionInner()
try {
await this._refreshSessionPromise
} finally {
this._refreshSessionPromise = undefined
}
}
/**
* Internal helper to refresh sessions (actual behavior)
*/
private async _refreshSessionInner() {
if (!AtpAgent.fetch) {
throw new Error('AtpAgent fetch() method not configured')
}
if (!this.session?.refreshJwt) {
return
}
// send the refresh request
const url = new URL((this.pdsUrl || this.service).origin)
url.pathname = `/xrpc/${REFRESH_SESSION}`
const res = await AtpAgent.fetch(
url.toString(),
'POST',
{
authorization: `Bearer ${this.session.refreshJwt}`,
},
undefined,
)
if (isErrorResponse(res, ['ExpiredToken', 'InvalidToken'])) {
// failed due to a bad refresh token
this.session = undefined
this._persistSession?.('expired', undefined)
} else if (isNewSessionObject(this._baseClient, res.body)) {
// succeeded, update the session
this.session = {
...(this.session || {}),
accessJwt: res.body.accessJwt,
refreshJwt: res.body.refreshJwt,
handle: res.body.handle,
did: res.body.did,
}
this._updateApiEndpoint(res.body.didDoc)
this._persistSession?.('update', this.session)
}
// else: other failures should be ignored - the issue will
// propagate in the _fetch() handler's second attempt to run
// the request
}
/**
* Upload a binary blob to the server
*/
uploadBlob: typeof this.api.com.atproto.repo.uploadBlob = (data, opts) =>
this.api.com.atproto.repo.uploadBlob(data, opts)
/**
* Resolve a handle to a DID
*/
resolveHandle: typeof this.api.com.atproto.identity.resolveHandle = (
params,
opts,
) => this.api.com.atproto.identity.resolveHandle(params, opts)
/**
* Change the user's handle
*/
updateHandle: typeof this.api.com.atproto.identity.updateHandle = (
data,
opts,
) => this.api.com.atproto.identity.updateHandle(data, opts)
/**
* Create a moderation report
*/
createModerationReport: typeof this.api.com.atproto.moderation.createReport =
(data, opts) => this.api.com.atproto.moderation.createReport(data, opts)
/**
* Helper to update the pds endpoint dynamically.
*
* The session methods (create, resume, refresh) may respond with the user's
* did document which contains the user's canonical PDS endpoint. That endpoint
* may differ from the endpoint used to contact the server. We capture that
* PDS endpoint and update the client to use that given endpoint for future
* requests. (This helps ensure smooth migrations between PDSes, especially
* when the PDSes are operated by a single org.)
*/
private _updateApiEndpoint(didDoc: unknown) {
if (isValidDidDoc(didDoc)) {
const endpoint = getPdsEndpoint(didDoc)
this.pdsUrl = endpoint ? new URL(endpoint) : undefined
}
this.api.xrpc.uri = this.pdsUrl || this.service
}
}
function isErrorObject(v: unknown): v is ErrorResponseBody {
return errorResponseBody.safeParse(v).success
}
function isErrorResponse(
res: AtpAgentFetchHandlerResponse,
errorNames: string[],
): boolean {
if (res.status !== 400) {
return false
}
if (!isErrorObject(res.body)) {
return false
}
return (
typeof res.body.error === 'string' && errorNames.includes(res.body.error)
)
}
function isNewSessionObject(
client: AtpBaseClient,
v: unknown,
): v is ComAtprotoServerRefreshSession.OutputSchema {
try {
client.xrpc.lex.assertValidXrpcOutput(
'com.atproto.server.refreshSession',
v,
)
return true
} catch {
return false
}
}