@prunellejs/auth 0.1.1 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts CHANGED
@@ -3,67 +3,107 @@
3
3
  // Supports Argon2id passwords, hashed DB sessions with sliding renewal, email verification,
4
4
  // magic links, OAuth 2.0 + PKCE (S256), role/route guards, RGPD helpers, and memory or `bun:sqlite` stores.
5
5
 
6
- import type { PrunellePlugin } from 'prunelle/config'
7
- import type { PrunelleLocals, Middleware, RequestContext, TrustProxy } from 'prunelle/server'
6
+ import type { PrunellePlugin, ServerPluginAPI } from 'prunelle/config'
7
+ import type { Middleware, PrunelleLocals, RequestContext, TrustProxy } from 'prunelle/server'
8
+ import type { AuthFormMessage } from './form-messages'
8
9
  import type { OAuthProvider } from './oauth'
9
-
10
- import type { AuthSession, AuthStore, AuthUser, PublicUser, UserExport } from './store'
10
+ import type { CreateOrgInput, InviteToOrgInput } from './orgs'
11
+ import type { PasskeyOptions } from './passkeys'
12
+ import type {
13
+ AuthSession,
14
+ AuthStore,
15
+ AuthUser,
16
+ Organization,
17
+ OrgInvitation,
18
+ OrgMembership,
19
+ PasskeySummary,
20
+ PruneOptions,
21
+ PublicUser,
22
+ UserExport,
23
+ UserOrgSummary,
24
+ } from './store'
25
+ import type { TotpOptions } from './totp'
11
26
  import { definePlugin } from 'prunelle/config'
12
- import { createRateLimitStore, isHttpsRequest, nodeEnv, safeRedirect, wantsJson } from 'prunelle/server'
13
- import { hashPassword, randomToken, sha256Hex } from './crypto'
14
- import { authLimits, fail, isValidEmail } from './http'
27
+ import { isHttpsRequest, nodeEnv } from 'prunelle/server'
28
+ import { hashPassword, randomToken } from './crypto'
29
+ import { authLimits, createAuthLimiters, createAuthRouteRegistrar, isValidEmail } from './http'
30
+ import { buildMailDeliverer, createLinkService } from './links'
15
31
  import { registerOAuthRoutes } from './oauth-routes'
16
-
32
+ import { registerOrgRoutes } from './org-routes'
33
+ import { createAuthGuard, createOrgManager } from './orgs'
34
+ import { registerPasskeyRoutes } from './passkey-routes'
35
+ import { createAccountService, registerAccountRoutes } from './account'
36
+ import { createPasskeyManager } from './passkeys'
17
37
  import { registerAuthRoutes } from './routes'
38
+ import { authFormMessages, readFormMessage } from './form-messages'
18
39
  import { createSessionManager } from './session'
19
40
  import { isKeptInMemory, memoryAuthStore, normalizeEmail, toPublicUser } from './store'
41
+ import { createTotpManager } from './totp'
42
+ import { registerTotpRoutes } from './totp-routes'
20
43
 
21
44
  declare module 'prunelle/server' {
22
45
  interface PrunelleLocals {
23
46
  user?: PublicUser | undefined
24
47
  session?: AuthSession | undefined
48
+ org?: Organization | undefined
49
+ orgMembership?: OrgMembership | undefined
25
50
  }
26
51
  }
27
52
 
28
53
  export interface RateLimitOptions {
29
- /** Attempts per window, per scope and address and per scope and email (default: 15). */
54
+ /** Attempts per window, per scope and address (default: 15). */
30
55
  max?: number | undefined
31
56
  /** Window duration in ms (default: 60_000). */
32
57
  windowMs?: number | undefined
33
- /** @deprecated Read by `createRateLimiter` only: the server's store bounds the auth limits. Removed in the next release. */
34
- maxKeys?: number | undefined
35
- }
36
-
37
- /** @deprecated Use `api.rateLimiter()` in a plugin, or `rateLimit` on `api.route` and `action()`. Removed in the next release. */
38
- export interface RateLimiter {
39
- allow(key: string): boolean
40
- sweep(now?: number): number
41
- size(): number
42
- }
43
-
44
- /** @deprecated Use `api.rateLimiter()` in a plugin, or `rateLimit` on `api.route` and `action()`. Removed in the next release. */
45
- export function createRateLimiter(opts: RateLimitOptions | false | undefined): RateLimiter {
46
- if (opts === false)
47
- return { allow: () => true, sweep: () => 0, size: () => 0 }
48
- const store = createRateLimitStore({ maxKeys: opts?.maxKeys })
49
- const limiter = store.limiter({ max: opts?.max ?? 15, windowMs: opts?.windowMs ?? 60_000 })
50
- return { allow: key => limiter.hit(key) === 0, sweep: now => store.sweep(now), size: () => store.size }
58
+ /** Mails sent to one address by sign-up, magic links and org invites, per 10 minutes (default: 3). */
59
+ mailsPerAddress?: number | undefined
60
+ /** Wrong passwords one account takes across all addresses per hour before sign-in refuses it (default: 100). */
61
+ failuresPerAccount?: number | undefined
51
62
  }
52
63
 
64
+ export { FRESH_SIGNIN_MS } from './account'
53
65
  export { safeRedirect } from 'prunelle/server'
