release: promote develop → main (staging) #5

Merged
chrnx merged 164 commits from develop into main 2026-07-18 19:01:55 +00:00
4 changed files with 108 additions and 18 deletions
Showing only changes of commit 08cb8554e6 - Show all commits

No files matched your search

+13 -8
View File
@@ -141,7 +141,7 @@ export function createApp(opts: {
onError: opts.onError,
};
const fetchFn = buildAppFetch(
booted,
() => booted,
routePlans,
{ providedSeed, planSteps, bus, onError: opts.onError },
fetchOpts,
@@ -617,22 +617,27 @@ function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps
/**
* Builds `app.fetch`: a Web-Standards handler over the same route table `listen()` uses, so
* `Deno.serve(app.fetch)` / `Bun.serve({ fetch: app.fetch })` work without ever calling `listen()`.
* Non-mesh apps finalize eagerly, so `booted` is already `true` and the route table is ready
* immediately. Mesh apps defer finalize to `listen()` (remote scopes must splice into the graph
* first), so the returned function throws until then — mirroring the explain()/graph()/inspect()
* "unavailable before listen()" guard.
* Non-mesh apps finalize eagerly, so `getBooted()` is already `true` and the route table is built
* on the very first call. Mesh apps defer finalize to `listen()` (remote scopes must splice into the
* graph first): `getBooted` reads the outer `booted` flag *live* on every call — exactly like
* `explain()`/`graph()`/`inspect()` do — so the returned function throws until `listen()` finalizes,
* then starts working from the next call on, without ever needing to be rebuilt.
*/
function buildAppFetch(
booted: boolean,
getBooted: () => boolean,
routePlans: RoutePlan[],
deps: PipelineDeps,
fetchOpts: HttpOptions,
ensureBooted: () => Promise<void>,
): (request: Request) => Promise<Response> {
const handler = booted ? buildFetch(buildHttpRoutes(routePlans, [], deps), fetchOpts) : undefined;
let handler: ((request: Request) => Promise<Response>) | undefined;
return async (request: Request): Promise<Response> => {
if (!handler) throw new Error('fetch() unavailable before listen() for mesh apps');
if (!handler) {
if (!getBooted()) throw new Error('fetch() unavailable before listen() for mesh apps');
handler = buildFetch(buildHttpRoutes(routePlans, [], deps), fetchOpts);
}
await ensureBooted(); // idempotent: no-op if listen() already booted the providers
return handler(request);
};
+16 -2
View File
@@ -34,6 +34,21 @@ export interface Preflight {
preflight: Record<string, string>;
}
/**
* Computes the security + CORS headers that get injected into every response for a request — the same
* authoritative set {@link handle} applies to its outcomes. Shared with `buildFetch` (src/http/web.ts)
* so early-failure responses (413/400/501, before a route even matches) carry the same headers Node's
* `patchResponseHeaders` would have installed up-front.
*/
export function computeInjected(
opts: HttpOptions | undefined,
req: { secure: boolean; headers: Record<string, string | string[] | undefined> },
): Record<string, string> {
const injected: Record<string, string> = { ...buildSecurityHeaders(opts?.security ?? true, req.secure) };
if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req));
return injected;
}
/**
* Runtime-neutral request handler: security/CORS headers, preflight short-circuit, route match / 404 / 405,
* route-handler invocation with error rendering, and the buffered-vs-stream decision. Does no I/O — the
@@ -45,8 +60,7 @@ export async function handle(
req: NeutralRequest,
): Promise<HandleResult | Preflight> {
const path = req.url.split('?')[0];
const injected: Record<string, string> = { ...buildSecurityHeaders(opts?.security ?? true, req.secure) };
if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req));
const injected = computeInjected(opts, req);
if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) {
return { preflight: corsPreflightHeaders(opts.cors, req) };
+25 -8
View File
@@ -1,5 +1,5 @@
import type { StreamEncoder } from '../encoders';
import { handle, type HandleResult } from './core';
import { handle, computeInjected, type HandleResult } from './core';
import { mergeInjectedHeaders } from './headers';
import { parseRequestBody } from './server';
import { matchRoute } from './router';
@@ -43,9 +43,15 @@ function headersToRecord(headers: Headers): Record<string, string> {
return out;
}
/** Turns a rendered error (or any {status, headers, body}) into a web `Response`. */
function errorResponse(rendered: ErrorResponse): Response {
return new Response(rendered.body, { status: rendered.status, headers: rendered.headers });
/**
* Turns a rendered error (or any {status, headers, body}) into a web `Response`, merging in the
* authoritative `injected` security/CORS headers — mirrors the Node adapter, where
* `patchResponseHeaders` installs these before body acquisition even runs, so early failures
* (413/400/501) carry them too.
*/
function errorResponse(rendered: ErrorResponse, injected: Record<string, string>): Response {
const headers = mergeInjectedHeaders(rendered.headers, injected);
return new Response(rendered.body, { status: rendered.status, headers });
}
/**
@@ -59,6 +65,7 @@ async function acquireFetchBody(
path: string,
maxBody: number,
opts: HttpOptions | undefined,
injected: Record<string, string>,
): Promise<{ body: unknown } | { response: Response }> {
const errReq: ErrorRequest = { method: request.method, url: path, headers };
let buf: Buffer | undefined;
@@ -68,7 +75,9 @@ async function acquireFetchBody(
const bodyLimit = matched.def.maxBodyBytes ?? maxBody;
if (arrayBuffer.byteLength > bodyLimit) {
return { response: errorResponse(renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError)) };
return {
response: errorResponse(renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError), injected),
};
}
buf = arrayBuffer.byteLength === 0 ? undefined : Buffer.from(arrayBuffer);
@@ -81,7 +90,10 @@ async function acquireFetchBody(
if ('error' in parsed) {
return {
response: errorResponse(renderError(new HttpError(parsed.status ?? 400, parsed.error), errReq, opts?.onError)),
response: errorResponse(
renderError(new HttpError(parsed.status ?? 400, parsed.error), errReq, opts?.onError),
injected,
),
};
}
@@ -112,10 +124,15 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
const path = url.pathname + url.search;
const headers = headersToRecord(request.headers);
const matched = matchRoute(routes, request.method, url.pathname);
const secure = url.protocol === 'https:';
// Computed up-front from the same inputs `handle()` uses, so early-failure responses (413/400/501,
// before a route handler even runs) carry the same security/CORS headers Node's writeHead patch
// would have installed before body acquisition.
const injected = computeInjected(opts, { secure, headers });
let body: unknown;
if (matched) {
const acquired = await acquireFetchBody(request, matched, headers, path, maxBody, opts);
const acquired = await acquireFetchBody(request, matched, headers, path, maxBody, opts, injected);
if ('response' in acquired) return acquired.response;
body = acquired.body;
}
@@ -125,7 +142,7 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
url: path,
headers,
body,
secure: url.protocol === 'https:',
secure,
ip: headers['x-forwarded-for'] ?? '',
});
+54
View File
@@ -15,11 +15,23 @@ class Ctl {
@Post('/echo') echo(@body() b: any) {
return { got: b };
}
@Post('/tiny', { maxBodyBytes: 10 }) tiny(@body() b: any) {
return { got: b };
}
}
@Module({ mountpoint: '/', providers: [Store], controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M] });
@Route('/mesh')
class MeshCtl {
@Get('/ping') ping() {
return { pong: true };
}
}
@Module({ mountpoint: '/api', controllers: [MeshCtl] })
class MeshModule {}
describe('app.fetch', () => {
it('handles GET and returns JSON 200', async () => {
const res = await app.fetch(new Request('http://x/api/hello'));
@@ -44,4 +56,46 @@ describe('app.fetch', () => {
const res = await app.fetch(new Request('http://x/api/hello'));
expect(res.headers.get('x-content-type-options')).toBe('nosniff');
});
it('a 413 (oversized body) still carries the injected security headers', async () => {
const res = await app.fetch(
new Request('http://x/api/tiny', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ x: 'well over ten bytes' }),
}),
);
expect(res.status).toBe(413);
expect(res.headers.get('x-content-type-options')).toBe('nosniff');
expect(res.headers.get('x-frame-options')).toBe('SAMEORIGIN');
});
it('a 400 (invalid JSON) still carries the injected security headers', async () => {
const res = await app.fetch(
new Request('http://x/api/echo', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: '{not json',
}),
);
expect(res.status).toBe(400);
expect(res.headers.get('x-content-type-options')).toBe('nosniff');
});
});
describe('app.fetch mesh gating (live `booted` read)', () => {
it('throws before listen() and starts working after listen() finalizes', async () => {
const meshApp = createApp({ modules: [MeshModule], experimental: true, mesh: { secret: 's3cr3t' } });
await expect(meshApp.fetch(new Request('http://x/api/mesh/ping'))).rejects.toThrow(/unavailable before listen/);
const server = await meshApp.listen(0);
try {
const res = await meshApp.fetch(new Request('http://x/api/mesh/ping'));
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ pong: true });
} finally {
server.close();
}
});
});