@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/http.ts ADDED
@@ -0,0 +1,214 @@
1
+ // Request parsing and client-address helpers shared by the auth routes.
2
+
3
+ import type { PluginRouteOptions, ServerPluginAPI } from 'prunelle/config'
4
+ import type { CookieOptions, RateLimiter, RequestContext, TrustProxy } from 'prunelle/server'
5
+ import type { AuthFormMessage } from './form-messages'
6
+ import type { RateLimitOptions } from './index'
7
+ import { getClientIp, rateLimitAddress, readStringFields, safeRedirect, wantsJson } from 'prunelle/server'
8
+ import { normalizeEmail } from './store'
9
+
10
+ /** Every auth cookie: HttpOnly and Lax, and essential, since no one can sign in without it. */
11
+ export function authCookie(secure: boolean, maxAgeSeconds: number): CookieOptions {
12
+ return { path: '/', httpOnly: true, sameSite: 'lax', secure, maxAge: maxAgeSeconds, category: 'essential' }
13
+ }
14
+
15
+ export function fail(ctx: RequestContext, status: number, error: string): Response {
16
+ return ctx.json({ ok: false, error }, { status })
17
+ }
18
+
19
+ /** A JSON caller gets the error as JSON; a form goes back to its page with the error's code, which `auth.formMessage(url)` reads. */
20
+ export function respondAuthError(ctx: RequestContext, status: number, message: AuthFormMessage): Response {
21
+ const back = formPagePath(ctx, 'error', message.code)
22
+ if (back === undefined)
23
+ return ctx.json({ ok: false, error: message.text, code: message.code }, { status })
24
+ return ctx.redirect(back, 303)
25
+ }
26
+
27
+ /** The same-origin page a form was posted from (its Referer), with `param` set to `code` and any earlier error or notice dropped; `undefined` for a JSON caller or a page that cannot be told. */
28
+ export function formPagePath(ctx: RequestContext, param: 'error' | 'notice', code: string): string | undefined {
29
+ const referer = ctx.request.headers.get('referer')
30
+ if (wantsJson(ctx.request) || referer === null)
31
+ return undefined
32
+ const from = URL.parse(referer)
33
+ if (from === null || from.origin !== (ctx.request.headers.get('origin') ?? ctx.url.origin))
34
+ return undefined
35
+ from.searchParams.delete('error')
36
+ from.searchParams.delete('notice')
37
+ from.searchParams.set(param, code)
38
+ const path = safeRedirect(`${from.pathname}${from.search}`, '')
39
+ return path === '' ? undefined : path
40
+ }
41
+
42
+ const ATTR_SPECIALS_RE = /[&"<>]/g
43
+ const ATTR_ENTITIES: Record<string, string> = { '&': '&amp;', '"': '&quot;', '<': '&lt;', '>': '&gt;' }
44
+
45
+ export function escapeHtml(value: string): string {
46
+ return value.replace(ATTR_SPECIALS_RE, c => ATTR_ENTITIES[c]!)
47
+ }
48
+
49
+ /** The page a mailed link opens: one button posting the token back, so a mail scanner's GET leaves the link unused. No script or style, so any CSP lets it through. */
50
+ export function linkConfirmPage(copy: { title: string, button: string }, fields: Record<string, string>): Response {
51
+ let inputs = ''
52
+ for (const [name, value] of Object.entries(fields))
53
+ inputs += `<input type="hidden" name="${name}" value="${escapeHtml(value)}">`
54
+ const html = `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="robots" content="noindex"><meta name="referrer" content="no-referrer"><title>${copy.title}</title></head><body><main><h1>${copy.title}</h1><form method="post">${inputs}<button type="submit">${copy.button}</button></form></main></body></html>`
55
+ return new Response(html, { headers: { 'content-type': 'text/html; charset=utf-8' } })
56
+ }
57
+
58
+ export function withNoStore(res: Response): Response {
59
+ if (res.headers.has('cache-control'))
60
+ return res
61
+ try {
62
+ res.headers.set('cache-control', 'no-store')
63
+ return res
64
+ }
65
+ catch {
66
+ const headers = new Headers(res.headers)
67
+ headers.set('cache-control', 'no-store')
68
+ return new Response(res.body, { status: res.status, statusText: res.statusText, headers })
69
+ }
70
+ }
71
+
72
+ export async function parseBody(ctx: RequestContext): Promise<Record<string, string> | Response> {
73
+ try {
74
+ return await readStringFields(ctx.request)
75
+ }
76
+ catch {
77
+ return fail(ctx, 400, 'Invalid request body')
78
+ }
79
+ }
80
+
81
+ export async function parseJsonBody(ctx: RequestContext): Promise<Record<string, unknown> | Response> {
82
+ try {
83
+ const raw = await ctx.request.text()
84
+ if (!raw.trim())
85
+ return {}
86
+ const parsed: unknown = JSON.parse(raw)
87
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
88
+ return fail(ctx, 400, 'Invalid JSON body')
89
+ return parsed as Record<string, unknown>
90
+ }
91
+ catch {
92
+ return fail(ctx, 400, 'Invalid JSON body')
93
+ }
94
+ }
95
+
96
+ export type AuthRouteRegistrar = (
97
+ method: 'GET' | 'POST',
98
+ path: string,
99
+ routeCfg: { limit?: string, readBody?: boolean },
100
+ handler: (ctx: RequestContext, body: Record<string, string>) => Response | Promise<Response>,
101
+ ) => void
102
+
103
+ export function createAuthRouteRegistrar(
104
+ api: ServerPluginAPI,
105
+ basePath: string,
106
+ authRouteOpts: PluginRouteOptions,
107
+ limits: AuthLimits,
108
+ ): AuthRouteRegistrar {
109
+ return (method, path, routeCfg, handler) => {
110
+ api.route(method, `${basePath}${path}`, async (ctx) => {
111
+ if (routeCfg.limit !== undefined) {
112
+ const limited = limits.limitIp(ctx, routeCfg.limit)
113
+ if (limited)
114
+ return withNoStore(limited)
115
+ }
116
+ let body: Record<string, string> = {}
117
+ if (routeCfg.readBody) {
118
+ const parsed = await parseBody(ctx)
119
+ if (parsed instanceof Response)
120
+ return withNoStore(parsed)
121
+ body = parsed
122
+ }
123
+ return withNoStore(await handler(ctx, body))
124
+ }, method === 'POST' ? authRouteOpts : undefined)
125
+ }
126
+ }
127
+
128
+ // Control characters (C0/DEL), whitespace, and the characters that split or wrap an address list.
129
+ const EMAIL_FORBIDDEN_RE = /[\u0000-\u001F\u007F\s,;<>]/
130
+
131
+ export function isValidEmail(email: string): boolean {
132
+ const e = email.trim()
133
+ const at = e.indexOf('@')
134
+ return at > 0 && at === e.lastIndexOf('@') && e.indexOf('.', at + 2) > at + 1 && !EMAIL_FORBIDDEN_RE.test(e)
135
+ }
136
+
137
+ export function resolveClientIp(ctx: RequestContext, trustProxy: TrustProxy): string {
138
+ return ctx.ip?.trim() || getClientIp(ctx.request, trustProxy) || 'unknown'
139
+ }
140
+
141
+ export interface AuthLimits {
142
+ /** The 429 to answer when this address is past the limit of `scope`, else `undefined`. */
143
+ limitIp: (ctx: RequestContext, scope: string) => Response | undefined
144
+ /** The same per normalized email across addresses and mail routes, at the mail limit; nothing is counted without an email. */
145
+ limitMail: (ctx: RequestContext, email: string | undefined) => Response | undefined
146
+ /** The 429 to answer, before the password is checked, when this account is past its wrong passwords across addresses. */
147
+ refuseLockedAccount: (ctx: RequestContext, email: string) => Response | undefined
148
+ /** Counts a wrong password against the account. */
149
+ countFailedSignin: (email: string) => void
150
+ }
151
+
152
+ export interface AuthLimiters {
153
+ attempts: RateLimiter
154
+ mails: RateLimiter
155
+ failures: RateLimiter
156
+ }
157
+
158
+ export function createAuthLimiters(api: ServerPluginAPI, rateLimit: RateLimitOptions | false | undefined): AuthLimiters | undefined {
159
+ if (rateLimit === false)
160
+ return undefined
161
+ return {
162
+ attempts: api.rateLimiter({ max: rateLimit?.max ?? 15, windowMs: rateLimit?.windowMs ?? 60_000 }),
163
+ mails: api.rateLimiter({ max: rateLimit?.mailsPerAddress ?? 3, windowMs: 600_000 }),
164
+ failures: api.rateLimiter({ max: rateLimit?.failuresPerAccount ?? 100, windowMs: 3_600_000 }),
165
+ }
166
+ }
167
+
168
+ function tooMany(ctx: RequestContext, retryAfter: number): Response | undefined {
169
+ if (retryAfter === 0)
170
+ return undefined
171
+ const refused = fail(ctx, 429, 'Too many requests')
172
+ refused.headers.set('retry-after', String(retryAfter))
173
+ return refused
174
+ }
175
+
176
+ export function authLimits(limiters: AuthLimiters | undefined, getTrustProxy: () => TrustProxy): AuthLimits {
177
+ return {
178
+ limitIp: (ctx, scope) => tooMany(ctx, limiters?.attempts.hit(`${scope}:ip:${rateLimitAddress(resolveClientIp(ctx, getTrustProxy()))}`) ?? 0),
179
+ limitMail(ctx, email) {
180
+ const normalized = normalizeEmail(email ?? '')
181
+ return normalized ? tooMany(ctx, limiters?.mails.hit(normalized) ?? 0) : undefined
182
+ },
183
+ refuseLockedAccount: (ctx, email) => tooMany(ctx, email ? limiters?.failures.peek(`signin:${email}`) ?? 0 : 0),
184
+ countFailedSignin(email) {
185
+ if (email)
186
+ limiters?.failures.hit(`signin:${email}`)
187
+ },
188
+ }
189
+ }
190
+
191
+ export function formatSessionIp(ip: string, mode: boolean | 'truncate'): string | undefined {
192
+ if (mode === false || ip === 'unknown')
193
+ return undefined
194
+ if (mode === true)
195
+ return ip
196
+ // Truncate mode: IPv4 -> /24, IPv4-mapped IPv6 -> /120, IPv6 -> /48
197
+ const v4 = /^(\d{1,3}\.\d{1,3}\.\d{1,3})\.\d{1,3}$/.exec(ip)
198
+ if (v4)
199
+ return `${v4[1]}.0`
200
+ const v4Mapped = /^(::ffff:\d{1,3}\.\d{1,3}\.\d{1,3})\.\d{1,3}$/i.exec(ip)
201
+ if (v4Mapped)
202
+ return `${v4Mapped[1]}.0`
203
+ if (ip.includes(':')) {
204
+ const [head = '', tail = ''] = ip.split('::')
205
+ const headParts = head ? head.split(':').filter(Boolean) : []
206
+ const tailParts = ip.includes('::') && tail ? tail.split(':').filter(Boolean) : []
207
+ const full = ip.includes('::')
208
+ ? [...headParts, ...Array.from({ length: Math.max(0, 8 - headParts.length - tailParts.length) }, () => '0'), ...tailParts]
209
+ : headParts
210
+ if (full.length >= 3)
211
+ return `${full.slice(0, 3).join(':')}::`
212
+ }
213
+ return undefined
214
+ }