-
Notifications
You must be signed in to change notification settings - Fork 402
/
createAccount.ts
160 lines (141 loc) · 4.9 KB
/
createAccount.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
import { InvalidRequestError } from '@atproto/xrpc-server'
import * as ident from '@atproto/identifier'
import * as plc from '@did-plc/lib'
import * as scrypt from '../../../../db/scrypt'
import { Server } from '../../../../lexicon'
import { countAll } from '../../../../db/util'
import { UserAlreadyExistsError } from '../../../../services/account'
import AppContext from '../../../../context'
import Database from '../../../../db'
export default function (server: Server, ctx: AppContext) {
server.com.atproto.server.createAccount(async ({ input, req }) => {
const { email, password, inviteCode, recoveryKey } = input.body
if (ctx.cfg.inviteRequired && !inviteCode) {
throw new InvalidRequestError(
'No invite code provided',
'InvalidInviteCode',
)
}
// validate handle
let handle: string
try {
handle = ident.normalizeAndEnsureValidHandle(input.body.handle)
ident.ensureHandleServiceConstraints(handle, ctx.cfg.availableUserDomains)
} catch (err) {
if (err instanceof ident.InvalidHandleError) {
throw new InvalidRequestError(err.message, 'InvalidHandle')
} else if (err instanceof ident.ReservedHandleError) {
throw new InvalidRequestError(err.message, 'HandleNotAvailable')
} else if (err instanceof ident.UnsupportedDomainError) {
throw new InvalidRequestError(err.message, 'UnsupportedDomain')
}
throw err
}
// check that the invite code still has uses
if (ctx.cfg.inviteRequired && inviteCode) {
await ensureCodeIsAvailable(ctx.db, inviteCode)
}
const now = new Date().toISOString()
const rotationKeys = [ctx.cfg.recoveryKey, ctx.plcRotationKey.did()]
if (recoveryKey) {
rotationKeys.unshift(recoveryKey)
}
// format create op, but don't send until we ensure the username & email are available
const plcCreate = await plc.createOp({
signingKey: ctx.repoSigningKey.did(),
rotationKeys,
handle,
pds: ctx.cfg.publicUrl,
signer: ctx.plcRotationKey,
})
const did = plcCreate.did
const passwordScrypt = await scrypt.genSaltAndHash(password)
const result = await ctx.db.transaction(async (dbTxn) => {
const actorTxn = ctx.services.account(dbTxn)
const repoTxn = ctx.services.repo(dbTxn)
// it's a bit goofy that we run this logic twice,
// but we run it once for a sanity check before doing scrypt & plc ops
// & a second time for locking + integrity check
if (ctx.cfg.inviteRequired && inviteCode) {
await ensureCodeIsAvailable(dbTxn, inviteCode, true)
}
// Register user before going out to PLC to get a real did
try {
await actorTxn.registerUser({ email, handle, did, passwordScrypt })
} catch (err) {
if (err instanceof UserAlreadyExistsError) {
const got = await actorTxn.getAccount(handle, true)
if (got) {
throw new InvalidRequestError(`Handle already taken: ${handle}`)
} else {
throw new InvalidRequestError(`Email already taken: ${email}`)
}
}
throw err
}
// Generate a real did with PLC
try {
await ctx.plcClient.sendOperation(did, plcCreate.op)
} catch (err) {
req.log.error(
{ didKey: ctx.plcRotationKey.did(), handle },
'failed to create did:plc',
)
throw err
}
// insert invite code use
if (ctx.cfg.inviteRequired && inviteCode) {
await dbTxn.db
.insertInto('invite_code_use')
.values({
code: inviteCode,
usedBy: did,
usedAt: now,
})
.execute()
}
// Setup repo root
await repoTxn.createRepo(did, [], now)
const access = ctx.auth.createAccessToken({ did })
const refresh = ctx.auth.createRefreshToken({ did })
await ctx.services.auth(dbTxn).grantRefreshToken(refresh.payload, null)
return {
did,
accessJwt: access.jwt,
refreshJwt: refresh.jwt,
}
})
return {
encoding: 'application/json',
body: {
handle,
did: result.did,
accessJwt: result.accessJwt,
refreshJwt: result.refreshJwt,
},
}
})
}
export const ensureCodeIsAvailable = async (
db: Database,
inviteCode: string,
withLock = false,
): Promise<void> => {
const invite = await db.db
.selectFrom('invite_code')
.selectAll()
.where('code', '=', inviteCode)
.if(withLock && db.dialect === 'pg', (qb) => qb.forUpdate().skipLocked())
.executeTakeFirst()
const uses = await db.db
.selectFrom('invite_code_use')
.select(countAll.as('count'))
.where('code', '=', inviteCode)
.executeTakeFirstOrThrow()
if (!invite || invite.disabled || invite.availableUses <= uses.count) {
throw new InvalidRequestError(
'Provided invite code not available',
'InvalidInviteCode',
)
}
}