-
Notifications
You must be signed in to change notification settings - Fork 872
Expand file tree
/
Copy pathagent.ts
More file actions
345 lines (314 loc) · 8.73 KB
/
Copy pathagent.ts
File metadata and controls
345 lines (314 loc) · 8.73 KB
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
import { ErrorResponseBody, errorResponseBody } from '@atproto/xrpc'
import { defaultFetchHandler } from '@atproto/xrpc'
import {
AtpBaseClient,
AtpServiceClient,
ComAtprotoServerCreateAccount,
ComAtprotoServerCreateSession,
ComAtprotoServerGetSession,
ComAtprotoServerRefreshSession,
ComAtprotoRepoUploadBlob,
} from './client'
import {
AtpSessionData,
AtpAgentCreateAccountOpts,
AtpAgentLoginOpts,
AtpAgentFetchHandler,
AtpAgentFetchHandlerResponse,
AtpAgentGlobalOpts,
AtpPersistSessionHandler,
AtpAgentOpts,
} from './types'
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
private _baseClient: AtpBaseClient
private _persistSession?: AtpPersistSessionHandler
private _refreshSessionPromise: Promise<void> | undefined
get com() {
return this.api.com
}
/**
* The `fetch` implementation; must be implemented for your platform.
*/
static fetch: AtpAgentFetchHandler | undefined = defaultFetchHandler
/**
* Configures the API globally.
*/
static configure(opts: AtpAgentGlobalOpts) {
AtpAgent.fetch = opts.fetch
}
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)
}
/**
* 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
}
/**
* Create a new account and hydrate its session in this agent.
*/
async createAccount(
opts: AtpAgentCreateAccountOpts,
): Promise<ComAtprotoServerCreateAccount.Response> {
try {
const res = await this.api.com.atproto.server.createAccount({
handle: opts.handle,
password: opts.password,
email: opts.email,
inviteCode: opts.inviteCode,
})
this.session = {
accessJwt: res.data.accessJwt,
refreshJwt: res.data.refreshJwt,
handle: res.data.handle,
did: res.data.did,
email: opts.email,
}
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,
})
this.session = {
accessJwt: res.data.accessJwt,
refreshJwt: res.data.refreshJwt,
handle: res.data.handle,
did: res.data.did,
email: res.data.email,
}
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.success || res.data.did !== this.session.did) {
throw new Error('Invalid session')
}
this.session.email = res.data.email
this.session.handle = res.data.handle
return res
} catch (e) {
this.session = undefined
throw e
} finally {
if (this.session) {
this._persistSession?.('create', this.session)
} else {
this._persistSession?.('create-failed', undefined)
}
}
}
/**
* Internal helper to add authorization headers to requests.
*/
private _addAuthHeader(reqHeaders: Record<string, string>) {
if (!reqHeaders.authorization && this.session?.accessJwt) {
return {
...reqHeaders,
authorization: `Bearer ${this.session.accessJwt}`,
}
}
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._addAuthHeader(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._addAuthHeader(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.
*/
private 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.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 = {
accessJwt: res.body.accessJwt,
refreshJwt: res.body.refreshJwt,
handle: res.body.handle,
did: res.body.did,
}
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)
}
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
}
}