feat: beta-hardening — routing, degradation, mesh gate, uploads, @header

Restructure first: split the two oversized files by cohesion (http.ts 449
→ http/{router,request,stream,ws,server,types}; app.ts 556 → app/{types,
introspect,index}), rename cryptic locals, JSDoc the public API, and
extract helpers so no function exceeds the complexity gate (createApp
187 → <15, listen 113 → 6). Public import paths are unchanged (barrels).

On that structure, five features that close the biggest gaps vs
Express/Fastify/Nest for a comparable beta:

- routing: `:name*` catch-all, specificity precedence (static ▸ param ▸
  catch-all, not registration order), and 405 + Allow when a path exists
  under a different method (was 404)
- visible degradation: optional providers that fail boot are summarized on
  listen() and queryable via app.degraded(), instead of a silent warn
- mesh is alpha — gated behind `experimental: true`; createApp throws if
  `mesh` is configured without it
- multipart moves to the optional `busboy` peer dependency (clear 501 when
  absent), keeping the core at one runtime dependency
- `@header('name')` as a singular alias of `@headers`

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-07-07 12:00:15 -05:00
1 parent 9d79972f62
commit d6c5cee0ee
42 files changed
+2619 -1170

No files matched your search

+92 -45
View File
@@ -4,30 +4,105 @@ import { encode, decode, type Manifest, type RequestEnvelope, type Frame } from
let connSeq = 0; // module-level: deterministic unique connection-id prefix (no Date.now/Math.random)
/** Client handle to a remote mesh server: its manifest, an RPC caller, and a close(). */
export interface Link {
manifest: Manifest;
rpc(kind: 'scope' | 'route', name: string, ctx: RequestEnvelope): Promise<unknown>;
close(): void;
}
/** An in-flight RPC awaiting its `rpc-res`, keyed by id in the pending map. */
type PendingEntry = {
resolve: (v: unknown) => void;
reject: (e: unknown) => void;
timer: ReturnType<typeof setTimeout>;
};
function loadWs(): any {
return require('ws'); // lazy/optional, like streams; the ws CJS export is the WebSocket class
// lazy/optional, like streams; the ws CJS export is the WebSocket class
// eslint-disable-next-line @typescript-eslint/no-require-imports
return require('ws');
}
export function connectLink(args: {
url: string;
secret: string;
timeoutMs?: number;
bus?: Bus;
}): Promise<Link> {
/** Reject and clear every in-flight RPC — used when the link closes. */
function rejectAllPending(pending: Map<string, PendingEntry>, reason: string): void {
for (const [, entry] of pending) {
clearTimeout(entry.timer);
entry.reject(new Error(reason));
}
pending.clear();
}
/** Register one RPC in `pending` by id, send its request, and reject it on timeout. */
function sendRpc(
ws: any,
pending: Map<string, PendingEntry>,
id: string,
kind: 'scope' | 'route',
name: string,
ctx: RequestEnvelope,
timeoutMs: number,
): Promise<unknown> {
return new Promise((resolveCall, rejectCall) => {
const timer = setTimeout(() => {
pending.delete(id);
rejectCall(new Error(`mesh rpc timeout: ${name}`));
}, timeoutMs);
pending.set(id, { resolve: resolveCall, reject: rejectCall, timer });
ws.send(encode({ type: 'rpc-req', id, kind, name, ctx }));
});
}
/** Assemble the client-facing Link once the manifest arrives. */
function buildLink(
ws: any,
pending: Map<string, PendingEntry>,
manifest: Manifest,
connId: string,
timeoutMs: number,
): Link {
let counter = 0;
return {
manifest,
rpc(kind, name, ctx) {
const id = `${connId}:${counter++}`;
return sendRpc(ws, pending, id, kind, name, ctx, timeoutMs);
},
close() {
ws.close();
},
};
}
/** Settle a pending RPC from its `rpc-res` frame — resolve on ok, reject (and emit) on error. */
function settleRpcResponse(
pending: Map<string, PendingEntry>,
frame: Extract<Frame, { type: 'rpc-res' }>,
bus?: Bus,
): void {
const entry = pending.get(frame.id);
if (!entry) return;
pending.delete(frame.id);
clearTimeout(entry.timer);
if (frame.ok) {
entry.resolve(frame.result);
} else {
bus?.emit('mesh:rpc:error', { name: frame.id, error: frame.error });
entry.reject(new HttpError(frame.error.status ?? 500, frame.error.message));
}
}
/** Open a WebSocket link to a mesh server, handshake with `secret`, and resolve once its manifest arrives. */
export function connectLink(args: { url: string; secret: string; timeoutMs?: number; bus?: Bus }): Promise<Link> {
const timeoutMs = args.timeoutMs ?? 30_000;
const WS = loadWs();
const ws = new WS(args.url);
const pending = new Map<
string,
{ resolve: (v: unknown) => void; reject: (e: unknown) => void; timer: ReturnType<typeof setTimeout> }
>();
let counter = 0;
const pending = new Map<string, PendingEntry>();
const connId = `c${connSeq++}`;
let manifest: Manifest | undefined;
@@ -38,20 +113,17 @@ export function connectLink(args: {
}, timeoutMs);
ws.on('open', () => ws.send(encode({ type: 'hello', secret: args.secret })));
ws.on('error', (e: unknown) => reject(e));
ws.on('error', (error: unknown) => reject(error));
ws.on('close', () => {
clearTimeout(connectTimer);
args.bus?.emit('mesh:disconnect', { name: args.url });
for (const [, p] of pending) {
clearTimeout(p.timer);
p.reject(new Error('mesh link closed'));
}
pending.clear();
rejectAllPending(pending, 'mesh link closed');
if (!manifest) reject(new Error(`mesh handshake failed: ${args.url}`));
});
ws.on('message', (data: unknown) => {
let frame: Frame;
try {
frame = decode(String(data));
} catch {
@@ -62,37 +134,12 @@ export function connectLink(args: {
manifest = { scopes: frame.scopes, routes: frame.routes };
clearTimeout(connectTimer);
args.bus?.emit('mesh:connect', { name: args.url });
resolve({
manifest,
rpc(kind, name, ctx) {
const id = `${connId}:${counter++}`;
return new Promise((res, rej) => {
const timer = setTimeout(() => {
pending.delete(id);
rej(new Error(`mesh rpc timeout: ${name}`));
}, timeoutMs);
pending.set(id, { resolve: res, reject: rej, timer });
ws.send(encode({ type: 'rpc-req', id, kind, name, ctx }));
});
},
close() {
ws.close();
},
});
resolve(buildLink(ws, pending, manifest, connId, timeoutMs));
return;
}
if (frame.type === 'rpc-res') {
const p = pending.get(frame.id);
if (!p) return;
pending.delete(frame.id);
clearTimeout(p.timer);
if (frame.ok) {
p.resolve(frame.result);
} else {
args.bus?.emit('mesh:rpc:error', { name: frame.id, error: frame.error });
p.reject(new HttpError(frame.error.status ?? 500, frame.error.message));
}
settleRpcResponse(pending, frame, args.bus);
}
});
});
+28 -10
View File
@@ -1,3 +1,4 @@
/** Serialized request context sent across the mesh for a scope or route RPC. */
export interface RequestEnvelope {
method: string;
params: Record<string, string>;
@@ -6,10 +7,23 @@ export interface RequestEnvelope {
headers: Record<string, string | string[] | undefined>;
}
export interface ScopeEntry { token: string; scope: 'app' | 'request' }
export interface RouteEntry { method: string; pattern: string }
export interface Manifest { scopes: ScopeEntry[]; routes: RouteEntry[] }
/** Manifest entry for an exported scope token and its lifetime. */
export interface ScopeEntry {
token: string;
scope: 'app' | 'request';
}
/** Manifest entry for an exported route. */
export interface RouteEntry {
method: string;
pattern: string;
}
/** A mesh server's advertised scopes and routes. */
export interface Manifest {
scopes: ScopeEntry[];
routes: RouteEntry[];
}
/** Discriminated union of every message on the mesh wire. */
export type Frame =
| { type: 'hello'; secret: string }
| { type: 'manifest'; scopes: ScopeEntry[]; routes: RouteEntry[] }
@@ -19,14 +33,18 @@ export type Frame =
const TYPES = new Set(['hello', 'manifest', 'rpc-req', 'rpc-res']);
export function encode(f: Frame): string {
return JSON.stringify(f);
/** Serialize a frame to a JSON wire string. */
export function encode(frame: Frame): string {
return JSON.stringify(frame);
}
export function decode(s: string): Frame {
const f = JSON.parse(s) as { type?: unknown };
if (typeof f.type !== 'string' || !TYPES.has(f.type)) {
throw new Error(`unknown frame type: ${String(f.type)}`);
/** Parse a wire string into a frame, throwing if the `type` tag is unknown. */
export function decode(json: string): Frame {
const parsed = JSON.parse(json) as { type?: unknown };
if (typeof parsed.type !== 'string' || !TYPES.has(parsed.type)) {
throw new Error(`unknown frame type: ${String(parsed.type)}`);
}
return f as Frame;
return parsed as Frame;
}
+27 -11
View File
@@ -2,9 +2,19 @@ import type { Link } from './link';
import type { RequestEnvelope } from './protocol';
import type { ResponseShape } from '../pipeline';
export interface RemoteScopeNode { name: string; run: (ctx: any) => Promise<Record<string, unknown>> }
export interface RemoteRoute { method: string; pattern: string; handler: (req: RequestEnvelope) => Promise<ResponseShape> }
/** Local proxy for a remote scope: runs the RPC and returns its token→value binding. */
export interface RemoteScopeNode {
name: string;
run: (ctx: any) => Promise<Record<string, unknown>>;
}
/** Local proxy for a remote route: forwards the request envelope over the link. */
export interface RemoteRoute {
method: string;
pattern: string;
handler: (req: RequestEnvelope) => Promise<ResponseShape>;
}
/** Extract a {@link RequestEnvelope} from a local request context for transmission over the mesh. */
export function envelopeFrom(ctx: any): RequestEnvelope {
return {
method: ctx?.req?.method ?? ctx?.method ?? 'GET',
@@ -15,21 +25,27 @@ export function envelopeFrom(ctx: any): RequestEnvelope {
};
}
export function buildRemote(link: Link, origin: string): {
providers: RemoteScopeNode[]; steps: RemoteScopeNode[]; routes: RemoteRoute[];
/** Turn a link's manifest into local proxy nodes: app-scope providers, request-scope steps, and routes. */
export function buildRemote(link: Link): {
providers: RemoteScopeNode[];
steps: RemoteScopeNode[];
routes: RemoteRoute[];
} {
const providers: RemoteScopeNode[] = [];
const steps: RemoteScopeNode[] = [];
for (const s of link.manifest.scopes) {
for (const scope of link.manifest.scopes) {
const node: RemoteScopeNode = {
name: s.token,
run: async (ctx: any) => ({ [s.token]: await link.rpc('scope', s.token, envelopeFrom(ctx)) }),
name: scope.token,
run: async (ctx: any) => ({ [scope.token]: await link.rpc('scope', scope.token, envelopeFrom(ctx)) }),
};
(s.scope === 'app' ? providers : steps).push(node);
(scope.scope === 'app' ? providers : steps).push(node);
}
const routes: RemoteRoute[] = link.manifest.routes.map((r) => ({
method: r.method, pattern: r.pattern,
handler: async (req: RequestEnvelope) => (await link.rpc('route', r.pattern, req)) as ResponseShape,
const routes: RemoteRoute[] = link.manifest.routes.map((route) => ({
method: route.method,
pattern: route.pattern,
handler: async (req: RequestEnvelope) => (await link.rpc('route', route.pattern, req)) as ResponseShape,
}));
return { providers, steps, routes };
}
+91 -34
View File
@@ -4,12 +4,14 @@ import type { ResponseShape } from '../pipeline';
import { isHttpError } from '../signals';
import { encode, decode, type Manifest, type RequestEnvelope, type RouteEntry, type Frame } from './protocol';
/** WebSocket path where a teapot exposes its mesh control channel. */
export const MESH_CONTROL_PATH = '/__mesh__/control';
/** Assemble a {@link Manifest} from exported provider/step tokens and buffered routes. */
export function buildManifest(args: {
providers: string[]; // exported provider tokens (app-scope)
steps: string[]; // exported step tokens (request-scope)
routes: RouteEntry[]; // exported buffered routes
providers: string[]; // exported provider tokens (app-scope)
steps: string[]; // exported step tokens (request-scope)
routes: RouteEntry[]; // exported buffered routes
}): Manifest {
return {
scopes: [
@@ -20,13 +22,14 @@ export function buildManifest(args: {
};
}
function safeEqual(a: string, b: string): boolean {
const ba = Buffer.from(a);
const bb = Buffer.from(b);
if (ba.length !== bb.length) return false;
return crypto.timingSafeEqual(ba, bb);
function safeEqual(left: string, right: string): boolean {
const leftBuf = Buffer.from(left);
const rightBuf = Buffer.from(right);
if (leftBuf.length !== rightBuf.length) return false;
return crypto.timingSafeEqual(leftBuf, rightBuf);
}
/** Dependencies for the mesh control handler: shared secret, manifest, and scope/route resolvers. */
export interface MeshControlDeps {
secret: string;
manifest: Manifest;
@@ -35,9 +38,77 @@ export interface MeshControlDeps {
bus?: Bus;
}
/** The rpc-req member of the {@link Frame} union. */
type RpcReqFrame = Extract<Frame, { type: 'rpc-req' }>;
/** Build a 403 "not exported" error for an unknown scope/route token. */
function notExported(name: string): Error {
const error: any = new Error(`not exported: ${name}`);
error.status = 403;
return error;
}
/** Validate an unauthenticated hello frame; reply with the manifest on success or close on mismatch. */
function handleHandshake(ws: any, frame: Frame, deps: MeshControlDeps): boolean {
if (frame.type === 'hello' && safeEqual(frame.secret, deps.secret)) {
ws.send(encode({ type: 'manifest', scopes: deps.manifest.scopes, routes: deps.manifest.routes }));
deps.bus?.emit('mesh:connect', { name: 'teapot' });
return true;
}
ws.close(1008);
return false;
}
/** Resolve an authenticated rpc-req against the exported scopes/routes, enforcing export gating. */
function resolveRpc(
frame: RpcReqFrame,
deps: MeshControlDeps,
exportedScopes: Set<string>,
exportedRoutes: Set<string>,
): Promise<unknown> {
const { kind, name, ctx } = frame;
if (kind === 'scope') {
if (!exportedScopes.has(name)) throw notExported(name);
return deps.resolveScope(name, ctx);
}
if (![...exportedRoutes].some((key) => key.endsWith(` ${name}`))) throw notExported(name);
return deps.resolveRoute(name, ctx);
}
/** Serve one authenticated rpc-req: resolve it and frame the ok/error response back to the peer. */
async function handleRpc(
ws: any,
frame: RpcReqFrame,
deps: MeshControlDeps,
exportedScopes: Set<string>,
exportedRoutes: Set<string>,
): Promise<void> {
const { id, name } = frame;
try {
const result = await resolveRpc(frame, deps, exportedScopes, exportedRoutes);
ws.send(encode({ type: 'rpc-res', id, ok: true, result }));
} catch (err) {
const status = isHttpError(err) ? err.status : ((err as any)?.status ?? 500);
deps.bus?.emit('mesh:rpc:error', { name, error: err });
ws.send(encode({ type: 'rpc-res', id, ok: false, error: { message: (err as Error).message, status } }));
}
}
/** Build a WebSocket handler that authenticates peers and serves scope/route RPCs from the manifest. */
export function createMeshControl(deps: MeshControlDeps): { path: string; handle: (ws: any) => void } {
const exportedScopes = new Set(deps.manifest.scopes.map((s) => s.token));
const exportedRoutes = new Set(deps.manifest.routes.map((r) => `${r.method} ${r.pattern}`));
const exportedScopes = new Set(deps.manifest.scopes.map((scope) => scope.token));
const exportedRoutes = new Set(deps.manifest.routes.map((route) => `${route.method} ${route.pattern}`));
return {
path: MESH_CONTROL_PATH,
@@ -45,36 +116,22 @@ export function createMeshControl(deps: MeshControlDeps): { path: string; handle
let authed = false;
ws.on('message', async (data: unknown) => {
let frame: Frame;
try { frame = decode(String(data)); } catch { return; }
try {
frame = decode(String(data));
} catch {
return;
}
if (!authed) {
if (frame.type === 'hello' && safeEqual(frame.secret, deps.secret)) {
authed = true;
ws.send(encode({ type: 'manifest', scopes: deps.manifest.scopes, routes: deps.manifest.routes }));
deps.bus?.emit('mesh:connect', { name: 'teapot' });
} else {
ws.close(1008);
}
authed = handleHandshake(ws, frame, deps);
return;
}
if (frame.type !== 'rpc-req') return;
const { id, kind, name, ctx } = frame;
try {
let result: unknown;
if (kind === 'scope') {
if (!exportedScopes.has(name)) { const e: any = new Error(`not exported: ${name}`); e.status = 403; throw e; }
result = await deps.resolveScope(name, ctx);
} else {
if (![...exportedRoutes].some((k) => k.endsWith(` ${name}`))) { const e: any = new Error(`not exported: ${name}`); e.status = 403; throw e; }
result = await deps.resolveRoute(name, ctx);
}
ws.send(encode({ type: 'rpc-res', id, ok: true, result }));
} catch (err) {
const status = isHttpError(err) ? err.status : (err as any)?.status ?? 500;
deps.bus?.emit('mesh:rpc:error', { name, error: err });
ws.send(encode({ type: 'rpc-res', id, ok: false, error: { message: (err as Error).message, status } }));
}
await handleRpc(ws, frame, deps, exportedScopes, exportedRoutes);
});
ws.on('close', () => deps.bus?.emit('mesh:disconnect', { name: 'teapot' }));
},