From 7e553812018a7ff8fe4f63da43fba1a86e5e60a7 Mon Sep 17 00:00:00 2001 From: Brenley Dueck Date: Wed, 25 Nov 2026 18:14:48 -0600 Subject: [PATCH 1/2] feat(node-entry): take the request scheme from a trusted proxy --- .changeset/node-entry-trust-proxy.md | 11 +++++ README.md | 25 +++++++++++- src/http.test.ts | 61 +++++++++++++++++++++++++++- src/http.ts | 47 +++++++++++++++++++-- src/node-entry/index.ts | 21 ++++++++-- 5 files changed, 156 insertions(+), 9 deletions(-) create mode 100644 .changeset/node-entry-trust-proxy.md diff --git a/.changeset/node-entry-trust-proxy.md b/.changeset/node-entry-trust-proxy.md new file mode 100644 index 00000000..9e80a368 --- /dev/null +++ b/.changeset/node-entry-trust-proxy.md @@ -0,0 +1,11 @@ +--- +'@solidjs/vite-plugin': patch +--- + +The emitted `node.js` entry can take the request scheme from a trusted +proxy's `X-Forwarded-Proto`. Set `TRUST_PROXY` (`loopback`, a comma-separated +list of peer addresses, or `true`) or pass `trustProxy` to `createListener` or +`serve`. Behind a TLS-terminating proxy, `request.url` was always `http://`, +so the server-function same-origin check refused every protected call from +browsers that send no `Sec-Fetch-Site`, such as Safari before 16.4 +(solidjs/solid#5196). diff --git a/README.md b/README.md index cb2a012d..fa6093f7 100644 --- a/README.md +++ b/README.md @@ -348,7 +348,7 @@ Solid options accepted by `handleRequest`'s second parameter. command is: ```sh -node dist/server/node.js # PORT (default 3000), HOST +node dist/server/node.js # PORT (default 3000), HOST, TRUST_PROXY ``` The entry serves `dist/client` statically — files under @@ -396,7 +396,20 @@ app.listen(process.env.PORT || 3000); mode, the `index.html` history fallback — the framework owns both. `createListener({ event: (req) => ({ ... }) })` merges extra fields over `{ nativeEvent: req }` into the request event. `serve({ port, host, static, -event })` takes the same two options on top of the listen address. +event, trustProxy })` takes the same options on top of the listen address. + +Behind a TLS-terminating proxy the entry's socket is plain HTTP, so +`request.url` starts with `http://`, and application code that compares +URLs with the public `https://` origin goes wrong. One example is the +server-function same-origin check for browsers that send no +`Sec-Fetch-Site`, such as Safari before 16.4. Set `TRUST_PROXY` (or +`createListener({ trustProxy })`) to take the scheme from the +`X-Forwarded-Proto` value that the nearest proxy sets: `loopback` trusts a +proxy on the same host, a comma-separated list trusts those peer +addresses, and `true` trusts any peer. Any client can send that header, so +trust only a proxy you control, and have it set `X-Forwarded-Proto` +(nginx: `proxy_set_header X-Forwarded-Proto $scheme;`). Only the scheme is +taken from the proxy; the host is still the `Host` header. `node.js` is an emitted asset, not a second build input: `server.js` and its `handleRequest` / `{ fetch }` contracts are unchanged. With @@ -1004,6 +1017,14 @@ configureServerFunctionsServer({ Set `csrf: false` only when another trusted layer protects the endpoint. +The check compares `Origin` with the origin of `request.url`. Behind a +TLS-terminating proxy that origin is `http://` unless the server takes the +scheme from the proxy, so browsers that send no `Sec-Fetch-Site` (Safari +before 16.4) get a `403` on every protected call. With the emitted +`node.js` entry, set [`TRUST_PROXY`](#optionsstart); with another server, +build `request.url` from a trusted `X-Forwarded-Proto` (srvx: +`trustProxy`), or list the public origin in `csrf.origin`. + Custom serialization (extra seroval plugins for class instances such as a `Money` or an `ObjectId`) is configured the same way, once per side. Set the server codec in the `serverSetup` module and the client codec in diff --git a/src/http.test.ts b/src/http.test.ts index b64b3244..da22e7f3 100644 --- a/src/http.test.ts +++ b/src/http.test.ts @@ -1,6 +1,6 @@ import type { IncomingMessage } from 'node:http'; import { describe, expect, it } from 'vitest'; -import { parseRequestTarget, webRequestFromNode } from './http.js'; +import { parseRequestTarget, parseTrustProxy, webRequestFromNode } from './http.js'; function nodeRequest(url: string): IncomingMessage { return { url, method: 'GET', headers: { host: 'localhost:3000' }, socket: {} } as IncomingMessage; @@ -30,3 +30,62 @@ describe('request URLs', () => { expect(webRequestFromNode(nodeRequest('/a/b?c=1')).url).toBe('http://localhost:3000/a/b?c=1'); }); }); + +function proxiedRequest(remoteAddress: string, proto?: string): IncomingMessage { + const headers: Record = { host: 'example.com' }; + if (proto !== undefined) headers['x-forwarded-proto'] = proto; + return { url: '/_server', method: 'GET', headers, socket: { remoteAddress } } as IncomingMessage; +} + +describe('trustProxy', () => { + it('ignores X-Forwarded-Proto by default', () => { + expect(webRequestFromNode(proxiedRequest('127.0.0.1', 'https')).url).toBe( + 'http://example.com/_server', + ); + }); + + it('takes the scheme from a trusted peer', () => { + const url = (address: string, trust: Parameters[3]) => + webRequestFromNode(proxiedRequest(address, 'https'), undefined, undefined, trust).url; + expect(url('203.0.113.9', true)).toBe('https://example.com/_server'); + expect(url('127.0.0.1', 'loopback')).toBe('https://example.com/_server'); + expect(url('::ffff:127.0.0.1', 'loopback')).toBe('https://example.com/_server'); + expect(url('::1', 'loopback')).toBe('https://example.com/_server'); + expect(url('10.0.0.2', ['10.0.0.2'])).toBe('https://example.com/_server'); + }); + + it('ignores the header from a peer it does not trust', () => { + const url = (address: string, trust: Parameters[3]) => + webRequestFromNode(proxiedRequest(address, 'https'), undefined, undefined, trust).url; + expect(url('203.0.113.9', 'loopback')).toBe('http://example.com/_server'); + expect(url('10.0.0.3', ['10.0.0.2'])).toBe('http://example.com/_server'); + }); + + it('uses the nearest proxy value and only http or https', () => { + const url = (proto: string) => + webRequestFromNode(proxiedRequest('127.0.0.1', proto), undefined, undefined, true).url; + expect(url('http, https')).toBe('https://example.com/_server'); + expect(url('https, http')).toBe('http://example.com/_server'); + expect(url(' HTTPS ')).toBe('https://example.com/_server'); + expect(url('ftp')).toBe('http://example.com/_server'); + }); + + it('keeps https on a TLS socket when the header is absent', () => { + const req = proxiedRequest('127.0.0.1'); + (req.socket as { encrypted?: boolean }).encrypted = true; + expect(webRequestFromNode(req, undefined, undefined, true).url).toBe( + 'https://example.com/_server', + ); + }); + + it('parses TRUST_PROXY', () => { + expect(parseTrustProxy(undefined)).toBe(false); + expect(parseTrustProxy('')).toBe(false); + expect(parseTrustProxy('0')).toBe(false); + expect(parseTrustProxy('false')).toBe(false); + expect(parseTrustProxy('1')).toBe(true); + expect(parseTrustProxy('true')).toBe(true); + expect(parseTrustProxy('loopback')).toBe('loopback'); + expect(parseTrustProxy('10.0.0.2, 10.0.0.3')).toEqual(['10.0.0.2', '10.0.0.3']); + }); +}); diff --git a/src/http.ts b/src/http.ts index 7123a025..5cc87c91 100644 --- a/src/http.ts +++ b/src/http.ts @@ -24,13 +24,14 @@ export function webRequestFromNode( req: IncomingMessage, urlPath?: string, res?: ServerResponse, + trustProxy: TrustProxy = false, ): Request { // TLS sockets (https and h2) expose `encrypted`; a Request whose url says // http: on a TLS connection breaks secure-cookie logic, absolute // redirects, and origin checks in application code. - const protocol = (req.socket as { encrypted?: boolean } | undefined)?.encrypted - ? 'https' - : 'http'; + const protocol = + forwardedProto(req, trustProxy) ?? + ((req.socket as { encrypted?: boolean } | undefined)?.encrypted ? 'https' : 'http'); // HTTP/2 has no Host header — the authority travels in the `:authority` // pseudo-header instead. const host = req.headers.host ?? (req.headers[':authority'] as string | undefined) ?? 'localhost'; @@ -86,6 +87,46 @@ export function webRequestFromNode( } as RequestInit); } +/** + * Which peers may set the request scheme with `X-Forwarded-Proto`: `true` + * trusts any peer, `'loopback'` a proxy on the same host, and a list the + * peer addresses it names. + */ +export type TrustProxy = boolean | 'loopback' | string[]; + +function normalizeAddress(address: string): string { + return address.startsWith('::ffff:') ? address.slice(7) : address; +} + +function trustsPeer(trustProxy: TrustProxy, address: string | undefined): boolean { + if (trustProxy === true) return true; + if (!trustProxy || !address) return false; + const peer = normalizeAddress(address); + if (trustProxy === 'loopback') return peer === '::1' || peer.startsWith('127.'); + return trustProxy.some((trusted) => normalizeAddress(trusted) === peer); +} + +function forwardedProto(req: IncomingMessage, trustProxy: TrustProxy): string | undefined { + if (!trustsPeer(trustProxy, req.socket?.remoteAddress)) return; + const header = req.headers['x-forwarded-proto']; + if (typeof header !== 'string') return; + // The nearest proxy's value is the last one; earlier ones may come from the client. + const proto = header.split(',').pop()!.trim().toLowerCase(); + return proto === 'https' || proto === 'http' ? proto : undefined; +} + +/** Reads a `TrustProxy` from an env value such as `TRUST_PROXY`. */ +export function parseTrustProxy(value: string | undefined): TrustProxy { + const text = value?.trim() ?? ''; + if (text === '' || text === 'false' || text === '0') return false; + if (text === 'true' || text === '1') return true; + if (text === 'loopback') return 'loopback'; + return text + .split(',') + .map((address) => address.trim()) + .filter(Boolean); +} + export async function sendWebResponse(res: ServerResponse, response: Response): Promise { res.statusCode = response.status; // set-cookie is the one header that must not be comma-joined. diff --git a/src/node-entry/index.ts b/src/node-entry/index.ts index b571113d..bdfdf30f 100644 --- a/src/node-entry/index.ts +++ b/src/node-entry/index.ts @@ -1,7 +1,7 @@ // The Node server for a start-mode build (emitted as dist/server/node.js by // `start.nodeServer`): serves the client build statically and hands every other // request to the built handler in ./server.js. Runtime config is -// environment-only — PORT (default 3000) and HOST. Listens when run +// environment-only — PORT (default 3000), HOST and TRUST_PROXY. Listens when run // directly; `listener`, `createListener` and `serve` are exported for // mounting into an existing http server or framework. import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'; @@ -11,7 +11,13 @@ import path from 'node:path'; import { pipeline } from 'node:stream/promises'; import { fileURLToPath } from 'node:url'; import { handleRequest } from './server.js'; -import { parseRequestTarget, sendWebResponse, webRequestFromNode } from '../http.js'; +import { + parseRequestTarget, + parseTrustProxy, + sendWebResponse, + webRequestFromNode, + type TrustProxy, +} from '../http.js'; import { acceptedEncodings, PRECOMPRESSIBLE_EXTENSIONS } from './encoding.js'; // Baked in at build time by the plugin (the generated header above this @@ -144,6 +150,14 @@ export interface ListenerOptions { static?: boolean; /** Extra request-event fields, merged over `{ nativeEvent: req }`. */ event?: (req: IncomingMessage) => Record; + /** + * Take the request URL's scheme from `X-Forwarded-Proto` when the peer is + * a proxy you trust, so `request.url` is `https:` behind a TLS-terminating + * proxy. `true` trusts any peer, `'loopback'` a proxy on the same host, a + * list the peer addresses it names. Default: the `TRUST_PROXY` env var + * (`true`, `loopback` or comma-separated addresses), else false. + */ + trustProxy?: TrustProxy; } export type Listener = (req: IncomingMessage, res: ServerResponse) => Promise; @@ -152,6 +166,7 @@ export type Listener = (req: IncomingMessage, res: ServerResponse) => Promise Date: Wed, 25 Nov 2026 18:15:59 -0600 Subject: [PATCH 2/2] fix(node-entry): match TRUST_PROXY keywords case-insensitively --- README.md | 5 +++-- src/http.test.ts | 2 ++ src/http.ts | 9 +++++---- src/node-entry/index.ts | 5 +++-- 4 files changed, 13 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index fa6093f7..26611c97 100644 --- a/README.md +++ b/README.md @@ -405,8 +405,9 @@ server-function same-origin check for browsers that send no `Sec-Fetch-Site`, such as Safari before 16.4. Set `TRUST_PROXY` (or `createListener({ trustProxy })`) to take the scheme from the `X-Forwarded-Proto` value that the nearest proxy sets: `loopback` trusts a -proxy on the same host, a comma-separated list trusts those peer -addresses, and `true` trusts any peer. Any client can send that header, so +proxy on the same host, a comma-separated list trusts those exact peer +addresses (no CIDR ranges), and `true` trusts any peer. The exported +`listener` reads `TRUST_PROXY` when `node.js` is imported. Any client can send that header, so trust only a proxy you control, and have it set `X-Forwarded-Proto` (nginx: `proxy_set_header X-Forwarded-Proto $scheme;`). Only the scheme is taken from the proxy; the host is still the `Host` header. diff --git a/src/http.test.ts b/src/http.test.ts index da22e7f3..7ef4b059 100644 --- a/src/http.test.ts +++ b/src/http.test.ts @@ -85,7 +85,9 @@ describe('trustProxy', () => { expect(parseTrustProxy('false')).toBe(false); expect(parseTrustProxy('1')).toBe(true); expect(parseTrustProxy('true')).toBe(true); + expect(parseTrustProxy('TRUE')).toBe(true); expect(parseTrustProxy('loopback')).toBe('loopback'); + expect(parseTrustProxy(' Loopback ')).toBe('loopback'); expect(parseTrustProxy('10.0.0.2, 10.0.0.3')).toEqual(['10.0.0.2', '10.0.0.3']); }); }); diff --git a/src/http.ts b/src/http.ts index 5cc87c91..a31d3716 100644 --- a/src/http.ts +++ b/src/http.ts @@ -90,7 +90,7 @@ export function webRequestFromNode( /** * Which peers may set the request scheme with `X-Forwarded-Proto`: `true` * trusts any peer, `'loopback'` a proxy on the same host, and a list the - * peer addresses it names. + * exact peer addresses it names (no CIDR ranges). */ export type TrustProxy = boolean | 'loopback' | string[]; @@ -118,9 +118,10 @@ function forwardedProto(req: IncomingMessage, trustProxy: TrustProxy): string | /** Reads a `TrustProxy` from an env value such as `TRUST_PROXY`. */ export function parseTrustProxy(value: string | undefined): TrustProxy { const text = value?.trim() ?? ''; - if (text === '' || text === 'false' || text === '0') return false; - if (text === 'true' || text === '1') return true; - if (text === 'loopback') return 'loopback'; + const keyword = text.toLowerCase(); + if (keyword === '' || keyword === 'false' || keyword === '0') return false; + if (keyword === 'true' || keyword === '1') return true; + if (keyword === 'loopback') return 'loopback'; return text .split(',') .map((address) => address.trim()) diff --git a/src/node-entry/index.ts b/src/node-entry/index.ts index bdfdf30f..5a146d63 100644 --- a/src/node-entry/index.ts +++ b/src/node-entry/index.ts @@ -154,8 +154,9 @@ export interface ListenerOptions { * Take the request URL's scheme from `X-Forwarded-Proto` when the peer is * a proxy you trust, so `request.url` is `https:` behind a TLS-terminating * proxy. `true` trusts any peer, `'loopback'` a proxy on the same host, a - * list the peer addresses it names. Default: the `TRUST_PROXY` env var - * (`true`, `loopback` or comma-separated addresses), else false. + * list the exact peer addresses it names. Default: the `TRUST_PROXY` env + * var when `createListener` runs (`true`, `loopback` or comma-separated + * addresses), else false. The exported `listener` reads it at import. */ trustProxy?: TrustProxy; }