@prunellejs/auth 0.0.0-stage → 0.5.3

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 ADDED
@@ -0,0 +1,580 @@
1
+ // @prunellejs/auth — Zero-dependency Bun-native authentication plugin for Prunelle.
2
+ // Built strictly on the public PrunellePlugin API (`api.use` + `api.route`).
3
+ // Supports Argon2id passwords, hashed DB sessions with sliding renewal, email verification,
4
+ // magic links, OAuth 2.0 + PKCE (S256), role/route guards, RGPD helpers, and memory or `bun:sqlite` stores.
5
+
6
+ import type { PrunellePlugin } from 'prunelle/config'
7
+ import type { PrunelleLocals, Middleware, RequestContext, TrustProxy } from 'prunelle/server'
8
+ import type { OAuthProvider } from './oauth'
9
+
10
+ import type { AuthSession, AuthStore, AuthUser, PublicUser, UserExport } from './store'
11
+ import { definePlugin } from 'prunelle/config'
12
+ import { isHttpsRequest, nodeEnv, safeEqual, safeRedirect, wantsJson } from 'prunelle/server'
13
+ import { hashPassword, randomToken, sha256Hex } from './crypto'
14
+ import { authLimits, fail, isValidEmail } from './http'
15
+ import { registerOAuthRoutes } from './oauth-routes'
16
+
17
+ import { registerAuthRoutes } from './routes'
18
+ import { createSessionManager } from './session'
19
+ import { isKeptInMemory, memoryAuthStore, normalizeEmail, toPublicUser } from './store'
20
+
21
+ declare module 'prunelle/server' {
22
+ interface PrunelleLocals {
23
+ user?: PublicUser | undefined
24
+ session?: AuthSession | undefined
25
+ }
26
+ }
27
+
28
+ export interface RateLimitOptions {
29
+ /** Attempts per window, per scope and address and per scope and email (default: 15). */
30
+ max?: number | undefined
31
+ /** Window duration in ms (default: 60_000). */
32
+ windowMs?: number | undefined
33
+ }
34
+
35
+ export { safeRedirect } from 'prunelle/server'
36
+ export { discord, github, google, oauthProvider } from './oauth'
37
+ export type { OAuthPresetConfig, OAuthProfile, OAuthProvider } from './oauth'
38
+ export { memoryAuthStore, normalizeEmail, toPublicUser } from './store'
39
+ export type { AuthSession, AuthStore, AuthUser, OAuthAccount, PublicUser, TokenKind, UserExport, VerificationToken } from './store'
40
+
41
+ const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]'])
42
+ const DEFAULT_PRUNE_INTERVAL_MS = 15 * 60 * 1000
43
+ const MIN_PROD_SECRET_BYTES = 32
44
+ const DEFAULT_MAX_PASSWORD_LENGTH = 1024
45
+ const MAIL_DELAY_MIN_MS = 5
46
+ const MAIL_DELAY_MAX_MS = 2000
47
+ const LINK_PATHS = { 'magic-link': 'magic-link/verify', 'verify-email': 'verify-email' } as const
48
+ const LINK_MAILS = {
49
+ 'magic-link': { subject: 'Your sign-in link', text: 'Sign in using this one-time link', html: 'Click to sign in', label: 'Sign in' },
50
+ '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' },
51
+ } as const
52
+
53
+ // Binds a verify-email token to the user's current passwordHash so any password update invalidates prior verification links.
54
+ function verifyBinding(user: { id: string, passwordHash?: string | undefined }): string {
55
+ return sha256Hex(`verify:${user.id}:${user.passwordHash ?? ''}`).slice(0, 32)
56
+ }
57
+
58
+ function createMailDelayTracker(): { observe: (ms: number) => void, pad: () => Promise<void> } {
59
+ let ewmaMs: number | undefined
60
+ return {
61
+ observe(ms: number) {
62
+ const clamped = Math.min(MAIL_DELAY_MAX_MS, Math.max(0, ms))
63
+ ewmaMs = ewmaMs === undefined ? clamped : ewmaMs * 0.7 + clamped * 0.3
64
+ },
65
+ async pad() {
66
+ if (ewmaMs === undefined || ewmaMs < MAIL_DELAY_MIN_MS)
67
+ return
68
+ const jittered = Math.min(MAIL_DELAY_MAX_MS, Math.round(ewmaMs * (0.85 + Math.random() * 0.3)))
69
+ if (jittered >= MAIL_DELAY_MIN_MS)
70
+ await Bun.sleep(jittered)
71
+ },
72
+ }
73
+ }
74
+
75
+ function buildMailDeliverer(
76
+ sendMail: AuthOptions['sendMail'],
77
+ mailer: AuthOptions['mailer'],
78
+ ): ((mail: AuthMailPayload) => void | Promise<void>) | undefined {
79
+ if (sendMail)
80
+ return sendMail
81
+ if (!mailer)
82
+ return undefined
83
+ return async (mail) => {
84
+ await mailer.send({ to: mail.to, subject: mail.subject, text: mail.text, html: mail.html })
85
+ }
86
+ }
87
+
88
+ function createAuthGuard<TUser extends AuthUser>(
89
+ resolve: (ctx: RequestContext) => Promise<{ user: PublicUser<TUser>, session: AuthSession } | undefined>,
90
+ guardOpts: GuardOptions<TUser> = {},
91
+ ): Middleware {
92
+ const roles = guardOpts.role === undefined ? undefined : (Array.isArray(guardOpts.role) ? guardOpts.role : [guardOpts.role])
93
+ return async (ctx, next) => {
94
+ const resolved = await resolve(ctx)
95
+ if (!resolved) {
96
+ if (!wantsJson(ctx.request) && guardOpts.redirectTo) {
97
+ const nextParam = encodeURIComponent(ctx.url.pathname + ctx.url.search)
98
+ const sep = guardOpts.redirectTo.includes('?') ? '&' : '?'
99
+ return ctx.redirect(`${guardOpts.redirectTo}${sep}next=${nextParam}`, 302)
100
+ }
101
+ return fail(ctx, 401, 'Authentication required')
102
+ }
103
+ if (roles && !roles.includes(resolved.user.role))
104
+ return fail(ctx, 403, 'Forbidden')
105
+ if (guardOpts.allow && !(await guardOpts.allow(resolved.user, ctx)))
106
+ return fail(ctx, 403, 'Forbidden')
107
+ return next()
108
+ }
109
+ }
110
+
111
+ // Mailed links and OAuth callbacks start with `site`, so anything but an http(s) origin is a config mistake.
112
+ function siteOrigin(value: string): string {
113
+ const url = new URL(value)
114
+ if (url.protocol !== 'https:' && url.protocol !== 'http:')
115
+ throw new Error(`[prunelle/auth] \`site\` must be an http or https origin, got ${value}`)
116
+ return url.origin
117
+ }
118
+
119
+ export interface AuthMailPayload {
120
+ to: string
121
+ subject: string
122
+ text: string
123
+ html?: string | undefined
124
+ url: string
125
+ kind: 'magic-link' | 'verify-email' | 'reset-password'
126
+ }
127
+
128
+ /** Structural interface matching `@prunellejs/mail`'s `Mailer` so `createAuth({ mailer })` needs no glue callback. */
129
+ export interface AuthMailer {
130
+ send(message: {
131
+ to: string
132
+ subject: string
133
+ text?: string | undefined
134
+ html?: string | undefined
135
+ }): unknown
136
+ }
137
+
138
+ export type CreateUserInput<TUser extends AuthUser = AuthUser> = {
139
+ email: string
140
+ password?: string | undefined
141
+ name?: string | undefined
142
+ avatarUrl?: string | undefined
143
+ role?: string | undefined
144
+ emailVerified?: boolean | undefined
145
+ } & Omit<TUser, keyof AuthUser>
146
+
147
+ export interface AuthOptions<TUser extends AuthUser = AuthUser> {
148
+ /** Storage adapter (defaults to `memoryAuthStore()`). Use `sqliteAuthStore()` for production SQLite. */
149
+ store?: AuthStore<TUser> | undefined
150
+ /** Default custom fields merged into users created by signup, magic-link, or OAuth flows. */
151
+ defaultUserFields?: Omit<TUser, keyof AuthUser> | (() => Omit<TUser, keyof AuthUser>) | undefined
152
+ /**
153
+ * Secret used to sign short-lived OAuth state/PKCE cookies.
154
+ * Defaults to `AUTH_SECRET` env, or a random per-process key in development.
155
+ * In `NODE_ENV=production`, a non-empty secret of at least 32 UTF-8 bytes is required.
156
+ */
157
+ secret?: string | undefined
158
+ /** Route prefix (default: '/auth'). */
159
+ basePath?: string | undefined
160
+ /** Session cookie name (default: 'pru_session'). */
161
+ cookieName?: string | undefined
162
+ /** Session lifetime in seconds (default: 30 days). */
163
+ sessionTtlSeconds?: number | undefined
164
+ /** Minimum interval in seconds between sliding-expiry DB writes for the same session (default: up to 1 hour). */
165
+ renewalIntervalSeconds?: number | undefined
166
+ /** Magic-link / verification token lifetime in seconds (default: 15 minutes). */
167
+ tokenTtlSeconds?: number | undefined
168
+ /** Minimum password length (default: 12, aligned with CNIL guidance). */
169
+ minPasswordLength?: number | undefined
170
+ /** Maximum password length in characters / UTF-8 bytes before Argon2id hashing (default: 1024). */
171
+ maxPasswordLength?: number | undefined
172
+ /** Default role assigned to newly created users (default: 'user'). */
173
+ defaultRole?: string | undefined
174
+ /** Default redirect after successful form login/signup/OAuth (default: '/'). */
175
+ defaultRedirect?: string | undefined
176
+ /** Additional trusted cross-origin origins merged with `PrunelleConfig.trustedOrigins` for auth POST routes. */
177
+ trustedOrigins?: string[] | undefined
178
+ /** Public origin of the site (`https://example.com`), defaults to `PrunelleConfig.site`. Without it, mailed links are only built for a loopback host. */
179
+ site?: string | undefined
180
+ /** OAuth 2.0 providers (e.g. `[github(...), discord(...), google(...)]`). */
181
+ providers?: OAuthProvider[] | undefined
182
+ /** Pass a `@prunellejs/mail` `Mailer` instance directly for magic links & verification emails (shorthand for `sendMail`). */
183
+ mailer?: AuthMailer | undefined
184
+ /** Custom mail sender for magic links / verification emails (overrides `mailer` when both are provided). */
185
+ sendMail?: ((mail: AuthMailPayload) => void | Promise<void>) | undefined
186
+ /**
187
+ * Require email verification before opening a session on password sign-up / sign-in (default: `true`).
188
+ * Set explicitly to `false` only when you intentionally allow unverified password sessions (e.g. local dev without mail).
189
+ */
190
+ requireEmailVerification?: boolean | undefined
191
+ /**
192
+ * Trust `X-Forwarded-For` / `X-Real-IP` headers as a fallback when `ctx.ip` is not populated by the server (default: `false`).
193
+ * When `ctx.ip` is provided by Prunelle's `trustProxy`-aware server, `ctx.ip` is always used.
194
+ */
195
+ trustProxy?: TrustProxy | undefined
196
+ /** Optional per-key rate limit on auth endpoints (`false` disables). */
197
+ rateLimit?: RateLimitOptions | false | undefined
198
+ /** Periodic interval in ms to purge expired sessions and tokens (default: 15 minutes; `false` disables). */
199
+ pruneIntervalMs?: number | false | undefined
200
+ /**
201
+ * Control recording of client IP addresses on sessions (RGPD data minimization):
202
+ * - `'truncate'`: anonymize IPv4 to /24 (`a.b.c.0`) and IPv6 to /48 (`a:b:c::`) (default)
203
+ * - `true`: store full client IP
204
+ * - `false`: do not record IP on sessions
205
+ */
206
+ storeIp?: boolean | 'truncate' | undefined
207
+ /** Whether to record the `User-Agent` header on sessions (default: `true`). */
208
+ storeUserAgent?: boolean | undefined
209
+ }
210
+
211
+ export interface GuardOptions<TUser extends AuthUser = AuthUser> {
212
+ /** Redirect unauthenticated HTML requests here (JSON/API requests always receive 401). */
213
+ redirectTo?: string | undefined
214
+ /** Required user role(s); authenticated users without a matching role receive 403. */
215
+ role?: string | string[] | undefined
216
+ /** Custom authorization predicate. */
217
+ allow?: ((user: PublicUser<TUser>, ctx: RequestContext) => boolean | Promise<boolean>) | undefined
218
+ }
219
+
220
+ /** The plugin `prunelle.config.ts` registers, and the handle routes and actions call. */
221
+ export interface Auth<TUser extends AuthUser = AuthUser> extends PrunellePlugin {
222
+ readonly store: AuthStore<TUser>
223
+ readonly basePath: string
224
+ getUser(ctx: { locals: PrunelleLocals }): PublicUser<TUser> | undefined
225
+ getSession(ctx: { locals: PrunelleLocals }): AuthSession | undefined
226
+ resolve(ctx: RequestContext): Promise<{ user: PublicUser<TUser>, session: AuthSession } | undefined>
227
+ guard(options?: GuardOptions<TUser>): Middleware
228
+ createUser(input: CreateUserInput<TUser>): Promise<PublicUser<TUser>>
229
+ createSessionForUser(userId: string, ctx: RequestContext): Promise<AuthSession>
230
+ signOut(ctx: RequestContext): Promise<void>
231
+ revokeAllSessions(userId: string): Promise<void>
232
+ sendMagicLink(email: string, origin: string, redirectTo?: string): Promise<string>
233
+ sendVerificationEmail(email: string, origin: string, redirectTo?: string): Promise<string>
234
+ listSessions(userId: string): Promise<AuthSession[]>
235
+ exportUser(userId: string): Promise<UserExport<TUser> | null>
236
+ deleteUser(userId: string): Promise<void>
237
+ pruneExpired(): Promise<void>
238
+ dispose(): void
239
+ }
240
+
241
+ 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`.'
242
+
243
+ function resolveSecret(optionSecret: string | undefined): string {
244
+ if (optionSecret !== undefined && optionSecret.trim().length === 0)
245
+ throw new Error('[prunelle/auth] `secret` must not be empty')
246
+
247
+ const envSecret = process.env.AUTH_SECRET
248
+ const configured = optionSecret ?? (envSecret && envSecret.trim().length > 0 ? envSecret : undefined)
249
+ if (nodeEnv() === 'production') {
250
+ if (configured === undefined)
251
+ throw new Error('[prunelle/auth] `secret` (or `AUTH_SECRET` env) is required in production and must be at least 32 bytes')
252
+ if (Buffer.byteLength(configured, 'utf8') < MIN_PROD_SECRET_BYTES)
253
+ throw new Error(`[prunelle/auth] \`secret\` must be at least ${MIN_PROD_SECRET_BYTES} UTF-8 bytes in production`)
254
+ }
255
+ return configured ?? randomToken(32)
256
+ }
257
+
258
+ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptions<TUser> = {}): Auth<TUser> {
259
+ const secret = resolveSecret(options.secret)
260
+ const store = options.store ?? memoryAuthStore<TUser>()
261
+ const basePath = (options.basePath ?? '/auth').replace(/\/$/, '')
262
+ const cookieName = options.cookieName ?? 'pru_session'
263
+ const oauthCookieName = `${cookieName}_oauth`
264
+ const sessionTtlSeconds = options.sessionTtlSeconds ?? 60 * 60 * 24 * 30
265
+ const sessionTtlMs = sessionTtlSeconds * 1000
266
+ const renewalIntervalMs = Math.max(0, (options.renewalIntervalSeconds ?? Math.min(60 * 60, Math.max(1, Math.floor(sessionTtlSeconds / 4)))) * 1000)
267
+ const tokenTtlMs = (options.tokenTtlSeconds ?? 60 * 15) * 1000
268
+ const minPasswordLength = options.minPasswordLength ?? 12
269
+ const maxPasswordLength = options.maxPasswordLength ?? DEFAULT_MAX_PASSWORD_LENGTH
270
+ const mailDelay = createMailDelayTracker()
271
+ const defaultRole = options.defaultRole ?? 'user'
272
+ const defaultRedirect = options.defaultRedirect ?? '/'
273
+ const authRouteOpts = {
274
+ ...(options.trustedOrigins !== undefined ? { trustedOrigins: options.trustedOrigins } : {}),
275
+ ...(options.trustProxy !== undefined ? { trustProxy: options.trustProxy } : {}),
276
+ }
277
+ let site = options.site !== undefined ? siteOrigin(options.site) : undefined
278
+ const deliverMail = buildMailDeliverer(options.sendMail, options.mailer)
279
+ const requireEmailVerification = options.requireEmailVerification !== false
280
+ let trustProxy = options.trustProxy ?? false
281
+
282
+ const pruneIntervalMs = options.pruneIntervalMs === false
283
+ ? undefined
284
+ : (options.pruneIntervalMs ?? DEFAULT_PRUNE_INTERVAL_MS)
285
+
286
+ const providers = new Map<string, OAuthProvider>()
287
+ for (const p of options.providers ?? [])
288
+ providers.set(p.id, p)
289
+
290
+ const isSecureCookie = (ctx: RequestContext): boolean =>
291
+ ctx.url.protocol === 'https:'
292
+ || isHttpsRequest(ctx.request, trustProxy)
293
+ || nodeEnv() === 'production'
294
+
295
+ const sessions = createSessionManager({
296
+ store,
297
+ cookieName,
298
+ sessionTtlMs,
299
+ renewalIntervalMs,
300
+ storeIp: options.storeIp ?? 'truncate',
301
+ storeUserAgent: options.storeUserAgent !== false,
302
+ getTrustProxy: () => trustProxy,
303
+ isSecureCookie,
304
+ })
305
+
306
+ // One timer per server the plugin runs on: `prunelle dev` starts the next server before it shuts the previous one down.
307
+ const pruneTimers = new Set<ReturnType<typeof setInterval>>()
308
+ let activeServers = 0
309
+ const startPruneTimer = (): (() => void) | undefined => {
310
+ if (pruneIntervalMs === undefined || pruneIntervalMs <= 0)
311
+ return undefined
312
+ const timer = setInterval(() => {
313
+ try {
314
+ void Promise.resolve(store.pruneExpired?.()).catch(() => {})
315
+ sessions.sweepRenewedAt()
316
+ }
317
+ catch {
318
+ // Ignore prune errors if the underlying store has been closed
319
+ }
320
+ }, pruneIntervalMs)
321
+ timer.unref?.()
322
+ pruneTimers.add(timer)
323
+ return () => {
324
+ clearInterval(timer)
325
+ pruneTimers.delete(timer)
326
+ }
327
+ }
328
+
329
+ async function insertUser(fields: Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>): Promise<TUser> {
330
+ const now = Date.now()
331
+ const defaults = typeof options.defaultUserFields === 'function'
332
+ ? (options.defaultUserFields as () => Partial<TUser>)()
333
+ : (options.defaultUserFields as Partial<TUser> | undefined)
334
+ return sessions.observeAsync(store.createUser({
335
+ id: crypto.randomUUID(),
336
+ role: defaultRole,
337
+ createdAt: now,
338
+ updatedAt: now,
339
+ ...defaults,
340
+ ...fields,
341
+ } as TUser))
342
+ }
343
+
344
+ async function createUser(input: CreateUserInput<TUser>): Promise<PublicUser<TUser>> {
345
+ const { email: rawEmail, password, name, avatarUrl, role, emailVerified, ...extra } = input
346
+ const email = normalizeEmail(rawEmail)
347
+ if (!isValidEmail(email))
348
+ throw new Error('Invalid email address')
349
+ if (await sessions.observeAsync(store.getUserByEmail(email)))
350
+ throw new Error('Email is already registered')
351
+
352
+ const passwordHash = password !== undefined ? await hashPassword(password) : undefined
353
+ const created = await insertUser({
354
+ ...extra,
355
+ email,
356
+ ...(name !== undefined ? { name } : {}),
357
+ ...(avatarUrl !== undefined ? { avatarUrl } : {}),
358
+ ...(role !== undefined ? { role } : {}),
359
+ emailVerified: emailVerified ?? false,
360
+ ...(passwordHash !== undefined ? { passwordHash } : {}),
361
+ } as Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>)
362
+ return toPublicUser(created)
363
+ }
364
+
365
+ // The request URL comes from the Host header, which the client controls: a link mailed to a victim must not point at it.
366
+ function mailedLinkOrigin(url: URL): string | undefined {
367
+ if (site !== undefined)
368
+ return site
369
+ return LOOPBACK_HOSTS.has(url.hostname) ? url.origin : undefined
370
+ }
371
+
372
+ // 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.
373
+ // The password goes first, so a squatter cannot sign in again between the purge and the update.
374
+ async function claimUnverified(user: TUser): Promise<TUser> {
375
+ const claimed = (await sessions.observeAsync(store.updateUser(user.id, { emailVerified: true, passwordHash: undefined } as Partial<Omit<TUser, 'id' | 'createdAt'>>))) ?? user
376
+ await sessions.observeAsync(store.deleteUserSessions(user.id))
377
+ await sessions.observeAsync(store.deleteUserOAuthAccounts(user.id))
378
+ return claimed
379
+ }
380
+
381
+ // One-time emailed link: stores the hashed token, builds the URL and mails it when a transport is configured.
382
+ async function issueLink(kind: 'magic-link' | 'verify-email', userId: string | undefined, email: string, origin: string | undefined, redirectTo: string | undefined): Promise<string> {
383
+ const normalized = normalizeEmail(email)
384
+ const boundUser = kind === 'verify-email' && userId !== undefined ? await sessions.observeAsync(store.getUserById(userId)) : undefined
385
+ const rawToken = boundUser ? `${randomToken(32)}.${verifyBinding(boundUser)}` : randomToken(32)
386
+ const tokenHash = sha256Hex(rawToken)
387
+ await sessions.observeAsync(store.createToken({
388
+ tokenHash,
389
+ ...(userId !== undefined ? { userId } : {}),
390
+ email: normalized,
391
+ kind,
392
+ expiresAt: Date.now() + tokenTtlMs,
393
+ }))
394
+
395
+ const next = safeRedirect(redirectTo, defaultRedirect)
396
+ const path = `${basePath}/${LINK_PATHS[kind]}?token=${encodeURIComponent(rawToken)}&redirect=${encodeURIComponent(next)}`
397
+ const url = origin !== undefined ? `${origin.replace(/\/$/, '')}${path}` : path
398
+
399
+ if (deliverMail && origin !== undefined) {
400
+ const mail = LINK_MAILS[kind]
401
+ const startedAt = performance.now()
402
+ try {
403
+ await deliverMail({
404
+ to: normalized,
405
+ subject: mail.subject,
406
+ text: `${mail.text}: ${url}`,
407
+ html: `<p>${mail.html}: <a href="${url}">${mail.label}</a></p>`,
408
+ url,
409
+ kind,
410
+ })
411
+ mailDelay.observe(performance.now() - startedAt)
412
+ }
413
+ catch (err) {
414
+ try {
415
+ await sessions.observeAsync(store.consumeToken(tokenHash, kind))
416
+ }
417
+ catch {
418
+ // Best-effort token cleanup if delivery fails.
419
+ }
420
+ throw err
421
+ }
422
+ }
423
+ return url
424
+ }
425
+
426
+ async function sendVerificationEmail(email: string, origin: string, redirectTo?: string): Promise<string> {
427
+ const normalized = normalizeEmail(email)
428
+ const existing = await sessions.observeAsync(store.getUserByEmail(normalized))
429
+ return issueLink('verify-email', existing?.id, normalized, origin, redirectTo)
430
+ }
431
+
432
+ async function sendMagicLink(email: string, origin: string, redirectTo?: string): Promise<string> {
433
+ const normalized = normalizeEmail(email)
434
+ const existing = await sessions.observeAsync(store.getUserByEmail(normalized))
435
+ return issueLink('magic-link', existing?.id, normalized, origin, redirectTo)
436
+ }
437
+
438
+ // Consumes a one-time token and loads the user it was issued for (by id, else by email).
439
+ async function consumeLink(kind: 'magic-link' | 'verify-email', rawToken: string): Promise<{ email: string, user: TUser | undefined } | undefined> {
440
+ const consumed = await sessions.observeAsync(store.consumeToken(sha256Hex(rawToken), kind))
441
+ if (!consumed)
442
+ return undefined
443
+ const user = consumed.userId
444
+ ? await sessions.observeAsync(store.getUserById(consumed.userId))
445
+ : await sessions.observeAsync(store.getUserByEmail(consumed.email))
446
+ if (kind === 'verify-email') {
447
+ const dot = rawToken.lastIndexOf('.')
448
+ if (!user || dot <= 0 || !safeEqual(rawToken.slice(dot + 1), verifyBinding(user)))
449
+ return undefined
450
+ }
451
+ return { email: consumed.email, user }
452
+ }
453
+
454
+ const guard = (guardOpts?: GuardOptions<TUser>): Middleware => createAuthGuard(sessions.resolve, guardOpts)
455
+
456
+ const dispose = (): void => {
457
+ for (const timer of pruneTimers)
458
+ clearInterval(timer)
459
+ pruneTimers.clear()
460
+ activeServers = 0
461
+ void Promise.resolve(store.close?.()).catch(() => {})
462
+ }
463
+
464
+ const plugin: PrunellePlugin = definePlugin({
465
+ name: '@prunellejs/auth',
466
+ enforce: 'pre',
467
+ providesLocals: ['user', 'session'],
468
+ requires: () => isKeptInMemory(store) ? [STORE_IN_MEMORY] : [],
469
+ server(api) {
470
+ if (options.trustProxy === undefined)
471
+ trustProxy = api.trustProxy
472
+ if (options.site === undefined && api.site !== undefined)
473
+ site = siteOrigin(api.site)
474
+ activeServers++
475
+ const stopPruneTimer = startPruneTimer()
476
+ let stopped = false
477
+ api.onShutdown(async () => {
478
+ if (stopped)
479
+ return
480
+ stopped = true
481
+ stopPruneTimer?.()
482
+ activeServers = Math.max(0, activeServers - 1)
483
+ if (activeServers === 0)
484
+ await store.close?.()
485
+ })
486
+
487
+ // Sync stores resolve lazily on first read of ctx.locals.user/session; async or unknown Promise-returning stores await before next().
488
+ const internalPrefix = `${api.assetPrefix.replace(/\/$/, '')}/`
489
+ const actionPrefix = `${internalPrefix}action/`
490
+ api.use((ctx, next) => {
491
+ const p = ctx.url.pathname
492
+ if (!p.startsWith(internalPrefix) || p.startsWith(actionPrefix)) {
493
+ const pending = sessions.prepareRequest(ctx)
494
+ if (pending !== undefined)
495
+ return pending.then(() => next())
496
+ }
497
+ return next()
498
+ }, { scope: 'rendered' })
499
+
500
+ // Counted in this server's store, so a `prunelle dev` restart or a test's new server starts from zero.
501
+ const limits = options.rateLimit === false ? undefined : api.rateLimiter({ max: options.rateLimit?.max ?? 15, windowMs: options.rateLimit?.windowMs ?? 60_000 })
502
+ const { limitIp, limitEmail } = authLimits(limits, () => trustProxy)
503
+ registerAuthRoutes({
504
+ api,
505
+ store,
506
+ sessions,
507
+ limitEmail,
508
+ limitIp,
509
+ basePath,
510
+ authRouteOpts,
511
+ minPasswordLength,
512
+ maxPasswordLength,
513
+ defaultRedirect,
514
+ requireEmailVerification,
515
+ hasMailTransport: deliverMail !== undefined,
516
+ mailedLinkOrigin,
517
+ equalizeSignupMailDelay: () => deliverMail ? mailDelay.pad() : Promise.resolve(),
518
+ createUser,
519
+ insertUser,
520
+ claimUnverified,
521
+ issueLink,
522
+ consumeLink,
523
+ sendMagicLink,
524
+ })
525
+
526
+ registerOAuthRoutes({
527
+ route: (method, path, handler) => api.route(method, path, handler),
528
+ store,
529
+ providers,
530
+ secret,
531
+ site,
532
+ basePath,
533
+ stateCookieName: oauthCookieName,
534
+ defaultRedirect,
535
+ requireEmailVerification,
536
+ hasMailTransport: deliverMail !== undefined,
537
+ mailedLinkOrigin,
538
+ issueLink,
539
+ limitIp,
540
+ isSecureCookie,
541
+ claimUnverified,
542
+ insertUser,
543
+ createSessionForUser: sessions.createSessionForUser,
544
+ observeAsync: sessions.observeAsync,
545
+ })
546
+ },
547
+ })
548
+
549
+ return {
550
+ ...plugin,
551
+ store,
552
+ basePath,
553
+ getUser: sessions.getUser,
554
+ getSession: sessions.getSession,
555
+ resolve: sessions.resolve,
556
+ guard,
557
+ createUser,
558
+ createSessionForUser: (userId, ctx) => sessions.createSessionForUser(userId, ctx),
559
+ signOut: sessions.signOut,
560
+ async revokeAllSessions(userId) {
561
+ await sessions.observeAsync(store.deleteUserSessions(userId))
562
+ },
563
+ sendMagicLink,
564
+ sendVerificationEmail,
565
+ async listSessions(userId) {
566
+ return await sessions.observeAsync(store.listSessions(userId))
567
+ },
568
+ async exportUser(userId) {
569
+ return await sessions.observeAsync(store.exportUser(userId))
570
+ },
571
+ async deleteUser(userId) {
572
+ await sessions.observeAsync(store.deleteUser(userId))
573
+ },
574
+ async pruneExpired() {
575
+ await store.pruneExpired?.()
576
+ sessions.sweepRenewedAt()
577
+ },
578
+ dispose,
579
+ }
580
+ }