66
+ export type { AuthFormCode, AuthFormMessage } from './form-messages'
54
67
  export { discord, github, google, oauthProvider } from './oauth'
55
68
  export type { OAuthPresetConfig, OAuthProfile, OAuthProvider } from './oauth'
56
- export { memoryAuthStore, normalizeEmail, toPublicUser } from './store'
57
- export type { AuthSession, AuthStore, AuthUser, OAuthAccount, PublicUser, TokenKind, UserExport, VerificationToken } from './store'
69
+ export type { CreateOrgInput, InviteToOrgInput } from './orgs'
70
+ export type { PasskeyOptions, PasskeyUserVerification } from './passkeys'
71
+ export { memoryAuthStore, normalizeEmail, toPasskeySummary, toPublicUser } from './store'
72
+ export type {
73
+ AuthSession,
74
+ AuthStore,
75
+ AuthStoreExt,
76
+ AuthUser,
77
+ OAuthAccount,
78
+ Organization,
79
+ OrgInvitation,
80
+ OrgMembership,
81
+ PasskeyRecord,
82
+ PasskeySummary,
83
+ PruneOptions,
84
+ PublicUser,
85
+ RecoveryCodeRecord,
86
+ TokenKind,
87
+ TotpRecord,
88
+ UserExport,
89
+ UserExportExt,
90
+ UserOrgSummary,
91
+ VerificationToken,
92
+ } from './store'
93
+ export { buildOtpauthUrl, generateTotpCode, generateTotpSecret } from './totp'
94
+ export type { TotpOptions, TwoFactorMethod } from './totp'
58
95
 
59
96
  const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]'])
60
97
  const DEFAULT_PRUNE_INTERVAL_MS = 15 * 60 * 1000
61
98
  const MIN_PROD_SECRET_BYTES = 32
62
- const LINK_PATHS = { 'magic-link': 'magic-link/verify', 'verify-email': 'verify-email' } as const
63
- const LINK_MAILS = {
64
- 'magic-link': { subject: 'Your sign-in link', text: 'Sign in using this one-time link', html: 'Click to sign in', label: 'Sign in' },
65
- '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' },
66
- } as const
99
+ const DEFAULT_MAX_PASSWORD_LENGTH = 1024
100
+
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
+ }
67
107
 
68
108
  // Mailed links and OAuth callbacks start with `site`, so anything but an http(s) origin is a config mistake.
