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,163 @@
/**
* T7 · OIDC SSO for teams — auth-code flow + PKCE, with `state`/`nonce` validation. PKCE is
* mandatory; the issuer allow-list comes from config (validated at startup, INV9). `account_id` is
* derived from the verified `(iss, sub)` mapping via an INJECTED resolver — never from a client
* claim (INV3). The JIT-vs-pre-linked mapping policy is PLAN §5 open-Q #2 (surfaced to P3), so P5
* does not hard-code it: the resolver is supplied by the caller/config.
*/
import { createPublicKey, verify as cryptoVerify, type webcrypto } from 'node:crypto'
type JsonWebKey = webcrypto.JsonWebKey
import { decodeBase64UrlString, decodeBase64UrlBytes } from 'relay-contracts'
import type { OidcIdentity } from '../../types.js'
export interface OidcConfig {
readonly issuer: string
readonly clientId: string
readonly redirectUri: string
readonly scopes: readonly string[]
readonly authorizationEndpoint: string
readonly tokenEndpoint: string
readonly jwks: readonly (JsonWebKey & { kid?: string; alg?: string })[]
readonly allowedIssuers?: readonly string[]
/** (iss, sub) → accountId. Policy (JIT vs pre-linked) is P3-owned (open-Q #2). */
resolveAccount(issuer: string, subject: string): Promise<string>
}
export interface OidcTokenSet {
readonly accessToken: string
readonly idToken: string
readonly tokenType: string
readonly expiresIn?: number
readonly refreshToken?: string
}
export class OidcError extends Error {
constructor(message: string) {
super(message)
this.name = 'OidcError'
}
}
export function buildAuthUrl(
cfg: OidcConfig,
state: string,
nonce: string,
codeChallenge: string,
): string {
const u = new URL(cfg.authorizationEndpoint)
u.searchParams.set('response_type', 'code')
u.searchParams.set('client_id', cfg.clientId)
u.searchParams.set('redirect_uri', cfg.redirectUri)
u.searchParams.set('scope', cfg.scopes.join(' '))
u.searchParams.set('state', state)
u.searchParams.set('nonce', nonce)
u.searchParams.set('code_challenge', codeChallenge)
u.searchParams.set('code_challenge_method', 'S256')
return u.toString()
}
export type FetchLike = (url: string, init: RequestInit) => Promise<Response>
export async function exchangeCode(
cfg: OidcConfig,
code: string,
codeVerifier: string,
fetchImpl: FetchLike = fetch,
): Promise<OidcTokenSet> {
const body = new URLSearchParams({
grant_type: 'authorization_code',
code,
redirect_uri: cfg.redirectUri,
client_id: cfg.clientId,
code_verifier: codeVerifier,
})
const res = await fetchImpl(cfg.tokenEndpoint, {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
body: body.toString(),
})
if (!res.ok) throw new OidcError(`token endpoint returned ${res.status}`)
const json = (await res.json()) as Record<string, unknown>
if (typeof json.id_token !== 'string' || typeof json.access_token !== 'string') {
throw new OidcError('token response missing id_token/access_token')
}
return {
accessToken: json.access_token,
idToken: json.id_token,
tokenType: typeof json.token_type === 'string' ? json.token_type : 'Bearer',
...(typeof json.expires_in === 'number' ? { expiresIn: json.expires_in } : {}),
...(typeof json.refresh_token === 'string' ? { refreshToken: json.refresh_token } : {}),
}
}
interface JwtHeader {
readonly alg: string
readonly kid?: string
}
interface JwtClaims {
readonly iss: string
readonly aud: string | readonly string[]
readonly sub: string
readonly exp: number
readonly nonce?: string
}
function decodeSegment<T>(seg: string): T {
return JSON.parse(decodeBase64UrlString(seg)) as T
}
function verifyJwtSignature(
header: JwtHeader,
signingInput: string,
signature: Uint8Array,
jwks: OidcConfig['jwks'],
): boolean {
const jwk = jwks.find((k) => (header.kid === undefined ? true : k.kid === header.kid))
if (jwk === undefined) return false
const key = createPublicKey({ key: jwk as JsonWebKey, format: 'jwk' })
const data = Buffer.from(signingInput)
if (header.alg === 'RS256') {
return cryptoVerify('RSA-SHA256', data, key, signature)
}
if (header.alg === 'ES256') {
return cryptoVerify('sha256', data, { key, dsaEncoding: 'ieee-p1363' }, signature)
}
return false // no alg:none, no unexpected algs
}
/** Verify id_token: signature + iss allow-list + aud + exp + nonce; map (iss,sub) → accountId. */
export async function verifyIdToken(
cfg: OidcConfig,
idToken: string,
expectedNonce: string,
now: number,
): Promise<OidcIdentity> {
const parts = idToken.split('.')
if (parts.length !== 3) throw new OidcError('malformed id_token')
const [h, p, s] = parts as [string, string, string]
const header = decodeSegment<JwtHeader>(h)
const claims = decodeSegment<JwtClaims>(p)
const allowed = cfg.allowedIssuers ?? [cfg.issuer]
if (!allowed.includes(claims.iss)) throw new OidcError('issuer not in allow-list')
const aud = Array.isArray(claims.aud) ? claims.aud : [claims.aud]
if (!aud.includes(cfg.clientId)) throw new OidcError('aud mismatch')
if (typeof claims.exp !== 'number' || claims.exp <= now) throw new OidcError('id_token expired')
if (claims.nonce !== expectedNonce) throw new OidcError('nonce mismatch (replay)')
let sig: Uint8Array
try {
sig = decodeBase64UrlBytes(s)
} catch {
throw new OidcError('bad signature encoding')
}
if (!verifyJwtSignature(header, `${h}.${p}`, sig, cfg.jwks)) {
throw new OidcError('id_token signature verification failed')
}
const accountId = await cfg.resolveAccount(claims.iss, claims.sub)
return { issuer: claims.iss, subject: claims.sub, accountId }
}
/** state/nonce/PKCE-verifier CSPRNG helpers. */
export { randomUrlToken, pkceChallenge } from './pkce.js'

