RELAYLINK

Technical design

Document ID: DES-001
Status: Draft (Pending Review)
Version: v2.28.0
Updated: 2026-11-29
Researched: 2026-09-15
Related Docs: Requirements Index

1. Technical Conclusions

RelayLink implements a dedicated reverse TCP, unicast UDP, and HTTP(S) proxy on .NET 10 / C# + Sockets + optional SslStream + ASP.NET Core (aligned with the v0.1.0-rc.18 baseline). Control connections enable TLS by default; standard proxy data connections run as raw TCP on a separate port, with security trade-offs documented in ADR-0008.

  • Linux or Windows Servers expose separate control (:7443 default) and data (:7444 default) ports; only authenticated control sessions can authorize data tunnels.
  • Windows, Linux, and macOS Agents implement the multi-server servers[] schema (Multi-Server Agent Design), isolating each Server profile's control session, data tunnels, state/<profileId>/ directory, and E2E identity file.
  • Channels and per-client secrets live in one JSON file per client on the Server; snapshots are pushed on startup load, after registration, and after admin mutations.
  • Agents report their local E2E certificate fingerprint on registration, and the Server pins it to the client JSON on first confirmation; authorized channels do not store fingerprints, while outbound mappings reference the target client's pinned identity. Unexpected fingerprint changes are rejected rather than auto-overwritten, and legacy channel-level fingerprint fields are rejected on load (ADR-0011).
  • Standard proxies copy raw TCP bytes bidirectionally once the data tunnel binds and the target connects. Authorized peer access relays framed traffic through the Server by default with inner E2E TLS (or optional plaintext for raw TCP/UDP with HMAC access proof), preserving half-close semantics without multiplexing multiple business streams onto one TCP tunnel.
  • P2P Direct and Same-Mode Relay Fallback (DES-011 / ADR-0043): Optional preferDirect routing is implemented for authorized raw TCP and unicast UDP channels (default remains relayOnly). Using v5 control frames (42..52), Agents negotiate QUIC 1.3 (encrypted) or mutually bound ICE-TCP (plaintext) direct transport with optional Server-hosted STUN, strict probe CIDR/rate budgets, suspend-aware monotonic leases, and SQLite direct_lease_occupancy restart recovery, automatically falling back to same-mode relay when unreachable or behind symmetric NATs (DES-011).
  • Unicast UDP (v4): Source-isolated UDP sessions use 4-byte big-endian length framing over dedicated TCP tunnels (or direct P2P streams) while leaving raw TCP copying intact (UDP Design).
  • HTTP/HTTPS Reverse Proxy (v5): Uses a target-side YARP/Kestrel virtual ingress while preserving raw TCP/UDP; public browser TLS terminates at the target Agent, and peer HTTP enforces inner TLS, access proof, and application-stream unwrapping (HTTP Design, ADR-0026, HTTP Guide, HTTP Verification).
  • Assisted Updates and Controlled Distribution (DES-012 / ADR-0044): Introduced in v0.1.0-rc.17+, the Server checks public releases and verifies SHA256SUMS into protected cache, pushes aligned version state over :7443, serves packages over :7444 under 30s atomic leases and a shared FIFO token bucket, and generates platform-matched external upgrade commands with zero in-process self-updaters (DES-012).
  • AI Automation and 6-Language SDKs (DES-010): Optional automation listener (off by default, 127.0.0.1:18082 TLS-only) provides one-time pairing codes, ECDSA device-bound tokens, 4-tier risk controls, the relaylink CLI / relaylink-admin skill, and zero-dependency data-plane SDKs across C#/.NET, Python, TypeScript, Go, Java, and Rust without modifying core tunnel ports, TLS, identity verification, quotas, or wire protocols (REQ-001P, DES-010, ADR-0035, ADR-0036).

These are RelayLink design decisions, not a claim that an off-the-shelf .NET product satisfies every requirement out of the box.

2. Research and Alternatives

Option Verified Capabilities Fit Assessment
frp TCP proxy Listens on Server port and forwards to client target; multiple tunnel modes Useful reference and baseline; official TCP examples declare proxies on the client and adapting centralized Server push + C# requirements still requires substantial work
OpenSSH reverse forwarding ssh -R forwards remote listener to client-side target Fast path verification; lacks centralized config, Windows Service management, and operations dashboard
Custom .NET per-connection tunnels Socket, SslStream, and Generic Host provide required primitives Matches centralized config, identity, deployment, and dashboard requirements; requires owning protocol, fault, and load verification
Custom single-connection multiplexing Encodes multiple streams into one TCP tunnel Reduces socket/handshake count but adds stream windows, fair scheduling, and head-of-line loss across shared TCP; deferred

References: frp TCP Docs, frp Overview, OpenSSH Manual.

2.1 Runtime Selection

Microsoft's support lifecycle lists .NET 10 as LTS (end of support 2028-11-14), while .NET 8 support ends 2026-11-10. All projects target net10.0 (with RelayLink.Sdk multi-targeting netstandard2.0;net8.0;net10.0), pinned to the latest supported 10.0 patches at release time (Microsoft Support Policy).

Do not assume support for legacy Windows versions; verify target hosts against the official .NET 10 OS support matrix.

3. Network Architecture

flowchart LR
    App["Cloud / Intranet App"] -->|"TCP / UDP / HTTPS Proxy Port"| Proxy["Server Proxy Listener"]
    Browser["Intranet Browser"] -->|"HTTP 18080"| Web["AdminWeb Dashboard"]
    Agent["Windows / Linux / macOS Agent"] -->|"Control TLS 7443"| Control["Control Entry"]
    Agent -->|"Dedicated Data TCP 7444"| Data["Data Entry"]
    Agent -.->|"Optional UDP STUN"| Stun["STUN Responder"]
    Agent <-.->|"Optional P2P QUIC / ICE-TCP"| PeerAgent["Peer Agent"]
    Control --> State["In-Memory Snapshot & SQLite"]
    Proxy <-->|"Correlated Business Conn"| Data
    Agent -->|"TCP / UDP / HTTP"| SQL["Private Business Target"]
    Web --> State
    Data --> State

