This document specifies how the main server discovers VMs running the expansion software and enrolls them into the farm, modeled on SQL Server Browser network discovery. Scope: one site, multiple IP subnets, routed between them, no NAT on the node-to-main path. The design is implementation-ready but not yet implemented.
Approach summary
SQL Server discovery works because every machine running SQL Server runs the SQL Server Browser service on a well-known UDP port (1434); a client broadcasts one probe packet and every Browser answers with its instance list. Discovery therefore equals "a well-known UDP port plus a responder on it".
Because the site spans multiple subnets, plain broadcast alone cannot reach every node (routers do not forward broadcasts). The design layers four mechanisms and reconciles their results into one table:
| # | Mechanism | Reach | Role |
|---|---|---|---|
| 1 | Self-registration + heartbeat | Any routable path | Primary backbone; works across subnets and survives reboots |
| 2 | UDP discovery probe (broadcast + directed broadcast) | Same subnet; other subnets only where directed broadcast is allowed | Instant push-button discovery, no configuration on the node |
| 3 | TCP sweep of configured CIDR ranges | Any routed subnet | Fallback for nodes that never registered |
| 4 | Manual entry | Always | Escape hatch |
Discovery never grants membership. A found node is a candidate; joining the farm always requires the enrollment handshake below.
Ports
| Port | Transport | Direction on node | Purpose |
|---|---|---|---|
| 48515 | UDP | Inbound | Discovery responder (probe / reply) |
| 48516 | TCP | Inbound | Discovery sweep endpoint (same reply payload) |
| 3000 (existing API) | TCP | Outbound | Enrollment REST call and heartbeat Socket.io connection |
All ports are configurable via environment variables. The responder
runs inside the existing NodeBackend service; no additional
Windows service is required.
Discovery protocol
Probe packet (main server → UDP 48515)
Fixed-size binary datagram:
| Offset | Size | Field |
|---|---|---|
| 0 | 4 | Magic bytes LPRD |
| 4 | 1 | Protocol version (start at 1) |
| 5 | 16 | Nonce (random) |
| 21 | 32 | HMAC-SHA256 over bytes 0..20 using the farm secret |
The scanner sends the probe three times: once as subnet broadcast
(255.255.255.255), and once as a directed broadcast to each configured
subnet (x.x.x.255), then optionally unicast to each address
during a TCP sweep.
Reply packet (node → unicast to sender)
JSON, one datagram:
{
"serviceId": "b7e2c9a0-...-uuid, stable per install",
"hostname": "expansion-vm-03",
"appVersion": "2.4.1",
"roles": ["camera-relay", "ocr-worker"],
"apiPort": 3000,
"nonce": "hex echo of the probe nonce"
}
Responder rules:
- Silently drop datagrams with wrong magic, unknown version, or invalid HMAC.
- Echo the nonce so the scanner can match replies to its own probes and reject spoofed replies.
- Rate-limit replies per source IP (default 10/minute) so the port cannot be used as a traffic amplifier.
- Never include secrets in the reply; identity fields only.
The TCP endpoint on 48516 accepts one connection, expects the same probe bytes, and answers with the same JSON followed by connection close. This gives sweeps a reliable handshake where UDP is filtered.
Scan reconciliation
POST /expansion/discovery/scan performs all three
network mechanisms in parallel with a 3-second collection window and
merges results:
- Deduplicate by
serviceId(one node may answer on several IPs; keep the IP list). - Cross-reference the
expansion_nodestable to label each candidatenew,known(enrolled and healthy),offline(enrolled, no heartbeat), orduplicate(sameserviceIdseen from more than one IP — see below). - Stream each merged candidate to the frontend over the existing
Socket.io connection (
expansion:scan-resultevent) so the table fills in live.
Enrollment flow
- An administrator generates an enrollment token in the main UI. The token is single-use with a TTL (default 24 hours) and is bound to nothing else.
- The expansion node is configured with the main server URL and the
enrollment token (installer flag or
.enventry). - The node calls
POST /expansion/enrollwith the token plus its identity (serviceId, hostname, app version, roles, API port). The main server validates the token, creates or reactivates the node row, and returns a long-lived node token. - The node stores the node token and opens a Socket.io connection to
the main server (existing server,
expansionnamespace), authenticating with the node token. - The node emits a heartbeat every 15 seconds carrying status: uptime,
app version, role health, and current workload counters. The main server
marks a node
offlineafter 3 consecutive missed heartbeats (45 seconds). - Node removal or re-keying revokes the node token; the node stops being trusted on its next heartbeat.
Because enrollment is initiated by the node toward the main server, it works across every subnet that can reach the main API — this is why registration is the backbone rather than broadcast.
Data model (Prisma sketch)
model ExpansionNode {
id String @id // serviceId GUID, generated once at install
hostname String
appVersion String
roles String
apiPort Int
status String // online | offline | disabled
lastHeartbeat DateTime?
nodeTokenHash String
createdAt DateTime
updatedAt DateTime
}
model EnrollmentToken {
token String @id
createdAt DateTime
expiresAt DateTime
usedAt DateTime?
usedBy String? // serviceId that consumed it
}
serviceId is persisted in the node's own database/config
so it survives reboots. If the same serviceId ever reports
from a different IP, the main server flags the node
duplicate and the UI surfaces a prominent warning — this is
the classic cloned-VM failure mode (a snapshot restored from an image
keeps the old id). Remediation: a regenerate-id command on
the cloned node.
Backend module layout (NestJS)
DiscoveryModule
├── ResponderService // binds UDP 48515 + TCP 48516 at boot, verifies HMAC, rate-limits
├── ScannerService // broadcast + directed broadcast + CIDR sweep, merge + dedupe
├── NodeRegistryService // heartbeats, online/offline transitions, duplicate detection
├── EnrollmentService // enrollment tokens, token exchange
└── ExpansionController
├── POST /expansion/discovery/scan // runs a scan, returns merged candidates
├── GET /expansion/nodes // enrolled nodes with status
├── POST /expansion/enrollment-tokens // create token (admin)
├── POST /expansion/enroll // called BY the node
└── DELETE /expansion/nodes/:id // revoke and remove
All controller routes sit behind the existing JWT role/permission
guards. Socket.io gateway additions: expansion namespace
(node → main heartbeats) and expansion:scan-result (main →
frontend live scan rows).
Frontend UX
Settings → Expansion Nodes page:
- Discover button → progress indicator, live table streaming in (IP, hostname, version, roles, source, status).
- Administrator selects candidates and clicks Enroll; the UI shows the enrollment token to paste into the node's installer/config.
- Enrolled nodes list with online/offline state, last heartbeat, and actions (disable, revoke, remove).
- Duplicate
serviceIdrows render as an error state, not a normal row.
Firewall and installer requirements
- The node installer (portable release
service.ps1) must create Windows Firewall inbound rules for UDP 48515 and TCP 48516. Without them the node is invisible to broadcast and sweep discovery (registration still works). - The main server needs no new inbound rules; it only dials out for probes and receives enrollment/heartbeats on the existing API port.
- Hypervisor note: broadcast reaches VMs on the same virtual switch or port group. Directed broadcast across subnets is opportunistic — many routers and virtual switches drop it, which is expected and why registration is primary.
Security considerations
- The farm secret (HMAC key) ships in the installer
.env; rotating it invalidates old probes, so rotation is a maintenance action, not routine. - Discovery replies expose only identity fields, and only to holders of the farm secret (unsigned probes are ignored).
- Enrollment tokens are single-use and expiring; node tokens are long-lived but revocable, stored hashed.
- Transport between node and main currently rides the trusted site LAN as plain HTTP like the rest of the API; when TLS termination is added fleet-wide, enrollment and heartbeats inherit it automatically.
- Rate limiting on the responder prevents discovery amplification abuse.
Configuration reference
| Variable | Default | Applies to | Purpose |
|---|---|---|---|
DISCOVERY_UDP_PORT |
48515 | both | UDP responder / probe port |
DISCOVERY_TCP_PORT |
48516 | both | TCP sweep responder port |
FARM_SECRET |
— | both | HMAC key for probe/reply |
DISCOVERY_SUBNETS |
local subnet | main | Extra CIDRs for directed broadcast, comma-separated |
DISCOVERY_SWEEP_ENABLED |
false | main | Enable TCP CIDR sweep (slower) |
DISCOVERY_COLLECT_MS |
3000 | main | Reply collection window |
MAIN_SERVER_URL |
— | node | Main API base URL for enrollment + heartbeat |
HEARTBEAT_INTERVAL_MS |
15000 | node | Heartbeat period |
HEARTBEAT_OFFLINE_AFTER |
3 | main | Missed heartbeats before offline |
Future work
- mDNS/DNS-SD advertisement if third-party tools should also see the nodes.
- Cross-site or cloud deployments: registration already works, but sweep and broadcast become meaningless there; a cloud mode would drop them.
- Node capability negotiation during enrollment (camera capacity, license seats) once expansion roles are defined.