@prunellejs/auth 0.1.1 → 0.5.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/llms.txt +3 -3
- package/package.json +2 -2
- package/src/index.ts +88 -60
- package/src/oauth-routes.ts +103 -41
- package/src/routes.ts +73 -25
- package/src/session.ts +113 -63
- package/src/sqlite.ts +3 -3
- package/src/store.ts +15 -2
package/llms.txt
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
## Imports
|
|
6
6
|
|
|
7
|
-
- `@prunellejs/auth`: `createAuth`, `memoryAuthStore`, `normalizeEmail`, `toPublicUser`, `safeRedirect` (re-exported from `prunelle/server`), `
|
|
7
|
+
- `@prunellejs/auth`: `createAuth`, `memoryAuthStore`, `normalizeEmail`, `toPublicUser`, `safeRedirect` (re-exported from `prunelle/server`), `github`, `discord`, `google`, `oauthProvider`; types `Auth`, `AuthOptions`, `GuardOptions`, `AuthStore`, `AuthUser`, `PublicUser`, `AuthSession`, `OAuthAccount`, `TokenKind`, `VerificationToken`, `UserExport`, `AuthMailPayload`, `AuthMailer`, `CreateUserInput`, `OAuthProvider`, `OAuthPresetConfig`, `OAuthProfile`, `RateLimitOptions`.
|
|
8
8
|
- `@prunellejs/auth/sqlite`: `sqliteAuthStore(dbOrPath?: string | Database)` (returns `AuthStore & { readonly db: Database }`, uses `bun:sqlite` in WAL mode).
|
|
9
9
|
- `@prunellejs/auth/oauth`: `github`, `discord`, `google`, `oauthProvider`.
|
|
10
10
|
|
|
@@ -18,8 +18,8 @@
|
|
|
18
18
|
- `basePath`: route prefix (default `'/auth'`).
|
|
19
19
|
- `cookieName`: session cookie name (default `'pru_session'`).
|
|
20
20
|
- `sessionTtlSeconds` (default 30 days), `renewalIntervalSeconds` (sliding renewal), `tokenTtlSeconds` (default 15 min).
|
|
21
|
-
- `minPasswordLength`: default `12` (CNIL guidance). `defaultRole`: `'user'`. `defaultRedirect`: `'/'`.
|
|
22
|
-
- `requireEmailVerification`: default `true` (signup sends verification link and returns `202` without opening a session; signin refuses unverified users with `403
|
|
21
|
+
- `minPasswordLength`: default `12` (CNIL guidance). `maxPasswordLength`: default `1024` (chars/UTF-8 bytes, capped before Argon2id). `defaultRole`: `'user'`. `defaultRedirect`: `'/'`.
|
|
22
|
+
- `requireEmailVerification`: default `true` (signup sends verification link and returns `202` without opening a session; signin refuses unverified users with `403`; unverified OAuth callbacks require email verification and do not open a session or persist an unverified link).
|
|
23
23
|
- `mailer`: pass a `@prunellejs/mail` `Mailer` directly, or `sendMail(mail: AuthMailPayload)`.
|
|
24
24
|
- `providers`: `[github({ clientId, clientSecret, scopes? }), discord(...), google(...), oauthProvider(...)]`.
|
|
25
25
|
- `trustProxy`: inherits `PrunelleConfig.trustProxy`. `trustedOrigins`: merged with `PrunelleConfig.trustedOrigins`.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prunellejs/auth",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.2",
|
|
4
4
|
"description": "Zero-dependency Bun-native auth plugin for Prunelle (Argon2id, hashed sessions, SQLite, magic links, OAuth2 PKCE)",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -23,6 +23,6 @@
|
|
|
23
23
|
"directory": "packages/plugin-auth"
|
|
24
24
|
},
|
|
25
25
|
"peerDependencies": {
|
|
26
|
-
"prunelle": "^0.
|
|
26
|
+
"prunelle": "^0.5.2"
|
|
27
27
|
}
|
|
28
28
|
}
|
package/src/index.ts
CHANGED
|
@@ -9,7 +9,7 @@ import type { OAuthProvider } from './oauth'
|
|
|
9
9
|
|
|
10
10
|
import type { AuthSession, AuthStore, AuthUser, PublicUser, UserExport } from './store'
|
|
11
11
|
import { definePlugin } from 'prunelle/config'
|
|
12
|
-
import {
|
|
12
|
+
import { isHttpsRequest, nodeEnv, safeEqual, safeRedirect, wantsJson } from 'prunelle/server'
|
|
13
13
|
import { hashPassword, randomToken, sha256Hex } from './crypto'
|
|
14
14
|
import { authLimits, fail, isValidEmail } from './http'
|
|
15
15
|
import { registerOAuthRoutes } from './oauth-routes'
|
|
@@ -30,24 +30,6 @@ export interface RateLimitOptions {
|
|
|
30
30
|
max?: number | undefined
|
|
31
31
|
/** Window duration in ms (default: 60_000). */
|
|
32
32
|
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
33
|
}
|
|
52
34
|
|
|
53
35
|
export { safeRedirect } from 'prunelle/server'
|
|
@@ -59,12 +41,73 @@ export type { AuthSession, AuthStore, AuthUser, OAuthAccount, PublicUser, TokenK
|
|
|
59
41
|
const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]'])
|
|
60
42
|
const DEFAULT_PRUNE_INTERVAL_MS = 15 * 60 * 1000
|
|
61
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
|
|
62
47
|
const LINK_PATHS = { 'magic-link': 'magic-link/verify', 'verify-email': 'verify-email' } as const
|
|
63
48
|
const LINK_MAILS = {
|
|
64
49
|
'magic-link': { subject: 'Your sign-in link', text: 'Sign in using this one-time link', html: 'Click to sign in', label: 'Sign in' },
|
|
65
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' },
|
|
66
51
|
} as const
|
|
67
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
|
+
|
|
68
111
|
// Mailed links and OAuth callbacks start with `site`, so anything but an http(s) origin is a config mistake.
|
|
69
112
|
function siteOrigin(value: string): string {
|
|
70
113
|
const url = new URL(value)
|
|
@@ -124,6 +167,8 @@ export interface AuthOptions<TUser extends AuthUser = AuthUser> {
|
|
|
124
167
|
tokenTtlSeconds?: number | undefined
|
|
125
168
|
/** Minimum password length (default: 12, aligned with CNIL guidance). */
|
|
126
169
|
minPasswordLength?: number | undefined
|
|
170
|
+
/** Maximum password length in characters / UTF-8 bytes before Argon2id hashing (default: 1024). */
|
|
171
|
+
maxPasswordLength?: number | undefined
|
|
127
172
|
/** Default role assigned to newly created users (default: 'user'). */
|
|
128
173
|
defaultRole?: string | undefined
|
|
129
174
|
/** Default redirect after successful form login/signup/OAuth (default: '/'). */
|
|
@@ -221,6 +266,8 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
|
|
|
221
266
|
const renewalIntervalMs = Math.max(0, (options.renewalIntervalSeconds ?? Math.min(60 * 60, Math.max(1, Math.floor(sessionTtlSeconds / 4)))) * 1000)
|
|
222
267
|
const tokenTtlMs = (options.tokenTtlSeconds ?? 60 * 15) * 1000
|
|
223
268
|
const minPasswordLength = options.minPasswordLength ?? 12
|
|
269
|
+
const maxPasswordLength = options.maxPasswordLength ?? DEFAULT_MAX_PASSWORD_LENGTH
|
|
270
|
+
const mailDelay = createMailDelayTracker()
|
|
224
271
|
const defaultRole = options.defaultRole ?? 'user'
|
|
225
272
|
const defaultRedirect = options.defaultRedirect ?? '/'
|
|
226
273
|
const authRouteOpts = {
|
|
@@ -228,17 +275,7 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
|
|
|
228
275
|
...(options.trustProxy !== undefined ? { trustProxy: options.trustProxy } : {}),
|
|
229
276
|
}
|
|
230
277
|
let site = options.site !== undefined ? siteOrigin(options.site) : undefined
|
|
231
|
-
const deliverMail
|
|
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)
|
|
278
|
+
const deliverMail = buildMailDeliverer(options.sendMail, options.mailer)
|
|
242
279
|
const requireEmailVerification = options.requireEmailVerification !== false
|
|
243
280
|
let trustProxy = options.trustProxy ?? false
|
|
244
281
|
|
|
@@ -344,7 +381,8 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
|
|
|
344
381
|
// One-time emailed link: stores the hashed token, builds the URL and mails it when a transport is configured.
|
|
345
382
|
async function issueLink(kind: 'magic-link' | 'verify-email', userId: string | undefined, email: string, origin: string | undefined, redirectTo: string | undefined): Promise<string> {
|
|
346
383
|
const normalized = normalizeEmail(email)
|
|
347
|
-
const
|
|
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)
|
|
348
386
|
const tokenHash = sha256Hex(rawToken)
|
|
349
387
|
await sessions.observeAsync(store.createToken({
|
|
350
388
|
tokenHash,
|
|
@@ -360,6 +398,7 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
|
|
|
360
398
|
|
|
361
399
|
if (deliverMail && origin !== undefined) {
|
|
362
400
|
const mail = LINK_MAILS[kind]
|
|
401
|
+
const startedAt = performance.now()
|
|
363
402
|
try {
|
|
364
403
|
await deliverMail({
|
|
365
404
|
to: normalized,
|
|
@@ -369,6 +408,7 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
|
|
|
369
408
|
url,
|
|
370
409
|
kind,
|
|
371
410
|
})
|
|
411
|
+
mailDelay.observe(performance.now() - startedAt)
|
|
372
412
|
}
|
|
373
413
|
catch (err) {
|
|
374
414
|
try {
|
|
@@ -403,28 +443,15 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
|
|
|
403
443
|
const user = consumed.userId
|
|
404
444
|
? await sessions.observeAsync(store.getUserById(consumed.userId))
|
|
405
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
|
+
}
|
|
406
451
|
return { email: consumed.email, user }
|
|
407
452
|
}
|
|
408
453
|
|
|
409
|
-
|
|
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
|
-
}
|
|
454
|
+
const guard = (guardOpts?: GuardOptions<TUser>): Middleware => createAuthGuard(sessions.resolve, guardOpts)
|
|
428
455
|
|
|
429
456
|
const dispose = (): void => {
|
|
430
457
|
for (const timer of pruneTimers)
|
|
@@ -457,19 +484,15 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
|
|
|
457
484
|
await store.close?.()
|
|
458
485
|
})
|
|
459
486
|
|
|
460
|
-
// Sync stores resolve lazily on first read of ctx.locals.user/session; async stores
|
|
487
|
+
// Sync stores resolve lazily on first read of ctx.locals.user/session; async or unknown Promise-returning stores await before next().
|
|
461
488
|
const internalPrefix = `${api.assetPrefix.replace(/\/$/, '')}/`
|
|
462
489
|
const actionPrefix = `${internalPrefix}action/`
|
|
463
490
|
api.use((ctx, next) => {
|
|
464
491
|
const p = ctx.url.pathname
|
|
465
492
|
if (!p.startsWith(internalPrefix) || p.startsWith(actionPrefix)) {
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
}
|
|
470
|
-
else {
|
|
471
|
-
sessions.attachLazy(ctx)
|
|
472
|
-
}
|
|
493
|
+
const pending = sessions.prepareRequest(ctx)
|
|
494
|
+
if (pending !== undefined)
|
|
495
|
+
return pending.then(() => next())
|
|
473
496
|
}
|
|
474
497
|
return next()
|
|
475
498
|
}, { scope: 'rendered' })
|
|
@@ -486,10 +509,12 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
|
|
|
486
509
|
basePath,
|
|
487
510
|
authRouteOpts,
|
|
488
511
|
minPasswordLength,
|
|
512
|
+
maxPasswordLength,
|
|
489
513
|
defaultRedirect,
|
|
490
514
|
requireEmailVerification,
|
|
491
515
|
hasMailTransport: deliverMail !== undefined,
|
|
492
516
|
mailedLinkOrigin,
|
|
517
|
+
equalizeSignupMailDelay: () => deliverMail ? mailDelay.pad() : Promise.resolve(),
|
|
493
518
|
createUser,
|
|
494
519
|
insertUser,
|
|
495
520
|
claimUnverified,
|
|
@@ -507,12 +532,15 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
|
|
|
507
532
|
basePath,
|
|
508
533
|
stateCookieName: oauthCookieName,
|
|
509
534
|
defaultRedirect,
|
|
535
|
+
requireEmailVerification,
|
|
536
|
+
hasMailTransport: deliverMail !== undefined,
|
|
537
|
+
mailedLinkOrigin,
|
|
538
|
+
issueLink,
|
|
510
539
|
limitIp,
|
|
511
540
|
isSecureCookie,
|
|
512
541
|
claimUnverified,
|
|
513
542
|
insertUser,
|
|
514
543
|
createSessionForUser: sessions.createSessionForUser,
|
|
515
|
-
setResolvedUser: sessions.setResolvedUser,
|
|
516
544
|
observeAsync: sessions.observeAsync,
|
|
517
545
|
})
|
|
518
546
|
},
|
|
@@ -527,7 +555,7 @@ export function createAuth<TUser extends AuthUser = AuthUser>(options: AuthOptio
|
|
|
527
555
|
resolve: sessions.resolve,
|
|
528
556
|
guard,
|
|
529
557
|
createUser,
|
|
530
|
-
createSessionForUser: sessions.createSessionForUser,
|
|
558
|
+
createSessionForUser: (userId, ctx) => sessions.createSessionForUser(userId, ctx),
|
|
531
559
|
signOut: sessions.signOut,
|
|
532
560
|
async revokeAllSessions(userId) {
|
|
533
561
|
await sessions.observeAsync(store.deleteUserSessions(userId))
|
package/src/oauth-routes.ts
CHANGED
|
@@ -7,7 +7,7 @@ import type { AuthStore, AuthUser, PublicUser } from './store'
|
|
|
7
7
|
import { pkceChallenge, randomToken, signPayload, verifyPayload } from './crypto'
|
|
8
8
|
import { fail, withNoStore } from './http'
|
|
9
9
|
import { OAUTH_FETCH_TIMEOUT_MS } from './oauth'
|
|
10
|
-
import { toPublicUser } from './store'
|
|
10
|
+
import { normalizeEmail, toPublicUser } from './store'
|
|
11
11
|
|
|
12
12
|
interface OAuthStateCookie {
|
|
13
13
|
provider: string
|
|
@@ -26,17 +26,110 @@ export interface OAuthRouteDeps<TUser extends AuthUser = AuthUser> {
|
|
|
26
26
|
basePath: string
|
|
27
27
|
stateCookieName: string
|
|
28
28
|
defaultRedirect: string
|
|
29
|
+
requireEmailVerification: boolean
|
|
30
|
+
hasMailTransport: boolean
|
|
31
|
+
mailedLinkOrigin: (url: URL) => string | undefined
|
|
32
|
+
issueLink: (kind: 'magic-link' | 'verify-email', userId: string | undefined, email: string, origin: string | undefined, redirectTo: string | undefined) => Promise<string>
|
|
29
33
|
limitIp: (ctx: RequestContext, scope: string) => Response | undefined
|
|
30
34
|
isSecureCookie: (ctx: RequestContext) => boolean
|
|
31
35
|
claimUnverified: (user: TUser) => Promise<TUser>
|
|
32
36
|
insertUser: (fields: Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>) => Promise<TUser>
|
|
33
|
-
createSessionForUser: (userId: string, ctx: RequestContext) => Promise<unknown>
|
|
34
|
-
setResolvedUser: (ctx: RequestContext, user: PublicUser<TUser>) => void
|
|
37
|
+
createSessionForUser: (userId: string, ctx: RequestContext, knownUser?: PublicUser<TUser>) => Promise<unknown>
|
|
35
38
|
observeAsync: <T>(value: T | Promise<T>) => T | Promise<T>
|
|
36
39
|
}
|
|
37
40
|
|
|
41
|
+
async function handleUnverifiedOAuthSignup<TUser extends AuthUser>(
|
|
42
|
+
deps: OAuthRouteDeps<TUser>,
|
|
43
|
+
ctx: RequestContext,
|
|
44
|
+
profile: OAuthProfile,
|
|
45
|
+
redirectTarget: string,
|
|
46
|
+
): Promise<Response> {
|
|
47
|
+
const linkOrigin = deps.mailedLinkOrigin(ctx.url)
|
|
48
|
+
if (deps.hasMailTransport && linkOrigin === undefined) {
|
|
49
|
+
console.error(`[prunelle/auth] refusing to mail a verification link for host ${ctx.url.host}: set the auth \`site\` option to the public origin`)
|
|
50
|
+
return fail(ctx, 500, 'Verification links are not configured')
|
|
51
|
+
}
|
|
52
|
+
const created = await deps.insertUser({
|
|
53
|
+
email: profile.email,
|
|
54
|
+
...(profile.name !== undefined ? { name: profile.name } : {}),
|
|
55
|
+
...(profile.avatarUrl !== undefined ? { avatarUrl: profile.avatarUrl } : {}),
|
|
56
|
+
emailVerified: false,
|
|
57
|
+
} as Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>)
|
|
58
|
+
try {
|
|
59
|
+
await deps.issueLink('verify-email', created.id, created.email, linkOrigin, redirectTarget)
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
try {
|
|
63
|
+
await deps.observeAsync(deps.store.deleteUser(created.id))
|
|
64
|
+
}
|
|
65
|
+
catch (rollbackErr) {
|
|
66
|
+
console.error('[prunelle/auth] failed to roll back unverified OAuth user:', rollbackErr)
|
|
67
|
+
}
|
|
68
|
+
return fail(ctx, 500, 'Unable to send verification email')
|
|
69
|
+
}
|
|
70
|
+
return ctx.redirect(redirectTarget, 302)
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async function resolveOAuthUser<TUser extends AuthUser>(
|
|
74
|
+
deps: OAuthRouteDeps<TUser>,
|
|
75
|
+
ctx: RequestContext,
|
|
76
|
+
provider: OAuthProvider,
|
|
77
|
+
profile: OAuthProfile,
|
|
78
|
+
redirectTarget: string,
|
|
79
|
+
): Promise<TUser | Response> {
|
|
80
|
+
const { store, observeAsync, requireEmailVerification } = deps
|
|
81
|
+
const existingLink = await observeAsync(store.getOAuthAccount(provider.id, profile.id))
|
|
82
|
+
|
|
83
|
+
if (existingLink) {
|
|
84
|
+
let userRecord = await observeAsync(store.getUserById(existingLink.userId))
|
|
85
|
+
if (!userRecord)
|
|
86
|
+
return fail(ctx, 500, 'Unable to resolve user account')
|
|
87
|
+
if (requireEmailVerification && !userRecord.emailVerified) {
|
|
88
|
+
if (profile.emailVerified && normalizeEmail(profile.email) === userRecord.email) {
|
|
89
|
+
userRecord = await deps.claimUnverified(userRecord)
|
|
90
|
+
await observeAsync(store.linkOAuthAccount({
|
|
91
|
+
provider: provider.id,
|
|
92
|
+
providerAccountId: profile.id,
|
|
93
|
+
userId: userRecord.id,
|
|
94
|
+
createdAt: Date.now(),
|
|
95
|
+
}))
|
|
96
|
+
return userRecord
|
|
97
|
+
}
|
|
98
|
+
return fail(ctx, 403, 'Email not verified')
|
|
99
|
+
}
|
|
100
|
+
return userRecord
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const byEmail = await observeAsync(store.getUserByEmail(profile.email))
|
|
104
|
+
let userRecord: TUser | undefined
|
|
105
|
+
if (byEmail && profile.emailVerified) {
|
|
106
|
+
userRecord = byEmail.emailVerified ? byEmail : await deps.claimUnverified(byEmail)
|
|
107
|
+
}
|
|
108
|
+
else if (!byEmail) {
|
|
109
|
+
if (requireEmailVerification && !profile.emailVerified)
|
|
110
|
+
return handleUnverifiedOAuthSignup(deps, ctx, profile, redirectTarget)
|
|
111
|
+
userRecord = await deps.insertUser({
|
|
112
|
+
email: profile.email,
|
|
113
|
+
...(profile.name !== undefined ? { name: profile.name } : {}),
|
|
114
|
+
...(profile.avatarUrl !== undefined ? { avatarUrl: profile.avatarUrl } : {}),
|
|
115
|
+
emailVerified: profile.emailVerified,
|
|
116
|
+
} as Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>)
|
|
117
|
+
}
|
|
118
|
+
else {
|
|
119
|
+
return fail(ctx, 409, 'An account with this email already exists; verify email to link')
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
await observeAsync(store.linkOAuthAccount({
|
|
123
|
+
provider: provider.id,
|
|
124
|
+
providerAccountId: profile.id,
|
|
125
|
+
userId: userRecord.id,
|
|
126
|
+
createdAt: Date.now(),
|
|
127
|
+
}))
|
|
128
|
+
return userRecord
|
|
129
|
+
}
|
|
130
|
+
|
|
38
131
|
export function registerOAuthRoutes<TUser extends AuthUser = AuthUser>(deps: OAuthRouteDeps<TUser>): void {
|
|
39
|
-
const { route,
|
|
132
|
+
const { route, providers, secret, site, basePath, stateCookieName, defaultRedirect, limitIp } = deps
|
|
40
133
|
const callbackUrlFor = (ctx: RequestContext, provider: OAuthProvider): string =>
|
|
41
134
|
`${site ?? ctx.url.origin}${basePath}/oauth/${encodeURIComponent(provider.id)}/callback`
|
|
42
135
|
|
|
@@ -151,43 +244,12 @@ export function registerOAuthRoutes<TUser extends AuthUser = AuthUser>(deps: OAu
|
|
|
151
244
|
if (!profile?.id || !profile.email)
|
|
152
245
|
return fail(ctx, 502, 'OAuth profile fetch failed')
|
|
153
246
|
|
|
154
|
-
const
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
userRecord = await observeAsync(store.getUserById(existingLink.userId))
|
|
159
|
-
}
|
|
160
|
-
else {
|
|
161
|
-
const byEmail = await observeAsync(store.getUserByEmail(profile.email))
|
|
162
|
-
if (byEmail && profile.emailVerified) {
|
|
163
|
-
userRecord = byEmail.emailVerified ? byEmail : await deps.claimUnverified(byEmail)
|
|
164
|
-
}
|
|
165
|
-
else if (!byEmail) {
|
|
166
|
-
userRecord = await deps.insertUser({
|
|
167
|
-
email: profile.email,
|
|
168
|
-
...(profile.name !== undefined ? { name: profile.name } : {}),
|
|
169
|
-
...(profile.avatarUrl !== undefined ? { avatarUrl: profile.avatarUrl } : {}),
|
|
170
|
-
emailVerified: profile.emailVerified,
|
|
171
|
-
} as Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>)
|
|
172
|
-
}
|
|
173
|
-
else {
|
|
174
|
-
return fail(ctx, 409, 'An account with this email already exists; verify email to link')
|
|
175
|
-
}
|
|
176
|
-
if (userRecord) {
|
|
177
|
-
await observeAsync(store.linkOAuthAccount({
|
|
178
|
-
provider: provider.id,
|
|
179
|
-
providerAccountId: profile.id,
|
|
180
|
-
userId: userRecord.id,
|
|
181
|
-
createdAt: Date.now(),
|
|
182
|
-
}))
|
|
183
|
-
}
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
if (!userRecord)
|
|
187
|
-
return fail(ctx, 500, 'Unable to resolve user account')
|
|
247
|
+
const redirectTarget = safeRedirect(saved.redirect, defaultRedirect)
|
|
248
|
+
const resolved = await resolveOAuthUser(deps, ctx, provider, profile, redirectTarget)
|
|
249
|
+
if (resolved instanceof Response)
|
|
250
|
+
return resolved
|
|
188
251
|
|
|
189
|
-
await deps.createSessionForUser(
|
|
190
|
-
|
|
191
|
-
return ctx.redirect(safeRedirect(saved.redirect, defaultRedirect), 302)
|
|
252
|
+
await deps.createSessionForUser(resolved.id, ctx, toPublicUser(resolved))
|
|
253
|
+
return ctx.redirect(redirectTarget, 302)
|
|
192
254
|
})
|
|
193
255
|
}
|
package/src/routes.ts
CHANGED
|
@@ -8,7 +8,7 @@ import type { CreateUserInput } from './index'
|
|
|
8
8
|
import type { AuthLimits } from './http'
|
|
9
9
|
import type { SessionManager } from './session'
|
|
10
10
|
import type { AuthStore, AuthUser, PublicUser } from './store'
|
|
11
|
-
import { verifyPassword } from './crypto'
|
|
11
|
+
import { hashPassword, verifyPassword } from './crypto'
|
|
12
12
|
import { fail, isValidEmail, linkConfirmPage, parseBody, respondAuthError, withNoStore } from './http'
|
|
13
13
|
import { normalizeEmail, toPublicUser } from './store'
|
|
14
14
|
|
|
@@ -17,6 +17,55 @@ const LINK_PAGES = {
|
|
|
17
17
|
'verify-email': { title: 'Confirm your email address', button: 'Confirm' },
|
|
18
18
|
}
|
|
19
19
|
|
|
20
|
+
function isPasswordTooLong(password: string, max: number): boolean {
|
|
21
|
+
return password.length > max || Buffer.byteLength(password, 'utf8') > max
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function respondVerificationAccepted(ctx: RequestContext, redirectTarget: string): Response {
|
|
25
|
+
if (wantsJson(ctx.request)) {
|
|
26
|
+
return ctx.json({
|
|
27
|
+
ok: true,
|
|
28
|
+
verificationRequired: true,
|
|
29
|
+
message: 'If that address can be registered, a verification link has been sent.',
|
|
30
|
+
}, { status: 202 })
|
|
31
|
+
}
|
|
32
|
+
return ctx.redirect(redirectTarget, 303)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async function reRegisterUnverified<TUser extends AuthUser>(
|
|
36
|
+
deps: AuthRoutesDeps<TUser>,
|
|
37
|
+
existing: TUser,
|
|
38
|
+
password: string,
|
|
39
|
+
name: string | undefined,
|
|
40
|
+
linkOrigin: string | undefined,
|
|
41
|
+
redirectTarget: string,
|
|
42
|
+
): Promise<boolean> {
|
|
43
|
+
const { store, sessions, issueLink } = deps
|
|
44
|
+
const passwordHash = await hashPassword(password)
|
|
45
|
+
const prevHash = existing.passwordHash
|
|
46
|
+
const prevName = existing.name
|
|
47
|
+
await sessions.observeAsync(store.deleteUserSessions(existing.id))
|
|
48
|
+
await sessions.observeAsync(store.deleteUserOAuthAccounts(existing.id))
|
|
49
|
+
const patch = {
|
|
50
|
+
passwordHash,
|
|
51
|
+
...(name !== undefined ? { name } : {}),
|
|
52
|
+
} as Partial<Omit<TUser, 'id' | 'createdAt'>>
|
|
53
|
+
await sessions.observeAsync(store.updateUser(existing.id, patch))
|
|
54
|
+
try {
|
|
55
|
+
await issueLink('verify-email', existing.id, existing.email, linkOrigin, redirectTarget)
|
|
56
|
+
return true
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
try {
|
|
60
|
+
await sessions.observeAsync(store.updateUser(existing.id, { passwordHash: prevHash, name: prevName } as Partial<Omit<TUser, 'id' | 'createdAt'>>))
|
|
61
|
+
}
|
|
62
|
+
catch (rollbackErr) {
|
|
63
|
+
console.error('[prunelle/auth] failed to roll back unverified signup update:', rollbackErr)
|
|
64
|
+
}
|
|
65
|
+
return false
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
20
69
|
export interface AuthRoutesDeps<TUser extends AuthUser = AuthUser> {
|
|
21
70
|
api: ServerPluginAPI
|
|
22
71
|
store: AuthStore<TUser>
|
|
@@ -26,10 +75,12 @@ export interface AuthRoutesDeps<TUser extends AuthUser = AuthUser> {
|
|
|
26
75
|
basePath: string
|
|
27
76
|
authRouteOpts: PluginRouteOptions
|
|
28
77
|
minPasswordLength: number
|
|
78
|
+
maxPasswordLength: number
|
|
29
79
|
defaultRedirect: string
|
|
30
80
|
requireEmailVerification: boolean
|
|
31
81
|
hasMailTransport: boolean
|
|
32
82
|
mailedLinkOrigin: (url: URL) => string | undefined
|
|
83
|
+
equalizeSignupMailDelay: () => Promise<void>
|
|
33
84
|
createUser: (input: CreateUserInput<TUser>) => Promise<PublicUser<TUser>>
|
|
34
85
|
insertUser: (fields: Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>) => Promise<TUser>
|
|
35
86
|
claimUnverified: (user: TUser) => Promise<TUser>
|
|
@@ -48,10 +99,12 @@ export function registerAuthRoutes<TUser extends AuthUser = AuthUser>(deps: Auth
|
|
|
48
99
|
basePath,
|
|
49
100
|
authRouteOpts,
|
|
50
101
|
minPasswordLength,
|
|
102
|
+
maxPasswordLength,
|
|
51
103
|
defaultRedirect,
|
|
52
104
|
requireEmailVerification,
|
|
53
105
|
hasMailTransport,
|
|
54
106
|
mailedLinkOrigin,
|
|
107
|
+
equalizeSignupMailDelay,
|
|
55
108
|
createUser,
|
|
56
109
|
insertUser,
|
|
57
110
|
claimUnverified,
|
|
@@ -111,26 +164,14 @@ export function registerAuthRoutes<TUser extends AuthUser = AuthUser>(deps: Auth
|
|
|
111
164
|
if (!userRecord)
|
|
112
165
|
return fail(ctx, 400, invalid)
|
|
113
166
|
|
|
114
|
-
await sessions.createSessionForUser(userRecord.id, ctx)
|
|
115
167
|
const pub = toPublicUser(userRecord)
|
|
116
|
-
sessions.
|
|
168
|
+
await sessions.createSessionForUser(userRecord.id, ctx, pub)
|
|
117
169
|
if (wantsJson(ctx.request))
|
|
118
170
|
return ctx.json({ ok: true, user: pub }, { status: 200 })
|
|
119
171
|
return ctx.redirect(redirectTarget, 303)
|
|
120
172
|
})
|
|
121
173
|
}
|
|
122
174
|
|
|
123
|
-
function respondVerificationAccepted(ctx: RequestContext, redirectTarget: string): Response {
|
|
124
|
-
if (wantsJson(ctx.request)) {
|
|
125
|
-
return ctx.json({
|
|
126
|
-
ok: true,
|
|
127
|
-
verificationRequired: true,
|
|
128
|
-
message: 'If that address can be registered, a verification link has been sent.',
|
|
129
|
-
}, { status: 202 })
|
|
130
|
-
}
|
|
131
|
-
return ctx.redirect(redirectTarget, 303)
|
|
132
|
-
}
|
|
133
|
-
|
|
134
175
|
authRoute('GET', '/session', {}, async (ctx) => {
|
|
135
176
|
const resolved = await sessions.resolve(ctx)
|
|
136
177
|
return ctx.json({
|
|
@@ -149,6 +190,8 @@ export function registerAuthRoutes<TUser extends AuthUser = AuthUser>(deps: Auth
|
|
|
149
190
|
return respondAuthError(ctx, 400, 'Please enter a valid email address')
|
|
150
191
|
if (password.length < minPasswordLength)
|
|
151
192
|
return respondAuthError(ctx, 400, `Password must be at least ${minPasswordLength} characters`)
|
|
193
|
+
if (isPasswordTooLong(password, maxPasswordLength))
|
|
194
|
+
return respondAuthError(ctx, 400, `Password must be at most ${maxPasswordLength} characters`)
|
|
152
195
|
|
|
153
196
|
if (requireEmailVerification) {
|
|
154
197
|
const linkOrigin = mailedLinkOrigin(ctx.url)
|
|
@@ -159,15 +202,15 @@ export function registerAuthRoutes<TUser extends AuthUser = AuthUser>(deps: Auth
|
|
|
159
202
|
|
|
160
203
|
const existing = await sessions.observeAsync(store.getUserByEmail(email))
|
|
161
204
|
if (existing) {
|
|
162
|
-
// Equalize timing with Argon2id hashing and avoid revealing whether the email is already registered.
|
|
163
|
-
await verifyPassword(password, undefined)
|
|
164
205
|
if (!existing.emailVerified) {
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
}
|
|
168
|
-
catch {
|
|
206
|
+
const sent = await reRegisterUnverified(deps, existing, password, name, linkOrigin, redirectTarget)
|
|
207
|
+
if (!sent)
|
|
169
208
|
return fail(ctx, 500, 'Unable to send verification email')
|
|
170
|
-
|
|
209
|
+
}
|
|
210
|
+
else {
|
|
211
|
+
// Equalize Argon2id + mail-delivery timing so signup does not reveal already-verified emails.
|
|
212
|
+
await hashPassword(password)
|
|
213
|
+
await equalizeSignupMailDelay()
|
|
171
214
|
}
|
|
172
215
|
return respondVerificationAccepted(ctx, redirectTarget)
|
|
173
216
|
}
|
|
@@ -202,8 +245,7 @@ export function registerAuthRoutes<TUser extends AuthUser = AuthUser>(deps: Auth
|
|
|
202
245
|
return respondAuthError(ctx, 409, 'An account with this email already exists')
|
|
203
246
|
|
|
204
247
|
const user = await createUser({ email, password, name } as CreateUserInput<TUser>)
|
|
205
|
-
await sessions.createSessionForUser(user.id, ctx)
|
|
206
|
-
sessions.setResolvedUser(ctx, user)
|
|
248
|
+
await sessions.createSessionForUser(user.id, ctx, user)
|
|
207
249
|
|
|
208
250
|
if (wantsJson(ctx.request))
|
|
209
251
|
return ctx.json({ ok: true, user }, { status: 201 })
|
|
@@ -214,6 +256,10 @@ export function registerAuthRoutes<TUser extends AuthUser = AuthUser>(deps: Auth
|
|
|
214
256
|
consumeLinkRoute('verify-email', '/verify-email', 'verify-email', 'Invalid or expired verification link', async ({ user }) => {
|
|
215
257
|
if (!user)
|
|
216
258
|
return undefined
|
|
259
|
+
if (!user.emailVerified) {
|
|
260
|
+
await sessions.observeAsync(store.deleteUserSessions(user.id))
|
|
261
|
+
await sessions.observeAsync(store.deleteUserOAuthAccounts(user.id))
|
|
262
|
+
}
|
|
217
263
|
return (await sessions.observeAsync(store.updateUser(user.id, { emailVerified: true } as Partial<Omit<TUser, 'id' | 'createdAt'>>))) ?? { ...user, emailVerified: true }
|
|
218
264
|
})
|
|
219
265
|
|
|
@@ -222,6 +268,9 @@ export function registerAuthRoutes<TUser extends AuthUser = AuthUser>(deps: Auth
|
|
|
222
268
|
const password = body.password ?? ''
|
|
223
269
|
const redirectTarget = safeRedirect(body.redirect ?? body.next, defaultRedirect)
|
|
224
270
|
|
|
271
|
+
if (isPasswordTooLong(password, maxPasswordLength))
|
|
272
|
+
return respondAuthError(ctx, 400, `Password must be at most ${maxPasswordLength} characters`)
|
|
273
|
+
|
|
225
274
|
const userRecord = email ? await sessions.observeAsync(store.getUserByEmail(email)) : undefined
|
|
226
275
|
const valid = await verifyPassword(password, userRecord?.passwordHash)
|
|
227
276
|
if (!userRecord || !valid)
|
|
@@ -230,9 +279,8 @@ export function registerAuthRoutes<TUser extends AuthUser = AuthUser>(deps: Auth
|
|
|
230
279
|
if (requireEmailVerification && !userRecord.emailVerified)
|
|
231
280
|
return respondAuthError(ctx, 403, 'Email not verified')
|
|
232
281
|
|
|
233
|
-
await sessions.createSessionForUser(userRecord.id, ctx)
|
|
234
282
|
const pub = toPublicUser(userRecord)
|
|
235
|
-
sessions.
|
|
283
|
+
await sessions.createSessionForUser(userRecord.id, ctx, pub)
|
|
236
284
|
|
|
237
285
|
if (wantsJson(ctx.request))
|
|
238
286
|
return ctx.json({ ok: true, user: pub }, { status: 200 })
|
package/src/session.ts
CHANGED
|
@@ -4,10 +4,61 @@ import type { PrunelleLocals, RequestContext, TrustProxy } from 'prunelle/server
|
|
|
4
4
|
import type { AuthSession, AuthStore, AuthUser, PublicUser } from './store'
|
|
5
5
|
import { randomToken, sha256Hex } from './crypto'
|
|
6
6
|
import { formatSessionIp, resolveClientIp } from './http'
|
|
7
|
-
import { toPublicUser } from './store'
|
|
7
|
+
import { isKnownSyncStore, toPublicUser } from './store'
|
|
8
8
|
|
|
9
9
|
const AsyncFunctionCtor = Object.getPrototypeOf(async () => {}).constructor
|
|
10
10
|
|
|
11
|
+
function defineLocal(locals: PrunelleLocals, key: 'user' | 'session', value: unknown): void {
|
|
12
|
+
if (value === undefined) {
|
|
13
|
+
delete locals[key]
|
|
14
|
+
return
|
|
15
|
+
}
|
|
16
|
+
Object.defineProperty(locals, key, {
|
|
17
|
+
value,
|
|
18
|
+
writable: true,
|
|
19
|
+
enumerable: true,
|
|
20
|
+
configurable: true,
|
|
21
|
+
})
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function sweepRenewedMap(renewedAt: Map<string, number>, renewalIntervalMs: number): void {
|
|
25
|
+
if (renewedAt.size === 0)
|
|
26
|
+
return
|
|
27
|
+
const cutoff = Date.now() - Math.max(renewalIntervalMs, 1000)
|
|
28
|
+
for (const [k, ts] of renewedAt) {
|
|
29
|
+
if (ts <= cutoff)
|
|
30
|
+
renewedAt.delete(k)
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function defineLazyLocals<TUser extends AuthUser>(
|
|
35
|
+
ctx: RequestContext,
|
|
36
|
+
read: () => { user: PublicUser<TUser>, session: AuthSession } | undefined,
|
|
37
|
+
): void {
|
|
38
|
+
Object.defineProperties(ctx.locals, {
|
|
39
|
+
user: {
|
|
40
|
+
configurable: true,
|
|
41
|
+
enumerable: false,
|
|
42
|
+
get() {
|
|
43
|
+
return read()?.user
|
|
44
|
+
},
|
|
45
|
+
set(val: PublicUser<TUser> | undefined) {
|
|
46
|
+
defineLocal(ctx.locals, 'user', val)
|
|
47
|
+
},
|
|
48
|
+
},
|
|
49
|
+
session: {
|
|
50
|
+
configurable: true,
|
|
51
|
+
enumerable: false,
|
|
52
|
+
get() {
|
|
53
|
+
return read()?.session
|
|
54
|
+
},
|
|
55
|
+
set(val: AuthSession | undefined) {
|
|
56
|
+
defineLocal(ctx.locals, 'session', val)
|
|
57
|
+
},
|
|
58
|
+
},
|
|
59
|
+
})
|
|
60
|
+
}
|
|
61
|
+
|
|
11
62
|
export function isPromiseLike<T>(value: T | Promise<T>): value is Promise<T> {
|
|
12
63
|
return typeof value === 'object' && value !== null && typeof (value as PromiseLike<T>).then === 'function'
|
|
13
64
|
}
|
|
@@ -15,6 +66,7 @@ export function isPromiseLike<T>(value: T | Promise<T>): value is Promise<T> {
|
|
|
15
66
|
export function hasAsyncStoreMethods<TUser extends AuthUser>(store: AuthStore<TUser>): boolean {
|
|
16
67
|
const methods = [
|
|
17
68
|
store.getSession,
|
|
69
|
+
store.listSessions,
|
|
18
70
|
store.getUserById,
|
|
19
71
|
store.getUserByEmail,
|
|
20
72
|
store.createUser,
|
|
@@ -23,11 +75,14 @@ export function hasAsyncStoreMethods<TUser extends AuthUser>(store: AuthStore<TU
|
|
|
23
75
|
store.updateSessionExpiry,
|
|
24
76
|
store.deleteSession,
|
|
25
77
|
store.deleteUser,
|
|
78
|
+
store.exportUser,
|
|
26
79
|
store.deleteUserSessions,
|
|
27
80
|
store.getOAuthAccount,
|
|
28
81
|
store.linkOAuthAccount,
|
|
82
|
+
store.deleteUserOAuthAccounts,
|
|
29
83
|
store.createToken,
|
|
30
84
|
store.consumeToken,
|
|
85
|
+
store.pruneExpired,
|
|
31
86
|
]
|
|
32
87
|
return methods.some(fn => typeof fn === 'function' && fn instanceof AsyncFunctionCtor)
|
|
33
88
|
}
|
|
@@ -46,9 +101,10 @@ export interface SessionManagerDeps<TUser extends AuthUser = AuthUser> {
|
|
|
46
101
|
export interface SessionManager<TUser extends AuthUser = AuthUser> {
|
|
47
102
|
isAsyncStore(): boolean
|
|
48
103
|
observeAsync<T>(value: T | Promise<T>): T | Promise<T>
|
|
104
|
+
prepareRequest(ctx: RequestContext): Promise<unknown> | undefined
|
|
49
105
|
attachLazy(ctx: RequestContext): void
|
|
50
106
|
resolve(ctx: RequestContext): Promise<{ user: PublicUser<TUser>, session: AuthSession } | undefined>
|
|
51
|
-
createSessionForUser(userId: string, ctx: RequestContext): Promise<AuthSession>
|
|
107
|
+
createSessionForUser(userId: string, ctx: RequestContext, knownUser?: PublicUser<TUser>): Promise<AuthSession>
|
|
52
108
|
signOut(ctx: RequestContext): Promise<void>
|
|
53
109
|
setResolvedUser(ctx: RequestContext, pub: PublicUser<TUser>): void
|
|
54
110
|
getUser(ctx: { locals: PrunelleLocals }): PublicUser<TUser> | undefined
|
|
@@ -59,7 +115,9 @@ export interface SessionManager<TUser extends AuthUser = AuthUser> {
|
|
|
59
115
|
export function createSessionManager<TUser extends AuthUser = AuthUser>(deps: SessionManagerDeps<TUser>): SessionManager<TUser> {
|
|
60
116
|
const { store, cookieName, sessionTtlMs, renewalIntervalMs, storeIp, storeUserAgent, getTrustProxy, isSecureCookie } = deps
|
|
61
117
|
|
|
62
|
-
let
|
|
118
|
+
let storeMode: 'unknown' | 'sync' | 'async' = isKnownSyncStore(store)
|
|
119
|
+
? 'sync'
|
|
120
|
+
: (hasAsyncStoreMethods(store) ? 'async' : 'unknown')
|
|
63
121
|
const resolvedContexts = new WeakSet<object>()
|
|
64
122
|
const resolvedUsers = new WeakMap<object, PublicUser<TUser>>()
|
|
65
123
|
const pendingContexts = new WeakMap<object, Promise<{ user: PublicUser<TUser>, session: AuthSession } | undefined>>()
|
|
@@ -67,7 +125,9 @@ export function createSessionManager<TUser extends AuthUser = AuthUser>(deps: Se
|
|
|
67
125
|
|
|
68
126
|
function observeAsync<T>(value: T | Promise<T>): T | Promise<T> {
|
|
69
127
|
if (isPromiseLike(value))
|
|
70
|
-
|
|
128
|
+
storeMode = 'async'
|
|
129
|
+
else if (storeMode === 'unknown')
|
|
130
|
+
storeMode = 'sync'
|
|
71
131
|
return value
|
|
72
132
|
}
|
|
73
133
|
|
|
@@ -81,19 +141,6 @@ export function createSessionManager<TUser extends AuthUser = AuthUser>(deps: Se
|
|
|
81
141
|
})
|
|
82
142
|
}
|
|
83
143
|
|
|
84
|
-
function defineLocal(locals: PrunelleLocals, key: 'user' | 'session', value: unknown): void {
|
|
85
|
-
if (value === undefined) {
|
|
86
|
-
delete locals[key]
|
|
87
|
-
return
|
|
88
|
-
}
|
|
89
|
-
Object.defineProperty(locals, key, {
|
|
90
|
-
value,
|
|
91
|
-
writable: true,
|
|
92
|
-
enumerable: true,
|
|
93
|
-
configurable: true,
|
|
94
|
-
})
|
|
95
|
-
}
|
|
96
|
-
|
|
97
144
|
function setResolvedUser(ctx: RequestContext, pub: PublicUser<TUser>): void {
|
|
98
145
|
resolvedUsers.set(ctx.locals, pub)
|
|
99
146
|
defineLocal(ctx.locals, 'user', pub)
|
|
@@ -109,15 +156,7 @@ export function createSessionManager<TUser extends AuthUser = AuthUser>(deps: Se
|
|
|
109
156
|
delete locals.session
|
|
110
157
|
}
|
|
111
158
|
|
|
112
|
-
|
|
113
|
-
if (renewedAt.size === 0)
|
|
114
|
-
return
|
|
115
|
-
const cutoff = Date.now() - Math.max(renewalIntervalMs, 1000)
|
|
116
|
-
for (const [k, ts] of renewedAt) {
|
|
117
|
-
if (ts <= cutoff)
|
|
118
|
-
renewedAt.delete(k)
|
|
119
|
-
}
|
|
120
|
-
}
|
|
159
|
+
const sweepRenewedAt = (): void => sweepRenewedMap(renewedAt, renewalIntervalMs)
|
|
121
160
|
|
|
122
161
|
function maybeRenewSession(ctx: RequestContext, rawToken: string, tokenHash: string, session: AuthSession): void | Promise<void> {
|
|
123
162
|
const now = Date.now()
|
|
@@ -203,73 +242,72 @@ export function createSessionManager<TUser extends AuthUser = AuthUser>(deps: Se
|
|
|
203
242
|
}
|
|
204
243
|
}
|
|
205
244
|
|
|
206
|
-
|
|
245
|
+
type SyncResolveResult =
|
|
246
|
+
| { pending: Promise<{ user: PublicUser<TUser>, session: AuthSession } | undefined> }
|
|
247
|
+
| { pending?: undefined, resolved: { user: PublicUser<TUser>, session: AuthSession } | undefined }
|
|
248
|
+
|
|
249
|
+
function tryResolveSync(ctx: RequestContext): SyncResolveResult {
|
|
207
250
|
if (resolvedContexts.has(ctx.locals)) {
|
|
208
251
|
const user = resolvedUsers.get(ctx.locals) ?? (ctx.locals.user as PublicUser<TUser> | undefined)
|
|
209
252
|
const session = ctx.locals.session
|
|
210
|
-
return user && session ? { user, session } : undefined
|
|
253
|
+
return { resolved: user && session ? { user, session } : undefined }
|
|
211
254
|
}
|
|
212
255
|
const rawToken = ctx.cookies.get(cookieName)
|
|
213
256
|
if (!rawToken) {
|
|
214
257
|
resolvedContexts.add(ctx.locals)
|
|
215
258
|
clearLazyLocals(ctx.locals)
|
|
216
|
-
return undefined
|
|
259
|
+
return { resolved: undefined }
|
|
217
260
|
}
|
|
218
261
|
const tokenHash = sha256Hex(rawToken)
|
|
219
262
|
const maybeSession = observeAsync(store.getSession(tokenHash))
|
|
220
|
-
if (isPromiseLike(maybeSession))
|
|
221
|
-
|
|
222
|
-
return undefined
|
|
223
|
-
}
|
|
263
|
+
if (isPromiseLike(maybeSession))
|
|
264
|
+
return { pending: resolveRequestSession(ctx, maybeSession) }
|
|
224
265
|
if (!maybeSession || maybeSession.expiresAt <= Date.now()) {
|
|
225
266
|
resolvedContexts.add(ctx.locals)
|
|
226
267
|
clearLazyLocals(ctx.locals)
|
|
227
268
|
ctx.cookies.delete(cookieName, { path: '/' })
|
|
228
|
-
return undefined
|
|
269
|
+
return { resolved: undefined }
|
|
229
270
|
}
|
|
230
271
|
const maybeUser = observeAsync(store.getUserById(maybeSession.userId))
|
|
231
|
-
if (isPromiseLike(maybeUser))
|
|
232
|
-
|
|
233
|
-
return undefined
|
|
234
|
-
}
|
|
272
|
+
if (isPromiseLike(maybeUser))
|
|
273
|
+
return { pending: resolveRequestSession(ctx, Promise.resolve(maybeSession), maybeUser) }
|
|
235
274
|
if (!maybeUser) {
|
|
236
275
|
resolvedContexts.add(ctx.locals)
|
|
237
276
|
clearLazyLocals(ctx.locals)
|
|
238
277
|
void Promise.resolve(observeAsync(store.deleteSession(tokenHash))).catch(() => {})
|
|
239
278
|
ctx.cookies.delete(cookieName, { path: '/' })
|
|
279
|
+
return { resolved: undefined }
|
|
280
|
+
}
|
|
281
|
+
return { resolved: finalizeResolved(ctx, rawToken, tokenHash, maybeSession, maybeUser) }
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
function readSyncLazy(ctx: RequestContext): { user: PublicUser<TUser>, session: AuthSession } | undefined {
|
|
285
|
+
const out = tryResolveSync(ctx)
|
|
286
|
+
if (out.pending !== undefined) {
|
|
287
|
+
void out.pending.catch(() => {})
|
|
240
288
|
return undefined
|
|
241
289
|
}
|
|
242
|
-
return
|
|
290
|
+
return out.resolved
|
|
243
291
|
}
|
|
244
292
|
|
|
245
293
|
function attachLazy(ctx: RequestContext): void {
|
|
246
294
|
if (resolvedContexts.has(ctx.locals) || !ctx.cookies.get(cookieName))
|
|
247
295
|
return
|
|
248
|
-
|
|
249
|
-
user: {
|
|
250
|
-
configurable: true,
|
|
251
|
-
enumerable: false,
|
|
252
|
-
get() {
|
|
253
|
-
return resolveRequestSessionSync(ctx)?.user
|
|
254
|
-
},
|
|
255
|
-
set(val: PublicUser<TUser> | undefined) {
|
|
256
|
-
defineLocal(ctx.locals, 'user', val)
|
|
257
|
-
},
|
|
258
|
-
},
|
|
259
|
-
session: {
|
|
260
|
-
configurable: true,
|
|
261
|
-
enumerable: false,
|
|
262
|
-
get() {
|
|
263
|
-
return resolveRequestSessionSync(ctx)?.session
|
|
264
|
-
},
|
|
265
|
-
set(val: AuthSession | undefined) {
|
|
266
|
-
defineLocal(ctx.locals, 'session', val)
|
|
267
|
-
},
|
|
268
|
-
},
|
|
269
|
-
})
|
|
296
|
+
defineLazyLocals(ctx, () => readSyncLazy(ctx))
|
|
270
297
|
}
|
|
271
298
|
|
|
272
|
-
|
|
299
|
+
function prepareRequest(ctx: RequestContext): Promise<unknown> | undefined {
|
|
300
|
+
if (!ctx.cookies.get(cookieName))
|
|
301
|
+
return undefined
|
|
302
|
+
if (storeMode === 'async')
|
|
303
|
+
return resolveRequestSession(ctx)
|
|
304
|
+
if (storeMode === 'unknown')
|
|
305
|
+
return tryResolveSync(ctx).pending
|
|
306
|
+
attachLazy(ctx)
|
|
307
|
+
return undefined
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
async function createSessionForUser(userId: string, ctx: RequestContext, knownUser?: PublicUser<TUser>): Promise<AuthSession> {
|
|
273
311
|
// Revoke any prior session cookie in the store when opening a new session on the same browser.
|
|
274
312
|
const prevToken = ctx.cookies.get(cookieName)
|
|
275
313
|
if (prevToken) {
|
|
@@ -292,7 +330,18 @@ export function createSessionManager<TUser extends AuthUser = AuthUser>(deps: Se
|
|
|
292
330
|
}
|
|
293
331
|
await observeAsync(store.createSession(session))
|
|
294
332
|
setSessionCookie(ctx, rawToken)
|
|
333
|
+
resolvedContexts.delete(ctx.locals)
|
|
334
|
+
resolvedUsers.delete(ctx.locals)
|
|
335
|
+
delete ctx.locals.user
|
|
295
336
|
setResolvedSession(ctx, session)
|
|
337
|
+
const pub = knownUser ?? await (async () => {
|
|
338
|
+
const rec = await observeAsync(store.getUserById(userId))
|
|
339
|
+
return rec ? toPublicUser(rec) : undefined
|
|
340
|
+
})()
|
|
341
|
+
if (pub !== undefined) {
|
|
342
|
+
resolvedContexts.add(ctx.locals)
|
|
343
|
+
setResolvedUser(ctx, pub)
|
|
344
|
+
}
|
|
296
345
|
return session
|
|
297
346
|
}
|
|
298
347
|
|
|
@@ -309,8 +358,9 @@ export function createSessionManager<TUser extends AuthUser = AuthUser>(deps: Se
|
|
|
309
358
|
}
|
|
310
359
|
|
|
311
360
|
return {
|
|
312
|
-
isAsyncStore: () =>
|
|
361
|
+
isAsyncStore: () => storeMode === 'async',
|
|
313
362
|
observeAsync,
|
|
363
|
+
prepareRequest,
|
|
314
364
|
attachLazy,
|
|
315
365
|
resolve: ctx => resolveRequestSession(ctx),
|
|
316
366
|
createSessionForUser,
|
package/src/sqlite.ts
CHANGED
|
@@ -5,7 +5,7 @@ import type { AuthSession, AuthStore, AuthUser, OAuthAccount, TokenKind, UserExp
|
|
|
5
5
|
import { mkdirSync } from 'node:fs'
|
|
6
6
|
import { dirname } from 'node:path'
|
|
7
7
|
import { Database } from 'bun:sqlite'
|
|
8
|
-
import { keptInMemory, normalizeEmail, toPublicUser } from './store'
|
|
8
|
+
import { keptInMemory, markSyncStore, normalizeEmail, toPublicUser } from './store'
|
|
9
9
|
|
|
10
10
|
interface UserRow {
|
|
11
11
|
id: string
|
|
@@ -201,7 +201,7 @@ export function sqliteAuthStore(dbOrPath: string | Database = ':memory:'): AuthS
|
|
|
201
201
|
return qListUserSessions.all(userId, now).map(row => rowToSession(row)!)
|
|
202
202
|
}
|
|
203
203
|
|
|
204
|
-
return keptInMemory(db.filename === ':memory:', {
|
|
204
|
+
return markSyncStore(keptInMemory(db.filename === ':memory:', {
|
|
205
205
|
db,
|
|
206
206
|
close() {
|
|
207
207
|
if (closed)
|
|
@@ -333,5 +333,5 @@ export function sqliteAuthStore(dbOrPath: string | Database = ':memory:'): AuthS
|
|
|
333
333
|
expiresAt: row.expires_at,
|
|
334
334
|
}
|
|
335
335
|
},
|
|
336
|
-
})
|
|
336
|
+
}))
|
|
337
337
|
}
|
package/src/store.ts
CHANGED
|
@@ -31,6 +31,7 @@ export interface OAuthAccount {
|
|
|
31
31
|
createdAt: number
|
|
32
32
|
}
|
|
33
33
|
|
|
34
|
+
/** Verification token purposes. `'reset-password'` is reserved for app-defined password-reset flows via `store.createToken`/`store.consumeToken`. */
|
|
34
35
|
export type TokenKind = 'magic-link' | 'verify-email' | 'reset-password'
|
|
35
36
|
|
|
36
37
|
export interface VerificationToken {
|
|
@@ -92,6 +93,7 @@ interface MemoryState<TUser extends AuthUser = AuthUser> {
|
|
|
92
93
|
}
|
|
93
94
|
|
|
94
95
|
const inMemoryStores = new WeakSet<object>()
|
|
96
|
+
const syncStores = new WeakSet<object>()
|
|
95
97
|
|
|
96
98
|
/** Marks `store` as one whose data lives in the process alone when `inMemory`, for `requires` to refuse it in production. */
|
|
97
99
|
export function keptInMemory<T extends object>(inMemory: boolean, store: T): T {
|
|
@@ -105,6 +107,17 @@ export function isKeptInMemory(store: object): boolean {
|
|
|
105
107
|
return inMemoryStores.has(store)
|
|
106
108
|
}
|
|
107
109
|
|
|
110
|
+
/** Marks a built-in store whose methods are guaranteed synchronous, enabling lazy session resolution on the very first request. */
|
|
111
|
+
export function markSyncStore<T extends object>(store: T): T {
|
|
112
|
+
syncStores.add(store)
|
|
113
|
+
return store
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Whether `store` is a known built-in synchronous `AuthStore`. */
|
|
117
|
+
export function isKnownSyncStore(store: object): boolean {
|
|
118
|
+
return syncStores.has(store)
|
|
119
|
+
}
|
|
120
|
+
|
|
108
121
|
export function memoryAuthStore<TUser extends AuthUser = AuthUser>(): AuthStore<TUser> {
|
|
109
122
|
const state: MemoryState<TUser> = {
|
|
110
123
|
users: new Map(),
|
|
@@ -114,7 +127,7 @@ export function memoryAuthStore<TUser extends AuthUser = AuthUser>(): AuthStore<
|
|
|
114
127
|
tokens: new Map(),
|
|
115
128
|
}
|
|
116
129
|
|
|
117
|
-
return keptInMemory(true, {
|
|
130
|
+
return markSyncStore(keptInMemory(true, {
|
|
118
131
|
getUserById(userId) {
|
|
119
132
|
return state.users.get(userId)
|
|
120
133
|
},
|
|
@@ -263,5 +276,5 @@ export function memoryAuthStore<TUser extends AuthUser = AuthUser>(): AuthStore<
|
|
|
263
276
|
state.tokens.delete(k)
|
|
264
277
|
}
|
|
265
278
|
},
|
|
266
|
-
})
|
|
279
|
+
}))
|
|
267
280
|
}
|