Arrows indicate dial direction; data transfer is bidirectional.

Example Endpoint Bind Address Purpose Reachability
TCP 7443 0.0.0.0 Control connection, TLS by default Agents only
TCP 7444 0.0.0.0 Dedicated data connection (standard raw TCP, peer relay frames, assisted update downloads) Agents only; requires trusted network or inner/link encryption
UDP (optional, e.g. 13478) 0.0.0.0 / peerDirect.stunListenAddress RFC 8489 STUN Binding responder (active only when stunListenPort > 0) Agents
TCP 21433, 21434... 0.0.0.0 or VPC IP Business TCP / UDP / HTTPS proxy listeners VPC/LAN only, controlled by security groups
TCP 18080 127.0.0.1 Server dashboard and read/admin API, plaintext HTTP Loopback only; remote access via co-located Agent peer tunnel
TCP 18082 (optional) 127.0.0.1 AI automation HTTPS surface (off by default) Loopback only; reached remotely over inner-TLS peer channel
TCP 18081 127.0.0.1 Agent local monitoring UI and v2 read/write API, plaintext HTTP Agent loopback only

Cloud NAT public IPs need not appear on Server NICs. Admin-created standard channels default to 0.0.0.0 to avoid accidental loopback-only binds, and can be narrowed to a specific VPC IPv4 address. The creation form queries GET /api/v1/admin/next-channel-port, which probes upward from 19000 skipping control, data, dashboard, and configured standard-channel ports (including disabled ones) and attempts an exclusive 0.0.0.0 bind as a non-reserving hint. Authorized-only channels open no Server business listener and consume no port hint. Business ports must still be restricted by cloud security groups or host firewalls; application-layer IP/CIDR security groups supplement standard channels. Target hostnames resolve on the Agent within the overall connection timeout.

The Server dashboard remains plaintext HTTP without TLS certificates. Example and Docker configs bind dashboard.listenAddress to 127.0.0.1 (Docker Compose uses network_mode: host). Remote admins run a co-located Agent and open the dashboard through an inner-TLS peer channel. Binding to a non-loopback address logs an Error prefixed with SECURITY: and mirrors it to stderr. Session cookies are HttpOnly, SameSite=Strict, adding Secure only when the request arrived over HTTPS. Passwords exceeding 1024 bytes are rejected before PBKDF2. Login throttling counts failures per (RemoteIpAddress, username) (locking after 5) plus a 20-failure cap per IP across usernames, ignoring forwarded headers and capping tracked addresses at 10,000 (returning 503 + Retry-After when full). New admin sessions replace existing ones only after the login audit event commits; audit storage failure fails login and preserves any active session. Management responses include Content-Security-Policy (frame-ancestors 'none'), X-Content-Type-Options: nosniff, and X-Frame-Options: DENY.

Control and data planes use distinct ports and cannot sit behind HTTP-only L7 proxies; load balancing requires L4 TCP passthrough.

4. Solution Layout and Component Responsibilities

RelayLink.slnx
  src/RelayLink.Protocol/              Wire framing (v3-v5), DTOs, error codes, SemVer, platform probes, update helpers
  src/RelayLink.Transport/             TLS, frame I/O, UDP framing, duplex pump, and P2P direct primitives
  src/RelayLink.Logging/               Serilog file logging, level splitting, rolling retention
  src/RelayLink.AdminWeb/              React/TypeScript/Vite Server Admin UI
  src/RelayLink.AgentWeb/              React/TypeScript/Vite Agent local UI
  src/RelayLink.Server/                ASP.NET Core host, control/data/STUN listeners, dashboard, SQLite, update cache, automation
  src/RelayLink.Agent/                 Generic Host, Windows Service/systemd/launchd, multi-server contexts, YARP HTTP, P2P
  src/RelayLink.Agent.ConfigMigrator/  Pre-start Agent configuration migrator
  src/RelayLink.AutomationClient/      Shared Automation HTTP/ECDSA proof client for CLI
  src/RelayLink.Cli/                   AI automation CLI (relaylink)
  src/RelayLink.Sdk/                   C#/.NET multi-targeted (netstandard2.0/net8.0/net10.0) data-plane SDK
  sdk/                                 Python, TypeScript, Go, Java, Rust data-plane SDKs
  contract/                            OpenAPI, error/exit code maps, cross-language conformance suite
  skills/relaylink-admin/              Operations agent skill distributed with CLI
  tests/RelayLink.UnitTests/           State machines, config, direct policy, tokens, updates, framing, SDK tests
  tests/RelayLink.IntegrationTests/    Real TCP/TLS, P2P direct, HTTP, CLI, fault, and SQL integration tests