View File

@@ -0,0 +1,14 @@
/** PKCE + state/nonce helpers (CSPRNG). */
import { randomBytes, createHash } from 'node:crypto'
import { encodeBase64UrlBytes } from 'relay-contracts'
/** A random base64url token for `state`/`nonce`/`code_verifier`. */
export function randomUrlToken(bytes = 32): string {
return encodeBase64UrlBytes(new Uint8Array(randomBytes(bytes)))
}
/** S256 code challenge = base64url(SHA-256(code_verifier)). */
export function pkceChallenge(codeVerifier: string): string {
const digest = createHash('sha256').update(codeVerifier).digest()
return encodeBase64UrlBytes(new Uint8Array(digest))
}

View File

@@ -0,0 +1,45 @@
/**
* T8 · Step-up auth before OPENING a session (not just at login). A fresh login is NOT sufficient:
* before dropping into a live root-capable shell, presence must be re-asserted. Enforced in T12's
* `onUpgrade`/`onReattach` (v0.10 augmentation), not merely asserted in prose (Finding-3).
*
* `hostContentSecret` browser-delivery gate (§4.5 / FIX 3): a fresh step-up here is ALSO the gate
* for releasing the host-scoped content secret to an authorized browser device (unwrapped only when
* `needsStepUp` is false). P5 does not mint/wrap it (P3 mints+wraps at BIND, P2 unwraps for the
* agent) — P5 only performs the step-up-gated release; a revoked host/device (T10) can no longer
* obtain it (INV12). See PLAN §T8.
*/
import type { HostRecord } from 'relay-contracts'
import type { AuthMethod, AuthenticatedPrincipal, StepUpPolicy } from '../../types.js'
export const DEFAULT_STEPUP_MAX_AGE_SECONDS = 300 as const
/** Per-host step-up freshness requirement (default: recent passkey step-up). */
export function policyForHost(_host: HostRecord): StepUpPolicy {
return { maxAgeSeconds: DEFAULT_STEPUP_MAX_AGE_SECONDS, requiredMethod: 'passkey' }
}
/**
* true when step-up is required: never stepped up, OR the last step-up is stale, OR the required
* method is not present in `amr` — i.e. a fresh login alone does NOT satisfy it.
*/
export function needsStepUp(
principal: AuthenticatedPrincipal,
policy: StepUpPolicy,
now: number,
): boolean {
if (principal.stepUpAt === null) return true
if (now - principal.stepUpAt > policy.maxAgeSeconds) return true
if (!principal.amr.includes(policy.requiredMethod)) return true
return false
}
/** Returns a NEW principal with `stepUpAt = now` and `method` added to `amr` (immutable). */
export function recordStepUp(
principal: AuthenticatedPrincipal,
method: AuthMethod,
now: number,
): AuthenticatedPrincipal {
const amr = principal.amr.includes(method) ? principal.amr : [...principal.amr, method]
return { ...principal, amr, stepUpAt: now }
}

View File

