diff --git a/src/mesh/teapot.ts b/src/mesh/teapot.ts new file mode 100644 index 0000000..e0e5496 --- /dev/null +++ b/src/mesh/teapot.ts @@ -0,0 +1,82 @@ +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'; + +export const MESH_CONTROL_PATH = '/__mesh__/control'; + +export function buildManifest(args: { + providers: string[]; // exported provider tokens (app-scope) + steps: string[]; // exported step tokens (request-scope) + routes: RouteEntry[]; // exported buffered routes +}): Manifest { + return { + scopes: [ + ...args.providers.map((token) => ({ token, scope: 'app' as const })), + ...args.steps.map((token) => ({ token, scope: 'request' as const })), + ], + routes: args.routes, + }; +} + +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); +} + +export interface MeshControlDeps { + secret: string; + manifest: Manifest; + resolveScope: (name: string, env: RequestEnvelope) => Promise; + resolveRoute: (name: string, env: RequestEnvelope) => Promise; + bus?: Bus; +} + +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}`)); + + return { + path: MESH_CONTROL_PATH, + handle(ws: any) { + let authed = false; + ws.on('message', async (data: unknown) => { + let frame: Frame; + 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); + } + 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 } })); + } + }); + ws.on('close', () => deps.bus?.emit('mesh:disconnect', { name: 'teapot' })); + }, + }; +} diff --git a/test/mesh/teapot.test.ts b/test/mesh/teapot.test.ts new file mode 100644 index 0000000..3ed2746 --- /dev/null +++ b/test/mesh/teapot.test.ts @@ -0,0 +1,84 @@ +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 { Unauthorized } from '../../src/signals'; + +const fakeWs = () => { + const ws: any = new EventEmitter(); + ws.sent = []; + ws.send = (s: string) => ws.sent.push(decode(s)); + ws.close = vi.fn(); + return ws; +}; + +describe('buildManifest', () => { + it('maps providers to app scope and steps to request scope', () => { + const m = buildManifest({ providers: ['config'], steps: ['auth'], routes: [{ method: 'GET', pattern: '/u/:id' }] }); + expect(m.scopes).toContainEqual({ token: 'config', scope: 'app' }); + expect(m.scopes).toContainEqual({ token: 'auth', scope: 'request' }); + expect(m.routes).toEqual([{ method: 'GET', pattern: '/u/:id' }]); + }); +}); + +describe('createMeshControl', () => { + const manifest = buildManifest({ providers: ['config'], steps: ['auth'], routes: [{ method: 'GET', pattern: '/u/:id' }] }); + const make = (over: Partial[0]> = {}) => createMeshControl({ + secret: 'good', manifest, + resolveScope: async (name) => ({ resolved: name }), + resolveRoute: async () => ({ status: 200, headers: {}, body: 'route-body' }), + ...over, + }); + + it('exposes the reserved control path', () => { + expect(make().path).toBe('/__mesh__/control'); + }); + + it('rejects a bad secret and closes', () => { + const ws = fakeWs(); make().handle(ws); + ws.emit('message', encode({ type: 'hello', secret: 'wrong' })); + expect(ws.close).toHaveBeenCalledWith(1008); + expect(ws.sent).toEqual([]); + }); + + it('answers a good hello with the manifest', () => { + const ws = fakeWs(); make().handle(ws); + ws.emit('message', encode({ type: 'hello', secret: 'good' })); + expect(ws.sent[0]).toMatchObject({ type: 'manifest', scopes: manifest.scopes }); + }); + + it('does NOT process rpc before handshake', async () => { + const ws = fakeWs(); make().handle(ws); + ws.emit('message', encode({ type: 'rpc-req', id: '1', kind: 'scope', name: 'config', ctx: {} as any })); + await new Promise((r) => setTimeout(r, 5)); + expect(ws.sent).toEqual([]); + }); + + 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: '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' } }); + }); + + 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: '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'); + expect(res.ok).toBe(false); + expect(res.error.status).toBe(403); + }); + + 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: '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'); + expect(res).toMatchObject({ id: '9', ok: false, error: { message: 'nope', status: 401 } }); + }); +});