@prunellejs/auth 0.0.0-stage → 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/src/routes.ts ADDED
@@ -0,0 +1,317 @@
1
+ // Auth HTTP routes: /session, /signup, /verify-email, /signin, /signout, /magic-link, /magic-link/verify.
2
+
3
+ import type { PluginRouteOptions, ServerPluginAPI } from 'prunelle/config'
4
+ import type { RequestContext } from 'prunelle/server'
5
+ import { safeRedirect, wantsJson } from 'prunelle/server'
6
+ import type { CreateUserInput } from './index'
7
+
8
+ import type { AuthLimits } from './http'
9
+ import type { SessionManager } from './session'
10
+ import type { AuthStore, AuthUser, PublicUser } from './store'
11
+ import { hashPassword, verifyPassword } from './crypto'
12
+ import { fail, isValidEmail, linkConfirmPage, parseBody, respondAuthError, withNoStore } from './http'
13
+ import { normalizeEmail, toPublicUser } from './store'
14
+
15
+ const LINK_PAGES = {
16
+ 'magic-link': { title: 'Sign in', button: 'Sign in' },
17
+ 'verify-email': { title: 'Confirm your email address', button: 'Confirm' },
18
+ }
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
+
69
+ export interface AuthRoutesDeps<TUser extends AuthUser = AuthUser> {
70
+ api: ServerPluginAPI
71
+ store: AuthStore<TUser>
72
+ sessions: SessionManager<TUser>
73
+ limitIp: AuthLimits['limitIp']
74
+ limitEmail: AuthLimits['limitEmail']
75
+ basePath: string
76
+ authRouteOpts: PluginRouteOptions
77
+ minPasswordLength: number
78
+ maxPasswordLength: number
79
+ defaultRedirect: string
80
+ requireEmailVerification: boolean
81
+ hasMailTransport: boolean
82
+ mailedLinkOrigin: (url: URL) => string | undefined
83
+ equalizeSignupMailDelay: () => Promise<void>
84
+ createUser: (input: CreateUserInput<TUser>) => Promise<PublicUser<TUser>>
85
+ insertUser: (fields: Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>) => Promise<TUser>
86
+ claimUnverified: (user: TUser) => Promise<TUser>
87
+ issueLink: (kind: 'magic-link' | 'verify-email', userId: string | undefined, email: string, origin: string | undefined, redirectTo: string | undefined) => Promise<string>
88
+ consumeLink: (kind: 'magic-link' | 'verify-email', rawToken: string) => Promise<{ email: string, user: TUser | undefined } | undefined>
89
+ sendMagicLink: (email: string, origin: string, redirectTo?: string) => Promise<string>
90
+ }
91
+
92
+ export function registerAuthRoutes<TUser extends AuthUser = AuthUser>(deps: AuthRoutesDeps<TUser>): void {
93
+ const {
94
+ api,
95
+ store,
96
+ sessions,
97
+ limitEmail,
98
+ limitIp,
99
+ basePath,
100
+ authRouteOpts,
101
+ minPasswordLength,
102
+ maxPasswordLength,
103
+ defaultRedirect,
104
+ requireEmailVerification,
105
+ hasMailTransport,
106
+ mailedLinkOrigin,
107
+ equalizeSignupMailDelay,
108
+ createUser,
109
+ insertUser,
110
+ claimUnverified,
111
+ issueLink,
112
+ consumeLink,
113
+ sendMagicLink,
114
+ } = deps
115
+
116
+ function authRoute(
117
+ method: 'GET' | 'POST',
118
+ path: string,
119
+ routeCfg: { limit?: string, emailLimit?: string, readBody?: boolean },
120
+ handler: (ctx: RequestContext, body: Record<string, string>) => Response | Promise<Response>,
121
+ ): void {
122
+ api.route(method, `${basePath}${path}`, async (ctx) => {
123
+ if (routeCfg.limit !== undefined) {
124
+ const limited = limitIp(ctx, routeCfg.limit)
125
+ if (limited)
126
+ return withNoStore(limited)
127
+ }
128
+ let body: Record<string, string> = {}
129
+ if (routeCfg.readBody) {
130
+ const parsed = await parseBody(ctx)
131
+ if (parsed instanceof Response)
132
+ return withNoStore(parsed)
133
+ body = parsed
134
+ }
135
+ if (routeCfg.emailLimit !== undefined) {
136
+ const limited = limitEmail(ctx, routeCfg.emailLimit, body.email)
137
+ if (limited)
138
+ return withNoStore(limited)
139
+ }
140
+ return withNoStore(await handler(ctx, body))
141
+ }, method === 'POST' ? authRouteOpts : undefined)
142
+ }
143
+
144
+ // GET on a mailed link: the token stays unused until the page's button posts it, and the POST checks the redirect.
145
+ function confirmLinkRoute(kind: 'magic-link' | 'verify-email', path: string, limit: string): void {
146
+ authRoute('GET', path, { limit }, (ctx) => {
147
+ const token = ctx.url.searchParams.get('token') ?? ''
148
+ if (!token)
149
+ return fail(ctx, 400, 'Missing token')
150
+ return linkConfirmPage(LINK_PAGES[kind], { token, redirect: ctx.url.searchParams.get('redirect') ?? '' })
151
+ })
152
+ }
153
+
154
+ // POST from the confirm page (form) or a client (JSON): consumes the token, then `signIn` picks the user to open a session for.
155
+ function consumeLinkRoute(kind: 'magic-link' | 'verify-email', path: string, limit: string, invalid: string, signIn: (consumed: { email: string, user: TUser | undefined }) => Promise<TUser | undefined>): void {
156
+ authRoute('POST', path, { limit, readBody: true }, async (ctx, body) => {
157
+ const rawToken = body.token ?? ctx.url.searchParams.get('token') ?? ''
158
+ const redirectTarget = safeRedirect(body.redirect ?? body.next ?? ctx.url.searchParams.get('redirect'), defaultRedirect)
159
+ if (!rawToken)
160
+ return fail(ctx, 400, 'Missing token')
161
+
162
+ const consumed = await consumeLink(kind, rawToken)
163
+ const userRecord = consumed && await signIn(consumed)
164
+ if (!userRecord)
165
+ return fail(ctx, 400, invalid)
166
+
167
+ const pub = toPublicUser(userRecord)
168
+ await sessions.createSessionForUser(userRecord.id, ctx, pub)
169
+ if (wantsJson(ctx.request))
170
+ return ctx.json({ ok: true, user: pub }, { status: 200 })
171
+ return ctx.redirect(redirectTarget, 303)
172
+ })
173
+ }
174
+
175
+ authRoute('GET', '/session', {}, async (ctx) => {
176
+ const resolved = await sessions.resolve(ctx)
177
+ return ctx.json({
178
+ user: resolved?.user ?? null,
179
+ session: resolved ? { id: resolved.session.id, expiresAt: resolved.session.expiresAt } : null,
180
+ })
181
+ })
182
+
183
+ authRoute('POST', '/signup', { limit: 'signup', emailLimit: 'signup', readBody: true }, async (ctx, body) => {
184
+ const email = normalizeEmail(body.email ?? '')
185
+ const password = body.password ?? ''
186
+ const name = body.name?.trim() || undefined
187
+ const redirectTarget = safeRedirect(body.redirect ?? body.next, defaultRedirect)
188
+
189
+ if (!isValidEmail(email))
190
+ return respondAuthError(ctx, 400, 'Please enter a valid email address')
191
+ if (password.length < minPasswordLength)
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`)
195
+
196
+ if (requireEmailVerification) {
197
+ const linkOrigin = mailedLinkOrigin(ctx.url)
198
+ if (hasMailTransport && linkOrigin === undefined) {
199
+ console.error(`[prunelle/auth] refusing to mail a verification link for host ${ctx.url.host}: set the auth \`site\` option to the public origin`)
200
+ return fail(ctx, 500, 'Verification links are not configured')
201
+ }
202
+
203
+ const existing = await sessions.observeAsync(store.getUserByEmail(email))
204
+ if (existing) {
205
+ if (!existing.emailVerified) {
206
+ const sent = await reRegisterUnverified(deps, existing, password, name, linkOrigin, redirectTarget)
207
+ if (!sent)
208
+ return fail(ctx, 500, 'Unable to send verification email')
209
+ }
210
+ else {
211
+ // Equalize Argon2id + mail-delivery timing so signup does not reveal already-verified emails.
212
+ await hashPassword(password)
213
+ await equalizeSignupMailDelay()
214
+ }
215
+ return respondVerificationAccepted(ctx, redirectTarget)
216
+ }
217
+
218
+ let user: PublicUser<TUser>
219
+ try {
220
+ user = await createUser({ email, password, name, emailVerified: false } as CreateUserInput<TUser>)
221
+ }
222
+ catch (err) {
223
+ if (await sessions.observeAsync(store.getUserByEmail(email)))
224
+ return respondVerificationAccepted(ctx, redirectTarget)
225
+ throw err
226
+ }
227
+
228
+ try {
229
+ await issueLink('verify-email', user.id, user.email, linkOrigin, redirectTarget)
230
+ }
231
+ catch {
232
+ try {
233
+ await sessions.observeAsync(store.deleteUser(user.id))
234
+ }
235
+ catch {
236
+ // Best-effort rollback so a mail outage does not permanently lock out the email address.
237
+ }
238
+ return fail(ctx, 500, 'Unable to send verification email')
239
+ }
240
+
241
+ return respondVerificationAccepted(ctx, redirectTarget)
242
+ }
243
+
244
+ if (await sessions.observeAsync(store.getUserByEmail(email)))
245
+ return respondAuthError(ctx, 409, 'An account with this email already exists')
246
+
247
+ const user = await createUser({ email, password, name } as CreateUserInput<TUser>)
248
+ await sessions.createSessionForUser(user.id, ctx, user)
249
+
250
+ if (wantsJson(ctx.request))
251
+ return ctx.json({ ok: true, user }, { status: 201 })
252
+ return ctx.redirect(redirectTarget, 303)
253
+ })
254
+
255
+ confirmLinkRoute('verify-email', '/verify-email', 'verify-email')
256
+ consumeLinkRoute('verify-email', '/verify-email', 'verify-email', 'Invalid or expired verification link', async ({ user }) => {
257
+ if (!user)
258
+ return undefined
259
+ if (!user.emailVerified) {
260
+ await sessions.observeAsync(store.deleteUserSessions(user.id))
261
+ await sessions.observeAsync(store.deleteUserOAuthAccounts(user.id))
262
+ }
263
+ return (await sessions.observeAsync(store.updateUser(user.id, { emailVerified: true } as Partial<Omit<TUser, 'id' | 'createdAt'>>))) ?? { ...user, emailVerified: true }
264
+ })
265
+
266
+ authRoute('POST', '/signin', { limit: 'signin', emailLimit: 'signin', readBody: true }, async (ctx, body) => {
267
+ const email = normalizeEmail(body.email ?? '')
268
+ const password = body.password ?? ''
269
+ const redirectTarget = safeRedirect(body.redirect ?? body.next, defaultRedirect)
270
+
271
+ if (isPasswordTooLong(password, maxPasswordLength))
272
+ return respondAuthError(ctx, 400, `Password must be at most ${maxPasswordLength} characters`)
273
+
274
+ const userRecord = email ? await sessions.observeAsync(store.getUserByEmail(email)) : undefined
275
+ const valid = await verifyPassword(password, userRecord?.passwordHash)
276
+ if (!userRecord || !valid)
277
+ return respondAuthError(ctx, 401, 'Invalid email or password')
278
+
279
+ if (requireEmailVerification && !userRecord.emailVerified)
280
+ return respondAuthError(ctx, 403, 'Email not verified')
281
+
282
+ const pub = toPublicUser(userRecord)
283
+ await sessions.createSessionForUser(userRecord.id, ctx, pub)
284
+
285
+ if (wantsJson(ctx.request))
286
+ return ctx.json({ ok: true, user: pub }, { status: 200 })
287
+ return ctx.redirect(redirectTarget, 303)
288
+ })
289
+
290
+ authRoute('POST', '/signout', {}, async (ctx) => {
291
+ await sessions.signOut(ctx)
292
+ if (wantsJson(ctx.request))
293
+ return ctx.json({ ok: true })
294
+ return ctx.redirect(safeRedirect(ctx.url.searchParams.get('redirect'), defaultRedirect), 303)
295
+ })
296
+
297
+ authRoute('POST', '/magic-link', { limit: 'magic', emailLimit: 'magic', readBody: true }, async (ctx, body) => {
298
+ const email = normalizeEmail(body.email ?? '')
299
+ if (!isValidEmail(email))
300
+ return fail(ctx, 400, 'Please enter a valid email address')
301
+
302
+ const linkOrigin = mailedLinkOrigin(ctx.url)
303
+ if (linkOrigin === undefined) {
304
+ console.error(`[prunelle/auth] refusing to mail a sign-in link for host ${ctx.url.host}: set the auth \`site\` option to the public origin`)
305
+ return fail(ctx, 500, 'Sign-in links are not configured')
306
+ }
307
+ await sendMagicLink(email, linkOrigin, body.redirect ?? body.next)
308
+ return ctx.json({ ok: true, message: 'If that address can sign in, a link has been sent.' })
309
+ })
310
+
311
+ confirmLinkRoute('magic-link', '/magic-link/verify', 'magic-verify')
312
+ consumeLinkRoute('magic-link', '/magic-link/verify', 'magic-verify', 'Invalid or expired sign-in link', async ({ email, user }) => {
313
+ if (!user)
314
+ return insertUser({ email, emailVerified: true } as Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>)
315
+ return user.emailVerified ? user : claimUnverified(user)
316
+ })
317
+ }
package/src/session.ts ADDED
@@ -0,0 +1,380 @@
1
+ // Session resolution, sliding renewal, lazy/async locals binding, and sign-in/sign-out session lifecycle.
2
+
3
+ import type { PrunelleLocals, RequestContext, TrustProxy } from 'prunelle/server'
4
+ import type { AuthSession, AuthStore, AuthUser, PublicUser } from './store'
5
+ import { randomToken, sha256Hex } from './crypto'
6
+ import { formatSessionIp, resolveClientIp } from './http'
7
+ import { isKnownSyncStore, toPublicUser } from './store'
8
+
9
+ const AsyncFunctionCtor = Object.getPrototypeOf(async () => {}).constructor
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
+
62
+ export function isPromiseLike<T>(value: T | Promise<T>): value is Promise<T> {
63
+ return typeof value === 'object' && value !== null && typeof (value as PromiseLike<T>).then === 'function'
64
+ }
65
+
66
+ export function hasAsyncStoreMethods<TUser extends AuthUser>(store: AuthStore<TUser>): boolean {
67
+ const methods = [
68
+ store.getSession,
69
+ store.listSessions,
70
+ store.getUserById,
71
+ store.getUserByEmail,
72
+ store.createUser,
73
+ store.createSession,
74
+ store.updateUser,
75
+ store.updateSessionExpiry,
76
+ store.deleteSession,
77
+ store.deleteUser,
78
+ store.exportUser,
79
+ store.deleteUserSessions,
80
+ store.getOAuthAccount,
81
+ store.linkOAuthAccount,
82
+ store.deleteUserOAuthAccounts,
83
+ store.createToken,
84
+ store.consumeToken,
85
+ store.pruneExpired,
86
+ ]
87
+ return methods.some(fn => typeof fn === 'function' && fn instanceof AsyncFunctionCtor)
88
+ }
89
+
90
+ export interface SessionManagerDeps<TUser extends AuthUser = AuthUser> {
91
+ store: AuthStore<TUser>
92
+ cookieName: string
93
+ sessionTtlMs: number
94
+ renewalIntervalMs: number
95
+ storeIp: boolean | 'truncate'
96
+ storeUserAgent: boolean
97
+ getTrustProxy: () => TrustProxy
98
+ isSecureCookie: (ctx: RequestContext) => boolean
99
+ }
100
+
101
+ export interface SessionManager<TUser extends AuthUser = AuthUser> {
102
+ isAsyncStore(): boolean
103
+ observeAsync<T>(value: T | Promise<T>): T | Promise<T>
104
+ prepareRequest(ctx: RequestContext): Promise<unknown> | undefined
105
+ attachLazy(ctx: RequestContext): void
106
+ resolve(ctx: RequestContext): Promise<{ user: PublicUser<TUser>, session: AuthSession } | undefined>
107
+ createSessionForUser(userId: string, ctx: RequestContext, knownUser?: PublicUser<TUser>): Promise<AuthSession>
108
+ signOut(ctx: RequestContext): Promise<void>
109
+ setResolvedUser(ctx: RequestContext, pub: PublicUser<TUser>): void
110
+ getUser(ctx: { locals: PrunelleLocals }): PublicUser<TUser> | undefined
111
+ getSession(ctx: { locals: PrunelleLocals }): AuthSession | undefined
112
+ sweepRenewedAt(): void
113
+ }
114
+
115
+ export function createSessionManager<TUser extends AuthUser = AuthUser>(deps: SessionManagerDeps<TUser>): SessionManager<TUser> {
116
+ const { store, cookieName, sessionTtlMs, renewalIntervalMs, storeIp, storeUserAgent, getTrustProxy, isSecureCookie } = deps
117
+
118
+ let storeMode: 'unknown' | 'sync' | 'async' = isKnownSyncStore(store)
119
+ ? 'sync'
120
+ : (hasAsyncStoreMethods(store) ? 'async' : 'unknown')
121
+ const resolvedContexts = new WeakSet<object>()
122
+ const resolvedUsers = new WeakMap<object, PublicUser<TUser>>()
123
+ const pendingContexts = new WeakMap<object, Promise<{ user: PublicUser<TUser>, session: AuthSession } | undefined>>()
124
+ const renewedAt = new Map<string, number>()
125
+
126
+ function observeAsync<T>(value: T | Promise<T>): T | Promise<T> {
127
+ if (isPromiseLike(value))
128
+ storeMode = 'async'
129
+ else if (storeMode === 'unknown')
130
+ storeMode = 'sync'
131
+ return value
132
+ }
133
+
134
+ function setSessionCookie(ctx: RequestContext, rawToken: string): void {
135
+ ctx.cookies.set(cookieName, rawToken, {
136
+ path: '/',
137
+ httpOnly: true,
138
+ sameSite: 'lax',
139
+ secure: isSecureCookie(ctx),
140
+ maxAge: Math.floor(sessionTtlMs / 1000),
141
+ })
142
+ }
143
+
144
+ function setResolvedUser(ctx: RequestContext, pub: PublicUser<TUser>): void {
145
+ resolvedUsers.set(ctx.locals, pub)
146
+ defineLocal(ctx.locals, 'user', pub)
147
+ }
148
+
149
+ function setResolvedSession(ctx: RequestContext, session: AuthSession): void {
150
+ defineLocal(ctx.locals, 'session', session)
151
+ }
152
+
153
+ function clearLazyLocals(locals: PrunelleLocals): void {
154
+ resolvedUsers.delete(locals)
155
+ delete locals.user
156
+ delete locals.session
157
+ }
158
+
159
+ const sweepRenewedAt = (): void => sweepRenewedMap(renewedAt, renewalIntervalMs)
160
+
161
+ function maybeRenewSession(ctx: RequestContext, rawToken: string, tokenHash: string, session: AuthSession): void | Promise<void> {
162
+ const now = Date.now()
163
+ if (session.expiresAt - now >= sessionTtlMs / 2)
164
+ return
165
+ const prev = renewedAt.get(tokenHash)
166
+ if (prev !== undefined && now - prev < renewalIntervalMs)
167
+ return
168
+ if (renewedAt.size >= 10_000)
169
+ sweepRenewedAt()
170
+ renewedAt.set(tokenHash, now)
171
+ const nextExpiry = now + sessionTtlMs
172
+ session.expiresAt = nextExpiry
173
+ setSessionCookie(ctx, rawToken)
174
+ return observeAsync(store.updateSessionExpiry(tokenHash, nextExpiry))
175
+ }
176
+
177
+ function finalizeResolved(ctx: RequestContext, rawToken: string, tokenHash: string, session: AuthSession, userRecord: TUser): { user: PublicUser<TUser>, session: AuthSession } {
178
+ const pub = toPublicUser(userRecord)
179
+ resolvedContexts.add(ctx.locals)
180
+ setResolvedUser(ctx, pub)
181
+ setResolvedSession(ctx, session)
182
+ const renew = maybeRenewSession(ctx, rawToken, tokenHash, session)
183
+ if (isPromiseLike(renew))
184
+ void renew.catch(() => {})
185
+ return { user: pub, session }
186
+ }
187
+
188
+ async function resolveRequestSession(
189
+ ctx: RequestContext,
190
+ preloadedSession?: Promise<AuthSession | undefined>,
191
+ preloadedUser?: Promise<TUser | undefined>,
192
+ ): Promise<{ user: PublicUser<TUser>, session: AuthSession } | undefined> {
193
+ if (resolvedContexts.has(ctx.locals)) {
194
+ const user = resolvedUsers.get(ctx.locals) ?? (ctx.locals.user as PublicUser<TUser> | undefined)
195
+ const session = ctx.locals.session
196
+ return user && session ? { user, session } : undefined
197
+ }
198
+ const inFlight = pendingContexts.get(ctx.locals)
199
+ if (inFlight !== undefined)
200
+ return inFlight
201
+
202
+ const run = (async (): Promise<{ user: PublicUser<TUser>, session: AuthSession } | undefined> => {
203
+ const rawToken = ctx.cookies.get(cookieName)
204
+ if (!rawToken) {
205
+ resolvedContexts.add(ctx.locals)
206
+ clearLazyLocals(ctx.locals)
207
+ return undefined
208
+ }
209
+
210
+ const tokenHash = sha256Hex(rawToken)
211
+ const session = preloadedSession !== undefined ? await preloadedSession : await observeAsync(store.getSession(tokenHash))
212
+ if (!session || session.expiresAt <= Date.now()) {
213
+ resolvedContexts.add(ctx.locals)
214
+ clearLazyLocals(ctx.locals)
215
+ ctx.cookies.delete(cookieName, { path: '/' })
216
+ return undefined
217
+ }
218
+
219
+ const userRecord = preloadedUser !== undefined ? await preloadedUser : await observeAsync(store.getUserById(session.userId))
220
+ if (!userRecord) {
221
+ resolvedContexts.add(ctx.locals)
222
+ clearLazyLocals(ctx.locals)
223
+ await observeAsync(store.deleteSession(tokenHash))
224
+ ctx.cookies.delete(cookieName, { path: '/' })
225
+ return undefined
226
+ }
227
+
228
+ const pub = toPublicUser(userRecord)
229
+ resolvedContexts.add(ctx.locals)
230
+ setResolvedUser(ctx, pub)
231
+ setResolvedSession(ctx, session)
232
+ await maybeRenewSession(ctx, rawToken, tokenHash, session)
233
+ return { user: pub, session }
234
+ })()
235
+
236
+ pendingContexts.set(ctx.locals, run)
237
+ try {
238
+ return await run
239
+ }
240
+ finally {
241
+ pendingContexts.delete(ctx.locals)
242
+ }
243
+ }
244
+
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 {
250
+ if (resolvedContexts.has(ctx.locals)) {
251
+ const user = resolvedUsers.get(ctx.locals) ?? (ctx.locals.user as PublicUser<TUser> | undefined)
252
+ const session = ctx.locals.session
253
+ return { resolved: user && session ? { user, session } : undefined }
254
+ }
255
+ const rawToken = ctx.cookies.get(cookieName)
256
+ if (!rawToken) {
257
+ resolvedContexts.add(ctx.locals)
258
+ clearLazyLocals(ctx.locals)
259
+ return { resolved: undefined }
260
+ }
261
+ const tokenHash = sha256Hex(rawToken)
262
+ const maybeSession = observeAsync(store.getSession(tokenHash))
263
+ if (isPromiseLike(maybeSession))
264
+ return { pending: resolveRequestSession(ctx, maybeSession) }
265
+ if (!maybeSession || maybeSession.expiresAt <= Date.now()) {
266
+ resolvedContexts.add(ctx.locals)
267
+ clearLazyLocals(ctx.locals)
268
+ ctx.cookies.delete(cookieName, { path: '/' })
269
+ return { resolved: undefined }
270
+ }
271
+ const maybeUser = observeAsync(store.getUserById(maybeSession.userId))
272
+ if (isPromiseLike(maybeUser))
273
+ return { pending: resolveRequestSession(ctx, Promise.resolve(maybeSession), maybeUser) }
274
+ if (!maybeUser) {
275
+ resolvedContexts.add(ctx.locals)
276
+ clearLazyLocals(ctx.locals)
277
+ void Promise.resolve(observeAsync(store.deleteSession(tokenHash))).catch(() => {})
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(() => {})
288
+ return undefined
289
+ }
290
+ return out.resolved
291
+ }
292
+
293
+ function attachLazy(ctx: RequestContext): void {
294
+ if (resolvedContexts.has(ctx.locals) || !ctx.cookies.get(cookieName))
295
+ return
296
+ defineLazyLocals(ctx, () => readSyncLazy(ctx))
297
+ }
298
+
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> {
311
+ // Revoke any prior session cookie in the store when opening a new session on the same browser.
312
+ const prevToken = ctx.cookies.get(cookieName)
313
+ if (prevToken) {
314
+ const prevHash = sha256Hex(prevToken)
315
+ renewedAt.delete(prevHash)
316
+ await observeAsync(store.deleteSession(prevHash))
317
+ }
318
+
319
+ const rawToken = randomToken(32)
320
+ const now = Date.now()
321
+ const recordedIp = formatSessionIp(resolveClientIp(ctx, getTrustProxy()), storeIp)
322
+ const recordedUa = storeUserAgent ? (ctx.request.headers.get('user-agent') ?? undefined) : undefined
323
+ const session: AuthSession = {
324
+ id: sha256Hex(rawToken),
325
+ userId,
326
+ createdAt: now,
327
+ expiresAt: now + sessionTtlMs,
328
+ ...(recordedUa !== undefined ? { userAgent: recordedUa } : {}),
329
+ ...(recordedIp !== undefined ? { ip: recordedIp } : {}),
330
+ }
331
+ await observeAsync(store.createSession(session))
332
+ setSessionCookie(ctx, rawToken)
333
+ resolvedContexts.delete(ctx.locals)
334
+ resolvedUsers.delete(ctx.locals)
335
+ delete ctx.locals.user
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
+ }
345
+ return session
346
+ }
347
+
348
+ async function signOut(ctx: RequestContext): Promise<void> {
349
+ const rawToken = ctx.cookies.get(cookieName)
350
+ if (rawToken) {
351
+ const tokenHash = sha256Hex(rawToken)
352
+ renewedAt.delete(tokenHash)
353
+ await observeAsync(store.deleteSession(tokenHash))
354
+ }
355
+ ctx.cookies.delete(cookieName, { path: '/' })
356
+ resolvedContexts.add(ctx.locals)
357
+ clearLazyLocals(ctx.locals)
358
+ }
359
+
360
+ return {
361
+ isAsyncStore: () => storeMode === 'async',
362
+ observeAsync,
363
+ prepareRequest,
364
+ attachLazy,
365
+ resolve: ctx => resolveRequestSession(ctx),
366
+ createSessionForUser,
367
+ signOut,
368
+ setResolvedUser,
369
+ getUser(ctx) {
370
+ const cached = resolvedUsers.get(ctx.locals)
371
+ if (cached !== undefined)
372
+ return cached
373
+ return ctx.locals.user as PublicUser<TUser> | undefined
374
+ },
375
+ getSession(ctx) {
376
+ return ctx.locals.session
377
+ },
378
+ sweepRenewedAt,
379
+ }
380
+ }