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:
Yaojia Wang
2026-07-02 06:10:16 +02:00
parent e4c327e25e
commit 2af57e6686
326 changed files with 40877 additions and 0 deletions

View File

@@ -0,0 +1,102 @@
import { describe, test, expect, beforeEach } from 'vitest'
import type { FastifyInstance } from 'fastify'
import { createMemoryStores } from '../src/store/memory.js'
import { buildControlPlane } from '../src/main.js'
import { loadEnv } from '../src/env.js'
import { generateEd25519 } from '../src/util/crypto.js'
import { buildCsr } from '../src/ca/csr.js'
import { bytesToBase64 } from '../src/util/bytes.js'
import { nodeIdentityFromRequest, type RequestWithTls } from '../src/node-auth/identity.js'
import type { CapabilityVerifier } from '../src/api/authz.js'
import type { CapabilityToken, CapabilityRight } from 'relay-contracts'
import type { Stores } from '../src/store/ports.js'
const ACCOUNT_A = '11111111-1111-4111-8111-111111111111'
const env = loadEnv({
PG_URL: 'postgres://u:p@localhost:5432/cp',
REDIS_URL: 'redis://localhost:6379',
CAPABILITY_SIGN_PUBKEY_B64: bytesToBase64(new Uint8Array(32).fill(1)),
CA_INTERMEDIATE_KMS_KEY_REF: 'kms://key/intermediate',
CA_INTERMEDIATE_CERT_PATH: '/etc/cp/int.pem',
NODE_MTLS_TRUST_BUNDLE_PATH: '/etc/cp/node-ca.pem',
BASE_DOMAIN: 'term.example.com',
})
const verifier: CapabilityVerifier = {
verify(raw, expectedAud, now): CapabilityToken {
if (raw !== 'tokenA') throw new Error('invalid token')
return { sub: ACCOUNT_A, aud: expectedAud, host: 'x', rights: ['manage'] as CapabilityRight[], iat: now, exp: now + 3600, jti: 'jti-A' }
},
}
let app: FastifyInstance
let stores: Stores
beforeEach(async () => {
stores = createMemoryStores()
const built = await buildControlPlane(env, { stores, verifier })
app = built.app
await app.ready()
})
const auth = { authorization: 'Bearer tokenA' }
describe('T11 provisioning API — remaining routes', () => {
test('POST /accounts creates an account (201)', async () => {
const res = await app.inject({ method: 'POST', url: '/accounts', headers: auth, payload: { plan: 'pro' } })
expect(res.statusCode).toBe(201)
expect(JSON.parse(res.body).plan).toBe('pro')
})
test('POST /accounts/:id/status suspends own account', async () => {
// must be the caller's own account id (A) — create A explicitly in store
const { createAccountRegistry } = await import('../src/registry/accounts.js')
const reg = createAccountRegistry({ accounts: stores.accounts })
await stores.accounts.insert({ accountId: ACCOUNT_A, plan: 'free', createdAt: new Date().toISOString(), status: 'active' })
void reg
const res = await app.inject({ method: 'POST', url: `/accounts/${ACCOUNT_A}/status`, headers: auth, payload: { status: 'suspended' } })
expect(res.statusCode).toBe(200)
expect(JSON.parse(res.body).status).toBe('suspended')
})
test('GET /accounts/:id/hosts returns ownership-scoped list', async () => {
const res = await app.inject({ method: 'GET', url: `/accounts/${ACCOUNT_A}/hosts`, headers: auth })
expect(res.statusCode).toBe(200)
expect(Array.isArray(JSON.parse(res.body))).toBe(true)
})
test('end-to-end enroll: issue code then POST /enroll → 201 EnrollResult', async () => {
const issued = await app.inject({ method: 'POST', url: `/accounts/${ACCOUNT_A}/pairing-codes`, headers: auth })
const code = JSON.parse(issued.body).code as string
const { publicKeyRaw, privateKey } = generateEd25519()
const res = await app.inject({
method: 'POST',
url: '/enroll',
payload: {
code,
agentPubkey: bytesToBase64(publicKeyRaw),
csr: bytesToBase64(buildCsr(privateKey, publicKeyRaw)),
},
})
expect(res.statusCode).toBe(201)
const body = JSON.parse(res.body)
expect(body.subdomain).toBeDefined()
expect(body.cert).toContain('BEGIN CERTIFICATE')
expect(typeof body.hostContentSecret).toBe('string')
})
})
describe('T9 nodeIdentityFromRequest wrapper', () => {
test('derives nodeId from an authorized TLS peer cert subject CN', () => {
const req: RequestWithTls = {
socket: { authorized: true, getPeerCertificate: () => ({ subject: { CN: 'spiffe://relay/node-7' } }) },
}
expect(nodeIdentityFromRequest(req).nodeId).toBe('spiffe://relay/node-7')
})
test('unauthenticated socket → 401', () => {
const req: RequestWithTls = { socket: { authorized: false, getPeerCertificate: () => undefined } }
expect(() => nodeIdentityFromRequest(req)).toThrow(/mutually authenticated/)
})
})