@prunellejs/auth 0.1.1 → 0.7.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.
@@ -0,0 +1,210 @@
1
+ // HTTP routes for WebAuthn passkeys: registration, passwordless login, 2FA verification, listing, and deletion.
2
+
3
+ import type { RequestContext } from 'prunelle/server'
4
+ import type { AuthRouteRegistrar } from './http'
5
+ import type { AssertionVerifyInput, PasskeyError, PasskeyManager, RegisterVerifyInput } from './passkeys'
6
+ import type { SessionManager } from './session'
7
+ import type { AuthStore, AuthUser } from './store'
8
+ import type { TotpManager } from './totp'
9
+ import { safeRedirect, wantsJson } from 'prunelle/server'
10
+ import { fail, parseJsonBody } from './http'
11
+ import { toPublicUser } from './store'
12
+
13
+ export interface PasskeyRoutesDeps<TUser extends AuthUser = AuthUser> {
14
+ authRoute: AuthRouteRegistrar
15
+ store: AuthStore<TUser>
16
+ sessions: SessionManager<TUser>
17
+ passkeys: PasskeyManager
18
+ totp: TotpManager
19
+ defaultRedirect: string
20
+ requireEmailVerification: boolean
21
+ }
22
+
23
+ function respondPasskeyErr(ctx: RequestContext, err: unknown): Response {
24
+ const pe = err as Partial<PasskeyError>
25
+ const status = typeof pe?.status === 'number' ? pe.status : 400
26
+ const message = err instanceof Error ? err.message : 'Passkey verification failed'
27
+ return fail(ctx, status, message)
28
+ }
29
+
30
+ function asRegisterInput(body: Record<string, unknown>): RegisterVerifyInput | undefined {
31
+ const resp = body.response
32
+ if (resp === null || typeof resp !== 'object' || Array.isArray(resp))
33
+ return undefined
34
+ const r = resp as Record<string, unknown>
35
+ if (typeof r.clientDataJSON !== 'string' || typeof r.attestationObject !== 'string')
36
+ return undefined
37
+ const transports = Array.isArray(r.transports) ? r.transports.filter((t): t is string => typeof t === 'string') : undefined
38
+ return {
39
+ ...(typeof body.id === 'string' ? { id: body.id } : {}),
40
+ ...(typeof body.rawId === 'string' ? { rawId: body.rawId } : {}),
41
+ ...(typeof body.name === 'string' ? { name: body.name } : {}),
42
+ response: {
43
+ clientDataJSON: r.clientDataJSON,
44
+ attestationObject: r.attestationObject,
45
+ ...(transports !== undefined ? { transports } : {}),
46
+ },
47
+ }
48
+ }
49
+
50
+ function asAssertionInput(body: Record<string, unknown>): AssertionVerifyInput | undefined {
51
+ const resp = body.response
52
+ if (resp === null || typeof resp !== 'object' || Array.isArray(resp))
53
+ return undefined
54
+ const r = resp as Record<string, unknown>
55
+ if (typeof r.clientDataJSON !== 'string' || typeof r.authenticatorData !== 'string' || typeof r.signature !== 'string')
56
+ return undefined
57
+ return {
58
+ ...(typeof body.id === 'string' ? { id: body.id } : {}),
59
+ ...(typeof body.rawId === 'string' ? { rawId: body.rawId } : {}),
60
+ response: {
61
+ clientDataJSON: r.clientDataJSON,
62
+ authenticatorData: r.authenticatorData,
63
+ signature: r.signature,
64
+ ...(typeof r.userHandle === 'string' ? { userHandle: r.userHandle } : {}),
65
+ },
66
+ }
67
+ }
68
+
69
+ export function registerPasskeyRoutes<TUser extends AuthUser = AuthUser>(deps: PasskeyRoutesDeps<TUser>): void {
70
+ const { authRoute, store, sessions, passkeys, totp, defaultRedirect, requireEmailVerification } = deps
71
+
72
+ authRoute('POST', '/passkeys/register/options', { limit: 'passkey-reg' }, async (ctx) => {
73
+ const resolved = await sessions.resolve(ctx)
74
+ if (!resolved)
75
+ return fail(ctx, 401, 'Authentication required')
76
+ try {
77
+ const options = await passkeys.createRegisterOptions(ctx, resolved.user)
78
+ return ctx.json({ ok: true, options }, { status: 200 })
79
+ }
80
+ catch (err) {
81
+ return respondPasskeyErr(ctx, err)
82
+ }
83
+ })
84
+
85
+ authRoute('POST', '/passkeys/register/verify', { limit: 'passkey-reg' }, async (ctx) => {
86
+ const resolved = await sessions.resolve(ctx)
87
+ if (!resolved)
88
+ return fail(ctx, 401, 'Authentication required')
89
+ const raw = await parseJsonBody(ctx)
90
+ if (raw instanceof Response)
91
+ return raw
92
+ const input = asRegisterInput(raw)
93
+ if (!input)
94
+ return fail(ctx, 400, 'Invalid passkey registration payload')
95
+ try {
96
+ const passkey = await passkeys.verifyRegistration(ctx, resolved.user.id, input)
97
+ return ctx.json({ ok: true, passkey }, { status: 201 })
98
+ }
99
+ catch (err) {
100
+ return respondPasskeyErr(ctx, err)
101
+ }
102
+ })
103
+
104
+ authRoute('POST', '/passkeys/login/options', { limit: 'passkey-login' }, async (ctx) => {
105
+ const raw = await parseJsonBody(ctx)
106
+ if (raw instanceof Response)
107
+ return raw
108
+ const email = typeof raw.email === 'string' && raw.email.trim() ? raw.email.trim() : undefined
109
+ try {
110
+ const options = await passkeys.createAssertionOptions(ctx, 'login', { email })
111
+ return ctx.json({ ok: true, options }, { status: 200 })
112
+ }
113
+ catch (err) {
114
+ return respondPasskeyErr(ctx, err)
115
+ }
116
+ })
117
+
118
+ authRoute('POST', '/passkeys/login/verify', { limit: 'passkey-login' }, async (ctx) => {
119
+ const raw = await parseJsonBody(ctx)
120
+ if (raw instanceof Response)
121
+ return raw
122
+ const input = asAssertionInput(raw)
123
+ if (!input)
124
+ return fail(ctx, 400, 'Invalid passkey assertion payload')
125
+ try {
126
+ const { userId } = await passkeys.verifyAssertion(ctx, 'login', input)
127
+ const userRecord = await sessions.observeAsync(store.getUserById(userId))
128
+ if (!userRecord)
129
+ return fail(ctx, 401, 'Unable to resolve user account')
130
+ if (requireEmailVerification && !userRecord.emailVerified)
131
+ return fail(ctx, 403, 'Email not verified')
132
+
133
+ const pub = toPublicUser(userRecord)
134
+ await sessions.createSessionForUser(userRecord.id, ctx, pub)
135
+ const redirect = safeRedirect(typeof raw.redirect === 'string' ? raw.redirect : (typeof raw.next === 'string' ? raw.next : undefined), defaultRedirect)
136
+ if (wantsJson(ctx.request))
137
+ return ctx.json({ ok: true, user: pub }, { status: 200 })
138
+ return ctx.redirect(redirect, 303)
139
+ }
140
+ catch (err) {
141
+ return respondPasskeyErr(ctx, err)
142
+ }
143
+ })
144
+
145
+ authRoute('POST', '/passkeys/2fa/options', { limit: 'passkey-2fa' }, async (ctx) => {
146
+ const pending = totp.readPendingCookie(ctx)
147
+ if (!pending)
148
+ return fail(ctx, 401, 'Two-factor session expired or invalid')
149
+ try {
150
+ const options = await passkeys.createAssertionOptions(ctx, '2fa', { userId: pending.userId })
151
+ return ctx.json({ ok: true, options }, { status: 200 })
152
+ }
153
+ catch (err) {
154
+ return respondPasskeyErr(ctx, err)
155
+ }
156
+ })
157
+
158
+ authRoute('POST', '/passkeys/2fa/verify', { limit: 'passkey-2fa' }, async (ctx) => {
159
+ const pending = totp.readPendingCookie(ctx)
160
+ if (!pending)
161
+ return fail(ctx, 401, 'Two-factor session expired or invalid')
162
+ const raw = await parseJsonBody(ctx)
163
+ if (raw instanceof Response)
164
+ return raw
165
+ const input = asAssertionInput(raw)
166
+ if (!input)
167
+ return fail(ctx, 400, 'Invalid passkey assertion payload')
168
+ try {
169
+ await passkeys.verifyAssertion(ctx, '2fa', input, pending.userId)
170
+ const userRecord = await sessions.observeAsync(store.getUserById(pending.userId))
171
+ if (!userRecord) {
172
+ totp.clearPendingCookie(ctx)
173
+ return fail(ctx, 401, 'Unable to resolve user account')
174
+ }
175
+ totp.clearPendingCookie(ctx)
176
+ const pub = toPublicUser(userRecord)
177
+ await sessions.createSessionForUser(userRecord.id, ctx, pub)
178
+ const redirect = safeRedirect(typeof raw.redirect === 'string' ? raw.redirect : (typeof raw.next === 'string' ? raw.next : pending.redirect), defaultRedirect)
179
+ if (wantsJson(ctx.request))
180
+ return ctx.json({ ok: true, user: pub }, { status: 200 })
181
+ return ctx.redirect(redirect, 303)
182
+ }
183
+ catch (err) {
184
+ return respondPasskeyErr(ctx, err)
185
+ }
186
+ })
187
+
188
+ authRoute('GET', '/passkeys', {}, async (ctx) => {
189
+ const resolved = await sessions.resolve(ctx)
190
+ if (!resolved)
191
+ return fail(ctx, 401, 'Authentication required')
192
+ const list = await passkeys.listPasskeys(resolved.user.id)
193
+ return ctx.json({ ok: true, passkeys: list }, { status: 200 })
194
+ })
195
+
196
+ authRoute('POST', '/passkeys/delete', { limit: 'passkey-del', readBody: true }, async (ctx, body) => {
197
+ const resolved = await sessions.resolve(ctx)
198
+ if (!resolved)
199
+ return fail(ctx, 401, 'Authentication required')
200
+ const credentialId = (body.id ?? body.credentialId ?? '').trim()
201
+ if (!credentialId)
202
+ return fail(ctx, 400, 'Passkey id is required')
203
+ const deleted = await passkeys.deletePasskey(resolved.user.id, credentialId)
204
+ if (!deleted)
205
+ return fail(ctx, 404, 'Passkey not found')
206
+ if (wantsJson(ctx.request))
207
+ return ctx.json({ ok: true }, { status: 200 })
208
+ return ctx.redirect(safeRedirect(body.redirect ?? body.next, defaultRedirect), 303)
209
+ })
210
+ }
@@ -0,0 +1,421 @@
1
+ // WebAuthn L2 passkey registration and assertion verification (passwordless sign-in + 2FA).
2
+
3
+ import type { RequestContext } from 'prunelle/server'
4
+ import type { SessionManager } from './session'
5
+ import type { AuthStore, AuthUser, PasskeyRecord, PasskeySummary } from './store'
6
+ import { safeEqual } from 'prunelle/server'
7
+ import { fromBase64Url, randomToken, sha256Bytes, signPayload, toBase64Url, verifyPayload } from './crypto'
8
+ import { authCookie } from './http'
9
+ import { toPasskeySummary } from './store'
10
+ import { COSE_ALG_EDDSA, COSE_ALG_ES256, COSE_ALG_RS256, coseKeyToJwk, decodeCbor, parseAuthenticatorData, verifyWebAuthnSignature } from './webauthn-crypto'
11
+
12
+ const CHALLENGE_TTL_MS = 5 * 60 * 1000
13
+ const MAX_ACTIVE_CHALLENGES = 10_000
14
+
15
+ export type PasskeyUserVerification = 'required' | 'preferred' | 'discouraged'
16
+
17
+ export interface PasskeyOptions {
18
+ /** Relying Party ID (defaults to `site` or request hostname). */
19
+ rpId?: string | undefined
20
+ /** Relying Party display name (defaults to `rpId`). */
21
+ rpName?: string | undefined
22
+ /** Expected WebAuthn origin (defaults to `site` or request origin). */
23
+ origin?: string | undefined
24
+ /** Authenticator user verification requirement (default: `'preferred'`). */
25
+ userVerification?: PasskeyUserVerification | undefined
26
+ }
27
+
28
+ export interface PasskeyError extends Error {
29
+ status: number
30
+ }
31
+
32
+ function passkeyError(status: number, message: string): PasskeyError {
33
+ const err = new Error(message) as PasskeyError
34
+ err.status = status
35
+ return err
36
+ }
37
+
38
+ interface ChallengeCookiePayload {
39
+ challenge: string
40
+ purpose: 'register' | 'login' | '2fa'
41
+ userId?: string | undefined
42
+ exp: number
43
+ }
44
+
45
+ interface ClientDataPayload {
46
+ type?: unknown
47
+ challenge?: unknown
48
+ origin?: unknown
49
+ }
50
+
51
+ export interface RegisterVerifyInput {
52
+ id?: string | undefined
53
+ rawId?: string | undefined
54
+ name?: string | undefined
55
+ response: {
56
+ clientDataJSON: string
57
+ attestationObject: string
58
+ transports?: string[] | undefined
59
+ }
60
+ }
61
+
62
+ export interface AssertionVerifyInput {
63
+ id?: string | undefined
64
+ rawId?: string | undefined
65
+ response: {
66
+ clientDataJSON: string
67
+ authenticatorData: string
68
+ signature: string
69
+ userHandle?: string | undefined
70
+ }
71
+ }
72
+
73
+ export interface PasskeyManagerDeps<TUser extends AuthUser = AuthUser> {
74
+ store: AuthStore<TUser>
75
+ sessions: SessionManager<TUser>
76
+ /** The app's signing secret, resolved at first use. */
77
+ secret: () => string
78
+ challengeCookieName: string
79
+ getSite: () => string | undefined
80
+ options?: PasskeyOptions | undefined
81
+ isSecureCookie: (ctx: RequestContext) => boolean
82
+ }
83
+
84
+ export interface PasskeyManager {
85
+ createRegisterOptions(ctx: RequestContext, user: { id: string, email: string, name?: string | undefined }): Promise<Record<string, unknown>>
86
+ verifyRegistration(ctx: RequestContext, userId: string, input: RegisterVerifyInput): Promise<PasskeySummary>
87
+ createAssertionOptions(ctx: RequestContext, purpose: 'login' | '2fa', opts?: { userId?: string | undefined, email?: string | undefined }): Promise<Record<string, unknown>>
88
+ verifyAssertion(ctx: RequestContext, purpose: 'login' | '2fa', input: AssertionVerifyInput, expectedUserId?: string): Promise<{ passkey: PasskeyRecord, userId: string }>
89
+ listPasskeys(userId: string): Promise<PasskeySummary[]>
90
+ deletePasskey(userId: string, credentialId: string): Promise<boolean>
91
+ pruneChallenges(): void
92
+ }
93
+
94
+ function requirePasskeyStore<TUser extends AuthUser>(store: AuthStore<TUser>) {
95
+ if (!store.getPasskey || !store.listPasskeys || !store.createPasskey || !store.updatePasskeyUsage || !store.deletePasskey)
96
+ throw passkeyError(500, 'prunelle: configured AuthStore does not support passkeys')
97
+ return {
98
+ getPasskey: store.getPasskey.bind(store),
99
+ listPasskeys: store.listPasskeys.bind(store),
100
+ createPasskey: store.createPasskey.bind(store),
101
+ updatePasskeyUsage: store.updatePasskeyUsage.bind(store),
102
+ deletePasskey: store.deletePasskey.bind(store),
103
+ }
104
+ }
105
+
106
+ function parseClientData(clientDataB64: string, expectedType: string, expectedChallenge: string, expectedOrigin: string): Uint8Array {
107
+ let bytes: Uint8Array
108
+ let parsed: ClientDataPayload
109
+ try {
110
+ bytes = fromBase64Url(clientDataB64)
111
+ parsed = JSON.parse(new TextDecoder().decode(bytes)) as ClientDataPayload
112
+ }
113
+ catch {
114
+ throw passkeyError(400, 'Invalid clientDataJSON')
115
+ }
116
+ if (parsed.type !== expectedType)
117
+ throw passkeyError(400, `Unexpected WebAuthn ceremony type: expected ${expectedType}`)
118
+ if (typeof parsed.challenge !== 'string' || !safeEqual(parsed.challenge, expectedChallenge))
119
+ throw passkeyError(400, 'WebAuthn challenge mismatch')
120
+ if (typeof parsed.origin !== 'string' || parsed.origin !== expectedOrigin)
121
+ throw passkeyError(400, 'WebAuthn origin mismatch')
122
+ return bytes
123
+ }
124
+
125
+ function verifyRpIdAndFlags(rpIdHash: Uint8Array, rpId: string, up: boolean, uv: boolean, userVerification: PasskeyUserVerification): void {
126
+ const expectedHash = sha256Bytes(rpId)
127
+ if (!safeEqual(toBase64Url(rpIdHash), toBase64Url(expectedHash)))
128
+ throw passkeyError(400, 'WebAuthn rpIdHash mismatch')
129
+ if (!up)
130
+ throw passkeyError(400, 'WebAuthn user presence flag not set')
131
+ if (userVerification === 'required' && !uv)
132
+ throw passkeyError(400, 'WebAuthn user verification required')
133
+ }
134
+
135
+ interface CeremonyContext {
136
+ expectedChallenge: string
137
+ expectedOrigin: string
138
+ expectedRpId: string
139
+ userVerification: PasskeyUserVerification
140
+ }
141
+
142
+ async function performRegistrationVerify<TUser extends AuthUser>(
143
+ store: AuthStore<TUser>,
144
+ sessions: SessionManager<TUser>,
145
+ userId: string,
146
+ input: RegisterVerifyInput,
147
+ ceremony: CeremonyContext,
148
+ ): Promise<PasskeySummary> {
149
+ const ps = requirePasskeyStore(store)
150
+ parseClientData(input.response.clientDataJSON, 'webauthn.create', ceremony.expectedChallenge, ceremony.expectedOrigin)
151
+
152
+ let authDataBytes: Uint8Array
153
+ try {
154
+ const decoded = decodeCbor(fromBase64Url(input.response.attestationObject))
155
+ if (!(decoded.value instanceof Map))
156
+ throw new Error('attestationObject must be a CBOR map')
157
+ const rawAuthData = decoded.value.get('authData')
158
+ if (!(rawAuthData instanceof Uint8Array))
159
+ throw new Error('attestationObject missing authData')
160
+ authDataBytes = rawAuthData
161
+ }
162
+ catch (err) {
163
+ throw passkeyError(400, err instanceof Error ? err.message : 'Invalid attestationObject')
164
+ }
165
+
166
+ let parsed
167
+ try {
168
+ parsed = parseAuthenticatorData(authDataBytes)
169
+ }
170
+ catch (err) {
171
+ throw passkeyError(400, err instanceof Error ? err.message : 'Invalid authenticatorData')
172
+ }
173
+
174
+ verifyRpIdAndFlags(parsed.rpIdHash, ceremony.expectedRpId, parsed.up, parsed.uv, ceremony.userVerification)
175
+ if (!parsed.at || !parsed.credentialId || !parsed.cosePublicKey)
176
+ throw passkeyError(400, 'Attested credential data missing from registration')
177
+
178
+ let keyInfo: { algorithm: number, jwk: JsonWebKey }
179
+ try {
180
+ keyInfo = coseKeyToJwk(parsed.cosePublicKey)
181
+ }
182
+ catch (err) {
183
+ throw passkeyError(400, err instanceof Error ? err.message : 'Unsupported COSE public key')
184
+ }
185
+
186
+ const credentialId = toBase64Url(parsed.credentialId)
187
+ const providedId = input.id ?? input.rawId
188
+ if (providedId !== undefined && providedId !== credentialId)
189
+ throw passkeyError(400, 'Credential ID does not match attested credential data')
190
+
191
+ const duplicate = await sessions.observeAsync(ps.getPasskey(credentialId))
192
+ if (duplicate)
193
+ throw passkeyError(409, 'Passkey is already registered')
194
+
195
+ const transports = Array.isArray(input.response.transports)
196
+ ? input.response.transports.filter((t): t is string => typeof t === 'string')
197
+ : undefined
198
+ const record: PasskeyRecord = {
199
+ id: credentialId,
200
+ userId,
201
+ publicKeyJwk: JSON.stringify(keyInfo.jwk),
202
+ algorithm: keyInfo.algorithm,
203
+ signCount: parsed.signCount,
204
+ ...(transports && transports.length > 0 ? { transports } : {}),
205
+ ...(input.name?.trim() ? { name: input.name.trim() } : {}),
206
+ ...(parsed.aaguid !== undefined ? { aaguid: parsed.aaguid } : {}),
207
+ createdAt: Date.now(),
208
+ }
209
+ await sessions.observeAsync(ps.createPasskey(record))
210
+ return toPasskeySummary(record)
211
+ }
212
+
213
+ async function performAssertionVerify<TUser extends AuthUser>(
214
+ store: AuthStore<TUser>,
215
+ sessions: SessionManager<TUser>,
216
+ input: AssertionVerifyInput,
217
+ ceremony: CeremonyContext,
218
+ expectedUserId?: string,
219
+ ): Promise<{ passkey: PasskeyRecord, userId: string }> {
220
+ const ps = requirePasskeyStore(store)
221
+ const credentialId = input.id ?? input.rawId
222
+ if (!credentialId)
223
+ throw passkeyError(400, 'Missing credential ID')
224
+
225
+ const passkey = await sessions.observeAsync(ps.getPasskey(credentialId))
226
+ if (!passkey)
227
+ throw passkeyError(401, 'Unknown passkey credential')
228
+ if (expectedUserId !== undefined && passkey.userId !== expectedUserId)
229
+ throw passkeyError(401, 'Passkey does not belong to this account')
230
+
231
+ const clientDataBytes = parseClientData(input.response.clientDataJSON, 'webauthn.get', ceremony.expectedChallenge, ceremony.expectedOrigin)
232
+ const authDataBytes = fromBase64Url(input.response.authenticatorData)
233
+ const signatureBytes = fromBase64Url(input.response.signature)
234
+
235
+ let parsed
236
+ try {
237
+ parsed = parseAuthenticatorData(authDataBytes)
238
+ }
239
+ catch (err) {
240
+ throw passkeyError(400, err instanceof Error ? err.message : 'Invalid authenticatorData')
241
+ }
242
+
243
+ verifyRpIdAndFlags(parsed.rpIdHash, ceremony.expectedRpId, parsed.up, parsed.uv, ceremony.userVerification)
244
+
245
+ let signatureValid = false
246
+ try {
247
+ signatureValid = await verifyWebAuthnSignature(passkey.publicKeyJwk, passkey.algorithm, signatureBytes, authDataBytes, clientDataBytes)
248
+ }
249
+ catch {
250
+ signatureValid = false
251
+ }
252
+ if (!signatureValid)
253
+ throw passkeyError(401, 'Invalid passkey signature')
254
+
255
+ if (passkey.signCount > 0 && parsed.signCount <= passkey.signCount)
256
+ throw passkeyError(401, 'Passkey signature counter mismatch (possible cloned authenticator)')
257
+
258
+ const now = Date.now()
259
+ await sessions.observeAsync(ps.updatePasskeyUsage(passkey.id, parsed.signCount, now))
260
+ return { passkey: { ...passkey, signCount: parsed.signCount, lastUsedAt: now }, userId: passkey.userId }
261
+ }
262
+
263
+ export function createPasskeyManager<TUser extends AuthUser = AuthUser>(deps: PasskeyManagerDeps<TUser>): PasskeyManager {
264
+ const { store, sessions, secret, challengeCookieName, getSite, options, isSecureCookie } = deps
265
+ const userVerification: PasskeyUserVerification = options?.userVerification ?? 'preferred'
266
+ const activeChallenges = new Map<string, number>()
267
+
268
+ function resolveExpectedOrigin(ctx: RequestContext): string {
269
+ return options?.origin ?? getSite() ?? ctx.url.origin
270
+ }
271
+
272
+ function resolveRpId(ctx: RequestContext): string {
273
+ return options?.rpId ?? new URL(resolveExpectedOrigin(ctx)).hostname
274
+ }
275
+
276
+ function pruneChallenges(): void {
277
+ const now = Date.now()
278
+ for (const [ch, exp] of activeChallenges) {
279
+ if (exp <= now)
280
+ activeChallenges.delete(ch)
281
+ }
282
+ }
283
+
284
+ function issueChallenge(ctx: RequestContext, purpose: 'register' | 'login' | '2fa', userId?: string): string {
285
+ if (activeChallenges.size >= MAX_ACTIVE_CHALLENGES)
286
+ pruneChallenges()
287
+ const challenge = randomToken(32)
288
+ const exp = Date.now() + CHALLENGE_TTL_MS
289
+ activeChallenges.set(challenge, exp)
290
+ const payload: ChallengeCookiePayload = {
291
+ challenge,
292
+ purpose,
293
+ ...(userId !== undefined ? { userId } : {}),
294
+ exp,
295
+ }
296
+ ctx.cookies.set(challengeCookieName, signPayload(secret(), payload), authCookie(isSecureCookie(ctx), Math.floor(CHALLENGE_TTL_MS / 1000)))
297
+ return challenge
298
+ }
299
+
300
+ function consumeChallenge(ctx: RequestContext, purpose: 'register' | 'login' | '2fa', expectedUserId?: string): string {
301
+ const raw = ctx.cookies.get(challengeCookieName)
302
+ ctx.cookies.delete(challengeCookieName, { path: '/' })
303
+ if (!raw)
304
+ throw passkeyError(400, 'Missing passkey challenge')
305
+ const payload = verifyPayload<ChallengeCookiePayload>(secret(), raw)
306
+ const now = Date.now()
307
+ if (!payload || payload.exp <= now || payload.purpose !== purpose)
308
+ throw passkeyError(400, 'Invalid or expired passkey challenge')
309
+ if (expectedUserId !== undefined && payload.userId !== expectedUserId)
310
+ throw passkeyError(400, 'Passkey challenge does not match user')
311
+ const storedExp = activeChallenges.get(payload.challenge)
312
+ activeChallenges.delete(payload.challenge)
313
+ if (storedExp === undefined || storedExp <= now)
314
+ throw passkeyError(400, 'Passkey challenge expired or already used')
315
+ return payload.challenge
316
+ }
317
+
318
+ function ceremonyFor(ctx: RequestContext, purpose: 'register' | 'login' | '2fa', expectedUserId?: string): CeremonyContext {
319
+ return {
320
+ expectedChallenge: consumeChallenge(ctx, purpose, expectedUserId),
321
+ expectedOrigin: resolveExpectedOrigin(ctx),
322
+ expectedRpId: resolveRpId(ctx),
323
+ userVerification,
324
+ }
325
+ }
326
+
327
+ return {
328
+ pruneChallenges,
329
+
330
+ async createRegisterOptions(ctx, user) {
331
+ const ps = requirePasskeyStore(store)
332
+ const existing = await sessions.observeAsync(ps.listPasskeys(user.id))
333
+ const rpId = resolveRpId(ctx)
334
+ const rpName = options?.rpName ?? rpId
335
+ const challenge = issueChallenge(ctx, 'register', user.id)
336
+ return {
337
+ challenge,
338
+ rp: { name: rpName, id: rpId },
339
+ user: {
340
+ id: toBase64Url(new TextEncoder().encode(user.id)),
341
+ name: user.email,
342
+ displayName: user.name ?? user.email,
343
+ },
344
+ pubKeyCredParams: [
345
+ { type: 'public-key', alg: COSE_ALG_ES256 },
346
+ { type: 'public-key', alg: COSE_ALG_RS256 },
347
+ { type: 'public-key', alg: COSE_ALG_EDDSA },
348
+ ],
349
+ timeout: CHALLENGE_TTL_MS,
350
+ attestation: 'none',
351
+ authenticatorSelection: {
352
+ residentKey: 'preferred',
353
+ userVerification,
354
+ },
355
+ excludeCredentials: existing.map(p => ({
356
+ type: 'public-key',
357
+ id: p.id,
358
+ ...(p.transports ? { transports: p.transports } : {}),
359
+ })),
360
+ }
361
+ },
362
+
363
+ verifyRegistration(ctx, userId, input) {
364
+ return performRegistrationVerify(store, sessions, userId, input, ceremonyFor(ctx, 'register', userId))
365
+ },
366
+
367
+ async createAssertionOptions(ctx, purpose, opts) {
368
+ const ps = requirePasskeyStore(store)
369
+ const rpId = resolveRpId(ctx)
370
+ let allowCredentials: Array<{ type: 'public-key', id: string, transports?: string[] | undefined }> | undefined
371
+
372
+ if (purpose === '2fa' && opts?.userId !== undefined) {
373
+ const list = await sessions.observeAsync(ps.listPasskeys(opts.userId))
374
+ if (list.length === 0)
375
+ throw passkeyError(400, 'No passkeys registered for this account')
376
+ allowCredentials = list.map(p => ({
377
+ type: 'public-key',
378
+ id: p.id,
379
+ ...(p.transports ? { transports: p.transports } : {}),
380
+ }))
381
+ }
382
+ else if (opts?.email) {
383
+ const user = await sessions.observeAsync(store.getUserByEmail(opts.email))
384
+ if (user) {
385
+ const list = await sessions.observeAsync(ps.listPasskeys(user.id))
386
+ if (list.length > 0) {
387
+ allowCredentials = list.map(p => ({
388
+ type: 'public-key',
389
+ id: p.id,
390
+ ...(p.transports ? { transports: p.transports } : {}),
391
+ }))
392
+ }
393
+ }
394
+ }
395
+
396
+ const challenge = issueChallenge(ctx, purpose, opts?.userId)
397
+ return {
398
+ challenge,
399
+ timeout: CHALLENGE_TTL_MS,
400
+ rpId,
401
+ userVerification,
402
+ ...(allowCredentials !== undefined ? { allowCredentials } : {}),
403
+ }
404
+ },
405
+
406
+ verifyAssertion(ctx, purpose, input, expectedUserId) {
407
+ return performAssertionVerify(store, sessions, input, ceremonyFor(ctx, purpose, expectedUserId), expectedUserId)
408
+ },
409
+
410
+ async listPasskeys(userId) {
411
+ const ps = requirePasskeyStore(store)
412
+ const list = await sessions.observeAsync(ps.listPasskeys(userId))
413
+ return list.map(toPasskeySummary)
414
+ },
415
+
416
+ async deletePasskey(userId, credentialId) {
417
+ const ps = requirePasskeyStore(store)
418
+ return await sessions.observeAsync(ps.deletePasskey(userId, credentialId))
419
+ },
420
+ }
421
+ }