@prunellejs/auth 0.1.1 → 0.7.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/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,22 @@ 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>`, and a session still under the plain name is moved on its next request. */
118
158
  cookieName?: string | undefined
119
159
  /** Session lifetime in seconds (default: 30 days). */
120
160
  sessionTtlSeconds?: number | undefined
161
+ /** 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). */
162
+ absoluteTtlSeconds?: number | false | undefined
121
163
  /** Minimum interval in seconds between sliding-expiry DB writes for the same session (default: up to 1 hour). */
122
164
  renewalIntervalSeconds?: number | undefined
123
165
  /** Magic-link / verification token lifetime in seconds (default: 15 minutes). */
124
166
  tokenTtlSeconds?: number | undefined
167
+ /** 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. */
168
+ unverifiedTtlSeconds?: number | false | undefined
125
169
  /** Minimum password length (default: 12, aligned with CNIL guidance). */
126
170
  minPasswordLength?: number | undefined
171
+ /** Maximum password length in characters / UTF-8 bytes before Argon2id hashing (default: 1024). */
172
+ maxPasswordLength?: number | undefined
127
173
  /** Default role assigned to newly created users (default: 'user'). */
128
174
  defaultRole?: string | undefined
129
175
  /** Default redirect after successful form login/signup/OAuth (default: '/'). */
@@ -138,6 +184,10 @@ export interface AuthOptions<TUser extends AuthUser = AuthUser> {
138
184
  mailer?: AuthMailer | undefined
139
185
  /** Custom mail sender for magic links / verification emails (overrides `mailer` when both are provided). */
140
186
  sendMail?: ((mail: AuthMailPayload) => void | Promise<void>) | undefined
187
+ /** Adds the app's own data about a user to `GET /auth/me/export` and `auth.exportUser()`, under `app`. */
188
+ onExportUser?: ((user: PublicUser<TUser>) => unknown) | undefined
189
+ /** 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. */
190
+ onDeleteUser?: ((user: PublicUser<TUser>) => void | Promise<void>) | undefined
141
191
  /**
142
192
  * Require email verification before opening a session on password sign-up / sign-in (default: `true`).
143
193
  * Set explicitly to `false` only when you intentionally allow unverified password sessions (e.g. local dev without mail).
@@ -159,15 +209,32 @@ export interface AuthOptions<TUser extends AuthUser = AuthUser> {
159
209
  * - `false`: do not record IP on sessions
160
210
  */
161
211
  storeIp?: boolean | 'truncate' | undefined
212
+ /** 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). */
213
+ storeOAuthProfile?: boolean | undefined
162
214
  /** Whether to record the `User-Agent` header on sessions (default: `true`). */
163
215
  storeUserAgent?: boolean | undefined
216
+ /** TOTP second-factor configuration (`issuer`, `verifyPath`). */
217
+ totp?: TotpOptions | undefined
218
+ /** Redirect path for HTML form sign-ins when 2FA is required (overrides `totp.verifyPath`, defaults to `${basePath}/totp/verify`). */
219
+ twoFactorRedirect?: string | undefined
220
+ /** WebAuthn Passkeys configuration (`rpId`, `rpName`, `origin`, `userVerification`). */
221
+ passkeys?: PasskeyOptions | undefined
222
+ /** Organization invitation lifetime in seconds (default: 7 days). */
223
+ orgInviteTtlSeconds?: number | undefined
164
224
  }
165
225
 
166
226
  export interface GuardOptions<TUser extends AuthUser = AuthUser> {
167
227
  /** Redirect unauthenticated HTML requests here (JSON/API requests always receive 401). */
168
228
  redirectTo?: string | undefined
169
- /** Required user role(s); authenticated users without a matching role receive 403. */
229
+ /** Required role(s): checks `orgMembership.role` when `org` is set, otherwise `user.role`. */
170
230
  role?: string | string[] | undefined
231
+ /**
232
+ * Require organization membership and populate `ctx.locals.org` & `ctx.locals.orgMembership`:
233
+ * - `true`: reads `ctx.params.org ?? ctx.params.orgId ?? ctx.params.slug`
234
+ * - `string`: reads `ctx.params[org]` (or falls back to looking up `org` as a slug/id)
235
+ * - function: calls `await org(ctx)` to resolve the org id or slug
236
+ */
237
+ org?: boolean | string | ((ctx: RequestContext) => string | undefined | Promise<string | undefined>) | undefined
171
238
  /** Custom authorization predicate. */
172
239
  allow?: ((user: PublicUser<TUser>, ctx: RequestContext) => boolean | Promise<boolean>) | undefined
173
240
  }
@@ -178,6 +245,8 @@ export interface Auth<TUser extends AuthUser = AuthUser> extends PrunellePlugin
178
245
  readonly basePath: string
179
246
  getUser(ctx: { locals: PrunelleLocals }): PublicUser<TUser> | undefined
180
247
  getSession(ctx: { locals: PrunelleLocals }): AuthSession | undefined
248
+ /** 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. */
249
+ formMessage(url: URL): AuthFormMessage | undefined
181
250
  resolve(ctx: RequestContext): Promise<{ user: PublicUser<TUser>, session: AuthSession } | undefined>
182
251
  guard(options?: GuardOptions<TUser>): Middleware
183
252
  createUser(input: CreateUserInput<TUser>): Promise<PublicUser<TUser>>
@@ -186,6 +255,24 @@ export interface Auth<TUser extends AuthUser = AuthUser> extends PrunellePlugin
186
255
  revokeAllSessions(userId: string): Promise<void>
187
256
  sendMagicLink(email: string, origin: string, redirectTo?: string): Promise<string>
188
257
  sendVerificationEmail(email: string, origin: string, redirectTo?: string): Promise<string>
258
+ setupTotp(userId: string, opts?: { issuer?: string | undefined }): Promise<{ secret: string, otpauthUrl: string }>
259
+ confirmTotp(userId: string, code: string): Promise<{ enabled: true, recoveryCodes: string[] }>
260
+ verifyTotp(userId: string, code: string): Promise<{ valid: boolean, method?: 'totp' | 'recovery' | undefined }>
261
+ disableTotp(userId: string, code: string): Promise<boolean>
262
+ regenerateRecoveryCodes(userId: string): Promise<string[]>
263
+ listPasskeys(userId: string): Promise<PasskeySummary[]>
264
+ deletePasskey(userId: string, credentialId: string): Promise<boolean>
265
+ createOrg(ownerUserId: string, input: CreateOrgInput): Promise<Organization>
266
+ getOrg(idOrSlug: string): Promise<Organization | undefined>
267
+ listUserOrgs(userId: string): Promise<UserOrgSummary[]>
268
+ listOrgMembers(orgId: string): Promise<OrgMembership[]>
269
+ addOrgMember(orgId: string, userId: string, role?: string): Promise<OrgMembership>
270
+ updateOrgMemberRole(orgId: string, userId: string, role: string): Promise<OrgMembership | undefined>
271
+ removeOrgMember(orgId: string, userId: string): Promise<boolean>
272
+ inviteToOrg(orgId: string, input: InviteToOrgInput): Promise<{ invitation: OrgInvitation, url: string }>
273
+ acceptOrgInvite(token: string, userId: string): Promise<{ org: Organization, membership: OrgMembership }>
274
+ revokeOrgInvite(orgId: string, inviteId: string): Promise<boolean>
275
+ deleteOrg(orgId: string): Promise<void>
189
276
  listSessions(userId: string): Promise<AuthSession[]>
190
277
  exportUser(userId: string): Promise<UserExport<TUser> | null>
191
278
  deleteUser(userId: string): Promise<void>
@@ -193,79 +280,133 @@ export interface Auth<TUser extends AuthUser = AuthUser> extends PrunellePlugin
193
280
  dispose(): void
194
281
  }
195
282
 
283
+ 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`.'
284
+ const DEFAULT_UNVERIFIED_TTL_SECONDS = 7 * 24 * 60 * 60
285
+ const DEFAULT_ABSOLUTE_TTL_SECONDS = 90 * 24 * 60 * 60
286
+
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
+ const sessionTtlSeconds = options.sessionTtlSeconds ?? 60 * 60 * 24 * 30
290
+ const sessionTtlMs = sessionTtlSeconds * 1000
291
+ return {
292
+ sessionTtlMs,
293
+ absoluteTtlMs: options.absoluteTtlSeconds === false ? undefined : Math.max(sessionTtlMs, (options.absoluteTtlSeconds ?? DEFAULT_ABSOLUTE_TTL_SECONDS) * 1000),
294
+ renewalIntervalMs: Math.max(0, (options.renewalIntervalSeconds ?? Math.min(60 * 60, Math.max(1, Math.floor(sessionTtlSeconds / 4)))) * 1000),
295
+ }
296
+ }
297
+
298
+ function unverifiedPruneOptions(ttlSeconds: number | false | undefined, requireEmailVerification: boolean): () => PruneOptions | undefined {
299
+ if (!requireEmailVerification || ttlSeconds === false)
300
+ return () => undefined
301
+ const ttlMs = (ttlSeconds ?? DEFAULT_UNVERIFIED_TTL_SECONDS) * 1000
302
+ return () => ({ unverifiedCreatedBefore: Date.now() - ttlMs })
303
+ }
304
+
196
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`.'
197
306
 
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')
307
+ function routeOriginOptions(options: Pick<AuthOptions, 'trustedOrigins' | 'trustProxy'>) {
308
+ return {
309
+ ...(options.trustedOrigins !== undefined ? { trustedOrigins: options.trustedOrigins } : {}),
310
+ ...(options.trustProxy !== undefined ? { trustProxy: options.trustProxy } : {}),
311
+ }
312
+ }
313
+
314
+ function isSecureRequest(ctx: RequestContext, trustProxy: Parameters<typeof isHttpsRequest>[1]): boolean {
315
+ return ctx.url.protocol === 'https:' || isHttpsRequest(ctx.request, trustProxy) || nodeEnv() === 'production'
316
+ }
201
317
 
318
+ function configuredSecret(optionSecret: string | undefined): string | undefined {
202
319
  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`)
