@prunellejs/auth 0.1.1 → 0.6.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,25 +3,46 @@
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
8
  import type { OAuthProvider } from './oauth'
9
-
10
- import type { AuthSession, AuthStore, AuthUser, PublicUser, UserExport } from './store'
9
+ import type { CreateOrgInput, InviteToOrgInput } from './orgs'
10
+ import type { PasskeyOptions } from './passkeys'
11
+ import type {
12
+ AuthSession,
13
+ AuthStore,
14
+ AuthUser,
15
+ Organization,
16
+ OrgInvitation,
17
+ OrgMembership,
18
+ PasskeySummary,
19
+ PublicUser,
20
+ UserExport,
21
+ UserOrgSummary,
22
+ } from './store'
23
+ import type { TotpOptions } from './totp'
11
24
  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'
25
+ import { isHttpsRequest, nodeEnv } from 'prunelle/server'
26
+ import { hashPassword, randomToken } from './crypto'
27
+ import { authLimits, createAuthRouteRegistrar, isValidEmail } from './http'
28
+ import { buildMailDeliverer, createLinkService } from './links'
15
29
  import { registerOAuthRoutes } from './oauth-routes'
16
-
30
+ import { registerOrgRoutes } from './org-routes'
31
+ import { createAuthGuard, createOrgManager } from './orgs'
32
+ import { registerPasskeyRoutes } from './passkey-routes'
33
+ import { createPasskeyManager } from './passkeys'
17
34
  import { registerAuthRoutes } from './routes'
18
35
  import { createSessionManager } from './session'
19
36
  import { isKeptInMemory, memoryAuthStore, normalizeEmail, toPublicUser } from './store'
37
+ import { createTotpManager } from './totp'
38
+ import { registerTotpRoutes } from './totp-routes'
20
39
 
21
40
  declare module 'prunelle/server' {
22
41
  interface PrunelleLocals {
23
42
  user?: PublicUser | undefined
24
43
  session?: AuthSession | undefined
44
+ org?: Organization | undefined
45
+ orgMembership?: OrgMembership | undefined
25
46
  }
26
47
  }
27
48
 
@@ -30,40 +51,41 @@ export interface RateLimitOptions {
30
51
  max?: number | undefined
31
52
  /** Window duration in ms (default: 60_000). */
32
53
  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 }
51
54
  }
52
55
 
53
56
  export { safeRedirect } from 'prunelle/server'
54
57
  export { discord, github, google, oauthProvider } from './oauth'
55
58
  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'
59
+ export type { CreateOrgInput, InviteToOrgInput } from './orgs'
60
+ export type { PasskeyOptions, PasskeyUserVerification } from './passkeys'
61
+ export { memoryAuthStore, normalizeEmail, toPasskeySummary, toPublicUser } from './store'
62
+ export type {
63
+ AuthSession,
64
+ AuthStore,
65
+ AuthStoreExt,
66
+ AuthUser,
67
+ OAuthAccount,
68
+ Organization,
69
+ OrgInvitation,
70
+ OrgMembership,
71
+ PasskeyRecord,
72
+ PasskeySummary,
73
+ PublicUser,
74
+ RecoveryCodeRecord,
75
+ TokenKind,
76
+ TotpRecord,
77
+ UserExport,
78
+ UserExportExt,
79
+ UserOrgSummary,
80
+ VerificationToken,
81
+ } from './store'
82
+ export { buildOtpauthUrl, generateTotpCode, generateTotpSecret } from './totp'
83
+ export type { TotpOptions, TwoFactorMethod } from './totp'
58
84
 
59
85
  const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]'])
60
86
  const DEFAULT_PRUNE_INTERVAL_MS = 15 * 60 * 1000
61
87
  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
88
+ const DEFAULT_MAX_PASSWORD_LENGTH = 1024
67
89
 
68
90
  // Mailed links and OAuth callbacks start with `site`, so anything but an http(s) origin is a config mistake.
