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,150 @@
import { describe, it, expect, beforeEach } from 'vitest'
import { onUpgrade, onReattach, type EnforceDeps, type UpgradeContext } from '../src/index.js'
import { verifyCapabilityToken, resetDpopCacheForTest } from '../src/capability/verify.js'
import { needsStepUp } from '../src/human/stepup/stepup.js'
import type { StepUpPolicy } from '../src/types.js'
import {
setupP5SigningKey,
makeHost,
principal,
fakeHostRegistry,
fakeSessionRegistry,
fakeRevocationStore,
fakeTokenBucket,
fakeAuditSink,
issueWithDpop,
uuid,
} from './_helpers.js'
const NOW = 1_700_000_000
const AUD_A = 'alice.term.example.com'
const ORIGIN_A = `https://${AUD_A}`
const ALLOWED = [ORIGIN_A]
const NEVER_REQUIRED: StepUpPolicy = { maxAgeSeconds: Number.MAX_SAFE_INTEGER, requiredMethod: 'passkey' }
describe('enforcement onUpgrade/onReattach (T12)', () => {
let signingKey: CryptoKey
let hostA: string
let deps: EnforceDeps
let rev: ReturnType<typeof fakeRevocationStore>
let audit: ReturnType<typeof fakeAuditSink>
beforeEach(async () => {
;({ signingKey } = await setupP5SigningKey())
resetDpopCacheForTest()
hostA = uuid()
rev = fakeRevocationStore()
audit = fakeAuditSink()
deps = {
hosts: fakeHostRegistry([makeHost('acct-A', hostA)]),
sessions: fakeSessionRegistry([]),
revocation: rev,
buckets: fakeTokenBucket(),
audit,
stepUpPolicyFor: () => NEVER_REQUIRED,
}
})
function ctxFor(bundle: { raw: string; dpop: UpgradeContext['dpop'] }, over: Partial<UpgradeContext> = {}): UpgradeContext {
return {
capabilityRaw: bundle.raw,
originHeader: ORIGIN_A,
expectedAud: AUD_A,
requestedHostId: hostA,
requiredRight: 'attach',
remoteAddrHash: 'ip-hash',
activeSessionCount: 0,
dpop: bundle.dpop,
principal: null,
...over,
}
}
it('foreign Origin → 401 even with a valid token (INV15 retained)', async () => {
const b = await issueWithDpop(signingKey, { accountId: 'acct-A', host: hostA, aud: AUD_A, now: NOW })
const out = await onUpgrade(ctxFor(b, { originHeader: 'https://evil.com' }), deps, ALLOWED, NOW)
expect(out).toMatchObject({ ok: false, status: 401, reason: 'bad_origin' })
expect(audit.events).toHaveLength(1)
expect(audit.events[0]!.outcome).toBe('deny')
})
it('valid Origin, no/garbage token → 401', async () => {
const out = await onUpgrade(ctxFor({ raw: 'garbage', dpop: { proofJws: 'a.b.c', htu: 'h', htm: 'GET' } }), deps, ALLOWED, NOW)
expect(out).toMatchObject({ ok: false, status: 401 })
})
it('cross-tenant (A token, host B) → 403 with exactly one cross-tenant-attempt audit event', async () => {
const hostB = uuid()
deps = { ...deps, hosts: fakeHostRegistry([makeHost('acct-B', hostB)]) }
const b = await issueWithDpop(signingKey, { accountId: 'acct-A', host: hostB, aud: AUD_A, now: NOW })
const out = await onUpgrade(ctxFor(b, { requestedHostId: hostB }), deps, ALLOWED, NOW)
expect(out).toMatchObject({ ok: false, status: 403, reason: 'cross_tenant' })
expect(audit.events).toHaveLength(1)
expect(audit.events[0]!.action).toBe('cross-tenant-attempt')
})
it('pre-auth throttle fires BEFORE token verification (Finding-5)', async () => {
const buckets = fakeTokenBucket()
buckets.blocked.add('preauth:ip:ip-hash')
deps = { ...deps, buckets }
// even a totally invalid token is thrown out at the pre-auth stage
const out = await onUpgrade(ctxFor({ raw: 'garbage', dpop: { proofJws: 'a.b.c', htu: 'h', htm: 'GET' } }), deps, ALLOWED, NOW)
expect(out).toMatchObject({ ok: false, status: 403, reason: 'pre_auth_throttled' })
})
it('per-account rate-limited → deny', async () => {
const buckets = fakeTokenBucket()
buckets.blocked.add('connect:acct:acct-A')
deps = { ...deps, buckets }
const b = await issueWithDpop(signingKey, { accountId: 'acct-A', host: hostA, aud: AUD_A, now: NOW })
const out = await onUpgrade(ctxFor(b), deps, ALLOWED, NOW)
expect(out).toMatchObject({ ok: false, status: 403, reason: 'rate_limited' })
})
it('replayed single-use token (jti already consumed) → 403 token_replayed', async () => {
const b = await issueWithDpop(signingKey, { accountId: 'acct-A', host: hostA, aud: AUD_A, now: NOW })
const tok = await verifyCapabilityToken(b.raw, AUD_A, NOW)
await rev.consumeOnce(tok.jti, tok.exp) // pre-consume
const out = await onUpgrade(ctxFor(b), deps, ALLOWED, NOW)
expect(out).toMatchObject({ ok: false, status: 403, reason: 'token_replayed' })
})
it('happy path → ok:true with an allow audit event', async () => {
const b = await issueWithDpop(signingKey, { accountId: 'acct-A', host: hostA, aud: AUD_A, now: NOW })
const out = await onUpgrade(ctxFor(b), deps, ALLOWED, NOW)
expect(out.ok).toBe(true)
expect(audit.events).toHaveLength(1)
expect(audit.events[0]!.outcome).toBe('allow')
expect(audit.events[0]!.action).toBe('attach')
})
it('reattach to a foreign session → 403', async () => {
const sessionB = uuid()
deps = { ...deps, sessions: fakeSessionRegistry([{ sessionId: sessionB, hostId: uuid(), accountId: 'acct-B' }]) }
const b = await issueWithDpop(signingKey, { accountId: 'acct-A', host: hostA, aud: AUD_A, now: NOW })
const out = await onReattach({ ...ctxFor(b), sessionId: sessionB }, deps, ALLOWED, NOW)
expect(out).toMatchObject({ ok: false, status: 403, reason: 'cross_tenant_session' })
})
describe('v0.10 step-up augmentation (Finding-3)', () => {
const STRICT: StepUpPolicy = { maxAgeSeconds: 300, requiredMethod: 'passkey' }
it('fresh login but stale step-up → 403 step_up_required at onUpgrade', async () => {
deps = { ...deps, stepUpPolicyFor: () => STRICT }
const b = await issueWithDpop(signingKey, { accountId: 'acct-A', host: hostA, aud: AUD_A, now: NOW })
const freshLogin = principal('acct-A', { authAt: NOW, stepUpAt: null, amr: ['passkey'] })
const out = await onUpgrade(ctxFor(b, { principal: freshLogin }), deps, ALLOWED, NOW)
expect(out).toMatchObject({ ok: false, status: 403, reason: 'step_up_required' })
expect(audit.events.some((e) => e.action === 'stepup' && e.outcome === 'deny')).toBe(true)
})
it('after a fresh step-up the same request → ok:true', async () => {
deps = { ...deps, stepUpPolicyFor: () => STRICT }
const b = await issueWithDpop(signingKey, { accountId: 'acct-A', host: hostA, aud: AUD_A, now: NOW })
const steppedUp = principal('acct-A', { authAt: NOW, stepUpAt: NOW, amr: ['passkey', 'stepup'] })
expect(needsStepUp(steppedUp, STRICT, NOW)).toBe(false)
const out = await onUpgrade(ctxFor(b, { principal: steppedUp }), deps, ALLOWED, NOW)
expect(out.ok).toBe(true)
})
})
})