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:
42 files changed
+2619
-1170
No files matched your search
+91
-34
@@ -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' }));
|
||||
},
|
||||
|
||||
Reference in new issue
Block a user