@prunellejs/auth 0.7.3 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/llms.txt CHANGED
@@ -27,9 +27,9 @@
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). 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.
30
+ - `passkeys`: `{ rpId?, rpName?, origin?, userVerification? }` (WebAuthn L2 ES256 / RS256 / EdDSA, zero npm deps; registration refuses an off-curve EC point, an RSA key under 2048 bits, repeated CBOR keys and trailing bytes). 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
- - `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).
32
+ - `rateLimit`: `{ max?, windowMs?, mailsPerAddress?, failuresPerAccount?, twoFactorFailuresPerAccount? } | 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. `twoFactorFailuresPerAccount`: wrong TOTP codes, recovery codes and passkey assertions per hour on one account (default 10), past which `/totp/verify` and `/passkeys/2fa/verify` answer `429` and drop the pending 2FA cookie. `pruneIntervalMs`: default 15 min (`false` disables).
33
33
  - RGPD minimization: `storeIp`: `'truncate'` (default, /24 IPv4 and /48 IPv6) | `true` | `false`; `storeUserAgent`: `true` (default) | `false`.
34
34
  - `defaultUserFields`: extra columns/fields merged on user creation when extending `AuthUser`.
35
35
 
@@ -44,9 +44,11 @@
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.
46
46
  - `POST /auth/totp/disable` (authenticated, `code` = TOTP or recovery code) → disables TOTP and deletes recovery codes.
47
+ - `POST /auth/totp/recovery-codes` (authenticated, TOTP enabled) → 10 new recovery codes, the earlier ones no longer working.
48
+ - Setup, confirm, disable and recovery codes, like passkey registration and deletion, need a sign-in from the last 10 minutes (`FRESH_SIGNIN_MS`), else `403` `{ code: 'reauth-required' }`; adding or removing a factor signs out the user's other sessions and renews this one's cookie.
47
49
  - Passkeys (WebAuthn L2, passwordless sign-in & 2FA):
48
50
  - `POST /auth/passkeys/register/options` & `POST /auth/passkeys/register/verify` (authenticated).
49
- - `POST /auth/passkeys/login/options` & `POST /auth/passkeys/login/verify` (public, discoverable or with optional `email` hint).
51
+ - `POST /auth/passkeys/login/options` & `POST /auth/passkeys/login/verify` (public, discoverable or with optional `email` hint; an email with no passkey, or unknown, gets a decoy credential id stable per email, so the answer never tells whether the account exists or has passkeys).
50
52
  - `POST /auth/passkeys/2fa/options` & `POST /auth/passkeys/2fa/verify` (pending 2FA cookie; completes 2FA when user has registered passkeys).
51
53
  - `GET /auth/passkeys` & `POST /auth/passkeys/delete` (authenticated, own passkeys only).
52
54
  - Organizations (HTML form POST or JSON):
@@ -59,11 +61,11 @@
59
61
 
60
62
  ## Handle Methods (`auth`)
61
63
 