69
109
  function siteOrigin(value: string): string {
@@ -79,7 +119,7 @@ export interface AuthMailPayload {
79
119
  text: string
80
120
  html?: string | undefined
81
121
  url: string
82
- kind: 'magic-link' | 'verify-email' | 'reset-password'
122
+ kind: 'magic-link' | 'verify-email' | 'reset-password' | 'org-invite'
83
123
  }
84
124
 
85
125
  /** Structural interface matching `@prunellejs/mail`'s `Mailer` so `createAuth({ mailer })` needs no glue callback. */
@@ -114,16 +154,24 @@ export interface AuthOptions<TUser extends AuthUser = AuthUser> {
114
154
  secret?: string | undefined
115
155
  /** Route prefix (default: '/auth'). */
116
156
  basePath?: string | undefined
117
- /** Session cookie name (default: 'pru_session'). */
157
+ /** Session cookie name (default: 'pru_session'). Over https the cookie is sent as `__Host-<name>`. */
118
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
119
161
  /** Session lifetime in seconds (default: 30 days). */
120
162
  sessionTtlSeconds?: number | undefined
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). */
164
+ absoluteTtlSeconds?: number | false | undefined
121
165
  /** Minimum interval in seconds between sliding-expiry DB writes for the same session (default: up to 1 hour). */
122
166
  renewalIntervalSeconds?: number | undefined
123
167
  /** Magic-link / verification token lifetime in seconds (default: 15 minutes). */
124
168
  tokenTtlSeconds?: number | undefined
169
+ /** Seconds a sign-up whose email was never verified is kept before the prune deletes it with its data (default: 7 days; `false` keeps it). Applies only while `requireEmailVerification` is on. */
170
+ unverifiedTtlSeconds?: number | false | undefined
125
171
  /** Minimum password length (default: 12, aligned with CNIL guidance). */
126
172
  minPasswordLength?: number | undefined
173
+ /** Maximum password length in characters / UTF-8 bytes before Argon2id hashing (default: 1024). */
174
+ maxPasswordLength?: number | undefined
127
175
  /** Default role assigned to newly created users (default: 'user'). */
128
176
  defaultRole?: string | undefined
129
177
  /** Default redirect after successful form login/signup/OAuth (default: '/'). */
@@ -138,6 +186,10 @@ export interface AuthOptions<TUser extends AuthUser = AuthUser> {
138
186
  mailer?: AuthMailer | undefined
139
187
  /** Custom mail sender for magic links / verification emails (overrides `mailer` when both are provided). */
140
188
  sendMail?: ((mail: AuthMailPayload) => void | Promise<void>) | undefined
189
+ /** Adds the app's own data about a user to `GET /auth/me/export` and `auth.exportUser()`, under `app`. */
190
+ onExportUser?: ((user: PublicUser<TUser>) => unknown) | undefined
191
+ /** Erases the app's own data about a user before `POST /auth/me/delete` or `auth.deleteUser()` deletes the account; a throw keeps the account. */
192
+ onDeleteUser?: ((user: PublicUser<TUser>) => void | Promise<void>) | undefined
141
193
  /**
142
194
  * Require email verification before opening a session on password sign-up / sign-in (default: `true`).
143
195
  * Set explicitly to `false` only when you intentionally allow unverified password sessions (e.g. local dev without mail).
@@ -159,15 +211,32 @@ export interface AuthOptions<TUser extends AuthUser = AuthUser> {
159
211
  * - `false`: do not record IP on sessions
160
212
  */
161
213
  storeIp?: boolean | 'truncate' | undefined
214
+ /** Whether an OAuth sign-up keeps the provider's display name and avatar URL on the new account (default: `false`, RGPD data minimisation: the account holds the email alone). */
215
+ storeOAuthProfile?: boolean | undefined
162
216
  /** Whether to record the `User-Agent` header on sessions (default: `true`). */
163
217
  storeUserAgent?: boolean | undefined
218
+ /** TOTP second-factor configuration (`issuer`, `verifyPath`). */
219
+ totp?: TotpOptions | undefined
220
+ /** Redirect path for HTML form sign-ins when 2FA is required (overrides `totp.verifyPath`, defaults to `${basePath}/totp/verify`). */
221
+ twoFactorRedirect?: string | undefined
222
+ /** WebAuthn Passkeys configuration (`rpId`, `rpName`, `origin`, `userVerification`). */
223
+ passkeys?: PasskeyOptions | undefined
224
+ /** Organization invitation lifetime in seconds (default: 7 days). */
225
+ orgInviteTtlSeconds?: number | undefined
164
226
  }
165
227
 
166
228
  export interface GuardOptions<TUser extends AuthUser = AuthUser> {
167
229
  /** Redirect unauthenticated HTML requests here (JSON/API requests always receive 401). */
168
230
  redirectTo?: string | undefined
169
- /** Required user role(s); authenticated users without a matching role receive 403. */
231
+ /** Required role(s): checks `orgMembership.role` when `org` is set, otherwise `user.role`. */
170
232
  role?: string | string[] | undefined
233
+ /**
234
+ * Require organization membership and populate `ctx.locals.org` & `ctx.locals.orgMembership`:
235
+ * - `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)
237
+ * - function: calls `await org(ctx)` to resolve the org id or slug
238
+ */
239
+ org?: boolean | string | ((ctx: RequestContext) => string | undefined | Promise<string | undefined>) | undefined
171
240
  /** Custom authorization predicate. */
172
241
  allow?: ((user: PublicUser<TUser>, ctx: RequestContext) => boolean | Promise<boolean>) | undefined
173
242
  }
@@ -178,6 +247,8 @@ export interface Auth<TUser extends AuthUser = AuthUser> extends PrunellePlugin
178
247
  readonly basePath: string
179
248
  getUser(ctx: { locals: PrunelleLocals }): PublicUser<TUser> | undefined
180
249
  getSession(ctx: { locals: PrunelleLocals }): AuthSession | undefined
250
+ /** The error or notice a sign-in, sign-up or two-factor form post carried back to the page at `url`, for the page to show; `undefined` when there is none. */
251
+ formMessage(url: URL): AuthFormMessage | undefined
181
252
  resolve(ctx: RequestContext): Promise<{ user: PublicUser<TUser>, session: AuthSession } | undefined>
182
253
  guard(options?: GuardOptions<TUser>): Middleware
183
254
  createUser(input: CreateUserInput<TUser>): Promise<PublicUser<TUser>>
@@ -186,6 +257,24 @@ export interface Auth<TUser extends AuthUser = AuthUser> extends PrunellePlugin
186
257
  revokeAllSessions(userId: string): Promise<void>
187
258
  sendMagicLink(email: string, origin: string, redirectTo?: string): Promise<string>
188
259
  sendVerificationEmail(email: string, origin: string, redirectTo?: string): Promise<string>
260
+ setupTotp(userId: string, opts?: { issuer?: string | undefined }): Promise<{ secret: string, otpauthUrl: string }>
261
+ confirmTotp(userId: string, code: string): Promise<{ enabled: true, recoveryCodes: string[] }>
262
+ verifyTotp(userId: string, code: string): Promise<{ valid: boolean, method?: 'totp' | 'recovery' | undefined }>
263
+ disableTotp(userId: string, code: string): Promise<boolean>
264
+ regenerateRecoveryCodes(userId: string): Promise<string[]>
265
+ listPasskeys(userId: string): Promise<PasskeySummary[]>
266
+ deletePasskey(userId: string, credentialId: string): Promise<boolean>
267
+ createOrg(ownerUserId: string, input: CreateOrgInput): Promise<Organization>
268
+ getOrg(idOrSlug: string): Promise<Organization | undefined>
269
+ listUserOrgs(userId: string): Promise<UserOrgSummary[]>
270
+ listOrgMembers(orgId: string): Promise<OrgMembership[]>
271
+ addOrgMember(orgId: string, userId: string, role?: string): Promise<OrgMembership>
272
+ updateOrgMemberRole(orgId: string, userId: string, role: string): Promise<OrgMembership | undefined>
273
+ removeOrgMember(orgId: string, userId: string): Promise<boolean>
274
+ inviteToOrg(orgId: string, input: InviteToOrgInput): Promise<{ invitation: OrgInvitation, url: string }>
275
+ acceptOrgInvite(token: string, userId: string): Promise<{ org: Organization, membership: OrgMembership }>
276
+ revokeOrgInvite(orgId: string, inviteId: string): Promise<boolean>
277
+ deleteOrg(orgId: string): Promise<void>
189
278
  listSessions(userId: string): Promise<AuthSession[]>
190
279
  exportUser(userId: string): Promise<UserExport<TUser> | null>
191
280
  deleteUser(userId: string): Promise<void>
@@ -193,79 +282,134 @@ export interface Auth<TUser extends AuthUser = AuthUser> extends PrunellePlugin
193
282
  dispose(): void
194
283
  }
