@prunellejs/auth 0.1.1 → 0.7.2

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.
@@ -0,0 +1,144 @@
1
+ // HTTP routes for TOTP second factor setup, confirmation, verification (2FA), and disabling.
2
+ // Works both with JSON clients and with zero-JS HTML forms.
3
+
4
+ import type { RequestContext } from 'prunelle/server'
5
+ import type { AuthFormMessages } from './form-messages'
6
+ import type { AuthRouteRegistrar } from './http'
7
+ import type { SessionManager } from './session'
8
+ import type { AuthStore, AuthUser } from './store'
9
+ import type { TotpManager } from './totp'
10
+ import { safeRedirect, wantsJson } from 'prunelle/server'
11
+ import { readFormMessage } from './form-messages'
12
+ import { escapeHtml, fail, respondAuthError } from './http'
13
+ import { toPublicUser } from './store'
14
+
15
+ export interface TotpRoutesDeps<TUser extends AuthUser = AuthUser> {
16
+ authRoute: AuthRouteRegistrar
17
+ store: AuthStore<TUser>
18
+ sessions: SessionManager<TUser>
19
+ totp: TotpManager
20
+ basePath: string
21
+ defaultRedirect: string
22
+ messages: AuthFormMessages
23
+ }
24
+
25
+ function renderHtmlPage(title: string, bodyHtml: string): Response {
26
+ const html = `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="robots" content="noindex"><meta name="referrer" content="same-origin"><title>${escapeHtml(title)}</title></head><body><main>${bodyHtml}</main></body></html>`
27
+ return new Response(html, { headers: { 'content-type': 'text/html; charset=utf-8' } })
28
+ }
29
+
30
+ export function registerTotpRoutes<TUser extends AuthUser = AuthUser>(deps: TotpRoutesDeps<TUser>): void {
31
+ const { authRoute, store, sessions, totp, basePath, defaultRedirect, messages } = deps
32
+
33
+ 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')
37
+
38
+ try {
39
+ const setup = await totp.setupTotp(resolved.user.id, body.issuer ? { issuer: body.issuer } : undefined)
40
+ if (wantsJson(ctx.request))
41
+ return ctx.json({ ok: true, secret: setup.secret, otpauthUrl: setup.otpauthUrl }, { status: 200 })
42
+ const redirect = safeRedirect(body.redirect ?? body.next, '')
43
+ const redirectInput = redirect ? `<input type="hidden" name="redirect" value="${escapeHtml(redirect)}">` : ''
44
+ return renderHtmlPage(
45
+ 'Set up two-factor authentication',
46
+ `<h1>Set up two-factor authentication</h1><p>Secret: <code>${escapeHtml(setup.secret)}</code></p><p>URI: <code>${escapeHtml(setup.otpauthUrl)}</code></p><form method="post" action="${escapeHtml(`${basePath}/totp/confirm`)}">${redirectInput}<label>Verification code <input type="text" name="code" inputmode="numeric" autocomplete="one-time-code" required></label><button type="submit">Enable 2FA</button></form>`,
47
+ )
48
+ }
49
+ catch (err) {
50
+ const msg = err instanceof Error ? err.message : 'Unable to start TOTP setup'
51
+ const status = msg.includes('already enabled') ? 409 : 400
52
+ return fail(ctx, status, msg)
53
+ }
54
+ })
55
+
56
+ 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')
60
+
61
+ const code = (body.code ?? '').trim()
62
+ if (!code)
63
+ return fail(ctx, 400, 'Verification code is required')
64
+
65
+ try {
66
+ const result = await totp.confirmTotp(resolved.user.id, code)
67
+ if (wantsJson(ctx.request))
68
+ return ctx.json({ ok: true, enabled: true, recoveryCodes: result.recoveryCodes }, { status: 200 })
69
+ if (body.redirect || body.next)
70
+ return ctx.redirect(safeRedirect(body.redirect ?? body.next, defaultRedirect), 303)
71
+ const list = result.recoveryCodes.map(c => `<li><code>${escapeHtml(c)}</code></li>`).join('')
72
+ return renderHtmlPage(
73
+ 'Two-factor authentication enabled',
74
+ `<h1>Two-factor authentication enabled</h1><p>Save these single-use recovery codes in a safe place:</p><ul>${list}</ul>`,
75
+ )
76
+ }
77
+ catch (err) {
78
+ const msg = err instanceof Error ? err.message : 'Invalid verification code'
79
+ const status = msg.includes('already enabled') ? 409 : 400
80
+ return fail(ctx, status, msg)
81
+ }
82
+ })
83
+
84
+ authRoute('GET', '/totp/verify', { limit: 'totp-verify' }, (ctx: RequestContext) => {
85
+ const pending = totp.readPendingCookie(ctx)
86
+ if (!pending)
87
+ return fail(ctx, 401, 'Two-factor session expired or invalid')
88
+ const redirect = safeRedirect(ctx.url.searchParams.get('next') ?? ctx.url.searchParams.get('redirect') ?? pending.redirect, defaultRedirect)
89
+ const message = readFormMessage(messages, ctx.url)
90
+ const error = message?.form === 'totp' ? message.text : undefined
91
+ const described = error !== undefined ? ' aria-invalid="true" aria-describedby="code-error"' : ''
92
+ return renderHtmlPage(
93
+ 'Two-factor verification',
94
+ `<h1>Two-factor verification</h1><form method="post" action="${escapeHtml(`${basePath}/totp/verify`)}"><input type="hidden" name="redirect" value="${escapeHtml(redirect)}"><label>Authentication or recovery code <input type="text" name="code" autocomplete="one-time-code" required${described}></label>${error !== undefined ? `<p id="code-error" role="alert">${escapeHtml(error)}</p>` : ''}<button type="submit">Verify</button></form>`,
95
+ )
96
+ })
97
+
98
+ authRoute('POST', '/totp/verify', { limit: 'totp-verify', readBody: true }, async (ctx, body) => {
99
+ const pending = totp.readPendingCookie(ctx)
100
+ if (!pending)
101
+ return fail(ctx, 401, 'Two-factor session expired or invalid')
102
+
103
+ const code = (body.code ?? '').trim()
104
+ if (!code)
105
+ return respondAuthError(ctx, 400, messages['totp.code-required'])
106
+
107
+ const check = await totp.verifyTotp(pending.userId, code)
108
+ if (!check.valid)
109
+ return respondAuthError(ctx, 401, messages['totp.invalid-code'])
110
+
111
+ const userRecord = await sessions.observeAsync(store.getUserById(pending.userId))
112
+ if (!userRecord) {
113
+ totp.clearPendingCookie(ctx)
114
+ return fail(ctx, 401, 'Unable to resolve user account')
115
+ }
116
+
117
+ totp.clearPendingCookie(ctx)
118
+ const pub = toPublicUser(userRecord)
119
+ await sessions.createSessionForUser(userRecord.id, ctx, pub)
120
+ const redirectTarget = safeRedirect(body.redirect ?? body.next ?? pending.redirect, defaultRedirect)
121
+
122
+ if (wantsJson(ctx.request))
123
+ return ctx.json({ ok: true, user: pub, usedRecoveryCode: check.method === 'recovery' }, { status: 200 })
124
+ return ctx.redirect(redirectTarget, 303)
125
+ })
126
+
127
+ 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')
131
+
132
+ const code = (body.code ?? '').trim()
133
+ if (!code)
134
+ return fail(ctx, 400, 'Verification code is required')
135
+
136
+ const disabled = await totp.disableTotp(resolved.user.id, code)
137
+ if (!disabled)
138
+ return fail(ctx, 401, 'Invalid verification code')
139
+
140
+ if (wantsJson(ctx.request))
141
+ return ctx.json({ ok: true, enabled: false }, { status: 200 })
142
+ return ctx.redirect(safeRedirect(body.redirect ?? body.next, defaultRedirect), 303)
143
+ })
144
+ }
package/src/totp.ts ADDED
@@ -0,0 +1,395 @@
1
+ // Pure RFC 6238 TOTP (HMAC-SHA1, 6 digits, 30s period, ±1 step window), AES-256-GCM secret encryption,
2
+ // single-use recovery codes, and signed pending-2FA cookie helpers.
3
+
4
+ import type { RequestContext } from 'prunelle/server'
5
+ import type { SessionManager } from './session'
6
+ import type { AuthStore, AuthUser, RecoveryCodeRecord } from './store'
7
+ import { safeEqual, wantsJson } from 'prunelle/server'
8
+ import { decryptSecret, encryptSecret, randomToken, sha256Hex, signPayload, verifyPayload } from './crypto'
9
+ import { authCookie } from './http'
10
+
11
+ const BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
12
+ const RECOVERY_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'
13
+ const TOTP_PERIOD_SECONDS = 30
14
+ const TOTP_DIGITS = 6
15
+ const RECOVERY_CODE_COUNT = 10
16
+ const PENDING_2FA_TTL_MS = 5 * 60 * 1000
17
+
18
+ export type TwoFactorMethod = 'totp' | 'passkey'
19
+
20
+ export interface TotpOptions {
21
+ /** Issuer label displayed in authenticator apps (defaults to `site` hostname or `'Prunelle'`). */
22
+ issuer?: string | undefined
23
+ /** Path HTML form sign-ins redirect to when 2FA is required (default: `${basePath}/totp/verify`). */
24
+ verifyPath?: string | undefined
25
+ }
26
+
27
+ export interface PendingTwoFactor {
28
+ userId: string
29
+ redirect: string
30
+ methods: TwoFactorMethod[]
31
+ exp: number
32
+ }
33
+
34
+ export function base32Encode(bytes: Uint8Array): string {
35
+ let out = ''
36
+ let bits = 0
37
+ let value = 0
38
+ for (let i = 0; i < bytes.length; i++) {
39
+ value = (value << 8) | bytes[i]!
40
+ bits += 8
41
+ while (bits >= 5) {
42
+ out += BASE32_ALPHABET[(value >>> (bits - 5)) & 31]!
43
+ bits -= 5
44
+ }
45
+ }
46
+ if (bits > 0)
47
+ out += BASE32_ALPHABET[(value << (5 - bits)) & 31]!
48
+ return out
49
+ }
50
+
51
+ export function base32Decode(input: string): Uint8Array {
52
+ const clean = input.toUpperCase().replace(/[\s=-]+/g, '')
53
+ const out: number[] = []
54
+ let bits = 0
55
+ let value = 0
56
+ for (let i = 0; i < clean.length; i++) {
57
+ const idx = BASE32_ALPHABET.indexOf(clean[i]!)
58
+ if (idx === -1)
59
+ throw new Error('prunelle: invalid base32 character in TOTP secret')
60
+ value = (value << 5) | idx
61
+ bits += 5
62
+ if (bits >= 8) {
63
+ out.push((value >>> (bits - 8)) & 0xFF)
64
+ bits -= 8
65
+ }
66
+ }
67
+ return new Uint8Array(out)
68
+ }
69
+
70
+ export function generateTotpSecret(): string {
71
+ const bytes = new Uint8Array(20)
72
+ crypto.getRandomValues(bytes)
73
+ return base32Encode(bytes)
74
+ }
75
+
76
+ export function generateTotpCode(secretBase32: string, timestampMs = Date.now()): string {
77
+ const key = base32Decode(secretBase32)
78
+ const step = Math.floor(timestampMs / 1000 / TOTP_PERIOD_SECONDS)
79
+ const counter = new Uint8Array(8)
80
+ const view = new DataView(counter.buffer)
81
+ view.setUint32(0, Math.floor(step / 0x1_0000_0000), false)
82
+ view.setUint32(4, step >>> 0, false)
83
+
84
+ const digest = new Uint8Array(new Bun.CryptoHasher('sha1', key).update(counter).digest())
85
+ const offset = digest[19]! & 0x0F
86
+ const binary = ((digest[offset]! & 0x7F) << 24)
87
+ | ((digest[offset + 1]! & 0xFF) << 16)
88
+ | ((digest[offset + 2]! & 0xFF) << 8)
89
+ | (digest[offset + 3]! & 0xFF)
90
+ const code = binary % (10 ** TOTP_DIGITS)
91
+ return String(code).padStart(TOTP_DIGITS, '0')
92
+ }
93
+
94
+ export function buildOtpauthUrl(issuer: string, email: string, secretBase32: string): string {
95
+ const label = `${encodeURIComponent(issuer)}:${encodeURIComponent(email)}`
96
+ return `otpauth://totp/${label}?secret=${encodeURIComponent(secretBase32)}&issuer=${encodeURIComponent(issuer)}&algorithm=SHA1&digits=${TOTP_DIGITS}&period=${TOTP_PERIOD_SECONDS}`
97
+ }
98
+
99
+ function matchTotpStep(secretBase32: string, rawCode: string, nowMs: number, lastUsedStep?: number): number | undefined {
100
+ const clean = rawCode.replace(/[\s-]+/g, '')
101
+ if (!/^\d{6}$/.test(clean))
102
+ return undefined
103
+ const currentStep = Math.floor(nowMs / 1000 / TOTP_PERIOD_SECONDS)
104
+ for (const offset of [-1, 0, 1]) {
105
+ const step = currentStep + offset
106
+ if (lastUsedStep !== undefined && step <= lastUsedStep)
107
+ continue
108
+ const expected = generateTotpCode(secretBase32, step * TOTP_PERIOD_SECONDS * 1000)
109
+ if (safeEqual(clean, expected))
110
+ return step
111
+ }
112
+ return undefined
113
+ }
114
+
115
+ function normalizeRecoveryCode(code: string): string {
116
+ return code.replace(/[\s-]+/g, '').toUpperCase()
117
+ }
118
+
119
+ function generateRecoveryCodeBatch(userId: string): { plain: string[], records: RecoveryCodeRecord[] } {
120
+ const now = Date.now()
121
+ const plain: string[] = []
122
+ const records: RecoveryCodeRecord[] = []
123
+ for (let i = 0; i < RECOVERY_CODE_COUNT; i++) {
124
+ const bytes = new Uint8Array(8)
125
+ crypto.getRandomValues(bytes)
126
+ let raw = ''
127
+ for (let j = 0; j < 8; j++)
128
+ raw += RECOVERY_ALPHABET[bytes[j]! & 31]!
129
+ const formatted = `${raw.slice(0, 4)}-${raw.slice(4)}`
130
+ const salt = randomToken(16)
131
+ plain.push(formatted)
132
+ records.push({
133
+ id: crypto.randomUUID(),
134
+ userId,
135
+ codeHash: sha256Hex(`${salt}:${raw}`),
136
+ salt,
137
+ createdAt: now,
138
+ })
139
+ }
140
+ return { plain, records }
141
+ }
142
+
143
+ export interface TotpManagerDeps<TUser extends AuthUser = AuthUser> {
144
+ store: AuthStore<TUser>
145
+ sessions: SessionManager<TUser>
146
+ /** The app's signing secret, resolved at first use. */
147
+ secret: () => string
148
+ twoFactorCookieName: string
149
+ getDefaultIssuer: () => string
150
+ isSecureCookie: (ctx: RequestContext) => boolean
151
+ }
152
+
153
+ export interface TotpManager {
154
+ setupTotp(userId: string, opts?: { issuer?: string | undefined }): Promise<{ secret: string, otpauthUrl: string }>
155
+ confirmTotp(userId: string, code: string): Promise<{ enabled: true, recoveryCodes: string[] }>
156
+ verifyTotp(userId: string, code: string): Promise<{ valid: boolean, method?: 'totp' | 'recovery' | undefined }>
157
+ disableTotp(userId: string, code: string): Promise<boolean>
158
+ regenerateRecoveryCodes(userId: string): Promise<string[]>
159
+ getTwoFactorMethods(userId: string): Promise<TwoFactorMethod[]>
160
+ issuePendingCookie(ctx: RequestContext, userId: string, redirect: string, methods: TwoFactorMethod[]): void
161
+ readPendingCookie(ctx: RequestContext): PendingTwoFactor | undefined
162
+ clearPendingCookie(ctx: RequestContext): void
163
+ }
164
+
165
+ function requireTotpStore<TUser extends AuthUser>(store: AuthStore<TUser>) {
166
+ if (!store.getTotp || !store.setTotp || !store.deleteTotp || !store.listRecoveryCodes || !store.setRecoveryCodes || !store.consumeRecoveryCode || !store.deleteRecoveryCodes)
167
+ throw new Error('prunelle: configured AuthStore does not support TOTP')
168
+ return {
169
+ getTotp: store.getTotp.bind(store),
170
+ setTotp: store.setTotp.bind(store),
171
+ deleteTotp: store.deleteTotp.bind(store),
172
+ listRecoveryCodes: store.listRecoveryCodes.bind(store),
173
+ setRecoveryCodes: store.setRecoveryCodes.bind(store),
174
+ consumeRecoveryCode: store.consumeRecoveryCode.bind(store),
175
+ deleteRecoveryCodes: store.deleteRecoveryCodes.bind(store),
176
+ }
177
+ }
178
+
179
+ function createKeyedLock() {
180
+ const queues = new Map<string, Promise<void>>()
181
+ return async function withLock<T>(key: string, fn: () => Promise<T>): Promise<T> {
182
+ const prev = queues.get(key) ?? Promise.resolve()
183
+ let release!: () => void
184
+ const current = new Promise<void>((resolve) => { release = resolve })
185
+ const tail = prev.then(() => current)
186
+ queues.set(key, tail)
187
+ await prev
188
+ try {
189
+ return await fn()
190
+ }
191
+ finally {
192
+ release()
193
+ if (queues.get(key) === tail)
194
+ queues.delete(key)
195
+ }
196
+ }
197
+ }
198
+
199
+ export function respondTwoFactorChallenge(
200
+ totp: Pick<TotpManager, 'issuePendingCookie'>,
201
+ ctx: RequestContext,
202
+ userId: string,
203
+ redirectTarget: string,
204
+ twoFactorRedirect: string,
205
+ methods: TwoFactorMethod[],
206
+ redirectStatus: 302 | 303 = 303,
207
+ ): Response {
208
+ totp.issuePendingCookie(ctx, userId, redirectTarget, methods)
209
+ if (wantsJson(ctx.request))
210
+ return ctx.json({ ok: true, twoFactorRequired: true, methods, userId }, { status: 200 })
211
+ const sep = twoFactorRedirect.includes('?') ? '&' : '?'
212
+ return ctx.redirect(`${twoFactorRedirect}${sep}next=${encodeURIComponent(redirectTarget)}`, redirectStatus)
213
+ }
214
+
215
+ function createPendingCookieHelpers(
216
+ secret: () => string,
217
+ twoFactorCookieName: string,
218
+ isSecureCookie: (ctx: RequestContext) => boolean,
219
+ ): Pick<TotpManager, 'issuePendingCookie' | 'readPendingCookie' | 'clearPendingCookie'> {
220
+ return {
221
+ issuePendingCookie(ctx, userId, redirect, methods) {
222
+ const payload: PendingTwoFactor = {
223
+ userId,
224
+ redirect,
225
+ methods,
226
+ exp: Date.now() + PENDING_2FA_TTL_MS,
227
+ }
228
+ ctx.cookies.set(twoFactorCookieName, signPayload(secret(), payload), authCookie(isSecureCookie(ctx), Math.floor(PENDING_2FA_TTL_MS / 1000)))
229
+ },
230
+
231
+ readPendingCookie(ctx) {
232
+ const raw = ctx.cookies.get(twoFactorCookieName)
233
+ if (!raw)
234
+ return undefined
235
+ const parsed = verifyPayload<PendingTwoFactor>(secret(), raw)
236
+ if (!parsed || parsed.exp <= Date.now() || !parsed.userId)
237
+ return undefined
238
+ return parsed
239
+ },
240
+
241
+ clearPendingCookie(ctx) {
242
+ ctx.cookies.delete(twoFactorCookieName, { path: '/' })
243
+ },
244
+ }
245
+ }
246
+
247
+ export function createTotpManager<TUser extends AuthUser = AuthUser>(deps: TotpManagerDeps<TUser>): TotpManager {
248
+ const { store, sessions, secret, twoFactorCookieName, getDefaultIssuer, isSecureCookie } = deps
249
+ const withUserLock = createKeyedLock()
250
+
251
+ async function tryConsumeRecoveryCode(userId: string, rawCode: string): Promise<boolean> {
252
+ const ts = requireTotpStore(store)
253
+ const normalized = normalizeRecoveryCode(rawCode)
254
+ if (normalized.length < 6)
255
+ return false
256
+ const records = await sessions.observeAsync(ts.listRecoveryCodes(userId))
257
+ for (const rec of records) {
258
+ const candidate = sha256Hex(`${rec.salt}:${normalized}`)
259
+ if (safeEqual(candidate, rec.codeHash)) {
260
+ const consumed = await sessions.observeAsync(ts.consumeRecoveryCode(rec.id))
261
+ if (consumed)
262
+ return true
263
+ }
264
+ }
265
+ return false
266
+ }
267
+
268
+ async function claimTotpStep(userId: string, encryptedSecret: string, matchedStep: number): Promise<boolean> {
269
+ const now = Date.now()
270
+ if (store.advanceTotpStep)
271
+ return await sessions.observeAsync(store.advanceTotpStep(userId, matchedStep, now))
272
+ return withUserLock(userId, async () => {
273
+ const ts = requireTotpStore(store)
274
+ const latest = await sessions.observeAsync(ts.getTotp(userId))
275
+ if (!latest || !latest.enabled || latest.encryptedSecret !== encryptedSecret)
276
+ return false
277
+ if (latest.lastUsedStep !== undefined && matchedStep <= latest.lastUsedStep)
278
+ return false
279
+ await sessions.observeAsync(ts.setTotp({ ...latest, lastUsedStep: matchedStep, updatedAt: now }))
280
+ return true
281
+ })
282
+ }
283
+
284
+ async function verifyTotp(userId: string, code: string): Promise<{ valid: boolean, method?: 'totp' | 'recovery' | undefined }> {
285
+ const ts = requireTotpStore(store)
286
+ const record = await sessions.observeAsync(ts.getTotp(userId))
287
+ if (!record || !record.enabled)
288
+ return { valid: false }
289
+
290
+ const plainSecret = await decryptSecret(secret(), record.encryptedSecret)
291
+ const matchedStep = matchTotpStep(plainSecret, code, Date.now(), record.lastUsedStep)
292
+ if (matchedStep !== undefined) {
293
+ const claimed = await claimTotpStep(userId, record.encryptedSecret, matchedStep)
294
+ return claimed ? { valid: true, method: 'totp' } : { valid: false }
295
+ }
296
+
297
+ if (await tryConsumeRecoveryCode(userId, code))
298
+ return { valid: true, method: 'recovery' }
299
+
300
+ return { valid: false }
301
+ }
302
+
303
+ return {
304
+ async setupTotp(userId, opts) {
305
+ const ts = requireTotpStore(store)
306
+ const user = await sessions.observeAsync(store.getUserById(userId))
307
+ if (!user)
308
+ throw new Error('prunelle: user not found')
309
+ const existing = await sessions.observeAsync(ts.getTotp(userId))
310
+ if (existing?.enabled)
311
+ throw new Error('prunelle: TOTP is already enabled for this account')
312
+
313
+ const base32Secret = generateTotpSecret()
314
+ const encryptedSecret = await encryptSecret(secret(), base32Secret)
315
+ const now = Date.now()
316
+ await sessions.observeAsync(ts.setTotp({
317
+ userId,
318
+ encryptedSecret,
319
+ enabled: false,
320
+ createdAt: now,
321
+ updatedAt: now,
322
+ }))
323
+ const issuer = opts?.issuer?.trim() || getDefaultIssuer()
324
+ return {
325
+ secret: base32Secret,
326
+ otpauthUrl: buildOtpauthUrl(issuer, user.email, base32Secret),
327
+ }
328
+ },
329
+
330
+ async confirmTotp(userId, code) {
331
+ const ts = requireTotpStore(store)
332
+ const record = await sessions.observeAsync(ts.getTotp(userId))
333
+ if (!record)
334
+ throw new Error('prunelle: no pending TOTP enrollment found')
335
+ if (record.enabled)
336
+ throw new Error('prunelle: TOTP is already enabled for this account')
337
+
338
+ const plainSecret = await decryptSecret(secret(), record.encryptedSecret)
339
+ const matchedStep = matchTotpStep(plainSecret, code, Date.now())
340
+ if (matchedStep === undefined)
341
+ throw new Error('prunelle: invalid TOTP verification code')
342
+
343
+ const { plain, records } = generateRecoveryCodeBatch(userId)
344
+ await sessions.observeAsync(ts.setTotp({
345
+ ...record,
346
+ enabled: true,
347
+ lastUsedStep: matchedStep,
348
+ updatedAt: Date.now(),
349
+ }))
350
+ await sessions.observeAsync(ts.setRecoveryCodes(userId, records))
351
+ return { enabled: true, recoveryCodes: plain }
352
+ },
353
+
354
+ verifyTotp,
355
+
356
+ async disableTotp(userId, code) {
357
+ const ts = requireTotpStore(store)
358
+ const result = await verifyTotp(userId, code)
359
+ if (!result.valid)
360
+ return false
361
+ await withUserLock(userId, async () => {
362
+ await sessions.observeAsync(ts.deleteTotp(userId))
363
+ await sessions.observeAsync(ts.deleteRecoveryCodes(userId))
364
+ })
365
+ return true
366
+ },
367
+
368
+ async regenerateRecoveryCodes(userId) {
369
+ const ts = requireTotpStore(store)
370
+ const record = await sessions.observeAsync(ts.getTotp(userId))
371
+ if (!record || !record.enabled)
372
+ throw new Error('prunelle: TOTP is not enabled for this account')
373
+ const { plain, records } = generateRecoveryCodeBatch(userId)
374
+ await sessions.observeAsync(ts.setRecoveryCodes(userId, records))
375
+ return plain
376
+ },
377
+
378
+ async getTwoFactorMethods(userId) {
379
+ if (!store.getTotp)
380
+ return []
381
+ const record = await sessions.observeAsync(store.getTotp(userId))
382
+ if (!record?.enabled)
383
+ return []
384
+ const methods: TwoFactorMethod[] = ['totp']
385
+ if (store.listPasskeys) {
386
+ const passkeys = await sessions.observeAsync(store.listPasskeys(userId))
387
+ if (passkeys.length > 0)
388
+ methods.push('passkey')
389
+ }
390
+ return methods
391
+ },
392
+
393
+ ...createPendingCookieHelpers(secret, twoFactorCookieName, isSecureCookie),
394
+ }
395
+ }