320
+ return optionSecret ?? (envSecret !== undefined && envSecret.trim().length > 0 ? envSecret : undefined)
321
+ }
322
+
323
+ // What production refuses in a secret; anywhere else a missing one is a key made at start.
324
+ function secretProblem(configured: string | undefined): string | undefined {
325
+ if (configured === undefined)
326
+ 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()\`.`
327
+ const bytes = Buffer.byteLength(configured, 'utf8')
328
+ 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
329
+ }
330
+
331
+ // 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`.
332
+ function lazySecret(optionSecret: string | undefined): () => string {
333
+ if (optionSecret !== undefined && optionSecret.trim().length === 0)
334
+ throw new Error('prunelle: @prunellejs/auth `secret` is empty: give it 32 random bytes or more, or leave it out and set `AUTH_SECRET`.')
335
+ let resolved: string | undefined
336
+ return () => {
337
+ if (resolved !== undefined)
338
+ return resolved
339
+ const configured = configuredSecret(optionSecret)
340
+ const problem = nodeEnv() === 'production' ? secretProblem(configured) : undefined
341
+ if (problem !== undefined)
342
+ throw new Error(`prunelle: @prunellejs/auth: ${problem}`)
343
+ resolved = configured ?? randomToken(32)
344
+ return resolved
209
345
  }
210
- return configured ?? randomToken(32)
211
346
  }