69
91
  function siteOrigin(value: string): string {
@@ -79,7 +101,7 @@ export interface AuthMailPayload {
79
101
  text: string
80
102
  html?: string | undefined
81
103
  url: string
82
- kind: 'magic-link' | 'verify-email' | 'reset-password'
104
+ kind: 'magic-link' | 'verify-email' | 'reset-password' | 'org-invite'
83
105
  }
84
106
 
85
107
  /** Structural interface matching `@prunellejs/mail`'s `Mailer` so `createAuth({ mailer })` needs no glue callback. */
@@ -124,6 +146,8 @@ export interface AuthOptions<TUser extends AuthUser = AuthUser> {
124
146
  tokenTtlSeconds?: number | undefined
125
147
  /** Minimum password length (default: 12, aligned with CNIL guidance). */
126
148
  minPasswordLength?: number | undefined
149
+ /** Maximum password length in characters / UTF-8 bytes before Argon2id hashing (default: 1024). */
150
+ maxPasswordLength?: number | undefined
127
151
  /** Default role assigned to newly created users (default: 'user'). */
128
152
  defaultRole?: string | undefined
129
153
  /** Default redirect after successful form login/signup/OAuth (default: '/'). */
@@ -161,13 +185,28 @@ export interface AuthOptions<TUser extends AuthUser = AuthUser> {
161
185
  storeIp?: boolean | 'truncate' | undefined
162
186
  /** Whether to record the `User-Agent` header on sessions (default: `true`). */
163
187
  storeUserAgent?: boolean | undefined
188
+ /** TOTP second-factor configuration (`issuer`, `verifyPath`). */
189
+ totp?: TotpOptions | undefined
190
+ /** Redirect path for HTML form sign-ins when 2FA is required (overrides `totp.verifyPath`, defaults to `${basePath}/totp/verify`). */
191
+ twoFactorRedirect?: string | undefined
192
+ /** WebAuthn Passkeys configuration (`rpId`, `rpName`, `origin`, `userVerification`). */
193
+ passkeys?: PasskeyOptions | undefined
194
+ /** Organization invitation lifetime in seconds (default: 7 days). */
195
+ orgInviteTtlSeconds?: number | undefined
164
196
  }
165
197
 
166
198
  export interface GuardOptions<TUser extends AuthUser = AuthUser> {
167
199
  /** Redirect unauthenticated HTML requests here (JSON/API requests always receive 401). */
168
200
  redirectTo?: string | undefined
169
- /** Required user role(s); authenticated users without a matching role receive 403. */
201
+ /** Required role(s): checks `orgMembership.role` when `org` is set, otherwise `user.role`. */
170
202
  role?: string | string[] | undefined
203
+ /**
204
+ * Require organization membership and populate `ctx.locals.org` & `ctx.locals.orgMembership`:
205
+ * - `true`: reads `ctx.params.org ?? ctx.params.orgId ?? ctx.params.slug`
206
+ * - `string`: reads `ctx.params[org]` (or falls back to looking up `org` as a slug/id)
207
+ * - function: calls `await org(ctx)` to resolve the org id or slug
208
+ */
209
+ org?: boolean | string | ((ctx: RequestContext) => string | undefined | Promise<string | undefined>) | undefined
171
210
  /** Custom authorization predicate. */
172
211
  allow?: ((user: PublicUser<TUser>, ctx: RequestContext) => boolean | Promise<boolean>) | undefined
173
212
  }
@@ -186,6 +225,24 @@ export interface Auth<TUser extends AuthUser = AuthUser> extends PrunellePlugin
186
225
  revokeAllSessions(userId: string): Promise<void>
187
226
  sendMagicLink(email: string, origin: string, redirectTo?: string): Promise<string>
188
227
  sendVerificationEmail(email: string, origin: string, redirectTo?: string): Promise<string>
228
+ setupTotp(userId: string, opts?: { issuer?: string | undefined }): Promise<{ secret: string, otpauthUrl: string }>
229
+ confirmTotp(userId: string, code: string): Promise<{ enabled: true, recoveryCodes: string[] }>
230
+ verifyTotp(userId: string, code: string): Promise<{ valid: boolean, method?: 'totp' | 'recovery' | undefined }>
231
+ disableTotp(userId: string, code: string): Promise<boolean>
232
+ regenerateRecoveryCodes(userId: string): Promise<string[]>
233
+ listPasskeys(userId: string): Promise<PasskeySummary[]>
234
+ deletePasskey(userId: string, credentialId: string): Promise<boolean>
235
+ createOrg(ownerUserId: string, input: CreateOrgInput): Promise<Organization>
236
+ getOrg(idOrSlug: string): Promise<Organization | undefined>
237
+ listUserOrgs(userId: string): Promise<UserOrgSummary[]>
238
+ listOrgMembers(orgId: string): Promise<OrgMembership[]>
239
+ addOrgMember(orgId: string, userId: string, role?: string): Promise<OrgMembership>
240
+ updateOrgMemberRole(orgId: string, userId: string, role: string): Promise<OrgMembership | undefined>
241
+ removeOrgMember(orgId: string, userId: string): Promise<boolean>
242
+ inviteToOrg(orgId: string, input: InviteToOrgInput): Promise<{ invitation: OrgInvitation, url: string }>
243
+ acceptOrgInvite(token: string, userId: string): Promise<{ org: Organization, membership: OrgMembership }>
244
+ revokeOrgInvite(orgId: string, inviteId: string): Promise<boolean>
245
+ deleteOrg(orgId: string): Promise<void>
189
246
  listSessions(userId: string): Promise<AuthSession[]>
190
247
  exportUser(userId: string): Promise<UserExport<TUser> | null>
191
248
  deleteUser(userId: string): Promise<void>
@@ -221,6 +278,7 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
221
278
  const renewalIntervalMs = Math.max(0, (options.renewalIntervalSeconds ?? Math.min(60 * 60, Math.max(1, Math.floor(sessionTtlSeconds / 4)))) * 1000)
222
279
  const tokenTtlMs = (options.tokenTtlSeconds ?? 60 * 15) * 1000
223
280
  const minPasswordLength = options.minPasswordLength ?? 12
281
+ const maxPasswordLength = options.maxPasswordLength ?? DEFAULT_MAX_PASSWORD_LENGTH
224
282
  const defaultRole = options.defaultRole ?? 'user'
225
283
  const defaultRedirect = options.defaultRedirect ?? '/'
226
284
  const authRouteOpts = {
@@ -228,17 +286,7 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
228
286
  ...(options.trustProxy !== undefined ? { trustProxy: options.trustProxy } : {}),
229
287
  }
230
288
  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)
289
+ const deliverMail = buildMailDeliverer(options.sendMail, options.mailer)
242
290
  const requireEmailVerification = options.requireEmailVerification !== false
243
291
  let trustProxy = options.trustProxy ?? false
244
292
 
@@ -266,6 +314,33 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
266
314
  isSecureCookie,
267
315
  })
