feat(mesh): version the wire protocol and validate frame shapes

Cross-runtime mesh means peers are separate processes on separate deploy
cadences, so the frame union is a contract between green-tea versions rather
than an internal detail. There was no version field, and decode validated only
that `type` was a known tag before casting `parsed as Frame` — every other
field was trusted, so a skewed or malformed peer failed somewhere downstream
instead of at the boundary.

Add MESH_PROTOCOL_VERSION to the hello/manifest frames. Both ends refuse a
mismatch: the teapot checks the version *before* the secret, since a skewed
peer is not an auth failure and "wrong secret" would send its operator hunting
the wrong bug.

Validate fields per frame type via a Record keyed on the type tag, so a new
frame type must add a row. The lookup uses an own-property check: `type` is
peer-controlled and a bare lookup would resolve SHAPE['constructor'] up the
prototype chain to a truthy non-check.

This is a breaking wire change, done now because it is free exactly once —
mesh is alpha behind experimental:true and has no deployed peers. Adding a
version later would break every peer already in the field.

Refs .specs/2026-07-15-green-tea-mesh-cross-runtime-plan.md Task 1

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-07-15 14:47:35 -05:00
1 parent d56eeafcd8
commit dd0ea91a1b
6 files changed
+243 -38

No files matched your search

+14 -3
View File
@@ -1,6 +1,6 @@
import type { Bus } from '../bus';
import { HttpError } from '../signals';
import { encode, decode, type Manifest, type RequestEnvelope, type Frame } from './protocol';
import { encode, decode, MESH_PROTOCOL_VERSION, type Manifest, type RequestEnvelope, type Frame } from './protocol';
/** Client handle to a remote mesh server: its manifest, an RPC caller, and a close(). */
export interface Link {
@@ -105,7 +105,7 @@ export function connectLink(args: { url: string; secret: string; timeoutMs?: num
reject(new Error(`mesh connect timeout: ${args.url}`));
}, timeoutMs);
ws.on('open', () => ws.send(encode({ type: 'hello', secret: args.secret })));
ws.on('open', () => ws.send(encode({ type: 'hello', v: MESH_PROTOCOL_VERSION, secret: args.secret })));
ws.on('error', (error: unknown) => reject(error));
ws.on('close', () => {
clearTimeout(connectTimer);
@@ -124,8 +124,19 @@ export function connectLink(args: { url: string; secret: string; timeoutMs?: num
}
if (frame.type === 'manifest') {
manifest = { scopes: frame.scopes, routes: frame.routes };
clearTimeout(connectTimer);
if (frame.v !== MESH_PROTOCOL_VERSION) {
ws.close();
reject(
new Error(
`mesh protocol version mismatch at ${args.url}: teapot speaks v${frame.v}, this teacup speaks v${MESH_PROTOCOL_VERSION}`,
),
);
return;
}
manifest = { scopes: frame.scopes, routes: frame.routes };
args.bus?.emit('mesh:connect', { name: args.url });
resolve(buildLink(ws, pending, manifest, timeoutMs));
return;
+57 -10
View File
@@ -1,3 +1,11 @@
/**
* Version of the mesh wire protocol. Peers are separate processes on separate deploy
* cadences — possibly on different runtimes — so the frame shapes are a contract between
* green-tea versions, not an internal detail. Bump on any breaking frame change; peers
* refuse each other on mismatch rather than misparsing downstream.
*/
export const MESH_PROTOCOL_VERSION = 1;
/** Serialized request context sent across the mesh for a scope or route RPC. */
export interface RequestEnvelope {
method: string;
@@ -23,28 +31,67 @@ export interface Manifest {
routes: RouteEntry[];
}
/** Discriminated union of every message on the mesh wire. */
/** Discriminated union of every message on the mesh wire. The handshake frames carry `v`. */
export type Frame =
| { type: 'hello'; secret: string }
| { type: 'manifest'; scopes: ScopeEntry[]; routes: RouteEntry[] }
| { type: 'hello'; v: number; secret: string }
| { type: 'manifest'; v: number; scopes: ScopeEntry[]; routes: RouteEntry[] }
| { type: 'rpc-req'; id: string; kind: 'scope' | 'route'; name: string; ctx: RequestEnvelope }
| { type: 'rpc-res'; id: string; ok: true; result: unknown }
| { type: 'rpc-res'; id: string; ok: false; error: { message: string; status?: number } };
const TYPES = new Set(['hello', 'manifest', 'rpc-req', 'rpc-res']);
const isString = (value: unknown): value is string => typeof value === 'string';
const isNumber = (value: unknown): boolean => typeof value === 'number';
const isObject = (value: unknown): boolean => typeof value === 'object' && value !== null;
/** Rejects a frame whose fields don't match its `type` tag. `bad` always throws. */
type ShapeCheck = (frame: Record<string, unknown>, bad: (why: string) => never) => void;
/**
* Field checks per frame type. `decode` is the mesh's trust boundary: past it, frames are fed
* straight to the scope/route resolvers, so a bad shape must die here rather than surface as a
* confusing failure downstream. A new frame type must add a row — the compiler fails until it does.
*/
const SHAPE: Record<Frame['type'], ShapeCheck> = {
hello: (frame, bad) => {
if (!isNumber(frame.v)) bad('missing protocol version');
if (!isString(frame.secret)) bad('secret must be a string');
},
manifest: (frame, bad) => {
if (!isNumber(frame.v)) bad('missing protocol version');
if (!Array.isArray(frame.scopes) || !Array.isArray(frame.routes)) bad('scopes and routes must be arrays');
},
'rpc-req': (frame, bad) => {
if (!isString(frame.id)) bad('id must be a string');
if (frame.kind !== 'scope' && frame.kind !== 'route') bad("kind must be 'scope' or 'route'");
if (!isString(frame.name)) bad('name must be a string');
if (!isObject(frame.ctx)) bad('ctx must be an object');
},
'rpc-res': (frame, bad) => {
if (!isString(frame.id)) bad('id must be a string');
if (typeof frame.ok !== 'boolean') bad('ok must be a boolean');
if (frame.ok === false && !isObject(frame.error)) bad('error must be an object when ok is false');
},
};
/** Serialize a frame to a JSON wire string. */
export function encode(frame: Frame): string {
return JSON.stringify(frame);
}
/** Parse a wire string into a frame, throwing if the `type` tag is unknown. */
/** Parse a wire string into a frame, throwing if the `type` tag is unknown or the shape is malformed. */
export function decode(json: string): Frame {
const parsed = JSON.parse(json) as { type?: unknown };
const parsed = JSON.parse(json) as Record<string, unknown>;
const type = parsed.type;
// own-property check, not a bare lookup: `type` is peer-controlled, and SHAPE['constructor']
// would otherwise resolve up the prototype chain to a truthy non-check.
const known = isString(type) && Object.prototype.hasOwnProperty.call(SHAPE, type);
const check = known ? SHAPE[type as Frame['type']] : undefined;
if (typeof parsed.type !== 'string' || !TYPES.has(parsed.type)) {
throw new Error(`unknown frame type: ${String(parsed.type)}`);
}
if (!check) throw new Error(`unknown frame type: ${String(type)}`);
return parsed as Frame;
check(parsed, (why) => {
throw new Error(`malformed ${String(type)} frame: ${why}`);
});
return parsed as unknown as Frame;
}
+42 -8
View File
@@ -2,7 +2,15 @@ import crypto from 'crypto';
import type { Bus } from '../bus';
import type { ResponseShape } from '../pipeline';
import { isHttpError } from '../signals';
import { encode, decode, type Manifest, type RequestEnvelope, type RouteEntry, type Frame } from './protocol';
import {
encode,
decode,
MESH_PROTOCOL_VERSION,
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';
@@ -49,18 +57,44 @@ function notExported(name: string): Error {
return error;
}
/** Validate an unauthenticated hello frame; reply with the manifest on success or close on mismatch. */
/**
* Validate an unauthenticated hello frame; reply with the manifest on success or close on mismatch.
* The version is checked *before* the secret: a skewed peer is not an auth failure, and telling it
* "wrong secret" would send its operator hunting the wrong bug.
*/
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' });
if (frame.type !== 'hello') {
ws.close(1008);
return true;
return false;
}
ws.close(1008);
if (frame.v !== MESH_PROTOCOL_VERSION) {
ws.close(
1008,
`mesh protocol version mismatch: peer speaks v${frame.v}, this teapot speaks v${MESH_PROTOCOL_VERSION}`,
);
return false;
return false;
}
if (!safeEqual(frame.secret, deps.secret)) {
ws.close(1008);
return false;
}
ws.send(
encode({
type: 'manifest',
v: MESH_PROTOCOL_VERSION,
scopes: deps.manifest.scopes,
routes: deps.manifest.routes,
}),
);
deps.bus?.emit('mesh:connect', { name: 'teapot' });
return true;
}
/** Resolve an authenticated rpc-req against the exported scopes/routes, enforcing export gating. */