@prunellejs/auth 0.7.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/llms.txt CHANGED
@@ -17,7 +17,7 @@
17
17
  - `secret`: string (defaults to `process.env.AUTH_SECRET`; required and ≥32 UTF-8 bytes in `NODE_ENV=production`, checked by `requires()` at start, so a build runs without it). Also derives the AES-256-GCM key (via HKDF-SHA256) encrypting TOTP seeds at rest.
18
18
  - `site`: public origin (`https://example.com`, inherits `PrunelleConfig.site`; required off localhost for mailed links, OAuth callbacks, and WebAuthn origin/rpId defaults).
19
19
  - `basePath`: route prefix (default `'/auth'`).
20
- - `cookieName`: session cookie name (default `'pru_session'`; sent as `__Host-pru_session` over https, a session under the plain name is moved on its next request). Short-lived signed cookies use `${cookieName}_oauth`, `${cookieName}_2fa`, and `${cookieName}_webauthn`.
20
+ - `cookieName`: session cookie name (default `'pru_session'`; sent as `__Host-pru_session` over https). Set `acceptLegacyCookie: true` temporarily when upgrading to accept and migrate sessions still under the unprefixed name over https (default `false` so sibling subdomains cannot fixate sessions). Short-lived signed cookies use `${cookieName}_oauth`, `${cookieName}_2fa`, and `${cookieName}_webauthn`.
21
21
  - `storeOAuthProfile` (default `false`): keep the provider's name and avatar URL on an OAuth sign-up; off, the account holds the email alone.
22
22
  - `sessionTtlSeconds` (default 30 days), `absoluteTtlSeconds` (default 90 days from sign-in, however often the session is used; `false` for none), `renewalIntervalSeconds` (sliding renewal), `tokenTtlSeconds` (default 15 min), `orgInviteTtlSeconds` (default 7 days).
23
23
  - `minPasswordLength`: default `12` (CNIL guidance). `maxPasswordLength`: default `1024` (chars/UTF-8 bytes, capped before Argon2id). `defaultRole`: `'user'`. `defaultRedirect`: `'/'`.
@@ -27,7 +27,7 @@
27
27
  - `mailer`: pass a `@prunellejs/mail` `Mailer` directly, or `sendMail(mail: AuthMailPayload)` (handles `kind: 'magic-link' | 'verify-email' | 'reset-password' | 'org-invite'`).
28
28
  - `providers`: `[github({ clientId, clientSecret, scopes? }), discord(...), google(...), oauthProvider(...)]`.
29
29
  - `totp`: `{ issuer?, verifyPath? }`. `twoFactorRedirect`: custom redirect target for HTML form sign-ins when 2FA is required (default `${basePath}/totp/verify`).
30
- - `passkeys`: `{ rpId?, rpName?, origin?, userVerification? }` (WebAuthn L2 ES256 / RS256 / EdDSA, zero npm deps).
30
+ - `passkeys`: `{ rpId?, rpName?, origin?, userVerification? }` (WebAuthn L2 ES256 / RS256 / EdDSA, zero npm deps). By default `userVerification` is `'required'` for registration and passwordless login (refusing assertions without UV) and `'preferred'` when used as 2FA; set `userVerification: 'preferred' | 'discouraged'` to opt out explicitly.
31
31
  - `trustProxy`: inherits `PrunelleConfig.trustProxy`. `trustedOrigins`: merged with `PrunelleConfig.trustedOrigins`.
32
32
  - `rateLimit`: `{ max?, windowMs?, mailsPerAddress?, failuresPerAccount? } | false`, counted in the server's store, a refusal being a `429` with `Retry-After`: `max` attempts per `windowMs` per scope and address (default 15 a minute); `mailsPerAddress` mails to one address per 10 minutes from sign-up, magic links and org invites (default 3); `failuresPerAccount` wrong passwords per hour on one account across all addresses (default 100), past which sign-in refuses that account before checking the password. A right password never counts, so a guesser can lock an account only by sending that many wrong ones. `pruneIntervalMs`: default 15 min (`false` disables).
33
33
  - RGPD minimization: `storeIp`: `'truncate'` (default, /24 IPv4 and /48 IPv6) | `true` | `false`; `storeUserAgent`: `true` (default) | `false`.
@@ -39,7 +39,7 @@
39
39
  - Core: `GET /auth/session`, `POST /auth/signup`, `POST /auth/signin`, `POST /auth/signout`, `GET|POST /auth/verify-email`, `POST /auth/magic-link`, `GET|POST /auth/magic-link/verify`, `GET /auth/oauth/:provider`, `GET /auth/oauth/:provider/callback`.
40
40
  - Account (RGPD art. 15, 17, 20), both refusing `401` when signed out and `403` `{ code: 'reauth-required' }` when the session opened more than 10 minutes ago (`FRESH_SIGNIN_MS`): `GET /auth/me/export` downloads `auth.exportUser()` as `account.json`; `POST /auth/me/delete` runs `auth.deleteUser()`, signs out and answers `{ ok: true }` or redirects to `redirect` (default `/`). Deleting takes the orgs the user alone belongs to and refuses `409` while they are the last owner of one with other members.
41
41
  - TOTP 2FA (works without JS via HTML forms or JSON):
42
- - When a user with TOTP enabled signs in via `POST /auth/signin`, no session is opened yet: a 5-minute HttpOnly signed `${cookieName}_2fa` cookie is issued; HTML redirects to `/auth/totp/verify?next=...` and JSON returns `{ ok: true, twoFactorRequired: true, methods: ['totp', ...], userId }`.
42
+ - When a user with TOTP enabled signs in via any path (`POST /auth/signin`, magic link verify, OAuth callback, or passkey login), no session is opened yet: a 5-minute HttpOnly signed `${cookieName}_2fa` cookie is issued; HTML redirects to `/auth/totp/verify?next=...` and JSON returns `{ ok: true, twoFactorRequired: true, methods: ['totp', ...], userId }` (passkey login requires TOTP/recovery code and excludes `'passkey'` from `methods`).
43
43
  - `POST /auth/totp/setup` (authenticated) → creates pending enrollment `{ secret, otpauthUrl }`.
44
44
  - `POST /auth/totp/confirm` (authenticated, `code`) → enables TOTP and returns 10 single-use recovery codes (`XXXX-XXXX`).
45
45
  - `GET /auth/totp/verify` & `POST /auth/totp/verify` (pending 2FA cookie, `code` = 6-digit TOTP or recovery code) → clears pending cookie and opens session.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prunellejs/auth",
3
- "version": "0.7.0",
3
+ "version": "0.7.1",
4
4
  "description": "Zero-dependency Bun-native auth plugin for Prunelle (Argon2id, hashed sessions, SQLite, magic links, OAuth2 PKCE, TOTP 2FA, Passkeys, Organizations)",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -24,6 +24,6 @@
24
24
  "directory": "packages/plugin-auth"
25
25
  },
26
26
  "peerDependencies": {
27
- "prunelle": "^0.7.0"
27
+ "prunelle": "^0.7.1"
28
28
  }
29
29
  }
package/src/http.ts CHANGED
@@ -96,7 +96,7 @@ export async function parseJsonBody(ctx: RequestContext): Promise<Record<string,
96
96
  export type AuthRouteRegistrar = (
97
97
  method: 'GET' | 'POST',
98
98
  path: string,
99
- routeCfg: { limit?: string, mailLimit?: string, readBody?: boolean },
99
+ routeCfg: { limit?: string, readBody?: boolean },
100
100
  handler: (ctx: RequestContext, body: Record<string, string>) => Response | Promise<Response>,
101
101
  ) => void
