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