268
316
 
317
+ const twoFactorRedirect = options.twoFactorRedirect ?? options.totp?.verifyPath ?? `${basePath}/totp/verify`
318
+ const totp = createTotpManager({
319
+ store,
320
+ sessions,
321
+ secret,
322
+ twoFactorCookieName: `${cookieName}_2fa`,
323
+ getDefaultIssuer: () => options.totp?.issuer ?? (site ? new URL(site).hostname : 'Prunelle'),
324
+ isSecureCookie,
325
+ })
326
+ const passkeys = createPasskeyManager({
327
+ store,
328
+ sessions,
329
+ secret,
330
+ challengeCookieName: `${cookieName}_webauthn`,
331
+ getSite: () => site,
332
+ options: options.passkeys,
333
+ isSecureCookie,
334
+ })
335
+ const orgs = createOrgManager({
336
+ store,
337
+ sessions,
338
+ basePath,
339
+ defaultRedirect,
340
+ orgInviteTtlMs: options.orgInviteTtlSeconds !== undefined ? options.orgInviteTtlSeconds * 1000 : undefined,
341
+ deliverMail,
342
+ })
343
+
269
344
  // One timer per server the plugin runs on: `prunelle dev` starts the next server before it shuts the previous one down.
270
345
  const pruneTimers = new Set<ReturnType<typeof setInterval>>()
271
346
  let activeServers = 0
@@ -276,6 +351,7 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
276
351
  try {
277
352
  void Promise.resolve(store.pruneExpired?.()).catch(() => {})
278
353
  sessions.sweepRenewedAt()
354
+ passkeys.pruneChallenges()
279
355
  }
280
356
  catch {
281
357
  // Ignore prune errors if the underlying store has been closed
@@ -341,90 +417,10 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
341
417
  return claimed
342
418
  }
343
419
 
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
- }
420
+ const links = createLinkService({ store, sessions, basePath, defaultRedirect, tokenTtlMs, deliverMail })
421
+ const { issueLink, sendVerificationEmail, sendMagicLink, consumeLink, equalizeSignupMailDelay } = links
397
422
 
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
- }
423
+ const guard = (guardOpts?: GuardOptions<TUser>): Middleware => createAuthGuard(sessions.resolve, orgs, guardOpts)
428
424
 
429
425
  const dispose = (): void => {
430
426
  for (const timer of pruneTimers)
@@ -434,10 +430,61 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
434
430
  void Promise.resolve(store.close?.()).catch(() => {})
435
431
  }
436
432
 