195
284
 
285
+ const NO_MAILER = '`requireEmailVerification` is on but no mailer is set, so no sign-up can ever be verified: pass `mailer` (`createMailer()` from `@prunellejs/mail`) or `sendMail`, or set `requireEmailVerification: false`.'
286
+ const DEFAULT_UNVERIFIED_TTL_SECONDS = 7 * 24 * 60 * 60
287
+ const DEFAULT_ABSOLUTE_TTL_SECONDS = 90 * 24 * 60 * 60
288
+
289
+ /** Session timings and cookie/privacy settings derived from `AuthOptions`. */
290
+ function sessionConfig(options: Pick<AuthOptions, 'sessionTtlSeconds' | 'absoluteTtlSeconds' | 'renewalIntervalSeconds' | 'acceptLegacyCookie' | 'storeIp' | 'storeUserAgent'>) {
291
+ const sessionTtlSeconds = options.sessionTtlSeconds ?? 60 * 60 * 24 * 30
292
+ const sessionTtlMs = sessionTtlSeconds * 1000
293
+ return {
294
+ sessionTtlMs,
295
+ absoluteTtlMs: options.absoluteTtlSeconds === false ? undefined : Math.max(sessionTtlMs, (options.absoluteTtlSeconds ?? DEFAULT_ABSOLUTE_TTL_SECONDS) * 1000),
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,
300
+ }
301
+ }
302
+
303
+ function unverifiedPruneOptions(ttlSeconds: number | false | undefined, requireEmailVerification: boolean): () => PruneOptions | undefined {
304
+ if (!requireEmailVerification || ttlSeconds === false)
305
+ return () => undefined
306
+ const ttlMs = (ttlSeconds ?? DEFAULT_UNVERIFIED_TTL_SECONDS) * 1000
307
+ return () => ({ unverifiedCreatedBefore: Date.now() - ttlMs })
308
+ }
309
+
196
310
  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`.'
197
311
 
198
- function resolveSecret(optionSecret: string | undefined): string {
199
- if (optionSecret !== undefined && optionSecret.trim().length === 0)
200
- throw new Error('[prunelle/auth] `secret` must not be empty')
312
+ function routeOriginOptions(options: Pick<AuthOptions, 'trustedOrigins' | 'trustProxy'>) {
313
+ return {
314
+ ...(options.trustedOrigins !== undefined ? { trustedOrigins: options.trustedOrigins } : {}),
315
+ ...(options.trustProxy !== undefined ? { trustProxy: options.trustProxy } : {}),
316
+ }
317
+ }
318
+
319
+ function isSecureRequest(ctx: RequestContext, trustProxy: Parameters<typeof isHttpsRequest>[1]): boolean {
320
+ return ctx.url.protocol === 'https:' || isHttpsRequest(ctx.request, trustProxy) || nodeEnv() === 'production'
321
+ }
201
322
 
323
+ function configuredSecret(optionSecret: string | undefined): string | undefined {
202
324
  const envSecret = process.env.AUTH_SECRET
203
- const configured = optionSecret ?? (envSecret && envSecret.trim().length > 0 ? envSecret : undefined)
204
- if (nodeEnv() === 'production') {
205
- if (configured === undefined)
206
- throw new Error('[prunelle/auth] `secret` (or `AUTH_SECRET` env) is required in production and must be at least 32 bytes')
207
- if (Buffer.byteLength(configured, 'utf8') < MIN_PROD_SECRET_BYTES)
208
- throw new Error(`[prunelle/auth] \`secret\` must be at least ${MIN_PROD_SECRET_BYTES} UTF-8 bytes in production`)
325
+ return optionSecret ?? (envSecret !== undefined && envSecret.trim().length > 0 ? envSecret : undefined)
326
+ }
327
+
328
+ // What production refuses in a secret; anywhere else a missing one is a key made at start.
329
+ function secretProblem(configured: string | undefined): string | undefined {
330
+ if (configured === undefined)
331
+ return `no \`secret\`, so TOTP seeds are encrypted, and the two-factor, passkey and OAuth cookies signed, with a key made at each start, and after a restart no one with two-factor sign-in can sign in: set \`AUTH_SECRET\` to ${MIN_PROD_SECRET_BYTES} random bytes or more (\`openssl rand -base64 32\`), or pass \`secret\` to \`createAuth()\`.`
332
+ const bytes = Buffer.byteLength(configured, 'utf8')
333
+ return bytes < MIN_PROD_SECRET_BYTES ? `\`secret\` is ${bytes} bytes, too short to resist guessing: give it ${MIN_PROD_SECRET_BYTES} random bytes or more (\`openssl rand -base64 32\`).` : undefined
334
+ }
335
+
336
+ // The secret, resolved at first use rather than when prunelle.config.ts imports the app's auth: a build signs nothing, and a production start refuses a missing one through `requires`.
337
+ function lazySecret(optionSecret: string | undefined): () => string {
338
+ if (optionSecret !== undefined && optionSecret.trim().length === 0)
339
+ throw new Error('prunelle: @prunellejs/auth `secret` is empty: give it 32 random bytes or more, or leave it out and set `AUTH_SECRET`.')
340
+ let resolved: string | undefined
341
+ return () => {
342
+ if (resolved !== undefined)
343
+ return resolved
344
+ const configured = configuredSecret(optionSecret)
345
+ const problem = nodeEnv() === 'production' ? secretProblem(configured) : undefined
346
+ if (problem !== undefined)
347
+ throw new Error(`prunelle: @prunellejs/auth: ${problem}`)
348
+ resolved = configured ?? randomToken(32)
349
+ return resolved
209
350
  }
210
- return configured ?? randomToken(32)
211
351
  }
