@prunellejs/auth 0.1.1 → 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/src/routes.ts CHANGED
@@ -1,15 +1,16 @@
1
1
  // Auth HTTP routes: /session, /signup, /verify-email, /signin, /signout, /magic-link, /magic-link/verify.
2
2
 
3
- import type { PluginRouteOptions, ServerPluginAPI } from 'prunelle/config'
4
3
  import type { RequestContext } from 'prunelle/server'
5
- import { safeRedirect, wantsJson } from 'prunelle/server'
4
+ import type { AuthFormMessage, AuthFormMessages } from './form-messages'
5
+ import type { AuthLimits, AuthRouteRegistrar } from './http'
6
6
  import type { CreateUserInput } from './index'
7
-
8
- import type { AuthLimits } from './http'
7
+ import type { MailInBackground } from './links'
9
8
  import type { SessionManager } from './session'
10
9
  import type { AuthStore, AuthUser, PublicUser } from './store'
11
- import { verifyPassword } from './crypto'
12
- import { fail, isValidEmail, linkConfirmPage, parseBody, respondAuthError, withNoStore } from './http'
10
+ import type { TotpManager } from './totp'
11
+ import { safeRedirect, wantsJson } from 'prunelle/server'
12
+ import { hashPassword, verifyPassword } from './crypto'
13
+ import { fail, formPagePath, isValidEmail, linkConfirmPage, respondAuthError } from './http'
13
14
  import { normalizeEmail, toPublicUser } from './store'
14
15
 
