-
Notifications
You must be signed in to change notification settings - Fork 642
/
Copy pathindex.ts
387 lines (333 loc) · 10.7 KB
/
index.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
import { KeyObject } from 'node:crypto'
import { HOUR } from '@atproto/common'
import { CID } from 'multiformats/cid'
import { AccountDb, EmailTokenPurpose, getDb, getMigrator } from './db'
import * as scrypt from './helpers/scrypt'
import * as account from './helpers/account'
import { ActorAccount } from './helpers/account'
import * as repo from './helpers/repo'
import * as auth from './helpers/auth'
import * as invite from './helpers/invite'
import * as password from './helpers/password'
import * as emailToken from './helpers/email-token'
import { AuthScope } from '../auth-verifier'
import { StatusAttr } from '../lexicon/types/com/atproto/admin/defs'
export class AccountManager {
db: AccountDb
constructor(
dbLocation: string,
private jwtKey: KeyObject,
private serviceDid: string,
disableWalAutoCheckpoint = false,
) {
this.db = getDb(dbLocation, disableWalAutoCheckpoint)
}
async migrateOrThrow() {
await this.db.ensureWal()
await getMigrator(this.db).migrateToLatestOrThrow()
}
close() {
this.db.close()
}
// Account
// ----------
async getAccount(
handleOrDid: string,
flags?: account.AvailabilityFlags,
): Promise<ActorAccount | null> {
return account.getAccount(this.db, handleOrDid, flags)
}
async getAccountByEmail(
email: string,
flags?: account.AvailabilityFlags,
): Promise<ActorAccount | null> {
return account.getAccountByEmail(this.db, email, flags)
}
// Repo exists and is not taken-down
async isRepoAvailable(did: string) {
const got = await this.getAccount(did)
return !!got
}
async isAccountActivated(did: string): Promise<boolean> {
const account = await this.getAccount(did, { includeDeactivated: true })
if (!account) return false
return !account.deactivatedAt
}
async getDidForActor(
handleOrDid: string,
flags?: account.AvailabilityFlags,
): Promise<string | null> {
const got = await this.getAccount(handleOrDid, flags)
return got?.did ?? null
}
async createAccount(opts: {
did: string
handle: string
email?: string
password?: string
repoCid: CID
repoRev: string
inviteCode?: string
deactivated?: boolean
}) {
const {
did,
handle,
email,
password,
repoCid,
repoRev,
inviteCode,
deactivated,
} = opts
const passwordScrypt = password
? await scrypt.genSaltAndHash(password)
: undefined
const { accessJwt, refreshJwt } = await auth.createTokens({
did,
jwtKey: this.jwtKey,
serviceDid: this.serviceDid,
scope: AuthScope.Access,
})
const refreshPayload = auth.decodeRefreshToken(refreshJwt)
const now = new Date().toISOString()
await this.db.transaction(async (dbTxn) => {
if (inviteCode) {
await invite.ensureInviteIsAvailable(dbTxn, inviteCode)
}
await Promise.all([
account.registerActor(dbTxn, { did, handle, deactivated }),
email && passwordScrypt
? account.registerAccount(dbTxn, { did, email, passwordScrypt })
: Promise.resolve(),
invite.recordInviteUse(dbTxn, {
did,
inviteCode,
now,
}),
auth.storeRefreshToken(dbTxn, refreshPayload, null),
repo.updateRoot(dbTxn, did, repoCid, repoRev),
])
})
return { accessJwt, refreshJwt }
}
// @NOTE should always be paired with a sequenceHandle().
// the token output from this method should be passed to sequenceHandle().
async updateHandle(did: string, handle: string) {
return account.updateHandle(this.db, did, handle)
}
async deleteAccount(did: string) {
return account.deleteAccount(this.db, did)
}
async takedownAccount(did: string, takedown: StatusAttr) {
await this.db.transaction((dbTxn) =>
Promise.all([
account.updateAccountTakedownStatus(dbTxn, did, takedown),
auth.revokeRefreshTokensByDid(dbTxn, did),
]),
)
}
async getAccountTakedownStatus(did: string) {
return account.getAccountTakedownStatus(this.db, did)
}
async updateRepoRoot(did: string, cid: CID, rev: string) {
return repo.updateRoot(this.db, did, cid, rev)
}
async deactivateAccount(did: string, deleteAfter: string | null) {
return account.deactivateAccount(this.db, did, deleteAfter)
}
async activateAccount(did: string) {
return account.activateAccount(this.db, did)
}
// Auth
// ----------
async createSession(did: string, appPasswordName: string | null) {
const { accessJwt, refreshJwt } = await auth.createTokens({
did,
jwtKey: this.jwtKey,
serviceDid: this.serviceDid,
scope: appPasswordName === null ? AuthScope.Access : AuthScope.AppPass,
})
const refreshPayload = auth.decodeRefreshToken(refreshJwt)
await auth.storeRefreshToken(this.db, refreshPayload, appPasswordName)
return { accessJwt, refreshJwt }
}
async rotateRefreshToken(id: string) {
const token = await auth.getRefreshToken(this.db, id)
if (!token) return null
const now = new Date()
// take the chance to tidy all of a user's expired tokens
// does not need to be transactional since this is just best-effort
await auth.deleteExpiredRefreshTokens(this.db, token.did, now.toISOString())
// Shorten the refresh token lifespan down from its
// original expiration time to its revocation grace period.
const prevExpiresAt = new Date(token.expiresAt)
const REFRESH_GRACE_MS = 2 * HOUR
const graceExpiresAt = new Date(now.getTime() + REFRESH_GRACE_MS)
const expiresAt =
graceExpiresAt < prevExpiresAt ? graceExpiresAt : prevExpiresAt
if (expiresAt <= now) {
return null
}
// Determine the next refresh token id: upon refresh token
// reuse you always receive a refresh token with the same id.
const nextId = token.nextId ?? auth.getRefreshTokenId()
const { accessJwt, refreshJwt } = await auth.createTokens({
did: token.did,
jwtKey: this.jwtKey,
serviceDid: this.serviceDid,
scope:
token.appPasswordName === null ? AuthScope.Access : AuthScope.AppPass,
jti: nextId,
})
const refreshPayload = auth.decodeRefreshToken(refreshJwt)
try {
await this.db.transaction((dbTxn) =>
Promise.all([
auth.addRefreshGracePeriod(dbTxn, {
id,
expiresAt: expiresAt.toISOString(),
nextId,
}),
auth.storeRefreshToken(dbTxn, refreshPayload, token.appPasswordName),
]),
)
} catch (err) {
if (err instanceof auth.ConcurrentRefreshError) {
return this.rotateRefreshToken(id)
}
throw err
}
return { accessJwt, refreshJwt }
}
async revokeRefreshToken(id: string) {
return auth.revokeRefreshToken(this.db, id)
}
// Passwords
// ----------
async createAppPassword(did: string, name: string) {
return password.createAppPassword(this.db, did, name)
}
async listAppPasswords(did: string) {
return password.listAppPasswords(this.db, did)
}
async verifyAccountPassword(
did: string,
passwordStr: string,
): Promise<boolean> {
return password.verifyAccountPassword(this.db, did, passwordStr)
}
async verifyAppPassword(
did: string,
passwordStr: string,
): Promise<string | null> {
return password.verifyAppPassword(this.db, did, passwordStr)
}
async revokeAppPassword(did: string, name: string) {
await this.db.transaction(async (dbTxn) =>
Promise.all([
password.deleteAppPassword(dbTxn, did, name),
auth.revokeAppPasswordRefreshToken(dbTxn, did, name),
]),
)
}
// Invites
// ----------
async ensureInviteIsAvailable(code: string) {
return invite.ensureInviteIsAvailable(this.db, code)
}
async createInviteCodes(
toCreate: { account: string; codes: string[] }[],
useCount: number,
) {
return invite.createInviteCodes(this.db, toCreate, useCount)
}
async createAccountInviteCodes(
forAccount: string,
codes: string[],
expectedTotal: number,
disabled: 0 | 1,
) {
return invite.createAccountInviteCodes(
this.db,
forAccount,
codes,
expectedTotal,
disabled,
)
}
async getAccountInvitesCodes(did: string) {
return invite.getAccountInviteCodes(this.db, did)
}
async getInvitedByForAccounts(dids: string[]) {
return invite.getInvitedByForAccounts(this.db, dids)
}
async getInviteCodesUses(codes: string[]) {
return invite.getInviteCodesUses(this.db, codes)
}
async setAccountInvitesDisabled(did: string, disabled: boolean) {
return invite.setAccountInvitesDisabled(this.db, did, disabled)
}
async disableInviteCodes(opts: { codes: string[]; accounts: string[] }) {
return invite.disableInviteCodes(this.db, opts)
}
// Email Tokens
// ----------
async createEmailToken(did: string, purpose: EmailTokenPurpose) {
return emailToken.createEmailToken(this.db, did, purpose)
}
async assertValidEmailToken(
did: string,
purpose: EmailTokenPurpose,
token: string,
) {
return emailToken.assertValidToken(this.db, did, purpose, token)
}
async assertValidEmailTokenAndCleanup(
did: string,
purpose: EmailTokenPurpose,
token: string,
) {
await emailToken.assertValidToken(this.db, did, purpose, token)
await emailToken.deleteEmailToken(this.db, did, purpose)
}
async confirmEmail(opts: { did: string; token: string }) {
const { did, token } = opts
await emailToken.assertValidToken(this.db, did, 'confirm_email', token)
const now = new Date().toISOString()
await this.db.transaction((dbTxn) =>
Promise.all([
emailToken.deleteEmailToken(dbTxn, did, 'confirm_email'),
account.setEmailConfirmedAt(dbTxn, did, now),
]),
)
}
async updateEmail(opts: { did: string; email: string }) {
const { did, email } = opts
await this.db.transaction((dbTxn) =>
Promise.all([
account.updateEmail(dbTxn, did, email),
emailToken.deleteAllEmailTokens(dbTxn, did),
]),
)
}
async resetPassword(opts: { password: string; token: string }) {
const did = await emailToken.assertValidTokenAndFindDid(
this.db,
'reset_password',
opts.token,
)
await this.updateAccountPassword({ did, password: opts.password })
}
async updateAccountPassword(opts: { did: string; password: string }) {
const { did } = opts
const passwordScrypt = await scrypt.genSaltAndHash(opts.password)
await this.db.transaction(async (dbTxn) =>
Promise.all([
password.updateUserPassword(dbTxn, { did, passwordScrypt }),
emailToken.deleteEmailToken(dbTxn, did, 'reset_password'),
auth.revokeRefreshTokensByDid(dbTxn, did),
]),
)
}
}