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

+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;
}