@prunellejs/auth 0.0.0-stage → 0.7.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,327 @@
1
+ // Auth HTTP routes: /session, /signup, /verify-email, /signin, /signout, /magic-link, /magic-link/verify.
2
+
3
+ import type { RequestContext } from 'prunelle/server'
4
+ import type { AuthFormMessage, AuthFormMessages } from './form-messages'
5
+ import type { AuthLimits, AuthRouteRegistrar } from './http'
6
+ import type { CreateUserInput } from './index'
7
+ import type { MailInBackground } from './links'
8
+ import type { SessionManager } from './session'
9
+ import type { AuthStore, AuthUser, PublicUser } from './store'
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'
14
+ import { normalizeEmail, toPublicUser } from './store'
15
+ import { respondTwoFactorChallenge } from './totp'
16
+
17
+ const LINK_PAGES = {
18
+ 'magic-link': { title: 'Sign in', button: 'Sign in' },
19
+ 'verify-email': { title: 'Confirm your email address', button: 'Confirm' },
20
+ }
21
+
22
+ function isPasswordTooLong(password: string, max: number): boolean {
23
+ return password.length > max || Buffer.byteLength(password, 'utf8') > max
24
+ }
25
+
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)
31
+ }
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
+ async function reRegisterUnverified<TUser extends AuthUser>(
35
+ deps: AuthRoutesDeps<TUser>,
36
+ existing: TUser,
37
+ password: string,
38
+ linkOrigin: string | undefined,
39
+ redirectTarget: string,
40
+ ): Promise<boolean> {
41
+ const { store, sessions, issueLink } = deps
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
49
+ await sessions.observeAsync(store.deleteUserSessions(existing.id))
50
+ await sessions.observeAsync(store.deleteUserOAuthAccounts(existing.id))
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
+ }
59
+ try {
60
+ await issueLink('verify-email', existing.id, existing.email, linkOrigin, redirectTarget, { onFailure: restore })
61
+ return true
62
+ }
63
+ catch {
64
+ try {
65
+ await restore()
66
+ }
67
+ catch (rollbackErr) {
68
+ console.error('[prunelle/auth] failed to roll back unverified signup update:', rollbackErr)
69
+ }
70
+ return false
71
+ }
72
+ }
73
+
74
+ export interface AuthRoutesDeps<TUser extends AuthUser = AuthUser> {
75
+ authRoute: AuthRouteRegistrar
76
+ limits: AuthLimits
77
+ store: AuthStore<TUser>
78
+ sessions: SessionManager<TUser>
79
+ totp: TotpManager
80
+ twoFactorRedirect: string
81
+ minPasswordLength: number
82
+ maxPasswordLength: number
83
+ messages: AuthFormMessages
84
+ defaultRedirect: string
85
+ requireEmailVerification: boolean
86
+ hasMailTransport: boolean
87
+ mailedLinkOrigin: (url: URL) => string | undefined
88
+ createUser: (input: CreateUserInput<TUser>) => Promise<PublicUser<TUser>>
89
+ insertUser: (fields: Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>) => Promise<TUser>
90
+ claimUnverified: (user: TUser) => Promise<TUser>
91
+ issueLink: (kind: 'magic-link' | 'verify-email', userId: string | undefined, email: string, origin: string | undefined, redirectTo: string | undefined, background?: MailInBackground) => Promise<string>
92
+ consumeLink: (kind: 'magic-link' | 'verify-email', rawToken: string) => Promise<{ email: string, user: TUser | undefined } | undefined>
93
+ sendMagicLink: (email: string, origin: string, redirectTo?: string) => Promise<string>
94
+ }
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
+
160
+ export function registerAuthRoutes<TUser extends AuthUser = AuthUser>(deps: AuthRoutesDeps<TUser>): void {
161
+ const {
162
+ authRoute,
163
+ limits,
164
+ store,
165
+ sessions,
166
+ totp,
167
+ twoFactorRedirect,
168
+ minPasswordLength,
169
+ maxPasswordLength,
170
+ messages,
171
+ defaultRedirect,
172
+ requireEmailVerification,
173
+ mailedLinkOrigin,
174
+ createUser,
175
+ insertUser,
176
+ claimUnverified,
177
+ consumeLink,
178
+ sendMagicLink,
179
+ } = deps
180
+
181
+ // GET on a mailed link: the token stays unused until the page's button posts it, and the POST checks the redirect.
182
+ function confirmLinkRoute(kind: 'magic-link' | 'verify-email', path: string, limit: string): void {
183
+ authRoute('GET', path, { limit }, (ctx) => {
184
+ const token = ctx.url.searchParams.get('token') ?? ''
185
+ if (!token)
186
+ return fail(ctx, 400, 'Missing token')
187
+ return linkConfirmPage(LINK_PAGES[kind], { token, redirect: ctx.url.searchParams.get('redirect') ?? '' })
188
+ })
189
+ }
190
+
191
+ // POST from the confirm page (form) or a client (JSON): consumes the token, then `signIn` picks the user to open a session for.
192
+ function consumeLinkRoute(kind: 'magic-link' | 'verify-email', path: string, limit: string, invalid: string, signIn: (consumed: { email: string, user: TUser | undefined }) => Promise<TUser | undefined>): void {
193
+ authRoute('POST', path, { limit, readBody: true }, async (ctx, body) => {
194
+ const rawToken = body.token ?? ctx.url.searchParams.get('token') ?? ''
195
+ const redirectTarget = safeRedirect(body.redirect ?? body.next ?? ctx.url.searchParams.get('redirect'), defaultRedirect)
196
+ if (!rawToken)
197
+ return fail(ctx, 400, 'Missing token')
198
+
199
+ const consumed = await consumeLink(kind, rawToken)
200
+ const userRecord = consumed && await signIn(consumed)
201
+ if (!userRecord)
202
+ return fail(ctx, 400, invalid)
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
+
208
+ const pub = toPublicUser(userRecord)
209
+ await sessions.createSessionForUser(userRecord.id, ctx, pub)
210
+ if (wantsJson(ctx.request))
211
+ return ctx.json({ ok: true, user: pub }, { status: 200 })
212
+ return ctx.redirect(redirectTarget, 303)
213
+ })
214
+ }
215
+
216
+ authRoute('GET', '/session', {}, async (ctx) => {
217
+ const resolved = await sessions.resolve(ctx)
218
+ return ctx.json({
219
+ user: resolved?.user ?? null,
220
+ session: resolved ? { id: resolved.session.id, expiresAt: resolved.session.expiresAt } : null,
221
+ })
222
+ })
223
+
224
+ authRoute('POST', '/signup', { limit: 'signup', readBody: true }, async (ctx, body) => {
225
+ const email = normalizeEmail(body.email ?? '')
226
+ const password = body.password ?? ''
227
+ const name = body.name?.trim() || undefined
228
+ const redirectTarget = safeRedirect(body.redirect ?? body.next, defaultRedirect)
229
+
230
+ if (!isValidEmail(email))
231
+ return respondAuthError(ctx, 400, messages['signup.invalid-email'])
232
+ if (password.length < minPasswordLength)
233
+ return respondAuthError(ctx, 400, messages['signup.password-too-short'])
234
+ if (isPasswordTooLong(password, maxPasswordLength))
235
+ return respondAuthError(ctx, 400, messages['signup.password-too-long'])
236
+
237
+ if (requireEmailVerification)
238
+ return signUpPendingVerification(deps, ctx, { email, password, name, redirectTarget })
239
+
240
+ if (await sessions.observeAsync(store.getUserByEmail(email)))
241
+ return respondAuthError(ctx, 409, messages['signup.email-taken'])
242
+
243
+ const user = await createUser({ email, password, name } as CreateUserInput<TUser>)
244
+ await sessions.createSessionForUser(user.id, ctx, user)
245
+
246
+ if (wantsJson(ctx.request))
247
+ return ctx.json({ ok: true, user }, { status: 201 })
248
+ return ctx.redirect(redirectTarget, 303)
249
+ })
250
+
251
+ confirmLinkRoute('verify-email', '/verify-email', 'verify-email')
252
+ consumeLinkRoute('verify-email', '/verify-email', 'verify-email', 'Invalid or expired verification link', async ({ user }) => {
253
+ if (!user)
254
+ return undefined
255
+ if (!user.emailVerified) {
256
+ await sessions.observeAsync(store.deleteUserSessions(user.id))
257
+ await sessions.observeAsync(store.deleteUserOAuthAccounts(user.id))
258
+ }
259
+ return (await sessions.observeAsync(store.updateUser(user.id, { emailVerified: true } as Partial<Omit<TUser, 'id' | 'createdAt'>>))) ?? { ...user, emailVerified: true }
260
+ })
261
+
262
+ authRoute('POST', '/signin', { limit: 'signin', readBody: true }, async (ctx, body) => {
263
+ const email = normalizeEmail(body.email ?? '')
264
+ const password = body.password ?? ''
265
+ const redirectTarget = safeRedirect(body.redirect ?? body.next, defaultRedirect)
266
+
267
+ if (isPasswordTooLong(password, maxPasswordLength))
268
+ return respondAuthError(ctx, 400, messages['signin.password-too-long'])
269
+
270
+ const locked = limits.refuseLockedAccount(ctx, email)
271
+ if (locked)
272
+ return locked
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
+ limits.countFailedSignin(email)
278
+ return respondAuthError(ctx, 401, messages['signin.invalid-credentials'])
279
+ }
280
+
281
+ if (requireEmailVerification && !userRecord.emailVerified)
282
+ return respondAuthError(ctx, 403, messages['signin.email-not-verified'])
283
+
284
+ const twoFactorMethods = await totp.getTwoFactorMethods(userRecord.id)
285
+ if (twoFactorMethods.length > 0)
286
+ return respondTwoFactorChallenge(totp, ctx, userRecord.id, redirectTarget, twoFactorRedirect, twoFactorMethods)
287
+
288
+ const pub = toPublicUser(userRecord)
289
+ await sessions.createSessionForUser(userRecord.id, ctx, pub)
290
+
291
+ if (wantsJson(ctx.request))
292
+ return ctx.json({ ok: true, user: pub }, { status: 200 })
293
+ return ctx.redirect(redirectTarget, 303)
294
+ })
295
+
296
+ authRoute('POST', '/signout', {}, async (ctx) => {
297
+ totp.clearPendingCookie(ctx)
298
+ await sessions.signOut(ctx)
299
+ if (wantsJson(ctx.request))
300
+ return ctx.json({ ok: true })
301
+ return ctx.redirect(safeRedirect(ctx.url.searchParams.get('redirect'), defaultRedirect), 303)
302
+ })
303
+
304
+ authRoute('POST', '/magic-link', { limit: 'magic', readBody: true }, async (ctx, body) => {
305
+ const email = normalizeEmail(body.email ?? '')
306
+ if (!isValidEmail(email))
307
+ return fail(ctx, 400, 'Please enter a valid email address')
308
+
309
+ const linkOrigin = mailedLinkOrigin(ctx.url)
310
+ if (linkOrigin === undefined) {
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`)
312
+ return fail(ctx, 500, 'Sign-in links are not configured')
313
+ }
314
+ const limited = limits.limitMail(ctx, email)
315
+ if (limited)
316
+ return limited
317
+ await sendMagicLink(email, linkOrigin, body.redirect ?? body.next)
318
+ return ctx.json({ ok: true, message: 'If that address can sign in, a link has been sent.' })
319
+ })
320
+
321
+ confirmLinkRoute('magic-link', '/magic-link/verify', 'magic-verify')
322
+ consumeLinkRoute('magic-link', '/magic-link/verify', 'magic-verify', 'Invalid or expired sign-in link', async ({ email, user }) => {
323
+ if (!user)
324
+ return insertUser({ email, emailVerified: true } as Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>)
325
+ return user.emailVerified ? user : claimUnverified(user)
326
+ })
327
+ }
@@ -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
+ }