@prunellejs/auth 0.6.0 → 0.7.1
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/LICENSE +21 -0
- package/llms.txt +17 -11
- package/package.json +2 -2
- package/src/account.ts +101 -0
- package/src/form-messages.ts +58 -0
- package/src/http.ts +75 -29
- package/src/index.ts +124 -55
- package/src/links.ts +67 -39
- package/src/oauth-routes.ts +29 -24
- package/src/org-routes.ts +15 -5
- package/src/orgs.ts +17 -0
- package/src/passkey-client.ts +8 -4
- package/src/passkey-routes.ts +12 -2
- package/src/passkeys.ts +11 -14
- package/src/routes.ts +125 -92
- package/src/session-cookie.ts +62 -0
- package/src/session.ts +46 -42
- package/src/sqlite-ext.ts +6 -1
- package/src/sqlite.ts +97 -38
- package/src/store-ext.ts +9 -0
- package/src/store.ts +48 -19
- package/src/totp-routes.ts +11 -5
- package/src/totp.ts +99 -42
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
|
|
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,20 @@ 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>`. */
|
|
140
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
|
|
141
161
|
/** Session lifetime in seconds (default: 30 days). */
|
|
142
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
|
|
143
165
|
/** Minimum interval in seconds between sliding-expiry DB writes for the same session (default: up to 1 hour). */
|
|
144
166
|
renewalIntervalSeconds?: number | undefined
|
|
145
167
|
/** Magic-link / verification token lifetime in seconds (default: 15 minutes). */
|
|
146
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
|
|
147
171
|
/** Minimum password length (default: 12, aligned with CNIL guidance). */
|
|
148
172
|
minPasswordLength?: number | undefined
|
|
149
173
|
/** Maximum password length in characters / UTF-8 bytes before Argon2id hashing (default: 1024). */
|
|
@@ -162,6 +186,10 @@ export interface AuthOptions<TUser extends AuthUser = AuthUser> {
|
|
|
162
186
|
mailer?: AuthMailer | undefined
|
|
163
187
|
/** Custom mail sender for magic links / verification emails (overrides `mailer` when both are provided). */
|
|
164
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
|
|
165
193
|
/**
|
|
166
194
|
* Require email verification before opening a session on password sign-up / sign-in (default: `true`).
|
|
167
195
|
* Set explicitly to `false` only when you intentionally allow unverified password sessions (e.g. local dev without mail).
|
|
@@ -183,6 +211,8 @@ export interface AuthOptions<TUser extends AuthUser = AuthUser> {
|
|
|
183
211
|
* - `false`: do not record IP on sessions
|
|
184
212
|
*/
|
|
185
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
|
|
186
216
|
/** Whether to record the `User-Agent` header on sessions (default: `true`). */
|
|
187
217
|
storeUserAgent?: boolean | undefined
|
|
188
218
|
/** TOTP second-factor configuration (`issuer`, `verifyPath`). */
|
|
@@ -217,6 +247,8 @@ export interface Auth<TUser extends AuthUser = AuthUser> extends PrunellePlugin
|
|
|
217
247
|
readonly basePath: string
|
|
218
248
|
getUser(ctx: { locals: PrunelleLocals }): PublicUser<TUser> | undefined
|
|
219
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
|
|
220
252
|
resolve(ctx: RequestContext): Promise<{ user: PublicUser<TUser>, session: AuthSession } | undefined>
|
|
221
253
|
guard(options?: GuardOptions<TUser>): Middleware
|
|
222
254
|
createUser(input: CreateUserInput<TUser>): Promise<PublicUser<TUser>>
|
|
@@ -250,66 +282,102 @@ export interface Auth<TUser extends AuthUser = AuthUser> extends PrunellePlugin
|
|
|
250
282
|
dispose(): void
|
|
251
283
|
}
|
|
252
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
|
+
|
|
253
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`.'
|
|
254
311
|
|
|
255
|
-
function
|
|
256
|
-
|
|
257
|
-
|
|
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
|
+
}
|
|
258
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 {
|
|
259
324
|
const envSecret = process.env.AUTH_SECRET
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
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
|
|
266
350
|
}
|
|
267
|
-
return configured ?? randomToken(32)
|
|
268
351
|
}
|
|
269
352
|
|
|
270
353
|
export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptions<TUser> = {}): Auth<TUser> {
|
|
271
|
-
const secret =
|
|
354
|
+
const secret = lazySecret(options.secret)
|
|
272
355
|
const store = options.store ?? memoryAuthStore<TUser>()
|
|
273
356
|
const basePath = (options.basePath ?? '/auth').replace(/\/$/, '')
|
|
274
357
|
const cookieName = options.cookieName ?? 'pru_session'
|
|
275
358
|
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
359
|
const tokenTtlMs = (options.tokenTtlSeconds ?? 60 * 15) * 1000
|
|
280
360
|
const minPasswordLength = options.minPasswordLength ?? 12
|
|
281
361
|
const maxPasswordLength = options.maxPasswordLength ?? DEFAULT_MAX_PASSWORD_LENGTH
|
|
282
362
|
const defaultRole = options.defaultRole ?? 'user'
|
|
283
363
|
const defaultRedirect = options.defaultRedirect ?? '/'
|
|
284
|
-
const authRouteOpts =
|
|
285
|
-
...(options.trustedOrigins !== undefined ? { trustedOrigins: options.trustedOrigins } : {}),
|
|
286
|
-
...(options.trustProxy !== undefined ? { trustProxy: options.trustProxy } : {}),
|
|
287
|
-
}
|
|
364
|
+
const authRouteOpts = routeOriginOptions(options)
|
|
288
365
|
let site = options.site !== undefined ? siteOrigin(options.site) : undefined
|
|
289
366
|
const deliverMail = buildMailDeliverer(options.sendMail, options.mailer)
|
|
290
367
|
const requireEmailVerification = options.requireEmailVerification !== false
|
|
291
368
|
let trustProxy = options.trustProxy ?? false
|
|
292
369
|
|
|
293
|
-
const pruneIntervalMs = options.pruneIntervalMs === false
|
|
294
|
-
|
|
295
|
-
|
|
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)
|
|
296
374
|
|
|
297
|
-
const
|
|
298
|
-
for (const p of options.providers ?? [])
|
|
299
|
-
providers.set(p.id, p)
|
|
300
|
-
|
|
301
|
-
const isSecureCookie = (ctx: RequestContext): boolean =>
|
|
302
|
-
ctx.url.protocol === 'https:'
|
|
303
|
-
|| isHttpsRequest(ctx.request, trustProxy)
|
|
304
|
-
|| nodeEnv() === 'production'
|
|
375
|
+
const isSecureCookie = (ctx: RequestContext): boolean => isSecureRequest(ctx, trustProxy)
|
|
305
376
|
|
|
306
377
|
const sessions = createSessionManager({
|
|
307
378
|
store,
|
|
308
379
|
cookieName,
|
|
309
|
-
|
|
310
|
-
renewalIntervalMs,
|
|
311
|
-
storeIp: options.storeIp ?? 'truncate',
|
|
312
|
-
storeUserAgent: options.storeUserAgent !== false,
|
|
380
|
+
...sessionConfig(options),
|
|
313
381
|
getTrustProxy: () => trustProxy,
|
|
314
382
|
isSecureCookie,
|
|
315
383
|
})
|
|
@@ -323,6 +391,7 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
|
|
|
323
391
|
getDefaultIssuer: () => options.totp?.issuer ?? (site ? new URL(site).hostname : 'Prunelle'),
|
|
324
392
|
isSecureCookie,
|
|
325
393
|
})
|
|
394
|
+
const account = createAccountService(store, sessions, options)
|
|
326
395
|
const passkeys = createPasskeyManager({
|
|
327
396
|
store,
|
|
328
397
|
sessions,
|
|
@@ -349,7 +418,7 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
|
|
|
349
418
|
return undefined
|
|
350
419
|
const timer = setInterval(() => {
|
|
351
420
|
try {
|
|
352
|
-
void Promise.resolve(store.pruneExpired?.()).catch(() => {})
|
|
421
|
+
void Promise.resolve(store.pruneExpired?.(pruneOptions())).catch(() => {})
|
|
353
422
|
sessions.sweepRenewedAt()
|
|
354
423
|
passkeys.pruneChallenges()
|
|
355
424
|
}
|
|
@@ -401,12 +470,7 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
|
|
|
401
470
|
return toPublicUser(created)
|
|
402
471
|
}
|
|
403
472
|
|
|
404
|
-
|
|
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
|
-
}
|
|
473
|
+
const mailedLinkOrigin = (url: URL): string | undefined => linkOrigin(site, url)
|
|
410
474
|
|
|
411
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.
|
|
412
476
|
// The password goes first, so a squatter cannot sign in again between the purge and the update.
|
|
@@ -418,7 +482,7 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
|
|
|
418
482
|
}
|
|
419
483
|
|
|
420
484
|
const links = createLinkService({ store, sessions, basePath, defaultRedirect, tokenTtlMs, deliverMail })
|
|
421
|
-
const { issueLink, sendVerificationEmail, sendMagicLink, consumeLink
|
|
485
|
+
const { issueLink, sendVerificationEmail, sendMagicLink, consumeLink } = links
|
|
422
486
|
|
|
423
487
|
const guard = (guardOpts?: GuardOptions<TUser>): Middleware => createAuthGuard(sessions.resolve, orgs, guardOpts)
|
|
424
488
|
|
|
@@ -431,24 +495,24 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
|
|
|
431
495
|
}
|
|
432
496
|
|
|
433
497
|
function registerServerRoutes(api: ServerPluginAPI): void {
|
|
434
|
-
const
|
|
435
|
-
const authLimitsObj = authLimits(limits, () => trustProxy)
|
|
498
|
+
const authLimitsObj = authLimits(createAuthLimiters(api, options.rateLimit), () => trustProxy)
|
|
436
499
|
const authRoute = createAuthRouteRegistrar(api, basePath, authRouteOpts, authLimitsObj)
|
|
437
500
|
const hasMailTransport = deliverMail !== undefined
|
|
438
501
|
|
|
439
502
|
registerAuthRoutes({
|
|
440
503
|
authRoute,
|
|
504
|
+
limits: authLimitsObj,
|
|
441
505
|
store,
|
|
442
506
|
sessions,
|
|
443
507
|
totp,
|
|
444
508
|
twoFactorRedirect,
|
|
445
509
|
minPasswordLength,
|
|
446
510
|
maxPasswordLength,
|
|
511
|
+
messages,
|
|
447
512
|
defaultRedirect,
|
|
448
513
|
requireEmailVerification,
|
|
449
514
|
hasMailTransport,
|
|
450
515
|
mailedLinkOrigin,
|
|
451
|
-
equalizeSignupMailDelay,
|
|
452
516
|
createUser,
|
|
453
517
|
insertUser,
|
|
454
518
|
claimUnverified,
|
|
@@ -456,9 +520,10 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
|
|
|
456
520
|
consumeLink,
|
|
457
521
|
sendMagicLink,
|
|
458
522
|
})
|
|
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 })
|
|
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) })
|
|
462
527
|
registerOAuthRoutes({
|
|
463
528
|
route: (method, path, handler) => api.route(method, path, handler),
|
|
464
529
|
store,
|
|
@@ -476,6 +541,9 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
|
|
|
476
541
|
isSecureCookie,
|
|
477
542
|
claimUnverified,
|
|
478
543
|
insertUser,
|
|
544
|
+
storeProfile: options.storeOAuthProfile === true,
|
|
545
|
+
totp,
|
|
546
|
+
twoFactorRedirect,
|
|
479
547
|
createSessionForUser: sessions.createSessionForUser,
|
|
480
548
|
observeAsync: sessions.observeAsync,
|
|
481
549
|
})
|
|
@@ -485,7 +553,7 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
|
|
|
485
553
|
name: '@prunellejs/auth',
|
|
486
554
|
enforce: 'pre',
|
|
487
555
|
providesLocals: ['user', 'session', 'org', 'orgMembership'],
|
|
488
|
-
requires: () => isKeptInMemory(store) ?
|
|
556
|
+
requires: () => [isKeptInMemory(store) ? STORE_IN_MEMORY : undefined, requireEmailVerification && deliverMail === undefined ? NO_MAILER : undefined, secretProblem(configuredSecret(options.secret))].filter(line => line !== undefined),
|
|
489
557
|
server(api) {
|
|
490
558
|
if (options.trustProxy === undefined)
|
|
491
559
|
trustProxy = api.trustProxy
|
|
@@ -501,7 +569,7 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
|
|
|
501
569
|
stopPruneTimer?.()
|
|
502
570
|
activeServers = Math.max(0, activeServers - 1)
|
|
503
571
|
if (activeServers === 0)
|
|
504
|
-
await store.close?.()
|
|
572
|
+
await links.drain().then(() => store.close?.())
|
|
505
573
|
})
|
|
506
574
|
|
|
507
575
|
// Sync stores resolve lazily on first read of ctx.locals.user/session; async or unknown Promise-returning stores await before next().
|
|
@@ -527,6 +595,7 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
|
|
|
527
595
|
basePath,
|
|
528
596
|
getUser: sessions.getUser,
|
|
529
597
|
getSession: sessions.getSession,
|
|
598
|
+
formMessage: url => readFormMessage(messages, url),
|
|
530
599
|
resolve: sessions.resolve,
|
|
531
600
|
guard,
|
|
532
601
|
createUser,
|
|
@@ -554,10 +623,10 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
|
|
|
554
623
|
revokeOrgInvite: orgs.revokeOrgInvite,
|
|
555
624
|
deleteOrg: orgs.deleteOrg,
|
|
556
625
|
listSessions: async userId => await sessions.observeAsync(store.listSessions(userId)),
|
|
557
|
-
exportUser:
|
|
558
|
-
deleteUser:
|
|
626
|
+
exportUser: account.exportUser,
|
|
627
|
+
deleteUser: account.deleteUser,
|
|
559
628
|
async pruneExpired() {
|
|
560
|
-
await store.pruneExpired?.()
|
|
629
|
+
await store.pruneExpired?.(pruneOptions())
|
|
561
630
|
sessions.sweepRenewedAt()
|
|
562
631
|
passkeys.pruneChallenges()
|
|
563
632
|
},
|
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
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
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,7 @@ 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
|
|
52
|
+
const pendingDeliveries = new Set<Promise<void>>()
|
|
65
53
|
|
|
66
54
|
async function issueLink(
|
|
67
55
|
kind: 'magic-link' | 'verify-email',
|
|
@@ -69,6 +57,7 @@ export function createLinkService<TUser extends AuthUser = AuthUser>(deps: LinkS
|
|
|
69
57
|
email: string,
|
|
70
58
|
origin: string | undefined,
|
|
71
59
|
redirectTo: string | undefined,
|
|
60
|
+
background?: MailInBackground,
|
|
72
61
|
): Promise<string> {
|
|
73
62
|
const normalized = normalizeEmail(email)
|
|
74
63
|
const boundUser = kind === 'verify-email' && userId !== undefined ? await sessions.observeAsync(store.getUserById(userId)) : undefined
|
|
@@ -87,32 +76,52 @@ export function createLinkService<TUser extends AuthUser = AuthUser>(deps: LinkS
|
|
|
87
76
|
const url = origin !== undefined ? `${origin.replace(/\/$/, '')}${path}` : path
|
|
88
77
|
|
|
89
78
|
if (deliverMail && origin !== undefined) {
|
|
90
|
-
const
|
|
91
|
-
|
|
92
|
-
|
|
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)
|
|
79
|
+
const delivery = deliverLink(deliverMail, kind, normalized, url, tokenHash)
|
|
80
|
+
if (background === undefined) {
|
|
81
|
+
await delivery
|
|
102
82
|
}
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
}
|
|
107
|
-
catch (cleanupErr) {
|
|
108
|
-
console.error('[prunelle/auth] failed to clean up token after mail error:', cleanupErr)
|
|
109
|
-
}
|
|
110
|
-
throw err
|
|
83
|
+
else {
|
|
84
|
+
const tracked = delivery.catch(err => failBackgroundMail(err, background)).finally(() => { pendingDeliveries.delete(tracked) })
|
|
85
|
+
pendingDeliveries.add(tracked)
|
|
111
86
|
}
|
|
112
87
|
}
|
|
113
88
|
return url
|
|
114
89
|
}
|
|
115
90
|
|
|
91
|
+
// Mails the link; a mail that cannot be sent takes its token back, so a link that never arrived cannot be used.
|
|
92
|
+
async function deliverLink(send: MailDeliverer, kind: 'magic-link' | 'verify-email', to: string, url: string, tokenHash: string): Promise<void> {
|
|
93
|
+
const mail = LINK_MAILS[kind]
|
|
94
|
+
try {
|
|
95
|
+
await send({
|
|
96
|
+
to,
|
|
97
|
+
subject: mail.subject,
|
|
98
|
+
text: `${mail.text}: ${url}`,
|
|
99
|
+
html: `<p>${mail.html}: <a href="${url}">${mail.label}</a></p>`,
|
|
100
|
+
url,
|
|
101
|
+
kind,
|
|
102
|
+
})
|
|
103
|
+
}
|
|
104
|
+
catch (err) {
|
|
105
|
+
try {
|
|
106
|
+
await sessions.observeAsync(store.consumeToken(tokenHash, kind))
|
|
107
|
+
}
|
|
108
|
+
catch (cleanupErr) {
|
|
109
|
+
console.error('[prunelle/auth] failed to clean up token after mail error:', cleanupErr)
|
|
110
|
+
}
|
|
111
|
+
throw err
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async function failBackgroundMail(err: unknown, background: MailInBackground): Promise<void> {
|
|
116
|
+
console.error('[prunelle/auth] could not send a verification mail:', err)
|
|
117
|
+
try {
|
|
118
|
+
await background.onFailure()
|
|
119
|
+
}
|
|
120
|
+
catch (rollbackErr) {
|
|
121
|
+
console.error('[prunelle/auth] failed to roll back after a mail error:', rollbackErr)
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
116
125
|
async function sendVerificationEmail(email: string, origin: string, redirectTo?: string): Promise<string> {
|
|
117
126
|
const normalized = normalizeEmail(email)
|
|
118
127
|
const existing = await sessions.observeAsync(store.getUserByEmail(normalized))
|
|
@@ -140,11 +149,30 @@ export function createLinkService<TUser extends AuthUser = AuthUser>(deps: LinkS
|
|
|
140
149
|
return { email: consumed.email, user }
|
|
141
150
|
}
|
|
142
151
|
|
|
152
|
+
async function drain(timeoutMs = 5_000): Promise<void> {
|
|
153
|
+
if (pendingDeliveries.size === 0)
|
|
154
|
+
return
|
|
155
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
156
|
+
try {
|
|
157
|
+
await Promise.race([
|
|
158
|
+
Promise.allSettled([...pendingDeliveries]),
|
|
159
|
+
new Promise<void>((resolve) => {
|
|
160
|
+
timer = setTimeout(resolve, timeoutMs)
|
|
161
|
+
timer.unref?.()
|
|
162
|
+
}),
|
|
163
|
+
])
|
|
164
|
+
}
|
|
165
|
+
finally {
|
|
166
|
+
if (timer !== undefined)
|
|
167
|
+
clearTimeout(timer)
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
143
171
|
return {
|
|
144
172
|
issueLink,
|
|
145
173
|
sendVerificationEmail,
|
|
146
174
|
sendMagicLink,
|
|
147
175
|
consumeLink,
|
|
148
|
-
|
|
176
|
+
drain,
|
|
149
177
|
}
|
|
150
178
|
}
|