@@ -0,0 +1,94 @@
/**
* T6 · TOTP fallback (RFC 6238, HMAC-SHA1). NEVER SMS (SIM-swap → shell = catastrophic). The
* secret is stored ENCRYPTED at rest (INV5) and decrypted only in-process. A 6-digit code has only
* 10^6 space, so a per-account failed-attempt lockout (Finding-6, via T11's TokenBucketStore keyed
* on the authenticated accountId, INV3) is MANDATORY — it closes the brute-force hole.
*/
import { createHmac, randomBytes } from 'node:crypto'
import type { RateLimitPolicy, TokenBucketStore } from '../../types.js'
const DIGITS = 6
const STEP_SECONDS = 30
const SECRET_BYTES = 20
const BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
function base32Encode(bytes: Uint8Array): string {
let bits = 0
let value = 0
let out = ''
for (const b of bytes) {
value = (value << 8) | b
bits += 8
while (bits >= 5) {
out += BASE32_ALPHABET[(value >>> (bits - 5)) & 31]
bits -= 5
}
}
if (bits > 0) out += BASE32_ALPHABET[(value << (5 - bits)) & 31]
return out
}
function counterBytes(counter: number): Buffer {
const buf = Buffer.alloc(8)
buf.writeBigUInt64BE(BigInt(counter))
return buf
}
function hotp(secret: Uint8Array, counter: number): string {
const mac = createHmac('sha1', Buffer.from(secret)).update(counterBytes(counter)).digest()
const offset = mac[mac.length - 1]! & 0x0f
const bin =
((mac[offset]! & 0x7f) << 24) |
((mac[offset + 1]! & 0xff) << 16) |
((mac[offset + 2]! & 0xff) << 8) |
(mac[offset + 3]! & 0xff)
return (bin % 10 ** DIGITS).toString().padStart(DIGITS, '0')
}
export function generateTotpSecret(): { secret: Uint8Array; otpauthUri: string } {
const secret = new Uint8Array(randomBytes(SECRET_BYTES))
const b32 = base32Encode(secret)
const otpauthUri = `otpauth://totp/relay?secret=${b32}&algorithm=SHA1&digits=${DIGITS}&period=${STEP_SECONDS}`
return { secret, otpauthUri }
}
/** Verify a code within ±`window` steps (default ±1). Malformed codes → false. */
export function verifyTotp(secret: Uint8Array, code: string, now: number, window = 1): boolean {
if (!/^\d{6}$/.test(code)) return false
const step = Math.floor(now / STEP_SECONDS)
for (let w = -window; w <= window; w++) {
// constant-time-ish compare not required here (codes are 6 digits, rate-limited)
if (hotp(secret, step + w) === code) return true
}
return false
}
const BUCKET_KEY = (accountId: string) => `totp:fail:${accountId}`
/**
* Attempt gate (Finding-6): consumes one unit per verification attempt; false = locked out (deny
* WITHOUT checking the code). burst = policy.totpMaxFailsPerWindow, refilling over the window.
*/
export function checkTotpAttemptRate(
accountId: string,
policy: RateLimitPolicy,
store: TokenBucketStore,
now: number,
): Promise<boolean> {
const burst = policy.totpMaxFailsPerWindow
const refill = burst / policy.totpLockoutWindowSec
return store.take(BUCKET_KEY(accountId), refill, burst, now)
}
/**
* Record a failed attempt — drains an extra unit so bad guesses count more heavily toward lockout
* (escalating backoff). Uses the same failure bucket (already sized by `checkTotpAttemptRate`).
*/
export async function recordTotpFailure(
accountId: string,
store: TokenBucketStore,
now: number,
): Promise<void> {
// Params here are ignored by an already-initialized bucket; a fresh key defaults conservatively.
await store.take(BUCKET_KEY(accountId), 5 / 300, 5, now)
}

View File

@@ -0,0 +1,60 @@
/**
* T5 · Passkey/WebAuthn authentication ceremony. Enforces single-use challenge, origin/rpId
* binding, and the signCount-regression guard (a counter that goes backwards signals a cloned
* authenticator → reject). Yields an `AuthenticatedPrincipal` with `amr:['passkey']`.
*/
import { randomBytes } from 'node:crypto'
import { encodeBase64UrlBytes } from 'relay-contracts'
import type { AuthenticatedPrincipal, WebAuthnCredential } from '../../types.js'
import {
WebAuthnError,
type AuthenticationOptions,
type AuthenticationResponse,
type WebAuthnVerifier,
} from './verifier.js'
const CHALLENGE_BYTES = 32
const DEFAULT_TIMEOUT_MS = 60_000
export function startAuthentication(_accountId: string, rpId: string): Promise<AuthenticationOptions> {
return Promise.resolve({
rpId,
challenge: encodeBase64UrlBytes(new Uint8Array(randomBytes(CHALLENGE_BYTES))),
timeoutMs: DEFAULT_TIMEOUT_MS,
})
}
export async function finishAuthentication(
cred: WebAuthnCredential,
resp: AuthenticationResponse,
expectedChallenge: string,
rpId: string,
origin: string,
verifier: WebAuthnVerifier,
now: number,
): Promise<AuthenticatedPrincipal> {
if (resp.clientChallenge !== expectedChallenge) throw new WebAuthnError('challenge mismatch')
if (resp.origin !== origin) throw new WebAuthnError('origin mismatch')
if (resp.rpId !== rpId) throw new WebAuthnError('rpId mismatch')
const result = await verifier.verifyAuthentication(
resp,
expectedChallenge,
rpId,
origin,
cred.signCount,
)
if (!result.verified) throw new WebAuthnError('assertion not verified')
if (result.newSignCount <= cred.signCount && !(result.newSignCount === 0 && cred.signCount === 0)) {
throw new WebAuthnError('signCount regression (cloned authenticator)')
}
return {
kind: 'human',
accountId: cred.accountId,
principalId: cred.credentialId,
amr: ['passkey'],
authAt: now,
stepUpAt: null,
}
}

