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

+37 -3
View File
@@ -1,7 +1,9 @@
import { describe, it, expect } from 'vitest';
import { WebSocketServer } from 'ws';
import { connectLink } from '../../src/mesh/link';
import { encode, decode } from '../../src/mesh/protocol';
import { encode, decode, MESH_PROTOCOL_VERSION } from '../../src/mesh/protocol';
const V = MESH_PROTOCOL_VERSION;
const env = { method: 'GET', params: {}, query: {}, body: undefined, headers: {} };
@@ -13,7 +15,7 @@ function startTeapot(secret = 'good') {
ws.on('message', (d) => {
const f = decode(d.toString());
if (!authed) {
if (f.type === 'hello' && f.secret === secret) { authed = true; ws.send(encode({ type: 'manifest', scopes: [{ token: 'auth', scope: 'request' }], routes: [] })); }
if (f.type === 'hello' && f.secret === secret) { authed = true; ws.send(encode({ type: 'manifest', v: V, scopes: [{ token: 'auth', scope: 'request' }], routes: [] })); }
else ws.close(1008);
return;
}
@@ -33,7 +35,7 @@ function startSilentTeapot(secret = 'good') {
wss.on('connection', (ws) => {
ws.on('message', (d) => {
const f = decode(d.toString());
if (f.type === 'hello' && f.secret === secret) ws.send(encode({ type: 'manifest', scopes: [], routes: [] }));
if (f.type === 'hello' && f.secret === secret) ws.send(encode({ type: 'manifest', v: V, scopes: [], routes: [] }));
// ignore rpc-req entirely
});
});
@@ -41,7 +43,39 @@ function startSilentTeapot(secret = 'good') {
return { url: `ws://127.0.0.1:${port}/__mesh__/control`, close: () => wss.close() };
}
// teapot running a future protocol: handshakes, but answers with a skewed manifest
function startSkewedTeapot() {
const wss = new WebSocketServer({ port: 0 });
wss.on('connection', (ws) => {
ws.on('message', () => ws.send(encode({ type: 'manifest', v: V + 1, scopes: [], routes: [] } as any)));
});
const port = (wss.address() as any).port;
return { url: `ws://127.0.0.1:${port}/__mesh__/control`, close: () => wss.close() };
}
describe('connectLink', () => {
it('sends its protocol version in the hello', async () => {
const seen: any[] = [];
const wss = new WebSocketServer({ port: 0 });
wss.on('connection', (ws) =>
ws.on('message', (d) => {
seen.push(decode(d.toString()));
ws.send(encode({ type: 'manifest', v: V, scopes: [], routes: [] }));
}),
);
const url = `ws://127.0.0.1:${(wss.address() as any).port}/__mesh__/control`;
const link = await connectLink({ url, secret: 'good' });
expect(seen[0]).toMatchObject({ type: 'hello', v: V });
link.close();
wss.close();
});
it('refuses a teapot on a different protocol version', async () => {
const t = startSkewedTeapot();
await expect(connectLink({ url: t.url, secret: 'good', timeoutMs: 500 })).rejects.toThrow(/version/i);
t.close();
});
it('handshakes and exposes the manifest', async () => {
const t = startTeapot();
const link = await connectLink({ url: t.url, secret: 'good' });
+65 -6
View File
@@ -1,16 +1,22 @@
import { describe, it, expect } from 'vitest';
import { encode, decode, type Frame, type RequestEnvelope } from '../../src/mesh/protocol';
import { encode, decode, MESH_PROTOCOL_VERSION, type Frame, type RequestEnvelope } from '../../src/mesh/protocol';
const env: RequestEnvelope = { method: 'GET', params: { id: '1' }, query: {}, body: undefined, headers: {} };
const V = MESH_PROTOCOL_VERSION;
describe('protocol codec', () => {
it('round-trips each frame type', () => {
const frames: Frame[] = [
{ type: 'hello', secret: 's3cr3t' },
{ type: 'manifest', scopes: [{ token: 'auth', scope: 'request' }], routes: [{ method: 'GET', pattern: '/u/:id' }] },
{ type: 'rpc-req', id: 'c1:1', kind: 'scope', name: 'auth', ctx: env },
{ type: 'rpc-res', id: 'c1:1', ok: true, result: { id: 'u1' } },
{ type: 'rpc-res', id: 'c1:2', ok: false, error: { message: 'no', status: 401 } },
{ type: 'hello', v: V, secret: 's3cr3t' },
{
type: 'manifest',
v: V,
scopes: [{ token: 'auth', scope: 'request' }],
routes: [{ method: 'GET', pattern: '/u/:id' }],
},
{ type: 'rpc-req', id: '1', kind: 'scope', name: 'auth', ctx: env },
{ type: 'rpc-res', id: '1', ok: true, result: { id: 'u1' } },
{ type: 'rpc-res', id: '2', ok: false, error: { message: 'no', status: 401 } },
];
for (const f of frames) expect(decode(encode(f))).toEqual(f);
});
@@ -22,4 +28,57 @@ describe('protocol codec', () => {
it('throws on unknown frame type', () => {
expect(() => decode(JSON.stringify({ type: 'bogus' }))).toThrow(/unknown frame/i);
});
it.each(['constructor', 'toString', '__proto__', 'hasOwnProperty'])(
'treats inherited Object property %s as an unknown type, not a validator',
(type) => {
// `type` is peer-controlled; a bare SHAPE[type] lookup would walk the prototype chain
expect(() => decode(JSON.stringify({ type }))).toThrow(/unknown frame/i);
},
);
it('throws on a non-string type tag', () => {
expect(() => decode(JSON.stringify({ type: 42 }))).toThrow(/unknown frame/i);
expect(() => decode(JSON.stringify({}))).toThrow(/unknown frame/i);
});
});
describe('protocol versioning', () => {
it('carries the protocol version on the handshake frames', () => {
const hello = decode(encode({ type: 'hello', v: V, secret: 's' }));
const manifest = decode(encode({ type: 'manifest', v: V, scopes: [], routes: [] }));
expect(hello).toMatchObject({ v: V });
expect(manifest).toMatchObject({ v: V });
});
it('rejects a handshake frame with no version — an unversioned peer is not decodable', () => {
expect(() => decode(JSON.stringify({ type: 'hello', secret: 's' }))).toThrow(/malformed hello/i);
expect(() => decode(JSON.stringify({ type: 'manifest', scopes: [], routes: [] }))).toThrow(/malformed manifest/i);
});
});
describe('protocol field validation', () => {
// decode is the trust boundary: past it, teapot.ts feeds frames straight into
// resolveScope/resolveRoute. A bad shape must die here, not downstream.
it.each([
['hello without secret', { type: 'hello', v: V }],
['hello with non-string secret', { type: 'hello', v: V, secret: 42 }],
['manifest with non-array scopes', { type: 'manifest', v: V, scopes: 'nope', routes: [] }],
['rpc-req without id', { type: 'rpc-req', kind: 'scope', name: 'auth', ctx: env }],
['rpc-req without ctx', { type: 'rpc-req', id: '1', kind: 'scope', name: 'auth' }],
['rpc-req with unknown kind', { type: 'rpc-req', id: '1', kind: 'bogus', name: 'auth', ctx: env }],
['rpc-req without name', { type: 'rpc-req', id: '1', kind: 'scope', ctx: env }],
['rpc-res without id', { type: 'rpc-res', ok: true, result: 1 }],
['rpc-res with non-boolean ok', { type: 'rpc-res', id: '1', ok: 'yes' }],
['rpc-res error without an error payload', { type: 'rpc-res', id: '1', ok: false }],
])('rejects %s', (_label, frame) => {
expect(() => decode(JSON.stringify(frame))).toThrow(/malformed/i);
});
it('accepts a valid rpc-req unchanged', () => {
const frame: Frame = { type: 'rpc-req', id: '1', kind: 'route', name: '/u/:id', ctx: env };
expect(decode(encode(frame))).toEqual(frame);
});
});
+28 -8
View File
@@ -1,7 +1,9 @@
import { describe, it, expect, vi } from 'vitest';
import { EventEmitter } from 'events';
import { buildManifest, createMeshControl } from '../../src/mesh/teapot';
import { encode, decode } from '../../src/mesh/protocol';
import { encode, decode, MESH_PROTOCOL_VERSION } from '../../src/mesh/protocol';
const V = MESH_PROTOCOL_VERSION;
import { Unauthorized } from '../../src/signals';
const fakeWs = () => {
@@ -36,15 +38,33 @@ describe('createMeshControl', () => {
it('rejects a bad secret and closes', () => {
const ws = fakeWs(); make().handle(ws);
ws.emit('message', encode({ type: 'hello', secret: 'wrong' }));
ws.emit('message', encode({ type: 'hello', v: V, secret: 'wrong' }));
expect(ws.close).toHaveBeenCalledWith(1008);
expect(ws.sent).toEqual([]);
});
it('answers a good hello with the manifest', () => {
it('answers a good hello with the manifest, stamped with the protocol version', () => {
const ws = fakeWs(); make().handle(ws);
ws.emit('message', encode({ type: 'hello', secret: 'good' }));
expect(ws.sent[0]).toMatchObject({ type: 'manifest', scopes: manifest.scopes });
ws.emit('message', encode({ type: 'hello', v: V, secret: 'good' }));
expect(ws.sent[0]).toMatchObject({ type: 'manifest', v: V, scopes: manifest.scopes });
});
it('rejects a version-skewed peer before checking its secret, naming both versions', () => {
const ws = fakeWs(); make().handle(ws);
// correct secret, wrong protocol: must still be refused — and not as an auth failure
ws.emit('message', encode({ type: 'hello', v: V + 1, secret: 'good' } as any));
expect(ws.sent).toEqual([]);
const [code, reason] = ws.close.mock.calls[0];
expect(code).toBe(1008);
expect(reason).toContain(String(V));
expect(reason).toContain(String(V + 1));
});
it('refuses a version-skewed peer even when its secret is also wrong', () => {
const ws = fakeWs(); make().handle(ws);
ws.emit('message', encode({ type: 'hello', v: V + 1, secret: 'wrong' } as any));
expect(ws.sent).toEqual([]);
expect(ws.close).toHaveBeenCalled();
});
it('does NOT process rpc before handshake', async () => {
@@ -56,7 +76,7 @@ describe('createMeshControl', () => {
it('resolves an exported scope after handshake', async () => {
const ws = fakeWs(); make().handle(ws);
ws.emit('message', encode({ type: 'hello', secret: 'good' }));
ws.emit('message', encode({ type: 'hello', v: V, secret: 'good' }));
ws.emit('message', encode({ type: 'rpc-req', id: '7', kind: 'scope', name: 'config', ctx: {} as any }));
await new Promise((r) => setTimeout(r, 5));
expect(ws.sent.find((f: any) => f.type === 'rpc-res')).toEqual({ type: 'rpc-res', id: '7', ok: true, result: { resolved: 'config' } });
@@ -64,7 +84,7 @@ describe('createMeshControl', () => {
it('rejects an unexported scope', async () => {
const ws = fakeWs(); make().handle(ws);
ws.emit('message', encode({ type: 'hello', secret: 'good' }));
ws.emit('message', encode({ type: 'hello', v: V, secret: 'good' }));
ws.emit('message', encode({ type: 'rpc-req', id: '8', kind: 'scope', name: 'secretsvc', ctx: {} as any }));
await new Promise((r) => setTimeout(r, 5));
const res: any = ws.sent.find((f: any) => f.type === 'rpc-res');
@@ -75,7 +95,7 @@ describe('createMeshControl', () => {
it('propagates a thrown HttpError status in the error frame', async () => {
const ws = fakeWs();
make({ resolveScope: async () => { throw new Unauthorized('nope'); } }).handle(ws);
ws.emit('message', encode({ type: 'hello', secret: 'good' }));
ws.emit('message', encode({ type: 'hello', v: V, secret: 'good' }));
ws.emit('message', encode({ type: 'rpc-req', id: '9', kind: 'scope', name: 'config', ctx: {} as any }));
await new Promise((r) => setTimeout(r, 5));
const res: any = ws.sent.find((f: any) => f.type === 'rpc-res');