212
347
 
213
348
  export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptions<TUser> = {}): Auth<TUser> {
214
- const secret = resolveSecret(options.secret)
349
+ const secret = lazySecret(options.secret)
215
350
  const store = options.store ?? memoryAuthStore<TUser>()
216
351
  const basePath = (options.basePath ?? '/auth').replace(/\/$/, '')
217
352
  const cookieName = options.cookieName ?? 'pru_session'
218
353
  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
354
  const tokenTtlMs = (options.tokenTtlSeconds ?? 60 * 15) * 1000
223
355
  const minPasswordLength = options.minPasswordLength ?? 12
356
+ const maxPasswordLength = options.maxPasswordLength ?? DEFAULT_MAX_PASSWORD_LENGTH
224
357
  const defaultRole = options.defaultRole ?? 'user'
225
358
  const defaultRedirect = options.defaultRedirect ?? '/'
226
- const authRouteOpts = {
227
- ...(options.trustedOrigins !== undefined ? { trustedOrigins: options.trustedOrigins } : {}),
228
- ...(options.trustProxy !== undefined ? { trustProxy: options.trustProxy } : {}),
229
- }
359
+ const authRouteOpts = routeOriginOptions(options)
230
360
  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)
361
+ const deliverMail = buildMailDeliverer(options.sendMail, options.mailer)
242
362
  const requireEmailVerification = options.requireEmailVerification !== false
