@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.
package/src/orgs.ts ADDED
@@ -0,0 +1,403 @@
1
+ // Organization management (orgs, members, roles, mail invitations) and organization-aware route guards.
2
+
3
+ import type { Middleware, RequestContext } from 'prunelle/server'
4
+ import type { AuthMailPayload, GuardOptions } from './index'
5
+ import type { SessionManager } from './session'
6
+ import type { AuthSession, AuthStore, AuthUser, Organization, OrgInvitation, OrgMembership, PublicUser, UserOrgSummary } from './store'
7
+ import { safeRedirect, wantsJson } from 'prunelle/server'
8
+ import { randomToken, sha256Hex } from './crypto'
9
+ import { escapeHtml, fail, isValidEmail } from './http'
10
+ import { normalizeEmail } from './store'
11
+
12
+ const ORG_SLUG_RE = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/
13
+ const DEFAULT_ORG_INVITE_TTL_MS = 7 * 24 * 60 * 60 * 1000
14
+
15
+ export interface OrgError extends Error {
16
+ status: number
17
+ }
18
+
19
+ function orgError(status: number, message: string): OrgError {
20
+ const err = new Error(message) as OrgError
21
+ err.status = status
22
+ return err
23
+ }
24
+
25
+ // The orgs a user's deletion takes with it, those they are the only member of; throws 409 when they are the last owner of an org others still belong to.
26
+ export async function orgsDeletedWithUser<TUser extends AuthUser>(store: AuthStore<TUser>, userId: string): Promise<string[]> {
27
+ if (!store.listUserOrgMemberships || !store.listOrgMembers)
28
+ return []
29
+ const deleted: string[] = []
30
+ for (const { org, role } of await store.listUserOrgMemberships(userId)) {
31
+ if (role !== 'owner')
32
+ continue
33
+ const members = await store.listOrgMembers(org.id)
34
+ if (members.length === 1)
35
+ deleted.push(org.id)
36
+ else if (members.filter(m => m.role === 'owner').length === 1)
37
+ throw orgError(409, `prunelle: this account is the last owner of "${org.name}": make another member owner, or delete the organization, before deleting the account`)
38
+ }
39
+ return deleted
40
+ }
41
+
42
+ export function slugifyOrgName(name: string): string {
43
+ return name
44
+ .normalize('NFKD')
45
+ .replace(/[\u0300-\u036f]/g, '')
46
+ .toLowerCase()
47
+ .replace(/[^a-z0-9]+/g, '-')
48
+ .replace(/^-+|-+$/g, '')
49
+ }
50
+
51
+ export interface CreateOrgInput {
52
+ name: string
53
+ slug?: string | undefined
54
+ }
55
+
56
+ export interface InviteToOrgInput {
57
+ email: string
58
+ role?: string | undefined
59
+ invitedBy: string
60
+ origin?: string | undefined
61
+ redirectTo?: string | undefined
62
+ }
63
+
64
+ export interface OrgManagerDeps<TUser extends AuthUser = AuthUser> {
65
+ store: AuthStore<TUser>
66
+ sessions: SessionManager<TUser>
67
+ basePath: string
68
+ defaultRedirect: string
69
+ orgInviteTtlMs?: number | undefined
70
+ deliverMail?: ((mail: AuthMailPayload) => void | Promise<void>) | undefined
71
+ }
72
+
73
+ export interface OrgManager {
74
+ createOrg(ownerUserId: string, input: CreateOrgInput): Promise<Organization>
75
+ getOrg(idOrSlug: string): Promise<Organization | undefined>
76
+ listUserOrgs(userId: string): Promise<UserOrgSummary[]>
77
+ listOrgMembers(orgId: string): Promise<OrgMembership[]>
78
+ getOrgMember(orgId: string, userId: string): Promise<OrgMembership | undefined>
79
+ addOrgMember(orgId: string, userId: string, role?: string): Promise<OrgMembership>
80
+ updateOrgMemberRole(orgId: string, userId: string, role: string): Promise<OrgMembership | undefined>
81
+ removeOrgMember(orgId: string, userId: string): Promise<boolean>
82
+ inviteToOrg(orgId: string, input: InviteToOrgInput): Promise<{ invitation: OrgInvitation, url: string }>
83
+ acceptOrgInvite(token: string, userId: string): Promise<{ org: Organization, membership: OrgMembership }>
84
+ revokeOrgInvite(orgId: string, inviteId: string): Promise<boolean>
85
+ deleteOrg(orgId: string): Promise<void>
86
+ }
87
+
88
+ function requireOrgStore<TUser extends AuthUser>(store: AuthStore<TUser>) {
89
+ if (
90
+ !store.createOrg || !store.getOrgById || !store.getOrgBySlug || !store.deleteOrg
91
+ || !store.getOrgMember || !store.listOrgMembers || !store.listUserOrgMemberships
92
+ || !store.addOrgMember || !store.updateOrgMemberRole || !store.removeOrgMember
93
+ || !store.createOrgInvite || !store.getOrgInviteByTokenHash || !store.deleteOrgInvite || !store.consumeOrgInvite
94
+ ) {
95
+ throw orgError(500, 'prunelle: configured AuthStore does not support organizations')
96
+ }
97
+ return {
98
+ createOrg: store.createOrg.bind(store),
99
+ getOrgById: store.getOrgById.bind(store),
100
+ getOrgBySlug: store.getOrgBySlug.bind(store),
101
+ deleteOrg: store.deleteOrg.bind(store),
102
+ getOrgMember: store.getOrgMember.bind(store),
103
+ listOrgMembers: store.listOrgMembers.bind(store),
104
+ listUserOrgMemberships: store.listUserOrgMemberships.bind(store),
105
+ addOrgMember: store.addOrgMember.bind(store),
106
+ updateOrgMemberRole: store.updateOrgMemberRole.bind(store),
107
+ removeOrgMember: store.removeOrgMember.bind(store),
108
+ createOrgInvite: store.createOrgInvite.bind(store),
109
+ getOrgInviteByTokenHash: store.getOrgInviteByTokenHash.bind(store),
110
+ deleteOrgInvite: store.deleteOrgInvite.bind(store),
111
+ consumeOrgInvite: store.consumeOrgInvite.bind(store),
112
+ }
113
+ }
114
+
115
+ function createInviteMethods<TUser extends AuthUser>(
116
+ deps: OrgManagerDeps<TUser>,
117
+ inviteTtlMs: number,
118
+ ): Pick<OrgManager, 'inviteToOrg' | 'acceptOrgInvite' | 'revokeOrgInvite'> {
119
+ const { store, sessions, basePath, defaultRedirect, deliverMail } = deps
120
+ return {
121
+ async inviteToOrg(orgId, input) {
122
+ const os = requireOrgStore(store)
123
+ const org = await sessions.observeAsync(os.getOrgById(orgId))
124
+ if (!org)
125
+ throw orgError(404, 'prunelle: organization not found')
126
+ const email = normalizeEmail(input.email)
127
+ if (!isValidEmail(email))
128
+ throw orgError(400, 'prunelle: please enter a valid email address')
129
+ const role = (input.role?.trim()) || 'member'
130
+
131
+ const rawToken = randomToken(32)
132
+ const tokenHash = sha256Hex(rawToken)
133
+ const now = Date.now()
134
+ const invitation = await sessions.observeAsync(os.createOrgInvite({
135
+ id: crypto.randomUUID(),
136
+ orgId: org.id,
137
+ email,
138
+ role,
139
+ invitedBy: input.invitedBy,
140
+ tokenHash,
141
+ expiresAt: now + inviteTtlMs,
142
+ createdAt: now,
143
+ }))
144
+
145
+ const next = safeRedirect(input.redirectTo, defaultRedirect)
146
+ const path = `${basePath}/orgs/invite/accept?token=${encodeURIComponent(rawToken)}&redirect=${encodeURIComponent(next)}`
147
+ const url = input.origin !== undefined ? `${input.origin.replace(/\/$/, '')}${path}` : path
148
+
149
+ if (deliverMail && input.origin !== undefined) {
150
+ try {
151
+ await deliverMail({
152
+ to: email,
153
+ subject: `You're invited to join ${org.name}`,
154
+ text: `You have been invited to join ${org.name} as ${role}. Accept your invitation: ${url}`,
155
+ html: `<p>You have been invited to join <strong>${escapeHtml(org.name)}</strong> as ${escapeHtml(role)}: <a href="${escapeHtml(url)}">Accept invitation</a></p>`,
156
+ url,
157
+ kind: 'org-invite',
158
+ })
159
+ }
160
+ catch (err) {
161
+ try {
162
+ await sessions.observeAsync(os.deleteOrgInvite(org.id, invitation.id))
163
+ }
164
+ catch (rollbackErr) {
165
+ console.error('[prunelle/auth] failed to roll back org invite after mail error:', rollbackErr)
166
+ }
167
+ throw err
168
+ }
169
+ }
170
+
171
+ return { invitation, url }
172
+ },
173
+
174
+ async acceptOrgInvite(token, userId) {
175
+ const os = requireOrgStore(store)
176
+ const trimmed = token.trim()
177
+ if (!trimmed)
178
+ throw orgError(400, 'prunelle: invitation token is required')
179
+ const tokenHash = sha256Hex(trimmed)
180
+ const invite = await sessions.observeAsync(os.getOrgInviteByTokenHash(tokenHash))
181
+ if (!invite || invite.expiresAt <= Date.now())
182
+ throw orgError(400, 'prunelle: invalid or expired organization invitation')
183
+
184
+ const user = await sessions.observeAsync(store.getUserById(userId))
185
+ if (!user)
186
+ throw orgError(404, 'prunelle: user not found')
187
+ if (normalizeEmail(user.email) !== normalizeEmail(invite.email))
188
+ throw orgError(403, 'prunelle: invitation email does not match your account')
189
+
190
+ const org = await sessions.observeAsync(os.getOrgById(invite.orgId))
191
+ if (!org)
192
+ throw orgError(404, 'prunelle: organization no longer exists')
193
+
194
+ const consumed = await sessions.observeAsync(os.consumeOrgInvite(tokenHash))
195
+ if (!consumed)
196
+ throw orgError(400, 'prunelle: invitation has already been used')
197
+
198
+ const existing = await sessions.observeAsync(os.getOrgMember(org.id, user.id))
199
+ const membership = existing ?? await sessions.observeAsync(os.addOrgMember({
200
+ orgId: org.id,
201
+ userId: user.id,
202
+ role: consumed.role,
203
+ createdAt: Date.now(),
204
+ }))
205
+ return { org, membership }
206
+ },
207
+
208
+ async revokeOrgInvite(orgId, inviteId) {
209
+ const os = requireOrgStore(store)
210
+ return await sessions.observeAsync(os.deleteOrgInvite(orgId, inviteId))
211
+ },
212
+ }
213
+ }
214
+
215
+ export function createOrgManager<TUser extends AuthUser = AuthUser>(deps: OrgManagerDeps<TUser>): OrgManager {
216
+ const { store, sessions } = deps
217
+ const inviteTtlMs = deps.orgInviteTtlMs ?? DEFAULT_ORG_INVITE_TTL_MS
218
+ const invites = createInviteMethods(deps, inviteTtlMs)
219
+
220
+ async function getOrg(idOrSlug: string): Promise<Organization | undefined> {
221
+ const os = requireOrgStore(store)
222
+ const trimmed = idOrSlug.trim()
223
+ if (!trimmed)
224
+ return undefined
225
+ const byId = await sessions.observeAsync(os.getOrgById(trimmed))
226
+ if (byId)
227
+ return byId
228
+ return await sessions.observeAsync(os.getOrgBySlug(trimmed.toLowerCase()))
229
+ }
230
+
231
+ async function assertNotLastOwner(orgId: string, userId: string, action: 'remove' | 'demote'): Promise<OrgMembership | undefined> {
232
+ const os = requireOrgStore(store)
233
+ const current = await sessions.observeAsync(os.getOrgMember(orgId, userId))
234
+ if (!current)
235
+ return undefined
236
+ if (current.role === 'owner') {
237
+ const members = await sessions.observeAsync(os.listOrgMembers(orgId))
238
+ const ownerCount = members.filter(m => m.role === 'owner').length
239
+ if (ownerCount <= 1)
240
+ throw orgError(400, `prunelle: cannot ${action} the last owner of an organization`)
241
+ }
242
+ return current
243
+ }
244
+
245
+ return {
246
+ async createOrg(ownerUserId, input) {
247
+ const os = requireOrgStore(store)
248
+ const name = input.name.trim()
249
+ if (!name)
250
+ throw orgError(400, 'prunelle: organization name is required')
251
+ const slug = (input.slug?.trim().toLowerCase()) || slugifyOrgName(name)
252
+ if (!ORG_SLUG_RE.test(slug))
253
+ throw orgError(400, 'prunelle: organization slug must contain only lowercase letters, numbers, and hyphens')
254
+ const owner = await sessions.observeAsync(store.getUserById(ownerUserId))
255
+ if (!owner)
256
+ throw orgError(404, 'prunelle: owner user not found')
257
+ const existing = await sessions.observeAsync(os.getOrgBySlug(slug))
258
+ if (existing)
259
+ throw orgError(409, `prunelle: organization slug "${slug}" already exists`)
260
+
261
+ const now = Date.now()
262
+ const org = await sessions.observeAsync(os.createOrg({
263
+ id: crypto.randomUUID(),
264
+ slug,
265
+ name,
266
+ createdAt: now,
267
+ updatedAt: now,
268
+ }))
269
+ await sessions.observeAsync(os.addOrgMember({
270
+ orgId: org.id,
271
+ userId: ownerUserId,
272
+ role: 'owner',
273
+ createdAt: now,
274
+ }))
275
+ return org
276
+ },
277
+
278
+ getOrg,
279
+
280
+ async listUserOrgs(userId) {
281
+ const os = requireOrgStore(store)
282
+ return await sessions.observeAsync(os.listUserOrgMemberships(userId))
283
+ },
284
+
285
+ async listOrgMembers(orgId) {
286
+ const os = requireOrgStore(store)
287
+ return await sessions.observeAsync(os.listOrgMembers(orgId))
288
+ },
289
+
290
+ async getOrgMember(orgId, userId) {
291
+ const os = requireOrgStore(store)
292
+ return await sessions.observeAsync(os.getOrgMember(orgId, userId))
293
+ },
294
+
295
+ async addOrgMember(orgId, userId, role = 'member') {
296
+ const os = requireOrgStore(store)
297
+ const cleanRole = role.trim()
298
+ if (!cleanRole)
299
+ throw orgError(400, 'prunelle: organization role is required')
300
+ const org = await sessions.observeAsync(os.getOrgById(orgId))
301
+ if (!org)
302
+ throw orgError(404, 'prunelle: organization not found')
303
+ const user = await sessions.observeAsync(store.getUserById(userId))
304
+ if (!user)
305
+ throw orgError(404, 'prunelle: user not found')
306
+ const existing = await sessions.observeAsync(os.getOrgMember(orgId, userId))
307
+ if (existing)
308
+ throw orgError(409, 'prunelle: user is already a member of this organization')
309
+ return await sessions.observeAsync(os.addOrgMember({
310
+ orgId,
311
+ userId,
312
+ role: cleanRole,
313
+ createdAt: Date.now(),
314
+ }))
315
+ },
316
+
317
+ async updateOrgMemberRole(orgId, userId, role) {
318
+ const os = requireOrgStore(store)
319
+ const cleanRole = role.trim()
320
+ if (!cleanRole)
321
+ throw orgError(400, 'prunelle: organization role is required')
322
+ const current = await sessions.observeAsync(os.getOrgMember(orgId, userId))
323
+ if (!current)
324
+ return undefined
325
+ if (current.role === 'owner' && cleanRole !== 'owner')
326
+ await assertNotLastOwner(orgId, userId, 'demote')
327
+ return await sessions.observeAsync(os.updateOrgMemberRole(orgId, userId, cleanRole))
328
+ },
329
+
330
+ async removeOrgMember(orgId, userId) {
331
+ const os = requireOrgStore(store)
332
+ const existing = await assertNotLastOwner(orgId, userId, 'remove')
333
+ if (!existing)
334
+ return false
335
+ return await sessions.observeAsync(os.removeOrgMember(orgId, userId))
336
+ },
337
+
338
+ ...invites,
339
+
340
+ async deleteOrg(orgId) {
341
+ const os = requireOrgStore(store)
342
+ await sessions.observeAsync(os.deleteOrg(orgId))
343
+ },
344
+ }
345
+ }
346
+
347
+ async function resolveGuardOrgRef(
348
+ orgOpt: NonNullable<GuardOptions['org']>,
349
+ ctx: RequestContext,
350
+ ): Promise<string | undefined> {
351
+ if (orgOpt === true)
352
+ return ctx.params.org ?? ctx.params.orgId ?? ctx.params.slug
353
+ if (typeof orgOpt === 'string') {
354
+ if (Object.prototype.hasOwnProperty.call(ctx.params, orgOpt))
355
+ return ctx.params[orgOpt]
356
+ return orgOpt
357
+ }
358
+ if (typeof orgOpt === 'function')
359
+ return await orgOpt(ctx)
360
+ return undefined
361
+ }
362
+
363
+ export function createAuthGuard<TUser extends AuthUser>(
364
+ resolve: (ctx: RequestContext) => Promise<{ user: PublicUser<TUser>, session: AuthSession } | undefined>,
365
+ orgs: OrgManager,
366
+ guardOpts: GuardOptions<TUser> = {},
367
+ ): Middleware {
368
+ const roles = guardOpts.role === undefined ? undefined : (Array.isArray(guardOpts.role) ? guardOpts.role : [guardOpts.role])
369
+ return async (ctx, next) => {
370
+ const resolved = await resolve(ctx)
371
+ if (!resolved) {
372
+ if (!wantsJson(ctx.request) && guardOpts.redirectTo) {
373
+ const nextParam = encodeURIComponent(ctx.url.pathname + ctx.url.search)
374
+ const sep = guardOpts.redirectTo.includes('?') ? '&' : '?'
375
+ return ctx.redirect(`${guardOpts.redirectTo}${sep}next=${nextParam}`, 302)
376
+ }
377
+ return fail(ctx, 401, 'Authentication required')
378
+ }
379
+
380
+ if (guardOpts.org) {
381
+ const ref = await resolveGuardOrgRef(guardOpts.org, ctx)
382
+ if (!ref)
383
+ return fail(ctx, 403, 'Forbidden')
384
+ const org = await orgs.getOrg(ref)
385
+ if (!org)
386
+ return fail(ctx, 403, 'Forbidden')
387
+ const membership = await orgs.getOrgMember(org.id, resolved.user.id)
388
+ if (!membership)
389
+ return fail(ctx, 403, 'Forbidden')
390
+ if (roles && !roles.includes(membership.role))
391
+ return fail(ctx, 403, 'Forbidden')
392
+ ctx.locals.org = org
393
+ ctx.locals.orgMembership = membership
394
+ }
395
+ else if (roles && !roles.includes(resolved.user.role)) {
396
+ return fail(ctx, 403, 'Forbidden')
397
+ }
398
+
399
+ if (guardOpts.allow && !(await guardOpts.allow(resolved.user, ctx)))
400
+ return fail(ctx, 403, 'Forbidden')
401
+ return next()
402
+ }
403
+ }
@@ -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
+ }