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