243
363
  let trustProxy = options.trustProxy ?? false
244
364
 
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)
365
+ const pruneIntervalMs = options.pruneIntervalMs === false ? undefined : (options.pruneIntervalMs ?? DEFAULT_PRUNE_INTERVAL_MS)
366
+ const pruneOptions = unverifiedPruneOptions(options.unverifiedTtlSeconds, requireEmailVerification)
367
+ const providers = new Map<string, OAuthProvider>((options.providers ?? []).map(p => [p.id, p]))
368
+ const messages = authFormMessages(minPasswordLength, maxPasswordLength)
252
369
 
253
- const isSecureCookie = (ctx: RequestContext): boolean =>
254
- ctx.url.protocol === 'https:'
255
- || isHttpsRequest(ctx.request, trustProxy)
256
- || nodeEnv() === 'production'
370
+ const isSecureCookie = (ctx: RequestContext): boolean => isSecureRequest(ctx, trustProxy)
257
371
 
258
372
  const sessions = createSessionManager({
259
373
  store,
260
374
  cookieName,
261
- sessionTtlMs,
262
- renewalIntervalMs,
375
+ ...sessionTimings(options),
263
376
  storeIp: options.storeIp ?? 'truncate',
264
377
  storeUserAgent: options.storeUserAgent !== false,
265
378
  getTrustProxy: () => trustProxy,
266
379
  isSecureCookie,
267
380
  })
268
381
 
382
+ const twoFactorRedirect = options.twoFactorRedirect ?? options.totp?.verifyPath ?? `${basePath}/totp/verify`
383
+ const totp = createTotpManager({
384
+ store,
385
+ sessions,
386
+ secret,
387
+ twoFactorCookieName: `${cookieName}_2fa`,
388
+ getDefaultIssuer: () => options.totp?.issuer ?? (site ? new URL(site).hostname : 'Prunelle'),
389
+ isSecureCookie,
390
+ })
391
+ const account = createAccountService(store, sessions, options)
392
+ const passkeys = createPasskeyManager({
393
+ store,
394
+ sessions,
395
+ secret,
396
+ challengeCookieName: `${cookieName}_webauthn`,
397
+ getSite: () => site,
398
+ options: options.passkeys,
399
+ isSecureCookie,
400
+ })
401
+ const orgs = createOrgManager({
402
+ store,
403
+ sessions,
404
+ basePath,
405
+ defaultRedirect,
406
+ orgInviteTtlMs: options.orgInviteTtlSeconds !== undefined ? options.orgInviteTtlSeconds * 1000 : undefined,
407
+ deliverMail,
408
+ })
409
+
269
410
  // One timer per server the plugin runs on: `prunelle dev` starts the next server before it shuts the previous one down.