212
352
 
213
353
  export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptions<TUser> = {}): Auth<TUser> {
214
- const secret = resolveSecret(options.secret)
354
+ const secret = lazySecret(options.secret)
215
355
  const store = options.store ?? memoryAuthStore<TUser>()
216
356
  const basePath = (options.basePath ?? '/auth').replace(/\/$/, '')
217
357
  const cookieName = options.cookieName ?? 'pru_session'
218
358
  const oauthCookieName = `${cookieName}_oauth`
219
- const sessionTtlSeconds = options.sessionTtlSeconds ?? 60 * 60 * 24 * 30
220
- const sessionTtlMs = sessionTtlSeconds * 1000
221
- const renewalIntervalMs = Math.max(0, (options.renewalIntervalSeconds ?? Math.min(60 * 60, Math.max(1, Math.floor(sessionTtlSeconds / 4)))) * 1000)
222
359
  const tokenTtlMs = (options.tokenTtlSeconds ?? 60 * 15) * 1000
223
360
  const minPasswordLength = options.minPasswordLength ?? 12
361
+ const maxPasswordLength = options.maxPasswordLength ?? DEFAULT_MAX_PASSWORD_LENGTH
224
362
  const defaultRole = options.defaultRole ?? 'user'
225
363
  const defaultRedirect = options.defaultRedirect ?? '/'
226
- const authRouteOpts = {
227
- ...(options.trustedOrigins !== undefined ? { trustedOrigins: options.trustedOrigins } : {}),
228
- ...(options.trustProxy !== undefined ? { trustProxy: options.trustProxy } : {}),
229
- }
364
+ const authRouteOpts = routeOriginOptions(options)
230
365
  let site = options.site !== undefined ? siteOrigin(options.site) : undefined
231
- const deliverMail: ((mail: AuthMailPayload) => void | Promise<void>) | undefined = options.sendMail
232
- ?? (options.mailer !== undefined
233
- ? async (mail) => {
234
- await options.mailer!.send({
235
- to: mail.to,
236
- subject: mail.subject,
237
- text: mail.text,
238
- html: mail.html,
239
- })
240
- }
241
- : undefined)
366
+ const deliverMail = buildMailDeliverer(options.sendMail, options.mailer)
242
367
  const requireEmailVerification = options.requireEmailVerification !== false
243
368
  let trustProxy = options.trustProxy ?? false
244
369
 
245
- const pruneIntervalMs = options.pruneIntervalMs === false
246
- ? undefined
247
- : (options.pruneIntervalMs ?? DEFAULT_PRUNE_INTERVAL_MS)
248
-
249
- const providers = new Map<string, OAuthProvider>()
250
- for (const p of options.providers ?? [])
251
- providers.set(p.id, p)
370
+ const pruneIntervalMs = options.pruneIntervalMs === false ? undefined : (options.pruneIntervalMs ?? DEFAULT_PRUNE_INTERVAL_MS)
371
+ const pruneOptions = unverifiedPruneOptions(options.unverifiedTtlSeconds, requireEmailVerification)
372
+ const providers = new Map<string, OAuthProvider>((options.providers ?? []).map(p => [p.id, p]))
373
+ const messages = authFormMessages(minPasswordLength, maxPasswordLength)
252
374
 
253
- const isSecureCookie = (ctx: RequestContext): boolean =>
254
- ctx.url.protocol === 'https:'
255
- || isHttpsRequest(ctx.request, trustProxy)
256
- || nodeEnv() === 'production'
375
+ const isSecureCookie = (ctx: RequestContext): boolean => isSecureRequest(ctx, trustProxy)
257
376
 
258
377
  const sessions = createSessionManager({
259
378
  store,
260
379
  cookieName,
261
- sessionTtlMs,
262
- renewalIntervalMs,
263
- storeIp: options.storeIp ?? 'truncate',
264
- storeUserAgent: options.storeUserAgent !== false,
380
+ ...sessionConfig(options),
265
381
  getTrustProxy: () => trustProxy,
266
382
  isSecureCookie,
267
383
  })
268
384
 
385
+ const twoFactorRedirect = options.twoFactorRedirect ?? options.totp?.verifyPath ?? `${basePath}/totp/verify`
386
+ const totp = createTotpManager({
387
+ store,
388
+ sessions,
389
+ secret,
390
+ twoFactorCookieName: `${cookieName}_2fa`,
391
+ getDefaultIssuer: () => options.totp?.issuer ?? (site ? new URL(site).hostname : 'Prunelle'),
392
+ isSecureCookie,
393
+ })
394
+ const account = createAccountService(store, sessions, options)
395
+ const passkeys = createPasskeyManager({
396
+ store,
397
+ sessions,
398
+ secret,
399
+ challengeCookieName: `${cookieName}_webauthn`,
400
+ getSite: () => site,
401
+ options: options.passkeys,
402
+ isSecureCookie,
403
+ })
404
+ const orgs = createOrgManager({
405
+ store,
406
+ sessions,
407
+ basePath,
408
+ defaultRedirect,
409
+ orgInviteTtlMs: options.orgInviteTtlSeconds !== undefined ? options.orgInviteTtlSeconds * 1000 : undefined,
410
+ deliverMail,
411
+ })
412
+
269
413
  // One timer per server the plugin runs on: `prunelle dev` starts the next server before it shuts the previous one down.
270
414
  const pruneTimers = new Set<ReturnType<typeof setInterval>>()
271
415
  let activeServers = 0
@@ -274,8 +418,9 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
274
418
  return undefined
275
419
  const timer = setInterval(() => {
276
420
  try {
277
- void Promise.resolve(store.pruneExpired?.()).catch(() => {})
421
+ void Promise.resolve(store.pruneExpired?.(pruneOptions())).catch(() => {})
278
422
  sessions.sweepRenewedAt()
423
+ passkeys.pruneChallenges()
279
424
  }
280
425
  catch {
281
426
  // Ignore prune errors if the underlying store has been closed
@@ -325,12 +470,7 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
325
470
  return toPublicUser(created)
326
471
  }
327
472
 
328
- // The request URL comes from the Host header, which the client controls: a link mailed to a victim must not point at it.
329
- function mailedLinkOrigin(url: URL): string | undefined {
330
- if (site !== undefined)
331
- return site
332
- return LOOPBACK_HOSTS.has(url.hostname) ? url.origin : undefined
333
- }
473
+ const mailedLinkOrigin = (url: URL): string | undefined => linkOrigin(site, url)
334
474
 
335
475
  // Whoever signed up with an address before it was proven may hold its password, sessions and provider links; proving it hands the account to the owner alone.
336
476
  // The password goes first, so a squatter cannot sign in again between the purge and the update.
@@ -341,90 +481,10 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
341
481
  return claimed
342
482
  }
343
483
 
344
- // One-time emailed link: stores the hashed token, builds the URL and mails it when a transport is configured.
345
- async function issueLink(kind: 'magic-link' | 'verify-email', userId: string | undefined, email: string, origin: string | undefined, redirectTo: string | undefined): Promise<string> {
346
- const normalized = normalizeEmail(email)
347
- const rawToken = randomToken(32)
348
- const tokenHash = sha256Hex(rawToken)
349
- await sessions.observeAsync(store.createToken({
350
- tokenHash,
351
- ...(userId !== undefined ? { userId } : {}),
352
- email: normalized,
353
- kind,
354
- expiresAt: Date.now() + tokenTtlMs,
355
- }))
356
-
357
- const next = safeRedirect(redirectTo, defaultRedirect)
358
- const path = `${basePath}/${LINK_PATHS[kind]}?token=${encodeURIComponent(rawToken)}&redirect=${encodeURIComponent(next)}`
359
- const url = origin !== undefined ? `${origin.replace(/\/$/, '')}${path}` : path
360
-
361
- if (deliverMail && origin !== undefined) {
362
- const mail = LINK_MAILS[kind]
363
- try {
364
- await deliverMail({
365
- to: normalized,
366
- subject: mail.subject,
367
- text: `${mail.text}: ${url}`,
368
- html: `<p>${mail.html}: <a href="${url}">${mail.label}</a></p>`,
369
- url,
370
- kind,
371
- })
372
- }
373
- catch (err) {
374
- try {
375
- await sessions.observeAsync(store.consumeToken(tokenHash, kind))
376
- }
377
- catch {
378
- // Best-effort token cleanup if delivery fails.
379
- }
380
- throw err
381
- }
382
- }
383
- return url
384
- }
385
-
386
- async function sendVerificationEmail(email: string, origin: string, redirectTo?: string): Promise<string> {
387
- const normalized = normalizeEmail(email)
388
- const existing = await sessions.observeAsync(store.getUserByEmail(normalized))
389
- return issueLink('verify-email', existing?.id, normalized, origin, redirectTo)
390
- }
391
-
392
- async function sendMagicLink(email: string, origin: string, redirectTo?: string): Promise<string> {
393
- const normalized = normalizeEmail(email)
394
- const existing = await sessions.observeAsync(store.getUserByEmail(normalized))
395
- return issueLink('magic-link', existing?.id, normalized, origin, redirectTo)
396
- }
397
-
398
- // Consumes a one-time token and loads the user it was issued for (by id, else by email).
399
- async function consumeLink(kind: 'magic-link' | 'verify-email', rawToken: string): Promise<{ email: string, user: TUser | undefined } | undefined> {
400
- const consumed = await sessions.observeAsync(store.consumeToken(sha256Hex(rawToken), kind))
401
- if (!consumed)
402
- return undefined
403
- const user = consumed.userId
404
- ? await sessions.observeAsync(store.getUserById(consumed.userId))
405
- : await sessions.observeAsync(store.getUserByEmail(consumed.email))
406
- return { email: consumed.email, user }
407
- }
484
+ const links = createLinkService({ store, sessions, basePath, defaultRedirect, tokenTtlMs, deliverMail })
485
+ const { issueLink, sendVerificationEmail, sendMagicLink, consumeLink } = links
408
486
 
409
- function guard(guardOpts: GuardOptions<TUser> = {}): Middleware {
410
- const roles = guardOpts.role === undefined ? undefined : (Array.isArray(guardOpts.role) ? guardOpts.role : [guardOpts.role])
411
- return async (ctx, next) => {
412
- const resolved = await sessions.resolve(ctx)
413
- if (!resolved) {
414
- if (!wantsJson(ctx.request) && guardOpts.redirectTo) {
415
- const nextParam = encodeURIComponent(ctx.url.pathname + ctx.url.search)
416
- const sep = guardOpts.redirectTo.includes('?') ? '&' : '?'
417
- return ctx.redirect(`${guardOpts.redirectTo}${sep}next=${nextParam}`, 302)
418
- }
419
- return fail(ctx, 401, 'Authentication required')
420
- }
421
- if (roles && !roles.includes(resolved.user.role))
422
- return fail(ctx, 403, 'Forbidden')
423
- if (guardOpts.allow && !(await guardOpts.allow(resolved.user, ctx)))
424
- return fail(ctx, 403, 'Forbidden')
425
- return next()
426
- }
427
- }
487
+ const guard = (guardOpts?: GuardOptions<TUser>): Middleware => createAuthGuard(sessions.resolve, orgs, guardOpts)
428
488
 
429
489
  const dispose = (): void => {
430
490
  for (const timer of pruneTimers)
@@ -434,11 +494,66 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
434
494
  void Promise.resolve(store.close?.()).catch(() => {})
435
495
  }
436
496
 
497
+ function registerServerRoutes(api: ServerPluginAPI): void {
498
+ const authLimitsObj = authLimits(createAuthLimiters(api, options.rateLimit), () => trustProxy)
499
+ const authRoute = createAuthRouteRegistrar(api, basePath, authRouteOpts, authLimitsObj)
500
+ const hasMailTransport = deliverMail !== undefined
501
+
502
+ registerAuthRoutes({
503
+ authRoute,
504
+ limits: authLimitsObj,
505
+ store,
506
+ sessions,
507
+ totp,
508
+ twoFactorRedirect,
509
+ minPasswordLength,
510
+ maxPasswordLength,
511
+ messages,
512
+ defaultRedirect,
513
+ requireEmailVerification,
514
+ hasMailTransport,
515
+ mailedLinkOrigin,
516
+ createUser,
517
+ insertUser,
518
+ claimUnverified,
519
+ issueLink,
520
+ consumeLink,
521
+ sendMagicLink,
522
+ })
523
+ registerTotpRoutes({ authRoute, store, sessions, totp, basePath, defaultRedirect, messages })
524
+ registerPasskeyRoutes({ authRoute, store, sessions, passkeys, totp, twoFactorRedirect, defaultRedirect, requireEmailVerification })
525
+ registerOrgRoutes({ authRoute, limits: authLimitsObj, sessions, orgs, defaultRedirect, hasMailTransport, mailedLinkOrigin })
526
+ registerAccountRoutes({ authRoute, sessions, account, clearPendingCookie: ctx => totp.clearPendingCookie(ctx) })
527
+ registerOAuthRoutes({
528
+ route: (method, path, handler) => api.route(method, path, handler),
529
+ store,
530
+ providers,
531
+ secret,
532
+ site,
533
+ basePath,
534
+ stateCookieName: oauthCookieName,
535
+ defaultRedirect,
536
+ requireEmailVerification,
537
+ hasMailTransport,
538
+ mailedLinkOrigin,
539
+ issueLink,
540
+ limitIp: authLimitsObj.limitIp,
541
+ isSecureCookie,
542
+ claimUnverified,
543
+ insertUser,
544
+ storeProfile: options.storeOAuthProfile === true,
545
+ totp,
546
+ twoFactorRedirect,
547
+ createSessionForUser: sessions.createSessionForUser,
548
+ observeAsync: sessions.observeAsync,
549
+ })
550
+ }
551
+
437
552
  const plugin: PrunellePlugin = definePlugin({
438
553
  name: '@prunellejs/auth',
439
554
  enforce: 'pre',
440
- providesLocals: ['user', 'session'],
441
- requires: () => isKeptInMemory(store) ? [STORE_IN_MEMORY] : [],
555
+ providesLocals: ['user', 'session', 'org', 'orgMembership'],
556
+ requires: () => [isKeptInMemory(store) ? STORE_IN_MEMORY : undefined, requireEmailVerification && deliverMail === undefined ? NO_MAILER : undefined, secretProblem(configuredSecret(options.secret))].filter(line => line !== undefined),
442
557
  server(api) {
443
558
  if (options.trustProxy === undefined)
444
559
  trustProxy = api.trustProxy
@@ -454,67 +569,23 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
454
569
  stopPruneTimer?.()
455
570
  activeServers = Math.max(0, activeServers - 1)
456
571
  if (activeServers === 0)
457
- await store.close?.()
572
+ await links.drain().then(() => store.close?.())
458
573
  })
459
574
 
460
- // Sync stores resolve lazily on first read of ctx.locals.user/session; async stores resolve before next().
575
+ // Sync stores resolve lazily on first read of ctx.locals.user/session; async or unknown Promise-returning stores await before next().
461
576
  const internalPrefix = `${api.assetPrefix.replace(/\/$/, '')}/`
462
577
  const actionPrefix = `${internalPrefix}action/`
463
578
  api.use((ctx, next) => {
464
579
  const p = ctx.url.pathname
465
580
  if (!p.startsWith(internalPrefix) || p.startsWith(actionPrefix)) {
466
- if (sessions.isAsyncStore()) {
467
- if (ctx.cookies.get(cookieName))
468
- return sessions.resolve(ctx).then(() => next())
469
- }
470
- else {
471
- sessions.attachLazy(ctx)
472
- }
581
+ const pending = sessions.prepareRequest(ctx)
582
+ if (pending !== undefined)
583
+ return pending.then(() => next())
473
584
  }
474
585
  return next()
475
586
  }, { scope: 'rendered' })
476
587
 
477
- // Counted in this server's store, so a `prunelle dev` restart or a test's new server starts from zero.
478
- const limits = options.rateLimit === false ? undefined : api.rateLimiter({ max: options.rateLimit?.max ?? 15, windowMs: options.rateLimit?.windowMs ?? 60_000 })
479
- const { limitIp, limitEmail } = authLimits(limits, () => trustProxy)
480
- registerAuthRoutes({
481
- api,
482
- store,
483
- sessions,
484
- limitEmail,
485
- limitIp,
486
- basePath,
487
- authRouteOpts,
488
- minPasswordLength,
489
- defaultRedirect,
490
- requireEmailVerification,
491
- hasMailTransport: deliverMail !== undefined,
492
- mailedLinkOrigin,
493
- createUser,
494
- insertUser,
495
- claimUnverified,
496
- issueLink,
497
- consumeLink,
498
- sendMagicLink,
499
- })
500
-
501
- registerOAuthRoutes({
502
- route: (method, path, handler) => api.route(method, path, handler),
503
- store,
504
- providers,
505
- secret,
506
- site,
507
- basePath,
508
- stateCookieName: oauthCookieName,
509
- defaultRedirect,
510
- limitIp,
511
- isSecureCookie,
512
- claimUnverified,
513
- insertUser,
514
- createSessionForUser: sessions.createSessionForUser,
515
- setResolvedUser: sessions.setResolvedUser,
516
- observeAsync: sessions.observeAsync,
517
- })
588
+ registerServerRoutes(api)
518
589
  },
519
590
  })