15
16
  const LINK_PAGES = {
@@ -17,15 +18,62 @@ const LINK_PAGES = {
17
18
  'verify-email': { title: 'Confirm your email address', button: 'Confirm' },
18
19
  }
19
20
 
21
+ function isPasswordTooLong(password: string, max: number): boolean {
22
+ return password.length > max || Buffer.byteLength(password, 'utf8') > max
23
+ }
24
+
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)
30
+ }
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).
33
+ async function reRegisterUnverified<TUser extends AuthUser>(
34
+ deps: AuthRoutesDeps<TUser>,
35
+ existing: TUser,
36
+ password: string,
37
+ linkOrigin: string | undefined,
38
+ redirectTarget: string,
39
+ ): Promise<boolean> {
40
+ const { store, sessions, issueLink } = deps
41
+ // Same Argon2id cost as a first sign-up, so timing does not reveal a pending account.
42
+ await hashPassword(password)
43
+ const prevHash = existing.passwordHash
44
+ const prevName = existing.name
45
+ await sessions.observeAsync(store.deleteUserSessions(existing.id))
46
+ await sessions.observeAsync(store.deleteUserOAuthAccounts(existing.id))
47
+ const patch = { passwordHash: undefined, name: undefined } as Partial<Omit<TUser, 'id' | 'createdAt'>>
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
+ }
52
+ try {
53
+ await issueLink('verify-email', existing.id, existing.email, linkOrigin, redirectTarget, { onFailure: restore })
54
+ return true
55
+ }
56
+ catch {
57
+ try {
58
+ await restore()
59
+ }
60
+ catch (rollbackErr) {
61
+ console.error('[prunelle/auth] failed to roll back unverified signup update:', rollbackErr)
62
+ }
63
+ return false
64
+ }
65
+ }
66
+
20
67
  export interface AuthRoutesDeps<TUser extends AuthUser = AuthUser> {
21
- api: ServerPluginAPI
68
+ authRoute: AuthRouteRegistrar
69
+ limits: AuthLimits
22
70
  store: AuthStore<TUser>
23
71
  sessions: SessionManager<TUser>
24
- limitIp: AuthLimits['limitIp']
25
- limitEmail: AuthLimits['limitEmail']
26
- basePath: string
27
- authRouteOpts: PluginRouteOptions
72
+ totp: TotpManager
73
+ twoFactorRedirect: string
28
74
  minPasswordLength: number
75
+ maxPasswordLength: number
76
+ messages: AuthFormMessages
29
77
  defaultRedirect: string
30
78
  requireEmailVerification: boolean
31
79
  hasMailTransport: boolean
@@ -33,61 +81,87 @@ export interface AuthRoutesDeps<TUser extends AuthUser = AuthUser> {
33
81
  createUser: (input: CreateUserInput<TUser>) => Promise<PublicUser<TUser>>
34
82
  insertUser: (fields: Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>) => Promise<TUser>
35
83
  claimUnverified: (user: TUser) => Promise<TUser>
36
- 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>
37
85
  consumeLink: (kind: 'magic-link' | 'verify-email', rawToken: string) => Promise<{ email: string, user: TUser | undefined } | undefined>
38
86
  sendMagicLink: (email: string, origin: string, redirectTo?: string) => Promise<string>
39
87
  }
40
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
+
41
144
  export function registerAuthRoutes<TUser extends AuthUser = AuthUser>(deps: AuthRoutesDeps<TUser>): void {
42
145
  const {
43
- api,
146
+ authRoute,
147
+ limits,
44
148
  store,
45
149
  sessions,
46
- limitEmail,
47
- limitIp,
48
- basePath,
49
- authRouteOpts,
150
+ totp,
151
+ twoFactorRedirect,
50
152
  minPasswordLength,
153
+ maxPasswordLength,
154
+ messages,
51
155
  defaultRedirect,
52
156
  requireEmailVerification,
53
- hasMailTransport,
54
157
  mailedLinkOrigin,
55
158
  createUser,
56
159
  insertUser,
57
160
  claimUnverified,
58
- issueLink,
59
161
  consumeLink,
60
162
  sendMagicLink,
61
163
  } = deps
62
164
 
63
- function authRoute(
64
- method: 'GET' | 'POST',
65
- path: string,
66
- routeCfg: { limit?: string, emailLimit?: string, readBody?: boolean },
67
- handler: (ctx: RequestContext, body: Record<string, string>) => Response | Promise<Response>,
68
- ): void {
69
- api.route(method, `${basePath}${path}`, async (ctx) => {
70
- if (routeCfg.limit !== undefined) {
71
- const limited = limitIp(ctx, routeCfg.limit)
72
- if (limited)
73
- return withNoStore(limited)
74
- }
75
- let body: Record<string, string> = {}
76
- if (routeCfg.readBody) {
77
- const parsed = await parseBody(ctx)
78
- if (parsed instanceof Response)
79
- return withNoStore(parsed)
80
- body = parsed
81
- }
82
- if (routeCfg.emailLimit !== undefined) {
83
- const limited = limitEmail(ctx, routeCfg.emailLimit, body.email)
84
- if (limited)
85
- return withNoStore(limited)
86
- }
87
- return withNoStore(await handler(ctx, body))
88
- }, method === 'POST' ? authRouteOpts : undefined)
89
- }
90
-
91
165
  // GET on a mailed link: the token stays unused until the page's button posts it, and the POST checks the redirect.
92
166
  function confirmLinkRoute(kind: 'magic-link' | 'verify-email', path: string, limit: string): void {
93
167
  authRoute('GET', path, { limit }, (ctx) => {
@@ -111,26 +185,14 @@ export function registerAuthRoutes<TUser extends AuthUser = AuthUser>(deps: Auth
111
185
  if (!userRecord)
112
186
  return fail(ctx, 400, invalid)
113
187
 
114
- await sessions.createSessionForUser(userRecord.id, ctx)
115
188
  const pub = toPublicUser(userRecord)
116
- sessions.setResolvedUser(ctx, pub)
189
+ await sessions.createSessionForUser(userRecord.id, ctx, pub)
117
190
  if (wantsJson(ctx.request))
118
191
  return ctx.json({ ok: true, user: pub }, { status: 200 })
119
192
  return ctx.redirect(redirectTarget, 303)
120
193
  })
121
194
  }
122
195
 
123
- function respondVerificationAccepted(ctx: RequestContext, redirectTarget: string): Response {
124
- if (wantsJson(ctx.request)) {
125
- return ctx.json({
126
- ok: true,
127
- verificationRequired: true,
128
- message: 'If that address can be registered, a verification link has been sent.',
129
- }, { status: 202 })
130
- }
131
- return ctx.redirect(redirectTarget, 303)
132
- }
133
-
134
196
  authRoute('GET', '/session', {}, async (ctx) => {
135
197
  const resolved = await sessions.resolve(ctx)
136
198
  return ctx.json({
@@ -139,71 +201,27 @@ export function registerAuthRoutes<TUser extends AuthUser = AuthUser>(deps: Auth
139
201
  })
140
202
  })
141
203
 
142
- authRoute('POST', '/signup', { limit: 'signup', emailLimit: 'signup', readBody: true }, async (ctx, body) => {
204
+ authRoute('POST', '/signup', { limit: 'signup', mailLimit: 'signup', readBody: true }, async (ctx, body) => {
143
205
  const email = normalizeEmail(body.email ?? '')
144
206
  const password = body.password ?? ''
145
207
  const name = body.name?.trim() || undefined
146
208
  const redirectTarget = safeRedirect(body.redirect ?? body.next, defaultRedirect)
147
209
 
148
210
  if (!isValidEmail(email))
149
- return respondAuthError(ctx, 400, 'Please enter a valid email address')
211
+ return respondAuthError(ctx, 400, messages['signup.invalid-email'])
150
212
  if (password.length < minPasswordLength)
151
- return respondAuthError(ctx, 400, `Password must be at least ${minPasswordLength} characters`)
152
-
153
- if (requireEmailVerification) {
154
- const linkOrigin = mailedLinkOrigin(ctx.url)
155
- if (hasMailTransport && linkOrigin === undefined) {
156
- console.error(`[prunelle/auth] refusing to mail a verification link for host ${ctx.url.host}: set the auth \`site\` option to the public origin`)
157
- return fail(ctx, 500, 'Verification links are not configured')
158
- }
159
-
160
- const existing = await sessions.observeAsync(store.getUserByEmail(email))
161
- if (existing) {
162
- // Equalize timing with Argon2id hashing and avoid revealing whether the email is already registered.
163
- await verifyPassword(password, undefined)
164
- if (!existing.emailVerified) {
165
- try {
166
- await issueLink('verify-email', existing.id, existing.email, linkOrigin, redirectTarget)
167
- }
168
- catch {
169
- return fail(ctx, 500, 'Unable to send verification email')
170
- }
171
- }
172
- return respondVerificationAccepted(ctx, redirectTarget)
173
- }
174
-
175
- let user: PublicUser<TUser>
176
- try {
177
- user = await createUser({ email, password, name, emailVerified: false } as CreateUserInput<TUser>)
178
- }
179
- catch (err) {
180
- if (await sessions.observeAsync(store.getUserByEmail(email)))
181
- return respondVerificationAccepted(ctx, redirectTarget)
182
- throw err
183
- }
184
-
185
- try {
186
- await issueLink('verify-email', user.id, user.email, linkOrigin, redirectTarget)
187
- }
188
- catch {
189
- try {
190
- await sessions.observeAsync(store.deleteUser(user.id))
191
- }
192
- catch {
193
- // Best-effort rollback so a mail outage does not permanently lock out the email address.
194
- }
195
- return fail(ctx, 500, 'Unable to send verification email')
196
- }
213
+ return respondAuthError(ctx, 400, messages['signup.password-too-short'])
214
+ if (isPasswordTooLong(password, maxPasswordLength))
215
+ return respondAuthError(ctx, 400, messages['signup.password-too-long'])
197
216
 
198
- return respondVerificationAccepted(ctx, redirectTarget)
199
- }
217
+ if (requireEmailVerification)
218
+ return signUpPendingVerification(deps, ctx, { email, password, name, redirectTarget })
200
219
 
201
220
  if (await sessions.observeAsync(store.getUserByEmail(email)))
202
- return respondAuthError(ctx, 409, 'An account with this email already exists')
221
+ return respondAuthError(ctx, 409, messages['signup.email-taken'])
203
222
 
204
223
  const user = await createUser({ email, password, name } as CreateUserInput<TUser>)
205
- await sessions.createSessionForUser(user.id, ctx)
206
- sessions.setResolvedUser(ctx, user)
224
+ await sessions.createSessionForUser(user.id, ctx, user)
207
225
 
208
226
  if (wantsJson(ctx.request))
209
227
  return ctx.json({ ok: true, user }, { status: 201 })
@@ -214,25 +232,46 @@ export function registerAuthRoutes<TUser extends AuthUser = AuthUser>(deps: Auth
214
232
  consumeLinkRoute('verify-email', '/verify-email', 'verify-email', 'Invalid or expired verification link', async ({ user }) => {
215
233
  if (!user)
216
234
  return undefined
235
+ if (!user.emailVerified) {
236
+ await sessions.observeAsync(store.deleteUserSessions(user.id))
237
+ await sessions.observeAsync(store.deleteUserOAuthAccounts(user.id))
238
+ }
217
239
  return (await sessions.observeAsync(store.updateUser(user.id, { emailVerified: true } as Partial<Omit<TUser, 'id' | 'createdAt'>>))) ?? { ...user, emailVerified: true }
218
240
  })
219
241
 
220
- authRoute('POST', '/signin', { limit: 'signin', emailLimit: 'signin', readBody: true }, async (ctx, body) => {
242
+ authRoute('POST', '/signin', { limit: 'signin', readBody: true }, async (ctx, body) => {
221
243
  const email = normalizeEmail(body.email ?? '')
222
244
  const password = body.password ?? ''
223
245
  const redirectTarget = safeRedirect(body.redirect ?? body.next, defaultRedirect)
224
246
 
247
+ if (isPasswordTooLong(password, maxPasswordLength))
248
+ return respondAuthError(ctx, 400, messages['signin.password-too-long'])
249
+
250
+ const locked = limits.refuseLockedAccount(ctx, email)
251
+ if (locked)
252
+ return locked
253
+
225
254
  const userRecord = email ? await sessions.observeAsync(store.getUserByEmail(email)) : undefined
226
255
  const valid = await verifyPassword(password, userRecord?.passwordHash)
227
- if (!userRecord || !valid)
228
- return respondAuthError(ctx, 401, 'Invalid email or password')
256
+ if (!userRecord || !valid) {
257
+ limits.countFailedSignin(email)
258
+ return respondAuthError(ctx, 401, messages['signin.invalid-credentials'])
259
+ }
229
260
 
230
261
  if (requireEmailVerification && !userRecord.emailVerified)
231
- return respondAuthError(ctx, 403, 'Email not verified')
262
+ return respondAuthError(ctx, 403, messages['signin.email-not-verified'])
263
+
264
+ const twoFactorMethods = await totp.getTwoFactorMethods(userRecord.id)
265
+ if (twoFactorMethods.length > 0) {
266
+ totp.issuePendingCookie(ctx, userRecord.id, redirectTarget, twoFactorMethods)
267
+ if (wantsJson(ctx.request))
268
+ return ctx.json({ ok: true, twoFactorRequired: true, methods: twoFactorMethods, userId: userRecord.id }, { status: 200 })
269
+ const sep = twoFactorRedirect.includes('?') ? '&' : '?'
270
+ return ctx.redirect(`${twoFactorRedirect}${sep}next=${encodeURIComponent(redirectTarget)}`, 303)
271
+ }
232
272
 
233
- await sessions.createSessionForUser(userRecord.id, ctx)
234
273
  const pub = toPublicUser(userRecord)
235
- sessions.setResolvedUser(ctx, pub)
274
+ await sessions.createSessionForUser(userRecord.id, ctx, pub)
236
275
 
237
276
  if (wantsJson(ctx.request))
238
277
  return ctx.json({ ok: true, user: pub }, { status: 200 })
@@ -240,13 +279,14 @@ export function registerAuthRoutes<TUser extends AuthUser = AuthUser>(deps: Auth
240
279
  })
241
280
 
242
281
  authRoute('POST', '/signout', {}, async (ctx) => {
282
+ totp.clearPendingCookie(ctx)
243
283
  await sessions.signOut(ctx)
244
284
  if (wantsJson(ctx.request))
245
285
  return ctx.json({ ok: true })
246
286
  return ctx.redirect(safeRedirect(ctx.url.searchParams.get('redirect'), defaultRedirect), 303)
247
287
  })
248
288
 
249
- authRoute('POST', '/magic-link', { limit: 'magic', emailLimit: 'magic', readBody: true }, async (ctx, body) => {
289
+ authRoute('POST', '/magic-link', { limit: 'magic', mailLimit: 'magic', readBody: true }, async (ctx, body) => {
250
290
  const email = normalizeEmail(body.email ?? '')
251
291
  if (!isValidEmail(email))
252
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
+ }