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