270
411
  const pruneTimers = new Set<ReturnType<typeof setInterval>>()
271
412
  let activeServers = 0
@@ -274,8 +415,9 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
274
415
  return undefined
275
416
  const timer = setInterval(() => {
276
417
  try {
277
- void Promise.resolve(store.pruneExpired?.()).catch(() => {})
418
+ void Promise.resolve(store.pruneExpired?.(pruneOptions())).catch(() => {})
278
419
  sessions.sweepRenewedAt()
420
+ passkeys.pruneChallenges()
279
421
  }
280
422
  catch {
281
423
  // Ignore prune errors if the underlying store has been closed
@@ -325,12 +467,7 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
325
467
  return toPublicUser(created)
326
468
  }
327
469
 
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
- }
470
+ const mailedLinkOrigin = (url: URL): string | undefined => linkOrigin(site, url)
334
471
 
335
472
  // 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
473
  // The password goes first, so a squatter cannot sign in again between the purge and the update.
@@ -341,90 +478,10 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
341
478
  return claimed
342
479
  }
343
480
 
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
- }
481
+ const links = createLinkService({ store, sessions, basePath, defaultRedirect, tokenTtlMs, deliverMail })
482
+ const { issueLink, sendVerificationEmail, sendMagicLink, consumeLink } = links
385
483
 
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
- }
408
-
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
- }
484
+ const guard = (guardOpts?: GuardOptions<TUser>): Middleware => createAuthGuard(sessions.resolve, orgs, guardOpts)
428
485
 
429
486
  const dispose = (): void => {
430
487
  for (const timer of pruneTimers)
@@ -434,11 +491,64 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
434
491
  void Promise.resolve(store.close?.()).catch(() => {})
435
492
  }
436
493
 
494
+ function registerServerRoutes(api: ServerPluginAPI): void {
495
+ const authLimitsObj = authLimits(createAuthLimiters(api, options.rateLimit), () => trustProxy)
496
+ const authRoute = createAuthRouteRegistrar(api, basePath, authRouteOpts, authLimitsObj)
497
+ const hasMailTransport = deliverMail !== undefined
498
+
499
+ registerAuthRoutes({
500
+ authRoute,
501
+ limits: authLimitsObj,
502
+ store,
503
+ sessions,
504
+ totp,
505
+ twoFactorRedirect,
506
+ minPasswordLength,
507
+ maxPasswordLength,
508
+ messages,
509
+ defaultRedirect,
510
+ requireEmailVerification,
511
+ hasMailTransport,
512
+ mailedLinkOrigin,
513
+ createUser,
514
+ insertUser,
515
+ claimUnverified,
516
+ issueLink,
517
+ consumeLink,
518
+ sendMagicLink,
519
+ })
520
+ 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 })
523
+ registerAccountRoutes({ authRoute, sessions, account, clearPendingCookie: ctx => totp.clearPendingCookie(ctx) })
524
+ registerOAuthRoutes({
525
+ route: (method, path, handler) => api.route(method, path, handler),
526
+ store,
527
+ providers,
528
+ secret,
529
+ site,
530
+ basePath,
531
+ stateCookieName: oauthCookieName,
532
+ defaultRedirect,
533
+ requireEmailVerification,
534
+ hasMailTransport,
535
+ mailedLinkOrigin,
536
+ issueLink,
537
+ limitIp: authLimitsObj.limitIp,
538
+ isSecureCookie,
539
+ claimUnverified,
540
+ insertUser,
541
+ storeProfile: options.storeOAuthProfile === true,
542
+ createSessionForUser: sessions.createSessionForUser,
543
+ observeAsync: sessions.observeAsync,
544
+ })
545
+ }
546
+
437
547
  const plugin: PrunellePlugin = definePlugin({
438
548
  name: '@prunellejs/auth',
439
549
  enforce: 'pre',
440
- providesLocals: ['user', 'session'],
441
- requires: () => isKeptInMemory(store) ? [STORE_IN_MEMORY] : [],
550
+ providesLocals: ['user', 'session', 'org', 'orgMembership'],
551
+ requires: () => [isKeptInMemory(store) ? STORE_IN_MEMORY : undefined, requireEmailVerification && deliverMail === undefined ? NO_MAILER : undefined, secretProblem(configuredSecret(options.secret))].filter(line => line !== undefined),
442
552
  server(api) {
443
553
  if (options.trustProxy === undefined)
444
554
  trustProxy = api.trustProxy
@@ -457,64 +567,20 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
457
567
  await store.close?.()
458
568
  })
459
569
 
460
- // Sync stores resolve lazily on first read of ctx.locals.user/session; async stores resolve before next().
570
+ // Sync stores resolve lazily on first read of ctx.locals.user/session; async or unknown Promise-returning stores await before next().
461
571
  const internalPrefix = `${api.assetPrefix.replace(/\/$/, '')}/`
462
572
  const actionPrefix = `${internalPrefix}action/`
463
573
  api.use((ctx, next) => {
464
574
  const p = ctx.url.pathname
465
575
  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
- }
576
+ const pending = sessions.prepareRequest(ctx)
577
+ if (pending !== undefined)
578
+ return pending.then(() => next())
473
579
  }
474
580
  return next()
475
581
  }, { scope: 'rendered' })