102
102
 
@@ -120,18 +120,13 @@ export function createAuthRouteRegistrar(
120
120
  return withNoStore(parsed)
121
121
  body = parsed
122
122
  }
123
- if (routeCfg.mailLimit !== undefined) {
124
- const limited = limits.limitMail(ctx, routeCfg.mailLimit, body.email)
125
- if (limited)
126
- return withNoStore(limited)
127
- }
128
123
  return withNoStore(await handler(ctx, body))
129
124
  }, method === 'POST' ? authRouteOpts : undefined)
130
125
  }
131
126
  }
132
127
 
133
- // Whitespace, and the characters that split or wrap an address list.
134
- const EMAIL_FORBIDDEN_RE = /[\s,;<>]/
128
+ // Control characters (C0/DEL), whitespace, and the characters that split or wrap an address list.
129
+ const EMAIL_FORBIDDEN_RE = /[\u0000-\u001F\u007F\s,;<>]/
135
130
 
136
131
  export function isValidEmail(email: string): boolean {
137
132
  const e = email.trim()
@@ -146,8 +141,8 @@ export function resolveClientIp(ctx: RequestContext, trustProxy: TrustProxy): st
146
141
  export interface AuthLimits {
147
142
  /** The 429 to answer when this address is past the limit of `scope`, else `undefined`. */
148
143
  limitIp: (ctx: RequestContext, scope: string) => Response | undefined
149
- /** The same per email across addresses, at the mail limit, for the forms that mail it; nothing is counted without an email. */
150
- limitMail: (ctx: RequestContext, scope: string, email: string | undefined) => Response | undefined
144
+ /** The same per normalized email across addresses and mail routes, at the mail limit; nothing is counted without an email. */
145
+ limitMail: (ctx: RequestContext, email: string | undefined) => Response | undefined
151
146
  /** The 429 to answer, before the password is checked, when this account is past its wrong passwords across addresses. */
152
147
  refuseLockedAccount: (ctx: RequestContext, email: string) => Response | undefined
153
148
  /** Counts a wrong password against the account. */
@@ -181,9 +176,9 @@ function tooMany(ctx: RequestContext, retryAfter: number): Response | undefined
181
176
  export function authLimits(limiters: AuthLimiters | undefined, getTrustProxy: () => TrustProxy): AuthLimits {
182
177
  return {
183
178
  limitIp: (ctx, scope) => tooMany(ctx, limiters?.attempts.hit(`${scope}:ip:${rateLimitAddress(resolveClientIp(ctx, getTrustProxy()))}`) ?? 0),
184
- limitMail(ctx, scope, email) {
179
+ limitMail(ctx, email) {
185
180
  const normalized = normalizeEmail(email ?? '')
186
- return normalized ? tooMany(ctx, limiters?.mails.hit(`${scope}:${normalized}`) ?? 0) : undefined
181
+ return normalized ? tooMany(ctx, limiters?.mails.hit(normalized) ?? 0) : undefined
187
182
  },
188
183
  refuseLockedAccount: (ctx, email) => tooMany(ctx, email ? limiters?.failures.peek(`signin:${email}`) ?? 0 : 0),
189
184
  countFailedSignin(email) {
package/src/index.ts CHANGED
@@ -154,8 +154,10 @@ export interface AuthOptions<TUser extends AuthUser = AuthUser> {
154
154
  secret?: string | undefined
155
155
  /** Route prefix (default: '/auth'). */
156
156
  basePath?: string | undefined
157
- /** Session cookie name (default: 'pru_session'). Over https the cookie is sent as `__Host-<name>`, and a session still under the plain name is moved on its next request. */
157
+ /** Session cookie name (default: 'pru_session'). Over https the cookie is sent as `__Host-<name>`. */
158
158
  cookieName?: string | undefined
159
+ /** Accept and migrate sessions still sent under the unprefixed `cookieName` over https (default: `false`). Enable temporarily when upgrading existing apps so sibling subdomains cannot fixate sessions. */
160
+ acceptLegacyCookie?: boolean | undefined
159
161
  /** Session lifetime in seconds (default: 30 days). */
160
162
  sessionTtlSeconds?: number | undefined
161
163
  /** Longest a session lives, counted from sign-in however often it is used (default: 90 days, never less than `sessionTtlSeconds`; `false` lets renewal go on forever). */
@@ -284,14 +286,17 @@ const NO_MAILER = '`requireEmailVerification` is on but no mailer is set, so no
284
286
  const DEFAULT_UNVERIFIED_TTL_SECONDS = 7 * 24 * 60 * 60
285
287
  const DEFAULT_ABSOLUTE_TTL_SECONDS = 90 * 24 * 60 * 60
286
288
 
287
- /** The sliding lifetime, the absolute one and the renewal interval of a session, in ms. */
288
- function sessionTimings(options: Pick<AuthOptions, 'sessionTtlSeconds' | 'absoluteTtlSeconds' | 'renewalIntervalSeconds'>): { sessionTtlMs: number, absoluteTtlMs: number | undefined, renewalIntervalMs: number } {
289
+ /** Session timings and cookie/privacy settings derived from `AuthOptions`. */
290
+ function sessionConfig(options: Pick<AuthOptions, 'sessionTtlSeconds' | 'absoluteTtlSeconds' | 'renewalIntervalSeconds' | 'acceptLegacyCookie' | 'storeIp' | 'storeUserAgent'>) {
289
291
  const sessionTtlSeconds = options.sessionTtlSeconds ?? 60 * 60 * 24 * 30
290
292
  const sessionTtlMs = sessionTtlSeconds * 1000
291
293
  return {
292
294
  sessionTtlMs,
293
295
  absoluteTtlMs: options.absoluteTtlSeconds === false ? undefined : Math.max(sessionTtlMs, (options.absoluteTtlSeconds ?? DEFAULT_ABSOLUTE_TTL_SECONDS) * 1000),
294
296
  renewalIntervalMs: Math.max(0, (options.renewalIntervalSeconds ?? Math.min(60 * 60, Math.max(1, Math.floor(sessionTtlSeconds / 4)))) * 1000),
297
+ acceptLegacyCookie: options.acceptLegacyCookie === true,
298
+ storeIp: options.storeIp ?? 'truncate' as const,
299
+ storeUserAgent: options.storeUserAgent !== false,
295
300
  }
296
301
  }
297
302
 
@@ -372,9 +377,7 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
372
377
  const sessions = createSessionManager({
373
378
  store,
374
379
  cookieName,
375
- ...sessionTimings(options),
376
- storeIp: options.storeIp ?? 'truncate',
377
- storeUserAgent: options.storeUserAgent !== false,
380
+ ...sessionConfig(options),
378
381
  getTrustProxy: () => trustProxy,
379
382
  isSecureCookie,
380
383
  })
@@ -518,8 +521,8 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
518
521
  sendMagicLink,
519
522
  })
520
523
  registerTotpRoutes({ authRoute, store, sessions, totp, basePath, defaultRedirect, messages })
521
- registerPasskeyRoutes({ authRoute, store, sessions, passkeys, totp, defaultRedirect, requireEmailVerification })
522
- registerOrgRoutes({ authRoute, sessions, orgs, defaultRedirect, hasMailTransport, mailedLinkOrigin })
524
+ registerPasskeyRoutes({ authRoute, store, sessions, passkeys, totp, twoFactorRedirect, defaultRedirect, requireEmailVerification })
525
+ registerOrgRoutes({ authRoute, limits: authLimitsObj, sessions, orgs, defaultRedirect, hasMailTransport, mailedLinkOrigin })
523
526
  registerAccountRoutes({ authRoute, sessions, account, clearPendingCookie: ctx => totp.clearPendingCookie(ctx) })
524
527
  registerOAuthRoutes({
525
528
  route: (method, path, handler) => api.route(method, path, handler),
@@ -539,6 +542,8 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
539
542
  claimUnverified,
540
543
  insertUser,
541
544
  storeProfile: options.storeOAuthProfile === true,
545
+ totp,
546
+ twoFactorRedirect,
542
547
  createSessionForUser: sessions.createSessionForUser,
543
548
  observeAsync: sessions.observeAsync,
544
549
  })
@@ -564,7 +569,7 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
564
569
  stopPruneTimer?.()
565
570
  activeServers = Math.max(0, activeServers - 1)
566
571
  if (activeServers === 0)
567
- await store.close?.()
572
+ await links.drain().then(() => store.close?.())
568
573
  })
569
574
 
570
575
  // Sync stores resolve lazily on first read of ctx.locals.user/session; async or unknown Promise-returning stores await before next().
package/src/links.ts CHANGED
@@ -49,6 +49,7 @@ export interface LinkServiceDeps<TUser extends AuthUser = AuthUser> {
49
49
 
50
50
  export function createLinkService<TUser extends AuthUser = AuthUser>(deps: LinkServiceDeps<TUser>) {
51
51
  const { store, sessions, basePath, defaultRedirect, tokenTtlMs, deliverMail } = deps
52
+ const pendingDeliveries = new Set<Promise<void>>()
52
53
 
53
54
  async function issueLink(
54
55
  kind: 'magic-link' | 'verify-email',
@@ -76,10 +77,13 @@ export function createLinkService<TUser extends AuthUser = AuthUser>(deps: LinkS
76
77
 
77
78
  if (deliverMail && origin !== undefined) {
78
79
  const delivery = deliverLink(deliverMail, kind, normalized, url, tokenHash)
79
- if (background === undefined)
80
+ if (background === undefined) {
80
81
  await delivery
81
- else
82
- void delivery.catch(err => failBackgroundMail(err, background))
82
+ }
83
+ else {
84
+ const tracked = delivery.catch(err => failBackgroundMail(err, background)).finally(() => { pendingDeliveries.delete(tracked) })
85
+ pendingDeliveries.add(tracked)
86
+ }
83
87
  }
84
88
  return url
85
89
  }
@@ -145,10 +149,30 @@ export function createLinkService<TUser extends AuthUser = AuthUser>(deps: LinkS
145
149
  return { email: consumed.email, user }
146
150
  }
147
151
 
152
+ async function drain(timeoutMs = 5_000): Promise<void> {
153
+ if (pendingDeliveries.size === 0)
154
+ return
155
+ let timer: ReturnType<typeof setTimeout> | undefined
156
+ try {
157
+ await Promise.race([
158
+ Promise.allSettled([...pendingDeliveries]),
159
+ new Promise<void>((resolve) => {
160
+ timer = setTimeout(resolve, timeoutMs)
161
+ timer.unref?.()
162
+ }),
163
+ ])
164
+ }
165
+ finally {
166
+ if (timer !== undefined)
167
+ clearTimeout(timer)
168
+ }
169
+ }
170
+
148
171
  return {
149
172
  issueLink,
150
173
  sendVerificationEmail,
151
174
  sendMagicLink,
152
175
  consumeLink,
176
+ drain,
153
177
  }
154
178
  }
@@ -4,10 +4,12 @@ import type { RequestContext } from 'prunelle/server'
4
4
  import { safeEqual, safeRedirect } from 'prunelle/server'
5
5
  import type { OAuthProfile, OAuthProvider } from './oauth'
6
6
  import type { AuthStore, AuthUser, PublicUser } from './store'
7
+ import type { TotpManager } from './totp'
7
8
  import { pkceChallenge, randomToken, signPayload, verifyPayload } from './crypto'
8
9
  import { authCookie, fail, withNoStore } from './http'
9
10
  import { OAUTH_FETCH_TIMEOUT_MS } from './oauth'
10
11
  import { normalizeEmail, toPublicUser } from './store'
12
+ import { respondTwoFactorChallenge } from './totp'
11
13
 
12
14
  interface OAuthStateCookie {
13
15
  provider: string
@@ -37,6 +39,8 @@ export interface OAuthRouteDeps<TUser extends AuthUser = AuthUser> {
37
39
  insertUser: (fields: Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>) => Promise<TUser>
38
40
  /** Keep the provider's name and avatar URL on a new account. */
39
41
  storeProfile: boolean
42
+ totp: Pick<TotpManager, 'getTwoFactorMethods' | 'issuePendingCookie'>
43
+ twoFactorRedirect: string
40
44
  createSessionForUser: (userId: string, ctx: RequestContext, knownUser?: PublicUser<TUser>) => Promise<unknown>
41
45
  observeAsync: <T>(value: T | Promise<T>) => T | Promise<T>
42
46
  }
@@ -246,6 +250,10 @@ export function registerOAuthRoutes<TUser extends AuthUser = AuthUser>(deps: OAu
246
250
  if (resolved instanceof Response)
247
251
  return resolved
248
252
 
253
+ const twoFactorMethods = await deps.totp.getTwoFactorMethods(resolved.id)
254
+ if (twoFactorMethods.length > 0)
255
+ return respondTwoFactorChallenge(deps.totp, ctx, resolved.id, redirectTarget, deps.twoFactorRedirect, twoFactorMethods, 302)
256
+
249
257
  await deps.createSessionForUser(resolved.id, ctx, toPublicUser(resolved))
250
258
  return ctx.redirect(redirectTarget, 302)
251
259
  })
package/src/org-routes.ts CHANGED
@@ -1,15 +1,17 @@
1
1
  // HTTP routes for organizations: create, invite, accept invitation, update member role, remove/leave member.
2
2
 
3
3
  import type { RequestContext } from 'prunelle/server'
4
- import type { AuthRouteRegistrar } from './http'
4
+ import type { AuthLimits, AuthRouteRegistrar } from './http'
5
5
  import type { OrgError, OrgManager } from './orgs'
6
6
  import type { SessionManager } from './session'
7
7
  import type { AuthUser, Organization } from './store'
8
8
  import { safeRedirect, wantsJson } from 'prunelle/server'
9
- import { fail, linkConfirmPage } from './http'
9
+ import { fail, isValidEmail, linkConfirmPage } from './http'
10
+ import { normalizeEmail } from './store'
10
11
 
11
12
  export interface OrgRoutesDeps<TUser extends AuthUser = AuthUser> {
12
13
  authRoute: AuthRouteRegistrar
14
+ limits: AuthLimits
13
15
  sessions: SessionManager<TUser>
14
16
  orgs: OrgManager
15
17
  defaultRedirect: string
@@ -107,7 +109,7 @@ function registerOrgMemberRoutes<TUser extends AuthUser>(
107
109
  }
108
110
 
109
111
  export function registerOrgRoutes<TUser extends AuthUser = AuthUser>(deps: OrgRoutesDeps<TUser>): void {
110
- const { authRoute, sessions, orgs, defaultRedirect, hasMailTransport, mailedLinkOrigin } = deps
112
+ const { authRoute, limits, sessions, orgs, defaultRedirect, hasMailTransport, mailedLinkOrigin } = deps
111
113
 
112
114
  async function resolveOrgParam(body: Record<string, string>): Promise<Organization | undefined> {
113
115
  const ref = (body.orgId ?? body.org ?? body.slug ?? '').trim()
@@ -132,7 +134,7 @@ export function registerOrgRoutes<TUser extends AuthUser = AuthUser>(deps: OrgRo
132
134
  }
133
135
  })
134
136
 
135
- authRoute('POST', '/orgs/invite', { limit: 'orgs-invite', mailLimit: 'orgs-invite', readBody: true }, async (ctx, body) => {
137
+ authRoute('POST', '/orgs/invite', { limit: 'orgs-invite', readBody: true }, async (ctx, body) => {
136
138
  const resolved = await sessions.resolve(ctx)
137
139
  if (!resolved)
138
140
  return fail(ctx, 401, 'Authentication required')
@@ -149,16 +151,24 @@ export function registerOrgRoutes<TUser extends AuthUser = AuthUser>(deps: OrgRo
149
151
  if (role === 'owner' && caller.role !== 'owner')
150
152
  return fail(ctx, 403, 'Only organization owners can invite another owner')
151
153
 
154
+ const email = normalizeEmail(body.email ?? '')
155
+ if (!isValidEmail(email))
156
+ return fail(ctx, 400, 'prunelle: please enter a valid email address')
157
+
152
158
  const linkOrigin = mailedLinkOrigin(ctx.url)
153
159
  if (hasMailTransport && linkOrigin === undefined) {
154
160
  console.error(`[prunelle/auth] refusing to mail an organization invite for host ${ctx.url.host}: set the auth \`site\` option to the public origin`)
155
161
  return fail(ctx, 500, 'Invitation links are not configured')
156
162
  }
157
163
 
164
+ const limited = limits.limitMail(ctx, email)
165
+ if (limited)
166
+ return limited
167
+
158
168
  const redirectTarget = safeRedirect(body.redirect ?? body.next, defaultRedirect)
159
169
  try {
160
170
  const { invitation } = await orgs.inviteToOrg(org.id, {
161
- email: body.email ?? '',
171
+ email,
162
172
  role,
163
173
  invitedBy: resolved.user.id,
164
174
  origin: linkOrigin,
@@ -130,14 +130,18 @@ export async function registerPasskey(options: RegisterPasskeyOptions = {}): Pro
130
130
  })
131
131
  }
132
132
 
133
- async function runAssertion(
133
+ export type PasskeySignInResult =
134
+ | { ok: true, user: Record<string, unknown>, twoFactorRequired?: false | undefined }
135
+ | { ok: true, twoFactorRequired: true, methods: Array<'totp' | 'passkey'>, userId: string, user?: undefined }
136
+
137
+ async function runAssertion<T = { ok: true, user: Record<string, unknown> }>(
134
138
  fetchImpl: typeof globalThis.fetch,
135
139
  optionsUrl: string,
136
140
  verifyUrl: string,
137
141
  startBody: Record<string, unknown>,
138
142
  extraVerify: Record<string, unknown>,
139
143
  mediation?: CredentialMediationRequirement,
140
- ): Promise<{ ok: true, user: Record<string, unknown> }> {
144
+ ): Promise<T> {
141
145
  if (!isPasskeySupported())
142
146
  throw new Error('Passkeys are not supported in this browser')
143
147
 
@@ -181,10 +185,10 @@ async function runAssertion(
181
185
  })
182
186
  }
183
187
 
184
- export async function signInWithPasskey(options: SignInWithPasskeyOptions = {}): Promise<{ ok: true, user: Record<string, unknown> }> {
188
+ export async function signInWithPasskey(options: SignInWithPasskeyOptions = {}): Promise<PasskeySignInResult> {
185
189
  const base = (options.basePath ?? '/auth').replace(/\/$/, '')
186
190
  const fetchImpl = options.fetch ?? globalThis.fetch
187
- return runAssertion(
191
+ return runAssertion<PasskeySignInResult>(
188
192
  fetchImpl,
189
193
  `${base}/passkeys/login/options`,
190
194
  `${base}/passkeys/login/verify`,
@@ -9,6 +9,7 @@ import type { TotpManager } from './totp'
9
9
  import { safeRedirect, wantsJson } from 'prunelle/server'
10
10
  import { fail, parseJsonBody } from './http'
11
11
  import { toPublicUser } from './store'
12
+ import { respondTwoFactorChallenge } from './totp'
12
13
 
13
14
  export interface PasskeyRoutesDeps<TUser extends AuthUser = AuthUser> {
14
15
  authRoute: AuthRouteRegistrar
@@ -16,6 +17,7 @@ export interface PasskeyRoutesDeps<TUser extends AuthUser = AuthUser> {
16
17
  sessions: SessionManager<TUser>
17
18
  passkeys: PasskeyManager
18
19
  totp: TotpManager
20
+ twoFactorRedirect: string
19
21
  defaultRedirect: string
20
22
  requireEmailVerification: boolean
21
23
  }
@@ -67,7 +69,7 @@ function asAssertionInput(body: Record<string, unknown>): AssertionVerifyInput |
67
69
  }
68
70
 
69
71
  export function registerPasskeyRoutes<TUser extends AuthUser = AuthUser>(deps: PasskeyRoutesDeps<TUser>): void {
70
- const { authRoute, store, sessions, passkeys, totp, defaultRedirect, requireEmailVerification } = deps
72
+ const { authRoute, store, sessions, passkeys, totp, twoFactorRedirect, defaultRedirect, requireEmailVerification } = deps
71
73
 
72
74
  authRoute('POST', '/passkeys/register/options', { limit: 'passkey-reg' }, async (ctx) => {
73
75
  const resolved = await sessions.resolve(ctx)
@@ -130,9 +132,13 @@ export function registerPasskeyRoutes<TUser extends AuthUser = AuthUser>(deps: P
130
132
  if (requireEmailVerification && !userRecord.emailVerified)
131
133
  return fail(ctx, 403, 'Email not verified')
132
134
 
135
+ const redirect = safeRedirect(typeof raw.redirect === 'string' ? raw.redirect : (typeof raw.next === 'string' ? raw.next : undefined), defaultRedirect)
136
+ const twoFactorMethods = (await totp.getTwoFactorMethods(userRecord.id)).filter(m => m !== 'passkey')
137
+ if (twoFactorMethods.length > 0)
138
+ return respondTwoFactorChallenge(totp, ctx, userRecord.id, redirect, twoFactorRedirect, twoFactorMethods)
139
+
133
140
  const pub = toPublicUser(userRecord)
134
141
  await sessions.createSessionForUser(userRecord.id, ctx, pub)
135
- const redirect = safeRedirect(typeof raw.redirect === 'string' ? raw.redirect : (typeof raw.next === 'string' ? raw.next : undefined), defaultRedirect)
136
142
  if (wantsJson(ctx.request))
137
143
  return ctx.json({ ok: true, user: pub }, { status: 200 })
138
144
  return ctx.redirect(redirect, 303)
@@ -146,6 +152,8 @@ export function registerPasskeyRoutes<TUser extends AuthUser = AuthUser>(deps: P
146
152
  const pending = totp.readPendingCookie(ctx)
147
153
  if (!pending)
148
154
  return fail(ctx, 401, 'Two-factor session expired or invalid')
155
+ if (!pending.methods.includes('passkey'))
156
+ return fail(ctx, 403, 'Passkey cannot be used as second factor for this sign-in')
149
157
  try {
150
158
  const options = await passkeys.createAssertionOptions(ctx, '2fa', { userId: pending.userId })
151
159
  return ctx.json({ ok: true, options }, { status: 200 })
@@ -159,6 +167,8 @@ export function registerPasskeyRoutes<TUser extends AuthUser = AuthUser>(deps: P
159
167
  const pending = totp.readPendingCookie(ctx)
160
168
  if (!pending)
161
169
  return fail(ctx, 401, 'Two-factor session expired or invalid')
170
+ if (!pending.methods.includes('passkey'))
171
+ return fail(ctx, 403, 'Passkey cannot be used as second factor for this sign-in')
162
172
  const raw = await parseJsonBody(ctx)
163
173
  if (raw instanceof Response)
164
174
  return raw
package/src/passkeys.ts CHANGED
@@ -21,7 +21,7 @@ export interface PasskeyOptions {
21
21
  rpName?: string | undefined
22
22
  /** Expected WebAuthn origin (defaults to `site` or request origin). */
23
23
  origin?: string | undefined
24
- /** Authenticator user verification requirement (default: `'preferred'`). */
24
+ /** Authenticator user verification requirement (default: `'required'` for registration and passwordless login, `'preferred'` for 2FA). */
25
25
  userVerification?: PasskeyUserVerification | undefined
26
26
  }
27
27
 
@@ -262,7 +262,8 @@ async function performAssertionVerify<TUser extends AuthUser>(
262
262
 
263
263
  export function createPasskeyManager<TUser extends AuthUser = AuthUser>(deps: PasskeyManagerDeps<TUser>): PasskeyManager {
264
264
  const { store, sessions, secret, challengeCookieName, getSite, options, isSecureCookie } = deps
265
- const userVerification: PasskeyUserVerification = options?.userVerification ?? 'preferred'
265
+ const userVerificationFor = (purpose: 'register' | 'login' | '2fa'): PasskeyUserVerification =>
266
+ options?.userVerification ?? (purpose === '2fa' ? 'preferred' : 'required')
266
267
  const activeChallenges = new Map<string, number>()
267
268
 
268
269
  function resolveExpectedOrigin(ctx: RequestContext): string {
@@ -320,7 +321,7 @@ export function createPasskeyManager<TUser extends AuthUser = AuthUser>(deps: Pa
320
321
  expectedChallenge: consumeChallenge(ctx, purpose, expectedUserId),
321
322
  expectedOrigin: resolveExpectedOrigin(ctx),
322
323
  expectedRpId: resolveRpId(ctx),
323
- userVerification,
324
+ userVerification: userVerificationFor(purpose),
324
325
  }
325
326
  }
326
327
 
@@ -350,7 +351,7 @@ export function createPasskeyManager<TUser extends AuthUser = AuthUser>(deps: Pa
350
351
  attestation: 'none',
351
352
  authenticatorSelection: {
352
353
  residentKey: 'preferred',
353
- userVerification,
354
+ userVerification: userVerificationFor('register'),
354
355
  },
355
356
  excludeCredentials: existing.map(p => ({
356
357
  type: 'public-key',
@@ -398,7 +399,7 @@ export function createPasskeyManager<TUser extends AuthUser = AuthUser>(deps: Pa
398
399
  challenge,
399
400
  timeout: CHALLENGE_TTL_MS,
400
401
  rpId,
401
- userVerification,
402
+ userVerification: userVerificationFor(purpose),
402
403
  ...(allowCredentials !== undefined ? { allowCredentials } : {}),
403
404
  }
404
405
  },
package/src/routes.ts CHANGED
@@ -12,6 +12,7 @@ import { safeRedirect, wantsJson } from 'prunelle/server'
12
12
  import { hashPassword, verifyPassword } from './crypto'
13
13
  import { fail, formPagePath, isValidEmail, linkConfirmPage, respondAuthError } from './http'
14
14
  import { normalizeEmail, toPublicUser } from './store'
15
+ import { respondTwoFactorChallenge } from './totp'
15
16
 
16
17
  const LINK_PAGES = {
17
18
  'magic-link': { title: 'Sign in', button: 'Sign in' },
@@ -40,13 +41,19 @@ async function reRegisterUnverified<TUser extends AuthUser>(
40
41
  const { store, sessions, issueLink } = deps
41
42
  // Same Argon2id cost as a first sign-up, so timing does not reveal a pending account.
42
43
  await hashPassword(password)
43
- const prevHash = existing.passwordHash
44
- const prevName = existing.name
44
+ const latest = await sessions.observeAsync(store.getUserById(existing.id))
45
+ if (!latest || latest.emailVerified)
46
+ return true
47
+ const prevHash = latest.passwordHash
48
+ const prevName = latest.name
45
49
  await sessions.observeAsync(store.deleteUserSessions(existing.id))
46
50
  await sessions.observeAsync(store.deleteUserOAuthAccounts(existing.id))
47
51
  const patch = { passwordHash: undefined, name: undefined } as Partial<Omit<TUser, 'id' | 'createdAt'>>
48
- await sessions.observeAsync(store.updateUser(existing.id, patch))
52
+ const cleared = await sessions.observeAsync(store.updateUser(existing.id, patch))
49
53
  const restore = async (): Promise<void> => {
54
+ const cur = await sessions.observeAsync(store.getUserById(existing.id))
55
+ if (!cur || cur.emailVerified || cur.updatedAt !== cleared?.updatedAt)
56
+ return
50
57
  await sessions.observeAsync(store.updateUser(existing.id, { passwordHash: prevHash, name: prevName } as Partial<Omit<TUser, 'id' | 'createdAt'>>))
51
58
  }
52
59
  try {
@@ -92,13 +99,16 @@ async function signUpPendingVerification<TUser extends AuthUser>(
92
99
  ctx: RequestContext,
93
100
  input: { email: string, password: string, name: string | undefined, redirectTarget: string },
94
101
  ): Promise<Response> {
95
- const { store, sessions, messages, hasMailTransport, mailedLinkOrigin, createUser, issueLink } = deps
102
+ const { limits, store, sessions, messages, hasMailTransport, mailedLinkOrigin, createUser, issueLink } = deps
96
103
  const { email, password, name, redirectTarget } = input
97
104
  const linkOrigin = mailedLinkOrigin(ctx.url)
98
105
  if (hasMailTransport && linkOrigin === undefined) {
99
106
  console.error(`[prunelle/auth] refusing to mail a verification link for host ${ctx.url.host}: set the auth \`site\` option to the public origin`)
100
107
  return fail(ctx, 500, 'Verification links are not configured')
101
108
  }
109
+ const limited = limits.limitMail(ctx, email)
110
+ if (limited)
111
+ return limited
102
112
 
103
113
  const existing = await sessions.observeAsync(store.getUserByEmail(email))
104
114
  if (existing) {
@@ -124,13 +134,19 @@ async function signUpPendingVerification<TUser extends AuthUser>(
124
134
  throw err
125
135
  }
126
136
 
137
+ const deleteIfUnchanged = async (): Promise<void> => {
138
+ const cur = await sessions.observeAsync(store.getUserById(user.id))
139
+ if (!cur || cur.emailVerified || cur.updatedAt !== user.updatedAt)
140
+ return
141
+ await sessions.observeAsync(store.deleteUser(user.id))
142
+ }
127
143
  try {
128
144
  // A mail outage deletes the account once the send fails, so it does not lock the address out.
129
- await issueLink('verify-email', user.id, user.email, linkOrigin, redirectTarget, { onFailure: async () => { await sessions.observeAsync(store.deleteUser(user.id)) } })
145
+ await issueLink('verify-email', user.id, user.email, linkOrigin, redirectTarget, { onFailure: deleteIfUnchanged })
130
146
  }
131
147
  catch {
132
148
  try {
133
- await sessions.observeAsync(store.deleteUser(user.id))
149
+ await deleteIfUnchanged()
134
150
  }
135
151
  catch {
136
152
  // Best-effort rollback so a store outage does not permanently lock out the email address.
@@ -185,6 +201,10 @@ export function registerAuthRoutes<TUser extends AuthUser = AuthUser>(deps: Auth
185
201
  if (!userRecord)
186
202
  return fail(ctx, 400, invalid)
187
203
 
204
+ const twoFactorMethods = await totp.getTwoFactorMethods(userRecord.id)
205
+ if (twoFactorMethods.length > 0)
206
+ return respondTwoFactorChallenge(totp, ctx, userRecord.id, redirectTarget, twoFactorRedirect, twoFactorMethods)
207
+
188
208
  const pub = toPublicUser(userRecord)
189
209
  await sessions.createSessionForUser(userRecord.id, ctx, pub)
190
210
  if (wantsJson(ctx.request))
@@ -201,7 +221,7 @@ export function registerAuthRoutes<TUser extends AuthUser = AuthUser>(deps: Auth
201
221
  })
202
222
  })
203
223
 
204
- authRoute('POST', '/signup', { limit: 'signup', mailLimit: 'signup', readBody: true }, async (ctx, body) => {
224
+ authRoute('POST', '/signup', { limit: 'signup', readBody: true }, async (ctx, body) => {
205
225
  const email = normalizeEmail(body.email ?? '')
206
226
  const password = body.password ?? ''
207
227
  const name = body.name?.trim() || undefined
@@ -262,13 +282,8 @@ export function registerAuthRoutes<TUser extends AuthUser = AuthUser>(deps: Auth
262
282
  return respondAuthError(ctx, 403, messages['signin.email-not-verified'])
263
283
 
264
284
  const twoFactorMethods = await totp.getTwoFactorMethods(userRecord.id)
265
- if (twoFactorMethods.length > 0) {
266
- totp.issuePendingCookie(ctx, userRecord.id, redirectTarget, twoFactorMethods)
267
- if (wantsJson(ctx.request))
268
- return ctx.json({ ok: true, twoFactorRequired: true, methods: twoFactorMethods, userId: userRecord.id }, { status: 200 })
269
- const sep = twoFactorRedirect.includes('?') ? '&' : '?'
270
- return ctx.redirect(`${twoFactorRedirect}${sep}next=${encodeURIComponent(redirectTarget)}`, 303)
271
- }
285
+ if (twoFactorMethods.length > 0)
286
+ return respondTwoFactorChallenge(totp, ctx, userRecord.id, redirectTarget, twoFactorRedirect, twoFactorMethods)
272
287
 
273
288
  const pub = toPublicUser(userRecord)
274
289
  await sessions.createSessionForUser(userRecord.id, ctx, pub)
@@ -286,7 +301,7 @@ export function registerAuthRoutes<TUser extends AuthUser = AuthUser>(deps: Auth
286
301
  return ctx.redirect(safeRedirect(ctx.url.searchParams.get('redirect'), defaultRedirect), 303)
287
302
  })
288
303
 
289
- authRoute('POST', '/magic-link', { limit: 'magic', mailLimit: 'magic', readBody: true }, async (ctx, body) => {
304
+ authRoute('POST', '/magic-link', { limit: 'magic', readBody: true }, async (ctx, body) => {
290
305
  const email = normalizeEmail(body.email ?? '')
291
306
  if (!isValidEmail(email))
292
307
  return fail(ctx, 400, 'Please enter a valid email address')
@@ -296,6 +311,9 @@ export function registerAuthRoutes<TUser extends AuthUser = AuthUser>(deps: Auth
296
311
  console.error(`[prunelle/auth] refusing to mail a sign-in link for host ${ctx.url.host}: set the auth \`site\` option to the public origin`)
297
312
  return fail(ctx, 500, 'Sign-in links are not configured')
298
313
  }
314
+ const limited = limits.limitMail(ctx, email)
315
+ if (limited)
316
+ return limited
299
317
  await sendMagicLink(email, linkOrigin, body.redirect ?? body.next)
300
318
  return ctx.json({ ok: true, message: 'If that address can sign in, a link has been sent.' })
301
319
  })
@@ -1,32 +1,38 @@
1
- // The session cookie's name and lifetime: `__Host-` prefixed over https, with a session still under the plain name read once and moved.
1
+ // The session cookie's name and lifetime: `__Host-` prefixed over https, with opt-in migration from the plain name.
2
2
 
3
3
  import type { RequestContext } from 'prunelle/server'
4
4
  import { authCookie } from './http'
5
5
 
6
6
  const HOST_PREFIX = '__Host-'
7
+ const SECURE_PREFIX = '__Secure-'
7
8
 
8
9
  export interface SessionCookie {
9
- /** The session token the request carries, under the https name or else the plain one. */
10
+ /** The session token the request carries, under the https name (or plain name when `acceptLegacyCookie` is enabled). */
10
11
  read: (ctx: RequestContext) => string | undefined
11
- /** Sets the cookie to expire with the session, and drops the plain name when the https one is used. */
12
+ /** Sets the cookie to expire with the session, and drops the plain name when migrating a legacy cookie. */
12
13
  set: (ctx: RequestContext, rawToken: string, expiresAt: number) => void
13
14
  /** Sets the cookie under its https name when the request carried the plain one. */
14
15
  moveLegacy: (ctx: RequestContext, rawToken: string, expiresAt: number) => void
15
16
  clear: (ctx: RequestContext) => void
16
17
  }
17
18
 
18
- export function createSessionCookie(cookieName: string, isSecureCookie: (ctx: RequestContext) => boolean): SessionCookie {
19
+ export function createSessionCookie(
20
+ cookieName: string,
21
+ isSecureCookie: (ctx: RequestContext) => boolean,
22
+ acceptLegacyCookie = false,
23
+ ): SessionCookie {
19
24
  // Contexts whose session came in under the plain name over https.
20
25
  const legacy = new WeakSet<object>()
21
26
  // A name that starts with `__` carries its own prefix rules and is used as given.
22
27
  const hostName = cookieName.startsWith('__') ? undefined : `${HOST_PREFIX}${cookieName}`
28
+ const requiresSecure = cookieName.startsWith(HOST_PREFIX) || cookieName.startsWith(SECURE_PREFIX)
23
29
  const currentName = (ctx: RequestContext): string => hostName !== undefined && isSecureCookie(ctx) ? hostName : cookieName
24
30
 
25
31
  const set: SessionCookie['set'] = (ctx, rawToken, expiresAt) => {
26
32
  const name = currentName(ctx)
27
- ctx.cookies.set(name, rawToken, authCookie(isSecureCookie(ctx), Math.max(0, Math.floor((expiresAt - Date.now()) / 1000))))
33
+ ctx.cookies.set(name, rawToken, authCookie(requiresSecure || isSecureCookie(ctx), Math.max(0, Math.floor((expiresAt - Date.now()) / 1000))))
28
34
  legacy.delete(ctx.locals)
29
- if (name !== cookieName)
35
+ if (name !== cookieName && acceptLegacyCookie)
30
36
  ctx.cookies.delete(cookieName, { path: '/' })
31
37
  }
32
38
 
@@ -34,7 +40,7 @@ export function createSessionCookie(cookieName: string, isSecureCookie: (ctx: Re
34
40
  read(ctx) {
35
41
  const name = currentName(ctx)
36
42
  const token = ctx.cookies.get(name)
37
- if (token !== undefined || name === cookieName)
43
+ if (token !== undefined || name === cookieName || !acceptLegacyCookie)
38
44
  return token
39
45
  const old = ctx.cookies.get(cookieName)
40
46
  if (old)
@@ -47,7 +53,8 @@ export function createSessionCookie(cookieName: string, isSecureCookie: (ctx: Re
47
53
  set(ctx, rawToken, expiresAt)
48
54
  },
49
55
  clear(ctx) {
50
- ctx.cookies.delete(cookieName, { path: '/' })
56
+ if (hostName === undefined || !isSecureCookie(ctx) || acceptLegacyCookie)
57
+ ctx.cookies.delete(cookieName, requiresSecure ? { path: '/', secure: true } : { path: '/' })
51
58
  if (hostName !== undefined && isSecureCookie(ctx))
52
59
  ctx.cookies.delete(hostName, { path: '/', secure: true })
53
60
  },
package/src/session.ts CHANGED
@@ -96,6 +96,7 @@ export function hasAsyncStoreMethods<TUser extends AuthUser>(store: AuthStore<TU
96
96
  export interface SessionManagerDeps<TUser extends AuthUser = AuthUser> {
97
97
  store: AuthStore<TUser>
98
98
  cookieName: string
99
+ acceptLegacyCookie?: boolean | undefined
99
100
  sessionTtlMs: number
100
101
  /** A session older than this is refused however recently it was used; `undefined` lets renewal go on forever. */
101
102
  absoluteTtlMs: number | undefined
@@ -121,7 +122,7 @@ export interface SessionManager<TUser extends AuthUser = AuthUser> {
121
122
  }
122
123
 
123
124
  export function createSessionManager<TUser extends AuthUser = AuthUser>(deps: SessionManagerDeps<TUser>): SessionManager<TUser> {
124
- const { store, cookieName, sessionTtlMs, absoluteTtlMs, renewalIntervalMs, storeIp, storeUserAgent, getTrustProxy, isSecureCookie } = deps
125
+ const { store, cookieName, acceptLegacyCookie, sessionTtlMs, absoluteTtlMs, renewalIntervalMs, storeIp, storeUserAgent, getTrustProxy, isSecureCookie } = deps
125
126
 
126
127
  let storeMode: 'unknown' | 'sync' | 'async' = isKnownSyncStore(store)
127
128
  ? 'sync'
@@ -130,7 +131,7 @@ export function createSessionManager<TUser extends AuthUser = AuthUser>(deps: Se
130
131
  const resolvedUsers = new WeakMap<object, PublicUser<TUser>>()
131
132
  const pendingContexts = new WeakMap<object, Promise<{ user: PublicUser<TUser>, session: AuthSession } | undefined>>()
132
133
  const renewedAt = new Map<string, number>()
133
- const sessionCookie = createSessionCookie(cookieName, isSecureCookie)
134
+ const sessionCookie = createSessionCookie(cookieName, isSecureCookie, acceptLegacyCookie === true)
134
135
  const { read: readToken, clear: clearCookies } = sessionCookie
135
136
 
136
137
  // This request has no session (any more): its locals stay empty, and the cookie goes when it was refused.
package/src/sqlite-ext.ts CHANGED
@@ -223,6 +223,7 @@ function createExtSchema(db: Database): void {
223
223
  interface ExtQueries {
224
224
  getTotp: Statement<TotpRow, [string]>
225
225
  upsertTotp: Statement<null, [string, string, number, number | null, number, number]>
226
+ advanceTotpStep: Statement<{ user_id: string }, [number, number, string, number]>
226
227
  delTotp: Statement<null, [string]>
227
228
  listRecovery: Statement<RecoveryRow, [string]>
228
229
  insertRecovery: Statement<null, [string, string, string, string, number]>
@@ -259,6 +260,7 @@ function prepareExtQueries(db: Database): ExtQueries {
259
260
  return {
260
261
  getTotp: db.query('SELECT * FROM prunelle_auth_totp WHERE user_id = ?'),
261
262
  upsertTotp: db.query('INSERT OR REPLACE INTO prunelle_auth_totp (user_id, encrypted_secret, enabled, last_used_step, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)'),
263
+ advanceTotpStep: db.query('UPDATE prunelle_auth_totp SET last_used_step = ?, updated_at = ? WHERE user_id = ? AND enabled = 1 AND (last_used_step IS NULL OR last_used_step < ?) RETURNING user_id'),
262
264
  delTotp: db.query('DELETE FROM prunelle_auth_totp WHERE user_id = ?'),
263
265
  listRecovery: db.query('SELECT * FROM prunelle_auth_recovery_codes WHERE user_id = ? ORDER BY created_at ASC'),
264
266
  insertRecovery: db.query('INSERT INTO prunelle_auth_recovery_codes (id, user_id, code_hash, salt, created_at) VALUES (?, ?, ?, ?, ?)'),
@@ -306,7 +308,7 @@ function hasExistingExtTable(db: Database): boolean {
306
308
 
307
309
  function buildTotpAndPasskeyMethods(db: Database, ensure: () => ExtQueries): Pick<
308
310
  Required<AuthStoreExt>,
309
- 'getTotp' | 'setTotp' | 'deleteTotp' | 'listRecoveryCodes' | 'setRecoveryCodes' | 'consumeRecoveryCode' | 'deleteRecoveryCodes' | 'getPasskey' | 'listPasskeys' | 'createPasskey' | 'updatePasskeyUsage' | 'deletePasskey' | 'deleteUserPasskeys'
311
+ 'getTotp' | 'setTotp' | 'advanceTotpStep' | 'deleteTotp' | 'listRecoveryCodes' | 'setRecoveryCodes' | 'consumeRecoveryCode' | 'deleteRecoveryCodes' | 'getPasskey' | 'listPasskeys' | 'createPasskey' | 'updatePasskeyUsage' | 'deletePasskey' | 'deleteUserPasskeys'
310
312
  > {
311
313
  return {
312
314
  getTotp(userId) {
@@ -315,6 +317,9 @@ function buildTotpAndPasskeyMethods(db: Database, ensure: () => ExtQueries): Pic
315
317
  setTotp(record) {
316
318
  ensure().upsertTotp.run(record.userId, record.encryptedSecret, record.enabled ? 1 : 0, record.lastUsedStep ?? null, record.createdAt, record.updatedAt)
317
319
  },
320
+ advanceTotpStep(userId, step, updatedAt) {
321
+ return ensure().advanceTotpStep.get(step, updatedAt, userId, step) !== null
322
+ },
318
323
  deleteTotp(userId) {
319
324
  ensure().delTotp.run(userId)
320
325
  },
package/src/sqlite.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  // Works out-of-the-box in single-binary `prunelle build --compile` deployments.
3
3
 
4
4
  import type { AuthSession, AuthStore, AuthUser, OAuthAccount, TokenKind, UserExport, VerificationToken } from './store'
5
- import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
5
+ import { mkdirSync, writeFileSync } from 'node:fs'
6
6
  import { dirname, isAbsolute, resolve } from 'node:path'
7
7
  import { Database } from 'bun:sqlite'
8
8
  import { getAppContext } from 'prunelle/internal/server'
@@ -246,14 +246,22 @@ function appPath(path: string): string {
246
246
  return resolve(getAppContext()?.root ?? process.cwd(), path)
247
247
  }
248
248
 
249
+ // SQLite gives the -wal and -shm files the mode of the main file: accounts, hashes and sessions are for the server's user alone.
250
+ function ensurePrivateDbFile(dbPath: string): void {
251
+ mkdirSync(dirname(dbPath), { recursive: true })
252
+ try {
253
+ writeFileSync(dbPath, '', { mode: 0o600, flag: 'wx' })
254
+ }
255
+ catch (err) {
256
+ if ((err as NodeJS.ErrnoException).code !== 'EEXIST')
257
+ throw err
258
+ }
259
+ }
260
+
249
261
  function openSqliteAuthStore(dbOrPath: string | Database): SqliteAuthStore {
250
262
  const ownsDb = typeof dbOrPath === 'string'
251
- if (ownsDb && dbOrPath !== ':memory:' && !dbOrPath.startsWith('file:')) {
252
- mkdirSync(dirname(dbOrPath), { recursive: true })
253
- // SQLite gives the -wal and -shm files the mode of the main file: accounts, hashes and sessions are for the server's user alone.
254
- if (!existsSync(dbOrPath))
255
- writeFileSync(dbOrPath, '', { mode: 0o600 })
256
- }
263
+ if (ownsDb && dbOrPath !== ':memory:' && !dbOrPath.startsWith('file:'))
264
+ ensurePrivateDbFile(dbOrPath)
257
265
  const db = ownsDb ? new Database(dbOrPath, { create: true }) : dbOrPath
258
266
  let closed = false
259
267
 
package/src/store-ext.ts CHANGED
@@ -86,6 +86,7 @@ export interface UserExportExt {
86
86
  export interface AuthStoreExt {
87
87
  getTotp?(userId: string): TotpRecord | undefined | Promise<TotpRecord | undefined>
88
88
  setTotp?(record: TotpRecord): void | Promise<void>
89
+ advanceTotpStep?(userId: string, step: number, updatedAt: number): boolean | Promise<boolean>
89
90
  deleteTotp?(userId: string): void | Promise<void>
90
91
  listRecoveryCodes?(userId: string): RecoveryCodeRecord[] | Promise<RecoveryCodeRecord[]>
91
92
  setRecoveryCodes?(userId: string, codes: RecoveryCodeRecord[]): void | Promise<void>
@@ -158,6 +159,14 @@ function buildMemoryTotpPasskeyMethods(state: MemoryExtState) {
158
159
  setTotp(record: TotpRecord): void {
159
160
  state.totp.set(record.userId, { ...record })
160
161
  },
162
+ advanceTotpStep(userId: string, step: number, updatedAt: number): boolean {
163
+ const rec = state.totp.get(userId)
164
+ if (!rec || !rec.enabled || (rec.lastUsedStep !== undefined && rec.lastUsedStep >= step))
165
+ return false
166
+ rec.lastUsedStep = step
167
+ rec.updatedAt = updatedAt
168
+ return true
169
+ },
161
170
  deleteTotp(userId: string): void {
162
171
  state.totp.delete(userId)
163
172
  },
package/src/totp.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  import type { RequestContext } from 'prunelle/server'
5
5
  import type { SessionManager } from './session'
6
6
  import type { AuthStore, AuthUser, RecoveryCodeRecord } from './store'
7
- import { safeEqual } from 'prunelle/server'
7
+ import { safeEqual, wantsJson } from 'prunelle/server'
8
8
  import { decryptSecret, encryptSecret, randomToken, sha256Hex, signPayload, verifyPayload } from './crypto'
9
9
  import { authCookie } from './http'
10
10
 
@@ -176,8 +176,77 @@ function requireTotpStore<TUser extends AuthUser>(store: AuthStore<TUser>) {
176
176
  }
177
177
  }
178
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
+
179
247
  export function createTotpManager<TUser extends AuthUser = AuthUser>(deps: TotpManagerDeps<TUser>): TotpManager {
180
248
  const { store, sessions, secret, twoFactorCookieName, getDefaultIssuer, isSecureCookie } = deps
249
+ const withUserLock = createKeyedLock()
181
250
 
182
251
  async function tryConsumeRecoveryCode(userId: string, rawCode: string): Promise<boolean> {
183
252
  const ts = requireTotpStore(store)
@@ -196,6 +265,22 @@ export function createTotpManager<TUser extends AuthUser = AuthUser>(deps: TotpM
196
265
  return false
197
266
  }
198
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
+
199
284
  async function verifyTotp(userId: string, code: string): Promise<{ valid: boolean, method?: 'totp' | 'recovery' | undefined }> {
200
285
  const ts = requireTotpStore(store)
201
286
  const record = await sessions.observeAsync(ts.getTotp(userId))
@@ -205,12 +290,8 @@ export function createTotpManager<TUser extends AuthUser = AuthUser>(deps: TotpM
205
290
  const plainSecret = await decryptSecret(secret(), record.encryptedSecret)
206
291
  const matchedStep = matchTotpStep(plainSecret, code, Date.now(), record.lastUsedStep)
207
292
  if (matchedStep !== undefined) {
208
- await sessions.observeAsync(ts.setTotp({
209
- ...record,
210
- lastUsedStep: matchedStep,
211
- updatedAt: Date.now(),
212
- }))
213
- return { valid: true, method: 'totp' }
293
+ const claimed = await claimTotpStep(userId, record.encryptedSecret, matchedStep)
294
+ return claimed ? { valid: true, method: 'totp' } : { valid: false }
214
295
  }
215
296
 
216
297
  if (await tryConsumeRecoveryCode(userId, code))
@@ -277,8 +358,10 @@ export function createTotpManager<TUser extends AuthUser = AuthUser>(deps: TotpM
277
358
  const result = await verifyTotp(userId, code)
278
359
  if (!result.valid)
279
360
  return false
280
- await sessions.observeAsync(ts.deleteTotp(userId))
281
- await sessions.observeAsync(ts.deleteRecoveryCodes(userId))
361
+ await withUserLock(userId, async () => {
362
+ await sessions.observeAsync(ts.deleteTotp(userId))
363
+ await sessions.observeAsync(ts.deleteRecoveryCodes(userId))
364
+ })
282
365
  return true
283
366
  },
284
367
 
@@ -307,28 +390,6 @@ export function createTotpManager<TUser extends AuthUser = AuthUser>(deps: TotpM
307
390
  return methods
308
391
  },
309
392
 
310
- issuePendingCookie(ctx, userId, redirect, methods) {
311
- const payload: PendingTwoFactor = {
312
- userId,
313
- redirect,
314
- methods,
315
- exp: Date.now() + PENDING_2FA_TTL_MS,
316
- }
317
- ctx.cookies.set(twoFactorCookieName, signPayload(secret(), payload), authCookie(isSecureCookie(ctx), Math.floor(PENDING_2FA_TTL_MS / 1000)))
318
- },
319
-
320
- readPendingCookie(ctx) {
321
- const raw = ctx.cookies.get(twoFactorCookieName)
322
- if (!raw)
323
- return undefined
324
- const parsed = verifyPayload<PendingTwoFactor>(secret(), raw)
325
- if (!parsed || parsed.exp <= Date.now() || !parsed.userId)
326
- return undefined
327
- return parsed
328
- },
329
-
330
- clearPendingCookie(ctx) {
331
- ctx.cookies.delete(twoFactorCookieName, { path: '/' })
332
- },
393
+ ...createPendingCookieHelpers(secret, twoFactorCookieName, isSecureCookie),
333
394
  }
334
395
  }