62
- - Guards & sessions: `auth.guard({ redirectTo?, org?, role?, allow? })` (when `org` is `true`, reads `ctx.params.org ?? ctx.params.orgId ?? ctx.params.slug`; when a string, reads `ctx.params[org]` or looks up that slug/id; when a function, calls `await org(ctx)`; checks `role` against the member's org role and populates `ctx.locals.org` & `ctx.locals.orgMembership`). `auth.getUser(ctx)`, `auth.getSession(ctx)`, `auth.formMessage(url)`, `auth.resolve(ctx)`, `auth.createUser(input)`, `auth.createSessionForUser(userId, ctx)`, `auth.signOut(ctx)`, `auth.revokeAllSessions(userId)`, `auth.sendMagicLink(email, origin, redirectTo?)`, `auth.sendVerificationEmail(email, origin, redirectTo?)`.
64
+ - Guards & sessions: `auth.guard({ redirectTo?, org?, role?, allow? })` (when `org` is `true`, reads `ctx.params.org ?? ctx.params.orgId ?? ctx.params.slug`; when a string, reads `ctx.params[org]` and answers `403` on a route without that param (a fixed org goes through a function); when a function, calls `await org(ctx)`; checks `role` against the member's org role, `owner` outranking `admin` outranking `member` and a custom role matching only itself, and populates `ctx.locals.org` & `ctx.locals.orgMembership`). `auth.getUser(ctx)`, `auth.getSession(ctx)`, `auth.formMessage(url)`, `auth.resolve(ctx)`, `auth.createUser(input)`, `auth.createSessionForUser(userId, ctx)`, `auth.signOut(ctx)`, `auth.revokeAllSessions(userId)`, `auth.sendMagicLink(email, origin, redirectTo?)`, `auth.sendVerificationEmail(email, origin, redirectTo?)`.
63
65
  - TOTP: `auth.setupTotp(userId, opts?)`, `auth.confirmTotp(userId, code)`, `auth.verifyTotp(userId, code)`, `auth.disableTotp(userId, code)`, `auth.regenerateRecoveryCodes(userId)`.
64
66
  - Passkeys: `auth.listPasskeys(userId)`, `auth.deletePasskey(userId, credentialId)`.
65
67
  - Organizations: `auth.createOrg(ownerUserId, { name, slug? })`, `auth.getOrg(idOrSlug)`, `auth.listUserOrgs(userId)`, `auth.listOrgMembers(orgId)`, `auth.addOrgMember(orgId, userId, role?)`, `auth.updateOrgMemberRole(orgId, userId, role)`, `auth.removeOrgMember(orgId, userId)`, `auth.inviteToOrg(orgId, { email, role?, invitedBy, origin?, redirectTo? })`, `auth.acceptOrgInvite(token, userId)`, `auth.revokeOrgInvite(orgId, inviteId)`, `auth.deleteOrg(orgId)`.
66
- - RGPD & maintenance: `auth.listSessions(userId)`, `auth.exportUser(userId)` (includes `user`, `sessions`, `oauthAccounts`, `totp` status/remaining recovery count without secrets, `passkeys` metadata, `organizations`, pending `invitations`, `pendingTokens` (kind and expiry of unexpired mailed links), and `app` from `onExportUser`), `auth.deleteUser(userId)` (runs `onDeleteUser` first, a throw keeping the account; cascades sessions, OAuth links, tokens, TOTP, recovery codes, passkeys, org memberships, and pending invitations), `auth.pruneExpired()` (expired sessions and tokens, and accounts left unverified past `unverifiedTtlSeconds`), `auth.dispose()`. A custom store implements `pruneExpired({ unverifiedCreatedBefore })`, deleting unverified users created before that timestamp like `deleteUser`.
68
+ - RGPD & maintenance: `auth.listSessions(userId)`, `auth.exportUser(userId)` (includes `user`, `sessions`, `oauthAccounts`, `totp` status/remaining recovery count without secrets, `passkeys` metadata, `organizations`, pending `invitations` to their email, `sentInvitations` (no invitee email), `pendingTokens` (kind and expiry of unexpired mailed links), and `app` from `onExportUser`), `auth.deleteUser(userId)` (runs `onDeleteUser` first, a throw keeping the account; cascades sessions, OAuth links, tokens, TOTP, recovery codes, passkeys, org memberships, and pending invitations), `auth.pruneExpired()` (expired sessions and tokens, and accounts left unverified past `unverifiedTtlSeconds`), `auth.dispose()`. A custom store implements `pruneExpired({ unverifiedCreatedBefore })`, deleting unverified users created before that timestamp like `deleteUser`. A custom store should also implement the atomic `updateUserIfUnverified(id, updatedAt, patch)`, `deleteUserIfUnverified(id, updatedAt)`, `advanceTotpStep(userId, step, updatedAt)` (with TOTP), `updateOrgMemberRoleIfNotLastOwner(orgId, userId, role)` and `removeOrgMemberIfNotLastOwner(orgId, userId)` (with orgs), each one transaction; without them prunelle checks then writes under an in-process lock and `prunelle check` warns `[auth/store-not-atomic]`.
67
69
 
68
70
  ## Snippets
69
71
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prunellejs/auth",
3
- "version": "0.7.3",
3
+ "version": "0.8.0",
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.3"
27
+ "prunelle": "^0.8.0"
28
28
  }
29
29
  }
package/src/account.ts CHANGED
@@ -5,7 +5,7 @@ import type { SessionManager } from './session'
5
5
  import type { AuthSession, AuthStore, AuthUser, PublicUser, UserExport } from './store'
6
6
  import { safeRedirect, wantsJson } from 'prunelle/server'
7
7
  import { fail, formPagePath } from './http'
