|
| 1 | +// The rules every request through an app's own address must pass before the development proxy acts |
| 2 | +// on it (gateway.js): which hosts it answers, which origins count as the app's own, where a sign-in |
| 3 | +// may return to, and which paths may go to another local server. |
| 4 | +import { isIP } from 'node:net'; |
| 5 | + |
| 6 | +import { SYNTAX_AUTH_LOCAL_PORT } from './container.js'; |
| 7 | + |
| 8 | +/** Every path the development proxy answers itself starts with this. */ |
| 9 | +export const MOUNT_PATH = '/__syntax_auth'; |
| 10 | +/** Lists the extra browser-facing origins of this dev server, like `https://lab.example.dev`. */ |
| 11 | +export const PUBLIC_ORIGINS_VARIABLE = 'SYNTAX_AUTH_PUBLIC_ORIGINS'; |
| 12 | +const MAX_RETURN_LENGTH = 2_048; |
| 13 | + |
| 14 | +/** |
| 15 | + * Whether text has a space or a control character (C0, DEL, or C1), which browsers strip from URLs. |
| 16 | + * @param {string} text |
| 17 | + */ |
| 18 | +export function has_space_or_control(text) { |
| 19 | + return [...text].some((char) => { |
| 20 | + const code = char.codePointAt(0) ?? 0; |
| 21 | + return code <= 0x20 || (code >= 0x7f && code <= 0x9f); |
| 22 | + }); |
| 23 | +} |
| 24 | + |
| 25 | +/** |
| 26 | + * The canonical form of a browser-facing origin (`http:` or `https:`, no credentials, path, query, |
| 27 | + * or fragment; a trailing "/" is allowed), or null. |
| 28 | + * @param {unknown} value |
| 29 | + */ |
| 30 | +export function canonical_origin(value) { |
| 31 | + if (typeof value !== 'string' || has_space_or_control(value) || value.includes('\\')) return null; |
| 32 | + try { |
| 33 | + const url = new URL(value); |
| 34 | + if (url.protocol !== 'http:' && url.protocol !== 'https:') return null; |
| 35 | + if (url.username || url.password || url.search || url.hash || url.pathname !== '/') return null; |
| 36 | + if (!/^(?:\[[0-9a-f:.]+\]|[a-z0-9._-]+)$/.test(url.hostname)) return null; |
| 37 | + const given = value.toLowerCase(); |
| 38 | + if (given !== url.origin && given !== `${url.origin}/`) return null; |
| 39 | + return url.origin; |
| 40 | + } catch { |
| 41 | + return null; |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +/** |
| 46 | + * The plugin's `public_origins` option and the SYNTAX_AUTH_PUBLIC_ORIGINS variable (separated by |
| 47 | + * commas or spaces), as canonical origins. A value that isn't an origin stops the dev server. |
| 48 | + * @param {unknown} option |
| 49 | + * @param {NodeJS.ProcessEnv} env |
| 50 | + * @returns {string[]} |
| 51 | + */ |
| 52 | +export function read_public_origins(option, env) { |
| 53 | + if (option !== undefined && !Array.isArray(option)) { |
| 54 | + throw new Error('syntax_auth(): public_origins must be an array of origins.'); |
| 55 | + } |
| 56 | + const from_env = (env[PUBLIC_ORIGINS_VARIABLE] ?? '').split(/[\s,]+/).filter(Boolean); |
| 57 | + /** @type {string[]} */ |
| 58 | + const origins = []; |
| 59 | + for (const [value, source] of [ |
| 60 | + ...(option ?? []).map((value) => [value, 'syntax_auth(): public_origins']), |
| 61 | + ...from_env.map((value) => [value, PUBLIC_ORIGINS_VARIABLE]) |
| 62 | + ]) { |
| 63 | + const origin = canonical_origin(value); |
| 64 | + if (!origin) { |
| 65 | + throw new Error( |
| 66 | + `${source} needs origins like https://lab.example.dev or http://box.example.ts.net:5173 (http or https, no path or credentials), not ${JSON.stringify(value)}.` |
| 67 | + ); |
| 68 | + } |
| 69 | + if (!origins.includes(origin)) origins.push(origin); |
| 70 | + } |
| 71 | + return origins; |
| 72 | +} |
| 73 | + |
| 74 | +/** |
| 75 | + * The parts of a Host header, or null when it is anything but a host and an optional port. |
| 76 | + * @param {unknown} host_header |
| 77 | + * @returns {{ host: string, hostname: string } | null} |
| 78 | + */ |
| 79 | +export function parse_host(host_header) { |
| 80 | + if (typeof host_header !== 'string' || host_header.length === 0 || host_header.length > 255) { |
| 81 | + return null; |
| 82 | + } |
| 83 | + if (!/^(?:\[[0-9A-Fa-f:.]+\]|[A-Za-z0-9._-]+)(?::\d{1,5})?$/.test(host_header)) return null; |
| 84 | + try { |
| 85 | + const url = new URL(`http://${host_header}`); |
| 86 | + return { host: url.host, hostname: url.hostname }; |
| 87 | + } catch { |
| 88 | + return null; |
| 89 | + } |
| 90 | +} |
| 91 | + |
| 92 | +/** |
| 93 | + * Vite's own host rule, applied again here so the proxy answers no other host even where Vite |
| 94 | + * doesn't check (an `https` dev server, or `allowedHosts: true`): IP addresses, `localhost` and |
| 95 | + * `*.localhost`, the entries of `server.allowedHosts` (a leading "." allows a domain and every name |
| 96 | + * under it), and the hosts of the public origins. |
| 97 | + * @param {unknown} host_header |
| 98 | + * @param {readonly string[]} allowed_hosts |
| 99 | + */ |
| 100 | +export function is_allowed_host(host_header, allowed_hosts) { |
| 101 | + const parsed = parse_host(host_header); |
| 102 | + if (!parsed) return false; |
| 103 | + const { hostname } = parsed; |
| 104 | + if (hostname.startsWith('[') || isIP(hostname) === 4) return true; |
| 105 | + if (hostname === 'localhost' || hostname.endsWith('.localhost')) return true; |
| 106 | + return allowed_hosts.some((entry) => { |
| 107 | + const allowed = entry.toLowerCase(); |
| 108 | + if (allowed === hostname) return true; |
| 109 | + return allowed.startsWith('.') && (allowed.slice(1) === hostname || hostname.endsWith(allowed)); |
| 110 | + }); |
| 111 | +} |
| 112 | + |
| 113 | +/** |
| 114 | + * The origins a browser on this request's host may have: the one this connection proves (https on |
| 115 | + * a TLS connection, otherwise http), plus each configured public origin with this very host. A |
| 116 | + * forwarded-protocol header is never read: a TLS proxy in front names its https origin in |
| 117 | + * SYNTAX_AUTH_PUBLIC_ORIGINS instead. |
| 118 | + * @param {string} host_header an allowed Host header |
| 119 | + * @param {{ encrypted: boolean, public_origins: readonly string[] }} options |
| 120 | + */ |
| 121 | +export function accepted_origins(host_header, { encrypted, public_origins }) { |
| 122 | + const own = new URL(`${encrypted ? 'https' : 'http'}://${host_header}`).origin; |
| 123 | + const configured = public_origins.filter( |
| 124 | + (origin) => new URL(`${new URL(origin).protocol}//${host_header}`).origin === origin |
| 125 | + ); |
| 126 | + return [...new Set([own, ...configured])]; |
| 127 | +} |
| 128 | + |
| 129 | +/** |
| 130 | + * The browser's origin when a state-changing request comes from this app's own pages, or why not. |
| 131 | + * Browsers send Origin on every POST and WebSocket upgrade, so a missing one is refused. |
| 132 | + * @param {import('node:http').IncomingHttpHeaders} headers |
| 133 | + * @param {readonly string[]} accepted |
| 134 | + * @returns {{ origin: string } | { problem: string }} |
| 135 | + */ |
| 136 | +export function check_origin(headers, accepted) { |
| 137 | + const origin = headers.origin; |
| 138 | + if (!origin || origin === 'null') { |
| 139 | + return { problem: 'The request has no Origin header, so it may not come from this app.' }; |
| 140 | + } |
| 141 | + if (!accepted.includes(origin)) { |
| 142 | + const https_hint = origin.startsWith('https://') |
| 143 | + ? ` If a TLS proxy serves this app at ${origin}, add that origin to ${PUBLIC_ORIGINS_VARIABLE} and restart dev.` |
| 144 | + : ''; |
| 145 | + return { |
| 146 | + problem: `The request came from ${JSON.stringify(origin)}, but this address is ${accepted.join(' or ')}.${https_hint}` |
| 147 | + }; |
| 148 | + } |
| 149 | + const site = headers['sec-fetch-site']; |
| 150 | + if (site && site !== 'same-origin') { |
| 151 | + return { problem: `The browser marked this request ${JSON.stringify(site)}, not same-origin.` }; |
| 152 | + } |
| 153 | + return { origin }; |
| 154 | +} |
| 155 | + |
| 156 | +/** |
| 157 | + * Where a sign-in or sign-out may send the browser: a path on this same app, kept with its query |
| 158 | + * and fragment. Anything else (an absolute or protocol-relative URL, a backslash, a space or control |
| 159 | + * character browsers would strip, a path that normalizes to "//", or one of the proxy's own paths) |
| 160 | + * becomes "/". |
| 161 | + * @param {unknown} value |
| 162 | + */ |
| 163 | +export function safe_return_path(value) { |
| 164 | + if (typeof value !== 'string' || value.length === 0 || value.length > MAX_RETURN_LENGTH) |
| 165 | + return '/'; |
| 166 | + if (!value.startsWith('/') || value.startsWith('//')) return '/'; |
| 167 | + if (value.includes('\\') || has_space_or_control(value)) return '/'; |
| 168 | + const base = 'http://return.invalid'; |
| 169 | + try { |
| 170 | + const url = new URL(value, base); |
| 171 | + const path = `${url.pathname}${url.search}${url.hash}`; |
| 172 | + if (url.origin !== base || path.startsWith('//')) return '/'; |
| 173 | + if (url.pathname === MOUNT_PATH || url.pathname.startsWith(`${MOUNT_PATH}/`)) return '/'; |
| 174 | + return path; |
| 175 | + } catch { |
| 176 | + return '/'; |
| 177 | + } |
| 178 | +} |
| 179 | + |
| 180 | +/** |
| 181 | + * @typedef {{ path: string, port: number }} RouteOption |
| 182 | + * @typedef {{ path: string, port: number, prefix: string | null }} Route |
| 183 | + * `prefix` (ending in "/") for a `/*` route, null for an exact path. |
| 184 | + */ |
| 185 | + |
| 186 | +const ROUTE_PATTERN = |
| 187 | + /^\/(?:[A-Za-z0-9_~-][A-Za-z0-9._~-]*\/)*(?:[A-Za-z0-9_~-][A-Za-z0-9._~-]*|\*)$/; |
| 188 | + |
| 189 | +/** |
| 190 | + * The plugin's `routes` option, checked: each is an exact path or a `/prefix/*`, with plain |
| 191 | + * segments (no "." or ".." segment, no encoded characters), and a port on this computer other than |
| 192 | + * local Syntax Auth's own. A wrong route stops the dev server. |
| 193 | + * @param {unknown} routes |
| 194 | + * @returns {Route[]} |
| 195 | + */ |
| 196 | +export function parse_routes(routes) { |
| 197 | + if (routes === undefined) return []; |
| 198 | + if (!Array.isArray(routes)) { |
| 199 | + throw new Error('syntax_auth(): routes must be an array of { path, port }.'); |
| 200 | + } |
| 201 | + return routes.map((route) => { |
| 202 | + const path = route?.path; |
| 203 | + const port = route?.port; |
| 204 | + if ( |
| 205 | + typeof path !== 'string' || |
| 206 | + !ROUTE_PATTERN.test(path) || |
| 207 | + path === '/*' || |
| 208 | + path === MOUNT_PATH || |
| 209 | + path.startsWith(`${MOUNT_PATH}/`) |
| 210 | + ) { |
| 211 | + throw new Error( |
| 212 | + `syntax_auth(): each route needs a path like '/parties/*' or '/exact/path' (plain segments, no "." or "..", not "/*" or under ${MOUNT_PATH}), not ${JSON.stringify(route)}.` |
| 213 | + ); |
| 214 | + } |
| 215 | + if (!Number.isInteger(port) || port <= 0 || port >= 65_536) { |
| 216 | + throw new Error( |
| 217 | + `syntax_auth(): each route needs a port number, not ${JSON.stringify(route)}.` |
| 218 | + ); |
| 219 | + } |
| 220 | + if (port === SYNTAX_AUTH_LOCAL_PORT) { |
| 221 | + throw new Error( |
| 222 | + `syntax_auth(): a route can't send paths to local Syntax Auth's port ${SYNTAX_AUTH_LOCAL_PORT}; its sign-in and sign-out already answer at ${MOUNT_PATH}/.` |
| 223 | + ); |
| 224 | + } |
| 225 | + return { path, port, prefix: path.endsWith('/*') ? path.slice(0, -1) : null }; |
| 226 | + }); |
| 227 | +} |
| 228 | + |
| 229 | +/** |
| 230 | + * The path and query of an origin-form request target ("/path?query"), or null for any other form, |
| 231 | + * such as an absolute URL that names its own destination, or "//host". |
| 232 | + * @param {unknown} target |
| 233 | + */ |
| 234 | +export function split_target(target) { |
| 235 | + if (typeof target !== 'string' || !target.startsWith('/') || target.startsWith('//')) return null; |
| 236 | + const query_start = target.indexOf('?'); |
| 237 | + return query_start === -1 |
| 238 | + ? { path: target, query: '' } |
| 239 | + : { path: target.slice(0, query_start), query: target.slice(query_start) }; |
| 240 | +} |
| 241 | + |
| 242 | +/** |
| 243 | + * @param {string} path the raw path of the request target |
| 244 | + * @param {readonly Route[]} routes |
| 245 | + */ |
| 246 | +export function find_route(path, routes) { |
| 247 | + return ( |
| 248 | + routes.find((route) => (route.prefix ? path.startsWith(route.prefix) : path === route.path)) ?? |
| 249 | + null |
| 250 | + ); |
| 251 | +} |
| 252 | + |
| 253 | +/** |
| 254 | + * Whether a routed path stays inside its route on any server: no "." or ".." segment, no empty |
| 255 | + * segment, no backslash, no encoded dot, slash, or backslash, and no space or control character. |
| 256 | + * @param {string} path |
| 257 | + */ |
| 258 | +export function is_clean_path(path) { |
| 259 | + if (path.includes('\\') || path.includes('//') || has_space_or_control(path)) return false; |
| 260 | + if (/%(?:2e|2f|5c)/i.test(path)) return false; |
| 261 | + return !path.split('/').some((segment) => segment === '.' || segment === '..'); |
| 262 | +} |
0 commit comments