433
+ 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)
436
+ const authRoute = createAuthRouteRegistrar(api, basePath, authRouteOpts, authLimitsObj)
437
+ const hasMailTransport = deliverMail !== undefined
438
+
439
+ registerAuthRoutes({
440
+ authRoute,
441
+ store,
442
+ sessions,
443
+ totp,
444
+ twoFactorRedirect,
445
+ minPasswordLength,
446
+ maxPasswordLength,
447
+ defaultRedirect,
448
+ requireEmailVerification,
449
+ hasMailTransport,
450
+ mailedLinkOrigin,
451
+ equalizeSignupMailDelay,
452
+ createUser,
453
+ insertUser,
454
+ claimUnverified,
455
+ issueLink,
456
+ consumeLink,
457
+ sendMagicLink,
458
+ })
459
+ registerTotpRoutes({ authRoute, store, sessions, totp, basePath, defaultRedirect })
460
+ registerPasskeyRoutes({ authRoute, store, sessions, passkeys, totp, defaultRedirect, requireEmailVerification })
461
+ registerOrgRoutes({ authRoute, sessions, orgs, defaultRedirect, hasMailTransport, mailedLinkOrigin })
462
+ registerOAuthRoutes({
463
+ route: (method, path, handler) => api.route(method, path, handler),
464
+ store,
465
+ providers,
466
+ secret,
467
+ site,
468
+ basePath,
469
+ stateCookieName: oauthCookieName,
470
+ defaultRedirect,
471
+ requireEmailVerification,
472
+ hasMailTransport,
473
+ mailedLinkOrigin,
474
+ issueLink,
475
+ limitIp: authLimitsObj.limitIp,
476
+ isSecureCookie,
477
+ claimUnverified,
478
+ insertUser,
479
+ createSessionForUser: sessions.createSessionForUser,
480
+ observeAsync: sessions.observeAsync,
481
+ })
482
+ }
483
+
437
484
  const plugin: PrunellePlugin = definePlugin({
438
485
  name: '@prunellejs/auth',
439
486
  enforce: 'pre',
440
- providesLocals: ['user', 'session'],
487
+ providesLocals: ['user', 'session', 'org', 'orgMembership'],
441
488
  requires: () => isKeptInMemory(store) ? [STORE_IN_MEMORY] : [],
442
489
  server(api) {
443
490
  if (options.trustProxy === undefined)
@@ -457,64 +504,20 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
457
504
  await store.close?.()
458
505
  })
459
506
 
460
- // Sync stores resolve lazily on first read of ctx.locals.user/session; async stores resolve before next().
507
+ // Sync stores resolve lazily on first read of ctx.locals.user/session; async or unknown Promise-returning stores await before next().
461
508
  const internalPrefix = `${api.assetPrefix.replace(/\/$/, '')}/`
462
509
  const actionPrefix = `${internalPrefix}action/`
463
510
  api.use((ctx, next) => {
464
511
  const p = ctx.url.pathname
465
512
  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
- }
513
+ const pending = sessions.prepareRequest(ctx)
514
+ if (pending !== undefined)
515
+ return pending.then(() => next())
473
516
  }
474
517
  return next()
475
518
  }, { scope: 'rendered' })
476
519
 
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
- })
520
+ registerServerRoutes(api)
518
521
  },
519
522
  })
520
523
 
@@ -527,25 +530,36 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
527
530
  resolve: sessions.resolve,
528
531
  guard,
529
532
  createUser,
530
- createSessionForUser: sessions.createSessionForUser,
533
+ createSessionForUser: (userId, ctx) => sessions.createSessionForUser(userId, ctx),
531
534
  signOut: sessions.signOut,
532
- async revokeAllSessions(userId) {
533
- await sessions.observeAsync(store.deleteUserSessions(userId))
534
- },
535
+ revokeAllSessions: async (userId) => { await sessions.observeAsync(store.deleteUserSessions(userId)) },
535
536
  sendMagicLink,
536
537
  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
- },
538
+ setupTotp: totp.setupTotp,
539
+ confirmTotp: totp.confirmTotp,
540
+ verifyTotp: totp.verifyTotp,
541
+ disableTotp: totp.disableTotp,
542
+ regenerateRecoveryCodes: totp.regenerateRecoveryCodes,
543
+ listPasskeys: passkeys.listPasskeys,
544
+ deletePasskey: passkeys.deletePasskey,
545
+ createOrg: orgs.createOrg,
546
+ getOrg: orgs.getOrg,
547
+ listUserOrgs: orgs.listUserOrgs,
548
+ listOrgMembers: orgs.listOrgMembers,
549
+ addOrgMember: orgs.addOrgMember,
550
+ updateOrgMemberRole: orgs.updateOrgMemberRole,
551
+ removeOrgMember: orgs.removeOrgMember,
552
+ inviteToOrg: orgs.inviteToOrg,
553
+ acceptOrgInvite: orgs.acceptOrgInvite,
554
+ revokeOrgInvite: orgs.revokeOrgInvite,
555
+ deleteOrg: orgs.deleteOrg,
556
+ 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)) },
546
559
  async pruneExpired() {
547
560
  await store.pruneExpired?.()
548
561
  sessions.sweepRenewedAt()
562
+ passkeys.pruneChallenges()
549
563
  },
550
564
  dispose,
551
565
  }