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,105 @@
/**
* T3 · Deny-by-default tenant authz core (INV1/INV3/INV6).
*
* The ONLY authorization path. There is NO `allow-if-unspecified` branch: the function returns 403
* unless every check passes. A host is resolved ONLY by a registry lookup keyed on the
* token-scoped `host_id` (never by raw addr/hostname). `account_id` comes from the token's
* authenticated `sub` (via `accountIdFromToken`) and `host.accountId` from the registry — never a
* client field. Single-use consumption is done by T12 AFTER a full allow, so T3 stays pure.
*/
import type { CapabilityRight, CapabilityToken } from 'relay-contracts'
import type {
AuthenticatedPrincipal,
HostRegistryPort,
SessionRegistryPort,
RevocationStore,
} from '../types.js'
import { verifyCapabilityToken, verifyDpopProof, type DpopContext } from '../capability/verify.js'
import { accountIdFromToken, principalFromToken } from './principal.js'
export type AuthzOutcome =
| {
readonly ok: true
readonly principal: AuthenticatedPrincipal
readonly hostId: string
readonly jti: string
}
| { readonly ok: false; readonly status: 401 | 403; readonly reason: string }
export interface ConnectRequest {
readonly capabilityRaw: string
readonly expectedAud: string
readonly requestedHostId: string
readonly requiredRight: CapabilityRight
}
export interface ReattachRequest extends ConnectRequest {
readonly sessionId: string
}
function deny(status: 401 | 403, reason: string): AuthzOutcome {
return { ok: false, status, reason }
}
/** Verify token + DPoP + revocation + rights + single-host + cross-tenant gate. Shared core. */
async function coreAuthorize(
req: ConnectRequest,
dpop: DpopContext,
hosts: HostRegistryPort,
revocation: RevocationStore,
now: number,
): Promise<{ outcome: AuthzOutcome; accountId?: string; token?: CapabilityToken }> {
let token: CapabilityToken
try {
token = await verifyCapabilityToken(req.capabilityRaw, req.expectedAud, now)
} catch {
return { outcome: deny(401, 'invalid_capability_token') }
}
if (!(await verifyDpopProof(token, dpop, now))) {
return { outcome: deny(401, 'dpop_proof_failed') }
}
if (await revocation.isRevoked(token.jti)) return { outcome: deny(403, 'token_revoked') }
if (!token.rights.includes(req.requiredRight)) return { outcome: deny(403, 'insufficient_rights') }
if (token.host !== req.requestedHostId) return { outcome: deny(403, 'host_scope_mismatch') }
const host = await hosts.getById(req.requestedHostId)
if (host === null) return { outcome: deny(403, 'unknown_host') }
if (host.status === 'revoked') return { outcome: deny(403, 'host_revoked') }
const tokenAccountId = accountIdFromToken(token) // == token.sub == principal.accountId
if (host.accountId !== tokenAccountId) {
return { outcome: deny(403, 'cross_tenant'), accountId: tokenAccountId, token } // THE INV1 gate
}
return {
outcome: { ok: true, principal: principalFromToken(token), hostId: host.hostId, jti: token.jti },
accountId: tokenAccountId,
token,
}
}
export async function authorizeConnect(
req: ConnectRequest,
dpop: DpopContext,
hosts: HostRegistryPort,
revocation: RevocationStore,
now: number,
): Promise<AuthzOutcome> {
return (await coreAuthorize(req, dpop, hosts, revocation, now)).outcome
}
export async function authorizeReattach(
req: ReattachRequest,
dpop: DpopContext,
hosts: HostRegistryPort,
sessions: SessionRegistryPort,
revocation: RevocationStore,
now: number,
): Promise<AuthzOutcome> {
const base = await coreAuthorize(req, dpop, hosts, revocation, now)
if (!base.outcome.ok) return base.outcome
// INV6 re-validate: session must exist AND belong to the same account.
const session = await sessions.getById(req.sessionId)
if (session === null || session.accountId !== base.accountId) {
return deny(403, 'cross_tenant_session')
}
return base.outcome
}

View File

@@ -0,0 +1,35 @@
/**
* T3 · The SINGLE resolver mapping a verified capability token → its authoritative `accountId`.
* Per the frozen T1 convention (CAP_TOKEN_SUB_IS_ACCOUNT_ID), `sub` IS the accountId. Kept as a
* named, greppable function so the cross-tenant gate (INV1) compares a value derived only from
* authenticated material — never a client field (INV3).
*/
import type { CapabilityToken, AuthenticatedPrincipal } from '../types.js'
export class AuthzInputError extends Error {
constructor(message: string) {
super(message)
this.name = 'AuthzInputError'
}
}
/** Returns `token.sub` (the accountId); throws on empty/malformed sub (deny-by-default input guard). */
export function accountIdFromToken(token: CapabilityToken): string {
const sub = token.sub
if (typeof sub !== 'string' || sub.length === 0) {
throw new AuthzInputError('capability token has empty/malformed sub')
}
return sub
}
/** Synthesize the token-derived principal for an allow outcome (account-scoped; INV3). */
export function principalFromToken(token: CapabilityToken): AuthenticatedPrincipal {
return {
kind: 'human',
accountId: accountIdFromToken(token),
principalId: accountIdFromToken(token),
amr: [],
authAt: token.iat,
stepUpAt: null,
}
}