8
- import { orgsDeletedWithUser } from './orgs'
8
+ import { leaveOrgsForDeletion } from './orgs'
9
9
  import { toPublicUser } from './store'
10
10
 
11
11
  /** How recent a sign-in must be to export or delete the account it opened. */
@@ -37,8 +37,14 @@ export function createAccountService<TUser extends AuthUser>(
37
37
  const user = await sessions.observeAsync(store.getUserById(userId))
38
38
  if (!user)
39
39
  return
40
- const orgIds = await orgsDeletedWithUser(store, userId)
41
- await hooks.onDeleteUser?.(toPublicUser(user))
40
+ const { deleted: orgIds, undo } = await leaveOrgsForDeletion(store, sessions, userId)
41
+ try {
42
+ await hooks.onDeleteUser?.(toPublicUser(user))
43
+ }
44
+ catch (err) {
45
+ await undo()
46
+ throw err
47
+ }
42
48
  for (const orgId of orgIds)
43
49
  await store.deleteOrg?.(orgId)
44
50
  await sessions.observeAsync(store.deleteUser(userId))
@@ -53,7 +59,7 @@ interface AccountRoutesDeps<TUser extends AuthUser> {
53
59
  clearPendingCookie: (ctx: RequestContext) => void
54
60
  }
55
61
 
56
- export const REAUTH_REQUIRED = 'Sign in again to confirm it is you: exporting or deleting an account needs a sign-in from the last 10 minutes'
62
+ export const REAUTH_REQUIRED = 'Sign in again to confirm it is you: exporting or deleting an account, or changing how you sign in, needs a sign-in from the last 10 minutes'
57
63
 
58
64
  // A form or a link from a page goes back to it with the refusal's code, which `auth.formMessage(url)` reads; a JSON caller gets `json`.
59
65
  function refuse(ctx: RequestContext, code: 'account.reauth-required' | 'account.last-owner', json: () => Response): Response {
@@ -61,7 +67,8 @@ function refuse(ctx: RequestContext, code: 'account.reauth-required' | 'account.
61
67
  return back === undefined ? json() : ctx.redirect(back, 303)
62
68
  }
63
69
 
64
- async function freshSignin<TUser extends AuthUser>(ctx: RequestContext, sessions: SessionManager<TUser>): Promise<{ user: PublicUser<TUser>, session: AuthSession } | Response> {
70
+ /** The signed-in user when the session opened in the last `FRESH_SIGNIN_MS`; else the refusal, `401` signed out and `403` `reauth-required` on a stale session. */
71
+ export async function freshSignin<TUser extends AuthUser>(ctx: RequestContext, sessions: SessionManager<TUser>): Promise<{ user: PublicUser<TUser>, session: AuthSession } | Response> {
65
72
  const resolved = await sessions.resolve(ctx)
66
73
  if (!resolved)
67
74
  return fail(ctx, 401, 'Authentication required')
@@ -70,6 +77,12 @@ async function freshSignin<TUser extends AuthUser>(ctx: RequestContext, sessions
70
77
  return resolved
71
78
  }
72
79
 
80
+ /** After a sign-in factor is added or removed: every other session of the user ends, as one may be the attacker's, and this one carries on under a new cookie. */
81
+ export async function keepOnlyThisSession<TUser extends AuthUser>(ctx: RequestContext, sessions: SessionManager<TUser>, store: AuthStore<TUser>, userId: string): Promise<void> {
82
+ await sessions.observeAsync(store.deleteUserSessions(userId))
83
+ await sessions.createSessionForUser(userId, ctx)
84
+ }
85
+
73
86
  export function registerAccountRoutes<TUser extends AuthUser>({ authRoute, sessions, account, clearPendingCookie }: AccountRoutesDeps<TUser>): void {
74
87
  authRoute('GET', '/me/export', { limit: 'account-export' }, async (ctx) => {
75
88
  const resolved = await freshSignin(ctx, sessions)
package/src/crypto.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  // Zero-dependency Bun-native crypto helpers for @prunellejs/auth.
2
2
  // Uses crypto.getRandomValues, Bun.CryptoHasher (SHA-256 / HMAC-SHA256), and Bun.password (Argon2id).
3
3
 
4
- import { safeEqual } from 'prunelle/server'
4
+ import { signPayload, verifyPayload } from 'prunelle/server'
5
5
 
6
6
  export function toBase64Url(bytes: Uint8Array): string {
7
7
  return Buffer.from(bytes).toString('base64url')
@@ -83,20 +83,18 @@ export function pkceChallenge(verifier: string): string {
83
83
  }
84
84
 
85
85
 
86
- export function signPayload(secret: string, payload: unknown): string {
87
- const encoded = Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url')
88
- const mac = new Bun.CryptoHasher('sha256', secret).update(encoded).digest().toString('base64url')
89
- return `${encoded}.${mac}`
86
+ /** What a signed auth cookie is for: its MAC covers it, so a cookie of one kind never verifies as another. */
87
+ export type SignedPurpose = 'oauth' | '2fa' | 'webauthn'
88
+
89
+ /** `payload` as base64url JSON, signed by prunelle's `signPayload` under the auth secret for `purpose`, so it fits a cookie. */
90
+ export function signJson(secret: string, purpose: SignedPurpose, payload: unknown): string {
91
+ return signPayload(`auth-${purpose}`, Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url'), secret)
90
92
  }
91
93
 
92
- export function verifyPayload<T>(secret: string, token: string): T | undefined {
93
- const dot = token.indexOf('.')
94
- if (dot <= 0)
95
- return undefined
96
- const encoded = token.slice(0, dot)
97
- const providedMac = token.slice(dot + 1)
98
- const expectedMac = new Bun.CryptoHasher('sha256', secret).update(encoded).digest().toString('base64url')
99
- if (!safeEqual(providedMac, expectedMac))
94
+ /** The value a `signJson` token for `purpose` carries, or undefined when its signature does not match. */
95
+ export function verifyJson<T>(secret: string, purpose: SignedPurpose, token: string): T | undefined {
96
+ const encoded = verifyPayload(`auth-${purpose}`, token, secret)
97
+ if (encoded === undefined)
100
98
  return undefined
101
99
  try {
102
100
  return JSON.parse(Buffer.from(encoded, 'base64url').toString('utf8')) as T
package/src/http.ts CHANGED
@@ -125,8 +125,8 @@ export function createAuthRouteRegistrar(
125
125
  }
126
126
  }
127
127
 
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,;<>]/
128
+ // Control characters (C0, DEL, C1 such as U+0085), whitespace, and the characters that split or wrap an address list.
129
+ const EMAIL_FORBIDDEN_RE = /[\u0000-\u001F\u007F-\u009F\s,;<>]/
130
130
 
131
131
  export function isValidEmail(email: string): boolean {
132
132
  const e = email.trim()
@@ -147,12 +147,17 @@ export interface AuthLimits {
147
147
  refuseLockedAccount: (ctx: RequestContext, email: string) => Response | undefined
148
148
  /** Counts a wrong password against the account. */
149
149
  countFailedSignin: (email: string) => void
150
+ /** The 429 to answer, before a second factor is checked, when this account is past its wrong second-factor attempts across addresses. */
151
+ refuseLockedSecondFactor: (ctx: RequestContext, userId: string) => Response | undefined
152
+ /** Counts a wrong TOTP, recovery code or passkey assertion against the account, answering the 429 once it reaches the limit. */
153
+ countFailedSecondFactor: (ctx: RequestContext, userId: string) => Response | undefined
150
154
  }
151
155
 
152
156
  export interface AuthLimiters {
153
157
  attempts: RateLimiter
154
158
  mails: RateLimiter
155
159
  failures: RateLimiter
160
+ secondFactors: RateLimiter
156
161
  }
157
162
 
158
163
  export function createAuthLimiters(api: ServerPluginAPI, rateLimit: RateLimitOptions | false | undefined): AuthLimiters | undefined {
@@ -162,6 +167,7 @@ export function createAuthLimiters(api: ServerPluginAPI, rateLimit: RateLimitOpt
162
167
  attempts: api.rateLimiter({ max: rateLimit?.max ?? 15, windowMs: rateLimit?.windowMs ?? 60_000 }),
163
168
  mails: api.rateLimiter({ max: rateLimit?.mailsPerAddress ?? 3, windowMs: 600_000 }),
164
169
  failures: api.rateLimiter({ max: rateLimit?.failuresPerAccount ?? 100, windowMs: 3_600_000 }),
170
+ secondFactors: api.rateLimiter({ max: rateLimit?.twoFactorFailuresPerAccount ?? 10, windowMs: 3_600_000 }),
165
171
  }
166
172
  }
167
173
 
@@ -185,6 +191,11 @@ export function authLimits(limiters: AuthLimiters | undefined, getTrustProxy: ()
185
191
  if (email)
186
192
  limiters?.failures.hit(`signin:${email}`)
187
193
  },
194
+ refuseLockedSecondFactor: (ctx, userId) => tooMany(ctx, limiters?.secondFactors.peek(userId) ?? 0),
195
+ countFailedSecondFactor(ctx, userId) {
196
+ limiters?.secondFactors.hit(userId)
197
+ return tooMany(ctx, limiters?.secondFactors.peek(userId) ?? 0)
198
+ },
188
199
  }
189
200
  }
190
201
 
@@ -212,3 +223,12 @@ export function formatSessionIp(ip: string, mode: boolean | 'truncate'): string
212
223
  }
213
224
  return undefined
214
225
  }
226
+
227
+ const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]'])
228
+
229
+ /** The origin a mailed link or a WebAuthn ceremony is bound to: `site`, else the request's own on a loopback host only, as elsewhere its Host header is the client's to choose. */
230
+ export function linkOrigin(site: string | undefined, url: URL): string | undefined {
231
+ if (site !== undefined)
232
+ return site
233
+ return LOOPBACK_HOSTS.has(url.hostname) ? url.origin : undefined
234
+ }
package/src/index.ts CHANGED
@@ -26,7 +26,7 @@ import type { TotpOptions } from './totp'
26
26
  import { definePlugin } from 'prunelle/config'
27
27
  import { isHttpsRequest, nodeEnv } from 'prunelle/server'
28
28
  import { hashPassword, randomToken } from './crypto'
29
- import { authLimits, createAuthLimiters, createAuthRouteRegistrar, isValidEmail } from './http'
29
+ import { authLimits, createAuthLimiters, createAuthRouteRegistrar, isValidEmail, linkOrigin } from './http'
30
30
  import { buildMailDeliverer, createLinkService } from './links'
31
31
  import { registerOAuthRoutes } from './oauth-routes'
32
32
  import { registerOrgRoutes } from './org-routes'
@@ -59,6 +59,8 @@ export interface RateLimitOptions {
59
59
  mailsPerAddress?: number | undefined
60
60
  /** Wrong passwords one account takes across all addresses per hour before sign-in refuses it (default: 100). */
61
61
  failuresPerAccount?: number | undefined
62
+ /** Wrong TOTP codes, recovery codes and passkey assertions one account takes across all addresses per hour before its second-factor step refuses it (default: 10). */
63
+ twoFactorFailuresPerAccount?: number | undefined
62
64
  }
63
65
 
64
66
  export { FRESH_SIGNIN_MS } from './account'
@@ -93,17 +95,10 @@ export type {
93
95
  export { buildOtpauthUrl, generateTotpCode, generateTotpSecret } from './totp'
94
96
  export type { TotpOptions, TwoFactorMethod } from './totp'
95
97
 
96
- const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]'])
97
98
  const DEFAULT_PRUNE_INTERVAL_MS = 15 * 60 * 1000
98
99
  const MIN_PROD_SECRET_BYTES = 32
99
100
  const DEFAULT_MAX_PASSWORD_LENGTH = 1024
100
101
 
101
- // The request URL comes from the Host header, which the client controls: a link mailed to a victim must not point at it.
102
- function linkOrigin(site: string | undefined, url: URL): string | undefined {
103
- if (site !== undefined)
104
- return site
105
- return LOOPBACK_HOSTS.has(url.hostname) ? url.origin : undefined
106
- }
107
102
 
108
103
  // Mailed links and OAuth callbacks start with `site`, so anything but an http(s) origin is a config mistake.
109
104
  function siteOrigin(value: string): string {
@@ -228,12 +223,12 @@ export interface AuthOptions<TUser extends AuthUser = AuthUser> {
228
223
  export interface GuardOptions<TUser extends AuthUser = AuthUser> {
229
224
  /** Redirect unauthenticated HTML requests here (JSON/API requests always receive 401). */
230
225
  redirectTo?: string | undefined
231
- /** Required role(s): checks `orgMembership.role` when `org` is set, otherwise `user.role`. */
226
+ /** Required role(s): checks `orgMembership.role` when `org` is set, where `owner` outranks `admin`, which outranks `member`, and a custom role matches only itself; otherwise `user.role`, matched exactly. */
232
227
  role?: string | string[] | undefined
233
228
  /**
234
229
  * Require organization membership and populate `ctx.locals.org` & `ctx.locals.orgMembership`:
235
230
  * - `true`: reads `ctx.params.org ?? ctx.params.orgId ?? ctx.params.slug`
236
- * - `string`: reads `ctx.params[org]` (or falls back to looking up `org` as a slug/id)
231
+ * - `string`: reads `ctx.params[org]`, answering `403` on a route without that param
237
232
  * - function: calls `await org(ctx)` to resolve the org id or slug
238
233
  */
239
234
  org?: boolean | string | ((ctx: RequestContext) => string | undefined | Promise<string | undefined>) | undefined
@@ -309,6 +304,19 @@ function unverifiedPruneOptions(ttlSeconds: number | false | undefined, requireE
309
304
 
310
305
  const STORE_IN_MEMORY = '`store` keeps accounts and sessions in memory, so a restart signs everyone out and loses every account: pass `store: sqliteAuthStore(\'data/auth.db\')` from `@prunellejs/auth/sqlite`, or your own `AuthStore`.'
311
306
 
307
+ // The store methods that make a check and its write one step; without one, prunelle reads then writes under an in-process lock.
308
+ function warnIfStoreNotAtomic(store: AuthStore<AuthUser>, warn: (message: string) => void): void {
309
+ const methods = [
310
+ 'updateUserIfUnverified',
311
+ 'deleteUserIfUnverified',
312
+ ...(store.setTotp ? ['advanceTotpStep'] as const : []),
313
+ ...(store.createOrg ? ['updateOrgMemberRoleIfNotLastOwner', 'removeOrgMemberIfNotLastOwner'] as const : []),
314
+ ] as const
315
+ const missing = methods.filter(name => typeof store[name] !== 'function')
316
+ if (missing.length > 0)
317
+ warn(`[auth/store-not-atomic] the AuthStore has no ${missing.join(', ')}, so prunelle checks then writes under a lock that only holds within one process: a second instance or a write from outside the app can slip between (a verification overwritten by the sign-up rollback, a TOTP code accepted twice, an org left with no owner). Implement them in the store, each as one transaction, as memoryAuthStore and sqliteAuthStore do.`)
318
+ }
319
+
312
320
  function routeOriginOptions(options: Pick<AuthOptions, 'trustedOrigins' | 'trustProxy'>) {
313
321
  return {
314
322
  ...(options.trustedOrigins !== undefined ? { trustedOrigins: options.trustedOrigins } : {}),
@@ -350,6 +358,40 @@ function lazySecret(optionSecret: string | undefined): () => string {
350
358
  }
351
359
  }
352
360
 
361
+ async function registerUser<TUser extends AuthUser>(
362
+ store: AuthStore<TUser>,
363
+ observeAsync: <T>(value: T | Promise<T>) => T | Promise<T>,
364
+ insertUser: (fields: Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>) => Promise<TUser>,
365
+ input: CreateUserInput<TUser>,
366
+ ): Promise<PublicUser<TUser>> {
367
+ const { email: rawEmail, password, name, avatarUrl, role, emailVerified, ...extra } = input
368
+ const email = normalizeEmail(rawEmail)
369
+ if (!isValidEmail(email))
370
+ throw new Error('Invalid email address')
371
+ if (await observeAsync(store.getUserByEmail(email)))
372
+ throw new Error('Email is already registered')
373
+
374
+ const passwordHash = password !== undefined ? await hashPassword(password) : undefined
375
+ let created: TUser
376
+ try {
377
+ created = await insertUser({
378
+ ...extra,
379
+ email,
380
+ ...(name !== undefined ? { name } : {}),
381
+ ...(avatarUrl !== undefined ? { avatarUrl } : {}),
382
+ ...(role !== undefined ? { role } : {}),
383
+ emailVerified: emailVerified ?? false,
384
+ ...(passwordHash !== undefined ? { passwordHash } : {}),
385
+ } as Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>)
386
+ }
387
+ catch (err) {
388
+ if (await observeAsync(store.getUserByEmail(email)))
389
+ throw new Error('Email is already registered', { cause: err })
390
+ throw err
391
+ }
392
+ return toPublicUser(created)
393
+ }
394
+
353
395
  export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptions<TUser> = {}): Auth<TUser> {
354
396
  const secret = lazySecret(options.secret)
355
397
  const store = options.store ?? memoryAuthStore<TUser>()
@@ -420,7 +462,6 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
420
462
  try {
421
463
  void Promise.resolve(store.pruneExpired?.(pruneOptions())).catch(() => {})
422
464
  sessions.sweepRenewedAt()
423
- passkeys.pruneChallenges()
424
465
  }
425
466
  catch {
426
467
  // Ignore prune errors if the underlying store has been closed
@@ -449,26 +490,8 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
449
490
  } as TUser))
450
491
  }
451
492
 
452
- async function createUser(input: CreateUserInput<TUser>): Promise<PublicUser<TUser>> {
453
- const { email: rawEmail, password, name, avatarUrl, role, emailVerified, ...extra } = input
454
- const email = normalizeEmail(rawEmail)
455
- if (!isValidEmail(email))
456
- throw new Error('Invalid email address')
457
- if (await sessions.observeAsync(store.getUserByEmail(email)))
458
- throw new Error('Email is already registered')
459
-
460
- const passwordHash = password !== undefined ? await hashPassword(password) : undefined
461
- const created = await insertUser({
462
- ...extra,
463
- email,
464
- ...(name !== undefined ? { name } : {}),
465
- ...(avatarUrl !== undefined ? { avatarUrl } : {}),
466
- ...(role !== undefined ? { role } : {}),
467
- emailVerified: emailVerified ?? false,
468
- ...(passwordHash !== undefined ? { passwordHash } : {}),
469
- } as Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>)
470
- return toPublicUser(created)
471
- }
493
+ const createUser = (input: CreateUserInput<TUser>): Promise<PublicUser<TUser>> =>
494
+ registerUser(store, sessions.observeAsync, insertUser, input)
472
495
 
473
496
  const mailedLinkOrigin = (url: URL): string | undefined => linkOrigin(site, url)
474
497
 
@@ -520,8 +543,8 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
520
543
  consumeLink,
521
544
  sendMagicLink,
522
545
  })
523
- registerTotpRoutes({ authRoute, store, sessions, totp, basePath, defaultRedirect, messages })
524
- registerPasskeyRoutes({ authRoute, store, sessions, passkeys, totp, twoFactorRedirect, defaultRedirect, requireEmailVerification })
546
+ registerTotpRoutes({ authRoute, limits: authLimitsObj, store, sessions, totp, basePath, defaultRedirect, messages })
547
+ registerPasskeyRoutes({ authRoute, limits: authLimitsObj, store, sessions, passkeys, totp, twoFactorRedirect, defaultRedirect, requireEmailVerification })
525
548
  registerOrgRoutes({ authRoute, limits: authLimitsObj, sessions, orgs, defaultRedirect, hasMailTransport, mailedLinkOrigin })
526
549
  registerAccountRoutes({ authRoute, sessions, account, clearPendingCookie: ctx => totp.clearPendingCookie(ctx) })
527
550
  registerOAuthRoutes({
@@ -554,6 +577,7 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
554
577
  enforce: 'pre',
555
578
  providesLocals: ['user', 'session', 'org', 'orgMembership'],
556
579
  requires: () => [isKeptInMemory(store) ? STORE_IN_MEMORY : undefined, requireEmailVerification && deliverMail === undefined ? NO_MAILER : undefined, secretProblem(configuredSecret(options.secret))].filter(line => line !== undefined),
580
+ check: ctx => warnIfStoreNotAtomic(store, ctx.warn),
557
581
  server(api) {
558
582
  if (options.trustProxy === undefined)
559
583
  trustProxy = api.trustProxy
@@ -628,7 +652,6 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
628
652
  async pruneExpired() {
629
653
  await store.pruneExpired?.(pruneOptions())
630
654
  sessions.sweepRenewedAt()
631
- passkeys.pruneChallenges()
632
655
  },
633
656
  dispose,
634
657
  }
package/src/links.ts CHANGED
@@ -13,8 +13,8 @@ const LINK_MAILS = {
13
13
  'verify-email': { subject: 'Verify your email address', text: 'Confirm your email address using this one-time link', html: 'Click to verify your email address', label: 'Verify email' },
14
14
  } as const
15
15
 
16
- // Binds a verify-email token to the user's current passwordHash so any password update invalidates prior verification links.
17
- function verifyBinding(user: { id: string, passwordHash?: string | undefined }): string {
16
+ // A tag of the user's current password, carried by a verify-email link so a password change invalidates the links sent before it.
17
+ function passwordTag(user: { id: string, passwordHash?: string | undefined }): string {
18
18
  return sha256Hex(`verify:${user.id}:${user.passwordHash ?? ''}`).slice(0, 32)
19
19
  }
20
20
 
@@ -61,7 +61,7 @@ export function createLinkService<TUser extends AuthUser = AuthUser>(deps: LinkS
61
61
  ): Promise<string> {
62
62
  const normalized = normalizeEmail(email)
63
63
  const boundUser = kind === 'verify-email' && userId !== undefined ? await sessions.observeAsync(store.getUserById(userId)) : undefined
64
- const rawToken = boundUser ? `${randomToken(32)}.${verifyBinding(boundUser)}` : randomToken(32)
64
+ const rawToken = boundUser ? `${randomToken(32)}.${passwordTag(boundUser)}` : randomToken(32)
65
65
  const tokenHash = sha256Hex(rawToken)
66
66
  await sessions.observeAsync(store.createToken({
67
67
  tokenHash,
@@ -143,7 +143,7 @@ export function createLinkService<TUser extends AuthUser = AuthUser>(deps: LinkS
143
143
  : await sessions.observeAsync(store.getUserByEmail(consumed.email))
144
144
  if (kind === 'verify-email') {
145
145
  const dot = rawToken.lastIndexOf('.')
146
- if (!user || dot <= 0 || !safeEqual(rawToken.slice(dot + 1), verifyBinding(user)))
146
+ if (!user || dot <= 0 || !safeEqual(rawToken.slice(dot + 1), passwordTag(user)))
147
147
  return undefined
148
148
  }
149
149
  return { email: consumed.email, user }
@@ -5,7 +5,7 @@ import { safeEqual, safeRedirect } from 'prunelle/server'
5
5
  import type { OAuthProfile, OAuthProvider } from './oauth'
6
6
  import type { AuthStore, AuthUser, PublicUser } from './store'
7
7
  import type { TotpManager } from './totp'
8
- import { pkceChallenge, randomToken, signPayload, verifyPayload } from './crypto'
8
+ import { pkceChallenge, randomToken, signJson, verifyJson } from './crypto'
9
9
  import { authCookie, fail, withNoStore } from './http'
10
10
  import { OAUTH_FETCH_TIMEOUT_MS } from './oauth'
11
11
  import { normalizeEmail, toPublicUser } from './store'
@@ -157,7 +157,7 @@ export function registerOAuthRoutes<TUser extends AuthUser = AuthUser>(deps: OAu
157
157
  const verifier = provider.pkce !== false ? randomToken(32) : undefined
158
158
  const redirectTarget = safeRedirect(ctx.url.searchParams.get('redirect') ?? ctx.url.searchParams.get('next'), defaultRedirect)
159
159
 
160
- const cookieVal = signPayload(secret(), {
160
+ const cookieVal = signJson(secret(), 'oauth', {
161
161
  provider: provider.id,
162
162
  state,
163
163
  verifier,
@@ -198,7 +198,7 @@ export function registerOAuthRoutes<TUser extends AuthUser = AuthUser>(deps: OAu
198
198
  if (!code || !returnedState || !rawCookie)
199
199
  return fail(ctx, 400, 'Invalid OAuth callback parameters')
200
200
 
201
- const saved = verifyPayload<OAuthStateCookie>(secret(), rawCookie)
201
+ const saved = verifyJson<OAuthStateCookie>(secret(), 'oauth', rawCookie)
202
202
  if (!saved || saved.exp <= Date.now() || saved.provider !== provider.id || !safeEqual(saved.state, returnedState))
203
203
  return fail(ctx, 400, 'Invalid or expired OAuth state')
204
204
 
package/src/org-routes.ts CHANGED
@@ -153,7 +153,7 @@ export function registerOrgRoutes<TUser extends AuthUser = AuthUser>(deps: OrgRo
153
153
 
154
154
  const email = normalizeEmail(body.email ?? '')
155
155
  if (!isValidEmail(email))
156
- return fail(ctx, 400, 'prunelle: please enter a valid email address')
156
+ return fail(ctx, 400, 'Please enter a valid email address')
157
157
 
158
158
  const linkOrigin = mailedLinkOrigin(ctx.url)
159
159
  if (hasMailTransport && linkOrigin === undefined) {