@prunellejs/auth 0.0.0-stage → 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,207 @@
1
+ // Browser-only WebAuthn Passkey helper (`@prunellejs/auth/passkey`).
2
+ // Zero server imports: pages that do not import this subpath ship 0 bytes of passkey client code.
3
+
4
+ export interface PasskeyClientOptions {
5
+ /** Auth route prefix (default: `'/auth'`). */
6
+ basePath?: string | undefined
7
+ /** Optional custom fetch implementation. */
8
+ fetch?: typeof globalThis.fetch | undefined
9
+ }
10
+
11
+ export interface RegisterPasskeyOptions extends PasskeyClientOptions {
12
+ /** Optional human-readable label for the passkey (e.g. "MacBook Touch ID"). */
13
+ name?: string | undefined
14
+ }
15
+
16
+ export interface SignInWithPasskeyOptions extends PasskeyClientOptions {
17
+ /** Optional email hint to restrict credentials to a specific account. */
18
+ email?: string | undefined
19
+ /** Optional browser mediation mode (e.g. `'conditional'` for autofill UI). */
20
+ mediation?: CredentialMediationRequirement | undefined
21
+ /** Optional post-login redirect hint. */
22
+ redirect?: string | undefined
23
+ }
24
+
25
+ interface JsonCredentialDescriptor {
26
+ type: 'public-key'
27
+ id: string
28
+ transports?: AuthenticatorTransport[] | undefined
29
+ }
30
+
31
+ function base64UrlToBuffer(value: string): ArrayBuffer {
32
+ const padded = value.replace(/-/g, '+').replace(/_/g, '/')
33
+ const padLen = (4 - (padded.length % 4)) % 4
34
+ const binary = atob(padded + '='.repeat(padLen))
35
+ const bytes = new Uint8Array(binary.length)
36
+ for (let i = 0; i < binary.length; i++)
37
+ bytes[i] = binary.charCodeAt(i)
38
+ return bytes.buffer
39
+ }
40
+
41
+ function bufferToBase64Url(buffer: ArrayBuffer): string {
42
+ const bytes = new Uint8Array(buffer)
43
+ let binary = ''
44
+ for (let i = 0; i < bytes.length; i++)
45
+ binary += String.fromCharCode(bytes[i]!)
46
+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
47
+ }
48
+
49
+ async function postJson<T>(fetchImpl: typeof globalThis.fetch, url: string, body: unknown): Promise<T> {
50
+ const res = await fetchImpl(url, {
51
+ method: 'POST',
52
+ credentials: 'same-origin',
53
+ headers: { 'content-type': 'application/json', 'accept': 'application/json' },
54
+ body: JSON.stringify(body),
55
+ })
56
+ const data = await res.json() as Record<string, unknown>
57
+ if (!res.ok) {
58
+ const msg = typeof data.error === 'string' ? data.error : `Passkey request failed (${res.status})`
59
+ throw new Error(msg)
60
+ }
61
+ return data as T
62
+ }
63
+
64
+ function decodeDescriptor(desc: JsonCredentialDescriptor): PublicKeyCredentialDescriptor {
65
+ return {
66
+ type: 'public-key',
67
+ id: base64UrlToBuffer(desc.id),
68
+ ...(desc.transports ? { transports: desc.transports } : {}),
69
+ }
70
+ }
71
+
72
+ export function isPasskeySupported(): boolean {
73
+ return typeof globalThis.window !== 'undefined'
74
+ && typeof globalThis.PublicKeyCredential !== 'undefined'
75
+ && typeof globalThis.navigator !== 'undefined'
76
+ && typeof globalThis.navigator.credentials?.create === 'function'
77
+ && typeof globalThis.navigator.credentials?.get === 'function'
78
+ }
79
+
80
+ export async function registerPasskey(options: RegisterPasskeyOptions = {}): Promise<{ ok: true, passkey: Record<string, unknown> }> {
81
+ if (!isPasskeySupported())
82
+ throw new Error('Passkeys are not supported in this browser')
83
+ const base = (options.basePath ?? '/auth').replace(/\/$/, '')
84
+ const fetchImpl = options.fetch ?? globalThis.fetch
85
+
86
+ const start = await postJson<{
87
+ ok: true
88
+ options: {
89
+ challenge: string
90
+ rp: PublicKeyCredentialRpEntity
91
+ user: { id: string, name: string, displayName: string }
92
+ pubKeyCredParams: PublicKeyCredentialParameters[]
93
+ timeout?: number
94
+ attestation?: AttestationConveyancePreference
95
+ authenticatorSelection?: AuthenticatorSelectionCriteria
96
+ excludeCredentials?: JsonCredentialDescriptor[]
97
+ }
98
+ }>(fetchImpl, `${base}/passkeys/register/options`, {})
99
+
100
+ const pubKey: PublicKeyCredentialCreationOptions = {
101
+ challenge: base64UrlToBuffer(start.options.challenge),
102
+ rp: start.options.rp,
103
+ user: {
104
+ id: base64UrlToBuffer(start.options.user.id),
105
+ name: start.options.user.name,
106
+ displayName: start.options.user.displayName,
107
+ },
108
+ pubKeyCredParams: start.options.pubKeyCredParams,
109
+ ...(start.options.timeout !== undefined ? { timeout: start.options.timeout } : {}),
110
+ ...(start.options.attestation !== undefined ? { attestation: start.options.attestation } : {}),
111
+ ...(start.options.authenticatorSelection !== undefined ? { authenticatorSelection: start.options.authenticatorSelection } : {}),
112
+ ...(start.options.excludeCredentials ? { excludeCredentials: start.options.excludeCredentials.map(decodeDescriptor) } : {}),
113
+ }
114
+
115
+ const cred = await navigator.credentials.create({ publicKey: pubKey }) as PublicKeyCredential | null
116
+ if (!cred)
117
+ throw new Error('Passkey registration was cancelled')
118
+ const response = cred.response as AuthenticatorAttestationResponse
119
+ const transports = typeof response.getTransports === 'function' ? response.getTransports() : undefined
120
+
121
+ return postJson(fetchImpl, `${base}/passkeys/register/verify`, {
122
+ id: cred.id,
123
+ rawId: bufferToBase64Url(cred.rawId),
124
+ ...(options.name ? { name: options.name } : {}),
125
+ response: {
126
+ clientDataJSON: bufferToBase64Url(response.clientDataJSON),
127
+ attestationObject: bufferToBase64Url(response.attestationObject),
128
+ ...(transports ? { transports } : {}),
129
+ },
130
+ })
131
+ }
132
+
133
+ async function runAssertion(
134
+ fetchImpl: typeof globalThis.fetch,
135
+ optionsUrl: string,
136
+ verifyUrl: string,
137
+ startBody: Record<string, unknown>,
138
+ extraVerify: Record<string, unknown>,
139
+ mediation?: CredentialMediationRequirement,
140
+ ): Promise<{ ok: true, user: Record<string, unknown> }> {
141
+ if (!isPasskeySupported())
142
+ throw new Error('Passkeys are not supported in this browser')
143
+
144
+ const start = await postJson<{
145
+ ok: true
146
+ options: {
147
+ challenge: string
148
+ timeout?: number
149
+ rpId?: string
150
+ userVerification?: UserVerificationRequirement
151
+ allowCredentials?: JsonCredentialDescriptor[]
152
+ }
153
+ }>(fetchImpl, optionsUrl, startBody)
154
+
155
+ const pubKey: PublicKeyCredentialRequestOptions = {
156
+ challenge: base64UrlToBuffer(start.options.challenge),
157
+ ...(start.options.timeout !== undefined ? { timeout: start.options.timeout } : {}),
158
+ ...(start.options.rpId !== undefined ? { rpId: start.options.rpId } : {}),
159
+ ...(start.options.userVerification !== undefined ? { userVerification: start.options.userVerification } : {}),
160
+ ...(start.options.allowCredentials ? { allowCredentials: start.options.allowCredentials.map(decodeDescriptor) } : {}),
161
+ }
162
+
163
+ const cred = await navigator.credentials.get({
164
+ publicKey: pubKey,
165
+ ...(mediation !== undefined ? { mediation } : {}),
166
+ }) as PublicKeyCredential | null
167
+ if (!cred)
168
+ throw new Error('Passkey authentication was cancelled')
169
+ const response = cred.response as AuthenticatorAssertionResponse
170
+
171
+ return postJson(fetchImpl, verifyUrl, {
172
+ ...extraVerify,
173
+ id: cred.id,
174
+ rawId: bufferToBase64Url(cred.rawId),
175
+ response: {
176
+ clientDataJSON: bufferToBase64Url(response.clientDataJSON),
177
+ authenticatorData: bufferToBase64Url(response.authenticatorData),
178
+ signature: bufferToBase64Url(response.signature),
179
+ ...(response.userHandle ? { userHandle: bufferToBase64Url(response.userHandle) } : {}),
180
+ },
181
+ })
182
+ }
183
+
184
+ export async function signInWithPasskey(options: SignInWithPasskeyOptions = {}): Promise<{ ok: true, user: Record<string, unknown> }> {
185
+ const base = (options.basePath ?? '/auth').replace(/\/$/, '')
186
+ const fetchImpl = options.fetch ?? globalThis.fetch
187
+ return runAssertion(
188
+ fetchImpl,
189
+ `${base}/passkeys/login/options`,
190
+ `${base}/passkeys/login/verify`,
191
+ options.email ? { email: options.email } : {},
192
+ options.redirect ? { redirect: options.redirect } : {},
193
+ options.mediation,
194
+ )
195
+ }
196
+
197
+ export async function verifyPasskey2FA(options: PasskeyClientOptions = {}): Promise<{ ok: true, user: Record<string, unknown> }> {
198
+ const base = (options.basePath ?? '/auth').replace(/\/$/, '')
199
+ const fetchImpl = options.fetch ?? globalThis.fetch
200
+ return runAssertion(
201
+ fetchImpl,
202
+ `${base}/passkeys/2fa/options`,
203
+ `${base}/passkeys/2fa/verify`,
204
+ {},
205
+ {},
206
+ )
207
+ }
@@ -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
+ }