520
591
 
@@ -524,28 +595,40 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
524
595
  basePath,
525
596
  getUser: sessions.getUser,
526
597
  getSession: sessions.getSession,
598
+ formMessage: url => readFormMessage(messages, url),
527
599
  resolve: sessions.resolve,
528
600
  guard,
529
601
  createUser,
530
- createSessionForUser: sessions.createSessionForUser,
602
+ createSessionForUser: (userId, ctx) => sessions.createSessionForUser(userId, ctx),
531
603
  signOut: sessions.signOut,
532
- async revokeAllSessions(userId) {
533
- await sessions.observeAsync(store.deleteUserSessions(userId))
534
- },
604
+ revokeAllSessions: async (userId) => { await sessions.observeAsync(store.deleteUserSessions(userId)) },
535
605
  sendMagicLink,
536
606
  sendVerificationEmail,
537
- async listSessions(userId) {
538
- return await sessions.observeAsync(store.listSessions(userId))
539
- },
540
- async exportUser(userId) {
541
- return await sessions.observeAsync(store.exportUser(userId))
542
- },
543
- async deleteUser(userId) {
544
- await sessions.observeAsync(store.deleteUser(userId))
545
- },
607
+ setupTotp: totp.setupTotp,
608
+ confirmTotp: totp.confirmTotp,
609
+ verifyTotp: totp.verifyTotp,
610
+ disableTotp: totp.disableTotp,
611
+ regenerateRecoveryCodes: totp.regenerateRecoveryCodes,
612
+ listPasskeys: passkeys.listPasskeys,
613
+ deletePasskey: passkeys.deletePasskey,
614
+ createOrg: orgs.createOrg,
615
+ getOrg: orgs.getOrg,
616
+ listUserOrgs: orgs.listUserOrgs,
617
+ listOrgMembers: orgs.listOrgMembers,
618
+ addOrgMember: orgs.addOrgMember,
619
+ updateOrgMemberRole: orgs.updateOrgMemberRole,
620
+ removeOrgMember: orgs.removeOrgMember,
621
+ inviteToOrg: orgs.inviteToOrg,
622
+ acceptOrgInvite: orgs.acceptOrgInvite,
623
+ revokeOrgInvite: orgs.revokeOrgInvite,
624
+ deleteOrg: orgs.deleteOrg,
625
+ listSessions: async userId => await sessions.observeAsync(store.listSessions(userId)),
626
+ exportUser: account.exportUser,
627
+ deleteUser: account.deleteUser,
546
628
  async pruneExpired() {
547
- await store.pruneExpired?.()
629
+ await store.pruneExpired?.(pruneOptions())
548
630
  sessions.sweepRenewedAt()
631
+ passkeys.pruneChallenges()
549
632
  },
550
633
  dispose,
551
634
  }