5 Commits
Author SHA1 Message Date
chrnx 56f953f0bb feat(graph)!: fail boot when a token has a second producer (CARD-18, GitHub #35)
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 26s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / runtimes (edge) (pull_request) Successful in 14s
topoSort, topoLevels and subgraphFor built their token -> node map with
producedBy.set(key, node), so the last node registered for a token won.
Plugin nodes are registered after module nodes, which let a plugin's
scope.add({ name: 'shadow', provides: ['user'] }) silently replace the
app's own @Provider({ provides: 'user' }) for every route that needed
it. setRunner only rejects duplicate names, and scope.add is the one
path where a name and its tokens differ.

D9 settles it graph-wide: topoSort now throws when a token already has
a producer, naming both nodes and their origins (module:..., plugin,
mesh:<url>, builtin). One check on the whole node set covers every
current and future registration path. It also protects the built-ins
(logger, rooms, events) by rule rather than by registration order.
topoSort runs at finalize, after the mesh splice, so remote steps are
checked too. topoLevels and subgraphFor only ever see nodes topoSort
has already validated, so they keep their plain maps.

overrides replace the runner of an existing token and add no node, so
they are unaffected. Steps that provide nothing (plugin observers) are
not producers. The official plugins (jwt, metrics, rate-limit) pass
their suites against this build.

BREAKING CHANGE: an app whose graph has two nodes providing one token,
  e.g. a plugin scope node providing a token a module or built-in
  already provides, now fails createApp instead of letting the later
  node win.
Refs: GitHub #35

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:50:26 -05:00
chrnx a9e0555516 Merge pull request 'feat(edge)!: trust cf-connecting-ip only under trustProxy, for HTTP and WebSocket (CARD-23, #119)' (#139) from feature/fprd-001c-edge-cf-connecting-ip into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 16s
CI / build (push) Successful in 27s
CI / runtimes (deno) (push) Successful in 20s
CI / runtimes (edge) (push) Successful in 14s
Promote → GitHub / push-github (push) Successful in 6s
2026-10-23 05:49:45 +00:00
chrnx 88cbe41f72 feat(edge)!: trust cf-connecting-ip only under trustProxy, for HTTP and WebSocket (CARD-23, #119)
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 25s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / runtimes (edge) (pull_request) Successful in 15s
edgeHandler copied cf-connecting-ip into ctx.ip on every WebSocket
upgrade, so any client that sent the header chose its own address, and
it never read the header for HTTP, so IP-keyed plugins saw '' there.
D21 settles both: the header counts only under trustProxy, on both
paths, with no new option.

The adapter cannot make that call, because trustProxy is an app option.
So edgeHandler records the header against the object it hands the app
(the Request for HTTP, the WsRequest for an upgrade) in an internal
registry next to the Deno/Bun peer one, and app.fetch and app.upgrade
both consult it through one helper, trustedProxyClient(), which returns
'' unless trustProxy is on. Under trustProxy it takes precedence over
x-forwarded-for, since Cloudflare sets it itself and XFF can carry
client-supplied hops.

Nothing else records into the registry, so the Node, Deno and Bun
adapters, and a bare app.fetch or app.upgrade, ignore the header as
before.

BREAKING CHANGE: an edge WebSocket upgrade no longer takes ctx.ip from
  cf-connecting-ip unless the app sets trustProxy: true; without it,
  ctx.ip is ''.
Refs: #119

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:47:58 -05:00
chrnx 89ac955072 Merge pull request 'fix(http): keep every ? after the first in the query string (CARD-25, GitHub #48)' (#136) from feature/fprd-001c-query-string-question-marks into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 15s
CI / build (push) Successful in 27s
CI / runtimes (edge) (push) Successful in 13s
CI / runtimes (deno) (push) Successful in 20s
Promote → GitHub / push-github (push) Successful in 7s
2026-10-23 05:47:53 +00:00
chrnx 8bf54ec168 fix(http): keep every ? after the first in the query string (CARD-25, GitHub #48)
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 27s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 14s
parseQuery took `url.split('?')[1]`, so a second `?` ended the query
string and `/search?q=what?now` gave `q: 'what'`. RFC 3986 §3.4 allows
`?` inside a query. The query string is now everything after the first
`?` and before `#`, if one is present. The early return for URLs without
a query is kept, and so is its measurement note. The comment that
deferred this behaviour question is removed because the question is now
decided (D23).

Path extraction already split on the first `?` and is unchanged.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:02:42 -05:00
10 changed files with 325 additions and 20 deletions

No files matched your search

+19
View File
@@ -58,6 +58,12 @@ npm treats versions as semver and semver forbids leading zeros.
constraints at a later segment of an otherwise unreachable route. The route then boots, as
before.
- **Edge WebSocket upgrades no longer trust `cf-connecting-ip` by default** (#119). `edgeHandler`
copied the header into `ctx.ip` on every upgrade, so any client that sent it chose its own
address. It now counts only under `trustProxy: true`, the same rule HTTP follows. Without it,
`ctx.ip` on an edge WebSocket is `''`, as it already was on edge HTTP: workerd exposes no peer
address. An app behind Cloudflare that keys anything on the WebSocket IP needs
`createApp({ trustProxy: true })`.
- **A token has one producer: a second one fails `createApp`** (GitHub #35). The graph kept the
last node registered for a token, and plugin nodes are registered after module nodes, so a
plugin whose `scope.add` provided `user` silently replaced the app's own `@Provider({ provides:
@@ -92,8 +98,21 @@ npm treats versions as semver and semver forbids leading zeros.
param hit −88%, method miss −94%, path miss −96%; at 10 routes, every cell is within noise or
faster (late param hit +3.4%, 95% CI −5.0…+12.6%).
- **A query string keeps every `?` after the first** (GitHub #48). `parseQuery` took the text
between the first and second `?`, so `/search?q=what?now` gave `q: 'what'` and dropped the rest.
RFC 3986 §3.4 allows `?` inside a query, so the query string is now everything after the first
`?` and before `#`, if there is one: `q: 'what?now'`, and `/search?a=1&b=?` gives `b: '?'`. URLs
with a single `?` parse as before. Path extraction is unchanged.
### Fixed
- **Edge HTTP fills `ctx.ip` from `cf-connecting-ip` under `trustProxy`** (#119). `edgeHandler`
never read the header for HTTP, so IP-keyed plugins such as rate-limit saw `''`, one bucket for
every client. Under `trustProxy: true` the header now sets `ctx.ip`, and it wins over
`x-forwarded-for`, because Cloudflare sets it itself while XFF can carry hops the client supplied.
Without `trustProxy` it is ignored. Only `edgeHandler` reads it: the Node, Deno and Bun adapters, and a
bare `app.fetch`, ignore it as before.
- **`static` no longer serves files outside its root through a symlink** (#106). The traversal guard
compared paths lexically, and the file read then followed symlinks, so `public/leak -> /etc/hosts`
was served. Containment now compares real paths: the requested file, and a directory's
+17 -3
View File
@@ -7,6 +7,7 @@ import { toMermaid, toDOT, graphHtml, type GraphView } from '../graph-viz';
import { runPipeline, runSteps, PipelineStep } from '../pipeline';
import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http';
import type { HttpOptions } from '../http';
import { trustedProxyClient } from '../http/peer';
import { buildFetch } from '../http/web';
import {
boundInbound,
@@ -331,7 +332,10 @@ export function createApp(opts: {
devRoutes,
() => remoteRoutes,
);
const upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl, opts.limits);
const upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl, {
limits: opts.limits,
trustProxy: opts.trustProxy,
});
const listen = async (port: number): Promise<http.Server> => {
const deps = pipelineDeps;
@@ -1395,7 +1399,7 @@ function buildAppUpgrade(
streams: Set<() => void>,
ensureBooted: () => Promise<void>,
getMeshControl: () => MeshControl | undefined,
limits?: RequestLimits,
{ limits, trustProxy }: { limits?: RequestLimits; trustProxy?: boolean },
): (request: WsRequest, socket: WsSocket) => Promise<void> {
let wsRoutes: WsRouteDef[] | undefined;
@@ -1444,10 +1448,20 @@ function buildAppUpgrade(
return;
}
await runWsConnection(ready, request, route, deps.bus, streams);
await runWsConnection(ready, withProxyClient(request, trustProxy), route, deps.bus, streams);
};
}
/**
* `request` with `ip` taken from the proxy header its adapter recorded, when `trustProxy` allows it
* (the edge adapter's `cf-connecting-ip`, CARD-23); otherwise `request` unchanged. The same check
* `app.fetch` runs, so an edge WebSocket upgrade and an edge HTTP request resolve `ctx.ip` alike.
*/
function withProxyClient(request: WsRequest, trustProxy: boolean | undefined): WsRequest {
const ip = trustedProxyClient(request, trustProxy);
return ip ? { ...request, ip } : request;
}
/** The dev-only `/__graph__` route: serves the dependency graph as Mermaid text or an HTML viewer. */
function devGraphRoute(graph: () => GraphView): RouteDef {
return {
+16 -1
View File
@@ -1,5 +1,6 @@
import type { App } from './app/types';
import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter';
import { setProxyClient } from './http/peer';
// Minimal ambient for the Cloudflare Workers globals we use — avoids @cloudflare/workers-types.
// Declares only what we call; mirrors the real workerd signatures.
@@ -30,7 +31,9 @@ export function edgeHandler(
if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
const [client, server] = Object.values(new WebSocketPair()) as [EdgeWebSocket, EdgeWebSocket];
server.accept();
const wsReq = toWsRequest(request, request.headers.get('cf-connecting-ip') ?? '');
// No peer address on the edge, so `ip` starts empty; the header only fills it under `trustProxy`.
const wsReq = toWsRequest(request, '');
recordClient(wsReq, request);
const lifecycle = upgradeSafely(app, wsReq, eventSocket(server));
if (ctx?.waitUntil) ctx.waitUntil(lifecycle);
else void lifecycle;
@@ -38,6 +41,18 @@ export function edgeHandler(
return new Response(null, { status: 101, webSocket: client } as ResponseInit & { webSocket: EdgeWebSocket });
}
recordClient(request, request);
return app.fetch(request);
};
}
/**
* Hands the app the `cf-connecting-ip` header for `source`, the object the app will be given for this
* request. The app — not this adapter — decides whether it counts, since `trustProxy` is an app
* option; HTTP and WebSocket both go through here and through the same check on the app side.
* Without `trustProxy` the header is ignored and `ctx.ip` stays `''`: workerd exposes no peer address,
* and an untrusted header is whatever the client chose to send.
*/
function recordClient(source: object, request: Request): void {
setProxyClient(source, request.headers.get('cf-connecting-ip') ?? '');
}
+25
View File
@@ -25,3 +25,28 @@ export function setPeer(request: Request, ip: string): void {
export function peerOf(request: Request): string {
return peers.get(request) ?? '';
}
// The client address a runtime adapter read from a header its platform's proxy sets — today only the
// edge adapter, from `cf-connecting-ip`. Unlike the socket peer above, a header is client-supplied
// unless a proxy in front overwrites it, so it only counts under `trustProxy`; the adapter cannot
// decide that, because the option lives on the app, so it records the value and the app decides.
// Keyed by the `Request` (HTTP) or the `WsRequest` (WebSocket upgrade) the adapter hands the app, for
// the same reasons as the peer: no handler-visible header, no extra public parameter. Same
// `globalThis` registration, because `@green-tea/core/edge` is a separate bundle too.
const PROXY_KEY = Symbol.for('@green-tea/core:proxy-client');
const proxyRegistry = globalThis as { [PROXY_KEY]?: WeakMap<object, string> };
const proxyClients = (proxyRegistry[PROXY_KEY] ??= new WeakMap<object, string>());
/** Records `ip` as the client address a proxy header named for `source`. An empty value is not recorded. */
export function setProxyClient(source: object, ip: string): void {
if (ip) proxyClients.set(source, ip);
}
/**
* The client address an adapter recorded for `source` from a proxy header, when `trustProxy` is on;
* `''` otherwise. The one check both `app.fetch` and `app.upgrade` run, so HTTP and WebSocket cannot
* disagree about whether the header counts.
*/
export function trustedProxyClient(source: object, trustProxy: boolean | undefined): string {
return trustProxy ? (proxyClients.get(source) ?? '') : '';
}
+15 -10
View File
@@ -743,18 +743,23 @@ export function allowedMethods(routes: RouteDef[], path: string): string[] {
});
}
/** Parses a URL's query string into a flat string map (last value wins for repeated keys). */
/**
* Parses a URL's query string into a flat string map (last value wins for repeated keys).
*
* The query string is everything after the **first** `?` and before a `#`, if one is present.
* A `?` inside the query is a legal character (RFC 3986 §3.4), so `/search?q=what?now` gives
* `{ q: 'what?now' }`.
*/
export function parseQuery(url: string): Record<string, string> {
// Most requests carry no query string, and the work below is not free for them: `split` builds
// an array, `new URLSearchParams('')` builds an object, and the loop runs zero times — three
// allocations to arrive at `{}`. Measured at 92.3 ns against 18.6 ns for this check.
//
// Only the guard is new; the parse below is untouched on purpose. Reaching for `indexOf` +
// `slice` instead of `split` would also drop an allocation, but it changes what a second `?`
// means, and that is a behaviour question rather than a performance one.
if (!url.includes('?')) return {};
// Most requests carry no query string, and the work below is not free for them:
// `new URLSearchParams('')` builds an object and the loop runs zero times, to arrive at `{}`.
// Measured at 92.3 ns against 18.6 ns for this check.
const start = url.indexOf('?');
if (start < 0) return {};
const queryString = url.split('?')[1] ?? '';
// `split('?')[1]` used to stop at a second `?` and drop the rest of the value (GitHub #48).
const hash = url.indexOf('#', start + 1);
const queryString = hash < 0 ? url.slice(start + 1) : url.slice(start + 1, hash);
const out: Record<string, string> = {};
for (const [key, value] of new URLSearchParams(queryString)) out[key] = value;
return out;
+5 -2
View File
@@ -11,7 +11,7 @@ import {
type Preflight,
} from './core';
import { mergeInjectedHeaders } from './headers';
import { peerOf } from './peer';
import { peerOf, trustedProxyClient } from './peer';
import { declaresOverLimit, type BodyFailure, type BodyReader, type MaybePromise } from './body';
import { HttpError } from '../signals';
import { renderError, type ErrorRequest } from '../transformers';
@@ -299,7 +299,10 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
// 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),
// Ahead of both, under `trustProxy` only: the address the edge adapter read from
// `cf-connecting-ip`. Cloudflare sets that header itself, while XFF can carry hops the
// client supplied, so on the edge it wins (CARD-23).
ip: trustedProxyClient(request, opts?.trustProxy) || forwardedFor(headers, opts) || peerOf(request),
},
// Already computed above for the shed-503 path; handing it down keeps `cors.origins` to
// one call per request.
+119
View File
@@ -0,0 +1,119 @@
// CARD-23 (#119, D21): on the edge, `cf-connecting-ip` sets `ctx.ip` only under `trustProxy`, for HTTP
// and WebSocket alike, and wins over `x-forwarded-for`. The full WebSocket path through workerd
// (`WebSocketPair`, a 101 response) cannot run under Node, so it is covered in `test/edge/run.ts`;
// here the edge HTTP path runs through `edgeHandler` itself, and the WebSocket side through
// `app.upgrade` with the value recorded the way `edgeHandler` records it.
import 'reflect-metadata';
import { describe, expect, it } from 'vitest';
import type { AddressInfo } from 'node:net';
import { createApp, Route, Get, Ws, Module, ctx } from '../src/index';
import { edgeHandler } from '../src/edge';
import { channel } from '../src/channel';
import { setProxyClient } from '../src/http/peer';
import type { WsSocket, WsRequest } from '../src/http/ws-core';
@Route('/ip')
class IpCtl {
@Get('/whoami') whoami(@ctx() c: any) {
return { ip: c.ip };
}
@Ws('/ws')
ws(@ctx() c: any) {
return (async function* () {
yield String(c.ip);
})();
}
}
@Module({ mountpoint: '/', controllers: [IpCtl] })
class IpModule {}
const trusting = createApp({ modules: [IpModule], trustProxy: true });
const untrusting = createApp({ modules: [IpModule] });
const whoami = async (handler: (r: Request) => Response | Promise<Response>, headers: Record<string, string>) =>
((await (await handler(new Request('http://x/ip/whoami', { headers }))).json()) as { ip: string }).ip;
describe('edge HTTP: cf-connecting-ip', () => {
it('T1: under trustProxy it sets ctx.ip', async () => {
expect(await whoami(edgeHandler(trusting), { 'cf-connecting-ip': '1.2.3.4' })).toBe('1.2.3.4');
});
it('T2: under trustProxy it wins over x-forwarded-for', async () => {
const headers = { 'cf-connecting-ip': '1.2.3.4', 'x-forwarded-for': '9.9.9.9' };
expect(await whoami(edgeHandler(trusting), headers)).toBe('1.2.3.4');
});
it('under trustProxy without the header, x-forwarded-for still applies', async () => {
expect(await whoami(edgeHandler(trusting), { 'x-forwarded-for': '9.9.9.9' })).toBe('9.9.9.9');
});
it('T3: without trustProxy it is ignored and ctx.ip stays empty', async () => {
expect(await whoami(edgeHandler(untrusting), { 'cf-connecting-ip': '1.2.3.4' })).toBe('');
});
});
function fakeSocket() {
const ac = new AbortController();
const sent: string[] = [];
const socket: WsSocket = {
inbound: channel<unknown>(),
abort: ac.signal,
isOpen: true,
send: (d) => sent.push(d),
close: () => ac.abort(),
terminate: () => ac.abort(),
};
return { socket, sent };
}
/** Upgrades the way `edgeHandler` does: `ip` empty, the header recorded on the `WsRequest`. */
async function edgeWsIp(app: typeof trusting, cfConnectingIp: string): Promise<string> {
const headers = { 'cf-connecting-ip': cfConnectingIp };
const req: WsRequest = { url: '/ip/ws', headers, protocol: 'http', ip: '' };
setProxyClient(req, cfConnectingIp);
const { socket, sent } = fakeSocket();
await app.upgrade(req, socket);
return sent[0];
}
describe('edge WebSocket: cf-connecting-ip', () => {
it('T4: without trustProxy it is ignored and ctx.ip stays empty', async () => {
expect(await edgeWsIp(untrusting, '1.2.3.4')).toBe('');
});
it('T5: under trustProxy it sets ctx.ip', async () => {
expect(await edgeWsIp(trusting, '1.2.3.4')).toBe('1.2.3.4');
});
it('an adapter-supplied ip with nothing recorded is passed through unchanged', async () => {
const { socket, sent } = fakeSocket();
await trusting.upgrade({ url: '/ip/ws', headers: {}, protocol: 'http', ip: '203.0.113.7' }, socket);
expect(sent).toEqual(['203.0.113.7']);
});
});
describe('outside the edge adapter the header means nothing', () => {
it('T6: the Node listener under trustProxy ignores cf-connecting-ip', async () => {
const server = await createApp({ modules: [IpModule], trustProxy: true }).listen(0);
try {
const { port } = server.address() as AddressInfo;
const res = await fetch(`http://127.0.0.1:${port}/ip/whoami`, { headers: { 'cf-connecting-ip': '1.2.3.4' } });
const { ip } = (await res.json()) as { ip: string };
expect(ip).not.toBe('1.2.3.4');
expect(ip).toMatch(/127\.0\.0\.1|::1/);
} finally {
await new Promise<void>((resolve) => server.close(() => resolve()));
}
});
it('a bare app.fetch under trustProxy ignores cf-connecting-ip', async () => {
expect(await whoami((r) => trusting.fetch(r), { 'cf-connecting-ip': '1.2.3.4' })).toBe('');
});
it('a bare app.upgrade under trustProxy ignores the header in WsRequest.headers', async () => {
const { socket, sent } = fakeSocket();
await trusting.upgrade({ url: '/ip/ws', headers: { 'cf-connecting-ip': '1.2.3.4' }, protocol: 'http', ip: '' }, socket);
expect(sent).toEqual(['']);
});
});
+26 -1
View File
@@ -138,7 +138,32 @@ async function main() {
assert.equal((await exchange(mf, 'http://localhost/rt/echo', ['a'.repeat(1_048_576)])).replies.length, 1);
assert.equal((await exchange(mf, 'http://localhost/rt/echo', ['a'.repeat(1_048_577)])).close?.code, 1009);
console.log('edge (workerd via miniflare): HTTP 200 + body limits 413/413/200/413 + WS echo:hi + ws limits — PASS');
// CARD-23 (#119): `cf-connecting-ip` sets ctx.ip only under trustProxy, for HTTP and WS alike,
// and wins over x-forwarded-for.
const cf = { 'cf-connecting-ip': '1.2.3.4' };
const httpIp = async (host: string, headers: Record<string, string>) =>
((await (await mf.dispatchFetch(`http://${host}/rt/ip`, { headers })).json()) as { ip: string }).ip;
const wsIp = async (host: string, headers: Record<string, string>) => {
const res = await mf.dispatchFetch(`http://${host}/rt/ws-ip`, { headers: { Upgrade: 'websocket', ...headers } });
const socket = res.webSocket;
assert.ok(socket, 'expected a client webSocket on the 101 response');
const reply = new Promise<string>((resolve) =>
socket.addEventListener('message', (e: { data: unknown }) => resolve(String(e.data))),
);
socket.accept();
const got = await reply;
socket.close();
return got;
};
assert.equal(await httpIp('trusted', cf), '1.2.3.4', 'T1 edge HTTP under trustProxy');
assert.equal(await httpIp('trusted', { ...cf, 'x-forwarded-for': '9.9.9.9' }), '1.2.3.4', 'T2 cf wins over XFF');
assert.equal(await httpIp('localhost', cf), '', 'T3 edge HTTP without trustProxy');
assert.equal(await wsIp('localhost', cf), 'ip:', 'T4 edge WS without trustProxy');
assert.equal(await wsIp('trusted', cf), 'ip:1.2.3.4', 'T5 edge WS under trustProxy');
console.log(
'edge (workerd via miniflare): HTTP 200 + body limits 413/413/200/413 + WS echo:hi + ws limits + cf-connecting-ip under trustProxy — PASS',
);
} finally {
await mf.dispose();
}
+22 -3
View File
@@ -35,6 +35,19 @@ class Rt {
})();
}
// CARD-23: what `ctx.ip` resolved to, over HTTP and over a WebSocket upgrade.
@Get('/ip')
ip(@ctx() c: any) {
return { ip: c.ip };
}
@Ws('/ws-ip')
wsIp(@ctx() c: any) {
return (async function* () {
yield `ip:${c.ip}`;
})();
}
@Ws('/room/:name')
room(@ctx() { inbound }: any) {
return (async function* () {
@@ -49,9 +62,15 @@ class M {}
const app = createApp({ modules: [M] });
// #107: the same graph with tight ws limits, reached through the `limited` host.
const limited = createApp({ modules: [M], limits: { maxWsMessageBytes: 1024, maxWsQueue: 4 } });
const handlers = { default: edgeHandler(app), limited: edgeHandler(limited) };
// CARD-23: the same graph under `trustProxy`, reached through the `trusted` host.
const trusted = createApp({ modules: [M], trustProxy: true });
const handlers: Record<string, ReturnType<typeof edgeHandler>> = {
default: edgeHandler(app),
limited: edgeHandler(limited),
trusted: edgeHandler(trusted),
};
export default {
fetch: (request: Request, env?: unknown, ctx?: Parameters<typeof handlers.default>[2]) =>
(new URL(request.url).hostname === 'limited' ? handlers.limited : handlers.default)(request, env, ctx),
fetch: (request: Request, env?: unknown, ctx?: Parameters<ReturnType<typeof edgeHandler>>[2]) =>
(handlers[new URL(request.url).hostname] ?? handlers.default)(request, env, ctx),
};
+61
View File
@@ -0,0 +1,61 @@
import 'reflect-metadata';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import type { AddressInfo } from 'node:net';
import type { Server } from 'node:http';
import { Get, Module, Route, Transformer } from '../src/metadata';
import { JsonTransformer } from '../src/transformers';
import { createApp } from '../src/app';
import { parseQuery } from '../src/http';
import { query } from '../src/params';
// CARD-25 / GitHub #48: the query string is everything after the FIRST `?` (and before `#`).
const CASES: Array<[string, Record<string, string>]> = [
['/search?q=what?now', { q: 'what?now' }], // T1
['/search?a=1&b=?', { a: '1', b: '?' }], // T2
['/search?', {}], // T3
['/search', {}], // T4
];
describe('parseQuery', () => {
test.each(CASES)('%s', (url, expected) => {
expect(parseQuery(url)).toEqual(expected);
});
test('stops at a fragment', () => {
expect(parseQuery('/search?q=a?b#frag?x=1')).toEqual({ q: 'a?b' });
});
});
@Route('/search')
class SearchCtl {
@Get('/')
@Transformer(JsonTransformer)
search(@query() q: Record<string, string>) {
return q;
}
}
@Module({ mountpoint: '/', controllers: [SearchCtl] })
class SearchModule {}
describe('query string with more than one `?`', () => {
const app = createApp({ modules: [SearchModule] });
let server: Server;
let base: string;
beforeAll(async () => {
server = await app.listen(0);
base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
});
afterAll(() => new Promise<void>((resolve) => server.close(() => resolve())));
test.each(CASES)('app.fetch %s', async (url, expected) => {
const res = await app.fetch(new Request(`http://x${url}`));
expect(await res.json()).toEqual(expected);
});
test.each(CASES)('Node listener %s', async (url, expected) => {
const res = await fetch(`${base}${url}`);
expect(await res.json()).toEqual(expected);
});
});