@prunellejs/auth 0.7.4 → 0.8.0
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/llms.txt +7 -5
- package/package.json +2 -2
- package/src/account.ts +18 -5
- package/src/crypto.ts +11 -13
- package/src/http.ts +22 -2
- package/src/index.ts +21 -14
- package/src/links.ts +4 -4
- package/src/oauth-routes.ts +3 -3
- package/src/org-routes.ts +1 -1
- package/src/orgs.ts +84 -36
- package/src/passkey-routes.ts +34 -24
- package/src/passkeys.ts +43 -49
- package/src/routes.ts +28 -11
- package/src/sqlite-ext.ts +5 -11
- package/src/sqlite.ts +45 -21
- package/src/store-ext.ts +17 -17
- package/src/store.ts +20 -2
- package/src/totp-routes.ts +43 -13
- package/src/totp.ts +18 -9
- package/src/webauthn-crypto.ts +49 -15
package/src/passkey-routes.ts
CHANGED
|
@@ -1,18 +1,20 @@
|
|
|
1
1
|
// HTTP routes for WebAuthn passkeys: registration, passwordless login, 2FA verification, listing, and deletion.
|
|
2
2
|
|
|
3
3
|
import type { RequestContext } from 'prunelle/server'
|
|
4
|
-
import type { AuthRouteRegistrar } from './http'
|
|
4
|
+
import type { AuthLimits, AuthRouteRegistrar } from './http'
|
|
5
5
|
import type { AssertionVerifyInput, PasskeyError, PasskeyManager, RegisterVerifyInput } from './passkeys'
|
|
6
6
|
import type { SessionManager } from './session'
|
|
7
7
|
import type { AuthStore, AuthUser } from './store'
|
|
8
8
|
import type { TotpManager } from './totp'
|
|
9
9
|
import { safeRedirect, wantsJson } from 'prunelle/server'
|
|
10
|
+
import { freshSignin, keepOnlyThisSession } from './account'
|
|
10
11
|
import { fail, parseJsonBody } from './http'
|
|
11
12
|
import { toPublicUser } from './store'
|
|
12
13
|
import { respondTwoFactorChallenge } from './totp'
|
|
13
14
|
|
|
14
15
|
export interface PasskeyRoutesDeps<TUser extends AuthUser = AuthUser> {
|
|
15
16
|
authRoute: AuthRouteRegistrar
|
|
17
|
+
limits: AuthLimits
|
|
16
18
|
store: AuthStore<TUser>
|
|
17
19
|
sessions: SessionManager<TUser>
|
|
18
20
|
passkeys: PasskeyManager
|
|
@@ -69,12 +71,12 @@ function asAssertionInput(body: Record<string, unknown>): AssertionVerifyInput |
|
|
|
69
71
|
}
|
|
70
72
|
|
|
71
73
|
export function registerPasskeyRoutes<TUser extends AuthUser = AuthUser>(deps: PasskeyRoutesDeps<TUser>): void {
|
|
72
|
-
const { authRoute, store, sessions, passkeys, totp, twoFactorRedirect, defaultRedirect, requireEmailVerification } = deps
|
|
74
|
+
const { authRoute, limits, store, sessions, passkeys, totp, twoFactorRedirect, defaultRedirect, requireEmailVerification } = deps
|
|
73
75
|
|
|
74
76
|
authRoute('POST', '/passkeys/register/options', { limit: 'passkey-reg' }, async (ctx) => {
|
|
75
|
-
const resolved = await
|
|
76
|
-
if (
|
|
77
|
-
return
|
|
77
|
+
const resolved = await freshSignin(ctx, sessions)
|
|
78
|
+
if (resolved instanceof Response)
|
|
79
|
+
return resolved
|
|
78
80
|
try {
|
|
79
81
|
const options = await passkeys.createRegisterOptions(ctx, resolved.user)
|
|
80
82
|
return ctx.json({ ok: true, options }, { status: 200 })
|
|
@@ -85,9 +87,9 @@ export function registerPasskeyRoutes<TUser extends AuthUser = AuthUser>(deps: P
|
|
|
85
87
|
})
|
|
86
88
|
|
|
87
89
|
authRoute('POST', '/passkeys/register/verify', { limit: 'passkey-reg' }, async (ctx) => {
|
|
88
|
-
const resolved = await
|
|
89
|
-
if (
|
|
90
|
-
return
|
|
90
|
+
const resolved = await freshSignin(ctx, sessions)
|
|
91
|
+
if (resolved instanceof Response)
|
|
92
|
+
return resolved
|
|
91
93
|
const raw = await parseJsonBody(ctx)
|
|
92
94
|
if (raw instanceof Response)
|
|
93
95
|
return raw
|
|
@@ -96,6 +98,7 @@ export function registerPasskeyRoutes<TUser extends AuthUser = AuthUser>(deps: P
|
|
|
96
98
|
return fail(ctx, 400, 'Invalid passkey registration payload')
|
|
97
99
|
try {
|
|
98
100
|
const passkey = await passkeys.verifyRegistration(ctx, resolved.user.id, input)
|
|
101
|
+
await keepOnlyThisSession(ctx, sessions, store, resolved.user.id)
|
|
99
102
|
return ctx.json({ ok: true, passkey }, { status: 201 })
|
|
100
103
|
}
|
|
101
104
|
catch (err) {
|
|
@@ -167,6 +170,11 @@ export function registerPasskeyRoutes<TUser extends AuthUser = AuthUser>(deps: P
|
|
|
167
170
|
const pending = totp.readPendingCookie(ctx)
|
|
168
171
|
if (!pending)
|
|
169
172
|
return fail(ctx, 401, 'Two-factor session expired or invalid')
|
|
173
|
+
const locked = limits.refuseLockedSecondFactor(ctx, pending.userId)
|
|
174
|
+
if (locked) {
|
|
175
|
+
totp.clearPendingCookie(ctx)
|
|
176
|
+
return locked
|
|
177
|
+
}
|
|
170
178
|
if (!pending.methods.includes('passkey'))
|
|
171
179
|
return fail(ctx, 403, 'Passkey cannot be used as second factor for this sign-in')
|
|
172
180
|
const raw = await parseJsonBody(ctx)
|
|
@@ -177,22 +185,23 @@ export function registerPasskeyRoutes<TUser extends AuthUser = AuthUser>(deps: P
|
|
|
177
185
|
return fail(ctx, 400, 'Invalid passkey assertion payload')
|
|
178
186
|
try {
|
|
179
187
|
await passkeys.verifyAssertion(ctx, '2fa', input, pending.userId)
|
|
180
|
-
const userRecord = await sessions.observeAsync(store.getUserById(pending.userId))
|
|
181
|
-
if (!userRecord) {
|
|
182
|
-
totp.clearPendingCookie(ctx)
|
|
183
|
-
return fail(ctx, 401, 'Unable to resolve user account')
|
|
184
|
-
}
|
|
185
|
-
totp.clearPendingCookie(ctx)
|
|
186
|
-
const pub = toPublicUser(userRecord)
|
|
187
|
-
await sessions.createSessionForUser(userRecord.id, ctx, pub)
|
|
188
|
-
const redirect = safeRedirect(typeof raw.redirect === 'string' ? raw.redirect : (typeof raw.next === 'string' ? raw.next : pending.redirect), defaultRedirect)
|
|
189
|
-
if (wantsJson(ctx.request))
|
|
190
|
-
return ctx.json({ ok: true, user: pub }, { status: 200 })
|
|
191
|
-
return ctx.redirect(redirect, 303)
|
|
192
188
|
}
|
|
193
189
|
catch (err) {
|
|
194
|
-
|
|
190
|
+
const refused = limits.countFailedSecondFactor(ctx, pending.userId)
|
|
191
|
+
if (refused)
|
|
192
|
+
totp.clearPendingCookie(ctx)
|
|
193
|
+
return refused ?? respondPasskeyErr(ctx, err)
|
|
195
194
|
}
|
|
195
|
+
const userRecord = await sessions.observeAsync(store.getUserById(pending.userId))
|
|
196
|
+
totp.clearPendingCookie(ctx)
|
|
197
|
+
if (!userRecord)
|
|
198
|
+
return fail(ctx, 401, 'Unable to resolve user account')
|
|
199
|
+
const pub = toPublicUser(userRecord)
|
|
200
|
+
await sessions.createSessionForUser(userRecord.id, ctx, pub)
|
|
201
|
+
const redirect = safeRedirect(typeof raw.redirect === 'string' ? raw.redirect : (typeof raw.next === 'string' ? raw.next : pending.redirect), defaultRedirect)
|
|
202
|
+
if (wantsJson(ctx.request))
|
|
203
|
+
return ctx.json({ ok: true, user: pub }, { status: 200 })
|
|
204
|
+
return ctx.redirect(redirect, 303)
|
|
196
205
|
})
|
|
197
206
|
|
|
198
207
|
authRoute('GET', '/passkeys', {}, async (ctx) => {
|
|
@@ -204,15 +213,16 @@ export function registerPasskeyRoutes<TUser extends AuthUser = AuthUser>(deps: P
|
|
|
204
213
|
})
|
|
205
214
|
|
|
206
215
|
authRoute('POST', '/passkeys/delete', { limit: 'passkey-del', readBody: true }, async (ctx, body) => {
|
|
207
|
-
const resolved = await
|
|
208
|
-
if (
|
|
209
|
-
return
|
|
216
|
+
const resolved = await freshSignin(ctx, sessions)
|
|
217
|
+
if (resolved instanceof Response)
|
|
218
|
+
return resolved
|
|
210
219
|
const credentialId = (body.id ?? body.credentialId ?? '').trim()
|
|
211
220
|
if (!credentialId)
|
|
212
221
|
return fail(ctx, 400, 'Passkey id is required')
|
|
213
222
|
const deleted = await passkeys.deletePasskey(resolved.user.id, credentialId)
|
|
214
223
|
if (!deleted)
|
|
215
224
|
return fail(ctx, 404, 'Passkey not found')
|
|
225
|
+
await keepOnlyThisSession(ctx, sessions, store, resolved.user.id)
|
|
216
226
|
if (wantsJson(ctx.request))
|
|
217
227
|
return ctx.json({ ok: true }, { status: 200 })
|
|
218
228
|
return ctx.redirect(safeRedirect(body.redirect ?? body.next, defaultRedirect), 303)
|
package/src/passkeys.ts
CHANGED
|
@@ -3,14 +3,14 @@
|
|
|
3
3
|
import type { RequestContext } from 'prunelle/server'
|
|
4
4
|
import type { SessionManager } from './session'
|
|
5
5
|
import type { AuthStore, AuthUser, PasskeyRecord, PasskeySummary } from './store'
|
|
6
|
+
import { createHmac } from 'node:crypto'
|
|
6
7
|
import { safeEqual } from 'prunelle/server'
|
|
7
|
-
import { fromBase64Url, randomToken, sha256Bytes,
|
|
8
|
-
import { authCookie } from './http'
|
|
9
|
-
import { toPasskeySummary } from './store'
|
|
10
|
-
import { COSE_ALG_EDDSA, COSE_ALG_ES256, COSE_ALG_RS256, coseKeyToJwk,
|
|
8
|
+
import { fromBase64Url, randomToken, sha256Bytes, sha256Hex, signJson, toBase64Url, verifyJson } from './crypto'
|
|
9
|
+
import { authCookie, linkOrigin } from './http'
|
|
10
|
+
import { normalizeEmail, toPasskeySummary } from './store'
|
|
11
|
+
import { COSE_ALG_EDDSA, COSE_ALG_ES256, COSE_ALG_RS256, coseKeyToJwk, decodeCborExact, importPasskeyKey, parseAuthenticatorData, verifyWebAuthnSignature } from './webauthn-crypto'
|
|
11
12
|
|
|
12
13
|
const CHALLENGE_TTL_MS = 5 * 60 * 1000
|
|
13
|
-
const MAX_ACTIVE_CHALLENGES = 10_000
|
|
14
14
|
|
|
15
15
|
export type PasskeyUserVerification = 'required' | 'preferred' | 'discouraged'
|
|
16
16
|
|
|
@@ -88,7 +88,6 @@ export interface PasskeyManager {
|
|
|
88
88
|
verifyAssertion(ctx: RequestContext, purpose: 'login' | '2fa', input: AssertionVerifyInput, expectedUserId?: string): Promise<{ passkey: PasskeyRecord, userId: string }>
|
|
89
89
|
listPasskeys(userId: string): Promise<PasskeySummary[]>
|
|
90
90
|
deletePasskey(userId: string, credentialId: string): Promise<boolean>
|
|
91
|
-
pruneChallenges(): void
|
|
92
91
|
}
|
|
93
92
|
|
|
94
93
|
function requirePasskeyStore<TUser extends AuthUser>(store: AuthStore<TUser>) {
|
|
@@ -151,10 +150,10 @@ async function performRegistrationVerify<TUser extends AuthUser>(
|
|
|
151
150
|
|
|
152
151
|
let authDataBytes: Uint8Array
|
|
153
152
|
try {
|
|
154
|
-
const decoded =
|
|
155
|
-
if (!(decoded
|
|
153
|
+
const decoded = decodeCborExact(fromBase64Url(input.response.attestationObject))
|
|
154
|
+
if (!(decoded instanceof Map))
|
|
156
155
|
throw new Error('attestationObject must be a CBOR map')
|
|
157
|
-
const rawAuthData = decoded.
|
|
156
|
+
const rawAuthData = decoded.get('authData')
|
|
158
157
|
if (!(rawAuthData instanceof Uint8Array))
|
|
159
158
|
throw new Error('attestationObject missing authData')
|
|
160
159
|
authDataBytes = rawAuthData
|
|
@@ -182,6 +181,12 @@ async function performRegistrationVerify<TUser extends AuthUser>(
|
|
|
182
181
|
catch (err) {
|
|
183
182
|
throw passkeyError(400, err instanceof Error ? err.message : 'Unsupported COSE public key')
|
|
184
183
|
}
|
|
184
|
+
try {
|
|
185
|
+
await importPasskeyKey(keyInfo.jwk, keyInfo.algorithm)
|
|
186
|
+
}
|
|
187
|
+
catch {
|
|
188
|
+
throw passkeyError(400, 'Passkey public key is not a valid key for its algorithm, such as an EC point off the curve')
|
|
189
|
+
}
|
|
185
190
|
|
|
186
191
|
const credentialId = toBase64Url(parsed.credentialId)
|
|
187
192
|
const providedId = input.id ?? input.rawId
|
|
@@ -260,65 +265,62 @@ async function performAssertionVerify<TUser extends AuthUser>(
|
|
|
260
265
|
return { passkey: { ...passkey, signCount: parsed.signCount, lastUsedAt: now }, userId: passkey.userId }
|
|
261
266
|
}
|
|
262
267
|
|
|
268
|
+
// A credential id no authenticator holds, the same on every call for one email.
|
|
269
|
+
function decoyCredentialId(secret: string, email: string): string {
|
|
270
|
+
return toBase64Url(new Uint8Array(createHmac('sha256', secret).update(`passkey-decoy:${normalizeEmail(email)}`).digest().subarray(0, 16)))
|
|
271
|
+
}
|
|
272
|
+
|
|
263
273
|
export function createPasskeyManager<TUser extends AuthUser = AuthUser>(deps: PasskeyManagerDeps<TUser>): PasskeyManager {
|
|
264
274
|
const { store, sessions, secret, challengeCookieName, getSite, options, isSecureCookie } = deps
|
|
265
275
|
const userVerificationFor = (purpose: 'register' | 'login' | '2fa'): PasskeyUserVerification =>
|
|
266
276
|
options?.userVerification ?? (purpose === '2fa' ? 'preferred' : 'required')
|
|
267
|
-
const activeChallenges = new Map<string, number>()
|
|
268
277
|
|
|
269
278
|
function resolveExpectedOrigin(ctx: RequestContext): string {
|
|
270
|
-
|
|
279
|
+
const origin = options?.origin ?? linkOrigin(getSite(), ctx.url)
|
|
280
|
+
if (origin === undefined)
|
|
281
|
+
throw passkeyError(500, 'prunelle: passkeys need the app\'s origin, which the Host header cannot be trusted for: set site in prunelle.config.ts (or passkeys.origin in createAuth())')
|
|
282
|
+
return origin
|
|
271
283
|
}
|
|
272
284
|
|
|
273
285
|
function resolveRpId(ctx: RequestContext): string {
|
|
274
286
|
return options?.rpId ?? new URL(resolveExpectedOrigin(ctx)).hostname
|
|
275
287
|
}
|
|
276
288
|
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
for (const [ch, exp] of activeChallenges) {
|
|
280
|
-
if (exp <= now)
|
|
281
|
-
activeChallenges.delete(ch)
|
|
282
|
-
}
|
|
283
|
-
}
|
|
284
|
-
|
|
285
|
-
function issueChallenge(ctx: RequestContext, purpose: 'register' | 'login' | '2fa', userId?: string): string {
|
|
286
|
-
if (activeChallenges.size >= MAX_ACTIVE_CHALLENGES)
|
|
287
|
-
pruneChallenges()
|
|
289
|
+
// The challenge is a single-use token of the store, so another instance or a restart sees it, and pruneExpired drops the unused ones.
|
|
290
|
+
async function issueChallenge(ctx: RequestContext, purpose: 'register' | 'login' | '2fa', userId?: string): Promise<string> {
|
|
288
291
|
const challenge = randomToken(32)
|
|
289
292
|
const exp = Date.now() + CHALLENGE_TTL_MS
|
|
290
|
-
|
|
293
|
+
await sessions.observeAsync(store.createToken({ tokenHash: sha256Hex(challenge), email: '', kind: 'passkey-challenge', expiresAt: exp }))
|
|
291
294
|
const payload: ChallengeCookiePayload = {
|
|
292
295
|
challenge,
|
|
293
296
|
purpose,
|
|
294
297
|
...(userId !== undefined ? { userId } : {}),
|
|
295
298
|
exp,
|
|
296
299
|
}
|
|
297
|
-
ctx.cookies.set(challengeCookieName,
|
|
300
|
+
ctx.cookies.set(challengeCookieName, signJson(secret(), 'webauthn', payload), authCookie(isSecureCookie(ctx), Math.floor(CHALLENGE_TTL_MS / 1000)))
|
|
298
301
|
return challenge
|
|
299
302
|
}
|
|
300
303
|
|
|
301
|
-
function consumeChallenge(ctx: RequestContext, purpose: 'register' | 'login' | '2fa', expectedUserId?: string): string {
|
|
304
|
+
async function consumeChallenge(ctx: RequestContext, purpose: 'register' | 'login' | '2fa', expectedUserId?: string): Promise<string> {
|
|
302
305
|
const raw = ctx.cookies.get(challengeCookieName)
|
|
303
306
|
ctx.cookies.delete(challengeCookieName, { path: '/' })
|
|
304
307
|
if (!raw)
|
|
305
308
|
throw passkeyError(400, 'Missing passkey challenge')
|
|
306
|
-
const payload =
|
|
309
|
+
const payload = verifyJson<ChallengeCookiePayload>(secret(), 'webauthn', raw)
|
|
307
310
|
const now = Date.now()
|
|
308
311
|
if (!payload || payload.exp <= now || payload.purpose !== purpose)
|
|
309
312
|
throw passkeyError(400, 'Invalid or expired passkey challenge')
|
|
310
313
|
if (expectedUserId !== undefined && payload.userId !== expectedUserId)
|
|
311
314
|
throw passkeyError(400, 'Passkey challenge does not match user')
|
|
312
|
-
const
|
|
313
|
-
|
|
314
|
-
if (storedExp === undefined || storedExp <= now)
|
|
315
|
+
const stored = await sessions.observeAsync(store.consumeToken(sha256Hex(payload.challenge), 'passkey-challenge'))
|
|
316
|
+
if (stored === undefined || stored.expiresAt <= now)
|
|
315
317
|
throw passkeyError(400, 'Passkey challenge expired or already used')
|
|
316
318
|
return payload.challenge
|
|
317
319
|
}
|
|
318
320
|
|
|
319
|
-
function ceremonyFor(ctx: RequestContext, purpose: 'register' | 'login' | '2fa', expectedUserId?: string): CeremonyContext {
|
|
321
|
+
async function ceremonyFor(ctx: RequestContext, purpose: 'register' | 'login' | '2fa', expectedUserId?: string): Promise<CeremonyContext> {
|
|
320
322
|
return {
|
|
321
|
-
expectedChallenge: consumeChallenge(ctx, purpose, expectedUserId),
|
|
323
|
+
expectedChallenge: await consumeChallenge(ctx, purpose, expectedUserId),
|
|
322
324
|
expectedOrigin: resolveExpectedOrigin(ctx),
|
|
323
325
|
expectedRpId: resolveRpId(ctx),
|
|
324
326
|
userVerification: userVerificationFor(purpose),
|
|
@@ -326,14 +328,12 @@ export function createPasskeyManager<TUser extends AuthUser = AuthUser>(deps: Pa
|
|
|
326
328
|
}
|
|
327
329
|
|
|
328
330
|
return {
|
|
329
|
-
pruneChallenges,
|
|
330
|
-
|
|
331
331
|
async createRegisterOptions(ctx, user) {
|
|
332
332
|
const ps = requirePasskeyStore(store)
|
|
333
333
|
const existing = await sessions.observeAsync(ps.listPasskeys(user.id))
|
|
334
334
|
const rpId = resolveRpId(ctx)
|
|
335
335
|
const rpName = options?.rpName ?? rpId
|
|
336
|
-
const challenge = issueChallenge(ctx, 'register', user.id)
|
|
336
|
+
const challenge = await issueChallenge(ctx, 'register', user.id)
|
|
337
337
|
return {
|
|
338
338
|
challenge,
|
|
339
339
|
rp: { name: rpName, id: rpId },
|
|
@@ -361,8 +361,8 @@ export function createPasskeyManager<TUser extends AuthUser = AuthUser>(deps: Pa
|
|
|
361
361
|
}
|
|
362
362
|
},
|
|
363
363
|
|
|
364
|
-
verifyRegistration(ctx, userId, input) {
|
|
365
|
-
return performRegistrationVerify(store, sessions, userId, input, ceremonyFor(ctx, 'register', userId))
|
|
364
|
+
async verifyRegistration(ctx, userId, input) {
|
|
365
|
+
return performRegistrationVerify(store, sessions, userId, input, await ceremonyFor(ctx, 'register', userId))
|
|
366
366
|
},
|
|
367
367
|
|
|
368
368
|
async createAssertionOptions(ctx, purpose, opts) {
|
|
@@ -381,20 +381,14 @@ export function createPasskeyManager<TUser extends AuthUser = AuthUser>(deps: Pa
|
|
|
381
381
|
}))
|
|
382
382
|
}
|
|
383
383
|
else if (opts?.email) {
|
|
384
|
+
// The same shape whether the email has passkeys, has none or is unknown, so the answer never tells which: no transports, and a decoy id in place of none.
|
|
384
385
|
const user = await sessions.observeAsync(store.getUserByEmail(opts.email))
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
allowCredentials = list.map(p => ({
|
|
389
|
-
type: 'public-key',
|
|
390
|
-
id: p.id,
|
|
391
|
-
...(p.transports ? { transports: p.transports } : {}),
|
|
392
|
-
}))
|
|
393
|
-
}
|
|
394
|
-
}
|
|
386
|
+
const list = user ? await sessions.observeAsync(ps.listPasskeys(user.id)) : []
|
|
387
|
+
const ids = list.length > 0 ? list.map(p => p.id) : [decoyCredentialId(secret(), opts.email)]
|
|
388
|
+
allowCredentials = ids.map(id => ({ type: 'public-key', id }))
|
|
395
389
|
}
|
|
396
390
|
|
|
397
|
-
const challenge = issueChallenge(ctx, purpose, opts?.userId)
|
|
391
|
+
const challenge = await issueChallenge(ctx, purpose, opts?.userId)
|
|
398
392
|
return {
|
|
399
393
|
challenge,
|
|
400
394
|
timeout: CHALLENGE_TTL_MS,
|
|
@@ -404,8 +398,8 @@ export function createPasskeyManager<TUser extends AuthUser = AuthUser>(deps: Pa
|
|
|
404
398
|
}
|
|
405
399
|
},
|
|
406
400
|
|
|
407
|
-
verifyAssertion(ctx, purpose, input, expectedUserId) {
|
|
408
|
-
return performAssertionVerify(store, sessions, input, ceremonyFor(ctx, purpose, expectedUserId), expectedUserId)
|
|
401
|
+
async verifyAssertion(ctx, purpose, input, expectedUserId) {
|
|
402
|
+
return performAssertionVerify(store, sessions, input, await ceremonyFor(ctx, purpose, expectedUserId), expectedUserId)
|
|
409
403
|
},
|
|
410
404
|
|
|
411
405
|
async listPasskeys(userId) {
|
package/src/routes.ts
CHANGED
|
@@ -30,6 +30,29 @@ function respondVerificationAccepted(ctx: RequestContext, redirectTarget: string
|
|
|
30
30
|
return ctx.redirect(formPagePath(ctx, 'notice', sent.code) ?? redirectTarget, 303)
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
+
type UnverifiedPatch<TUser extends AuthUser> = Partial<Omit<TUser, 'id' | 'createdAt' | 'email'>>
|
|
34
|
+
|
|
35
|
+
// The sign-up rollback's writes, which must lose to a verification: atomic through the store's own methods, else a read then a write.
|
|
36
|
+
async function updateIfUnverified<TUser extends AuthUser>({ store, sessions }: AuthRoutesDeps<TUser>, id: string, updatedAt: number, patch: UnverifiedPatch<TUser>): Promise<void> {
|
|
37
|
+
if (store.updateUserIfUnverified) {
|
|
38
|
+
await sessions.observeAsync(store.updateUserIfUnverified(id, updatedAt, patch))
|
|
39
|
+
return
|
|
40
|
+
}
|
|
41
|
+
const cur = await sessions.observeAsync(store.getUserById(id))
|
|
42
|
+
if (cur && !cur.emailVerified && cur.updatedAt === updatedAt)
|
|
43
|
+
await sessions.observeAsync(store.updateUser(id, patch as Partial<Omit<TUser, 'id' | 'createdAt'>>))
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function deleteIfUnverified<TUser extends AuthUser>({ store, sessions }: AuthRoutesDeps<TUser>, id: string, updatedAt: number): Promise<void> {
|
|
47
|
+
if (store.deleteUserIfUnverified) {
|
|
48
|
+
await sessions.observeAsync(store.deleteUserIfUnverified(id, updatedAt))
|
|
49
|
+
return
|
|
50
|
+
}
|
|
51
|
+
const cur = await sessions.observeAsync(store.getUserById(id))
|
|
52
|
+
if (cur && !cur.emailVerified && cur.updatedAt === updatedAt)
|
|
53
|
+
await sessions.observeAsync(store.deleteUser(id))
|
|
54
|
+
}
|
|
55
|
+
|
|
33
56
|
// A second sign-up on an unverified address contests it: the mailbox owner cannot tell whose mailed link they click, so neither party's password or name is kept, and the link alone signs the owner in (#75).
|
|
34
57
|
async function reRegisterUnverified<TUser extends AuthUser>(
|
|
35
58
|
deps: AuthRoutesDeps<TUser>,
|
|
@@ -49,12 +72,11 @@ async function reRegisterUnverified<TUser extends AuthUser>(
|
|
|
49
72
|
await sessions.observeAsync(store.deleteUserSessions(existing.id))
|
|
50
73
|
await sessions.observeAsync(store.deleteUserOAuthAccounts(existing.id))
|
|
51
74
|
const patch = { passwordHash: undefined, name: undefined } as Partial<Omit<TUser, 'id' | 'createdAt'>>
|
|
52
|
-
|
|
75
|
+
// A store's updateUser may return nothing, so the cleared state is read back for the rollback to compare against.
|
|
76
|
+
const cleared = await sessions.observeAsync(store.updateUser(existing.id, patch)) ?? await sessions.observeAsync(store.getUserById(existing.id))
|
|
53
77
|
const restore = async (): Promise<void> => {
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
return
|
|
57
|
-
await sessions.observeAsync(store.updateUser(existing.id, { passwordHash: prevHash, name: prevName } as Partial<Omit<TUser, 'id' | 'createdAt'>>))
|
|
78
|
+
if (cleared)
|
|
79
|
+
await updateIfUnverified(deps, existing.id, cleared.updatedAt, { passwordHash: prevHash, name: prevName } as UnverifiedPatch<TUser>)
|
|
58
80
|
}
|
|
59
81
|
try {
|
|
60
82
|
await issueLink('verify-email', existing.id, existing.email, linkOrigin, redirectTarget, { onFailure: restore })
|
|
@@ -134,12 +156,7 @@ async function signUpPendingVerification<TUser extends AuthUser>(
|
|
|
134
156
|
throw err
|
|
135
157
|
}
|
|
136
158
|
|
|
137
|
-
const deleteIfUnchanged =
|
|
138
|
-
const cur = await sessions.observeAsync(store.getUserById(user.id))
|
|
139
|
-
if (!cur || cur.emailVerified || cur.updatedAt !== user.updatedAt)
|
|
140
|
-
return
|
|
141
|
-
await sessions.observeAsync(store.deleteUser(user.id))
|
|
142
|
-
}
|
|
159
|
+
const deleteIfUnchanged = (): Promise<void> => deleteIfUnverified(deps, user.id, user.updatedAt)
|
|
143
160
|
try {
|
|
144
161
|
// A mail outage deletes the account once the send fails, so it does not lock the address out.
|
|
145
162
|
await issueLink('verify-email', user.id, user.email, linkOrigin, redirectTarget, { onFailure: deleteIfUnchanged })
|
package/src/sqlite-ext.ts
CHANGED
|
@@ -14,7 +14,7 @@ import type {
|
|
|
14
14
|
UserExportExt,
|
|
15
15
|
UserOrgSummary,
|
|
16
16
|
} from './store-ext'
|
|
17
|
-
import { toPasskeySummary } from './store-ext'
|
|
17
|
+
import { toPasskeySummary, userInvitationsExport } from './store-ext'
|
|
18
18
|
|
|
19
19
|
interface TotpRow {
|
|
20
20
|
user_id: string
|
|
@@ -504,7 +504,7 @@ export function createSqliteStoreExt(db: Database): SqliteStoreExtHooks {
|
|
|
504
504
|
exportUserExt(userId, email, now) {
|
|
505
505
|
const q = ensureIfPresent()
|
|
506
506
|
if (!q)
|
|
507
|
-
return { passkeys: [], organizations: [], invitations: [] }
|
|
507
|
+
return { passkeys: [], organizations: [], invitations: [], sentInvitations: [] }
|
|
508
508
|
const totpRec = rowToTotp(q.getTotp.get(userId))
|
|
509
509
|
const rcCount = q.listRecovery.all(userId).length
|
|
510
510
|
const passkeys = q.listPasskeys.all(userId).map(r => toPasskeySummary(rowToPasskey(r)!))
|
|
@@ -515,19 +515,13 @@ export function createSqliteStoreExt(db: Database): SqliteStoreExtHooks {
|
|
|
515
515
|
role: r.role,
|
|
516
516
|
joinedAt: r.joined_at,
|
|
517
517
|
}))
|
|
518
|
-
const
|
|
519
|
-
|
|
520
|
-
orgId: r.org_id,
|
|
521
|
-
email: r.email,
|
|
522
|
-
role: r.role,
|
|
523
|
-
expiresAt: r.expires_at,
|
|
524
|
-
createdAt: r.created_at,
|
|
525
|
-
}))
|
|
518
|
+
const normEmail = email.trim().toLowerCase()
|
|
519
|
+
const invites = q.listUserInvites.all(normEmail, userId, now).map(r => rowToInvite(r)!)
|
|
526
520
|
return {
|
|
527
521
|
...(totpRec ? { totp: { enabled: totpRec.enabled, createdAt: totpRec.createdAt, recoveryCodesRemaining: rcCount } } : {}),
|
|
528
522
|
passkeys,
|
|
529
523
|
organizations,
|
|
530
|
-
|
|
524
|
+
...userInvitationsExport(invites, normEmail, userId),
|
|
531
525
|
}
|
|
532
526
|
},
|
|
533
527
|
deleteUserExt(userId, email) {
|
package/src/sqlite.ts
CHANGED
|
@@ -205,6 +205,42 @@ function userDeletion(
|
|
|
205
205
|
})
|
|
206
206
|
}
|
|
207
207
|
|
|
208
|
+
/** A user's updates: a plain patch, and the sign-up rollback's conditional ones, whose compare and write run in one immediate transaction so a verification from another connection lands before or after, never between. */
|
|
209
|
+
function userWrites(
|
|
210
|
+
db: Database,
|
|
211
|
+
q: ReturnType<typeof prepareCoreQueries>,
|
|
212
|
+
delUserTx: (userId: string) => void,
|
|
213
|
+
) {
|
|
214
|
+
function writeUserPatch(id: string, patch: Partial<AuthUser>): AuthUser | undefined {
|
|
215
|
+
const cur = rowToUser(q.qUserById.get(id))
|
|
216
|
+
if (!cur)
|
|
217
|
+
return undefined
|
|
218
|
+
const next: AuthUser = {
|
|
219
|
+
...cur,
|
|
220
|
+
...patch,
|
|
221
|
+
email: patch.email !== undefined ? normalizeEmail(patch.email) : cur.email,
|
|
222
|
+
updatedAt: patch.updatedAt ?? Date.now(),
|
|
223
|
+
}
|
|
224
|
+
q.qUpdateUser.run(next.email, next.name ?? null, next.avatarUrl ?? null, next.role, next.emailVerified ? 1 : 0, next.passwordHash ?? null, next.updatedAt, id)
|
|
225
|
+
return next
|
|
226
|
+
}
|
|
227
|
+
const isUnchangedUnverified = (id: string, updatedAt: number): boolean => {
|
|
228
|
+
const cur = rowToUser(q.qUserById.get(id))
|
|
229
|
+
return cur !== undefined && !cur.emailVerified && cur.updatedAt === updatedAt
|
|
230
|
+
}
|
|
231
|
+
return {
|
|
232
|
+
writeUserPatch,
|
|
233
|
+
updateIfUnverifiedTx: db.transaction((id: string, updatedAt: number, patch: Partial<Omit<AuthUser, 'id' | 'createdAt' | 'email'>>) =>
|
|
234
|
+
isUnchangedUnverified(id, updatedAt) && writeUserPatch(id, patch) !== undefined),
|
|
235
|
+
deleteIfUnverifiedTx: db.transaction((id: string, updatedAt: number) => {
|
|
236
|
+
if (!isUnchangedUnverified(id, updatedAt))
|
|
237
|
+
return false
|
|
238
|
+
delUserTx(id)
|
|
239
|
+
return true
|
|
240
|
+
}),
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
208
244
|
function exportSqliteUser(
|
|
209
245
|
q: ReturnType<typeof prepareCoreQueries>,
|
|
210
246
|
ext: ReturnType<typeof createSqliteStoreExt>,
|
|
@@ -296,7 +332,7 @@ function openSqliteAuthStore(dbOrPath: string | Database): SqliteAuthStore {
|
|
|
296
332
|
createSchema(db)
|
|
297
333
|
const queries = prepareCoreQueries(db)
|
|
298
334
|
const {
|
|
299
|
-
qUserById, qUnverifiedUserIds, qUserByEmail, qInsertUser,
|
|
335
|
+
qUserById, qUnverifiedUserIds, qUserByEmail, qInsertUser,
|
|
300
336
|
qGetSession, qListUserSessions, qInsertSession, qTouchSession, qDelSession, qDelUserSessions,
|
|
301
337
|
qGetOAuth, qLinkOAuth, qDelUserOAuth,
|
|
302
338
|
qInsertToken, qConsumeToken,
|
|
@@ -305,6 +341,7 @@ function openSqliteAuthStore(dbOrPath: string | Database): SqliteAuthStore {
|
|
|
305
341
|
const ext = createSqliteStoreExt(db)
|
|
306
342
|
|
|
307
343
|
const delUserTx = userDeletion(db, queries, ext)
|
|
344
|
+
const { writeUserPatch, updateIfUnverifiedTx, deleteIfUnverifiedTx } = userWrites(db, queries, delUserTx)
|
|
308
345
|
|
|
309
346
|
function listActiveSessions(userId: string): AuthSession[] {
|
|
310
347
|
return qListUserSessions.all(userId, Date.now()).map(row => rowToSession(row)!)
|
|
@@ -353,30 +390,17 @@ function openSqliteAuthStore(dbOrPath: string | Database): SqliteAuthStore {
|
|
|
353
390
|
return norm
|
|
354
391
|
},
|
|
355
392
|
updateUser(id, patch) {
|
|
356
|
-
|
|
357
|
-
if (!cur)
|
|
358
|
-
return undefined
|
|
359
|
-
const next: AuthUser = {
|
|
360
|
-
...cur,
|
|
361
|
-
...patch,
|
|
362
|
-
email: patch.email !== undefined ? normalizeEmail(patch.email) : cur.email,
|
|
363
|
-
updatedAt: patch.updatedAt ?? Date.now(),
|
|
364
|
-
}
|
|
365
|
-
qUpdateUser.run(
|
|
366
|
-
next.email,
|
|
367
|
-
next.name ?? null,
|
|
368
|
-
next.avatarUrl ?? null,
|
|
369
|
-
next.role,
|
|
370
|
-
next.emailVerified ? 1 : 0,
|
|
371
|
-
next.passwordHash ?? null,
|
|
372
|
-
next.updatedAt,
|
|
373
|
-
id,
|
|
374
|
-
)
|
|
375
|
-
return next
|
|
393
|
+
return writeUserPatch(id, patch)
|
|
376
394
|
},
|
|
377
395
|
deleteUser(userId) {
|
|
378
396
|
delUserTx(userId)
|
|
379
397
|
},
|
|
398
|
+
updateUserIfUnverified(id, updatedAt, patch) {
|
|
399
|
+
return updateIfUnverifiedTx.immediate(id, updatedAt, patch)
|
|
400
|
+
},
|
|
401
|
+
deleteUserIfUnverified(id, updatedAt) {
|
|
402
|
+
return deleteIfUnverifiedTx.immediate(id, updatedAt)
|
|
403
|
+
},
|
|
380
404
|
exportUser(userId): UserExport | null {
|
|
381
405
|
return exportSqliteUser(queries, ext, userId)
|
|
382
406
|
},
|
package/src/store-ext.ts
CHANGED
|
@@ -80,7 +80,19 @@ export interface UserExportExt {
|
|
|
80
80
|
totp?: { enabled: boolean, createdAt: number, recoveryCodesRemaining: number } | undefined
|
|
81
81
|
passkeys?: PasskeySummary[] | undefined
|
|
82
82
|
organizations?: Array<{ orgId: string, slug: string, name: string, role: string, joinedAt: number }> | undefined
|
|
83
|
+
/** Pending invitations to the user's own email. */
|
|
83
84
|
invitations?: Array<{ id: string, orgId: string, email: string, role: string, expiresAt: number, createdAt: number }> | undefined
|
|
85
|
+
/** Pending invitations the user sent, without the invitee's email: that address is the invitee's data, not the sender's. */
|
|
86
|
+
sentInvitations?: Array<{ id: string, orgId: string, role: string, expiresAt: number, createdAt: number }> | undefined
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Splits the unexpired invitations naming a user into the ones they received and the ones they sent, oldest first. */
|
|
90
|
+
export function userInvitationsExport(invites: readonly OrgInvitation[], email: string, userId: string): Required<Pick<UserExportExt, 'invitations' | 'sentInvitations'>> {
|
|
91
|
+
const sorted = [...invites].sort((a, b) => a.createdAt - b.createdAt)
|
|
92
|
+
return {
|
|
93
|
+
invitations: sorted.filter(inv => inv.email === email).map(({ id, orgId, email, role, expiresAt, createdAt }) => ({ id, orgId, email, role, expiresAt, createdAt })),
|
|
94
|
+
sentInvitations: sorted.filter(inv => inv.invitedBy === userId).map(({ id, orgId, role, expiresAt, createdAt }) => ({ id, orgId, role, expiresAt, createdAt })),
|
|
95
|
+
}
|
|
84
96
|
}
|
|
85
97
|
|
|
86
98
|
export type UpdateOrgMemberRoleResult
|
|
@@ -445,30 +457,18 @@ export function createMemoryStoreExt(): MemoryStoreExtHooks {
|
|
|
445
457
|
role: item.role,
|
|
446
458
|
joinedAt: item.joinedAt,
|
|
447
459
|
}))
|
|
448
|
-
const
|
|
449
|
-
const normEmail = email.trim().toLowerCase()
|
|
460
|
+
const live: OrgInvitation[] = []
|
|
450
461
|
for (const [k, inv] of state.orgInvites) {
|
|
451
|
-
if (inv.expiresAt <= now)
|
|
462
|
+
if (inv.expiresAt <= now)
|
|
452
463
|
state.orgInvites.delete(k)
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
if (inv.email === normEmail || inv.invitedBy === userId) {
|
|
456
|
-
invitations.push({
|
|
457
|
-
id: inv.id,
|
|
458
|
-
orgId: inv.orgId,
|
|
459
|
-
email: inv.email,
|
|
460
|
-
role: inv.role,
|
|
461
|
-
expiresAt: inv.expiresAt,
|
|
462
|
-
createdAt: inv.createdAt,
|
|
463
|
-
})
|
|
464
|
-
}
|
|
464
|
+
else
|
|
465
|
+
live.push(inv)
|
|
465
466
|
}
|
|
466
|
-
invitations.sort((a, b) => a.createdAt - b.createdAt)
|
|
467
467
|
return {
|
|
468
468
|
...(totpRec ? { totp: { enabled: totpRec.enabled, createdAt: totpRec.createdAt, recoveryCodesRemaining: rcCount } } : {}),
|
|
469
469
|
passkeys: userPasskeys,
|
|
470
470
|
organizations,
|
|
471
|
-
|
|
471
|
+
...userInvitationsExport(live, email.trim().toLowerCase(), userId),
|
|
472
472
|
}
|
|
473
473
|
},
|
|
474
474
|
deleteUserExt(userId, email) {
|
package/src/store.ts
CHANGED
|
@@ -48,8 +48,8 @@ export interface OAuthAccount {
|
|
|
48
48
|
createdAt: number
|
|
49
49
|
}
|
|
50
50
|
|
|
51
|
-
/** Verification token purposes. `'reset-password'` is reserved for app-defined password-reset flows via `store.createToken`/`store.consumeToken
|
|
52
|
-
export type TokenKind = 'magic-link' | 'verify-email' | 'reset-password'
|
|
51
|
+
/** Verification token purposes. `'reset-password'` is reserved for app-defined password-reset flows via `store.createToken`/`store.consumeToken`; `'passkey-challenge'` holds a WebAuthn challenge, with no user and an empty email, for 5 minutes. */
|
|
52
|
+
export type TokenKind = 'magic-link' | 'verify-email' | 'reset-password' | 'passkey-challenge'
|
|
53
53
|
|
|
54
54
|
export interface VerificationToken {
|
|
55
55
|
tokenHash: string
|
|
@@ -76,6 +76,10 @@ export interface AuthStore<TUser extends AuthUser = AuthUser> extends AuthStoreE
|
|
|
76
76
|
createUser(user: TUser): TUser | Promise<TUser>
|
|
77
77
|
updateUser(id: string, patch: Partial<Omit<TUser, 'id' | 'createdAt'>>): TUser | undefined | Promise<TUser | undefined>
|
|
78
78
|
deleteUser(userId: string): void | Promise<void>
|
|
79
|
+
/** Applies `patch` only while the user is unverified and was last updated at `updatedAt`, in one step, so a verification landing first wins; `true` when it wrote. Optional: without it the sign-up rollback reads then writes, and can overwrite a verification landing in between. */
|
|
80
|
+
updateUserIfUnverified?(id: string, updatedAt: number, patch: Partial<Omit<TUser, 'id' | 'createdAt' | 'email'>>): boolean | Promise<boolean>
|
|
81
|
+
/** Deletes the user only while unverified and last updated at `updatedAt`, in one step; `true` when it deleted. Optional, like `updateUserIfUnverified`. */
|
|
82
|
+
deleteUserIfUnverified?(id: string, updatedAt: number): boolean | Promise<boolean>
|
|
79
83
|
exportUser(userId: string): UserExport<TUser> | null | Promise<UserExport<TUser> | null>
|
|
80
84
|
|
|
81
85
|
getSession(tokenHash: string): AuthSession | undefined | Promise<AuthSession | undefined>
|
|
@@ -255,6 +259,20 @@ export function memoryAuthStore<TUser extends AuthUser = AuthUser>(): AuthStore<
|
|
|
255
259
|
deleteUser(userId) {
|
|
256
260
|
deleteMemoryUser(state, ext, userId)
|
|
257
261
|
},
|
|
262
|
+
updateUserIfUnverified(userId, updatedAt, patch) {
|
|
263
|
+
const cur = state.users.get(userId)
|
|
264
|
+
if (!cur || cur.emailVerified || cur.updatedAt !== updatedAt)
|
|
265
|
+
return false
|
|
266
|
+
state.users.set(userId, { ...cur, ...patch, email: cur.email, updatedAt: Date.now() })
|
|
267
|
+
return true
|
|
268
|
+
},
|
|
269
|
+
deleteUserIfUnverified(userId, updatedAt) {
|
|
270
|
+
const cur = state.users.get(userId)
|
|
271
|
+
if (!cur || cur.emailVerified || cur.updatedAt !== updatedAt)
|
|
272
|
+
return false
|
|
273
|
+
deleteMemoryUser(state, ext, userId)
|
|
274
|
+
return true
|
|
275
|
+
},
|
|
258
276
|
exportUser(userId) {
|
|
259
277
|
return exportMemoryUser(state, ext, userId)
|
|
260
278
|
},
|