@prunellejs/auth 0.7.3 → 0.8.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/llms.txt +7 -5
- package/package.json +2 -2
- package/src/account.ts +18 -5
- package/src/crypto.ts +11 -13
- package/src/http.ts +22 -2
- package/src/index.ts +57 -34
- package/src/links.ts +4 -4
- package/src/oauth-routes.ts +3 -3
- package/src/org-routes.ts +1 -1
- package/src/orgs.ts +84 -36
- package/src/passkey-routes.ts +34 -24
- package/src/passkeys.ts +43 -49
- package/src/routes.ts +37 -12
- package/src/sqlite-ext.ts +5 -11
- package/src/sqlite.ts +78 -26
- package/src/store-ext.ts +19 -17
- package/src/store.ts +27 -2
- package/src/totp-routes.ts +43 -13
- package/src/totp.ts +18 -9
- package/src/webauthn-crypto.ts +61 -16
package/src/orgs.ts
CHANGED
|
@@ -8,6 +8,7 @@ import { safeRedirect, wantsJson } from 'prunelle/server'
|
|
|
8
8
|
import { randomToken, sha256Hex } from './crypto'
|
|
9
9
|
import { escapeHtml, fail, isValidEmail } from './http'
|
|
10
10
|
import { normalizeEmail } from './store'
|
|
11
|
+
import type { RemoveOrgMemberResult } from './store-ext'
|
|
11
12
|
import { createKeyedLock } from './store-ext'
|
|
12
13
|
|
|
13
14
|
const ORG_SLUG_RE = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/
|
|
@@ -23,21 +24,60 @@ function orgError(status: number, message: string): OrgError {
|
|
|
23
24
|
return err
|
|
24
25
|
}
|
|
25
26
|
|
|
26
|
-
//
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
27
|
+
// One in-process lock per store, shared by the org API and account deletion, for a store without the atomic last-owner methods.
|
|
28
|
+
const orgLocks = new WeakMap<object, ReturnType<typeof createKeyedLock>>()
|
|
29
|
+
|
|
30
|
+
function orgLockFor(store: object): ReturnType<typeof createKeyedLock> {
|
|
31
|
+
let lock = orgLocks.get(store)
|
|
32
|
+
if (lock === undefined) {
|
|
33
|
+
lock = createKeyedLock()
|
|
34
|
+
orgLocks.set(store, lock)
|
|
35
|
+
}
|
|
36
|
+
return lock
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Removes a member unless they are the org's last owner, in one step: through the store's atomic method, else under the store's in-process lock. */
|
|
40
|
+
export async function removeMemberUnlessLastOwner<TUser extends AuthUser>(store: AuthStore<TUser>, sessions: SessionManager<TUser>, orgId: string, userId: string): Promise<RemoveOrgMemberResult> {
|
|
41
|
+
if (store.removeOrgMemberIfNotLastOwner)
|
|
42
|
+
return await sessions.observeAsync(store.removeOrgMemberIfNotLastOwner(orgId, userId))
|
|
43
|
+
const os = requireOrgStore(store)
|
|
44
|
+
return orgLockFor(store)(orgId, async () => {
|
|
45
|
+
const current = await sessions.observeAsync(os.getOrgMember(orgId, userId))
|
|
46
|
+
if (!current)
|
|
47
|
+
return 'not-found'
|
|
48
|
+
if (current.role === 'owner' && (await sessions.observeAsync(os.listOrgMembers(orgId))).filter(m => m.role === 'owner').length <= 1)
|
|
49
|
+
return 'last-owner'
|
|
50
|
+
return await sessions.observeAsync(os.removeOrgMember(orgId, userId)) ? 'removed' : 'not-found'
|
|
51
|
+
})
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** What deleting a user does to their orgs: those they are the only member of go with them, and they leave the ones they own with others, refused with 409 where they are the last owner. Call `undo` if the deletion then fails. */
|
|
55
|
+
export async function leaveOrgsForDeletion<TUser extends AuthUser>(store: AuthStore<TUser>, sessions: SessionManager<TUser>, userId: string): Promise<{ deleted: string[], undo: () => Promise<void> }> {
|
|
30
56
|
const deleted: string[] = []
|
|
57
|
+
const left: OrgMembership[] = []
|
|
58
|
+
const undo = async (): Promise<void> => {
|
|
59
|
+
for (const membership of left)
|
|
60
|
+
await store.addOrgMember?.(membership)
|
|
61
|
+
}
|
|
62
|
+
if (!store.listUserOrgMemberships || !store.listOrgMembers || !store.getOrgMember)
|
|
63
|
+
return { deleted, undo }
|
|
31
64
|
for (const { org, role } of await store.listUserOrgMemberships(userId)) {
|
|
32
65
|
if (role !== 'owner')
|
|
33
66
|
continue
|
|
34
|
-
|
|
35
|
-
if (members.length === 1)
|
|
67
|
+
if ((await store.listOrgMembers(org.id)).length === 1) {
|
|
36
68
|
deleted.push(org.id)
|
|
37
|
-
|
|
69
|
+
continue
|
|
70
|
+
}
|
|
71
|
+
const membership = await store.getOrgMember(org.id, userId)
|
|
72
|
+
const result = await removeMemberUnlessLastOwner(store, sessions, org.id, userId)
|
|
73
|
+
if (result === 'last-owner') {
|
|
74
|
+
await undo()
|
|
38
75
|
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`)
|
|
76
|
+
}
|
|
77
|
+
if (result === 'removed' && membership)
|
|
78
|
+
left.push(membership)
|
|
39
79
|
}
|
|
40
|
-
return deleted
|
|
80
|
+
return { deleted, undo }
|
|
41
81
|
}
|
|
42
82
|
|
|
43
83
|
export function slugifyOrgName(name: string): string {
|
|
@@ -196,14 +236,26 @@ function createInviteMethods<TUser extends AuthUser>(
|
|
|
196
236
|
if (!consumed)
|
|
197
237
|
throw orgError(400, 'prunelle: invitation has already been used')
|
|
198
238
|
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
239
|
+
try {
|
|
240
|
+
const existing = await sessions.observeAsync(os.getOrgMember(org.id, user.id))
|
|
241
|
+
const membership = existing ?? await sessions.observeAsync(os.addOrgMember({
|
|
242
|
+
orgId: org.id,
|
|
243
|
+
userId: user.id,
|
|
244
|
+
role: consumed.role,
|
|
245
|
+
createdAt: Date.now(),
|
|
246
|
+
}))
|
|
247
|
+
return { org, membership }
|
|
248
|
+
}
|
|
249
|
+
catch (err) {
|
|
250
|
+
// The invitee did nothing wrong: put the invitation back so the same link works once the store recovers.
|
|
251
|
+
try {
|
|
252
|
+
await sessions.observeAsync(os.createOrgInvite(consumed))
|
|
253
|
+
}
|
|
254
|
+
catch (restoreErr) {
|
|
255
|
+
console.error('[prunelle/auth] failed to restore an org invite after a failed acceptance:', restoreErr)
|
|
256
|
+
}
|
|
257
|
+
throw err
|
|
258
|
+
}
|
|
207
259
|
},
|
|
208
260
|
|
|
209
261
|
async revokeOrgInvite(orgId, inviteId) {
|
|
@@ -217,7 +269,7 @@ export function createOrgManager<TUser extends AuthUser = AuthUser>(deps: OrgMan
|
|
|
217
269
|
const { store, sessions } = deps
|
|
218
270
|
const inviteTtlMs = deps.orgInviteTtlMs ?? DEFAULT_ORG_INVITE_TTL_MS
|
|
219
271
|
const invites = createInviteMethods(deps, inviteTtlMs)
|
|
220
|
-
const withOrgLock =
|
|
272
|
+
const withOrgLock = orgLockFor(store)
|
|
221
273
|
|
|
222
274
|
async function getOrg(idOrSlug: string): Promise<Organization | undefined> {
|
|
223
275
|
const os = requireOrgStore(store)
|
|
@@ -338,19 +390,10 @@ export function createOrgManager<TUser extends AuthUser = AuthUser>(deps: OrgMan
|
|
|
338
390
|
},
|
|
339
391
|
|
|
340
392
|
async removeOrgMember(orgId, userId) {
|
|
341
|
-
const
|
|
342
|
-
if (
|
|
343
|
-
|
|
344
|
-
|
|
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
|
-
})
|
|
393
|
+
const res = await removeMemberUnlessLastOwner(store, sessions, orgId, userId)
|
|
394
|
+
if (res === 'last-owner')
|
|
395
|
+
throw orgError(400, 'prunelle: cannot remove the last owner of an organization')
|
|
396
|
+
return res === 'removed'
|
|
354
397
|
},
|
|
355
398
|
|
|
356
399
|
...invites,
|
|
@@ -368,16 +411,21 @@ async function resolveGuardOrgRef(
|
|
|
368
411
|
): Promise<string | undefined> {
|
|
369
412
|
if (orgOpt === true)
|
|
370
413
|
return ctx.params.org ?? ctx.params.orgId ?? ctx.params.slug
|
|
371
|
-
if (typeof orgOpt === 'string')
|
|
372
|
-
|
|
373
|
-
return ctx.params[orgOpt]
|
|
374
|
-
return orgOpt
|
|
375
|
-
}
|
|
414
|
+
if (typeof orgOpt === 'string')
|
|
415
|
+
return Object.hasOwn(ctx.params, orgOpt) ? ctx.params[orgOpt] : undefined
|
|
376
416
|
if (typeof orgOpt === 'function')
|
|
377
417
|
return await orgOpt(ctx)
|
|
378
418
|
return undefined
|
|
379
419
|
}
|
|
380
420
|
|
|
421
|
+
// Built-in org roles by rank: a guard for one lets the higher ones through. A custom role matches only itself.
|
|
422
|
+
const ORG_ROLE_RANK: Readonly<Record<string, number>> = { member: 1, admin: 2, owner: 3 }
|
|
423
|
+
|
|
424
|
+
function hasOrgRole(held: string, wanted: readonly string[]): boolean {
|
|
425
|
+
const rank = ORG_ROLE_RANK[held]
|
|
426
|
+
return wanted.some(role => role === held || (rank !== undefined && rank > (ORG_ROLE_RANK[role] ?? Infinity)))
|
|
427
|
+
}
|
|
428
|
+
|
|
381
429
|
export function createAuthGuard<TUser extends AuthUser>(
|
|
382
430
|
resolve: (ctx: RequestContext) => Promise<{ user: PublicUser<TUser>, session: AuthSession } | undefined>,
|
|
383
431
|
orgs: OrgManager,
|
|
@@ -405,7 +453,7 @@ export function createAuthGuard<TUser extends AuthUser>(
|
|
|
405
453
|
const membership = await orgs.getOrgMember(org.id, resolved.user.id)
|
|
406
454
|
if (!membership)
|
|
407
455
|
return fail(ctx, 403, 'Forbidden')
|
|
408
|
-
if (roles && !
|
|
456
|
+
if (roles && !hasOrgRole(membership.role, roles))
|
|
409
457
|
return fail(ctx, 403, 'Forbidden')
|
|
410
458
|
ctx.locals.org = org
|
|
411
459
|
ctx.locals.orgMembership = membership
|
package/src/passkey-routes.ts
CHANGED
|
@@ -1,18 +1,20 @@
|
|
|
1
1
|
// HTTP routes for WebAuthn passkeys: registration, passwordless login, 2FA verification, listing, and deletion.
|
|
2
2
|
|
|
3
3
|
import type { RequestContext } from 'prunelle/server'
|
|
4
|
-
import type { AuthRouteRegistrar } from './http'
|
|
4
|
+
import type { AuthLimits, AuthRouteRegistrar } from './http'
|
|
5
5
|
import type { AssertionVerifyInput, PasskeyError, PasskeyManager, RegisterVerifyInput } from './passkeys'
|
|
6
6
|
import type { SessionManager } from './session'
|
|
7
7
|
import type { AuthStore, AuthUser } from './store'
|
|
8
8
|
import type { TotpManager } from './totp'
|
|
9
9
|
import { safeRedirect, wantsJson } from 'prunelle/server'
|
|
10
|
+
import { freshSignin, keepOnlyThisSession } from './account'
|
|
10
11
|
import { fail, parseJsonBody } from './http'
|
|
11
12
|
import { toPublicUser } from './store'
|
|
12
13
|
import { respondTwoFactorChallenge } from './totp'
|
|
13
14
|
|
|
14
15
|
export interface PasskeyRoutesDeps<TUser extends AuthUser = AuthUser> {
|
|
15
16
|
authRoute: AuthRouteRegistrar
|
|
17
|
+
limits: AuthLimits
|
|
16
18
|
store: AuthStore<TUser>
|
|
17
19
|
sessions: SessionManager<TUser>
|
|
18
20
|
passkeys: PasskeyManager
|
|
@@ -69,12 +71,12 @@ function asAssertionInput(body: Record<string, unknown>): AssertionVerifyInput |
|
|
|
69
71
|
}
|
|
70
72
|
|
|
71
73
|
export function registerPasskeyRoutes<TUser extends AuthUser = AuthUser>(deps: PasskeyRoutesDeps<TUser>): void {
|
|
72
|
-
const { authRoute, store, sessions, passkeys, totp, twoFactorRedirect, defaultRedirect, requireEmailVerification } = deps
|
|
74
|
+
const { authRoute, limits, store, sessions, passkeys, totp, twoFactorRedirect, defaultRedirect, requireEmailVerification } = deps
|
|
73
75
|
|
|
74
76
|
authRoute('POST', '/passkeys/register/options', { limit: 'passkey-reg' }, async (ctx) => {
|
|
75
|
-
const resolved = await
|
|
76
|
-
if (
|
|
77
|
-
return
|
|
77
|
+
const resolved = await freshSignin(ctx, sessions)
|
|
78
|
+
if (resolved instanceof Response)
|
|
79
|
+
return resolved
|
|
78
80
|
try {
|
|
79
81
|
const options = await passkeys.createRegisterOptions(ctx, resolved.user)
|
|
80
82
|
return ctx.json({ ok: true, options }, { status: 200 })
|
|
@@ -85,9 +87,9 @@ export function registerPasskeyRoutes<TUser extends AuthUser = AuthUser>(deps: P
|
|
|
85
87
|
})
|
|
86
88
|
|
|
87
89
|
authRoute('POST', '/passkeys/register/verify', { limit: 'passkey-reg' }, async (ctx) => {
|
|
88
|
-
const resolved = await
|
|
89
|
-
if (
|
|
90
|
-
return
|
|
90
|
+
const resolved = await freshSignin(ctx, sessions)
|
|
91
|
+
if (resolved instanceof Response)
|
|
92
|
+
return resolved
|
|
91
93
|
const raw = await parseJsonBody(ctx)
|
|
92
94
|
if (raw instanceof Response)
|
|
93
95
|
return raw
|
|
@@ -96,6 +98,7 @@ export function registerPasskeyRoutes<TUser extends AuthUser = AuthUser>(deps: P
|
|
|
96
98
|
return fail(ctx, 400, 'Invalid passkey registration payload')
|
|
97
99
|
try {
|
|
98
100
|
const passkey = await passkeys.verifyRegistration(ctx, resolved.user.id, input)
|
|
101
|
+
await keepOnlyThisSession(ctx, sessions, store, resolved.user.id)
|
|
99
102
|
return ctx.json({ ok: true, passkey }, { status: 201 })
|
|
100
103
|
}
|
|
101
104
|
catch (err) {
|
|
@@ -167,6 +170,11 @@ export function registerPasskeyRoutes<TUser extends AuthUser = AuthUser>(deps: P
|
|
|
167
170
|
const pending = totp.readPendingCookie(ctx)
|
|
168
171
|
if (!pending)
|
|
169
172
|
return fail(ctx, 401, 'Two-factor session expired or invalid')
|
|
173
|
+
const locked = limits.refuseLockedSecondFactor(ctx, pending.userId)
|
|
174
|
+
if (locked) {
|
|
175
|
+
totp.clearPendingCookie(ctx)
|
|
176
|
+
return locked
|
|
177
|
+
}
|
|
170
178
|
if (!pending.methods.includes('passkey'))
|
|
171
179
|
return fail(ctx, 403, 'Passkey cannot be used as second factor for this sign-in')
|
|
172
180
|
const raw = await parseJsonBody(ctx)
|
|
@@ -177,22 +185,23 @@ export function registerPasskeyRoutes<TUser extends AuthUser = AuthUser>(deps: P
|
|
|
177
185
|
return fail(ctx, 400, 'Invalid passkey assertion payload')
|
|
178
186
|
try {
|
|
179
187
|
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
188
|
}
|
|
193
189
|
catch (err) {
|
|
194
|
-
|
|
190
|
+
const refused = limits.countFailedSecondFactor(ctx, pending.userId)
|
|
191
|
+
if (refused)
|
|
192
|
+
totp.clearPendingCookie(ctx)
|
|
193
|
+
return refused ?? respondPasskeyErr(ctx, err)
|
|
195
194
|
}
|
|
195
|
+
const userRecord = await sessions.observeAsync(store.getUserById(pending.userId))
|
|
196
|
+
totp.clearPendingCookie(ctx)
|
|
197
|
+
if (!userRecord)
|
|
198
|
+
return fail(ctx, 401, 'Unable to resolve user account')
|
|
199
|
+
const pub = toPublicUser(userRecord)
|
|
200
|
+
await sessions.createSessionForUser(userRecord.id, ctx, pub)
|
|
201
|
+
const redirect = safeRedirect(typeof raw.redirect === 'string' ? raw.redirect : (typeof raw.next === 'string' ? raw.next : pending.redirect), defaultRedirect)
|
|
202
|
+
if (wantsJson(ctx.request))
|
|
203
|
+
return ctx.json({ ok: true, user: pub }, { status: 200 })
|
|
204
|
+
return ctx.redirect(redirect, 303)
|
|
196
205
|
})
|
|
197
206
|
|
|
198
207
|
authRoute('GET', '/passkeys', {}, async (ctx) => {
|
|
@@ -204,15 +213,16 @@ export function registerPasskeyRoutes<TUser extends AuthUser = AuthUser>(deps: P
|
|
|
204
213
|
})
|
|
205
214
|
|
|
206
215
|
authRoute('POST', '/passkeys/delete', { limit: 'passkey-del', readBody: true }, async (ctx, body) => {
|
|
207
|
-
const resolved = await
|
|
208
|
-
if (
|
|
209
|
-
return
|
|
216
|
+
const resolved = await freshSignin(ctx, sessions)
|
|
217
|
+
if (resolved instanceof Response)
|
|
218
|
+
return resolved
|
|
210
219
|
const credentialId = (body.id ?? body.credentialId ?? '').trim()
|
|
211
220
|
if (!credentialId)
|
|
212
221
|
return fail(ctx, 400, 'Passkey id is required')
|
|
213
222
|
const deleted = await passkeys.deletePasskey(resolved.user.id, credentialId)
|
|
214
223
|
if (!deleted)
|
|
215
224
|
return fail(ctx, 404, 'Passkey not found')
|
|
225
|
+
await keepOnlyThisSession(ctx, sessions, store, resolved.user.id)
|
|
216
226
|
if (wantsJson(ctx.request))
|
|
217
227
|
return ctx.json({ ok: true }, { status: 200 })
|
|
218
228
|
return ctx.redirect(safeRedirect(body.redirect ?? body.next, defaultRedirect), 303)
|
package/src/passkeys.ts
CHANGED
|
@@ -3,14 +3,14 @@
|
|
|
3
3
|
import type { RequestContext } from 'prunelle/server'
|
|
4
4
|
import type { SessionManager } from './session'
|
|
5
5
|
import type { AuthStore, AuthUser, PasskeyRecord, PasskeySummary } from './store'
|
|
6
|
+
import { createHmac } from 'node:crypto'
|
|
6
7
|
import { safeEqual } from 'prunelle/server'
|
|
7
|
-
import { fromBase64Url, randomToken, sha256Bytes,
|
|
8
|
-
import { authCookie } from './http'
|
|
9
|
-
import { toPasskeySummary } from './store'
|
|
10
|
-
import { COSE_ALG_EDDSA, COSE_ALG_ES256, COSE_ALG_RS256, coseKeyToJwk,
|
|
8
|
+
import { fromBase64Url, randomToken, sha256Bytes, sha256Hex, signJson, toBase64Url, verifyJson } from './crypto'
|
|
9
|
+
import { authCookie, linkOrigin } from './http'
|
|
10
|
+
import { normalizeEmail, toPasskeySummary } from './store'
|
|
11
|
+
import { COSE_ALG_EDDSA, COSE_ALG_ES256, COSE_ALG_RS256, coseKeyToJwk, decodeCborExact, importPasskeyKey, parseAuthenticatorData, verifyWebAuthnSignature } from './webauthn-crypto'
|
|
11
12
|
|
|
12
13
|
const CHALLENGE_TTL_MS = 5 * 60 * 1000
|
|
13
|
-
const MAX_ACTIVE_CHALLENGES = 10_000
|
|
14
14
|
|
|
15
15
|
export type PasskeyUserVerification = 'required' | 'preferred' | 'discouraged'
|
|
16
16
|
|
|
@@ -88,7 +88,6 @@ export interface PasskeyManager {
|
|
|
88
88
|
verifyAssertion(ctx: RequestContext, purpose: 'login' | '2fa', input: AssertionVerifyInput, expectedUserId?: string): Promise<{ passkey: PasskeyRecord, userId: string }>
|
|
89
89
|
listPasskeys(userId: string): Promise<PasskeySummary[]>
|
|
90
90
|
deletePasskey(userId: string, credentialId: string): Promise<boolean>
|
|
91
|
-
pruneChallenges(): void
|
|
92
91
|
}
|
|
93
92
|
|
|
94
93
|
function requirePasskeyStore<TUser extends AuthUser>(store: AuthStore<TUser>) {
|
|
@@ -151,10 +150,10 @@ async function performRegistrationVerify<TUser extends AuthUser>(
|
|
|
151
150
|
|
|
152
151
|
let authDataBytes: Uint8Array
|
|
153
152
|
try {
|
|
154
|
-
const decoded =
|
|
155
|
-
if (!(decoded
|
|
153
|
+
const decoded = decodeCborExact(fromBase64Url(input.response.attestationObject))
|
|
154
|
+
if (!(decoded instanceof Map))
|
|
156
155
|
throw new Error('attestationObject must be a CBOR map')
|
|
157
|
-
const rawAuthData = decoded.
|
|
156
|
+
const rawAuthData = decoded.get('authData')
|
|
158
157
|
if (!(rawAuthData instanceof Uint8Array))
|
|
159
158
|
throw new Error('attestationObject missing authData')
|
|
160
159
|
authDataBytes = rawAuthData
|
|
@@ -182,6 +181,12 @@ async function performRegistrationVerify<TUser extends AuthUser>(
|
|
|
182
181
|
catch (err) {
|
|
183
182
|
throw passkeyError(400, err instanceof Error ? err.message : 'Unsupported COSE public key')
|
|
184
183
|
}
|
|
184
|
+
try {
|
|
185
|
+
await importPasskeyKey(keyInfo.jwk, keyInfo.algorithm)
|
|
186
|
+
}
|
|
187
|
+
catch {
|
|
188
|
+
throw passkeyError(400, 'Passkey public key is not a valid key for its algorithm, such as an EC point off the curve')
|
|
189
|
+
}
|
|
185
190
|
|
|
186
191
|
const credentialId = toBase64Url(parsed.credentialId)
|
|
187
192
|
const providedId = input.id ?? input.rawId
|
|
@@ -260,65 +265,62 @@ async function performAssertionVerify<TUser extends AuthUser>(
|
|
|
260
265
|
return { passkey: { ...passkey, signCount: parsed.signCount, lastUsedAt: now }, userId: passkey.userId }
|
|
261
266
|
}
|
|
262
267
|
|
|
268
|
+
// A credential id no authenticator holds, the same on every call for one email.
|
|
269
|
+
function decoyCredentialId(secret: string, email: string): string {
|
|
270
|
+
return toBase64Url(new Uint8Array(createHmac('sha256', secret).update(`passkey-decoy:${normalizeEmail(email)}`).digest().subarray(0, 16)))
|
|
271
|
+
}
|
|
272
|
+
|
|
263
273
|
export function createPasskeyManager<TUser extends AuthUser = AuthUser>(deps: PasskeyManagerDeps<TUser>): PasskeyManager {
|
|
264
274
|
const { store, sessions, secret, challengeCookieName, getSite, options, isSecureCookie } = deps
|
|
265
275
|
const userVerificationFor = (purpose: 'register' | 'login' | '2fa'): PasskeyUserVerification =>
|
|
266
276
|
options?.userVerification ?? (purpose === '2fa' ? 'preferred' : 'required')
|
|
267
|
-
const activeChallenges = new Map<string, number>()
|
|
268
277
|
|
|
269
278
|
function resolveExpectedOrigin(ctx: RequestContext): string {
|
|
270
|
-
|
|
279
|
+
const origin = options?.origin ?? linkOrigin(getSite(), ctx.url)
|
|
280
|
+
if (origin === undefined)
|
|
281
|
+
throw passkeyError(500, 'prunelle: passkeys need the app\'s origin, which the Host header cannot be trusted for: set site in prunelle.config.ts (or passkeys.origin in createAuth())')
|
|
282
|
+
return origin
|
|
271
283
|
}
|
|
272
284
|
|
|
273
285
|
function resolveRpId(ctx: RequestContext): string {
|
|
274
286
|
return options?.rpId ?? new URL(resolveExpectedOrigin(ctx)).hostname
|
|
275
287
|
}
|
|
276
288
|
|
|
277
|
-
|
|
278
|
-
|
|
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()
|
|
289
|
+
// The challenge is a single-use token of the store, so another instance or a restart sees it, and pruneExpired drops the unused ones.
|
|
290
|
+
async function issueChallenge(ctx: RequestContext, purpose: 'register' | 'login' | '2fa', userId?: string): Promise<string> {
|
|
288
291
|
const challenge = randomToken(32)
|
|
289
292
|
const exp = Date.now() + CHALLENGE_TTL_MS
|
|
290
|
-
|
|
293
|
+
await sessions.observeAsync(store.createToken({ tokenHash: sha256Hex(challenge), email: '', kind: 'passkey-challenge', expiresAt: exp }))
|
|
291
294
|
const payload: ChallengeCookiePayload = {
|
|
292
295
|
challenge,
|
|
293
296
|
purpose,
|
|
294
297
|
...(userId !== undefined ? { userId } : {}),
|
|
295
298
|
exp,
|
|
296
299
|
}
|
|
297
|
-
ctx.cookies.set(challengeCookieName,
|
|
300
|
+
ctx.cookies.set(challengeCookieName, signJson(secret(), 'webauthn', payload), authCookie(isSecureCookie(ctx), Math.floor(CHALLENGE_TTL_MS / 1000)))
|
|
298
301
|
return challenge
|
|
299
302
|
}
|
|
300
303
|
|
|
301
|
-
function consumeChallenge(ctx: RequestContext, purpose: 'register' | 'login' | '2fa', expectedUserId?: string): string {
|
|
304
|
+
async function consumeChallenge(ctx: RequestContext, purpose: 'register' | 'login' | '2fa', expectedUserId?: string): Promise<string> {
|
|
302
305
|
const raw = ctx.cookies.get(challengeCookieName)
|
|
303
306
|
ctx.cookies.delete(challengeCookieName, { path: '/' })
|
|
304
307
|
if (!raw)
|
|
305
308
|
throw passkeyError(400, 'Missing passkey challenge')
|
|
306
|
-
const payload =
|
|
309
|
+
const payload = verifyJson<ChallengeCookiePayload>(secret(), 'webauthn', raw)
|
|
307
310
|
const now = Date.now()
|
|
308
311
|
if (!payload || payload.exp <= now || payload.purpose !== purpose)
|
|
309
312
|
throw passkeyError(400, 'Invalid or expired passkey challenge')
|
|
310
313
|
if (expectedUserId !== undefined && payload.userId !== expectedUserId)
|
|
311
314
|
throw passkeyError(400, 'Passkey challenge does not match user')
|
|
312
|
-
const
|
|
313
|
-
|
|
314
|
-
if (storedExp === undefined || storedExp <= now)
|
|
315
|
+
const stored = await sessions.observeAsync(store.consumeToken(sha256Hex(payload.challenge), 'passkey-challenge'))
|
|
316
|
+
if (stored === undefined || stored.expiresAt <= now)
|
|
315
317
|
throw passkeyError(400, 'Passkey challenge expired or already used')
|
|
316
318
|
return payload.challenge
|
|
317
319
|
}
|
|
318
320
|
|
|
319
|
-
function ceremonyFor(ctx: RequestContext, purpose: 'register' | 'login' | '2fa', expectedUserId?: string): CeremonyContext {
|
|
321
|
+
async function ceremonyFor(ctx: RequestContext, purpose: 'register' | 'login' | '2fa', expectedUserId?: string): Promise<CeremonyContext> {
|
|
320
322
|
return {
|
|
321
|
-
expectedChallenge: consumeChallenge(ctx, purpose, expectedUserId),
|
|
323
|
+
expectedChallenge: await consumeChallenge(ctx, purpose, expectedUserId),
|
|
322
324
|
expectedOrigin: resolveExpectedOrigin(ctx),
|
|
323
325
|
expectedRpId: resolveRpId(ctx),
|
|
324
326
|
userVerification: userVerificationFor(purpose),
|
|
@@ -326,14 +328,12 @@ export function createPasskeyManager<TUser extends AuthUser = AuthUser>(deps: Pa
|
|
|
326
328
|
}
|
|
327
329
|
|
|
328
330
|
return {
|
|
329
|
-
pruneChallenges,
|
|
330
|
-
|
|
331
331
|
async createRegisterOptions(ctx, user) {
|
|
332
332
|
const ps = requirePasskeyStore(store)
|
|
333
333
|
const existing = await sessions.observeAsync(ps.listPasskeys(user.id))
|
|
334
334
|
const rpId = resolveRpId(ctx)
|
|
335
335
|
const rpName = options?.rpName ?? rpId
|
|
336
|
-
const challenge = issueChallenge(ctx, 'register', user.id)
|
|
336
|
+
const challenge = await issueChallenge(ctx, 'register', user.id)
|
|
337
337
|
return {
|
|
338
338
|
challenge,
|
|
339
339
|
rp: { name: rpName, id: rpId },
|
|
@@ -361,8 +361,8 @@ export function createPasskeyManager<TUser extends AuthUser = AuthUser>(deps: Pa
|
|
|
361
361
|
}
|
|
362
362
|
},
|
|
363
363
|
|
|
364
|
-
verifyRegistration(ctx, userId, input) {
|
|
365
|
-
return performRegistrationVerify(store, sessions, userId, input, ceremonyFor(ctx, 'register', userId))
|
|
364
|
+
async verifyRegistration(ctx, userId, input) {
|
|
365
|
+
return performRegistrationVerify(store, sessions, userId, input, await ceremonyFor(ctx, 'register', userId))
|
|
366
366
|
},
|
|
367
367
|
|
|
368
368
|
async createAssertionOptions(ctx, purpose, opts) {
|
|
@@ -381,20 +381,14 @@ export function createPasskeyManager<TUser extends AuthUser = AuthUser>(deps: Pa
|
|
|
381
381
|
}))
|
|
382
382
|
}
|
|
383
383
|
else if (opts?.email) {
|
|
384
|
+
// The same shape whether the email has passkeys, has none or is unknown, so the answer never tells which: no transports, and a decoy id in place of none.
|
|
384
385
|
const user = await sessions.observeAsync(store.getUserByEmail(opts.email))
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
allowCredentials = list.map(p => ({
|
|
389
|
-
type: 'public-key',
|
|
390
|
-
id: p.id,
|
|
391
|
-
...(p.transports ? { transports: p.transports } : {}),
|
|
392
|
-
}))
|
|
393
|
-
}
|
|
394
|
-
}
|
|
386
|
+
const list = user ? await sessions.observeAsync(ps.listPasskeys(user.id)) : []
|
|
387
|
+
const ids = list.length > 0 ? list.map(p => p.id) : [decoyCredentialId(secret(), opts.email)]
|
|
388
|
+
allowCredentials = ids.map(id => ({ type: 'public-key', id }))
|
|
395
389
|
}
|
|
396
390
|
|
|
397
|
-
const challenge = issueChallenge(ctx, purpose, opts?.userId)
|
|
391
|
+
const challenge = await issueChallenge(ctx, purpose, opts?.userId)
|
|
398
392
|
return {
|
|
399
393
|
challenge,
|
|
400
394
|
timeout: CHALLENGE_TTL_MS,
|
|
@@ -404,8 +398,8 @@ export function createPasskeyManager<TUser extends AuthUser = AuthUser>(deps: Pa
|
|
|
404
398
|
}
|
|
405
399
|
},
|
|
406
400
|
|
|
407
|
-
verifyAssertion(ctx, purpose, input, expectedUserId) {
|
|
408
|
-
return performAssertionVerify(store, sessions, input, ceremonyFor(ctx, purpose, expectedUserId), expectedUserId)
|
|
401
|
+
async verifyAssertion(ctx, purpose, input, expectedUserId) {
|
|
402
|
+
return performAssertionVerify(store, sessions, input, await ceremonyFor(ctx, purpose, expectedUserId), expectedUserId)
|
|
409
403
|
},
|
|
410
404
|
|
|
411
405
|
async listPasskeys(userId) {
|
package/src/routes.ts
CHANGED
|
@@ -30,6 +30,29 @@ function respondVerificationAccepted(ctx: RequestContext, redirectTarget: string
|
|
|
30
30
|
return ctx.redirect(formPagePath(ctx, 'notice', sent.code) ?? redirectTarget, 303)
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
+
type UnverifiedPatch<TUser extends AuthUser> = Partial<Omit<TUser, 'id' | 'createdAt' | 'email'>>
|
|
34
|
+
|
|
35
|
+
// The sign-up rollback's writes, which must lose to a verification: atomic through the store's own methods, else a read then a write.
|
|
36
|
+
async function updateIfUnverified<TUser extends AuthUser>({ store, sessions }: AuthRoutesDeps<TUser>, id: string, updatedAt: number, patch: UnverifiedPatch<TUser>): Promise<void> {
|
|
37
|
+
if (store.updateUserIfUnverified) {
|
|
38
|
+
await sessions.observeAsync(store.updateUserIfUnverified(id, updatedAt, patch))
|
|
39
|
+
return
|
|
40
|
+
}
|
|
41
|
+
const cur = await sessions.observeAsync(store.getUserById(id))
|
|
42
|
+
if (cur && !cur.emailVerified && cur.updatedAt === updatedAt)
|
|
43
|
+
await sessions.observeAsync(store.updateUser(id, patch as Partial<Omit<TUser, 'id' | 'createdAt'>>))
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function deleteIfUnverified<TUser extends AuthUser>({ store, sessions }: AuthRoutesDeps<TUser>, id: string, updatedAt: number): Promise<void> {
|
|
47
|
+
if (store.deleteUserIfUnverified) {
|
|
48
|
+
await sessions.observeAsync(store.deleteUserIfUnverified(id, updatedAt))
|
|
49
|
+
return
|
|
50
|
+
}
|
|
51
|
+
const cur = await sessions.observeAsync(store.getUserById(id))
|
|
52
|
+
if (cur && !cur.emailVerified && cur.updatedAt === updatedAt)
|
|
53
|
+
await sessions.observeAsync(store.deleteUser(id))
|
|
54
|
+
}
|
|
55
|
+
|
|
33
56
|
// A second sign-up on an unverified address contests it: the mailbox owner cannot tell whose mailed link they click, so neither party's password or name is kept, and the link alone signs the owner in (#75).
|
|
34
57
|
async function reRegisterUnverified<TUser extends AuthUser>(
|
|
35
58
|
deps: AuthRoutesDeps<TUser>,
|
|
@@ -49,12 +72,11 @@ async function reRegisterUnverified<TUser extends AuthUser>(
|
|
|
49
72
|
await sessions.observeAsync(store.deleteUserSessions(existing.id))
|
|
50
73
|
await sessions.observeAsync(store.deleteUserOAuthAccounts(existing.id))
|
|
51
74
|
const patch = { passwordHash: undefined, name: undefined } as Partial<Omit<TUser, 'id' | 'createdAt'>>
|
|
52
|
-
|
|
75
|
+
// A store's updateUser may return nothing, so the cleared state is read back for the rollback to compare against.
|
|
76
|
+
const cleared = await sessions.observeAsync(store.updateUser(existing.id, patch)) ?? await sessions.observeAsync(store.getUserById(existing.id))
|
|
53
77
|
const restore = async (): Promise<void> => {
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
return
|
|
57
|
-
await sessions.observeAsync(store.updateUser(existing.id, { passwordHash: prevHash, name: prevName } as Partial<Omit<TUser, 'id' | 'createdAt'>>))
|
|
78
|
+
if (cleared)
|
|
79
|
+
await updateIfUnverified(deps, existing.id, cleared.updatedAt, { passwordHash: prevHash, name: prevName } as UnverifiedPatch<TUser>)
|
|
58
80
|
}
|
|
59
81
|
try {
|
|
60
82
|
await issueLink('verify-email', existing.id, existing.email, linkOrigin, redirectTarget, { onFailure: restore })
|
|
@@ -134,12 +156,7 @@ async function signUpPendingVerification<TUser extends AuthUser>(
|
|
|
134
156
|
throw err
|
|
135
157
|
}
|
|
136
158
|
|
|
137
|
-
const deleteIfUnchanged =
|
|
138
|
-
const cur = await sessions.observeAsync(store.getUserById(user.id))
|
|
139
|
-
if (!cur || cur.emailVerified || cur.updatedAt !== user.updatedAt)
|
|
140
|
-
return
|
|
141
|
-
await sessions.observeAsync(store.deleteUser(user.id))
|
|
142
|
-
}
|
|
159
|
+
const deleteIfUnchanged = (): Promise<void> => deleteIfUnverified(deps, user.id, user.updatedAt)
|
|
143
160
|
try {
|
|
144
161
|
// A mail outage deletes the account once the send fails, so it does not lock the address out.
|
|
145
162
|
await issueLink('verify-email', user.id, user.email, linkOrigin, redirectTarget, { onFailure: deleteIfUnchanged })
|
|
@@ -240,7 +257,15 @@ export function registerAuthRoutes<TUser extends AuthUser = AuthUser>(deps: Auth
|
|
|
240
257
|
if (await sessions.observeAsync(store.getUserByEmail(email)))
|
|
241
258
|
return respondAuthError(ctx, 409, messages['signup.email-taken'])
|
|
242
259
|
|
|
243
|
-
|
|
260
|
+
let user: PublicUser<TUser>
|
|
261
|
+
try {
|
|
262
|
+
user = await createUser({ email, password, name } as CreateUserInput<TUser>)
|
|
263
|
+
}
|
|
264
|
+
catch (err) {
|
|
265
|
+
if (await sessions.observeAsync(store.getUserByEmail(email)))
|
|
266
|
+
return respondAuthError(ctx, 409, messages['signup.email-taken'])
|
|
267
|
+
throw err
|
|
268
|
+
}
|
|
244
269
|
await sessions.createSessionForUser(user.id, ctx, user)
|
|
245
270
|
|
|
246
271
|
if (wantsJson(ctx.request))
|
package/src/sqlite-ext.ts
CHANGED
|
@@ -14,7 +14,7 @@ import type {
|
|
|
14
14
|
UserExportExt,
|
|
15
15
|
UserOrgSummary,
|
|
16
16
|
} from './store-ext'
|
|
17
|
-
import { toPasskeySummary } from './store-ext'
|
|
17
|
+
import { toPasskeySummary, userInvitationsExport } from './store-ext'
|
|
18
18
|
|
|
19
19
|
interface TotpRow {
|
|
20
20
|
user_id: string
|
|
@@ -504,7 +504,7 @@ export function createSqliteStoreExt(db: Database): SqliteStoreExtHooks {
|
|
|
504
504
|
exportUserExt(userId, email, now) {
|
|
505
505
|
const q = ensureIfPresent()
|
|
506
506
|
if (!q)
|
|
507
|
-
return { passkeys: [], organizations: [], invitations: [] }
|
|
507
|
+
return { passkeys: [], organizations: [], invitations: [], sentInvitations: [] }
|
|
508
508
|
const totpRec = rowToTotp(q.getTotp.get(userId))
|
|
509
509
|
const rcCount = q.listRecovery.all(userId).length
|
|
510
510
|
const passkeys = q.listPasskeys.all(userId).map(r => toPasskeySummary(rowToPasskey(r)!))
|
|
@@ -515,19 +515,13 @@ export function createSqliteStoreExt(db: Database): SqliteStoreExtHooks {
|
|
|
515
515
|
role: r.role,
|
|
516
516
|
joinedAt: r.joined_at,
|
|
517
517
|
}))
|
|
518
|
-
const
|
|
519
|
-
|
|
520
|
-
orgId: r.org_id,
|
|
521
|
-
email: r.email,
|
|
522
|
-
role: r.role,
|
|
523
|
-
expiresAt: r.expires_at,
|
|
524
|
-
createdAt: r.created_at,
|
|
525
|
-
}))
|
|
518
|
+
const normEmail = email.trim().toLowerCase()
|
|
519
|
+
const invites = q.listUserInvites.all(normEmail, userId, now).map(r => rowToInvite(r)!)
|
|
526
520
|
return {
|
|
527
521
|
...(totpRec ? { totp: { enabled: totpRec.enabled, createdAt: totpRec.createdAt, recoveryCodesRemaining: rcCount } } : {}),
|
|
528
522
|
passkeys,
|
|
529
523
|
organizations,
|
|
530
|
-
|
|
524
|
+
...userInvitationsExport(invites, normEmail, userId),
|
|
531
525
|
}
|
|
532
526
|
},
|
|
533
527
|
deleteUserExt(userId, email) {
|