@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/src/routes.ts CHANGED
@@ -1,15 +1,18 @@
1
1
  // Auth HTTP routes: /session, /signup, /verify-email, /signin, /signout, /magic-link, /magic-link/verify.
2
2
 
3
3
  import type { RequestContext } from 'prunelle/server'
4
- import type { AuthRouteRegistrar } from './http'
4
+ import type { AuthFormMessage, AuthFormMessages } from './form-messages'
5
+ import type { AuthLimits, AuthRouteRegistrar } from './http'
5
6
  import type { CreateUserInput } from './index'
7
+ import type { MailInBackground } from './links'
6
8
  import type { SessionManager } from './session'
7
9
  import type { AuthStore, AuthUser, PublicUser } from './store'
8
10
  import type { TotpManager } from './totp'
9
11
  import { safeRedirect, wantsJson } from 'prunelle/server'
10
12
  import { hashPassword, verifyPassword } from './crypto'
11
- import { fail, isValidEmail, linkConfirmPage, respondAuthError } from './http'
13
+ import { fail, formPagePath, isValidEmail, linkConfirmPage, respondAuthError } from './http'
12
14
  import { normalizeEmail, toPublicUser } from './store'
15
+ import { respondTwoFactorChallenge } from './totp'
13
16
 
14
17
  const LINK_PAGES = {
15
18
  'magic-link': { title: 'Sign in', button: 'Sign in' },
@@ -20,43 +23,46 @@ function isPasswordTooLong(password: string, max: number): boolean {
20
23
  return password.length > max || Buffer.byteLength(password, 'utf8') > max
21
24
  }
22
25
 
23
- function respondVerificationAccepted(ctx: RequestContext, redirectTarget: string): Response {
24
- if (wantsJson(ctx.request)) {
25
- return ctx.json({
26
- ok: true,
27
- verificationRequired: true,
28
- message: 'If that address can be registered, a verification link has been sent.',
29
- }, { status: 202 })
30
- }
31
- return ctx.redirect(redirectTarget, 303)
26
+ // A form goes back to its page to say a link was sent: the redirect target is for after the link, and a guard would bounce an unverified visitor from it.
27
+ function respondVerificationAccepted(ctx: RequestContext, redirectTarget: string, sent: AuthFormMessage): Response {
28
+ if (wantsJson(ctx.request))
29
+ return ctx.json({ ok: true, verificationRequired: true, message: sent.text }, { status: 202 })
30
+ return ctx.redirect(formPagePath(ctx, 'notice', sent.code) ?? redirectTarget, 303)
32
31
  }
33
32
 
33
+ // A second sign-up on an unverified address contests it: the mailbox owner cannot tell whose mailed link they click, so neither party's password or name is kept, and the link alone signs the owner in (#75).
34
34
  async function reRegisterUnverified<TUser extends AuthUser>(
35
35
  deps: AuthRoutesDeps<TUser>,
36
36
  existing: TUser,
37
37
  password: string,
38
- name: string | undefined,
39
38
  linkOrigin: string | undefined,
40
39
  redirectTarget: string,
41
40
  ): Promise<boolean> {
42
41
  const { store, sessions, issueLink } = deps
43
- const passwordHash = await hashPassword(password)
44
- const prevHash = existing.passwordHash
45
- const prevName = existing.name
42
+ // Same Argon2id cost as a first sign-up, so timing does not reveal a pending account.
43
+ await hashPassword(password)
44
+ const latest = await sessions.observeAsync(store.getUserById(existing.id))
45
+ if (!latest || latest.emailVerified)
46
+ return true
47
+ const prevHash = latest.passwordHash
48
+ const prevName = latest.name
46
49
  await sessions.observeAsync(store.deleteUserSessions(existing.id))
47
50
  await sessions.observeAsync(store.deleteUserOAuthAccounts(existing.id))
48
- const patch = {
49
- passwordHash,
50
- ...(name !== undefined ? { name } : {}),
51
- } as Partial<Omit<TUser, 'id' | 'createdAt'>>
52
- await sessions.observeAsync(store.updateUser(existing.id, patch))
51
+ const patch = { passwordHash: undefined, name: undefined } as Partial<Omit<TUser, 'id' | 'createdAt'>>
52
+ const cleared = await sessions.observeAsync(store.updateUser(existing.id, patch))
53
+ const restore = async (): Promise<void> => {
54
+ const cur = await sessions.observeAsync(store.getUserById(existing.id))
55
+ if (!cur || cur.emailVerified || cur.updatedAt !== cleared?.updatedAt)
56
+ return
57
+ await sessions.observeAsync(store.updateUser(existing.id, { passwordHash: prevHash, name: prevName } as Partial<Omit<TUser, 'id' | 'createdAt'>>))
58
+ }
53
59
  try {
54
- await issueLink('verify-email', existing.id, existing.email, linkOrigin, redirectTarget)
60
+ await issueLink('verify-email', existing.id, existing.email, linkOrigin, redirectTarget, { onFailure: restore })
55
61
  return true
56
62
  }
57
63
  catch {
58
64
  try {
59
- await sessions.observeAsync(store.updateUser(existing.id, { passwordHash: prevHash, name: prevName } as Partial<Omit<TUser, 'id' | 'createdAt'>>))
65
+ await restore()
60
66
  }
61
67
  catch (rollbackErr) {
62
68
  console.error('[prunelle/auth] failed to roll back unverified signup update:', rollbackErr)
@@ -67,43 +73,107 @@ async function reRegisterUnverified<TUser extends AuthUser>(
67
73
 
68
74
  export interface AuthRoutesDeps<TUser extends AuthUser = AuthUser> {
69
75
  authRoute: AuthRouteRegistrar
76
+ limits: AuthLimits
70
77
  store: AuthStore<TUser>
71
78
  sessions: SessionManager<TUser>
72
79
  totp: TotpManager
73
80
  twoFactorRedirect: string
74
81
  minPasswordLength: number
75
82
  maxPasswordLength: number
83
+ messages: AuthFormMessages
76
84
  defaultRedirect: string
77
85
  requireEmailVerification: boolean
78
86
  hasMailTransport: boolean
79
87
  mailedLinkOrigin: (url: URL) => string | undefined
80
- equalizeSignupMailDelay: () => Promise<void>
81
88
  createUser: (input: CreateUserInput<TUser>) => Promise<PublicUser<TUser>>
82
89
  insertUser: (fields: Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>) => Promise<TUser>
83
90
  claimUnverified: (user: TUser) => Promise<TUser>
84
- issueLink: (kind: 'magic-link' | 'verify-email', userId: string | undefined, email: string, origin: string | undefined, redirectTo: string | undefined) => Promise<string>
91
+ issueLink: (kind: 'magic-link' | 'verify-email', userId: string | undefined, email: string, origin: string | undefined, redirectTo: string | undefined, background?: MailInBackground) => Promise<string>
85
92
  consumeLink: (kind: 'magic-link' | 'verify-email', rawToken: string) => Promise<{ email: string, user: TUser | undefined } | undefined>
86
93
  sendMagicLink: (email: string, origin: string, redirectTo?: string) => Promise<string>
87
94
  }
88
95
 
96
+ // A sign-up that waits for its mailed link: the answer is the same whether the address was new, unverified or taken, so it does not tell them apart.
97
+ async function signUpPendingVerification<TUser extends AuthUser>(
98
+ deps: AuthRoutesDeps<TUser>,
99
+ ctx: RequestContext,
100
+ input: { email: string, password: string, name: string | undefined, redirectTarget: string },
101
+ ): Promise<Response> {
102
+ const { limits, store, sessions, messages, hasMailTransport, mailedLinkOrigin, createUser, issueLink } = deps
103
+ const { email, password, name, redirectTarget } = input
104
+ const linkOrigin = mailedLinkOrigin(ctx.url)
105
+ if (hasMailTransport && linkOrigin === undefined) {
106
+ console.error(`[prunelle/auth] refusing to mail a verification link for host ${ctx.url.host}: set the auth \`site\` option to the public origin`)
107
+ return fail(ctx, 500, 'Verification links are not configured')
108
+ }
109
+ const limited = limits.limitMail(ctx, email)
110
+ if (limited)
111
+ return limited
112
+
113
+ const existing = await sessions.observeAsync(store.getUserByEmail(email))
114
+ if (existing) {
115
+ if (!existing.emailVerified) {
116
+ const sent = await reRegisterUnverified(deps, existing, password, linkOrigin, redirectTarget)
117
+ if (!sent)
118
+ return fail(ctx, 500, 'Unable to send verification email')
119
+ }
120
+ else {
121
+ // The same Argon2id cost as a new address, and no mail inside the request on either path, so timing does not reveal a verified account.
122
+ await hashPassword(password)
123
+ }
124
+ return respondVerificationAccepted(ctx, redirectTarget, messages['signup.verification-sent'])
125
+ }
126
+
127
+ let user: PublicUser<TUser>
128
+ try {
129
+ user = await createUser({ email, password, name, emailVerified: false } as CreateUserInput<TUser>)
130
+ }
131
+ catch (err) {
132
+ if (await sessions.observeAsync(store.getUserByEmail(email)))
133
+ return respondVerificationAccepted(ctx, redirectTarget, messages['signup.verification-sent'])
134
+ throw err
135
+ }
136
+
137
+ const deleteIfUnchanged = async (): Promise<void> => {
138
+ const cur = await sessions.observeAsync(store.getUserById(user.id))
139
+ if (!cur || cur.emailVerified || cur.updatedAt !== user.updatedAt)
140
+ return
141
+ await sessions.observeAsync(store.deleteUser(user.id))
142
+ }
143
+ try {
144
+ // A mail outage deletes the account once the send fails, so it does not lock the address out.
145
+ await issueLink('verify-email', user.id, user.email, linkOrigin, redirectTarget, { onFailure: deleteIfUnchanged })
146
+ }
147
+ catch {
148
+ try {
149
+ await deleteIfUnchanged()
150
+ }
151
+ catch {
152
+ // Best-effort rollback so a store outage does not permanently lock out the email address.
153
+ }
154
+ return fail(ctx, 500, 'Unable to send verification email')
155
+ }
156
+
157
+ return respondVerificationAccepted(ctx, redirectTarget, messages['signup.verification-sent'])
158
+ }
159
+
89
160
  export function registerAuthRoutes<TUser extends AuthUser = AuthUser>(deps: AuthRoutesDeps<TUser>): void {
90
161
  const {
91
162
  authRoute,
163
+ limits,
92
164
  store,
93
165
  sessions,
94
166
  totp,
95
167
  twoFactorRedirect,
96
168
  minPasswordLength,
97
169
  maxPasswordLength,
170
+ messages,
98
171
  defaultRedirect,
99
172
  requireEmailVerification,
100
- hasMailTransport,
101
173
  mailedLinkOrigin,
102
- equalizeSignupMailDelay,
103
174
  createUser,
104
175
  insertUser,
105
176
  claimUnverified,
106
- issueLink,
107
177
  consumeLink,
108
178
  sendMagicLink,
109
179
  } = deps
@@ -131,6 +201,10 @@ export function registerAuthRoutes<TUser extends AuthUser = AuthUser>(deps: Auth
131
201
  if (!userRecord)
132
202
  return fail(ctx, 400, invalid)
133
203
 
204
+ const twoFactorMethods = await totp.getTwoFactorMethods(userRecord.id)
205
+ if (twoFactorMethods.length > 0)
206
+ return respondTwoFactorChallenge(totp, ctx, userRecord.id, redirectTarget, twoFactorRedirect, twoFactorMethods)
207
+
134
208
  const pub = toPublicUser(userRecord)
135
209
  await sessions.createSessionForUser(userRecord.id, ctx, pub)
136
210
  if (wantsJson(ctx.request))
@@ -147,69 +221,24 @@ export function registerAuthRoutes<TUser extends AuthUser = AuthUser>(deps: Auth
147
221
  })
148
222
  })
149
223
 
150
- authRoute('POST', '/signup', { limit: 'signup', emailLimit: 'signup', readBody: true }, async (ctx, body) => {
224
+ authRoute('POST', '/signup', { limit: 'signup', readBody: true }, async (ctx, body) => {
151
225
  const email = normalizeEmail(body.email ?? '')
152
226
  const password = body.password ?? ''
153
227
  const name = body.name?.trim() || undefined
154
228
  const redirectTarget = safeRedirect(body.redirect ?? body.next, defaultRedirect)
155
229
 
156
230
  if (!isValidEmail(email))
157
- return respondAuthError(ctx, 400, 'Please enter a valid email address')
231
+ return respondAuthError(ctx, 400, messages['signup.invalid-email'])
158
232
  if (password.length < minPasswordLength)
159
- return respondAuthError(ctx, 400, `Password must be at least ${minPasswordLength} characters`)
233
+ return respondAuthError(ctx, 400, messages['signup.password-too-short'])
160
234
  if (isPasswordTooLong(password, maxPasswordLength))
161
- return respondAuthError(ctx, 400, `Password must be at most ${maxPasswordLength} characters`)
162
-
163
- if (requireEmailVerification) {
164
- const linkOrigin = mailedLinkOrigin(ctx.url)
165
- if (hasMailTransport && linkOrigin === undefined) {
166
- console.error(`[prunelle/auth] refusing to mail a verification link for host ${ctx.url.host}: set the auth \`site\` option to the public origin`)
167
- return fail(ctx, 500, 'Verification links are not configured')
168
- }
169
-
170
- const existing = await sessions.observeAsync(store.getUserByEmail(email))
171
- if (existing) {
172
- if (!existing.emailVerified) {
173
- const sent = await reRegisterUnverified(deps, existing, password, name, linkOrigin, redirectTarget)
174
- if (!sent)
175
- return fail(ctx, 500, 'Unable to send verification email')
176
- }
177
- else {
178
- // Equalize Argon2id + mail-delivery timing so signup does not reveal already-verified emails.
179
- await hashPassword(password)
180
- await equalizeSignupMailDelay()
181
- }
182
- return respondVerificationAccepted(ctx, redirectTarget)
183
- }
184
-
185
- let user: PublicUser<TUser>
186
- try {
187
- user = await createUser({ email, password, name, emailVerified: false } as CreateUserInput<TUser>)
188
- }
189
- catch (err) {
190
- if (await sessions.observeAsync(store.getUserByEmail(email)))
191
- return respondVerificationAccepted(ctx, redirectTarget)
192
- throw err
193
- }
194
-
195
- try {
196
- await issueLink('verify-email', user.id, user.email, linkOrigin, redirectTarget)
197
- }
198
- catch {
199
- try {
200
- await sessions.observeAsync(store.deleteUser(user.id))
201
- }
202
- catch {
203
- // Best-effort rollback so a mail outage does not permanently lock out the email address.
204
- }
205
- return fail(ctx, 500, 'Unable to send verification email')
206
- }
235
+ return respondAuthError(ctx, 400, messages['signup.password-too-long'])
207
236
 
208
- return respondVerificationAccepted(ctx, redirectTarget)
209
- }
237
+ if (requireEmailVerification)
238
+ return signUpPendingVerification(deps, ctx, { email, password, name, redirectTarget })
210
239
 
211
240
  if (await sessions.observeAsync(store.getUserByEmail(email)))
212
- return respondAuthError(ctx, 409, 'An account with this email already exists')
241
+ return respondAuthError(ctx, 409, messages['signup.email-taken'])
213
242
 
214
243
  const user = await createUser({ email, password, name } as CreateUserInput<TUser>)
215
244
  await sessions.createSessionForUser(user.id, ctx, user)
@@ -230,30 +259,31 @@ export function registerAuthRoutes<TUser extends AuthUser = AuthUser>(deps: Auth
230
259
  return (await sessions.observeAsync(store.updateUser(user.id, { emailVerified: true } as Partial<Omit<TUser, 'id' | 'createdAt'>>))) ?? { ...user, emailVerified: true }
231
260
  })
232
261
 
233
- authRoute('POST', '/signin', { limit: 'signin', emailLimit: 'signin', readBody: true }, async (ctx, body) => {
262
+ authRoute('POST', '/signin', { limit: 'signin', readBody: true }, async (ctx, body) => {
234
263
  const email = normalizeEmail(body.email ?? '')
235
264
  const password = body.password ?? ''
236
265
  const redirectTarget = safeRedirect(body.redirect ?? body.next, defaultRedirect)
237
266
 
238
267
  if (isPasswordTooLong(password, maxPasswordLength))
239
- return respondAuthError(ctx, 400, `Password must be at most ${maxPasswordLength} characters`)
268
+ return respondAuthError(ctx, 400, messages['signin.password-too-long'])
269
+
270
+ const locked = limits.refuseLockedAccount(ctx, email)
271
+ if (locked)
272
+ return locked
240
273
 
241
274
  const userRecord = email ? await sessions.observeAsync(store.getUserByEmail(email)) : undefined
242
275
  const valid = await verifyPassword(password, userRecord?.passwordHash)
243
- if (!userRecord || !valid)
244
- return respondAuthError(ctx, 401, 'Invalid email or password')
276
+ if (!userRecord || !valid) {
277
+ limits.countFailedSignin(email)
278
+ return respondAuthError(ctx, 401, messages['signin.invalid-credentials'])
279
+ }
245
280
 
246
281
  if (requireEmailVerification && !userRecord.emailVerified)
247
- return respondAuthError(ctx, 403, 'Email not verified')
282
+ return respondAuthError(ctx, 403, messages['signin.email-not-verified'])
248
283
 
249
284
  const twoFactorMethods = await totp.getTwoFactorMethods(userRecord.id)
250
- if (twoFactorMethods.length > 0) {
251
- totp.issuePendingCookie(ctx, userRecord.id, redirectTarget, twoFactorMethods)
252
- if (wantsJson(ctx.request))
253
- return ctx.json({ ok: true, twoFactorRequired: true, methods: twoFactorMethods, userId: userRecord.id }, { status: 200 })
254
- const sep = twoFactorRedirect.includes('?') ? '&' : '?'
255
- return ctx.redirect(`${twoFactorRedirect}${sep}next=${encodeURIComponent(redirectTarget)}`, 303)
256
- }
285
+ if (twoFactorMethods.length > 0)
286
+ return respondTwoFactorChallenge(totp, ctx, userRecord.id, redirectTarget, twoFactorRedirect, twoFactorMethods)
257
287
 
258
288
  const pub = toPublicUser(userRecord)
259
289
  await sessions.createSessionForUser(userRecord.id, ctx, pub)
@@ -271,7 +301,7 @@ export function registerAuthRoutes<TUser extends AuthUser = AuthUser>(deps: Auth
271
301
  return ctx.redirect(safeRedirect(ctx.url.searchParams.get('redirect'), defaultRedirect), 303)
272
302
  })
273
303
 
274
- authRoute('POST', '/magic-link', { limit: 'magic', emailLimit: 'magic', readBody: true }, async (ctx, body) => {
304
+ authRoute('POST', '/magic-link', { limit: 'magic', readBody: true }, async (ctx, body) => {
275
305
  const email = normalizeEmail(body.email ?? '')
276
306
  if (!isValidEmail(email))
277
307
  return fail(ctx, 400, 'Please enter a valid email address')
@@ -281,6 +311,9 @@ export function registerAuthRoutes<TUser extends AuthUser = AuthUser>(deps: Auth
281
311
  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`)
282
312
  return fail(ctx, 500, 'Sign-in links are not configured')
283
313
  }
314
+ const limited = limits.limitMail(ctx, email)
315
+ if (limited)
316
+ return limited
284
317
  await sendMagicLink(email, linkOrigin, body.redirect ?? body.next)
285
318
  return ctx.json({ ok: true, message: 'If that address can sign in, a link has been sent.' })
286
319
  })
@@ -0,0 +1,62 @@
1
+ // The session cookie's name and lifetime: `__Host-` prefixed over https, with opt-in migration from the plain name.
2
+
3
+ import type { RequestContext } from 'prunelle/server'
4
+ import { authCookie } from './http'
5
+
6
+ const HOST_PREFIX = '__Host-'
7
+ const SECURE_PREFIX = '__Secure-'
8
+
9
+ export interface SessionCookie {
10
+ /** The session token the request carries, under the https name (or plain name when `acceptLegacyCookie` is enabled). */
11
+ read: (ctx: RequestContext) => string | undefined
12
+ /** Sets the cookie to expire with the session, and drops the plain name when migrating a legacy cookie. */
13
+ set: (ctx: RequestContext, rawToken: string, expiresAt: number) => void
14
+ /** Sets the cookie under its https name when the request carried the plain one. */
15
+ moveLegacy: (ctx: RequestContext, rawToken: string, expiresAt: number) => void
16
+ clear: (ctx: RequestContext) => void
17
+ }
18
+
19
+ export function createSessionCookie(
20
+ cookieName: string,
21
+ isSecureCookie: (ctx: RequestContext) => boolean,
22
+ acceptLegacyCookie = false,
23
+ ): SessionCookie {
24
+ // Contexts whose session came in under the plain name over https.
25
+ const legacy = new WeakSet<object>()
26
+ // A name that starts with `__` carries its own prefix rules and is used as given.
27
+ const hostName = cookieName.startsWith('__') ? undefined : `${HOST_PREFIX}${cookieName}`
28
+ const requiresSecure = cookieName.startsWith(HOST_PREFIX) || cookieName.startsWith(SECURE_PREFIX)
29
+ const currentName = (ctx: RequestContext): string => hostName !== undefined && isSecureCookie(ctx) ? hostName : cookieName
30
+
31
+ const set: SessionCookie['set'] = (ctx, rawToken, expiresAt) => {
32
+ const name = currentName(ctx)
33
+ ctx.cookies.set(name, rawToken, authCookie(requiresSecure || isSecureCookie(ctx), Math.max(0, Math.floor((expiresAt - Date.now()) / 1000))))
34
+ legacy.delete(ctx.locals)
35
+ if (name !== cookieName && acceptLegacyCookie)
36
+ ctx.cookies.delete(cookieName, { path: '/' })
37
+ }
38
+
39
+ return {
40
+ read(ctx) {
41
+ const name = currentName(ctx)
42
+ const token = ctx.cookies.get(name)
43
+ if (token !== undefined || name === cookieName || !acceptLegacyCookie)
44
+ return token
45
+ const old = ctx.cookies.get(cookieName)
46
+ if (old)
47
+ legacy.add(ctx.locals)
48
+ return old
49
+ },
50
+ set,
51
+ moveLegacy(ctx, rawToken, expiresAt) {
52
+ if (legacy.has(ctx.locals))
53
+ set(ctx, rawToken, expiresAt)
54
+ },
55
+ clear(ctx) {
56
+ if (hostName === undefined || !isSecureCookie(ctx) || acceptLegacyCookie)
57
+ ctx.cookies.delete(cookieName, requiresSecure ? { path: '/', secure: true } : { path: '/' })
58
+ if (hostName !== undefined && isSecureCookie(ctx))
59
+ ctx.cookies.delete(hostName, { path: '/', secure: true })
60
+ },
61
+ }
62
+ }
package/src/session.ts CHANGED
@@ -4,6 +4,7 @@ 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 { createSessionCookie } from './session-cookie'
7
8
  import { isKnownSyncStore, toPublicUser } from './store'
8
9
 
9
10
  const AsyncFunctionCtor = Object.getPrototypeOf(async () => {}).constructor
@@ -21,6 +22,11 @@ function defineLocal(locals: PrunelleLocals, key: 'user' | 'session', value: unk
21
22
  })
22
23
  }
23
24
 
25
+ function isLiveSession(session: AuthSession, absoluteTtlMs: number | undefined): boolean {
26
+ const now = Date.now()
27
+ return session.expiresAt > now && (absoluteTtlMs === undefined || session.createdAt + absoluteTtlMs > now)
28
+ }
29
+
24
30
  function sweepRenewedMap(renewedAt: Map<string, number>, renewalIntervalMs: number): void {
25
31
  if (renewedAt.size === 0)
26
32
  return
@@ -90,7 +96,10 @@ export function hasAsyncStoreMethods<TUser extends AuthUser>(store: AuthStore<TU
90
96
  export interface SessionManagerDeps<TUser extends AuthUser = AuthUser> {
91
97
  store: AuthStore<TUser>
92
98
  cookieName: string
99
+ acceptLegacyCookie?: boolean | undefined
93
100
  sessionTtlMs: number
101
+ /** A session older than this is refused however recently it was used; `undefined` lets renewal go on forever. */
102
+ absoluteTtlMs: number | undefined
94
103
  renewalIntervalMs: number
95
104
  storeIp: boolean | 'truncate'
96
105
  storeUserAgent: boolean
@@ -113,7 +122,7 @@ export interface SessionManager<TUser extends AuthUser = AuthUser> {
113
122
  }
114
123
 
115
124
  export function createSessionManager<TUser extends AuthUser = AuthUser>(deps: SessionManagerDeps<TUser>): SessionManager<TUser> {
116
- const { store, cookieName, sessionTtlMs, renewalIntervalMs, storeIp, storeUserAgent, getTrustProxy, isSecureCookie } = deps
125
+ const { store, cookieName, acceptLegacyCookie, sessionTtlMs, absoluteTtlMs, renewalIntervalMs, storeIp, storeUserAgent, getTrustProxy, isSecureCookie } = deps
117
126
 
118
127
  let storeMode: 'unknown' | 'sync' | 'async' = isKnownSyncStore(store)
119
128
  ? 'sync'
@@ -122,6 +131,16 @@ export function createSessionManager<TUser extends AuthUser = AuthUser>(deps: Se
122
131
  const resolvedUsers = new WeakMap<object, PublicUser<TUser>>()
123
132
  const pendingContexts = new WeakMap<object, Promise<{ user: PublicUser<TUser>, session: AuthSession } | undefined>>()
124
133
  const renewedAt = new Map<string, number>()
134
+ const sessionCookie = createSessionCookie(cookieName, isSecureCookie, acceptLegacyCookie === true)
135
+ const { read: readToken, clear: clearCookies } = sessionCookie
136
+
137
+ // This request has no session (any more): its locals stay empty, and the cookie goes when it was refused.
138
+ function endResolution(ctx: RequestContext, clearCookie = false): void {
139
+ resolvedContexts.add(ctx.locals)
140
+ clearLazyLocals(ctx.locals)
141
+ if (clearCookie)
142
+ clearCookies(ctx)
143
+ }
125
144
 
126
145
  function observeAsync<T>(value: T | Promise<T>): T | Promise<T> {
127
146
  if (isPromiseLike(value))
@@ -131,16 +150,6 @@ export function createSessionManager<TUser extends AuthUser = AuthUser>(deps: Se
131
150
  return value
132
151
  }
133
152
 
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
153
  function setResolvedUser(ctx: RequestContext, pub: PublicUser<TUser>): void {
145
154
  resolvedUsers.set(ctx.locals, pub)
146
155
  defineLocal(ctx.locals, 'user', pub)
@@ -160,17 +169,20 @@ export function createSessionManager<TUser extends AuthUser = AuthUser>(deps: Se
160
169
 
161
170
  function maybeRenewSession(ctx: RequestContext, rawToken: string, tokenHash: string, session: AuthSession): void | Promise<void> {
162
171
  const now = Date.now()
172
+ sessionCookie.moveLegacy(ctx, rawToken, session.expiresAt)
163
173
  if (session.expiresAt - now >= sessionTtlMs / 2)
164
174
  return
175
+ const nextExpiry = Math.min(now + sessionTtlMs, absoluteTtlMs === undefined ? Infinity : session.createdAt + absoluteTtlMs)
176
+ if (nextExpiry <= session.expiresAt)
177
+ return
165
178
  const prev = renewedAt.get(tokenHash)
166
179
  if (prev !== undefined && now - prev < renewalIntervalMs)
167
180
  return
168
181
  if (renewedAt.size >= 10_000)
169
182
  sweepRenewedAt()
170
183
  renewedAt.set(tokenHash, now)
171
- const nextExpiry = now + sessionTtlMs
172
184
  session.expiresAt = nextExpiry
173
- setSessionCookie(ctx, rawToken)
185
+ sessionCookie.set(ctx, rawToken, nextExpiry)
174
186
  return observeAsync(store.updateSessionExpiry(tokenHash, nextExpiry))
175
187
  }
176
188
 
@@ -200,28 +212,25 @@ export function createSessionManager<TUser extends AuthUser = AuthUser>(deps: Se
200
212
  return inFlight
201
213
 
202
214
  const run = (async (): Promise<{ user: PublicUser<TUser>, session: AuthSession } | undefined> => {
203
- const rawToken = ctx.cookies.get(cookieName)
215
+ const rawToken = readToken(ctx)
204
216
  if (!rawToken) {
205
- resolvedContexts.add(ctx.locals)
206
- clearLazyLocals(ctx.locals)
217
+ endResolution(ctx)
207
218
  return undefined
208
219
  }
209
220
 
210
221
  const tokenHash = sha256Hex(rawToken)
211
222
  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: '/' })
223
+ if (!session || !isLiveSession(session, absoluteTtlMs)) {
224
+ endResolution(ctx, true)
225
+ if (session)
226
+ await observeAsync(store.deleteSession(tokenHash))
216
227
  return undefined
217
228
  }
218
229
 
219
230
  const userRecord = preloadedUser !== undefined ? await preloadedUser : await observeAsync(store.getUserById(session.userId))
220
231
  if (!userRecord) {
221
- resolvedContexts.add(ctx.locals)
222
- clearLazyLocals(ctx.locals)
232
+ endResolution(ctx, true)
223
233
  await observeAsync(store.deleteSession(tokenHash))
224
- ctx.cookies.delete(cookieName, { path: '/' })
225
234
  return undefined
226
235
  }
227
236
 
@@ -252,30 +261,27 @@ export function createSessionManager<TUser extends AuthUser = AuthUser>(deps: Se
252
261
  const session = ctx.locals.session
253
262
  return { resolved: user && session ? { user, session } : undefined }
254
263
  }
255
- const rawToken = ctx.cookies.get(cookieName)
264
+ const rawToken = readToken(ctx)
256
265
  if (!rawToken) {
257
- resolvedContexts.add(ctx.locals)
258
- clearLazyLocals(ctx.locals)
266
+ endResolution(ctx)
259
267
  return { resolved: undefined }
260
268
  }
261
269
  const tokenHash = sha256Hex(rawToken)
262
270
  const maybeSession = observeAsync(store.getSession(tokenHash))
263
271
  if (isPromiseLike(maybeSession))
264
272
  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: '/' })
273
+ if (!maybeSession || !isLiveSession(maybeSession, absoluteTtlMs)) {
274
+ endResolution(ctx, true)
275
+ if (maybeSession)
276
+ void Promise.resolve(observeAsync(store.deleteSession(tokenHash))).catch(() => {})
269
277
  return { resolved: undefined }
270
278
  }
271
279
  const maybeUser = observeAsync(store.getUserById(maybeSession.userId))
272
280
  if (isPromiseLike(maybeUser))
273
281
  return { pending: resolveRequestSession(ctx, Promise.resolve(maybeSession), maybeUser) }
274
282
  if (!maybeUser) {
275
- resolvedContexts.add(ctx.locals)
276
- clearLazyLocals(ctx.locals)
283
+ endResolution(ctx, true)
277
284
  void Promise.resolve(observeAsync(store.deleteSession(tokenHash))).catch(() => {})
278
- ctx.cookies.delete(cookieName, { path: '/' })
279
285
  return { resolved: undefined }
280
286
  }
281
287
  return { resolved: finalizeResolved(ctx, rawToken, tokenHash, maybeSession, maybeUser) }
@@ -291,13 +297,13 @@ export function createSessionManager<TUser extends AuthUser = AuthUser>(deps: Se
291
297
  }
292
298
 
293
299
  function attachLazy(ctx: RequestContext): void {
294
- if (resolvedContexts.has(ctx.locals) || !ctx.cookies.get(cookieName))
300
+ if (resolvedContexts.has(ctx.locals) || !readToken(ctx))
295
301
  return
296
302
  defineLazyLocals(ctx, () => readSyncLazy(ctx))
297
303
  }
298
304
 
299
305
  function prepareRequest(ctx: RequestContext): Promise<unknown> | undefined {
300
- if (!ctx.cookies.get(cookieName))
306
+ if (!readToken(ctx))
301
307
  return undefined
302
308
  if (storeMode === 'async')
303
309
  return resolveRequestSession(ctx)
@@ -309,7 +315,7 @@ export function createSessionManager<TUser extends AuthUser = AuthUser>(deps: Se
309
315
 
310
316
  async function createSessionForUser(userId: string, ctx: RequestContext, knownUser?: PublicUser<TUser>): Promise<AuthSession> {
311
317
  // Revoke any prior session cookie in the store when opening a new session on the same browser.
312
- const prevToken = ctx.cookies.get(cookieName)
318
+ const prevToken = readToken(ctx)
313
319
  if (prevToken) {
314
320
  const prevHash = sha256Hex(prevToken)
315
321
  renewedAt.delete(prevHash)
@@ -324,12 +330,12 @@ export function createSessionManager<TUser extends AuthUser = AuthUser>(deps: Se
324
330
  id: sha256Hex(rawToken),
325
331
  userId,
326
332
  createdAt: now,
327
- expiresAt: now + sessionTtlMs,
333
+ expiresAt: absoluteTtlMs === undefined ? now + sessionTtlMs : now + Math.min(sessionTtlMs, absoluteTtlMs),
328
334
  ...(recordedUa !== undefined ? { userAgent: recordedUa } : {}),
329
335
  ...(recordedIp !== undefined ? { ip: recordedIp } : {}),
330
336
  }
331
337
  await observeAsync(store.createSession(session))
332
- setSessionCookie(ctx, rawToken)
338
+ sessionCookie.set(ctx, rawToken, session.expiresAt)
333
339
  resolvedContexts.delete(ctx.locals)
334
340
  resolvedUsers.delete(ctx.locals)
335
341
  delete ctx.locals.user
@@ -346,15 +352,13 @@ export function createSessionManager<TUser extends AuthUser = AuthUser>(deps: Se
346
352
  }
347
353
 
348
354
  async function signOut(ctx: RequestContext): Promise<void> {
349
- const rawToken = ctx.cookies.get(cookieName)
355
+ const rawToken = readToken(ctx)
350
356
  if (rawToken) {
351
357
  const tokenHash = sha256Hex(rawToken)
352
358
  renewedAt.delete(tokenHash)
353
359
  await observeAsync(store.deleteSession(tokenHash))
354
360
  }
355
- ctx.cookies.delete(cookieName, { path: '/' })
356
- resolvedContexts.add(ctx.locals)
357
- clearLazyLocals(ctx.locals)
361
+ endResolution(ctx, true)
358
362
  }
359
363
 
360
364
  return {