fix(runtime): give ctx.ip the socket peer on Deno and Bun
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 32s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / runtimes (edge) (pull_request) Successful in 15s

buildFetch had no channel for a peer address, so ctx.ip was '' for
every HTTP request served by serveDeno or serveBun unless trustProxy and
x-forwarded-for supplied one. Everything keyed on the address shared one
value: the rate-limit plugin put every client in a single bucket, and
one client could exhaust the limit for all of them.

The adapters now record the peer in a WeakMap keyed by the Request
object (src/http/peer.ts, not exported) and pass that same object to
app.fetch. A header would be visible to handlers and spoofable; a second
fetch parameter would be public API. buildFetch derives ctx.ip as Node's
deriveIp does: the first x-forwarded-for hop when trustProxy is on and
the header is present, the peer otherwise. trustProxy without the header
therefore falls back to the peer instead of answering ''.

The map hangs off globalThis under Symbol.for('@green-tea/core:peer')
rather than living in the module. tsup's CommonJS build bundles index,
deno and bun as separate files with no shared chunk, so each gets its
own copy of peer.ts; with a module-private map, serveBun from
@green-tea/core/bun recorded peers that app.fetch from @green-tea/core
never saw, and ctx.ip stayed ''. A test loads a second instance of the
module to pin this.

A bare app.fetch from user code, or a Request copied from the adapter's,
has no entry and answers exactly what it did before. Addresses are
passed through unnormalised. WebSocket and the edge adapter are
unchanged; trusting cf-connecting-ip is a separate decision.

Closes #116

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-10-09 13:59:59 -05:00
1 parent ae60cd68a2
commit f78c9dc6fd
8 files changed
+254 -12

No files matched your search

+27
View File
@@ -0,0 +1,27 @@
// src/http/peer.ts — the socket peer address, handed from the Deno and Bun adapters to `buildFetch`.
// Internal: not exported from the package.
//
// Keyed by the `Request` object rather than carried on it. A header would be visible to handlers and
// spoofable by any client that sent one with the same name; a second `fetch` parameter would be
// public API. The adapters call `app.fetch` with the very object they record, so identity holds, and
// the entry goes when the request does. A `Request` copied from it carries nothing, which is what a
// bare `app.fetch` from user code has always seen.
//
// The map lives on `globalThis` under a registered symbol, not in this module, because this module
// is not always one instance. The CommonJS build bundles `index`, `deno` and `bun` as separate files
// with no shared chunk, so each carries its own copy of this one: a module-private map in
// `@green-tea/core/bun` would record peers that `app.fetch` from `@green-tea/core` never sees. An app
// that loads core both as ESM and as CommonJS has the same split.
const KEY = Symbol.for('@green-tea/core:peer');
const registry = globalThis as { [KEY]?: WeakMap<Request, string> };
const peers = (registry[KEY] ??= new WeakMap<Request, string>());
/** Records `ip` as the peer of `request`. An empty address — a unix socket has none — is not recorded. */
export function setPeer(request: Request, ip: string): void {
if (ip) peers.set(request, ip);
}
/** The peer an adapter recorded for `request`, or `''` when none did. */
export function peerOf(request: Request): string {
return peers.get(request) ?? '';
}
+14 -8
View File
@@ -11,6 +11,7 @@ import {
type Preflight,
} from './core';
import { mergeInjectedHeaders } from './headers';
import { peerOf } from './peer';
import { declaresOverLimit, type BodyFailure, type BodyReader, type MaybePromise } from './body';
import { HttpError } from '../signals';
import { renderError, type ErrorRequest } from '../transformers';
@@ -218,6 +219,15 @@ function outcomeToResponse(result: HandleResult, bus?: Bus, correlation: Correla
return new Response(body, { status: result.outcome.status, headers });
}
/** The first `x-forwarded-for` hop when the proxy is trusted, else `''`. */
function forwardedFor(headers: Record<string, string>, opts: HttpOptions | undefined): string {
if (!opts?.trustProxy) return '';
return String(headers['x-forwarded-for'] ?? '')
.split(',')[0]
.trim();
}
/**
* Builds a Web-Standards `fetch(request)` handler over the same route table the Node adapter uses:
* describes the request for the runtime-neutral {@link handle}, supplies the {@link BodyReader} it
@@ -286,14 +296,10 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
source: request,
secure,
// Mirrors Node's `deriveIp` (src/http/request.ts): only trust `x-forwarded-for` when the
// proxy is trusted, and take its first hop — an untrusted XFF is client-spoofable, and
// there's no socket peer address to fall back to on the fetch path, so the untrusted case
// is simply ''.
ip: opts?.trustProxy
? String(headers['x-forwarded-for'] ?? '')
.split(',')[0]
.trim()
: '',
// proxy is trusted, and take its first hop — an untrusted XFF is client-spoofable.
// Otherwise the socket peer, which only the Deno and Bun adapters can supply; a bare
// `app.fetch` has none, so there the answer is still ''.
ip: forwardedFor(headers, opts) || peerOf(request),
},
// Already computed above for the shed-503 path; handing it down keeps `cors.origins` to
// one call per request.