View File

@@ -0,0 +1,55 @@
/**
* T5 · Passkey/WebAuthn registration ceremony. Passkey is PRIMARY (phishing-resistant; the payload
* is a root-capable shell). Challenges are CSPRNG, short-TTL, single-use, never logged (INV9).
*/
import { randomBytes } from 'node:crypto'
import { encodeBase64UrlBytes } from 'relay-contracts'
import type { WebAuthnCredential } from '../../types.js'
import {
WebAuthnError,
type RegistrationOptions,
type RegistrationResponse,
type WebAuthnVerifier,
} from './verifier.js'
const CHALLENGE_BYTES = 32
const DEFAULT_TIMEOUT_MS = 60_000
export function newChallenge(): string {
return encodeBase64UrlBytes(new Uint8Array(randomBytes(CHALLENGE_BYTES)))
}
export function startRegistration(accountId: string, rpId: string): Promise<RegistrationOptions> {
return Promise.resolve({
rpId,
challenge: newChallenge(),
userId: accountId,
timeoutMs: DEFAULT_TIMEOUT_MS,
})
}
/** Verify attestation and mint the stored credential. `rpId` is bound to the tenant subdomain. */
export async function finishRegistration(
accountId: string,
resp: RegistrationResponse,
expectedChallenge: string,
rpId: string,
origin: string,
verifier: WebAuthnVerifier,
): Promise<WebAuthnCredential> {
if (resp.clientChallenge !== expectedChallenge) throw new WebAuthnError('challenge mismatch')
if (resp.origin !== origin) throw new WebAuthnError('origin mismatch')
if (resp.rpId !== rpId) throw new WebAuthnError('rpId mismatch')
const result = await verifier.verifyRegistration(resp, expectedChallenge, rpId, origin)
if (!result.verified) throw new WebAuthnError('attestation not verified')
return {
credentialId: result.credentialId,
accountId,
publicKey: result.publicKey,
signCount: result.signCount,
transports: [...result.transports],
createdAt: new Date().toISOString(),
}
}

View File

@@ -0,0 +1,66 @@
/**
* T5 · WebAuthn verification SEAM. The heavy attestation/assertion crypto + CBOR parsing is
* delegated to a battle-tested verifier (production: `@simplewebauthn/server`, per the reuse rule)
* INJECTED here, so the P5-owned security guards — single-use challenge, origin/rpId binding, and
* signCount regression (cloned-authenticator signal) — stay dependency-light and deterministically
* testable. INTEGRATION POINT: wire `@simplewebauthn/server` verifyRegistrationResponse /
* verifyAuthenticationResponse into this interface at the P3/P6 boundary.
*/
export interface RegistrationOptions {
readonly rpId: string
readonly challenge: string
readonly userId: string
readonly timeoutMs: number
}
export interface AuthenticationOptions {
readonly rpId: string
readonly challenge: string
readonly timeoutMs: number
}
/** Opaque authenticator responses (shape provided by the browser / @simplewebauthn). */
export interface RegistrationResponse {
readonly clientChallenge: string
readonly origin: string
readonly rpId: string
}
export interface AuthenticationResponse {
readonly clientChallenge: string
readonly origin: string
readonly rpId: string
}
export interface RegistrationVerification {
readonly verified: boolean
readonly credentialId: string
readonly publicKey: Uint8Array
readonly signCount: number
readonly transports: readonly string[]
}
export interface AuthenticationVerification {
readonly verified: boolean
readonly newSignCount: number
}
export interface WebAuthnVerifier {
verifyRegistration(
resp: RegistrationResponse,
expectedChallenge: string,
rpId: string,
origin: string,
): Promise<RegistrationVerification>
verifyAuthentication(
resp: AuthenticationResponse,
expectedChallenge: string,
rpId: string,
origin: string,
storedSignCount: number,
): Promise<AuthenticationVerification>
}
export class WebAuthnError extends Error {
constructor(message: string) {
super(message)
this.name = 'WebAuthnError'
}
}