476
582
 
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
- })
583
+ registerServerRoutes(api)
518
584
  },
519
585
  })
520
586
 
@@ -524,28 +590,40 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
524
590
  basePath,
525
591
  getUser: sessions.getUser,
526
592
  getSession: sessions.getSession,
593
+ formMessage: url => readFormMessage(messages, url),
527
594
  resolve: sessions.resolve,
528
595
  guard,
529
596
  createUser,
530
- createSessionForUser: sessions.createSessionForUser,
597
+ createSessionForUser: (userId, ctx) => sessions.createSessionForUser(userId, ctx),
531
598
  signOut: sessions.signOut,
532
- async revokeAllSessions(userId) {
533
- await sessions.observeAsync(store.deleteUserSessions(userId))
534
- },
599
+ revokeAllSessions: async (userId) => { await sessions.observeAsync(store.deleteUserSessions(userId)) },
535
600
  sendMagicLink,
536
601
  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
- },
602
+ setupTotp: totp.setupTotp,
603
+ confirmTotp: totp.confirmTotp,
604
+ verifyTotp: totp.verifyTotp,
605
+ disableTotp: totp.disableTotp,
606
+ regenerateRecoveryCodes: totp.regenerateRecoveryCodes,
607
+ listPasskeys: passkeys.listPasskeys,
608
+ deletePasskey: passkeys.deletePasskey,
609
+ createOrg: orgs.createOrg,
610
+ getOrg: orgs.getOrg,
611
+ listUserOrgs: orgs.listUserOrgs,
612
+ listOrgMembers: orgs.listOrgMembers,
613
+ addOrgMember: orgs.addOrgMember,
614
+ updateOrgMemberRole: orgs.updateOrgMemberRole,
615
+ removeOrgMember: orgs.removeOrgMember,
616
+ inviteToOrg: orgs.inviteToOrg,
617
+ acceptOrgInvite: orgs.acceptOrgInvite,
618
+ revokeOrgInvite: orgs.revokeOrgInvite,
619
+ deleteOrg: orgs.deleteOrg,
620
+ listSessions: async userId => await sessions.observeAsync(store.listSessions(userId)),
621
+ exportUser: account.exportUser,
622
+ deleteUser: account.deleteUser,
546
623
  async pruneExpired() {
547
- await store.pruneExpired?.()
624
+ await store.pruneExpired?.(pruneOptions())
548
625
  sessions.sweepRenewedAt()
626
+ passkeys.pruneChallenges()
549
627
  },
550
628
  dispose,
551
629
  }