@prunellejs/auth 0.6.0 → 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
@@ -5,6 +5,7 @@
5
5
 
6
6
  import type { PrunellePlugin, ServerPluginAPI } from 'prunelle/config'
7
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 { CreateOrgInput, InviteToOrgInput } from './orgs'
10
11
  import type { PasskeyOptions } from './passkeys'
@@ -16,6 +17,7 @@ import type {
16
17
  OrgInvitation,
17
18
  OrgMembership,
18
19
  PasskeySummary,
20
+ PruneOptions,
19
21
  PublicUser,
20
22
  UserExport,
21
23
  UserOrgSummary,
@@ -24,14 +26,16 @@ import type { TotpOptions } from './totp'
24
26
  import { definePlugin } from 'prunelle/config'
25
27
  import { isHttpsRequest, nodeEnv } from 'prunelle/server'
26
28
  import { hashPassword, randomToken } from './crypto'
27
- import { authLimits, createAuthRouteRegistrar, isValidEmail } from './http'
29
+ import { authLimits, createAuthLimiters, createAuthRouteRegistrar, isValidEmail } from './http'
28
30
  import { buildMailDeliverer, createLinkService } from './links'
29
31
  import { registerOAuthRoutes } from './oauth-routes'
30
32
  import { registerOrgRoutes } from './org-routes'
31
33
  import { createAuthGuard, createOrgManager } from './orgs'
32
34
  import { registerPasskeyRoutes } from './passkey-routes'
35
+ import { createAccountService, registerAccountRoutes } from './account'
33
36
  import { createPasskeyManager } from './passkeys'
34
37
  import { registerAuthRoutes } from './routes'
38
+ import { authFormMessages, readFormMessage } from './form-messages'
35
39
  import { createSessionManager } from './session'
36
40
  import { isKeptInMemory, memoryAuthStore, normalizeEmail, toPublicUser } from './store'
37
41
  import { createTotpManager } from './totp'
@@ -47,13 +51,19 @@ declare module 'prunelle/server' {
47
51
  }
48
52
 
49
53
  export interface RateLimitOptions {
50
- /** Attempts per window, per scope and address and per scope and email (default: 15). */
54
+ /** Attempts per window, per scope and address (default: 15). */
51
55
  max?: number | undefined
52
56
  /** Window duration in ms (default: 60_000). */
53
57
  windowMs?: number | undefined
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
54
62
  }
55
63
 
64
+ export { FRESH_SIGNIN_MS } from './account'
56
65
  export { safeRedirect } from 'prunelle/server'
66
+ export type { AuthFormCode, AuthFormMessage } from './form-messages'
57
67
  export { discord, github, google, oauthProvider } from './oauth'
58
68
  export type { OAuthPresetConfig, OAuthProfile, OAuthProvider } from './oauth'
59
69
  export type { CreateOrgInput, InviteToOrgInput } from './orgs'
@@ -70,6 +80,7 @@ export type {
70
80
  OrgMembership,
71
81
  PasskeyRecord,
72
82
  PasskeySummary,
83
+ PruneOptions,
73
84
  PublicUser,
74
85
  RecoveryCodeRecord,
75
86
  TokenKind,
@@ -87,6 +98,13 @@ const DEFAULT_PRUNE_INTERVAL_MS = 15 * 60 * 1000
87
98
  const MIN_PROD_SECRET_BYTES = 32
88
99
  const DEFAULT_MAX_PASSWORD_LENGTH = 1024
89
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
+ }
107
+
90
108
  // Mailed links and OAuth callbacks start with `site`, so anything but an http(s) origin is a config mistake.
91
109
  function siteOrigin(value: string): string {
92
110
  const url = new URL(value)
@@ -136,14 +154,18 @@ export interface AuthOptions<TUser extends AuthUser = AuthUser> {
136
154
  secret?: string | undefined
137
155
  /** Route prefix (default: '/auth'). */
138
156
  basePath?: string | undefined
139
- /** 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. */
140
158
  cookieName?: string | undefined
141
159
  /** Session lifetime in seconds (default: 30 days). */
142
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
143
163
  /** Minimum interval in seconds between sliding-expiry DB writes for the same session (default: up to 1 hour). */
144
164
  renewalIntervalSeconds?: number | undefined
145
165
  /** Magic-link / verification token lifetime in seconds (default: 15 minutes). */
146
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
147
169
  /** Minimum password length (default: 12, aligned with CNIL guidance). */
148
170
  minPasswordLength?: number | undefined
149
171
  /** Maximum password length in characters / UTF-8 bytes before Argon2id hashing (default: 1024). */
@@ -162,6 +184,10 @@ export interface AuthOptions<TUser extends AuthUser = AuthUser> {
162
184
  mailer?: AuthMailer | undefined
163
185
  /** Custom mail sender for magic links / verification emails (overrides `mailer` when both are provided). */
164
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
165
191
  /**
166
192
  * Require email verification before opening a session on password sign-up / sign-in (default: `true`).
167
193
  * Set explicitly to `false` only when you intentionally allow unverified password sessions (e.g. local dev without mail).
@@ -183,6 +209,8 @@ export interface AuthOptions<TUser extends AuthUser = AuthUser> {
183
209
  * - `false`: do not record IP on sessions
184
210
  */
185
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
186
214
  /** Whether to record the `User-Agent` header on sessions (default: `true`). */
187
215
  storeUserAgent?: boolean | undefined
188
216
  /** TOTP second-factor configuration (`issuer`, `verifyPath`). */
@@ -217,6 +245,8 @@ export interface Auth<TUser extends AuthUser = AuthUser> extends PrunellePlugin
217
245
  readonly basePath: string
218
246
  getUser(ctx: { locals: PrunelleLocals }): PublicUser<TUser> | undefined
219
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
220
250
  resolve(ctx: RequestContext): Promise<{ user: PublicUser<TUser>, session: AuthSession } | undefined>
221
251
  guard(options?: GuardOptions<TUser>): Middleware
222
252
  createUser(input: CreateUserInput<TUser>): Promise<PublicUser<TUser>>
@@ -250,64 +280,99 @@ export interface Auth<TUser extends AuthUser = AuthUser> extends PrunellePlugin
250
280
  dispose(): void
251
281
  }
252
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
+
253
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`.'
254
306
 
255
- function resolveSecret(optionSecret: string | undefined): string {
256
- if (optionSecret !== undefined && optionSecret.trim().length === 0)
257
- 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
+ }
258
317
 
318
+ function configuredSecret(optionSecret: string | undefined): string | undefined {
259
319
  const envSecret = process.env.AUTH_SECRET
260
- const configured = optionSecret ?? (envSecret && envSecret.trim().length > 0 ? envSecret : undefined)
261
- if (nodeEnv() === 'production') {
262
- if (configured === undefined)
263
- throw new Error('[prunelle/auth] `secret` (or `AUTH_SECRET` env) is required in production and must be at least 32 bytes')
264
- if (Buffer.byteLength(configured, 'utf8') < MIN_PROD_SECRET_BYTES)
265
- 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
266
345
  }
267
- return configured ?? randomToken(32)
268
346
  }
269
347
 
270
348
  export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptions<TUser> = {}): Auth<TUser> {
271
- const secret = resolveSecret(options.secret)
349
+ const secret = lazySecret(options.secret)
272
350
  const store = options.store ?? memoryAuthStore<TUser>()
273
351
  const basePath = (options.basePath ?? '/auth').replace(/\/$/, '')
274
352
  const cookieName = options.cookieName ?? 'pru_session'
275
353
  const oauthCookieName = `${cookieName}_oauth`
276
- const sessionTtlSeconds = options.sessionTtlSeconds ?? 60 * 60 * 24 * 30
277
- const sessionTtlMs = sessionTtlSeconds * 1000
278
- const renewalIntervalMs = Math.max(0, (options.renewalIntervalSeconds ?? Math.min(60 * 60, Math.max(1, Math.floor(sessionTtlSeconds / 4)))) * 1000)
279
354
  const tokenTtlMs = (options.tokenTtlSeconds ?? 60 * 15) * 1000
280
355
  const minPasswordLength = options.minPasswordLength ?? 12
281
356
  const maxPasswordLength = options.maxPasswordLength ?? DEFAULT_MAX_PASSWORD_LENGTH
282
357
  const defaultRole = options.defaultRole ?? 'user'
283
358
  const defaultRedirect = options.defaultRedirect ?? '/'
284
- const authRouteOpts = {
285
- ...(options.trustedOrigins !== undefined ? { trustedOrigins: options.trustedOrigins } : {}),
286
- ...(options.trustProxy !== undefined ? { trustProxy: options.trustProxy } : {}),
287
- }
359
+ const authRouteOpts = routeOriginOptions(options)
288
360
  let site = options.site !== undefined ? siteOrigin(options.site) : undefined
289
361
  const deliverMail = buildMailDeliverer(options.sendMail, options.mailer)
290
362
  const requireEmailVerification = options.requireEmailVerification !== false
291
363
  let trustProxy = options.trustProxy ?? false
292
364
 
293
- const pruneIntervalMs = options.pruneIntervalMs === false
294
- ? undefined
295
- : (options.pruneIntervalMs ?? DEFAULT_PRUNE_INTERVAL_MS)
296
-
297
- const providers = new Map<string, OAuthProvider>()
298
- for (const p of options.providers ?? [])
299
- 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)
300
369
 
301
- const isSecureCookie = (ctx: RequestContext): boolean =>
302
- ctx.url.protocol === 'https:'
303
- || isHttpsRequest(ctx.request, trustProxy)
304
- || nodeEnv() === 'production'
370
+ const isSecureCookie = (ctx: RequestContext): boolean => isSecureRequest(ctx, trustProxy)
305
371
 
306
372
  const sessions = createSessionManager({
307
373
  store,
308
374
  cookieName,
309
- sessionTtlMs,
310
- renewalIntervalMs,
375
+ ...sessionTimings(options),
311
376
  storeIp: options.storeIp ?? 'truncate',
312
377
  storeUserAgent: options.storeUserAgent !== false,
313
378
  getTrustProxy: () => trustProxy,
@@ -323,6 +388,7 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
323
388
  getDefaultIssuer: () => options.totp?.issuer ?? (site ? new URL(site).hostname : 'Prunelle'),
324
389
  isSecureCookie,
325
390
  })
391
+ const account = createAccountService(store, sessions, options)
326
392
  const passkeys = createPasskeyManager({
327
393
  store,
328
394
  sessions,
@@ -349,7 +415,7 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
349
415
  return undefined
350
416
  const timer = setInterval(() => {
351
417
  try {
352
- void Promise.resolve(store.pruneExpired?.()).catch(() => {})
418
+ void Promise.resolve(store.pruneExpired?.(pruneOptions())).catch(() => {})
353
419
  sessions.sweepRenewedAt()
354
420
  passkeys.pruneChallenges()
355
421
  }
@@ -401,12 +467,7 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
401
467
  return toPublicUser(created)
402
468
  }
403
469
 
404
- // The request URL comes from the Host header, which the client controls: a link mailed to a victim must not point at it.
405
- function mailedLinkOrigin(url: URL): string | undefined {
406
- if (site !== undefined)
407
- return site
408
- return LOOPBACK_HOSTS.has(url.hostname) ? url.origin : undefined
409
- }
470
+ const mailedLinkOrigin = (url: URL): string | undefined => linkOrigin(site, url)
410
471
 
411
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.
412
473
  // The password goes first, so a squatter cannot sign in again between the purge and the update.
@@ -418,7 +479,7 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
418
479
  }
419
480
 
420
481
  const links = createLinkService({ store, sessions, basePath, defaultRedirect, tokenTtlMs, deliverMail })
421
- const { issueLink, sendVerificationEmail, sendMagicLink, consumeLink, equalizeSignupMailDelay } = links
482
+ const { issueLink, sendVerificationEmail, sendMagicLink, consumeLink } = links
422
483
 
423
484
  const guard = (guardOpts?: GuardOptions<TUser>): Middleware => createAuthGuard(sessions.resolve, orgs, guardOpts)
424
485
 
@@ -431,24 +492,24 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
431
492
  }
432
493
 
433
494
  function registerServerRoutes(api: ServerPluginAPI): void {
434
- const limits = options.rateLimit === false ? undefined : api.rateLimiter({ max: options.rateLimit?.max ?? 15, windowMs: options.rateLimit?.windowMs ?? 60_000 })
435
- const authLimitsObj = authLimits(limits, () => trustProxy)
495
+ const authLimitsObj = authLimits(createAuthLimiters(api, options.rateLimit), () => trustProxy)
436
496
  const authRoute = createAuthRouteRegistrar(api, basePath, authRouteOpts, authLimitsObj)
437
497
  const hasMailTransport = deliverMail !== undefined
438
498
 
439
499
  registerAuthRoutes({
440
500
  authRoute,
501
+ limits: authLimitsObj,
441
502
  store,
442
503
  sessions,
443
504
  totp,
444
505
  twoFactorRedirect,
445
506
  minPasswordLength,
446
507
  maxPasswordLength,
508
+ messages,
447
509
  defaultRedirect,
448
510
  requireEmailVerification,
449
511
  hasMailTransport,
450
512
  mailedLinkOrigin,
451
- equalizeSignupMailDelay,
452
513
  createUser,
453
514
  insertUser,
454
515
  claimUnverified,
@@ -456,9 +517,10 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
456
517
  consumeLink,
457
518
  sendMagicLink,
458
519
  })
459
- registerTotpRoutes({ authRoute, store, sessions, totp, basePath, defaultRedirect })
520
+ registerTotpRoutes({ authRoute, store, sessions, totp, basePath, defaultRedirect, messages })
460
521
  registerPasskeyRoutes({ authRoute, store, sessions, passkeys, totp, defaultRedirect, requireEmailVerification })
461
522
  registerOrgRoutes({ authRoute, sessions, orgs, defaultRedirect, hasMailTransport, mailedLinkOrigin })
523
+ registerAccountRoutes({ authRoute, sessions, account, clearPendingCookie: ctx => totp.clearPendingCookie(ctx) })
462
524
  registerOAuthRoutes({
463
525
  route: (method, path, handler) => api.route(method, path, handler),
464
526
  store,
@@ -476,6 +538,7 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
476
538
  isSecureCookie,
477
539
  claimUnverified,
478
540
  insertUser,
541
+ storeProfile: options.storeOAuthProfile === true,
479
542
  createSessionForUser: sessions.createSessionForUser,
480
543
  observeAsync: sessions.observeAsync,
481
544
  })
@@ -485,7 +548,7 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
485
548
  name: '@prunellejs/auth',
486
549
  enforce: 'pre',
487
550
  providesLocals: ['user', 'session', 'org', 'orgMembership'],
488
- requires: () => isKeptInMemory(store) ? [STORE_IN_MEMORY] : [],
551
+ requires: () => [isKeptInMemory(store) ? STORE_IN_MEMORY : undefined, requireEmailVerification && deliverMail === undefined ? NO_MAILER : undefined, secretProblem(configuredSecret(options.secret))].filter(line => line !== undefined),
489
552
  server(api) {
490
553
  if (options.trustProxy === undefined)
491
554
  trustProxy = api.trustProxy
@@ -527,6 +590,7 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
527
590
  basePath,
528
591
  getUser: sessions.getUser,
529
592
  getSession: sessions.getSession,
593
+ formMessage: url => readFormMessage(messages, url),
530
594
  resolve: sessions.resolve,
531
595
  guard,
532
596
  createUser,
@@ -554,10 +618,10 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
554
618
  revokeOrgInvite: orgs.revokeOrgInvite,
555
619
  deleteOrg: orgs.deleteOrg,
556
620
  listSessions: async userId => await sessions.observeAsync(store.listSessions(userId)),
557
- exportUser: async userId => await sessions.observeAsync(store.exportUser(userId)),
558
- deleteUser: async (userId) => { await sessions.observeAsync(store.deleteUser(userId)) },
621
+ exportUser: account.exportUser,
622
+ deleteUser: account.deleteUser,
559
623
  async pruneExpired() {
560
- await store.pruneExpired?.()
624
+ await store.pruneExpired?.(pruneOptions())
561
625
  sessions.sweepRenewedAt()
562
626
  passkeys.pruneChallenges()
563
627
  },
package/src/links.ts CHANGED
@@ -7,8 +7,6 @@ import { safeEqual, safeRedirect } from 'prunelle/server'
7
7
  import { randomToken, sha256Hex } from './crypto'
8
8
  import { normalizeEmail } from './store'
9
9
 
10
- const MAIL_DELAY_MIN_MS = 5
11
- const MAIL_DELAY_MAX_MS = 2000
12
10
  const LINK_PATHS = { 'magic-link': 'magic-link/verify', 'verify-email': 'verify-email' } as const
13
11
  const LINK_MAILS = {
14
12
  'magic-link': { subject: 'Your sign-in link', text: 'Sign in using this one-time link', html: 'Click to sign in', label: 'Sign in' },
@@ -33,21 +31,11 @@ export function buildMailDeliverer(
33
31
  }
34
32
  }
35
33
 
36
- function createMailDelayTracker(): { observe: (ms: number) => void, pad: () => Promise<void> } {
37
- let ewmaMs: number | undefined
38
- return {
39
- observe(ms: number) {
40
- const clamped = Math.min(MAIL_DELAY_MAX_MS, Math.max(0, ms))
41
- ewmaMs = ewmaMs === undefined ? clamped : ewmaMs * 0.7 + clamped * 0.3
42
- },
43
- async pad() {
44
- if (ewmaMs === undefined || ewmaMs < MAIL_DELAY_MIN_MS)
45
- return
46
- const jittered = Math.min(MAIL_DELAY_MAX_MS, Math.round(ewmaMs * (0.85 + Math.random() * 0.3)))
47
- if (jittered >= MAIL_DELAY_MIN_MS)
48
- await Bun.sleep(jittered)
49
- },
50
- }
34
+ type MailDeliverer = (mail: AuthMailPayload) => void | Promise<void>
35
+
36
+ /** A mail sent after the response, so a taken and a new address take the same time to answer; `onFailure` undoes what the sign-up did when it cannot be sent. */
37
+ export interface MailInBackground {
38
+ onFailure: () => void | Promise<void>
51
39
  }
52
40
 
53
41
  export interface LinkServiceDeps<TUser extends AuthUser = AuthUser> {
@@ -61,7 +49,6 @@ export interface LinkServiceDeps<TUser extends AuthUser = AuthUser> {
61
49
 
62
50
  export function createLinkService<TUser extends AuthUser = AuthUser>(deps: LinkServiceDeps<TUser>) {
63
51
  const { store, sessions, basePath, defaultRedirect, tokenTtlMs, deliverMail } = deps
64
- const mailDelay = createMailDelayTracker()
65
52
 
66
53
  async function issueLink(
67
54
  kind: 'magic-link' | 'verify-email',
@@ -69,6 +56,7 @@ export function createLinkService<TUser extends AuthUser = AuthUser>(deps: LinkS
69
56
  email: string,
70
57
  origin: string | undefined,
71
58
  redirectTo: string | undefined,
59
+ background?: MailInBackground,
72
60
  ): Promise<string> {
73
61
  const normalized = normalizeEmail(email)
74
62
  const boundUser = kind === 'verify-email' && userId !== undefined ? await sessions.observeAsync(store.getUserById(userId)) : undefined
@@ -87,30 +75,47 @@ export function createLinkService<TUser extends AuthUser = AuthUser>(deps: LinkS
87
75
  const url = origin !== undefined ? `${origin.replace(/\/$/, '')}${path}` : path
88
76
 
89
77
  if (deliverMail && origin !== undefined) {
90
- const mail = LINK_MAILS[kind]
91
- const startedAt = performance.now()
78
+ const delivery = deliverLink(deliverMail, kind, normalized, url, tokenHash)
79
+ if (background === undefined)
80
+ await delivery
81
+ else
82
+ void delivery.catch(err => failBackgroundMail(err, background))
83
+ }
84
+ return url
85
+ }
86
+
87
+ // Mails the link; a mail that cannot be sent takes its token back, so a link that never arrived cannot be used.
88
+ async function deliverLink(send: MailDeliverer, kind: 'magic-link' | 'verify-email', to: string, url: string, tokenHash: string): Promise<void> {
89
+ const mail = LINK_MAILS[kind]
90
+ try {
91
+ await send({
92
+ to,
93
+ subject: mail.subject,
94
+ text: `${mail.text}: ${url}`,
95
+ html: `<p>${mail.html}: <a href="${url}">${mail.label}</a></p>`,
96
+ url,
97
+ kind,
98
+ })
99
+ }
100
+ catch (err) {
92
101
  try {
93
- await deliverMail({
94
- to: normalized,
95
- subject: mail.subject,
96
- text: `${mail.text}: ${url}`,
97
- html: `<p>${mail.html}: <a href="${url}">${mail.label}</a></p>`,
98
- url,
99
- kind,
100
- })
101
- mailDelay.observe(performance.now() - startedAt)
102
+ await sessions.observeAsync(store.consumeToken(tokenHash, kind))
102
103
  }
103
- catch (err) {
104
- try {
105
- await sessions.observeAsync(store.consumeToken(tokenHash, kind))
106
- }
107
- catch (cleanupErr) {
108
- console.error('[prunelle/auth] failed to clean up token after mail error:', cleanupErr)
109
- }
110
- throw err
104
+ catch (cleanupErr) {
105
+ console.error('[prunelle/auth] failed to clean up token after mail error:', cleanupErr)
111
106
  }
107
+ throw err
108
+ }
109
+ }
110
+
111
+ async function failBackgroundMail(err: unknown, background: MailInBackground): Promise<void> {
112
+ console.error('[prunelle/auth] could not send a verification mail:', err)
113
+ try {
114
+ await background.onFailure()
115
+ }
116
+ catch (rollbackErr) {
117
+ console.error('[prunelle/auth] failed to roll back after a mail error:', rollbackErr)
112
118
  }
113
- return url
114
119
  }
115
120
 
116
121
  async function sendVerificationEmail(email: string, origin: string, redirectTo?: string): Promise<string> {
@@ -145,6 +150,5 @@ export function createLinkService<TUser extends AuthUser = AuthUser>(deps: LinkS
145
150
  sendVerificationEmail,
146
151
  sendMagicLink,
147
152
  consumeLink,
148
- equalizeSignupMailDelay: () => deliverMail ? mailDelay.pad() : Promise.resolve(),
149
153
  }
150
154
  }
@@ -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 { pkceChallenge, randomToken, signPayload, verifyPayload } from './crypto'
8
- import { fail, withNoStore } from './http'
8
+ import { authCookie, fail, withNoStore } from './http'
9
9
  import { OAUTH_FETCH_TIMEOUT_MS } from './oauth'
10
10
  import { normalizeEmail, toPublicUser } from './store'
11
11
 
@@ -21,7 +21,8 @@ export interface OAuthRouteDeps<TUser extends AuthUser = AuthUser> {
21
21
  route: (method: string, path: string, handler: (ctx: RequestContext) => Response | Promise<Response>) => void
22
22
  store: AuthStore<TUser>
23
23
  providers: ReadonlyMap<string, OAuthProvider>
24
- secret: string
24
+ /** The app's signing secret, resolved at first use. */
25
+ secret: () => string
25
26
  site: string | undefined
26
27
  basePath: string
27
28
  stateCookieName: string
@@ -34,10 +35,22 @@ export interface OAuthRouteDeps<TUser extends AuthUser = AuthUser> {
34
35
  isSecureCookie: (ctx: RequestContext) => boolean
35
36
  claimUnverified: (user: TUser) => Promise<TUser>
36
37
  insertUser: (fields: Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>) => Promise<TUser>
38
+ /** Keep the provider's name and avatar URL on a new account. */
39
+ storeProfile: boolean
37
40
  createSessionForUser: (userId: string, ctx: RequestContext, knownUser?: PublicUser<TUser>) => Promise<unknown>
38
41
  observeAsync: <T>(value: T | Promise<T>) => T | Promise<T>
39
42
  }
40
43
 
44
+ // The provider's name and avatar belong to the account only when the app asked to keep them.
45
+ function profileFields(deps: Pick<OAuthRouteDeps, 'storeProfile'>, profile: OAuthProfile): { name?: string, avatarUrl?: string } {
46
+ if (!deps.storeProfile)
47
+ return {}
48
+ return {
49
+ ...(profile.name !== undefined ? { name: profile.name } : {}),
50
+ ...(profile.avatarUrl !== undefined ? { avatarUrl: profile.avatarUrl } : {}),
51
+ }
52
+ }
53
+
41
54
  async function handleUnverifiedOAuthSignup<TUser extends AuthUser>(
42
55
  deps: OAuthRouteDeps<TUser>,
43
56
  ctx: RequestContext,
@@ -49,12 +62,7 @@ async function handleUnverifiedOAuthSignup<TUser extends AuthUser>(
49
62
  console.error(`[prunelle/auth] refusing to mail a verification link for host ${ctx.url.host}: set the auth \`site\` option to the public origin`)
50
63
  return fail(ctx, 500, 'Verification links are not configured')
51
64
  }
52
- const created = await deps.insertUser({
53
- email: profile.email,
54
- ...(profile.name !== undefined ? { name: profile.name } : {}),
55
- ...(profile.avatarUrl !== undefined ? { avatarUrl: profile.avatarUrl } : {}),
56
- emailVerified: false,
57
- } as Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>)
65
+ const created = await deps.insertUser({ ...profileFields(deps, profile), email: profile.email, emailVerified: false } as Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>)
58
66
  try {
59
67
  await deps.issueLink('verify-email', created.id, created.email, linkOrigin, redirectTarget)
60
68
  }
@@ -108,12 +116,7 @@ async function resolveOAuthUser<TUser extends AuthUser>(
108
116
  else if (!byEmail) {
109
117
  if (requireEmailVerification && !profile.emailVerified)
110
118
  return handleUnverifiedOAuthSignup(deps, ctx, profile, redirectTarget)
111
- userRecord = await deps.insertUser({
112
- email: profile.email,
113
- ...(profile.name !== undefined ? { name: profile.name } : {}),
114
- ...(profile.avatarUrl !== undefined ? { avatarUrl: profile.avatarUrl } : {}),
115
- emailVerified: profile.emailVerified,
116
- } as Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>)
119
+ userRecord = await deps.insertUser({ ...profileFields(deps, profile), email: profile.email, emailVerified: profile.emailVerified } as Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>)
117
120
  }
118
121
  else {
119
122
  return fail(ctx, 409, 'An account with this email already exists; verify email to link')
@@ -150,7 +153,7 @@ export function registerOAuthRoutes<TUser extends AuthUser = AuthUser>(deps: OAu
150
153
  const verifier = provider.pkce !== false ? randomToken(32) : undefined
151
154
  const redirectTarget = safeRedirect(ctx.url.searchParams.get('redirect') ?? ctx.url.searchParams.get('next'), defaultRedirect)
152
155
 
153
- const cookieVal = signPayload(secret, {
156
+ const cookieVal = signPayload(secret(), {
154
157
  provider: provider.id,
155
158
  state,
156
159
  verifier,
@@ -158,13 +161,7 @@ export function registerOAuthRoutes<TUser extends AuthUser = AuthUser>(deps: OAu
158
161
  exp: Date.now() + 10 * 60 * 1000,
159
162
  } satisfies OAuthStateCookie)
160
163
 
161
- ctx.cookies.set(stateCookieName, cookieVal, {
162
- path: '/',
163
- httpOnly: true,
164
- sameSite: 'lax',
165
- secure: deps.isSecureCookie(ctx),
166
- maxAge: 600,
167
- })
164
+ ctx.cookies.set(stateCookieName, cookieVal, authCookie(deps.isSecureCookie(ctx), 600))
168
165
 
169
166
  const callbackUrl = callbackUrlFor(ctx, provider)
170
167
  const authUrl = new URL(provider.authorizeUrl)
@@ -177,7 +174,7 @@ export function registerOAuthRoutes<TUser extends AuthUser = AuthUser>(deps: OAu
177
174
  authUrl.searchParams.set('code_challenge', pkceChallenge(verifier))
178
175
  authUrl.searchParams.set('code_challenge_method', 'S256')
179
176
  }
180
- return ctx.redirect(authUrl.toString(), 302)
177
+ return ctx.redirect(authUrl.toString(), 302, { external: true })
181
178
  })
182
179
 
183
180
  noStoreRoute('GET', `${basePath}/oauth/:provider/callback`, async (ctx) => {
@@ -197,7 +194,7 @@ export function registerOAuthRoutes<TUser extends AuthUser = AuthUser>(deps: OAu
197
194
  if (!code || !returnedState || !rawCookie)
198
195
  return fail(ctx, 400, 'Invalid OAuth callback parameters')
199
196
 
200
- const saved = verifyPayload<OAuthStateCookie>(secret, rawCookie)
197
+ const saved = verifyPayload<OAuthStateCookie>(secret(), rawCookie)
201
198
  if (!saved || saved.exp <= Date.now() || saved.provider !== provider.id || !safeEqual(saved.state, returnedState))
202
199
  return fail(ctx, 400, 'Invalid or expired OAuth state')
203
200
 
package/src/org-routes.ts CHANGED
@@ -132,7 +132,7 @@ export function registerOrgRoutes<TUser extends AuthUser = AuthUser>(deps: OrgRo
132
132
  }
133
133
  })
134
134
 
135
- authRoute('POST', '/orgs/invite', { limit: 'orgs-invite', emailLimit: 'orgs-invite', readBody: true }, async (ctx, body) => {
135
+ authRoute('POST', '/orgs/invite', { limit: 'orgs-invite', mailLimit: 'orgs-invite', readBody: true }, async (ctx, body) => {
136
136
  const resolved = await sessions.resolve(ctx)
137
137
  if (!resolved)
138
138
  return fail(ctx, 401, 'Authentication required')
package/src/orgs.ts CHANGED
@@ -22,6 +22,23 @@ function orgError(status: number, message: string): OrgError {
22
22
  return err
23
23
  }
24
24
 
25
+ // The orgs a user's deletion takes with it, those they are the only member of; throws 409 when they are the last owner of an org others still belong to.
26
+ export async function orgsDeletedWithUser<TUser extends AuthUser>(store: AuthStore<TUser>, userId: string): Promise<string[]> {
27
+ if (!store.listUserOrgMemberships || !store.listOrgMembers)
28
+ return []
29
+ const deleted: string[] = []
30
+ for (const { org, role } of await store.listUserOrgMemberships(userId)) {
31
+ if (role !== 'owner')
32
+ continue
33
+ const members = await store.listOrgMembers(org.id)
34
+ if (members.length === 1)
35
+ deleted.push(org.id)
36
+ else if (members.filter(m => m.role === 'owner').length === 1)
37
+ throw orgError(409, `prunelle: this account is the last owner of "${org.name}": make another member owner, or delete the organization, before deleting the account`)
38
+ }
39
+ return deleted
40
+ }
41
+
25
42
  export function slugifyOrgName(name: string): string {
26
43
  return name
27
44
  .normalize('NFKD')