@prunellejs/auth 0.0.0-stage → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts ADDED
@@ -0,0 +1,635 @@
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, ServerPluginAPI } from 'prunelle/config'
7
+ import type { Middleware, PrunelleLocals, RequestContext, TrustProxy } from 'prunelle/server'
8
+ import type { AuthFormMessage } from './form-messages'
9
+ import type { OAuthProvider } from './oauth'
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'
26
+ import { definePlugin } from 'prunelle/config'
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'
31
+ import { registerOAuthRoutes } from './oauth-routes'
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'
37
+ import { registerAuthRoutes } from './routes'
38
+ import { authFormMessages, readFormMessage } from './form-messages'
39
+ import { createSessionManager } from './session'
40
+ import { isKeptInMemory, memoryAuthStore, normalizeEmail, toPublicUser } from './store'
41
+ import { createTotpManager } from './totp'
42
+ import { registerTotpRoutes } from './totp-routes'
43
+
44
+ declare module 'prunelle/server' {
45
+ interface PrunelleLocals {
46
+ user?: PublicUser | undefined
47
+ session?: AuthSession | undefined
48
+ org?: Organization | undefined
49
+ orgMembership?: OrgMembership | undefined
50
+ }
51
+ }
52
+
53
+ export interface RateLimitOptions {
54
+ /** Attempts per window, per scope and address (default: 15). */
55
+ max?: number | undefined
56
+ /** Window duration in ms (default: 60_000). */
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
62
+ }
63
+
64
+ export { FRESH_SIGNIN_MS } from './account'
65
+ export { safeRedirect } from 'prunelle/server'
66
+ export type { AuthFormCode, AuthFormMessage } from './form-messages'
67
+ export { discord, github, google, oauthProvider } from './oauth'
68
+ export type { OAuthPresetConfig, OAuthProfile, OAuthProvider } from './oauth'
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'
95
+
96
+ const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]'])
97
+ const DEFAULT_PRUNE_INTERVAL_MS = 15 * 60 * 1000
98
+ const MIN_PROD_SECRET_BYTES = 32
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
+ }
107
+
108
+ // Mailed links and OAuth callbacks start with `site`, so anything but an http(s) origin is a config mistake.
109
+ function siteOrigin(value: string): string {
110
+ const url = new URL(value)
111
+ if (url.protocol !== 'https:' && url.protocol !== 'http:')
112
+ throw new Error(`[prunelle/auth] \`site\` must be an http or https origin, got ${value}`)
113
+ return url.origin
114
+ }
115
+
116
+ export interface AuthMailPayload {
117
+ to: string
118
+ subject: string
119
+ text: string
120
+ html?: string | undefined
121
+ url: string
122
+ kind: 'magic-link' | 'verify-email' | 'reset-password' | 'org-invite'
123
+ }
124
+
125
+ /** Structural interface matching `@prunellejs/mail`'s `Mailer` so `createAuth({ mailer })` needs no glue callback. */
126
+ export interface AuthMailer {
127
+ send(message: {
128
+ to: string
129
+ subject: string
130
+ text?: string | undefined
131
+ html?: string | undefined
132
+ }): unknown
133
+ }
134
+
135
+ export type CreateUserInput<TUser extends AuthUser = AuthUser> = {
136
+ email: string
137
+ password?: string | undefined
138
+ name?: string | undefined
139
+ avatarUrl?: string | undefined
140
+ role?: string | undefined
141
+ emailVerified?: boolean | undefined
142
+ } & Omit<TUser, keyof AuthUser>
143
+
144
+ export interface AuthOptions<TUser extends AuthUser = AuthUser> {
145
+ /** Storage adapter (defaults to `memoryAuthStore()`). Use `sqliteAuthStore()` for production SQLite. */
146
+ store?: AuthStore<TUser> | undefined
147
+ /** Default custom fields merged into users created by signup, magic-link, or OAuth flows. */
148
+ defaultUserFields?: Omit<TUser, keyof AuthUser> | (() => Omit<TUser, keyof AuthUser>) | undefined
149
+ /**
150
+ * Secret used to sign short-lived OAuth state/PKCE cookies.
151
+ * Defaults to `AUTH_SECRET` env, or a random per-process key in development.
152
+ * In `NODE_ENV=production`, a non-empty secret of at least 32 UTF-8 bytes is required.
153
+ */
154
+ secret?: string | undefined
155
+ /** Route prefix (default: '/auth'). */
156
+ basePath?: string | undefined
157
+ /** Session cookie name (default: 'pru_session'). Over https the cookie is sent as `__Host-<name>`. */
158
+ cookieName?: string | undefined
159
+ /** Accept and migrate sessions still sent under the unprefixed `cookieName` over https (default: `false`). Enable temporarily when upgrading existing apps so sibling subdomains cannot fixate sessions. */
160
+ acceptLegacyCookie?: boolean | undefined
161
+ /** Session lifetime in seconds (default: 30 days). */
162
+ sessionTtlSeconds?: number | undefined
163
+ /** Longest a session lives, counted from sign-in however often it is used (default: 90 days, never less than `sessionTtlSeconds`; `false` lets renewal go on forever). */
164
+ absoluteTtlSeconds?: number | false | undefined
165
+ /** Minimum interval in seconds between sliding-expiry DB writes for the same session (default: up to 1 hour). */
166
+ renewalIntervalSeconds?: number | undefined
167
+ /** Magic-link / verification token lifetime in seconds (default: 15 minutes). */
168
+ tokenTtlSeconds?: number | undefined
169
+ /** Seconds a sign-up whose email was never verified is kept before the prune deletes it with its data (default: 7 days; `false` keeps it). Applies only while `requireEmailVerification` is on. */
170
+ unverifiedTtlSeconds?: number | false | undefined
171
+ /** Minimum password length (default: 12, aligned with CNIL guidance). */
172
+ minPasswordLength?: number | undefined
173
+ /** Maximum password length in characters / UTF-8 bytes before Argon2id hashing (default: 1024). */
174
+ maxPasswordLength?: number | undefined
175
+ /** Default role assigned to newly created users (default: 'user'). */
176
+ defaultRole?: string | undefined
177
+ /** Default redirect after successful form login/signup/OAuth (default: '/'). */
178
+ defaultRedirect?: string | undefined
179
+ /** Additional trusted cross-origin origins merged with `PrunelleConfig.trustedOrigins` for auth POST routes. */
180
+ trustedOrigins?: string[] | undefined
181
+ /** Public origin of the site (`https://example.com`), defaults to `PrunelleConfig.site`. Without it, mailed links are only built for a loopback host. */
182
+ site?: string | undefined
183
+ /** OAuth 2.0 providers (e.g. `[github(...), discord(...), google(...)]`). */
184
+ providers?: OAuthProvider[] | undefined
185
+ /** Pass a `@prunellejs/mail` `Mailer` instance directly for magic links & verification emails (shorthand for `sendMail`). */
186
+ mailer?: AuthMailer | undefined
187
+ /** Custom mail sender for magic links / verification emails (overrides `mailer` when both are provided). */
188
+ sendMail?: ((mail: AuthMailPayload) => void | Promise<void>) | undefined
189
+ /** Adds the app's own data about a user to `GET /auth/me/export` and `auth.exportUser()`, under `app`. */
190
+ onExportUser?: ((user: PublicUser<TUser>) => unknown) | undefined
191
+ /** Erases the app's own data about a user before `POST /auth/me/delete` or `auth.deleteUser()` deletes the account; a throw keeps the account. */
192
+ onDeleteUser?: ((user: PublicUser<TUser>) => void | Promise<void>) | undefined
193
+ /**
194
+ * Require email verification before opening a session on password sign-up / sign-in (default: `true`).
195
+ * Set explicitly to `false` only when you intentionally allow unverified password sessions (e.g. local dev without mail).
196
+ */
197
+ requireEmailVerification?: boolean | undefined
198
+ /**
199
+ * Trust `X-Forwarded-For` / `X-Real-IP` headers as a fallback when `ctx.ip` is not populated by the server (default: `false`).
200
+ * When `ctx.ip` is provided by Prunelle's `trustProxy`-aware server, `ctx.ip` is always used.
201
+ */
202
+ trustProxy?: TrustProxy | undefined
203
+ /** Optional per-key rate limit on auth endpoints (`false` disables). */
204
+ rateLimit?: RateLimitOptions | false | undefined
205
+ /** Periodic interval in ms to purge expired sessions and tokens (default: 15 minutes; `false` disables). */
206
+ pruneIntervalMs?: number | false | undefined
207
+ /**
208
+ * Control recording of client IP addresses on sessions (RGPD data minimization):
209
+ * - `'truncate'`: anonymize IPv4 to /24 (`a.b.c.0`) and IPv6 to /48 (`a:b:c::`) (default)
210
+ * - `true`: store full client IP
211
+ * - `false`: do not record IP on sessions
212
+ */
213
+ storeIp?: boolean | 'truncate' | undefined
214
+ /** Whether an OAuth sign-up keeps the provider's display name and avatar URL on the new account (default: `false`, RGPD data minimisation: the account holds the email alone). */
215
+ storeOAuthProfile?: boolean | undefined
216
+ /** Whether to record the `User-Agent` header on sessions (default: `true`). */
217
+ storeUserAgent?: boolean | undefined
218
+ /** TOTP second-factor configuration (`issuer`, `verifyPath`). */
219
+ totp?: TotpOptions | undefined
220
+ /** Redirect path for HTML form sign-ins when 2FA is required (overrides `totp.verifyPath`, defaults to `${basePath}/totp/verify`). */
221
+ twoFactorRedirect?: string | undefined
222
+ /** WebAuthn Passkeys configuration (`rpId`, `rpName`, `origin`, `userVerification`). */
223
+ passkeys?: PasskeyOptions | undefined
224
+ /** Organization invitation lifetime in seconds (default: 7 days). */
225
+ orgInviteTtlSeconds?: number | undefined
226
+ }
227
+
228
+ export interface GuardOptions<TUser extends AuthUser = AuthUser> {
229
+ /** Redirect unauthenticated HTML requests here (JSON/API requests always receive 401). */
230
+ redirectTo?: string | undefined
231
+ /** Required role(s): checks `orgMembership.role` when `org` is set, otherwise `user.role`. */
232
+ role?: string | string[] | undefined
233
+ /**
234
+ * Require organization membership and populate `ctx.locals.org` & `ctx.locals.orgMembership`:
235
+ * - `true`: reads `ctx.params.org ?? ctx.params.orgId ?? ctx.params.slug`
236
+ * - `string`: reads `ctx.params[org]` (or falls back to looking up `org` as a slug/id)
237
+ * - function: calls `await org(ctx)` to resolve the org id or slug
238
+ */
239
+ org?: boolean | string | ((ctx: RequestContext) => string | undefined | Promise<string | undefined>) | undefined
240
+ /** Custom authorization predicate. */
241
+ allow?: ((user: PublicUser<TUser>, ctx: RequestContext) => boolean | Promise<boolean>) | undefined
242
+ }
243
+
244
+ /** The plugin `prunelle.config.ts` registers, and the handle routes and actions call. */
245
+ export interface Auth<TUser extends AuthUser = AuthUser> extends PrunellePlugin {
246
+ readonly store: AuthStore<TUser>
247
+ readonly basePath: string
248
+ getUser(ctx: { locals: PrunelleLocals }): PublicUser<TUser> | undefined
249
+ getSession(ctx: { locals: PrunelleLocals }): AuthSession | undefined
250
+ /** The error or notice a sign-in, sign-up or two-factor form post carried back to the page at `url`, for the page to show; `undefined` when there is none. */
251
+ formMessage(url: URL): AuthFormMessage | undefined
252
+ resolve(ctx: RequestContext): Promise<{ user: PublicUser<TUser>, session: AuthSession } | undefined>
253
+ guard(options?: GuardOptions<TUser>): Middleware
254
+ createUser(input: CreateUserInput<TUser>): Promise<PublicUser<TUser>>
255
+ createSessionForUser(userId: string, ctx: RequestContext): Promise<AuthSession>
256
+ signOut(ctx: RequestContext): Promise<void>
257
+ revokeAllSessions(userId: string): Promise<void>
258
+ sendMagicLink(email: string, origin: string, redirectTo?: string): Promise<string>
259
+ sendVerificationEmail(email: string, origin: string, redirectTo?: string): Promise<string>
260
+ setupTotp(userId: string, opts?: { issuer?: string | undefined }): Promise<{ secret: string, otpauthUrl: string }>
261
+ confirmTotp(userId: string, code: string): Promise<{ enabled: true, recoveryCodes: string[] }>
262
+ verifyTotp(userId: string, code: string): Promise<{ valid: boolean, method?: 'totp' | 'recovery' | undefined }>
263
+ disableTotp(userId: string, code: string): Promise<boolean>
264
+ regenerateRecoveryCodes(userId: string): Promise<string[]>
265
+ listPasskeys(userId: string): Promise<PasskeySummary[]>
266
+ deletePasskey(userId: string, credentialId: string): Promise<boolean>
267
+ createOrg(ownerUserId: string, input: CreateOrgInput): Promise<Organization>
268
+ getOrg(idOrSlug: string): Promise<Organization | undefined>
269
+ listUserOrgs(userId: string): Promise<UserOrgSummary[]>
270
+ listOrgMembers(orgId: string): Promise<OrgMembership[]>
271
+ addOrgMember(orgId: string, userId: string, role?: string): Promise<OrgMembership>
272
+ updateOrgMemberRole(orgId: string, userId: string, role: string): Promise<OrgMembership | undefined>
273
+ removeOrgMember(orgId: string, userId: string): Promise<boolean>
274
+ inviteToOrg(orgId: string, input: InviteToOrgInput): Promise<{ invitation: OrgInvitation, url: string }>
275
+ acceptOrgInvite(token: string, userId: string): Promise<{ org: Organization, membership: OrgMembership }>
276
+ revokeOrgInvite(orgId: string, inviteId: string): Promise<boolean>
277
+ deleteOrg(orgId: string): Promise<void>
278
+ listSessions(userId: string): Promise<AuthSession[]>
279
+ exportUser(userId: string): Promise<UserExport<TUser> | null>
280
+ deleteUser(userId: string): Promise<void>
281
+ pruneExpired(): Promise<void>
282
+ dispose(): void
283
+ }
284
+
285
+ const NO_MAILER = '`requireEmailVerification` is on but no mailer is set, so no sign-up can ever be verified: pass `mailer` (`createMailer()` from `@prunellejs/mail`) or `sendMail`, or set `requireEmailVerification: false`.'
286
+ const DEFAULT_UNVERIFIED_TTL_SECONDS = 7 * 24 * 60 * 60
287
+ const DEFAULT_ABSOLUTE_TTL_SECONDS = 90 * 24 * 60 * 60
288
+
289
+ /** Session timings and cookie/privacy settings derived from `AuthOptions`. */
290
+ function sessionConfig(options: Pick<AuthOptions, 'sessionTtlSeconds' | 'absoluteTtlSeconds' | 'renewalIntervalSeconds' | 'acceptLegacyCookie' | 'storeIp' | 'storeUserAgent'>) {
291
+ const sessionTtlSeconds = options.sessionTtlSeconds ?? 60 * 60 * 24 * 30
292
+ const sessionTtlMs = sessionTtlSeconds * 1000
293
+ return {
294
+ sessionTtlMs,
295
+ absoluteTtlMs: options.absoluteTtlSeconds === false ? undefined : Math.max(sessionTtlMs, (options.absoluteTtlSeconds ?? DEFAULT_ABSOLUTE_TTL_SECONDS) * 1000),
296
+ renewalIntervalMs: Math.max(0, (options.renewalIntervalSeconds ?? Math.min(60 * 60, Math.max(1, Math.floor(sessionTtlSeconds / 4)))) * 1000),
297
+ acceptLegacyCookie: options.acceptLegacyCookie === true,
298
+ storeIp: options.storeIp ?? 'truncate' as const,
299
+ storeUserAgent: options.storeUserAgent !== false,
300
+ }
301
+ }
302
+
303
+ function unverifiedPruneOptions(ttlSeconds: number | false | undefined, requireEmailVerification: boolean): () => PruneOptions | undefined {
304
+ if (!requireEmailVerification || ttlSeconds === false)
305
+ return () => undefined
306
+ const ttlMs = (ttlSeconds ?? DEFAULT_UNVERIFIED_TTL_SECONDS) * 1000
307
+ return () => ({ unverifiedCreatedBefore: Date.now() - ttlMs })
308
+ }
309
+
310
+ const STORE_IN_MEMORY = '`store` keeps accounts and sessions in memory, so a restart signs everyone out and loses every account: pass `store: sqliteAuthStore(\'data/auth.db\')` from `@prunellejs/auth/sqlite`, or your own `AuthStore`.'
311
+
312
+ function routeOriginOptions(options: Pick<AuthOptions, 'trustedOrigins' | 'trustProxy'>) {
313
+ return {
314
+ ...(options.trustedOrigins !== undefined ? { trustedOrigins: options.trustedOrigins } : {}),
315
+ ...(options.trustProxy !== undefined ? { trustProxy: options.trustProxy } : {}),
316
+ }
317
+ }
318
+
319
+ function isSecureRequest(ctx: RequestContext, trustProxy: Parameters<typeof isHttpsRequest>[1]): boolean {
320
+ return ctx.url.protocol === 'https:' || isHttpsRequest(ctx.request, trustProxy) || nodeEnv() === 'production'
321
+ }
322
+
323
+ function configuredSecret(optionSecret: string | undefined): string | undefined {
324
+ const envSecret = process.env.AUTH_SECRET
325
+ return optionSecret ?? (envSecret !== undefined && envSecret.trim().length > 0 ? envSecret : undefined)
326
+ }
327
+
328
+ // What production refuses in a secret; anywhere else a missing one is a key made at start.
329
+ function secretProblem(configured: string | undefined): string | undefined {
330
+ if (configured === undefined)
331
+ return `no \`secret\`, so TOTP seeds are encrypted, and the two-factor, passkey and OAuth cookies signed, with a key made at each start, and after a restart no one with two-factor sign-in can sign in: set \`AUTH_SECRET\` to ${MIN_PROD_SECRET_BYTES} random bytes or more (\`openssl rand -base64 32\`), or pass \`secret\` to \`createAuth()\`.`
332
+ const bytes = Buffer.byteLength(configured, 'utf8')
333
+ return bytes < MIN_PROD_SECRET_BYTES ? `\`secret\` is ${bytes} bytes, too short to resist guessing: give it ${MIN_PROD_SECRET_BYTES} random bytes or more (\`openssl rand -base64 32\`).` : undefined
334
+ }
335
+
336
+ // The secret, resolved at first use rather than when prunelle.config.ts imports the app's auth: a build signs nothing, and a production start refuses a missing one through `requires`.
337
+ function lazySecret(optionSecret: string | undefined): () => string {
338
+ if (optionSecret !== undefined && optionSecret.trim().length === 0)
339
+ throw new Error('prunelle: @prunellejs/auth `secret` is empty: give it 32 random bytes or more, or leave it out and set `AUTH_SECRET`.')
340
+ let resolved: string | undefined
341
+ return () => {
342
+ if (resolved !== undefined)
343
+ return resolved
344
+ const configured = configuredSecret(optionSecret)
345
+ const problem = nodeEnv() === 'production' ? secretProblem(configured) : undefined
346
+ if (problem !== undefined)
347
+ throw new Error(`prunelle: @prunellejs/auth: ${problem}`)
348
+ resolved = configured ?? randomToken(32)
349
+ return resolved
350
+ }
351
+ }
352
+
353
+ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptions<TUser> = {}): Auth<TUser> {
354
+ const secret = lazySecret(options.secret)
355
+ const store = options.store ?? memoryAuthStore<TUser>()
356
+ const basePath = (options.basePath ?? '/auth').replace(/\/$/, '')
357
+ const cookieName = options.cookieName ?? 'pru_session'
358
+ const oauthCookieName = `${cookieName}_oauth`
359
+ const tokenTtlMs = (options.tokenTtlSeconds ?? 60 * 15) * 1000
360
+ const minPasswordLength = options.minPasswordLength ?? 12
361
+ const maxPasswordLength = options.maxPasswordLength ?? DEFAULT_MAX_PASSWORD_LENGTH
362
+ const defaultRole = options.defaultRole ?? 'user'
363
+ const defaultRedirect = options.defaultRedirect ?? '/'
364
+ const authRouteOpts = routeOriginOptions(options)
365
+ let site = options.site !== undefined ? siteOrigin(options.site) : undefined
366
+ const deliverMail = buildMailDeliverer(options.sendMail, options.mailer)
367
+ const requireEmailVerification = options.requireEmailVerification !== false
368
+ let trustProxy = options.trustProxy ?? false
369
+
370
+ const pruneIntervalMs = options.pruneIntervalMs === false ? undefined : (options.pruneIntervalMs ?? DEFAULT_PRUNE_INTERVAL_MS)
371
+ const pruneOptions = unverifiedPruneOptions(options.unverifiedTtlSeconds, requireEmailVerification)
372
+ const providers = new Map<string, OAuthProvider>((options.providers ?? []).map(p => [p.id, p]))
373
+ const messages = authFormMessages(minPasswordLength, maxPasswordLength)
374
+
375
+ const isSecureCookie = (ctx: RequestContext): boolean => isSecureRequest(ctx, trustProxy)
376
+
377
+ const sessions = createSessionManager({
378
+ store,
379
+ cookieName,
380
+ ...sessionConfig(options),
381
+ getTrustProxy: () => trustProxy,
382
+ isSecureCookie,
383
+ })
384
+
385
+ const twoFactorRedirect = options.twoFactorRedirect ?? options.totp?.verifyPath ?? `${basePath}/totp/verify`
386
+ const totp = createTotpManager({
387
+ store,
388
+ sessions,
389
+ secret,
390
+ twoFactorCookieName: `${cookieName}_2fa`,
391
+ getDefaultIssuer: () => options.totp?.issuer ?? (site ? new URL(site).hostname : 'Prunelle'),
392
+ isSecureCookie,
393
+ })
394
+ const account = createAccountService(store, sessions, options)
395
+ const passkeys = createPasskeyManager({
396
+ store,
397
+ sessions,
398
+ secret,
399
+ challengeCookieName: `${cookieName}_webauthn`,
400
+ getSite: () => site,
401
+ options: options.passkeys,
402
+ isSecureCookie,
403
+ })
404
+ const orgs = createOrgManager({
405
+ store,
406
+ sessions,
407
+ basePath,
408
+ defaultRedirect,
409
+ orgInviteTtlMs: options.orgInviteTtlSeconds !== undefined ? options.orgInviteTtlSeconds * 1000 : undefined,
410
+ deliverMail,
411
+ })
412
+
413
+ // One timer per server the plugin runs on: `prunelle dev` starts the next server before it shuts the previous one down.
414
+ const pruneTimers = new Set<ReturnType<typeof setInterval>>()
415
+ let activeServers = 0
416
+ const startPruneTimer = (): (() => void) | undefined => {
417
+ if (pruneIntervalMs === undefined || pruneIntervalMs <= 0)
418
+ return undefined
419
+ const timer = setInterval(() => {
420
+ try {
421
+ void Promise.resolve(store.pruneExpired?.(pruneOptions())).catch(() => {})
422
+ sessions.sweepRenewedAt()
423
+ passkeys.pruneChallenges()
424
+ }
425
+ catch {
426
+ // Ignore prune errors if the underlying store has been closed
427
+ }
428
+ }, pruneIntervalMs)
429
+ timer.unref?.()
430
+ pruneTimers.add(timer)
431
+ return () => {
432
+ clearInterval(timer)
433
+ pruneTimers.delete(timer)
434
+ }
435
+ }
436
+
437
+ async function insertUser(fields: Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>): Promise<TUser> {
438
+ const now = Date.now()
439
+ const defaults = typeof options.defaultUserFields === 'function'
440
+ ? (options.defaultUserFields as () => Partial<TUser>)()
441
+ : (options.defaultUserFields as Partial<TUser> | undefined)
442
+ return sessions.observeAsync(store.createUser({
443
+ id: crypto.randomUUID(),
444
+ role: defaultRole,
445
+ createdAt: now,
446
+ updatedAt: now,
447
+ ...defaults,
448
+ ...fields,
449
+ } as TUser))
450
+ }
451
+
452
+ async function createUser(input: CreateUserInput<TUser>): Promise<PublicUser<TUser>> {
453
+ const { email: rawEmail, password, name, avatarUrl, role, emailVerified, ...extra } = input
454
+ const email = normalizeEmail(rawEmail)
455
+ if (!isValidEmail(email))
456
+ throw new Error('Invalid email address')
457
+ if (await sessions.observeAsync(store.getUserByEmail(email)))
458
+ throw new Error('Email is already registered')
459
+
460
+ const passwordHash = password !== undefined ? await hashPassword(password) : undefined
461
+ const created = await insertUser({
462
+ ...extra,
463
+ email,
464
+ ...(name !== undefined ? { name } : {}),
465
+ ...(avatarUrl !== undefined ? { avatarUrl } : {}),
466
+ ...(role !== undefined ? { role } : {}),
467
+ emailVerified: emailVerified ?? false,
468
+ ...(passwordHash !== undefined ? { passwordHash } : {}),
469
+ } as Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>)
470
+ return toPublicUser(created)
471
+ }
472
+
473
+ const mailedLinkOrigin = (url: URL): string | undefined => linkOrigin(site, url)
474
+
475
+ // Whoever signed up with an address before it was proven may hold its password, sessions and provider links; proving it hands the account to the owner alone.
476
+ // The password goes first, so a squatter cannot sign in again between the purge and the update.
477
+ async function claimUnverified(user: TUser): Promise<TUser> {
478
+ const claimed = (await sessions.observeAsync(store.updateUser(user.id, { emailVerified: true, passwordHash: undefined } as Partial<Omit<TUser, 'id' | 'createdAt'>>))) ?? user
479
+ await sessions.observeAsync(store.deleteUserSessions(user.id))
480
+ await sessions.observeAsync(store.deleteUserOAuthAccounts(user.id))
481
+ return claimed
482
+ }
483
+
484
+ const links = createLinkService({ store, sessions, basePath, defaultRedirect, tokenTtlMs, deliverMail })
485
+ const { issueLink, sendVerificationEmail, sendMagicLink, consumeLink } = links
486
+
487
+ const guard = (guardOpts?: GuardOptions<TUser>): Middleware => createAuthGuard(sessions.resolve, orgs, guardOpts)
488
+
489
+ const dispose = (): void => {
490
+ for (const timer of pruneTimers)
491
+ clearInterval(timer)
492
+ pruneTimers.clear()
493
+ activeServers = 0
494
+ void Promise.resolve(store.close?.()).catch(() => {})
495
+ }
496
+
497
+ function registerServerRoutes(api: ServerPluginAPI): void {
498
+ const authLimitsObj = authLimits(createAuthLimiters(api, options.rateLimit), () => trustProxy)
499
+ const authRoute = createAuthRouteRegistrar(api, basePath, authRouteOpts, authLimitsObj)
500
+ const hasMailTransport = deliverMail !== undefined
501
+
502
+ registerAuthRoutes({
503
+ authRoute,
504
+ limits: authLimitsObj,
505
+ store,
506
+ sessions,
507
+ totp,
508
+ twoFactorRedirect,
509
+ minPasswordLength,
510
+ maxPasswordLength,
511
+ messages,
512
+ defaultRedirect,
513
+ requireEmailVerification,
514
+ hasMailTransport,
515
+ mailedLinkOrigin,
516
+ createUser,
517
+ insertUser,
518
+ claimUnverified,
519
+ issueLink,
520
+ consumeLink,
521
+ sendMagicLink,
522
+ })
523
+ registerTotpRoutes({ authRoute, store, sessions, totp, basePath, defaultRedirect, messages })
524
+ registerPasskeyRoutes({ authRoute, store, sessions, passkeys, totp, twoFactorRedirect, defaultRedirect, requireEmailVerification })
525
+ registerOrgRoutes({ authRoute, limits: authLimitsObj, sessions, orgs, defaultRedirect, hasMailTransport, mailedLinkOrigin })
526
+ registerAccountRoutes({ authRoute, sessions, account, clearPendingCookie: ctx => totp.clearPendingCookie(ctx) })
527
+ registerOAuthRoutes({
528
+ route: (method, path, handler) => api.route(method, path, handler),
529
+ store,
530
+ providers,
531
+ secret,
532
+ site,
533
+ basePath,
534
+ stateCookieName: oauthCookieName,
535
+ defaultRedirect,
536
+ requireEmailVerification,
537
+ hasMailTransport,
538
+ mailedLinkOrigin,
539
+ issueLink,
540
+ limitIp: authLimitsObj.limitIp,
541
+ isSecureCookie,
542
+ claimUnverified,
543
+ insertUser,
544
+ storeProfile: options.storeOAuthProfile === true,
545
+ totp,
546
+ twoFactorRedirect,
547
+ createSessionForUser: sessions.createSessionForUser,
548
+ observeAsync: sessions.observeAsync,
549
+ })
550
+ }
551
+
552
+ const plugin: PrunellePlugin = definePlugin({
553
+ name: '@prunellejs/auth',
554
+ enforce: 'pre',
555
+ providesLocals: ['user', 'session', 'org', 'orgMembership'],
556
+ requires: () => [isKeptInMemory(store) ? STORE_IN_MEMORY : undefined, requireEmailVerification && deliverMail === undefined ? NO_MAILER : undefined, secretProblem(configuredSecret(options.secret))].filter(line => line !== undefined),
557
+ server(api) {
558
+ if (options.trustProxy === undefined)
559
+ trustProxy = api.trustProxy
560
+ if (options.site === undefined && api.site !== undefined)
561
+ site = siteOrigin(api.site)
562
+ activeServers++
563
+ const stopPruneTimer = startPruneTimer()
564
+ let stopped = false
565
+ api.onShutdown(async () => {
566
+ if (stopped)
567
+ return
568
+ stopped = true
569
+ stopPruneTimer?.()
570
+ activeServers = Math.max(0, activeServers - 1)
571
+ if (activeServers === 0)
572
+ await links.drain().then(() => store.close?.())
573
+ })
574
+
575
+ // Sync stores resolve lazily on first read of ctx.locals.user/session; async or unknown Promise-returning stores await before next().
576
+ const internalPrefix = `${api.assetPrefix.replace(/\/$/, '')}/`
577
+ const actionPrefix = `${internalPrefix}action/`
578
+ api.use((ctx, next) => {
579
+ const p = ctx.url.pathname
580
+ if (!p.startsWith(internalPrefix) || p.startsWith(actionPrefix)) {
581
+ const pending = sessions.prepareRequest(ctx)
582
+ if (pending !== undefined)
583
+ return pending.then(() => next())
584
+ }
585
+ return next()
586
+ }, { scope: 'rendered' })
587
+
588
+ registerServerRoutes(api)
589
+ },
590
+ })
591
+
592
+ return {
593
+ ...plugin,
594
+ store,
595
+ basePath,
596
+ getUser: sessions.getUser,
597
+ getSession: sessions.getSession,
598
+ formMessage: url => readFormMessage(messages, url),
599
+ resolve: sessions.resolve,
600
+ guard,
601
+ createUser,
602
+ createSessionForUser: (userId, ctx) => sessions.createSessionForUser(userId, ctx),
603
+ signOut: sessions.signOut,
604
+ revokeAllSessions: async (userId) => { await sessions.observeAsync(store.deleteUserSessions(userId)) },
605
+ sendMagicLink,
606
+ sendVerificationEmail,
607
+ setupTotp: totp.setupTotp,
608
+ confirmTotp: totp.confirmTotp,
609
+ verifyTotp: totp.verifyTotp,
610
+ disableTotp: totp.disableTotp,
611
+ regenerateRecoveryCodes: totp.regenerateRecoveryCodes,
612
+ listPasskeys: passkeys.listPasskeys,
613
+ deletePasskey: passkeys.deletePasskey,
614
+ createOrg: orgs.createOrg,
615
+ getOrg: orgs.getOrg,
616
+ listUserOrgs: orgs.listUserOrgs,
617
+ listOrgMembers: orgs.listOrgMembers,
618
+ addOrgMember: orgs.addOrgMember,
619
+ updateOrgMemberRole: orgs.updateOrgMemberRole,
620
+ removeOrgMember: orgs.removeOrgMember,
621
+ inviteToOrg: orgs.inviteToOrg,
622
+ acceptOrgInvite: orgs.acceptOrgInvite,
623
+ revokeOrgInvite: orgs.revokeOrgInvite,
624
+ deleteOrg: orgs.deleteOrg,
625
+ listSessions: async userId => await sessions.observeAsync(store.listSessions(userId)),
626
+ exportUser: account.exportUser,
627
+ deleteUser: account.deleteUser,
628
+ async pruneExpired() {
629
+ await store.pruneExpired?.(pruneOptions())
630
+ sessions.sweepRenewedAt()
631
+ passkeys.pruneChallenges()
632
+ },
633
+ dispose,
634
+ }
635
+ }