@prunellejs/auth 0.7.4 → 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.
@@ -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 },
@@ -272,24 +304,26 @@ export async function verifyWebAuthnSignature(
272
304
  authenticatorData: Uint8Array,
273
305
  clientDataJsonBytes: Uint8Array,
274
306
  ): Promise<boolean> {
275
- const jwk = JSON.parse(publicKeyJwkJson) as JsonWebKey
307
+ const key = await importPasskeyKey(JSON.parse(publicKeyJwkJson) as JsonWebKey, algorithm)
276
308
  const clientHash = sha256Bytes(clientDataJsonBytes)
277
309
  const signedData = new Uint8Array(authenticatorData.length + clientHash.length)
278
310
  signedData.set(authenticatorData, 0)
279
311
  signedData.set(clientHash, authenticatorData.length)
280
312
 
281
- if (algorithm === COSE_ALG_ES256) {
282
- const key = await crypto.subtle.importKey('jwk', jwk, { name: 'ECDSA', namedCurve: 'P-256' }, false, ['verify'])
283
- const rawSig = derToRawEcdsa(signature, 32)
284
- return crypto.subtle.verify({ name: 'ECDSA', hash: 'SHA-256' }, key, new Uint8Array(rawSig), new Uint8Array(signedData))
285
- }
286
- if (algorithm === COSE_ALG_RS256) {
287
- 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)
288
316
  return crypto.subtle.verify({ name: 'RSASSA-PKCS1-v1_5' }, key, new Uint8Array(signature), new Uint8Array(signedData))
289
- }
290
- if (algorithm === COSE_ALG_EDDSA) {
291
- const key = await crypto.subtle.importKey('jwk', jwk, { name: 'Ed25519' }, false, ['verify'])
292
- return crypto.subtle.verify({ name: 'Ed25519' }, key, new Uint8Array(signature), new Uint8Array(signedData))
293
- }
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'])
294
328
  throw new Error(`prunelle: unsupported passkey algorithm ${algorithm}`)
295
329
  }