Server Component Responsibilities
ConfigurationLoader Loads, validates, and builds immutable config snapshots and indexes
TunnelAcceptorService Accepts control TCP, optional TLS handshake, registration auth, capability/direct negotiation, pre-auth limits
DataAcceptorService Dedicated data listener, one-time token binding (standard / peer relay / update download), pre-bind limits
AuthenticationService Verifies clientId, enabled state, secret, and pinned E2E certificate fingerprint
SessionRegistry Single active session per client ID, heartbeats, session generations, cleanup
ProxyListenerService Per-channel TCP/UDP listeners and business admission (including security groups)
PendingConnectionRegistry Pending business sockets, bind tokens, deadlines, and capacity leases
PeerRelayRegistry / PeerDirectSession Peer relay pairing and P2P direct state machine, initial/renewal leases, revocation, same-mode fallback
DirectLeaseStore SQLite direct_lease_occupancy persistence and conservative restart lease-expiry recovery
StunServerService Optional lightweight RFC 8489 STUN Binding responder with per-source-IP rate limiting
MetricsRegistry / TrafficHistoryService / AuditService Channel/client counters, SQLite minute traffic history, and start-audit gating
UpdateCheckService / UpdateCacheStore / UpdateDownloadRegistry GitHub Release ETag polling, SHA256SUMS verification, single-flight cache, :7444 lease/rate-limited serving
Automation/* / AutomationEndpoints Loopback HTTPS automation surface, one-time pairing, ECDSA device tokens, risk-tiered mutations
AdminWeb / Minimal API Static Admin UI, read/admin APIs, live connection disconnect, health probes

The Agent comprises AgentProcessRuntime (maintaining isolated per-profileId contexts), ControlSessionWorker, SessionConfiguration, PeerSessionCoordinator, PeerDirectAgentAttempt, HttpProxyRuntime, AgentPortAllocator, AgentUpdateCoordinator, and AgentLocalDashboard (hosting RelayLink.AgentWeb). The control read loop never awaits target dialing or update downloads; Open, direct probes, and download requests execute in bounded async tasks so heartbeats stay responsive.

The Agent runs on .NET Generic Host via Microsoft.Extensions.Hosting.WindowsServices on Windows, Microsoft.Extensions.Hosting.Systemd on Linux, launchd foreground execution with SIGTERM handling on macOS, and standard console mode for debugging (Windows Service Docs).

5. Configuration Model

5.1 Server Config: server.json

See the full sanitized template at Server Config Example; core structure:

{
  "schemaVersion": 1,
  "tunnel": {
    "listenAddress": "0.0.0.0",
    "agentServerHost": "tunnel.example.com",
    "trustedCaPemPath": "/etc/relaylink/tls/root-ca.pem",
    "port": 7443,
    "dataPort": 7444,
    "tlsEnabled": true,
    "certificatePemPath": "/etc/relaylink/tls/fullchain.pem",
    "privateKeyPemPath": "/etc/relaylink/tls/privkey.pem",
    "handshakeTimeoutSeconds": 10,
    "heartbeatIntervalSeconds": 15,
    "heartbeatTimeoutSeconds": 45
  },
  "dashboard": {
    "listenAddress": "127.0.0.1",
    "port": 18080,
    "refreshSeconds": 5,
    "admin": {
      "username": "admin",
      "passwordHash": "PBKDF2-SHA256$210000$<saltBase64>$<hashBase64>",
      "sessionLifetimeMinutes": 60
    }
  },
  "clientsDirectory": "/etc/relaylink/clients",
  "limits": {
    "maxConnections": 2000,
    "maxPendingConnections": 200,
    "maxUnauthenticatedConnections": 100,
    "maxChannelsPerClient": 100,
    "openTimeoutSeconds": 20,
    "blockedWriteTimeoutSeconds": 120,
    "halfCloseDrainTimeoutSeconds": 300,
    "tcpIdleTimeoutSeconds": 900
  }
}

server.json also supports optional top-level sections: securityGroups, history, audit, update, peerDirect (direct toggle, optional stunListenAddress/stunListenPort, probe budgets, allowedCidrs, lease parameters), and automation (loopback HTTPS automation surface, enabled: false by default).

5.2 Per-Client Config: clients/shanghai-01.json

{
  "schemaVersion": 1,
  "clientId": "shanghai-01",
  "displayName": "Shanghai Node 01",
  "tags": ["production", "shanghai"],
  "enabled": true,
  "secret": "REPLACE_WITH_UNIQUE_32_RANDOM_BYTES_BASE64",
  "maxConnections": 100,
  "maxPendingConnections": 20,
  "channels": [
    {
      "channelId": "erp-sql",
      "displayName": "ERP SQL Server",
      "tags": ["database", "erp"],
      "enabled": true,
      "listenAddress": "0.0.0.0",
      "listenPort": 21433,
      "targetHost": "192.168.10.20",
      "targetPort": 1433,
      "maxConnections": 50,
      "targetConnectTimeoutSeconds": 5
    }
  ]
}

Each client owns a unique CSPRNG secret (at least 32 random bytes, Base64-encoded; placeholder or duplicate secrets fail validation). Secret verification compares decoded fixed-length bytes via CryptographicOperations.FixedTimeEquals. File ACLs restrict reads to the service account and admins.

Optional tags (up to 32 case-insensitive unique tags of 1–64 chars per client/channel) appear only in read/admin UI filtering and never enter Agent snapshots, config digests, auth, or forwarding; editing tags alone does not revoke connections or push config updates.

Channels support transportProtocol (tcp/udp), applicationProtocol (raw/http), authorizedClientsOnly, endToEndEncryptionEnabled, and peerRoutingPolicy (relayOnly default, or preferDirect for authorized raw TCP/UDP). tunnel.agentServerHost pre-populates downloaded Agent configs (falling back to specific non-wildcard listenAddress or required explicitly when binding 0.0.0.0 / ::) and must match TLS certificate SANs. tunnel.trustedCaPemPath points to the public CA PEM embedded as trustedCaPemBase64 in single-server Agent downloads; private keys are disallowed there. See Client Config Example and Multi-Server Agent Design.

5.3 Agent Local Config: agent.json

The Agent executable accepts only the servers[] multi-server schema (Agent Config Example). Top-level fields define dashboardPort (default 18081), outboundPortRangeStart (20000), outboundPortRangeEnd (59999), global maxConnections (2000), and optional update and peerDirect. Each profileId isolates its connection settings, CA trust (trustedCaPemBase64), E2E identity (state/<profileId>/identity.pfx), port state (ports.json), and operational diagnostics (relaylink-diagnostics.jsonl). Legacy single-server configs are migrated pre-start by RelayLink.Agent.ConfigMigrator. The local Agent UI implements grouped read views and write-session + CSRF-protected add, update, delete, and enable/disable mutations (ADR-0022, ADR-0023, ADR-0034). See Multi-Server Agent Design and ADR-0018.

Each servers[] profile uses serverHost for both control and data dialing and control TLS hostname verification, serverPort for control, and dataPort for data (serverPort + 1 when migrated from legacy files). Control TLS trusts strictly the profile's trustedCaPemBase64 without OS root fallback (online CRL/OCSP is unavailable for private CAs without CRL/OCSP endpoints). Local channels, target hosts, or proxy ports are rejected.

5.4 Pushed Snapshots

Snapshots include only client ID, display name, limits, channels, OutboundMappings, and configVersion, serialized via an explicit allowlisted DTO; RegisterAccepted also carries Server capability flags and optional peerDirectPolicy. Secrets, certificate paths, and sibling client configs are never pushed.

configVersion is the SHA-256 hex digest of deterministic UTF-8 JSON ordered by channelId; access secrets and peerRoutingPolicy participate in the digest under TLS without appearing in logs. v3 snapshots strip UDP, HTTP, and direct fields; v4 strips HTTP and direct fields; v5 includes full capabilities. The Server tracks up to 32 ordered pending ConfigAck versions without overwriting earlier unacknowledged updates, rejecting out-of-order, duplicate, or unknown acks. A full send queue skips the push while keeping the control session open; mid-frame write failure closes the control session because framing may be desynchronized. Neither case rolls back committed disk configuration, and the API returns pushedToAgent=false with pushFailureReason. Reconnecting Agents fetch the latest complete snapshot.

5.5 Loading and Activation

  1. Load server.json and all *.json under clientsDirectory explicitly on startup; hot reload is forbidden.
  2. Parse strictly: disallow duplicate JSON properties, unknown fields, invalid schemas, duplicate IDs, and invalid limits. Client and channel IDs match [a-z0-9][a-z0-9_-]{0,63}, unique per client. Peer mapping IDs combine two up-to-64-char IDs with - (max 129 chars; legacy IDs remain loadable).
  3. Require filename clientId.json; authentication looks up only the loaded dictionary.
  4. Ensure enabled endpoints are globally unique without colliding with control/data/dashboard ports, and verify snapshots stay within 256 KiB.
  5. Bind all enabled channel listeners on startup; any bind failure tears down prior listeners and aborts startup.
  6. Become ready once required listeners succeed regardless of whether Agents are online.
  7. Channel listeners remain bound while an Agent is offline, closing accepted business sockets immediately and recording offline rejections.

--check-config performs static validation without binding ports or creating runtime log/update cache directories. Unreadable config files or directories (including UnauthorizedAccessException / SecurityException) exit with code 2. Dashboard saves validate completely, atomically write client JSON, and switch listeners/snapshots—rolling back listeners and restoring prior JSON on bind failure without dropping existing connections. Diffing old vs. new records revokes only genuinely modified or removed channels/mappings (including active P2P direct connections) before pushing snapshots. Overlapping bind address changes on the same port (e.g. 127.0.0.1 to 0.0.0.0) briefly stop the old listener before rebinding (ADR-0009).

limits.tcpIdleTimeoutSeconds defaults to 900 (0 disables app-level idle timeout) alongside socket keepalives and halfCloseDrainTimeoutSeconds (300), both communicated in RegisterAccepted. Deleting a client checks for referencing outbound mappings first; disabling a client is permitted even when referenced, immediately stopping its listeners, revoking its standard and peer/direct connections, and closing its control session. Outbound mapping creation accepts only targetClientId and targetChannelId, generating <targetClientId>-<targetChannelId> with no PUT route (update via delete + recreate). Application-layer securityGroups (IPv4/IPv6 single IPs or CIDRs evaluated against socket RemoteEndPoint, normalizing IPv4-mapped IPv6, disallowed on peer-only channels) share the config write lock and revoke mismatched connections on rule updates (ADR-0012).

6. TLS and Authentication

The control port completes TLS (when enabled) before parsing Register. The Server loads its certificate chain and private key while Agents validate trust chain, validity period, and hostname without permissive callbacks. The data port uses no outer TLS: standard proxy payloads and bind tokens are unencrypted on the wire unless protected by a trusted network; peer traffic is protected by inner TLS (or QUIC TLS 1.3) by default, or uses access proofs and direct bind challenges over plaintext when endToEndEncryptionEnabled=false.

TLS relies on OS protocol/cipher policies requiring TLS 1.2+ (preferring TLS 1.3) and reuses SslStreamCertificateContext (SslStream Best Practices). Initial authentication uses clientId + secret inside TLS; business tunnels use per-connection one-time random tokens. Pre-auth concurrency and handshake deadlines protect Server resources and return AUTH_FAILED externally while logging detailed reasons internally without secrets.

7. Wire Protocol (Version 5)

7.1 Common Frame Header

Control messages and data-port bind handshakes share the 12-byte NTP1 header regardless of TCP packet boundaries. Standard proxies switch to raw TCP bytes after Start, and update downloads stream raw asset bytes after UpdateDownloadAccepted.

Offset Length Field
0 4 bytes ASCII magic: NTP1
4 1 byte version (3 / 4 / 5; locked on first frame; v3 TCP, v4 +UDP, v5 +HTTP, relay control handshake, updates, P2P direct; unknown or mid-session switches rejected)
5 1 byte type
6 2 bytes flags, must be 0, big-endian
8 4 bytes payloadLength, unsigned big-endian, excluding header
12 N bytes payload

Limits: max 256 KiB control JSON, 8 KiB initial frame, 1–32 KiB Data payload, 0-byte Fin, 1 KiB Reset JSON. Headers are validated before allocating payload buffers. Reserved types, non-zero flags, invalid state transitions, or truncated frames fail as protocol errors.

7.2 Message Types and Required Fields

type Name Direction and Key Fields
1 Register Agent→Server; clientId, secret, agentVersion, e2eCertificateSha256, relayControlReady, mappingEncryptionStatus, updateCapability, platform, peerDirectQuicReady, peerDirectPlainTcpReady
2 RegisterAccepted Server→Agent; sessionId, configVersion, config, heartbeatIntervalSeconds, heartbeatTimeoutSeconds, halfCloseDrainTimeoutSeconds, tcpIdleTimeoutSeconds, relayControlReady, updateCapability, serverVersion, updateServiceState, peerDirectQuicReady, peerDirectPlainTcpReady, peerDirectPolicy
3 ConfigAck Agent→Server; sessionId, configVersion
4 Ready Server→Agent; sessionId
5 Ping Server→Agent; sequence
6 Pong Agent→Server; matching sequence
7 Open Server→Agent; sessionId, connectionId, channelId, configVersion, token, remainingOpenTimeoutMs; v5 HTTP adds httpIngress
8 OpenFailed Agent→Server; sessionId, connectionId, errorCode
9 CancelOpen Server→Agent; sessionId, connectionId, reason
10 BindData Agent→Server (:7444 first frame); sessionId, connectionId, channelId, token
11 BindAccepted Server→Agent; connectionId
12 TargetReady Agent→Server (control); connectionId, targetConnectDurationMs
13 Start Server→Agent (control); connectionId
14 Error Either→Peer; code, optional reason (1..10), zero stack traces or secrets
15 ConfigUpdate Server→Agent; sessionId, configVersion, config; confirmed with ConfigAck
16 PeerOpenRequest Caller Agent→Server; requestId, mappingId (no secrets or payloads)
17 PeerOpenGranted Server→Caller Agent; requestId, connectionId, sessionId, token, endToEndEncryptionEnabled, transportProtocol, httpIngress, setupTimeoutMilliseconds, relayBinding
18 PeerOpen Server→Target Agent; connectionId, sessionId, callerClientId, channelId, token, endToEndEncryptionEnabled, transportProtocol, httpIngress, setupTimeoutMilliseconds, relayBinding
19 PeerBindData Both Agents→Server (:7444 first frame); connectionId, sessionId, token, role
20 PeerBindAccepted Server→Both Agents; connectionId
21 PeerOpenRejected Server→Caller Agent; requestId, errorCode
22 PeerMappingStatus Caller Agent→Server; sessionId, configVersion, addresses (mappingId, localAddress, localPort)
23 HttpStatus v5 Agent→Server (control); sessionId, configVersion, channels (channelId, policyHash, state)
24 HttpIngressReady v5 Agent→Server (control); connectionId
25 PeerRelayAuthenticated v5 Both→Server (TLS control); binding, handshakeId
26 PeerRelayPrepare v5 Server→Target (TLS control); binding, handshakeId, one-time preparationId
27 PeerRelayTargetReady v5 Target→Server→Caller (TLS control); binding, handshakeId, preparationId
28 PeerRelayAborted v5 Peer↔Server (TLS control); aborts or cancels the relay attempt
29 UpdateStatusPush v5 Server→Agent; repository, Server version, target policy, check state, recommended version, AssetName/FileSize/Sha256
30 UpdateCheckRequest v5 Agent→Server; requestId
31 UpdateCheckResponse v5 Server→Agent; requestId, status
32 Data Peer relay data plane; inner TLS records or plaintext bytes (1–32 KiB)
33 Fin Peer relay data plane; unidirectional EOF (0 bytes)
34 Reset Peer relay data plane; abnormal termination
35 UpdateDownloadRequest v5 Agent→Server; requestId, targetVersion, assetName, expectedSha256
36 UpdateDownloadPreparing v5 Server→Agent; requestId (immediate non-blocking acknowledgement while Server caches asset)
37 UpdateDownloadGranted v5 Server→Agent; requestId, downloadToken, version, assetName, fileSize, sha256, expiresAtUtc
38 UpdateDownloadRejected v5 Server→Agent; requestId, errorCode, message, retryable
39 BindUpdateDownload v5 Agent→Server (:7444 first frame); sessionId, requestId, downloadToken
40 UpdateDownloadAccepted v5 Server→Agent (:7444); requestId, fileSize, followed by token-bucket rate-limited asset stream
41 UpdateDownloadCancel v5 Agent→Server; requestId
42 PeerDirectStart v5 Server→Both (TLS control); binding, attemptSeq, directMode, serverChallenge, probeTimeoutMs, lease settings, ephemeral bind key or pinned fingerprint
43 PeerDirectCandidates v5 Both↔Server (TLS control); connectionId, attemptId, attemptSeq, candidates
44 PeerDirectReady v5 Both→Server (TLS control); binding, attemptSeq, handshakeId, directPath
45 PeerDirectLeaseGrant v5 Server→Both (TLS control); connectionId, attemptId, attemptSeq, leaseId, leaseDurationMs, serverNonce, isRenewal
46 PeerDirectPrepare v5 Server→Target (TLS control); binding, attemptSeq, handshakeId, preparationId
47 PeerDirectTargetReady v5 Target→Server→Caller (TLS control); binding, attemptSeq, handshakeId, preparationId
48 PeerDirectCancel v5 Both↔Server (TLS control); connectionId, attemptId, attemptSeq, reasonCode, authFailed
49 PeerDirectCancelAck v5 Both→Server (TLS control); connectionId, attemptId, attemptSeq, targetDialed
50 PeerDirectLeaseRenew v5 Both→Server (TLS control); connectionId, attemptId, attemptSeq, leaseId, bytesToTarget, bytesToCaller, reportSeq
51 PeerDirectRevoke v5 Server→Both (TLS control); connectionId, attemptId, reasonCode
52 PeerDirectClosed v5 Both→Server (TLS control); connectionId, attemptId, attemptSeq, reasonCode, bytesToTarget, bytesToCaller, reportSeq

All non-Data/Fin frames carry UTF-8 JSON. sessionId, connectionId, attemptId, requestId, leaseId, and preparationId are random UUIDs; clientId, channelId, and mappingId are stable config identifiers; bind and update download tokens are CSPRNG strings. Data port (:7444) accepts only BindData (10), PeerBindData (19), or BindUpdateDownload (39) as initial frames. Control rejection reason codes (reason 1–10) and diagnostic boundaries are specified in Logging and Diagnostics Design.

7.3 Control Session Flow

sequenceDiagram
    participant A as Agent
    participant S as Server
    A->>S: TCP to 7443, TLS certificate verification
    A->>S: Register(clientId, secret, agentVersion, capability flags)
    S->>S: Authenticate & atomically occupy clientId
    S->>A: RegisterAccepted(sessionId, snapshot, capabilities & direct policy)
    A->>A: Verify version, config & SHA-256 digest
    A->>S: ConfigAck
    S->>A: Ready
    loop Heartbeat
      S->>A: Ping(sequence)
      A->>S: Pong(sequence)
    end

The Server writes Ready before permitting Open or pushing UpdateStatusPush; the Agent enters Online upon receiving Ready. Registration-to-ack has a 10s limit; concurrent registrations resolve atomically by clientId, and old session cleanup verifies sessionId ownership before removing state. RTT uses the Server's monotonic clock, updating only on matching Pong.sequence; Agents also exit after 45s without a Server Ping.

7.4 Business Connection Establishment

sequenceDiagram
    participant B as Intranet Caller
    participant S as Server
    participant A as Agent
    participant D as SQL Server
    B->>S: TCP connect to proxy port
    S->>S: Reserve quota, create Pending & token
    S->>A: Open (control)
    A->>S: New TCP to dedicated data port 7444
    A->>S: BindData (data)
    S->>S: Atomically consume one-time token
    S->>A: BindAccepted
    A->>D: TCP connect to snapshot target
    A->>S: TargetReady (control)
    S->>S: Verify deadline & active session
    S->>A: Start (control)
    B<<->>D: Raw TCP byte copy in both directions

Caller TCP handshake completion precedes tunnel readiness; the Server holds off reading caller data until Start, allowing OS buffers to hold initial bytes such as SQL prelogin packets. Open carries only channelId—never dynamic target hosts. The 20s total deadline from Server accept covers bind, target dial (itself capped at 5s across DNS + IP attempts), and Start. Peer relay and P2P direct/fallback state machines are detailed in DES-002 and DES-011.

7.5 Data Tokens and Race Handling

Pending entries bind {sessionId, connectionId, channelId, tokenHash, deadline, state, businessSocket, capacityLease}, transitioning atomically via CAS from AwaitingBind to Bound while clearing the token hash. Timeouts cover both AwaitingBind and Bound/target-dialing stages, ensuring a single terminal outcome and one-time quota/socket cleanup.

8. Data Plane and Half-Close

8.1 Two Directions

Each connection runs two bounded async loops (ReceiveAsync -> SendAsync) with one ~32 KiB buffer per direction. Standard proxies copy raw bytes after Start; peer access uses framed relay or P2P direct streams (encrypted QUIC or plaintext ICE-TCP) with inner TLS / access proof, and HTTP uses PeerApplicationStream into the target Kestrel/YARP virtual host. See Socket.Shutdown API.

8.2 Half-Close Semantics

Standard proxies flush buffered bytes on EOF and invoke Shutdown(Send) on the opposite socket while letting the reverse direction finish trailing bytes up to halfCloseDrainTimeoutSeconds (default 300s). Encrypted peer TCP streams encode unidirectional EOF as a 0-length inner application record rather than premature TLS close_notify (preventing Windows Schannel from aborting reverse responses). Unicast UDP has no half-close.

8.3 Backpressure and Timeouts

Each direction holds at most ~32 KiB (~64 KiB app buffers per side), relying on TCP flow control for backpressure and TCP_NODELAY on control, data, proxy, and target sockets to avoid Nagle stalls. Blocking writes time out after 120s (aborting without replay), idle TCP streams close after 900s (tcpIdleTimeoutSeconds), and TCP keepalives probe idle sockets (60s idle, 15s interval, 3 probes).

9. State Model and Fault Recovery

9.1 State Model

Agent: Disconnected -> Connecting -> Authenticating -> Configuring -> Online
        ^                                                            |
        +---------------- Backoff <----------------------------------+

Business Conn: Accepted -> AwaitingBind -> Bound -> TargetConnecting
               -> Relaying -> HalfClosed -> Closed
               Any non-terminal -> Failed/Cancelled (single cleanup)

Channel availability (channelsAvailable) requires enabled channel, non-peer-only mode, and online Agent (plus v4+ for UDP and ready ingress for HTTP). Mapping availability additionally requires reported local address (and v4+ on both ends for UDP).

9.2 Control Connection Loss

Control EOF, error, or 45s heartbeat timeout atomically invalidates the session, cancels pending/active relays, and stops renewing P2P direct leases; the Agent clears its in-memory snapshot and tears down active connections and listeners (silent-partition direct connections stop at latest upon local lease expiration).

9.3 Reconnect and Error Strategy

Transient network failures back off via random(0, min(30s, 1s * 2^attempt)), resetting after 60s online. Auth rejections, protocol mismatches, and duplicate sessions wait 60s + random(0, 15s). Config errors exit non-zero.

Scenario Handling
Single data tunnel fails Close that business/target pair; control and sibling streams continue
Target dial failure Fail current connection; next request retries without global circuit breaking
Capacity limit reached Close promptly after accept, count LIMIT_EXCEEDED, never queue unboundedly
Heartbeat blackhole Expire session at 45s; re-authenticate for new sessionId
Server restart Drop all sessions, reset live counters, Agents back off and reconnect; unresolved direct leases wait full max lease via direct_lease_occupancy before clearing
Secret rotation Update files and restart Server; old sessions invalidate and reconnect under new snapshot
Admin disables client Persist config, stop listeners, revoke standard/peer/direct connections, close control session until re-enabled
SQL execution interrupted Return socket error to client app; proxy never replays statements

10. Metrics, Audit, and Dashboard

10.1 Unified Metrics

The Server is the sole authoritative counter source (direct connections accept monotonic reportSeq-deduplicated caller reports via lease renew/close frames): bytesToTarget, bytesToCaller, acceptedTotal, openedTotal, openFailedTotal, activeConnections, pendingConnections, normalClosedTotal, and abortedTotal, maintaining acceptedTotal = pendingConnections + openedTotal + openFailedTotal and openedTotal = activeConnections + normalClosedTotal + abortedTotal per snapshot. Responses include serverInstanceId, statsSinceUtc, and snapshotTimeUtc. When history.enabled is true, deltas persist every 5s per UTC minute into SQLite traffic_minute (90-day default retention) distinguishing standard, peer relay, and peer direct bytes (ADR-0010, Audit and Traffic Design).

10.2 Dashboard Layout

ASP.NET Core Minimal APIs serve the standalone React/TypeScript/Vite bundle from src/RelayLink.AdminWeb copied into wwwroot/ (zero Node.js runtime dependency, ADR-0004). The UI is anonymous read-only with modal admin login, paginated snapshot polling (GET /api/v1/dashboard/snapshot) that pauses while edit modals are open, clickable live connection inspection (showing relay / direct_quic / direct_tcp transportPath), and authenticated connection disconnect. The standalone Agent UI (src/RelayLink.AgentWeb) runs on 127.0.0.1:18081 grouped by profileId with routing policy badges, active direct paths, and non-dismissible update banners.

10.3 HTTP API

Method & Path Behavior
GET /api/v1/overview Overview counters, instance ID, and sample timestamps
GET /api/v1/dashboard/snapshot Anonymous read-only; paginated overview + client summaries, tags, channels, mappings (pageSize <= 100, zero secrets)
GET /api/v1/clients Client list & tags with query/status/page/pageSize (<= 100)
GET /api/v1/clients/{id}/channels Channel status, tags, config, and counters
GET /api/v1/clients/{id}/channels/{channelId}/connections Anonymous read-only; active standard/relay/direct connections with source, transportPath, phase, and directional bytes
GET /api/v1/clients/{id}/mappings Anonymous read-only; mapping IDs, reported loopback addresses, routing policy, targets (no access secrets or fingerprints)
GET /api/v1/history Minute/15m/hourly channel traffic history up to 365 days
GET /api/v1/updates/status Anonymous read-only; Server version, release check state, recommended version, external upgrade commands
POST /api/v1/admin/session Admin login issuing HttpOnly cookie and CSRF token
GET /api/v1/admin/session Session auth status and CSRF token when authenticated
GET /api/v1/admin/audit Authenticated; query SQLite audit_event (hours 1–2160, eventType, clientId, transportPath, page, pageSize <= 100)
DELETE /api/v1/admin/session Admin logout
POST /api/v1/admin/clients Authenticated + CSRF; create client with unique secret
PUT /api/v1/admin/clients/{id} Authenticated + CSRF; edit display name, tags, enable state, quotas (disable revokes immediately)
DELETE /api/v1/admin/clients/{id} Authenticated + CSRF; delete unreferenced client and revoke sessions/listeners
GET /api/v1/admin/clients/{id}/agent-config Authenticated; download single-profile servers[] Agent JSON (Cache-Control: no-store, never logged)
GET/POST /api/v1/admin/security-groups Authenticated (+CSRF for POST); list or create security groups
PUT/DELETE /api/v1/admin/security-groups/{id} Authenticated + CSRF; update or delete unreferenced security group
POST /api/v1/admin/clients/{id}/channels Authenticated + CSRF; create channel, bind listener, push snapshot
PUT /api/v1/admin/clients/{id}/channels/{channelId} Authenticated + CSRF; update/disable channel, update listener, push snapshot
DELETE /api/v1/admin/clients/{id}/channels/{channelId} Authenticated + CSRF; stop listener, delete channel, push snapshot
DELETE /api/v1/admin/clients/{id}/channels/{channelId}/connections/{connectionId} Authenticated + CSRF; disconnect matching active connection (204 / 404)
POST /api/v1/admin/updates/check / cache Authenticated + CSRF; refresh release metadata or trigger cached asset verification
/api/v1/admin/automation/* Authenticated (+CSRF for writes); approve/revoke pairings & device authorizations (paired with loopback TLS /api/v1/automation/* per DES-010)
GET /health/live Process liveness (200)
GET /health/ready Config and required listeners active (200 / 503)

SQLite stores audit_event, traffic_minute, and direct_lease_occupancy (default audit.db beside server.json if history is not configured). Start-audit persistence gates admin login, Agent Ready, and business/direct forwarding (failing closed if unwritable, ADR-0013). The Agent loopback dashboard (127.0.0.1:18081) serves anonymous /api/v2/status|channels|mappings|updates/status and write-session + CSRF-protected /api/v2/admin/session, /api/v2/admin/servers*, /api/v2/admin/servers/{profileId}/enabled, and /api/v2/admin/updates/download (DES-004, DES-012).

11. Resource Limits and Operational Parameters

Parameter Default Notes
Global connection quota 2,000 Shared by Pending + Active + active direct occupancy; acquired before allocating work
Global pending cap 200 Subset of global quota, not additive
Per-client quota 100 Configurable
Per-client pending cap 20 Enforced alongside per-client quota
Per-channel quota 50 Configurable
Pre-auth limit per entry 100 Separate limits for control TLS/first-frame and data bind first-frame
TLS / first-frame deadline 10s From accept
Control config ack deadline 10s After auth success
Business setup deadline 20s Total budget from business accept
Control heartbeat 15s / 45s Ping interval / timeout
Standard copy buffer 32 KiB / dir Raw copy; peer Data frames capped at 32 KiB (empty Data, >32 KiB Data, non-empty Fin rejected)
Control send queue 256 frames Bounded; overflow fails session and cleans up
Blocked write timeout 120s Aborts without replay
Half-close drain timeout 300s Adjustable; separate from idle timeout

Quotas are acquired in strict global -> client -> channel order with immediate rollback and one-shot lease disposal. Estimated Server FDs: 2 * active + 1..2 * pending + control + listeners + overhead (e.g., systemd LimitNOFILE=16384).

12. SQL Server Considerations

12.1 Fixed Endpoints

Configure SQL Server on a fixed TCP port; explicit UDP 1434 forwarding does not rewrite SQL Browser dynamic-port responses, and named-instance auto-discovery is not promised (SQL Server Connectivity Troubleshooting).

12.2 TLS, Authentication, and Connection Strings

Microsoft.Data.SqlClient 5.0+ supports HostNameInCertificate under Mandatory/Strict encryption (HostNameInCertificate Docs):

Server=tcp:10.20.0.10,21433;
Database=ERP;
User ID=app_user;
Password=<provided by application secrets manager>;
Encrypt=Mandatory;
TrustServerCertificate=False;
HostNameInCertificate=sql-shanghai.example.internal;
Connect Timeout=30;

Outer tunnel TLS protects Agent↔Server while SQL TLS runs end-to-end between driver and SQL Server; SQL Server sees the Agent's source IP, not the caller's. TDS is passed through unmodified.

12.3 Application Constraints

Dynamic routing redirects (e.g., AG read-only routing) are not rewritten, and Windows Integrated Auth requires domain/SPN reachability. Disconnects mid-commit surface as socket errors; applications must handle idempotency and retries.

13. Deployment and Operations

13.1 Server: Linux or Windows

Deploys natively via systemd (/opt/relaylink/server, /etc/relaylink/server.json, /etc/relaylink/clients/*.json, /etc/relaylink/tls, non-root relaylink user, LimitNOFILE=16384), Windows Service (deploy/windows/README.md, install-server-service.ps1), or Linux Docker Compose with host networking (deploy/docker/README.md). See Linux Hosting Docs, systemd template, and Linux Deployment. Upgrade the Server before upgrading Agents via platform-matched external commands.

13.2 Windows Agent

Ships win-x64 self-contained and framework-dependent bundles and Inno Setup installers (ADR-0019, ADR-0020, Windows Deployment). Installs binaries under C:\Program Files\RelayLink\Agent, protected config and state/<profileId>/ under C:\ProgramData\RelayLink\Agent, runs as LocalService, runs RelayLink.Agent.ConfigMigrator on update-only upgrades, and preserves config/identity/logs on uninstall.

13.3 Linux Agent

Ships linux-x64 self-contained bundles managed by Linux systemd template under /opt/relaylink/agent with isolated state in /var/lib/relaylink-agent and ExecStartPre config migration/validation (ADR-0014, Linux Deployment). Encrypted QUIC direct transport (preferDirect) on Linux requires libmsquic; if absent, the Agent automatically sets peerDirectQuicReady=false while keeping ICE-TCP and encrypted relay operational.

13.4 macOS Agent

Ships separate osx-x64 and osx-arm64 self-contained bundles managed by launchd template under /Library/RelayLink/Agent and /Library/Application Support/RelayLink/Agent (_relaylink-agent, ADR-0015, macOS Deployment). Initial packages are unsigned/unnotarized and require Developer ID signing/notarization for production distribution.

13.5 Operational Steps

  1. Allocate unique clientId, 32-byte random Base64 secret, and free proxy port.
  2. Write JSON and run --check-config; verify security group rules.
  3. Start/restart Server and confirm /health/ready returns 200.
  4. Download single-server Agent JSON and import into Agent (or run installer/migrator); start Agent.
  5. Confirm Online and channel availability in AdminWeb, then verify end-to-end business connectivity.
  6. Dashboard channel edits update listeners and push snapshots live; direct file or secret changes require a planned restart.
  7. Secret rotation requires coordinated Server + Agent updates with brief downtime.

Admin password hashes are generated via scripts/new-admin-password-hash.ps1 (PBKDF2-SHA256). Structured logs carry timestamp, level, eventId, profileId, clientId, channelId, sessionId, connectionId, attemptId, durationMs, and errorCode, using Serilog rolling retention (14 days routine, permanent errors, 10 MiB / daily). See Installation and Usage Guide.

14. Testing and Implementation Phases

14.1 Required Test Boundaries

  • Arbitrary header splits, coalescing, max payload, oversized frames, truncated JSON, invalid types, and Data after Fin.
  • Bidirectional concurrent random streams with hash verification, slow-read backpressure, partial writes, and half-close tails.
  • Concurrent same-ID registration races and old vs. new session cleanup.
  • Simultaneous Bind, TargetReady, timeout, Cancel, and disconnect ensuring one-time token consumption and one-time quota release.
  • Heartbeat continuity while a target stalls; full resource reclamation on session drop.
  • Data blackhole with healthy control session exercising keepalive and blocked-write timeouts.
  • Long-running SQL queries, connection pooling, SQL TLS hostname verification, interrupted transactions, and large result sets.
  • Server restarts, Agent SIGKILL, port collisions, invalid configs, and accurate dashboard counters.
  • Peer relay and preferDirect (QUIC / ICE-TCP) 8-case matrix, symmetric-NAT / restricted-egress fallback, suspend-aware monotonic leases, and Server-restart direct_lease_occupancy recovery.

14.2 Phases and Exit Criteria

Phase Scope Exit Criteria
P0 Prototype TLS, registration, single-connection DATA/FIN, fixed SQL port Linux↔Windows bidirectional bytes & half-close verified
P1 Core Service Multi-client/channel, quotas, one-time tokens, reconnect Concurrency and race tests pass
P2 Operations AdminWeb dashboard, --check-config, systemd/Windows Service/launchd Operational flows and acceptance items pass
P3 Stability & Extensions WAN emulation, SQL scenarios, 24h load, UDP/HTTP/multi-server/updates/P2P direct Baseline reports, fixes, and deployment parameters recorded

Performance runs must record runtime patches, CPU, RAM, NIC, RTT/loss, SQL driver versions, block sizes, and connection models. Current verified evidence is tracked in Verification Status.

Authorized peer access is specified in DES-002 and ADR-0005, with optional direct transport in DES-011 and ADR-0043. Control links must use TLS whenever peer access or direct transport is enabled.

15. Future Evolution Triggers

  • Connection setup latency becomes dominant: evaluate application connection pooling before pre-warmed data pools; avoid multiplexing complexity.
  • Single VM hits bandwidth, FD, or CPU limits: statically shard clients across independent Servers.
  • High availability required: redesign session ownership, endpoint routing, and config distribution; lossless live TCP migration is not automatic.
  • Cross-instance or complex reporting required: export to a time-series store; SQLite minute history is not a billing ledger.

16. Sources and Nature of Conclusions

Inline references cite official documentation and primary repository records (baseline research date 2026-09-15, with incremental designs and verification records updated through 2026-11-29). Platform support claims come from cited vendor docs; protocol fields, state policies, thresholds, and current verification scope follow Verification Status.

Repository source