Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .changeset/node-entry-trust-proxy.md
Original file line number Diff line number Diff line change
@@ -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).
26 changes: 24 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -396,7 +396,21 @@ 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 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.

`node.js` is an emitted asset, not a second build input: `server.js` and
its `handleRequest` / `{ fetch }` contracts are unchanged. With
Expand Down Expand Up @@ -1004,6 +1018,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
Expand Down
63 changes: 62 additions & 1 deletion src/http.test.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -30,3 +30,64 @@ 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<string, string> = { 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<typeof webRequestFromNode>[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<typeof webRequestFromNode>[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('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']);
});
});
48 changes: 45 additions & 3 deletions src/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -86,6 +87,47 @@ 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
* exact peer addresses it names (no CIDR ranges).
*/
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() ?? '';
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())
.filter(Boolean);
}

export async function sendWebResponse(res: ServerResponse, response: Response): Promise<void> {
res.statusCode = response.status;
// set-cookie is the one header that must not be comma-joined.
Expand Down
22 changes: 19 additions & 3 deletions src/node-entry/index.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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
Expand Down Expand Up @@ -144,6 +150,15 @@ export interface ListenerOptions {
static?: boolean;
/** Extra request-event fields, merged over `{ nativeEvent: req }`. */
event?: (req: IncomingMessage) => Record<string, unknown>;
/**
* 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 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;
}

export type Listener = (req: IncomingMessage, res: ServerResponse) => Promise<void>;
Expand All @@ -152,6 +167,7 @@ export type Listener = (req: IncomingMessage, res: ServerResponse) => Promise<vo
export function createListener({
static: serveStatic = true,
event,
trustProxy = parseTrustProxy(process.env.TRUST_PROXY),
}: ListenerOptions = {}): Listener {
return async function listener(req, res) {
try {
Expand All @@ -170,7 +186,7 @@ export function createListener({
}
// Pages, the server-function endpoint, middleware — everything else.
// `nativeEvent` is the raw Node request, readable via getRequestEvent().
const response = await handleRequest(webRequestFromNode(req, undefined, res), {
const response = await handleRequest(webRequestFromNode(req, undefined, res, trustProxy), {
event: { nativeEvent: req, ...event?.(req) },
});
await sendWebResponse(res, response);
Expand Down
Loading