Document ID: DES-004
Status: Draft
Version: v1.10.0
Updated: 2026-11-29
Related Requirement: Multi-Server Agent Connection Requirements
Architecture Decision: ADR-0018
1. Scope and Current Status
This document describes the design and current implementation allowing a single Agent process to connect to multiple independent, non-coordinating Servers. Schema validation, the standalone RelayLink.Agent.ConfigMigrator tool, single-server JSON downloads from Server, per-profileId control sessions and runtime contexts, persistent enable/disable toggles, and grouped local v2 read/write APIs are implemented. The main Agent executable accepts only the servers[] schema, reading E2E identity and port state from state/<profileId>/. Upgrade-only paths in the Linux, macOS, and Windows installers invoke the migrator before starting the Agent. The local web UI supports dynamic profile add/update/delete, enable/disable toggles, and same-origin/CSRF write-session checks; automated tests cover global port allocation and resource isolation, and Windows Sandbox verification covers all three installer modes. Full cross-platform production sign-off remains subject to verification records. Server authentication, snapshot distribution, standard proxying, and peer-access wire semantics remain unchanged; each Server continues to manage only the clients, channels, and mappings it defines.
2. Local Configuration and Identity Boundaries
The Agent configuration defines top-level dashboardPort (default 18081), outboundPortRangeStart (default 20000), outboundPortRangeEnd (default 59999), process-wide maxConnections (default 2000), and optional update (DES-012) and default peerDirect (DES-011) sections. servers is an array that may be empty so operators can still open the local web UI after deleting the final entry. Each item carries a stable profileId, optional enabled (default true), serverHost, serverPort, dataPort, useTls, clientId, secret, trustedCaPemBase64, maxConnections, maxPendingConnections, reconnect, and an optional per-profile peerDirect override. Connection endpoints, TLS trust, and reconnect parameters apply strictly to that profile. profileId uses the same restricted character set as client IDs ([a-z0-9][a-z0-9_-]{0,63}) and is locally unique; it is not issued by any Server and does not change when DNS or hostnames change. Example structure (placeholder secrets are non-runnable):
{
"dashboardPort": 18081,
"outboundPortRangeStart": 20000,
"outboundPortRangeEnd": 59999,
"maxConnections": 2000,
"servers": [
{
"profileId": "east",
"enabled": true,
"serverHost": "east.example.com",
"serverPort": 7443,
"dataPort": 7444,
"useTls": true,
"clientId": "agent-01",
"secret": "REPLACE_WITH_EAST_CLIENT_SECRET",
"trustedCaPemBase64": "REPLACE_WITH_EAST_CA_PEM_BASE64",
"maxConnections": 100,
"maxPendingConnections": 20,
"reconnect": { "initialDelaySeconds": 1, "maxDelaySeconds": 30, "permanentErrorDelaySeconds": 60 }
},
{
"profileId": "west",
"enabled": true,
"serverHost": "west.example.com",
"serverPort": 7443,
"dataPort": 7444,
"useTls": true,
"clientId": "agent-01",
"secret": "REPLACE_WITH_WEST_CLIENT_SECRET",
"trustedCaPemBase64": "REPLACE_WITH_WEST_CA_PEM_BASE64",
"maxConnections": 100,
"maxPendingConnections": 20,
"reconnect": { "initialDelaySeconds": 1, "maxDelaySeconds": 30, "permanentErrorDelaySeconds": 60 }
}
]
}
A committable sanitized example lives at Agent Config Example. --check-config validates all profiles in one pass: unknown or duplicate JSON properties, duplicate profileId values, invalid port ranges (outboundPortRangeStart must be 1024..65535 and <= outboundPortRangeEnd, and serverPort != dataPort), invalid CA data, placeholder or weak secrets, invalid quotas, or summed profile maxConnections exceeding the process limit all fail validation. Control TLS validates strictly against that profile's trustedCaPemBase64 with no cross-profile or OS trust-store fallback. Top-level legacy single-server keys, local channels, outbound mappings, and access secrets are disallowed. Server downloads produce this same schema with a single servers[] entry defaulting to profileId=primary; importing in the local Agent UI confirms or assigns a locally unique profileId without overwriting existing profiles. A Server admin API never touches another Server's credentials.
Each profile has an optional enabled flag defaulting to true so existing configs and Server downloads connect automatically. Setting enabled=false preserves registration settings, secret, and state/<profileId>/ while preventing the Agent from opening a control session for that profile. Disabled profiles are still validated for endpoint, secret, CA, and quota rules. See Agent Config Example.
3. Runtime Contexts and Protocol Isolation
The Agent (AgentProcessRuntime) creates an independent runtime context for each enabled profileId, encapsulating read-only connection settings, private CA certificates, E2E identity, control session (ControlSessionWorker), confirmed snapshot, heartbeat and reconnect state, pending/active connection registries, port mapping state, virtual HTTP host (HttpProxyRuntime), peer/direct coordinator (PeerSessionCoordinator / PeerDirectAgentAttempt), update coordinator (AgentUpdateCoordinator), quotas, and cancellation tokens. Across the process, only the local HTTP listener (AgentLocalDashboard), loopback port allocator (AgentPortAllocator), and process config write lock are shared. Asynchronous tasks are supervised per context so an exception in one session cancels only that profile's tasks and never triggers the process shutdown token. On shutdown, all contexts are cancelled and drained together.
Wire formats for Register, ConfigUpdate, ConfigAck, Open, Bind, peer relay, and peer direct messages remain unchanged. Every TCP or QUIC connection is bound at creation to a single profile context; data dialing targets that profile's serverHost/dataPort, and bind tokens belong solely to that Server's active control session. Internal lookups for channels, mappings, connections, and states use (profileId, resourceId) rather than bare resource IDs. References received from a Server resolve strictly within that context's confirmed snapshot; two Servers using identical IDs can never cross-resolve targets. Peer callers and targets must belong to authenticated sessions on the same Server; concurrent registration with another Server on the same Agent provides no bridging path.
Each profile independently verifies the config digest and requires snapshot clientId to match its configured clientId, treating mismatches as permanent config errors. Valid snapshots atomically replace that profile's state; invalid snapshots reject only that profile's update or session while leaving others untouched. Control disconnect clears only that profile's online snapshot, cancels its pending/active/direct attempts, and closes its local listeners without disturbing sibling profiles. Heartbeat tracking, permanent-error slow retry, and network backoff run per profile. Server-side revocation on session or channel changes continues to operate independently within each Server.
4. End-to-End Identity and Local Entry Listeners
The multi-server layout stores per-profile state in protected state/<profileId>/ directories containing identity.pfx, ports.json, and relaylink-diagnostics.jsonl. Renaming profileId creates a new profile without silently inheriting prior state; E2E fingerprint changes continue to follow explicit verification and rotation per ADR-0011. Even when two Servers share the same clientId, each profile uses distinct private keys, trusted CAs, and state files. Legacy identity and port state files are moved into the initial profile's state directory by the pre-start migrator; the Agent executable does not read legacy filenames. Server config downloads never contain Agent private keys.
Port state is keyed by (profileId, mappingId). The process-wide AgentPortAllocator serially reserves and binds 127.0.0.1 loopback ports within outboundPortRangeStart–outboundPortRangeEnd, persisting results to state/<profileId>/ports.json. On restart, it prefers the previously recorded port and picks another port in range if occupied by another profile or host process. Persistence writes to a unique temporary file in the same directory before atomic replacement; on Windows, transient access-denied or sharing violations retry briefly while holding the in-process port lock, failing only that mapping bind if retries are exhausted. PeerMappingStatus is reported to a Server only after its snapshot version is confirmed and local ports are actually bound. Failure of a single mapping listener cleans up only that entry; sibling entries and sibling Servers keep running. Stopping or disconnecting a profile releases only the listeners owned by that profile.
5. Quotas and Fault Isolation
Each profile defaults to maxConnections=100 and maxPendingConnections=20, both adjustable, with a process-wide default of maxConnections=2000. Configuration validation enforces that the sum of profile maxConnections does not exceed the process cap and each profile's maxPendingConnections <= maxConnections. Connections acquire their profile quota before allocating buffers and tasks, releasing via one-shot leases. The process cap serves as an upper bound against misconfiguration; normal runtime load on one profile cannot consume another profile's reserved quota. Control send queues, per-connection buffers, and target dial tasks remain bounded so a noisy or slow-reading Server cannot build an unbounded work queue. Shared CPU, disk, egress network, and OS handles remain host-level shared resources; runtime logging records quota rejections per profile without promising hardware-fault isolation across profiles.
Logs and diagnostics include profileId, the corresponding clientId, and relevant sessionId, connectionId, and attemptId values, while omitting secrets, tokens, CA PEM bodies, private keys, and application payloads. Single-profile auth rejections, invalid updates, port conflicts, disconnects, and target dial errors are reported for that profile while sibling profiles keep running.
The Agent uses RelayLink.Logging for unified file logging, and the local web host reuses the process ILoggerFactory. Profile workers attach profileId and clientId in their logging scope, logging the error code, rejection reason, and phase upon receiving rejection frames before entering slow retry without affecting other profiles. Log formats, retention, tool modes, rejection compatibility, and operational diagnostic boundaries are specified in Logging and Diagnostics Design, and paths/troubleshooting are covered in Installation and Usage Guide.
6. Local Monitoring Dashboard and Management API
The local monitoring UI is built as the standalone RelayLink.AgentWeb React/TypeScript/Vite project; Agent builds and publishes copy its static bundle into wwwroot/ hosted by the single loopback-only Kestrel instance. The UI consumes grouped v2 APIs for status and session management rather than embedding HTML/JS strings in C#. Visual components match the Server Admin UI while build and deployment boundaries stay separate per ADR-0021.
The UI groups entries by profileId, displaying online/disabled state, clientId, channels, local mappings (including peerRoutingPolicy badges and active direct_quic / direct_tcp / relay paths), and assisted-update banners, along with "Add Server", "Import Update", "Disable/Enable", and "Delete" actions. Add and update flows accept only single-server JSON files exported by a Server—there are no arbitrary manual parameter editors. Adding automatically selects a locally unique profileId (appending a numeric suffix on collision); updating selects an existing profile and preserves its local profileId. Previews show only non-sensitive fields, and imported secrets are cleared from browser memory after submission, failure, or modal dismissal. Saved profiles never expose secret prefill, display, copy, or download. Deletion warns that local connections will stop while remote client records and secrets remain managed on the remote Server. Deleting the last profile leaves an empty state with an add action.
Adding permits only a non-existent profileId; if protected state from a previously deleted profile with the same profileId exists, the UI requires explicit confirmation (confirmExistingState) that it still belongs to the same Server identity rather than silently reusing it. Updating uses explicit JSON import and requires clientId to match the existing profile; switching to a different clientId requires adding a new profile and verifying its identity on the Server. Add and update mutations validate the complete profile, global quotas, CA, and secret before persistence, then start or restart the context if enabled. An unreachable remote Server does not roll back a save; the profile remains offline and retries independently. Deletion atomically persists the removed profile first, cancels that profile's session, connections, and listeners, and awaits resource cleanup before returning success. Failed saves leave runtime state and on-disk configuration unchanged. Write operations serialize against the current config version, returning conflict on stale versions to prevent lost updates across tabs. Persistence writes to a restricted temporary file in the same directory, flushes to disk, and atomically replaces the config without logging secrets or creating readable backups. Only local API writes trigger live runtime updates; manual file edits still require an Agent restart.
Anonymous read endpoints are GET /api/v2/status, GET /api/v2/channels, and GET /api/v2/mappings, each returning a servers[] array with profileId, serverHost, useTls, enabled, clientId, online, updatedAtUtc, and resource lists. Offline or disabled groups retain identity and state with empty resource lists so stale addresses are never presented as usable. Write endpoints are POST /api/v2/admin/servers, PUT /api/v2/admin/servers/{profileId}, DELETE /api/v2/admin/servers/{profileId}, and PUT /api/v2/admin/servers/{profileId}/enabled; they require a local write session and CSRF token without a management password. Updates match the existing profileId and clientId, validate and persist first, then stop the old context and start the new one according to enabled, preserving E2E identity and port bindings. All GET routes use allowlisted DTOs and never return saved secrets, CA bodies, private keys, or access secrets; write request bodies and validation errors are never logged. The listener binds strictly to 127.0.0.1, sets Cache-Control: no-store on all responses, disables CORS, caps request size (1 MiB), rejects cross-site origins, and enforces a strict CSP blocking external scripts.
On opening management actions, the UI calls GET /api/v2/admin/session to obtain a short-lived HttpOnly, SameSite=Strict session cookie, csrfToken, and current config version; DELETE /api/v2/admin/session explicitly ends the session. Write requests verify loopback Host, same-origin Origin, Sec-Fetch-Site / Sec-Fetch-Dest, the session cookie, and the X-RelayLink-CSRF header. Per ADR-0034, the earlier X-RelayLink-Local-Token header and local-management.token file were removed because reading a local token file added no real security on a single-user workstation. Registration secrets exist in browser memory only during import/submission and never appear in read APIs. Loopback reads remain reachable by local processes on the same machine, while origin and CSRF checks block cross-site forgery from other browser tabs.
The threat model assumes a single-user or admin-operated workstation: do not run the Agent as LocalSystem or root on multi-user machines where unprivileged users can reach the local UI and alter outbound connections. Run under a dedicated low-privilege service account whenever possible, restricting config directory ACLs to that account and administrators. Importing a profile with useTls=false requires submitting confirmInsecureTransport=CONNECT_WITHOUT_TLS, typed manually in the UI. Every successful add, update, delete, or enable/disable toggle logs an Agent file audit entry containing profileId, host, port, useTls, and clientId without secrets, CAs, or tokens; plaintext control connections log at Warning. This audit log cannot be silenced independently.
Existing /api/v1/* and /api/status endpoints keep their original response shape when exactly one profile is configured, and return 409 Conflict with a non-sensitive hint pointing to /api/v2/* when multiple profiles exist instead of arbitrarily picking one Server. Setting dashboardPort=0 disables both the local UI and APIs. Server dashboards remain unchanged, displaying only their own sessions and mappings. Local UI mutations operate strictly on the multi-server schema and never perform legacy migration.
The local UI distinguishes "Disabled" from network "Offline"; toggling enable/disable requires no JSON import. PUT /api/v2/admin/servers/{profileId}/enabled takes the config version and target boolean enabled, protected by the same write session, same-origin, and CSRF checks. Disabling persists first, then stops that profile's control session, active connections, reconnect loop, and local listeners before returning. Re-enabling persists first and starts the profile session while preserving its E2E identity and port state. Neither action restarts other profiles, and failed saves leave runtime state unchanged. Importing an update preserves the current enabled state rather than re-enabling a disabled profile from the downloaded file. See ADR-0023.
7. Existing Agent Upgrades and Configuration Migration
RelayLink.Agent.ConfigMigrator is a standalone pre-start migrator accepting an Agent config path. It converts legacy single-server JSON into a single-entry servers[] config with a stable profileId (default primary), fills default ports and process settings, and preserves clientId, secret, endpoint settings, and TLS trust semantics. When legacy config uses trustedCaPemPath, the migrator reads and validates the public CA certificate and embeds it as trustedCaPemBase64; the Agent executable does not resolve legacy path fields. During upgrade of an installed Agent, the migrator moves <clientId>.e2e.pfx and <clientId>.ports.json into protected state/primary/, verifying fingerprint and port consistency so the Agent reads only state/<profileId>/ afterward. Original config and legacy state files remain as protected rollback material and are never reused as runtime inputs or bound to a second profile.
The migrator strictly validates legacy input and prepares new state files in the protected directory first; only after state files are written, permission-restricted, and verified does it atomically replace the config file via a restricted temporary file. Replacing the config file is the commit point: any failure before it leaves legacy config and state intact for retry without exposing partial state to the Agent; after it, referenced state files are guaranteed complete. Retries verify that prepared files match legacy sources and never overwrite inconsistent existing state. Already-migrated configs are validated read-only and exit 0 without touching files or generating identities; failures exit non-zero and halt startup without passing legacy config to the Agent. Error messages never include secrets, CA PEMs, or private keys. Final cleanup of legacy backup files is an explicit operator step.
All delivery entrypoints enforce "migrator success -> Agent start": the Windows installer's update-only mode runs the migrator after stopping the service and replacing binaries before restarting; Linux systemd uses ExecStartPre; macOS launchd uses a wrapper script that runs the migrator then execs the Agent; console and manual deployments run the migrator beforehand. Subsequent restarts still run the migrator in read-only validation mode. Bypassing startup wrappers to launch the new Agent directly against a legacy config fails clearly and exits rather than silently falling back in the loader, session, or UI. Linux/macOS package upgrades replace only the program directory and preserve the state directory.
Fresh installs and reconfiguration flows in the Windows installer accept only the multi-server schema, validating completely before touching any protected runtime config location and rejecting legacy input before stopping or cleaning an existing installation. Modern Servers export the single-entry multi-server schema directly. Legacy Server downloads can be pre-converted via the migrator's standalone single-file-to-file mode without touching installed Agent state; the installer never calls this implicitly. Reconfiguration preserves its semantic of clearing Agent-managed config and identity before writing the new config and warns that pinned fingerprints and entry ports may change. Neither path leaves legacy config in the runtime directory.
After migration completes, the legacy client re-registers with its original secret and E2E certificate; restarting disconnects active TCP tunnels so business apps reconnect. The Server-pinned fingerprint remains unchanged, and ports.json prefers previously assigned loopback ports. Subsequent UI additions append new entries to servers[] without re-running migration or interrupting existing profiles. Deleting the migrated primary profile removes it from servers[] and stops its context while leaving state/primary/ protected; reusing primary later requires confirming association with the original Server.
8. Verification and Implementation Order
Implementation proceeded from the standalone migrator, platform startup hooks, and strict multi-server config loader, to per-profile control/forwarding contexts, global port allocation, local v2 status and write APIs, and finally A61–A69. Automated tests cover colliding clientIds with distinct CAs/secrets, cross-server rejection of valid bind tokens, continued operation of sibling profiles during downtime or bad snapshots, concurrent multi-server high-throughput streams and half-close, cross-profile capacity isolation when one profile is saturated, live UI add/delete including deleting the last profile, active stream termination on profile removal, save-failure retry and version conflicts, interrupted and retried state migration, adding a second profile after migration and restarting, and port collisions across identically named peer mappings. Port reuse after state migration was verified with real peer connections, and CLI tests verify that legacy configs are rejected by the Agent and converted outputs pass --check-config.
Windows Sandbox testing used newly built installers and synthetic configs: fresh installs wrote exact SHA-256 matches under LocalService-only ACLs; both fresh install and reconfigure rejected legacy JSON before stopping services or clearing state; reconfiguring replaced ACL-restricted state and restarted cleanly; pre-converted legacy downloads succeeded in reconfigure; simulated update-only upgrades preserved legacy backups, E2E identity hashes, and port state across repeated runs; and intentional state conflicts caused non-zero installer exit with intact legacy state and stopped service. Quota unit tests verify idempotent release, integration tests verify capacity recovery after saturated runs, and UI, API, error, diagnostic, and Sandbox installer logs were scanned for secret leakage. Detailed evidence is recorded in Multi-Server Verification. This document remains Draft pending formal architecture review sign-off.