@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/src/sqlite.ts CHANGED
@@ -205,6 +205,42 @@ function userDeletion(
205
205
  })
206
206
  }
207
207
 
208
+ /** A user's updates: a plain patch, and the sign-up rollback's conditional ones, whose compare and write run in one immediate transaction so a verification from another connection lands before or after, never between. */
209
+ function userWrites(
210
+ db: Database,
211
+ q: ReturnType<typeof prepareCoreQueries>,
212
+ delUserTx: (userId: string) => void,
213
+ ) {
214
+ function writeUserPatch(id: string, patch: Partial<AuthUser>): AuthUser | undefined {
215
+ const cur = rowToUser(q.qUserById.get(id))
216
+ if (!cur)
217
+ return undefined
218
+ const next: AuthUser = {
219
+ ...cur,
220
+ ...patch,
221
+ email: patch.email !== undefined ? normalizeEmail(patch.email) : cur.email,
222
+ updatedAt: patch.updatedAt ?? Date.now(),
223
+ }
224
+ q.qUpdateUser.run(next.email, next.name ?? null, next.avatarUrl ?? null, next.role, next.emailVerified ? 1 : 0, next.passwordHash ?? null, next.updatedAt, id)
225
+ return next
226
+ }
227
+ const isUnchangedUnverified = (id: string, updatedAt: number): boolean => {
228
+ const cur = rowToUser(q.qUserById.get(id))
229
+ return cur !== undefined && !cur.emailVerified && cur.updatedAt === updatedAt
230
+ }
231
+ return {
232
+ writeUserPatch,
233
+ updateIfUnverifiedTx: db.transaction((id: string, updatedAt: number, patch: Partial<Omit<AuthUser, 'id' | 'createdAt' | 'email'>>) =>
234
+ isUnchangedUnverified(id, updatedAt) && writeUserPatch(id, patch) !== undefined),
235
+ deleteIfUnverifiedTx: db.transaction((id: string, updatedAt: number) => {
236
+ if (!isUnchangedUnverified(id, updatedAt))
237
+ return false
238
+ delUserTx(id)
239
+ return true
240
+ }),
241
+ }
242
+ }
243
+
208
244
  function exportSqliteUser(
209
245
  q: ReturnType<typeof prepareCoreQueries>,
210
246
  ext: ReturnType<typeof createSqliteStoreExt>,
@@ -226,16 +262,44 @@ function exportSqliteUser(
226
262
 
227
263
  type SqliteAuthStore = AuthStore & { readonly db: Database }
228
264
 
265
+ function isInMemorySqlitePath(path: string): boolean {
266
+ if (path === '' || path === ':memory:')
267
+ return true
268
+ if (!path.startsWith('file:'))
269
+ return false
270
+ const rest = path.slice('file:'.length)
271
+ const qIdx = rest.indexOf('?')
272
+ const target = (qIdx === -1 ? rest : rest.slice(0, qIdx)).split('#', 1)[0]!
273
+ if (target === '' || target === ':memory:')
274
+ return true
275
+ if (qIdx === -1)
276
+ return false
277
+ const query = rest.slice(qIdx + 1).split('#', 1)[0]!
278
+ return new URLSearchParams(query).get('mode') === 'memory'
279
+ }
280
+
229
281
  export function sqliteAuthStore(dbOrPath: string | Database = ':memory:'): SqliteAuthStore {
230
- if (typeof dbOrPath !== 'string' || dbOrPath === ':memory:')
282
+ if (typeof dbOrPath !== 'string' || isInMemorySqlitePath(dbOrPath))
231
283
  return openSqliteAuthStore(dbOrPath)
232
284
  // A file opens at first use, so a build importing prunelle.config.ts creates no database.
233
285
  let opened: SqliteAuthStore | undefined
234
286
  const open = (): SqliteAuthStore => (opened ??= openSqliteAuthStore(appPath(dbOrPath)))
235
287
  const target = Object.create(null) as SqliteAuthStore
236
288
  return markSyncStore(new Proxy(target, {
237
- get: (_, key) => key === 'close' && opened === undefined ? () => {} : Reflect.get(open(), key),
238
- has: (_, key) => Reflect.has(open(), key),
289
+ get: (_, key) => {
290
+ if (opened === undefined) {
291
+ if (key === 'close')
292
+ return () => {}
293
+ if (key === 'then' || typeof key === 'symbol')
294
+ return undefined
295
+ }
296
+ return Reflect.get(open(), key)
297
+ },
298
+ has: (_, key) => {
299
+ if (opened === undefined && (key === 'then' || typeof key === 'symbol'))
300
+ return false
301
+ return Reflect.has(open(), key)
302
+ },
239
303
  }))
240
304
  }
241
305
 
@@ -260,7 +324,7 @@ function ensurePrivateDbFile(dbPath: string): void {
260
324
 
261
325
  function openSqliteAuthStore(dbOrPath: string | Database): SqliteAuthStore {
262
326
  const ownsDb = typeof dbOrPath === 'string'
263
- if (ownsDb && dbOrPath !== ':memory:' && !dbOrPath.startsWith('file:'))
327
+ if (ownsDb && !isInMemorySqlitePath(dbOrPath) && !dbOrPath.startsWith('file:'))
264
328
  ensurePrivateDbFile(dbOrPath)
265
329
  const db = ownsDb ? new Database(dbOrPath, { create: true }) : dbOrPath
266
330
  let closed = false
@@ -268,7 +332,7 @@ function openSqliteAuthStore(dbOrPath: string | Database): SqliteAuthStore {
268
332
  createSchema(db)
269
333
  const queries = prepareCoreQueries(db)
270
334
  const {
271
- qUserById, qUnverifiedUserIds, qUserByEmail, qInsertUser, qUpdateUser,
335
+ qUserById, qUnverifiedUserIds, qUserByEmail, qInsertUser,
272
336
  qGetSession, qListUserSessions, qInsertSession, qTouchSession, qDelSession, qDelUserSessions,
273
337
  qGetOAuth, qLinkOAuth, qDelUserOAuth,
274
338
  qInsertToken, qConsumeToken,
@@ -277,12 +341,13 @@ function openSqliteAuthStore(dbOrPath: string | Database): SqliteAuthStore {
277
341
  const ext = createSqliteStoreExt(db)
278
342
 
279
343
  const delUserTx = userDeletion(db, queries, ext)
344
+ const { writeUserPatch, updateIfUnverifiedTx, deleteIfUnverifiedTx } = userWrites(db, queries, delUserTx)
280
345
 
281
346
  function listActiveSessions(userId: string): AuthSession[] {
282
347
  return qListUserSessions.all(userId, Date.now()).map(row => rowToSession(row)!)
283
348
  }
284
349
 
285
- return markSyncStore(keptInMemory(db.filename === ':memory:', {
350
+ return markSyncStore(keptInMemory(isInMemorySqlitePath(db.filename), {
286
351
  ...ext.methods,
287
352
  db,
288
353
  close() {
@@ -325,30 +390,17 @@ function openSqliteAuthStore(dbOrPath: string | Database): SqliteAuthStore {
325
390
  return norm
326
391
  },
327
392
  updateUser(id, patch) {
328
- const cur = rowToUser(qUserById.get(id))
329
- if (!cur)
330
- return undefined
331
- const next: AuthUser = {
332
- ...cur,
333
- ...patch,
334
- email: patch.email !== undefined ? normalizeEmail(patch.email) : cur.email,
335
- updatedAt: patch.updatedAt ?? Date.now(),
336
- }
337
- qUpdateUser.run(
338
- next.email,
339
- next.name ?? null,
340
- next.avatarUrl ?? null,
341
- next.role,
342
- next.emailVerified ? 1 : 0,
343
- next.passwordHash ?? null,
344
- next.updatedAt,
345
- id,
346
- )
347
- return next
393
+ return writeUserPatch(id, patch)
348
394
  },
349
395
  deleteUser(userId) {
350
396
  delUserTx(userId)
351
397
  },
398
+ updateUserIfUnverified(id, updatedAt, patch) {
399
+ return updateIfUnverifiedTx.immediate(id, updatedAt, patch)
400
+ },
401
+ deleteUserIfUnverified(id, updatedAt) {
402
+ return deleteIfUnverifiedTx.immediate(id, updatedAt)
403
+ },
352
404
  exportUser(userId): UserExport | null {
353
405
  return exportSqliteUser(queries, ext, userId)
354
406
  },
package/src/store-ext.ts CHANGED
@@ -80,7 +80,19 @@ export interface UserExportExt {
80
80
  totp?: { enabled: boolean, createdAt: number, recoveryCodesRemaining: number } | undefined
81
81
  passkeys?: PasskeySummary[] | undefined
82
82
  organizations?: Array<{ orgId: string, slug: string, name: string, role: string, joinedAt: number }> | undefined
83
+ /** Pending invitations to the user's own email. */
83
84
  invitations?: Array<{ id: string, orgId: string, email: string, role: string, expiresAt: number, createdAt: number }> | undefined
85
+ /** Pending invitations the user sent, without the invitee's email: that address is the invitee's data, not the sender's. */
86
+ sentInvitations?: Array<{ id: string, orgId: string, role: string, expiresAt: number, createdAt: number }> | undefined
87
+ }
88
+
89
+ /** Splits the unexpired invitations naming a user into the ones they received and the ones they sent, oldest first. */
90
+ export function userInvitationsExport(invites: readonly OrgInvitation[], email: string, userId: string): Required<Pick<UserExportExt, 'invitations' | 'sentInvitations'>> {
91
+ const sorted = [...invites].sort((a, b) => a.createdAt - b.createdAt)
92
+ return {
93
+ invitations: sorted.filter(inv => inv.email === email).map(({ id, orgId, email, role, expiresAt, createdAt }) => ({ id, orgId, email, role, expiresAt, createdAt })),
94
+ sentInvitations: sorted.filter(inv => inv.invitedBy === userId).map(({ id, orgId, role, expiresAt, createdAt }) => ({ id, orgId, role, expiresAt, createdAt })),
95
+ }
84
96
  }
85
97
 
86
98
  export type UpdateOrgMemberRoleResult
@@ -241,6 +253,8 @@ function buildMemoryTotpPasskeyMethods(state: MemoryExtState) {
241
253
  return out
242
254
  },
243
255
  createPasskey(record: PasskeyRecord): void {
256
+ if (state.passkeys.has(record.id))
257
+ throw new Error('prunelle: Passkey is already registered')
244
258
  state.passkeys.set(record.id, clonePasskey(record))
245
259
  },
246
260
  updatePasskeyUsage(credentialId: string, signCount: number, lastUsedAt: number): void {
@@ -443,30 +457,18 @@ export function createMemoryStoreExt(): MemoryStoreExtHooks {
443
457
  role: item.role,
444
458
  joinedAt: item.joinedAt,
445
459
  }))
446
- const invitations: NonNullable<UserExportExt['invitations']> = []
447
- const normEmail = email.trim().toLowerCase()
460
+ const live: OrgInvitation[] = []
448
461
  for (const [k, inv] of state.orgInvites) {
449
- if (inv.expiresAt <= now) {
462
+ if (inv.expiresAt <= now)
450
463
  state.orgInvites.delete(k)
451
- continue
452
- }
453
- if (inv.email === normEmail || inv.invitedBy === userId) {
454
- invitations.push({
455
- id: inv.id,
456
- orgId: inv.orgId,
457
- email: inv.email,
458
- role: inv.role,
459
- expiresAt: inv.expiresAt,
460
- createdAt: inv.createdAt,
461
- })
462
- }
464
+ else
465
+ live.push(inv)
463
466
  }
464
- invitations.sort((a, b) => a.createdAt - b.createdAt)
465
467
  return {
466
468
  ...(totpRec ? { totp: { enabled: totpRec.enabled, createdAt: totpRec.createdAt, recoveryCodesRemaining: rcCount } } : {}),
467
469
  passkeys: userPasskeys,
468
470
  organizations,
469
- invitations,
471
+ ...userInvitationsExport(live, email.trim().toLowerCase(), userId),
470
472
  }
471
473
  },
472
474
  deleteUserExt(userId, email) {
package/src/store.ts CHANGED
@@ -48,8 +48,8 @@ export interface OAuthAccount {
48
48
  createdAt: number
49
49
  }
50
50
 
51
- /** Verification token purposes. `'reset-password'` is reserved for app-defined password-reset flows via `store.createToken`/`store.consumeToken`. */
52
- export type TokenKind = 'magic-link' | 'verify-email' | 'reset-password'
51
+ /** Verification token purposes. `'reset-password'` is reserved for app-defined password-reset flows via `store.createToken`/`store.consumeToken`; `'passkey-challenge'` holds a WebAuthn challenge, with no user and an empty email, for 5 minutes. */
52
+ export type TokenKind = 'magic-link' | 'verify-email' | 'reset-password' | 'passkey-challenge'
53
53
 
54
54
  export interface VerificationToken {
55
55
  tokenHash: string
@@ -76,6 +76,10 @@ export interface AuthStore<TUser extends AuthUser = AuthUser> extends AuthStoreE
76
76
  createUser(user: TUser): TUser | Promise<TUser>
77
77
  updateUser(id: string, patch: Partial<Omit<TUser, 'id' | 'createdAt'>>): TUser | undefined | Promise<TUser | undefined>
78
78
  deleteUser(userId: string): void | Promise<void>
79
+ /** Applies `patch` only while the user is unverified and was last updated at `updatedAt`, in one step, so a verification landing first wins; `true` when it wrote. Optional: without it the sign-up rollback reads then writes, and can overwrite a verification landing in between. */
80
+ updateUserIfUnverified?(id: string, updatedAt: number, patch: Partial<Omit<TUser, 'id' | 'createdAt' | 'email'>>): boolean | Promise<boolean>
81
+ /** Deletes the user only while unverified and last updated at `updatedAt`, in one step; `true` when it deleted. Optional, like `updateUserIfUnverified`. */
82
+ deleteUserIfUnverified?(id: string, updatedAt: number): boolean | Promise<boolean>
79
83
  exportUser(userId: string): UserExport<TUser> | null | Promise<UserExport<TUser> | null>
80
84
 
81
85
  getSession(tokenHash: string): AuthSession | undefined | Promise<AuthSession | undefined>
@@ -228,6 +232,10 @@ export function memoryAuthStore<TUser extends AuthUser = AuthUser>(): AuthStore<
228
232
  },
229
233
  createUser(user) {
230
234
  const norm: TUser = { ...user, email: normalizeEmail(user.email) }
235
+ if (state.users.has(norm.id))
236
+ throw new Error(`prunelle: user id "${norm.id}" already exists`)
237
+ if (state.usersByEmail.has(norm.email))
238
+ throw new Error('prunelle: Email is already registered')
231
239
  state.users.set(norm.id, norm)
232
240
  state.usersByEmail.set(norm.email, norm.id)
233
241
  return norm
@@ -238,6 +246,9 @@ export function memoryAuthStore<TUser extends AuthUser = AuthUser>(): AuthStore<
238
246
  return undefined
239
247
  const nextEmail = patch.email !== undefined ? normalizeEmail(patch.email) : cur.email
240
248
  if (nextEmail !== cur.email) {
249
+ const owner = state.usersByEmail.get(nextEmail)
250
+ if (owner !== undefined && owner !== userId)
251
+ throw new Error('prunelle: Email is already registered')
241
252
  state.usersByEmail.delete(cur.email)
242
253
  state.usersByEmail.set(nextEmail, userId)
243
254
  }
@@ -248,6 +259,20 @@ export function memoryAuthStore<TUser extends AuthUser = AuthUser>(): AuthStore<
248
259
  deleteUser(userId) {
249
260
  deleteMemoryUser(state, ext, userId)
250
261
  },
262
+ updateUserIfUnverified(userId, updatedAt, patch) {
263
+ const cur = state.users.get(userId)
264
+ if (!cur || cur.emailVerified || cur.updatedAt !== updatedAt)
265
+ return false
266
+ state.users.set(userId, { ...cur, ...patch, email: cur.email, updatedAt: Date.now() })
267
+ return true
268
+ },
269
+ deleteUserIfUnverified(userId, updatedAt) {
270
+ const cur = state.users.get(userId)
271
+ if (!cur || cur.emailVerified || cur.updatedAt !== updatedAt)
272
+ return false
273
+ deleteMemoryUser(state, ext, userId)
274
+ return true
275
+ },
251
276
  exportUser(userId) {
252
277
  return exportMemoryUser(state, ext, userId)
253
278
  },
@@ -3,17 +3,19 @@
3
3
 
4
4
  import type { RequestContext } from 'prunelle/server'
5
5
  import type { AuthFormMessages } from './form-messages'
6
- import type { AuthRouteRegistrar } from './http'
6
+ import type { AuthLimits, AuthRouteRegistrar } from './http'
7
7
  import type { SessionManager } from './session'
8
8
  import type { AuthStore, AuthUser } from './store'
9
9
  import type { TotpManager } from './totp'
10
10
  import { safeRedirect, wantsJson } from 'prunelle/server'
11
+ import { freshSignin, keepOnlyThisSession } from './account'
11
12
  import { readFormMessage } from './form-messages'
12
13
  import { escapeHtml, fail, respondAuthError } from './http'
13
14
  import { toPublicUser } from './store'
14
15
 
15
16
  export interface TotpRoutesDeps<TUser extends AuthUser = AuthUser> {
16
17
  authRoute: AuthRouteRegistrar
18
+ limits: AuthLimits
17
19
  store: AuthStore<TUser>
18
20
  sessions: SessionManager<TUser>
19
21
  totp: TotpManager
@@ -28,12 +30,12 @@ function renderHtmlPage(title: string, bodyHtml: string): Response {
28
30
  }
29
31
 
30
32
  export function registerTotpRoutes<TUser extends AuthUser = AuthUser>(deps: TotpRoutesDeps<TUser>): void {
31
- const { authRoute, store, sessions, totp, basePath, defaultRedirect, messages } = deps
33
+ const { authRoute, limits, store, sessions, totp, basePath, defaultRedirect, messages } = deps
32
34
 
33
35
  authRoute('POST', '/totp/setup', { limit: 'totp-setup', readBody: true }, async (ctx, body) => {
34
- const resolved = await sessions.resolve(ctx)
35
- if (!resolved)
36
- return fail(ctx, 401, 'Authentication required')
36
+ const resolved = await freshSignin(ctx, sessions)
37
+ if (resolved instanceof Response)
38
+ return resolved
37
39
 
38
40
  try {
39
41
  const setup = await totp.setupTotp(resolved.user.id, body.issuer ? { issuer: body.issuer } : undefined)
@@ -54,9 +56,9 @@ export function registerTotpRoutes<TUser extends AuthUser = AuthUser>(deps: Totp
54
56
  })
55
57
 
56
58
  authRoute('POST', '/totp/confirm', { limit: 'totp-confirm', readBody: true }, async (ctx, body) => {
57
- const resolved = await sessions.resolve(ctx)
58
- if (!resolved)
59
- return fail(ctx, 401, 'Authentication required')
59
+ const resolved = await freshSignin(ctx, sessions)
60
+ if (resolved instanceof Response)
61
+ return resolved
60
62
 
61
63
  const code = (body.code ?? '').trim()
62
64
  if (!code)
@@ -64,6 +66,7 @@ export function registerTotpRoutes<TUser extends AuthUser = AuthUser>(deps: Totp
64
66
 
65
67
  try {
66
68
  const result = await totp.confirmTotp(resolved.user.id, code)
69
+ await keepOnlyThisSession(ctx, sessions, store, resolved.user.id)
67
70
  if (wantsJson(ctx.request))
68
71
  return ctx.json({ ok: true, enabled: true, recoveryCodes: result.recoveryCodes }, { status: 200 })
69
72
  if (body.redirect || body.next)
@@ -99,14 +102,23 @@ export function registerTotpRoutes<TUser extends AuthUser = AuthUser>(deps: Totp
99
102
  const pending = totp.readPendingCookie(ctx)
100
103
  if (!pending)
101
104
  return fail(ctx, 401, 'Two-factor session expired or invalid')
105
+ const locked = limits.refuseLockedSecondFactor(ctx, pending.userId)
106
+ if (locked) {
107
+ totp.clearPendingCookie(ctx)
108
+ return locked
109
+ }
102
110
 
103
111
  const code = (body.code ?? '').trim()
104
112
  if (!code)
105
113
  return respondAuthError(ctx, 400, messages['totp.code-required'])
106
114
 
107
115
  const check = await totp.verifyTotp(pending.userId, code)
108
- if (!check.valid)
109
- return respondAuthError(ctx, 401, messages['totp.invalid-code'])
116
+ if (!check.valid) {
117
+ const refused = limits.countFailedSecondFactor(ctx, pending.userId)
118
+ if (refused)
119
+ totp.clearPendingCookie(ctx)
120
+ return refused ?? respondAuthError(ctx, 401, messages['totp.invalid-code'])
121
+ }
110
122
 
111
123
  const userRecord = await sessions.observeAsync(store.getUserById(pending.userId))
112
124
  if (!userRecord) {
@@ -125,9 +137,9 @@ export function registerTotpRoutes<TUser extends AuthUser = AuthUser>(deps: Totp
125
137
  })
126
138
 
127
139
  authRoute('POST', '/totp/disable', { limit: 'totp-disable', readBody: true }, async (ctx, body) => {
128
- const resolved = await sessions.resolve(ctx)
129
- if (!resolved)
130
- return fail(ctx, 401, 'Authentication required')
140
+ const resolved = await freshSignin(ctx, sessions)
141
+ if (resolved instanceof Response)
142
+ return resolved
131
143
 
132
144
  const code = (body.code ?? '').trim()
133
145
  if (!code)
@@ -136,9 +148,27 @@ export function registerTotpRoutes<TUser extends AuthUser = AuthUser>(deps: Totp
136
148
  const disabled = await totp.disableTotp(resolved.user.id, code)
137
149
  if (!disabled)
138
150
  return fail(ctx, 401, 'Invalid verification code')
151
+ await keepOnlyThisSession(ctx, sessions, store, resolved.user.id)
139
152
 
140
153
  if (wantsJson(ctx.request))
141
154
  return ctx.json({ ok: true, enabled: false }, { status: 200 })
142
155
  return ctx.redirect(safeRedirect(body.redirect ?? body.next, defaultRedirect), 303)
143
156
  })
157
+
158
+ authRoute('POST', '/totp/recovery-codes', { limit: 'totp-recovery-codes', readBody: true }, async (ctx) => {
159
+ const resolved = await freshSignin(ctx, sessions)
160
+ if (resolved instanceof Response)
161
+ return resolved
162
+ if (!(await totp.getTwoFactorMethods(resolved.user.id)).includes('totp'))
163
+ return fail(ctx, 400, 'Two-factor authentication is not enabled')
164
+
165
+ const recoveryCodes = await totp.regenerateRecoveryCodes(resolved.user.id)
166
+ if (wantsJson(ctx.request))
167
+ return ctx.json({ ok: true, recoveryCodes }, { status: 200 })
168
+ const list = recoveryCodes.map(c => `<li><code>${escapeHtml(c)}</code></li>`).join('')
169
+ return renderHtmlPage(
170
+ 'New recovery codes',
171
+ `<h1>New recovery codes</h1><p>Your earlier recovery codes no longer work. Save these single-use codes in a safe place:</p><ul>${list}</ul>`,
172
+ )
173
+ })
144
174
  }
package/src/totp.ts CHANGED
@@ -5,7 +5,7 @@ import type { RequestContext } from 'prunelle/server'
5
5
  import type { SessionManager } from './session'
6
6
  import type { AuthStore, AuthUser, RecoveryCodeRecord } from './store'
7
7
  import { safeEqual, wantsJson } from 'prunelle/server'
8
- import { decryptSecret, encryptSecret, randomToken, sha256Hex, signPayload, verifyPayload } from './crypto'
8
+ import { decryptSecret, encryptSecret, randomToken, sha256Hex, signJson, verifyJson } from './crypto'
9
9
  import { authCookie } from './http'
10
10
  import { createKeyedLock } from './store-ext'
11
11
 
@@ -117,7 +117,16 @@ function normalizeRecoveryCode(code: string): string {
117
117
  return code.replace(/[\s-]+/g, '').toUpperCase()
118
118
  }
119
119
 
120
- function generateRecoveryCodeBatch(userId: string): { plain: string[], records: RecoveryCodeRecord[] } {
120
+ // A code has 40 bits, which a leaked salted SHA-256 gives up in hours: the hash is keyed with the app secret, so the database alone checks nothing. A salt without the prefix is a code stored before, hashed unkeyed.
121
+ const KEYED_SALT_PREFIX = 'k1.'
122
+
123
+ function recoveryCodeHash(secret: string, salt: string, normalized: string): string {
124
+ if (!salt.startsWith(KEYED_SALT_PREFIX))
125
+ return sha256Hex(`${salt}:${normalized}`)
126
+ return new Bun.CryptoHasher('sha256', `prunelle-auth-recovery:${secret}`).update(`${salt}:${normalized}`).digest('hex')
127
+ }
128
+
129
+ function generateRecoveryCodeBatch(userId: string, secret: string): { plain: string[], records: RecoveryCodeRecord[] } {
121
130
  const now = Date.now()
122
131
  const plain: string[] = []
123
132
  const records: RecoveryCodeRecord[] = []
@@ -128,12 +137,12 @@ function generateRecoveryCodeBatch(userId: string): { plain: string[], records:
128
137
  for (let j = 0; j < 8; j++)
129
138
  raw += RECOVERY_ALPHABET[bytes[j]! & 31]!
130
139
  const formatted = `${raw.slice(0, 4)}-${raw.slice(4)}`
131
- const salt = randomToken(16)
140
+ const salt = `${KEYED_SALT_PREFIX}${randomToken(16)}`
132
141
  plain.push(formatted)
133
142
  records.push({
134
143
  id: crypto.randomUUID(),
135
144
  userId,
136
- codeHash: sha256Hex(`${salt}:${raw}`),
145
+ codeHash: recoveryCodeHash(secret, salt, raw),
137
146
  salt,
138
147
  createdAt: now,
139
148
  })
@@ -206,14 +215,14 @@ function createPendingCookieHelpers(
206
215
  methods,
207
216
  exp: Date.now() + PENDING_2FA_TTL_MS,
208
217
  }
209
- ctx.cookies.set(twoFactorCookieName, signPayload(secret(), payload), authCookie(isSecureCookie(ctx), Math.floor(PENDING_2FA_TTL_MS / 1000)))
218
+ ctx.cookies.set(twoFactorCookieName, signJson(secret(), '2fa', payload), authCookie(isSecureCookie(ctx), Math.floor(PENDING_2FA_TTL_MS / 1000)))
210
219
  },
211
220
 
212
221
  readPendingCookie(ctx) {
213
222
  const raw = ctx.cookies.get(twoFactorCookieName)
214
223
  if (!raw)
215
224
  return undefined
216
- const parsed = verifyPayload<PendingTwoFactor>(secret(), raw)
225
+ const parsed = verifyJson<PendingTwoFactor>(secret(), '2fa', raw)
217
226
  if (!parsed || parsed.exp <= Date.now() || !parsed.userId)
218
227
  return undefined
219
228
  return parsed
@@ -236,7 +245,7 @@ export function createTotpManager<TUser extends AuthUser = AuthUser>(deps: TotpM
236
245
  return false
237
246
  const records = await sessions.observeAsync(ts.listRecoveryCodes(userId))
238
247
  for (const rec of records) {
239
- const candidate = sha256Hex(`${rec.salt}:${normalized}`)
248
+ const candidate = recoveryCodeHash(secret(), rec.salt, normalized)
240
249
  if (safeEqual(candidate, rec.codeHash)) {
241
250
  const consumed = await sessions.observeAsync(ts.consumeRecoveryCode(rec.id))
242
251
  if (consumed)
@@ -321,7 +330,7 @@ export function createTotpManager<TUser extends AuthUser = AuthUser>(deps: TotpM
321
330
  if (matchedStep === undefined)
322
331
  throw new Error('prunelle: invalid TOTP verification code')
323
332
 
324
- const { plain, records } = generateRecoveryCodeBatch(userId)
333
+ const { plain, records } = generateRecoveryCodeBatch(userId, secret())
325
334
  await sessions.observeAsync(ts.setTotp({
326
335
  ...record,
327
336
  enabled: true,
@@ -351,7 +360,7 @@ export function createTotpManager<TUser extends AuthUser = AuthUser>(deps: TotpM
351
360
  const record = await sessions.observeAsync(ts.getTotp(userId))
352
361
  if (!record || !record.enabled)
353
362
  throw new Error('prunelle: TOTP is not enabled for this account')
354
- const { plain, records } = generateRecoveryCodeBatch(userId)
363
+ const { plain, records } = generateRecoveryCodeBatch(userId, secret())
355
364
  await sessions.observeAsync(ts.setRecoveryCodes(userId, records))
356
365
  return plain
357
366
  },
@@ -4,6 +4,9 @@
4
4
  import { sha256Bytes, toBase64Url } from './crypto'
5
5
 
6
6
  const MAX_CBOR_DEPTH = 16
7
+ // WebAuthn L2 caps a credential ID at 1023 bytes; a 2048-bit RSA modulus is 256.
8
+ const MAX_CREDENTIAL_ID_BYTES = 1023
9
+ const MIN_RSA_MODULUS_BYTES = 256
7
10
 
8
11
  export const COSE_ALG_ES256 = -7
9
12
  export const COSE_ALG_RS256 = -257
@@ -110,6 +113,8 @@ export function decodeCbor(bytes: Uint8Array, offset = 0, depth = 0): CborDecode
110
113
  const map = new Map<unknown, unknown>()
111
114
  for (let i = 0; i < arg.value; i++) {
112
115
  const k = decodeCbor(bytes, pos, depth + 1)
116
+ if (map.has(k.value))
117
+ throw new Error('prunelle: duplicate CBOR map key')
113
118
  const v = decodeCbor(bytes, k.nextOffset, depth + 1)
114
119
  map.set(k.value, v.value)
115
120
  pos = v.nextOffset
@@ -121,6 +126,14 @@ export function decodeCbor(bytes: Uint8Array, offset = 0, depth = 0): CborDecode
121
126
  throw new Error(`prunelle: unsupported CBOR major type ${major}`)
122
127
  }
123
128
 
129
+ /** Decodes one CBOR item that must span all of `bytes`, so nothing can ride after it unsigned or unparsed. */
130
+ export function decodeCborExact(bytes: Uint8Array): unknown {
131
+ const decoded = decodeCbor(bytes)
132
+ if (decoded.nextOffset !== bytes.length)
133
+ throw new Error('prunelle: trailing bytes after CBOR data')
134
+ return decoded.value
135
+ }
136
+
124
137
  export interface ParsedAuthData {
125
138
  rpIdHash: Uint8Array
126
139
  flags: number
@@ -149,23 +162,39 @@ export function parseAuthenticatorData(authData: Uint8Array): ParsedAuthData {
149
162
  const at = (flags & 0x40) !== 0
150
163
  const signCount = view.getUint32(33, false)
151
164
 
152
- if (!at)
165
+ if (!at) {
166
+ expectAuthDataEnd(authData, flags, 37)
153
167
  return { rpIdHash, flags, up, uv, at, signCount }
168
+ }
154
169
 
155
170
  if (authData.length < 55)
156
171
  throw new Error('prunelle: attested credential data truncated')
157
172
  const aaguid = formatAaguid(authData.subarray(37, 53))
158
173
  const credIdLen = view.getUint16(53, false)
159
- if (credIdLen === 0 || 55 + credIdLen >= authData.length)
174
+ if (credIdLen === 0 || credIdLen > MAX_CREDENTIAL_ID_BYTES || 55 + credIdLen >= authData.length)
160
175
  throw new Error('prunelle: invalid credential ID length')
161
176
  const credentialId = authData.slice(55, 55 + credIdLen)
162
177
  const decoded = decodeCbor(authData, 55 + credIdLen)
163
178
  if (!(decoded.value instanceof Map))
164
179
  throw new Error('prunelle: COSE public key must be a CBOR map')
180
+ expectAuthDataEnd(authData, flags, decoded.nextOffset)
165
181
 
166
182
  return { rpIdHash, flags, up, uv, at, signCount, aaguid, credentialId, cosePublicKey: decoded.value }
167
183
  }
168
184
 
185
+ // Only an extensions map, announced by the ED flag, may follow the fixed part and the credential.
186
+ function expectAuthDataEnd(authData: Uint8Array, flags: number, offset: number): void {
187
+ let end = offset
188
+ if ((flags & 0x80) !== 0) {
189
+ const extensions = decodeCbor(authData, offset)
190
+ if (!(extensions.value instanceof Map))
191
+ throw new Error('prunelle: authenticatorData extensions must be a CBOR map')
192
+ end = extensions.nextOffset
193
+ }
194
+ if (end !== authData.length)
195
+ throw new Error('prunelle: trailing bytes after authenticatorData')
196
+ }
197
+
169
198
  export function coseKeyToJwk(cose: Map<unknown, unknown>): { algorithm: number, jwk: JsonWebKey } {
170
199
  const kty = cose.get(1)
171
200
  const alg = cose.get(3)
@@ -187,6 +216,9 @@ export function coseKeyToJwk(cose: Map<unknown, unknown>): { algorithm: number,
187
216
  const e = cose.get(-2)
188
217
  if (!(n instanceof Uint8Array) || !(e instanceof Uint8Array) || n.length === 0 || e.length === 0)
189
218
  throw new Error('prunelle: invalid RS256 COSE public key')
219
+ const firstSignificant = n.findIndex(byte => byte !== 0)
220
+ if (firstSignificant === -1 || n.length - firstSignificant < MIN_RSA_MODULUS_BYTES)
221
+ throw new Error('prunelle: RS256 passkey key is shorter than 2048 bits')
190
222
  return {
191
223
  algorithm: COSE_ALG_RS256,
192
224
  jwk: { kty: 'RSA', n: toBase64Url(n), e: toBase64Url(e), ext: true },
@@ -216,9 +248,13 @@ function readDerLength(der: Uint8Array, offset: number): { length: number, nextO
216
248
  const count = first & 0x7F
217
249
  if (count === 0 || count > 2 || offset + 1 + count > der.length)
218
250
  throw new Error('prunelle: unsupported DER length')
251
+ if (der[offset + 1] === 0x00)
252
+ throw new Error('prunelle: non-minimal DER length')
219
253
  let length = 0
220
254
  for (let i = 0; i < count; i++)
221
255
  length = (length << 8) | der[offset + 1 + i]!
256
+ if (length < 0x80)
257
+ throw new Error('prunelle: non-minimal DER length')
222
258
  return { length, nextOffset: offset + 1 + count }
223
259
  }
224
260
 
@@ -229,8 +265,15 @@ function readDerInteger(der: Uint8Array, offset: number, coordSize: number): { v
229
265
  if (length === 0 || nextOffset + length > der.length)
230
266
  throw new Error('prunelle: truncated DER integer')
231
267
  let slice = der.subarray(nextOffset, nextOffset + length)
232
- if (slice[0] === 0x00 && slice.length > 1)
268
+ if ((slice[0]! & 0x80) !== 0)
269
+ throw new Error('prunelle: DER integer must not be negative')
270
+ if (slice[0] === 0x00) {
271
+ if (slice.length === 1)
272
+ throw new Error('prunelle: DER integer must be positive')
273
+ if ((slice[1]! & 0x80) === 0)
274
+ throw new Error('prunelle: non-minimal DER integer')
233
275
  slice = slice.subarray(1)
276
+ }
234
277
  if (slice.length > coordSize)
235
278
  throw new Error('prunelle: DER integer exceeds coordinate size')
236
279
  const out = new Uint8Array(coordSize)
@@ -261,24 +304,26 @@ export async function verifyWebAuthnSignature(
261
304
  authenticatorData: Uint8Array,
262
305
  clientDataJsonBytes: Uint8Array,
263
306
  ): Promise<boolean> {
264
- const jwk = JSON.parse(publicKeyJwkJson) as JsonWebKey
307
+ const key = await importPasskeyKey(JSON.parse(publicKeyJwkJson) as JsonWebKey, algorithm)
265
308
  const clientHash = sha256Bytes(clientDataJsonBytes)
266
309
  const signedData = new Uint8Array(authenticatorData.length + clientHash.length)
267
310
  signedData.set(authenticatorData, 0)
268
311
  signedData.set(clientHash, authenticatorData.length)
269
312
 
270
- if (algorithm === COSE_ALG_ES256) {
271
- const key = await crypto.subtle.importKey('jwk', jwk, { name: 'ECDSA', namedCurve: 'P-256' }, false, ['verify'])
272
- const rawSig = derToRawEcdsa(signature, 32)
273
- return crypto.subtle.verify({ name: 'ECDSA', hash: 'SHA-256' }, key, new Uint8Array(rawSig), new Uint8Array(signedData))
274
- }
275
- if (algorithm === COSE_ALG_RS256) {
276
- const key = await crypto.subtle.importKey('jwk', jwk, { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }, false, ['verify'])
313
+ if (algorithm === COSE_ALG_ES256)
314
+ return crypto.subtle.verify({ name: 'ECDSA', hash: 'SHA-256' }, key, new Uint8Array(derToRawEcdsa(signature, 32)), new Uint8Array(signedData))
315
+ if (algorithm === COSE_ALG_RS256)
277
316
  return crypto.subtle.verify({ name: 'RSASSA-PKCS1-v1_5' }, key, new Uint8Array(signature), new Uint8Array(signedData))
278
- }
279
- if (algorithm === COSE_ALG_EDDSA) {
280
- const key = await crypto.subtle.importKey('jwk', jwk, { name: 'Ed25519' }, false, ['verify'])
281
- return crypto.subtle.verify({ name: 'Ed25519' }, key, new Uint8Array(signature), new Uint8Array(signedData))
282
- }
317
+ return crypto.subtle.verify({ name: 'Ed25519' }, key, new Uint8Array(signature), new Uint8Array(signedData))
318
+ }
319
+
320
+ /** Imports a passkey's public key for verifying, which throws on an EC point off the curve, so registration can refuse it up front. */
321
+ export function importPasskeyKey(jwk: JsonWebKey, algorithm: number): Promise<CryptoKey> {
322
+ if (algorithm === COSE_ALG_ES256)
323
+ return crypto.subtle.importKey('jwk', jwk, { name: 'ECDSA', namedCurve: 'P-256' }, false, ['verify'])
324
+ if (algorithm === COSE_ALG_RS256)
325
+ return crypto.subtle.importKey('jwk', jwk, { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }, false, ['verify'])
326
+ if (algorithm === COSE_ALG_EDDSA)
327
+ return crypto.subtle.importKey('jwk', jwk, { name: 'Ed25519' }, false, ['verify'])
283
328
  throw new Error(`prunelle: unsupported passkey algorithm ${algorithm}`)
284
329
  }