feat(relay): rendezvous-relay service — 7 packages + plans (contracts/transport/agent/control-plane/e2e/auth/web)
Multi-tenant reverse-tunnel service ("ngrok for Claude Code" with E2E): a
host-agent dials OUT to an operator-run relay; external devices reach the host
THROUGH the relay, routed by per-tenant subdomain, forwarding ciphertext only
(the relay never sees plaintext). Lets a customer reach their own self-hosted
web-terminal from anywhere with zero networking setup.
Packages — all tsc-strict + vitest green (656 tests), cross-package integration verified:
- relay-contracts: frozen shared contracts (mux frame codec, data model,
capability token, E2E envelope, pairing) — the src/types.ts analog
- term-relay: native WS mux + stateless data plane (subdomain routing, ciphertext forward)
- agent: host-agent (pairing, per-host Ed25519 + mTLS dial-out, forwards to 127.0.0.1:3000)
- control-plane: accounts/hosts registry, pairing-code flow, routing table, provisioning
- relay-e2e: browser<->agent E2E (X25519 ECDH through relay, AEAD, anti-replay, recoverable replay key)
- relay-auth: Passkey/WebAuthn, capability tokens, per-host certs, deny-by-default tenant isolation
- relay-web: browser login + Web Crypto E2E + client-side preview rendering
Security invariants INV1-15 enforced; cross-tenant isolation CI tripwire live
(.github/workflows/relay-tripwire.yml). Design + implementation-level plans in
docs/PLAN_RELAY_*.md and docs/EXPLORE_RELAY_SERVICE.md.
NOTE: generated autonomously per the reviewed plans. The security-critical
packages (relay-e2e, relay-auth) REQUIRE expert security audit before any real
deployment — passing tests prove self-consistency, not resistance to attackers.
Base app (src/, public/) unchanged; concurrent desktop work left uncommitted.
This commit is contained in:
49
control-plane/src/routing/bus.ts
Normal file
49
control-plane/src/routing/bus.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* RevocationBus implementations over the FROZEN `relay:revocations` channel (INDEX §4.2 FIX 4).
|
||||
* P3 only PUBLISHES (P1 owns the subscriber that injects §4.1 CLOSE+RST / GOAWAY). Drain (T10)
|
||||
* and revoke (T13) use the SAME named channel. The KillSignal shape + channel name are imported
|
||||
* from relay-contracts and NEVER redefined.
|
||||
*/
|
||||
import {
|
||||
RELAY_REVOCATIONS_CHANNEL,
|
||||
KillSignalSchema,
|
||||
type KillSignal,
|
||||
type RevocationBus,
|
||||
} from 'relay-contracts'
|
||||
|
||||
/** In-memory bus with a subscribe hook — used by tests and single-process wiring. */
|
||||
export interface TestableRevocationBus extends RevocationBus {
|
||||
subscribe(handler: (signal: KillSignal) => void): () => void
|
||||
readonly channel: typeof RELAY_REVOCATIONS_CHANNEL
|
||||
}
|
||||
|
||||
export function createInMemoryRevocationBus(): TestableRevocationBus {
|
||||
const handlers = new Set<(signal: KillSignal) => void>()
|
||||
return {
|
||||
channel: RELAY_REVOCATIONS_CHANNEL,
|
||||
async publish(signal) {
|
||||
// Validate at the boundary before it hits the wire (INV10: reason is metadata only).
|
||||
const parsed = KillSignalSchema.parse(signal)
|
||||
for (const h of handlers) h(parsed as KillSignal)
|
||||
},
|
||||
subscribe(handler) {
|
||||
handlers.add(handler)
|
||||
return () => handlers.delete(handler)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/** Minimal publisher surface of an ioredis client (integration seam; typed, not unit-tested). */
|
||||
export interface RedisPublisher {
|
||||
publish(channel: string, message: string): Promise<number>
|
||||
}
|
||||
|
||||
/** Redis-backed publisher (production). P1 relay nodes SUBSCRIBE to the same channel. */
|
||||
export function createRedisRevocationBus(redis: RedisPublisher): RevocationBus {
|
||||
return {
|
||||
async publish(signal) {
|
||||
const parsed = KillSignalSchema.parse(signal)
|
||||
await redis.publish(RELAY_REVOCATIONS_CHANNEL, JSON.stringify(parsed))
|
||||
},
|
||||
}
|
||||
}
|
||||
67
control-plane/src/routing/nodes.ts
Normal file
67
control-plane/src/routing/nodes.ts
Normal file
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* T10 — relay-node registry + graceful drain (INV7). Every mutation is scoped to the caller's
|
||||
* authenticated `NodeIdentity`: a node can only register/heartbeat/drain ITSELF. Drain marks the
|
||||
* node 'draining', enumerates its live routes, and PUBLISHES a per-host `KillSignal` on the frozen
|
||||
* `relay:revocations` bus (INDEX §4.2 FIX 4 — SAME channel T13 revoke uses); P1 nodes translate it
|
||||
* into the §4.1 GOAWAY. This module does NOT encode the frame (that is P1). Drain touches NO
|
||||
* Postgres host/session row — the running task lives on the customer machine (PTY survives).
|
||||
*
|
||||
* OQ4 residual: the frozen RevocationScope has no `node` kind, so a single-node operator drain is
|
||||
* expressed as per-host KillSignals with a drain reason (flagged to the INDEX for a future scope).
|
||||
*/
|
||||
import type { RevocationBus } from 'relay-contracts'
|
||||
import type { NodeStore, RouteStore } from '../store/ports.js'
|
||||
import type { NodeIdentity } from '../node-auth/identity.js'
|
||||
import type { AuditWriter } from '../audit/log.js'
|
||||
import { noopAuditWriter } from '../audit/log.js'
|
||||
import { nowIso } from '../util/ids.js'
|
||||
|
||||
export const DRAIN_REASON = 'operatorDrain'
|
||||
|
||||
export interface NodeCoordinator {
|
||||
registerNode(caller: NodeIdentity, addr: string): Promise<void>
|
||||
nodeHeartbeat(caller: NodeIdentity): Promise<void>
|
||||
beginDrain(caller: NodeIdentity): Promise<{ readonly hostIds: readonly string[] }>
|
||||
completeDrain(caller: NodeIdentity): Promise<void>
|
||||
}
|
||||
|
||||
export interface NodeCoordinatorDeps {
|
||||
readonly nodes: NodeStore
|
||||
readonly routes: RouteStore
|
||||
readonly bus: RevocationBus
|
||||
readonly audit?: AuditWriter
|
||||
}
|
||||
|
||||
export function createNodeCoordinator(deps: NodeCoordinatorDeps): NodeCoordinator {
|
||||
const audit = deps.audit ?? noopAuditWriter()
|
||||
return {
|
||||
async registerNode(caller, addr) {
|
||||
await deps.nodes.upsert({ nodeId: caller.nodeId, addr, status: 'active', lastSeen: nowIso() })
|
||||
},
|
||||
async nodeHeartbeat(caller) {
|
||||
await deps.nodes.touch(caller.nodeId, nowIso())
|
||||
},
|
||||
async beginDrain(caller) {
|
||||
await deps.nodes.setStatus(caller.nodeId, 'draining')
|
||||
const routed = await deps.routes.listByNode(caller.nodeId)
|
||||
const at = Math.floor(Date.now() / 1000)
|
||||
for (const { hostId } of routed) {
|
||||
// Per-host KillSignal with a drain reason on the frozen bus (P1 emits GOAWAY).
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
await deps.bus.publish({ scope: { kind: 'host', hostId }, at, reason: DRAIN_REASON })
|
||||
}
|
||||
await audit.writeAuditEvent({
|
||||
action: 'node.drain',
|
||||
principalId: `node:${caller.nodeId}`,
|
||||
accountId: 'system',
|
||||
hostId: null,
|
||||
ts: nowIso(),
|
||||
meta: { nodeId: caller.nodeId, routes: String(routed.length) },
|
||||
})
|
||||
return { hostIds: routed.map((r) => r.hostId) }
|
||||
},
|
||||
async completeDrain(caller) {
|
||||
await deps.nodes.delete(caller.nodeId) // deregister after routes re-homed
|
||||
},
|
||||
}
|
||||
}
|
||||
62
control-plane/src/routing/table.ts
Normal file
62
control-plane/src/routing/table.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* T9 — Redis routing table (`route:{host_id}`, heartbeat-TTL, INV7). Redis holds only LOCATION,
|
||||
* never ownership or secrets; a missing/expired key fails CLOSED (host treated offline). Every
|
||||
* mutation is scoped to the AUTHENTICATED node identity: a node can only route hosts to ITSELF
|
||||
* (`entry.relayNodeId === caller.nodeId`) and can only heartbeat/drop a route it currently holds.
|
||||
*/
|
||||
import type { RouteEntry } from '../model/records.js'
|
||||
import type { NodeStatus, RouteStore } from '../store/ports.js'
|
||||
import type { NodeIdentity } from '../node-auth/identity.js'
|
||||
|
||||
export class RouteAuthError extends Error {}
|
||||
|
||||
export interface RoutingTable {
|
||||
upsertRoute(caller: NodeIdentity, hostId: string, entry: RouteEntry, ttlSec: number): Promise<void>
|
||||
heartbeatRoute(caller: NodeIdentity, hostId: string, ttlSec: number): Promise<void>
|
||||
resolveRoute(hostId: string): Promise<RouteEntry | null>
|
||||
dropRoute(caller: NodeIdentity, hostId: string): Promise<void>
|
||||
/** System teardown path (drain/revoke) — bypasses the holding-node check by design. */
|
||||
systemDropRoute(hostId: string): Promise<void>
|
||||
}
|
||||
|
||||
export interface RoutingTableDeps {
|
||||
readonly routes: RouteStore
|
||||
/** Optional node-status hook: a draining node stops receiving new upserts (T10). */
|
||||
readonly nodeStatus?: (nodeId: string) => Promise<NodeStatus | null>
|
||||
}
|
||||
|
||||
export function createRoutingTable(deps: RoutingTableDeps): RoutingTable {
|
||||
return {
|
||||
async upsertRoute(caller, hostId, entry, ttlSec) {
|
||||
// A node may ONLY route hosts to itself — never inject a route for another node's id.
|
||||
if (entry.relayNodeId !== caller.nodeId) {
|
||||
throw new RouteAuthError('entry.relayNodeId must equal the authenticated caller nodeId')
|
||||
}
|
||||
if (deps.nodeStatus !== undefined) {
|
||||
const status = await deps.nodeStatus(caller.nodeId)
|
||||
if (status === 'draining') throw new RouteAuthError('node is draining; not accepting new routes')
|
||||
}
|
||||
await deps.routes.set(hostId, entry, ttlSec)
|
||||
},
|
||||
async heartbeatRoute(caller, hostId, ttlSec) {
|
||||
const current = await deps.routes.get(hostId)
|
||||
// A stale/foreign node cannot refresh (hijack) another node's live tunnel; missing ⇒ no-op.
|
||||
if (current === null || current.relayNodeId !== caller.nodeId) return
|
||||
await deps.routes.refreshTtl(hostId, ttlSec)
|
||||
},
|
||||
async resolveRoute(hostId) {
|
||||
return deps.routes.get(hostId) // null ⇒ offline (fails closed, INV7)
|
||||
},
|
||||
async dropRoute(caller, hostId) {
|
||||
const current = await deps.routes.get(hostId)
|
||||
if (current === null) return
|
||||
if (current.relayNodeId !== caller.nodeId) {
|
||||
throw new RouteAuthError('only the holding node may drop its route')
|
||||
}
|
||||
await deps.routes.delete(hostId)
|
||||
},
|
||||
async systemDropRoute(hostId) {
|
||||
await deps.routes.delete(hostId)
|
||||
},
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user