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