@prunellejs/auth 0.1.1 → 0.7.3
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/LICENSE +21 -0
- package/llms.txt +53 -23
- package/package.json +5 -4
- package/src/account.ts +101 -0
- package/src/crypto.ts +57 -0
- package/src/form-messages.ts +58 -0
- package/src/http.ts +127 -24
- package/src/index.ts +320 -237
- package/src/links.ts +178 -0
- package/src/oauth-routes.ts +119 -52
- package/src/org-routes.ts +226 -0
- package/src/orgs.ts +421 -0
- package/src/passkey-client.ts +211 -0
- package/src/passkey-routes.ts +220 -0
- package/src/passkeys.ts +422 -0
- package/src/routes.ts +178 -120
- package/src/session-cookie.ts +62 -0
- package/src/session.ts +158 -104
- package/src/sqlite-ext.ts +550 -0
- package/src/sqlite.ts +144 -71
- package/src/store-ext.ts +493 -0
- package/src/store.ts +120 -48
- package/src/totp-routes.ts +144 -0
- package/src/totp.ts +376 -0
- package/src/webauthn-crypto.ts +284 -0
|
@@ -0,0 +1,220 @@
|
|
|
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
|
+
import { respondTwoFactorChallenge } from './totp'
|
|
13
|
+
|
|
14
|
+
export interface PasskeyRoutesDeps<TUser extends AuthUser = AuthUser> {
|
|
15
|
+
authRoute: AuthRouteRegistrar
|
|
16
|
+
store: AuthStore<TUser>
|
|
17
|
+
sessions: SessionManager<TUser>
|
|
18
|
+
passkeys: PasskeyManager
|
|
19
|
+
totp: TotpManager
|
|
20
|
+
twoFactorRedirect: string
|
|
21
|
+
defaultRedirect: string
|
|
22
|
+
requireEmailVerification: boolean
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function respondPasskeyErr(ctx: RequestContext, err: unknown): Response {
|
|
26
|
+
const pe = err as Partial<PasskeyError>
|
|
27
|
+
const status = typeof pe?.status === 'number' ? pe.status : 400
|
|
28
|
+
const message = err instanceof Error ? err.message : 'Passkey verification failed'
|
|
29
|
+
return fail(ctx, status, message)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function asRegisterInput(body: Record<string, unknown>): RegisterVerifyInput | undefined {
|
|
33
|
+
const resp = body.response
|
|
34
|
+
if (resp === null || typeof resp !== 'object' || Array.isArray(resp))
|
|
35
|
+
return undefined
|
|
36
|
+
const r = resp as Record<string, unknown>
|
|
37
|
+
if (typeof r.clientDataJSON !== 'string' || typeof r.attestationObject !== 'string')
|
|
38
|
+
return undefined
|
|
39
|
+
const transports = Array.isArray(r.transports) ? r.transports.filter((t): t is string => typeof t === 'string') : undefined
|
|
40
|
+
return {
|
|
41
|
+
...(typeof body.id === 'string' ? { id: body.id } : {}),
|
|
42
|
+
...(typeof body.rawId === 'string' ? { rawId: body.rawId } : {}),
|
|
43
|
+
...(typeof body.name === 'string' ? { name: body.name } : {}),
|
|
44
|
+
response: {
|
|
45
|
+
clientDataJSON: r.clientDataJSON,
|
|
46
|
+
attestationObject: r.attestationObject,
|
|
47
|
+
...(transports !== undefined ? { transports } : {}),
|
|
48
|
+
},
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function asAssertionInput(body: Record<string, unknown>): AssertionVerifyInput | undefined {
|
|
53
|
+
const resp = body.response
|
|
54
|
+
if (resp === null || typeof resp !== 'object' || Array.isArray(resp))
|
|
55
|
+
return undefined
|
|
56
|
+
const r = resp as Record<string, unknown>
|
|
57
|
+
if (typeof r.clientDataJSON !== 'string' || typeof r.authenticatorData !== 'string' || typeof r.signature !== 'string')
|
|
58
|
+
return undefined
|
|
59
|
+
return {
|
|
60
|
+
...(typeof body.id === 'string' ? { id: body.id } : {}),
|
|
61
|
+
...(typeof body.rawId === 'string' ? { rawId: body.rawId } : {}),
|
|
62
|
+
response: {
|
|
63
|
+
clientDataJSON: r.clientDataJSON,
|
|
64
|
+
authenticatorData: r.authenticatorData,
|
|
65
|
+
signature: r.signature,
|
|
66
|
+
...(typeof r.userHandle === 'string' ? { userHandle: r.userHandle } : {}),
|
|
67
|
+
},
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function registerPasskeyRoutes<TUser extends AuthUser = AuthUser>(deps: PasskeyRoutesDeps<TUser>): void {
|
|
72
|
+
const { authRoute, store, sessions, passkeys, totp, twoFactorRedirect, defaultRedirect, requireEmailVerification } = deps
|
|
73
|
+
|
|
74
|
+
authRoute('POST', '/passkeys/register/options', { limit: 'passkey-reg' }, async (ctx) => {
|
|
75
|
+
const resolved = await sessions.resolve(ctx)
|
|
76
|
+
if (!resolved)
|
|
77
|
+
return fail(ctx, 401, 'Authentication required')
|
|
78
|
+
try {
|
|
79
|
+
const options = await passkeys.createRegisterOptions(ctx, resolved.user)
|
|
80
|
+
return ctx.json({ ok: true, options }, { status: 200 })
|
|
81
|
+
}
|
|
82
|
+
catch (err) {
|
|
83
|
+
return respondPasskeyErr(ctx, err)
|
|
84
|
+
}
|
|
85
|
+
})
|
|
86
|
+
|
|
87
|
+
authRoute('POST', '/passkeys/register/verify', { limit: 'passkey-reg' }, async (ctx) => {
|
|
88
|
+
const resolved = await sessions.resolve(ctx)
|
|
89
|
+
if (!resolved)
|
|
90
|
+
return fail(ctx, 401, 'Authentication required')
|
|
91
|
+
const raw = await parseJsonBody(ctx)
|
|
92
|
+
if (raw instanceof Response)
|
|
93
|
+
return raw
|
|
94
|
+
const input = asRegisterInput(raw)
|
|
95
|
+
if (!input)
|
|
96
|
+
return fail(ctx, 400, 'Invalid passkey registration payload')
|
|
97
|
+
try {
|
|
98
|
+
const passkey = await passkeys.verifyRegistration(ctx, resolved.user.id, input)
|
|
99
|
+
return ctx.json({ ok: true, passkey }, { status: 201 })
|
|
100
|
+
}
|
|
101
|
+
catch (err) {
|
|
102
|
+
return respondPasskeyErr(ctx, err)
|
|
103
|
+
}
|
|
104
|
+
})
|
|
105
|
+
|
|
106
|
+
authRoute('POST', '/passkeys/login/options', { limit: 'passkey-login' }, async (ctx) => {
|
|
107
|
+
const raw = await parseJsonBody(ctx)
|
|
108
|
+
if (raw instanceof Response)
|
|
109
|
+
return raw
|
|
110
|
+
const email = typeof raw.email === 'string' && raw.email.trim() ? raw.email.trim() : undefined
|
|
111
|
+
try {
|
|
112
|
+
const options = await passkeys.createAssertionOptions(ctx, 'login', { email })
|
|
113
|
+
return ctx.json({ ok: true, options }, { status: 200 })
|
|
114
|
+
}
|
|
115
|
+
catch (err) {
|
|
116
|
+
return respondPasskeyErr(ctx, err)
|
|
117
|
+
}
|
|
118
|
+
})
|
|
119
|
+
|
|
120
|
+
authRoute('POST', '/passkeys/login/verify', { limit: 'passkey-login' }, async (ctx) => {
|
|
121
|
+
const raw = await parseJsonBody(ctx)
|
|
122
|
+
if (raw instanceof Response)
|
|
123
|
+
return raw
|
|
124
|
+
const input = asAssertionInput(raw)
|
|
125
|
+
if (!input)
|
|
126
|
+
return fail(ctx, 400, 'Invalid passkey assertion payload')
|
|
127
|
+
try {
|
|
128
|
+
const { userId } = await passkeys.verifyAssertion(ctx, 'login', input)
|
|
129
|
+
const userRecord = await sessions.observeAsync(store.getUserById(userId))
|
|
130
|
+
if (!userRecord)
|
|
131
|
+
return fail(ctx, 401, 'Unable to resolve user account')
|
|
132
|
+
if (requireEmailVerification && !userRecord.emailVerified)
|
|
133
|
+
return fail(ctx, 403, 'Email not verified')
|
|
134
|
+
|
|
135
|
+
const redirect = safeRedirect(typeof raw.redirect === 'string' ? raw.redirect : (typeof raw.next === 'string' ? raw.next : undefined), defaultRedirect)
|
|
136
|
+
const twoFactorMethods = (await totp.getTwoFactorMethods(userRecord.id)).filter(m => m !== 'passkey')
|
|
137
|
+
if (twoFactorMethods.length > 0)
|
|
138
|
+
return respondTwoFactorChallenge(totp, ctx, userRecord.id, redirect, twoFactorRedirect, twoFactorMethods)
|
|
139
|
+
|
|
140
|
+
const pub = toPublicUser(userRecord)
|
|
141
|
+
await sessions.createSessionForUser(userRecord.id, ctx, pub)
|
|
142
|
+
if (wantsJson(ctx.request))
|
|
143
|
+
return ctx.json({ ok: true, user: pub }, { status: 200 })
|
|
144
|
+
return ctx.redirect(redirect, 303)
|
|
145
|
+
}
|
|
146
|
+
catch (err) {
|
|
147
|
+
return respondPasskeyErr(ctx, err)
|
|
148
|
+
}
|
|
149
|
+
})
|
|
150
|
+
|
|
151
|
+
authRoute('POST', '/passkeys/2fa/options', { limit: 'passkey-2fa' }, async (ctx) => {
|
|
152
|
+
const pending = totp.readPendingCookie(ctx)
|
|
153
|
+
if (!pending)
|
|
154
|
+
return fail(ctx, 401, 'Two-factor session expired or invalid')
|
|
155
|
+
if (!pending.methods.includes('passkey'))
|
|
156
|
+
return fail(ctx, 403, 'Passkey cannot be used as second factor for this sign-in')
|
|
157
|
+
try {
|
|
158
|
+
const options = await passkeys.createAssertionOptions(ctx, '2fa', { userId: pending.userId })
|
|
159
|
+
return ctx.json({ ok: true, options }, { status: 200 })
|
|
160
|
+
}
|
|
161
|
+
catch (err) {
|
|
162
|
+
return respondPasskeyErr(ctx, err)
|
|
163
|
+
}
|
|
164
|
+
})
|
|
165
|
+
|
|
166
|
+
authRoute('POST', '/passkeys/2fa/verify', { limit: 'passkey-2fa' }, async (ctx) => {
|
|
167
|
+
const pending = totp.readPendingCookie(ctx)
|
|
168
|
+
if (!pending)
|
|
169
|
+
return fail(ctx, 401, 'Two-factor session expired or invalid')
|
|
170
|
+
if (!pending.methods.includes('passkey'))
|
|
171
|
+
return fail(ctx, 403, 'Passkey cannot be used as second factor for this sign-in')
|
|
172
|
+
const raw = await parseJsonBody(ctx)
|
|
173
|
+
if (raw instanceof Response)
|
|
174
|
+
return raw
|
|
175
|
+
const input = asAssertionInput(raw)
|
|
176
|
+
if (!input)
|
|
177
|
+
return fail(ctx, 400, 'Invalid passkey assertion payload')
|
|
178
|
+
try {
|
|
179
|
+
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
|
+
}
|
|
193
|
+
catch (err) {
|
|
194
|
+
return respondPasskeyErr(ctx, err)
|
|
195
|
+
}
|
|
196
|
+
})
|
|
197
|
+
|
|
198
|
+
authRoute('GET', '/passkeys', {}, async (ctx) => {
|
|
199
|
+
const resolved = await sessions.resolve(ctx)
|
|
200
|
+
if (!resolved)
|
|
201
|
+
return fail(ctx, 401, 'Authentication required')
|
|
202
|
+
const list = await passkeys.listPasskeys(resolved.user.id)
|
|
203
|
+
return ctx.json({ ok: true, passkeys: list }, { status: 200 })
|
|
204
|
+
})
|
|
205
|
+
|
|
206
|
+
authRoute('POST', '/passkeys/delete', { limit: 'passkey-del', readBody: true }, async (ctx, body) => {
|
|
207
|
+
const resolved = await sessions.resolve(ctx)
|
|
208
|
+
if (!resolved)
|
|
209
|
+
return fail(ctx, 401, 'Authentication required')
|
|
210
|
+
const credentialId = (body.id ?? body.credentialId ?? '').trim()
|
|
211
|
+
if (!credentialId)
|
|
212
|
+
return fail(ctx, 400, 'Passkey id is required')
|
|
213
|
+
const deleted = await passkeys.deletePasskey(resolved.user.id, credentialId)
|
|
214
|
+
if (!deleted)
|
|
215
|
+
return fail(ctx, 404, 'Passkey not found')
|
|
216
|
+
if (wantsJson(ctx.request))
|
|
217
|
+
return ctx.json({ ok: true }, { status: 200 })
|
|
218
|
+
return ctx.redirect(safeRedirect(body.redirect ?? body.next, defaultRedirect), 303)
|
|
219
|
+
})
|
|
220
|
+
}
|
package/src/passkeys.ts
ADDED
|
@@ -0,0 +1,422 @@
|
|
|
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: `'required'` for registration and passwordless login, `'preferred'` for 2FA). */
|
|
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 userVerificationFor = (purpose: 'register' | 'login' | '2fa'): PasskeyUserVerification =>
|
|
266
|
+
options?.userVerification ?? (purpose === '2fa' ? 'preferred' : 'required')
|
|
267
|
+
const activeChallenges = new Map<string, number>()
|
|
268
|
+
|
|
269
|
+
function resolveExpectedOrigin(ctx: RequestContext): string {
|
|
270
|
+
return options?.origin ?? getSite() ?? ctx.url.origin
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
function resolveRpId(ctx: RequestContext): string {
|
|
274
|
+
return options?.rpId ?? new URL(resolveExpectedOrigin(ctx)).hostname
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function pruneChallenges(): void {
|
|
278
|
+
const now = Date.now()
|
|
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()
|
|
288
|
+
const challenge = randomToken(32)
|
|
289
|
+
const exp = Date.now() + CHALLENGE_TTL_MS
|
|
290
|
+
activeChallenges.set(challenge, exp)
|
|
291
|
+
const payload: ChallengeCookiePayload = {
|
|
292
|
+
challenge,
|
|
293
|
+
purpose,
|
|
294
|
+
...(userId !== undefined ? { userId } : {}),
|
|
295
|
+
exp,
|
|
296
|
+
}
|
|
297
|
+
ctx.cookies.set(challengeCookieName, signPayload(secret(), payload), authCookie(isSecureCookie(ctx), Math.floor(CHALLENGE_TTL_MS / 1000)))
|
|
298
|
+
return challenge
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
function consumeChallenge(ctx: RequestContext, purpose: 'register' | 'login' | '2fa', expectedUserId?: string): string {
|
|
302
|
+
const raw = ctx.cookies.get(challengeCookieName)
|
|
303
|
+
ctx.cookies.delete(challengeCookieName, { path: '/' })
|
|
304
|
+
if (!raw)
|
|
305
|
+
throw passkeyError(400, 'Missing passkey challenge')
|
|
306
|
+
const payload = verifyPayload<ChallengeCookiePayload>(secret(), raw)
|
|
307
|
+
const now = Date.now()
|
|
308
|
+
if (!payload || payload.exp <= now || payload.purpose !== purpose)
|
|
309
|
+
throw passkeyError(400, 'Invalid or expired passkey challenge')
|
|
310
|
+
if (expectedUserId !== undefined && payload.userId !== expectedUserId)
|
|
311
|
+
throw passkeyError(400, 'Passkey challenge does not match user')
|
|
312
|
+
const storedExp = activeChallenges.get(payload.challenge)
|
|
313
|
+
activeChallenges.delete(payload.challenge)
|
|
314
|
+
if (storedExp === undefined || storedExp <= now)
|
|
315
|
+
throw passkeyError(400, 'Passkey challenge expired or already used')
|
|
316
|
+
return payload.challenge
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
function ceremonyFor(ctx: RequestContext, purpose: 'register' | 'login' | '2fa', expectedUserId?: string): CeremonyContext {
|
|
320
|
+
return {
|
|
321
|
+
expectedChallenge: consumeChallenge(ctx, purpose, expectedUserId),
|
|
322
|
+
expectedOrigin: resolveExpectedOrigin(ctx),
|
|
323
|
+
expectedRpId: resolveRpId(ctx),
|
|
324
|
+
userVerification: userVerificationFor(purpose),
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
return {
|
|
329
|
+
pruneChallenges,
|
|
330
|
+
|
|
331
|
+
async createRegisterOptions(ctx, user) {
|
|
332
|
+
const ps = requirePasskeyStore(store)
|
|
333
|
+
const existing = await sessions.observeAsync(ps.listPasskeys(user.id))
|
|
334
|
+
const rpId = resolveRpId(ctx)
|
|
335
|
+
const rpName = options?.rpName ?? rpId
|
|
336
|
+
const challenge = issueChallenge(ctx, 'register', user.id)
|
|
337
|
+
return {
|
|
338
|
+
challenge,
|
|
339
|
+
rp: { name: rpName, id: rpId },
|
|
340
|
+
user: {
|
|
341
|
+
id: toBase64Url(new TextEncoder().encode(user.id)),
|
|
342
|
+
name: user.email,
|
|
343
|
+
displayName: user.name ?? user.email,
|
|
344
|
+
},
|
|
345
|
+
pubKeyCredParams: [
|
|
346
|
+
{ type: 'public-key', alg: COSE_ALG_ES256 },
|
|
347
|
+
{ type: 'public-key', alg: COSE_ALG_RS256 },
|
|
348
|
+
{ type: 'public-key', alg: COSE_ALG_EDDSA },
|
|
349
|
+
],
|
|
350
|
+
timeout: CHALLENGE_TTL_MS,
|
|
351
|
+
attestation: 'none',
|
|
352
|
+
authenticatorSelection: {
|
|
353
|
+
residentKey: 'preferred',
|
|
354
|
+
userVerification: userVerificationFor('register'),
|
|
355
|
+
},
|
|
356
|
+
excludeCredentials: existing.map(p => ({
|
|
357
|
+
type: 'public-key',
|
|
358
|
+
id: p.id,
|
|
359
|
+
...(p.transports ? { transports: p.transports } : {}),
|
|
360
|
+
})),
|
|
361
|
+
}
|
|
362
|
+
},
|
|
363
|
+
|
|
364
|
+
verifyRegistration(ctx, userId, input) {
|
|
365
|
+
return performRegistrationVerify(store, sessions, userId, input, ceremonyFor(ctx, 'register', userId))
|
|
366
|
+
},
|
|
367
|
+
|
|
368
|
+
async createAssertionOptions(ctx, purpose, opts) {
|
|
369
|
+
const ps = requirePasskeyStore(store)
|
|
370
|
+
const rpId = resolveRpId(ctx)
|
|
371
|
+
let allowCredentials: Array<{ type: 'public-key', id: string, transports?: string[] | undefined }> | undefined
|
|
372
|
+
|
|
373
|
+
if (purpose === '2fa' && opts?.userId !== undefined) {
|
|
374
|
+
const list = await sessions.observeAsync(ps.listPasskeys(opts.userId))
|
|
375
|
+
if (list.length === 0)
|
|
376
|
+
throw passkeyError(400, 'No passkeys registered for this account')
|
|
377
|
+
allowCredentials = list.map(p => ({
|
|
378
|
+
type: 'public-key',
|
|
379
|
+
id: p.id,
|
|
380
|
+
...(p.transports ? { transports: p.transports } : {}),
|
|
381
|
+
}))
|
|
382
|
+
}
|
|
383
|
+
else if (opts?.email) {
|
|
384
|
+
const user = await sessions.observeAsync(store.getUserByEmail(opts.email))
|
|
385
|
+
if (user) {
|
|
386
|
+
const list = await sessions.observeAsync(ps.listPasskeys(user.id))
|
|
387
|
+
if (list.length > 0) {
|
|
388
|
+
allowCredentials = list.map(p => ({
|
|
389
|
+
type: 'public-key',
|
|
390
|
+
id: p.id,
|
|
391
|
+
...(p.transports ? { transports: p.transports } : {}),
|
|
392
|
+
}))
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
const challenge = issueChallenge(ctx, purpose, opts?.userId)
|
|
398
|
+
return {
|
|
399
|
+
challenge,
|
|
400
|
+
timeout: CHALLENGE_TTL_MS,
|
|
401
|
+
rpId,
|
|
402
|
+
userVerification: userVerificationFor(purpose),
|
|
403
|
+
...(allowCredentials !== undefined ? { allowCredentials } : {}),
|
|
404
|
+
}
|
|
405
|
+
},
|
|
406
|
+
|
|
407
|
+
verifyAssertion(ctx, purpose, input, expectedUserId) {
|
|
408
|
+
return performAssertionVerify(store, sessions, input, ceremonyFor(ctx, purpose, expectedUserId), expectedUserId)
|
|
409
|
+
},
|
|
410
|
+
|
|
411
|
+
async listPasskeys(userId) {
|
|
412
|
+
const ps = requirePasskeyStore(store)
|
|
413
|
+
const list = await sessions.observeAsync(ps.listPasskeys(userId))
|
|
414
|
+
return list.map(toPasskeySummary)
|
|
415
|
+
},
|
|
416
|
+
|
|
417
|
+
async deletePasskey(userId, credentialId) {
|
|
418
|
+
const ps = requirePasskeyStore(store)
|
|
419
|
+
return await sessions.observeAsync(ps.deletePasskey(userId, credentialId))
|
|
420
|
+
},
|
|
421
|
+
}
|
|
422
|
+
}
|