@yuriai/relay-server 0.2.25 → 0.2.27-beta.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/DOCUMENTATION.md +43 -1
- package/README.md +97 -0
- package/package.json +8 -3
- package/src/core.js +338 -0
- package/src/index.js +25 -312
- package/src/worker-socket.js +52 -0
- package/src/worker.js +55 -0
- package/wrangler.jsonc +15 -0
package/DOCUMENTATION.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Relay Server Package Documentation
|
|
2
2
|
|
|
3
|
-
`packages/relay-server/` owns the self-hosted Layer 1 Relay server, the isolated Push Relay process, the `yuri-relay` and `yuri-push-relay` CLIs, and the package release and deployment contract.
|
|
3
|
+
`packages/relay-server/` owns the self-hosted Node and Cloudflare Workers Layer 1 Relay server, the isolated Push Relay process, the `yuri-relay` and `yuri-push-relay` CLIs, and the package release and deployment contract.
|
|
4
4
|
|
|
5
5
|
## Purpose and security boundary
|
|
6
6
|
|
|
@@ -12,6 +12,48 @@ Relay v1 admission accepts anonymous Client route requests. Per-IP, global, pend
|
|
|
12
12
|
|
|
13
13
|
The Relay keeps process-local routing state only. Hosts reconnect after Relay restarts, and a control disconnect retains its Host route for the 30-second grace period.
|
|
14
14
|
|
|
15
|
+
### Shared core and runtime ownership
|
|
16
|
+
|
|
17
|
+
- `src/core.js` owns the common Layer 1 parser, P-256 verification, replay and
|
|
18
|
+
admission records, host/client/data routing, control epochs, grace/pending
|
|
19
|
+
timers, queue limits and fair forwarding. Both runtimes call it; there is no
|
|
20
|
+
separate Worker protocol implementation. `node:crypto` and `node:buffer` use
|
|
21
|
+
Workers' `nodejs_compat`. Verification passes a JWK directly to `crypto.verify`
|
|
22
|
+
so it works in both Node and workerd; crypto import/verify failures reject auth.
|
|
23
|
+
- `src/index.js` owns Node HTTP/TCP admission, `ws` upgrades, heartbeat scheduling,
|
|
24
|
+
listener lifecycle and process snapshots. Its public API is unchanged.
|
|
25
|
+
- `src/worker.js` owns the Worker entry and `YuriRelay` Durable Object. All
|
|
26
|
+
requests go to one named object (`relay-v1`), so core-wide limits remain global
|
|
27
|
+
to one deployment. Do not shard by host without explicitly changing those
|
|
28
|
+
limits. Object routing state is ephemeral; restarts reconnect, not restore.
|
|
29
|
+
- `src/worker-socket.js` adapts Workers EventTarget sockets to core callbacks.
|
|
30
|
+
Binary delivery is explicitly `arraybuffer`; text/binary distinctions and byte
|
|
31
|
+
order are preserved. Runtime send exceptions feed the shared teardown path.
|
|
32
|
+
|
|
33
|
+
Workers uses **ordinary WebSocket acceptance, not hibernation**. In-memory queues,
|
|
34
|
+
timeouts and replay/admission records are not serialized. Open sockets keep the
|
|
35
|
+
object active and billable. Workers has no application-visible TCP backpressure
|
|
36
|
+
or send drain: Node's pause/resume and native-buffer guarantees are not portable.
|
|
37
|
+
Core queue caps still apply, but cannot bound runtime-owned outbound buffers.
|
|
38
|
+
Cloudflare owns raw TCP/ping-pong handling; core heartbeat scheduling remains
|
|
39
|
+
Node-only. Host/Client keepalives and reconnection remain unchanged. A frame is
|
|
40
|
+
size-checked after Cloudflare has fully received it, unlike `ws`'s parser limit.
|
|
41
|
+
|
|
42
|
+
Workers trusts only `CF-Connecting-IP` supplied by Cloudflare's public ingress.
|
|
43
|
+
No incoming `X-Forwarded-For` or application routing header can select a different
|
|
44
|
+
object or bypass deployment-wide limits. Malformed/auth/limit rejections preserve
|
|
45
|
+
the existing WebSocket close codes. Health output contains no route metadata.
|
|
46
|
+
The Worker mounts no Push handlers and takes no Apple credentials. A Host using
|
|
47
|
+
it needs an explicit separate `YURI_PUSH_RELAY_URL` for APNs delivery.
|
|
48
|
+
|
|
49
|
+
`wrangler.jsonc` is shipped with the package and defines the binding and initial
|
|
50
|
+
SQLite-class migration (available on Workers Free); the core does not use SQL.
|
|
51
|
+
It deliberately contains no account ID, domain or credentials and disables
|
|
52
|
+
observability/preview URLs. Normal redeploys retain binding and migration history;
|
|
53
|
+
rollback redeploys a known-good version without deleting the namespace. Detailed
|
|
54
|
+
auth, cost, local validation and deployment commands are in README's Cloudflare
|
|
55
|
+
Workers section.
|
|
56
|
+
|
|
15
57
|
Layer 1 and Push are separate processes in this package. Layer 1 never holds APNs credentials or the device-token database. Push never sees Relay tunnel frames, pairing secrets, or client bearer credentials. Give Apple secrets only to the Push process. SQLite token storage is single-instance: one Push process per database file.
|
|
16
58
|
|
|
17
59
|
## Quick deployment
|
package/README.md
CHANGED
|
@@ -79,6 +79,103 @@ Layer 1 (`yuri-relay`) and Push (`yuri-push-relay`) are separate processes in on
|
|
|
79
79
|
- Single-file Layer 1 bundle build: Bun. This repository uses Bun 1.3.14. Do not Bun-compile the Push entry; Docker runs it with Node 24.
|
|
80
80
|
- Public deployment: a DNS name, TLS certificate, reverse proxy, and firewall policy appropriate for the deployment.
|
|
81
81
|
|
|
82
|
+
### Cloudflare Workers
|
|
83
|
+
|
|
84
|
+
Layer 1 also runs on Workers with a Durable Object. Node/Docker and Workers use
|
|
85
|
+
the **same** routing, P-256 authentication, replay protection, admission limits,
|
|
86
|
+
pair lifecycle and forwarding queues in `src/core.js`. Only HTTP/WebSocket I/O
|
|
87
|
+
differs. Existing Yuri Hosts and Clients do not need a protocol or encryption change.
|
|
88
|
+
This does not move the Node APNs Push service to Workers.
|
|
89
|
+
|
|
90
|
+
From the repository root:
|
|
91
|
+
|
|
92
|
+
```sh
|
|
93
|
+
bun run --cwd packages/relay-server worker:dev
|
|
94
|
+
bun run --cwd packages/relay-server worker:build
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
The commands use a pinned Wrangler through `npx`; no Wrangler dependency is added
|
|
98
|
+
to the application. The build command is a dry run and creates no cloud resources.
|
|
99
|
+
For a public staging deployment, authenticate locally first:
|
|
100
|
+
|
|
101
|
+
```sh
|
|
102
|
+
npx --yes wrangler@4.156.1 login
|
|
103
|
+
bun run --cwd packages/relay-server worker:deploy
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
Alternatively supply `CLOUDFLARE_API_TOKEN` and `CLOUDFLARE_ACCOUNT_ID` through
|
|
107
|
+
the process environment. Use an account-scoped Workers Scripts Edit token; add
|
|
108
|
+
Account Settings Read if needed for account discovery. Custom-domain deployment
|
|
109
|
+
additionally needs the relevant zone permissions. Never put tokens in chat,
|
|
110
|
+
source files, Wrangler configuration or command arguments.
|
|
111
|
+
|
|
112
|
+
The default Worker name is `yuri-relay-worker`; change it or pass `--name` before
|
|
113
|
+
deploying if that service already exists. Wrangler prints a `https://…workers.dev`
|
|
114
|
+
URL; use the same hostname as `wss://…workers.dev/ws` in **Add a device**. This does
|
|
115
|
+
not change the product default or replace existing saved pairing endpoints.
|
|
116
|
+
Production may use a Cloudflare-managed custom domain via Wrangler `routes` with
|
|
117
|
+
`custom_domain: true`. Do not check personal deployment domains/account IDs into
|
|
118
|
+
the repository. Set them through a local configuration outside the repository or
|
|
119
|
+
the Cloudflare dashboard.
|
|
120
|
+
|
|
121
|
+
Operational boundaries:
|
|
122
|
+
|
|
123
|
+
- A single Durable Object coordinates the deployment, preserving deployment-wide
|
|
124
|
+
limits. This is not a horizontally sharded implementation. Active routes and
|
|
125
|
+
replay/admission records are ephemeral, just like Node. Deployment/restart can
|
|
126
|
+
disconnect sockets; Hosts and Clients reconnect. Do not delete/recreate the
|
|
127
|
+
Durable Object binding or migration to perform a normal update or rollback.
|
|
128
|
+
- This version uses **ordinary accepted WebSockets, not Hibernation**. Open
|
|
129
|
+
connections keep the object active and can incur duration charges even when
|
|
130
|
+
quiet. Free-plan quotas are finite; paid usage may exceed its base allocation.
|
|
131
|
+
Do not enable a paid plan without the account owner's approval.
|
|
132
|
+
- Workers exposes no TCP pause/resume, send-completion callback or documented
|
|
133
|
+
`bufferedAmount`. Shared limits bound application-owned queues and frame sizes,
|
|
134
|
+
but cannot bound or observe Cloudflare's outbound runtime buffers. Node's TCP
|
|
135
|
+
backpressure guarantee does **not** apply to Workers. Benchmark slow receivers
|
|
136
|
+
and remote-desktop traffic before adopting it as a production replacement.
|
|
137
|
+
- Cloudflare handles TCP admission and ping/pong frames. Node-only raw-TCP and
|
|
138
|
+
server-initiated heartbeat controls do not apply; existing Host/Client liveness
|
|
139
|
+
checks still apply. Per-IP limits use Cloudflare's `CF-Connecting-IP`, never
|
|
140
|
+
client-provided `X-Forwarded-For`.
|
|
141
|
+
- Workers accepts complete frames before application code can reject them.
|
|
142
|
+
The default shared 128-KiB frame limit is enforced **after** runtime receipt.
|
|
143
|
+
Cloudflare ingress/WAF limits and account budgets remain important.
|
|
144
|
+
- Only Layer 1 `/ws`, `/healthz`, and `/readyz` are provided. APNs notification
|
|
145
|
+
delivery requires an existing standalone Push service plus an explicit Host
|
|
146
|
+
`YURI_PUSH_RELAY_URL`, or is unavailable on this endpoint.
|
|
147
|
+
- Observability and preview URLs are disabled in the supplied configuration.
|
|
148
|
+
Do not enable logging of WebSocket query strings: they contain Host signatures
|
|
149
|
+
and public keys. No Apple secrets, client bearer tokens or pairing keys are
|
|
150
|
+
required for Layer 1 deployment.
|
|
151
|
+
|
|
152
|
+
`YURI_RELAY_PATH` defaults to `/ws`. Optional `YURI_RELAY_LIMITS_JSON` accepts an
|
|
153
|
+
object of positive-integer overrides using the same camelCase names as `Limits`
|
|
154
|
+
in `src/index.d.ts`. Invalid configuration fails closed. TCP-only overrides have
|
|
155
|
+
no effect on Workers. Configure cloud variables in the dashboard or a local
|
|
156
|
+
Wrangler config; `.dev.vars` and `.wrangler/` are ignored.
|
|
157
|
+
|
|
158
|
+
Validate against a **dedicated** local or staging Worker (these tests intentionally
|
|
159
|
+
trigger rejection limits; do not target a shared production Relay):
|
|
160
|
+
|
|
161
|
+
```sh
|
|
162
|
+
# Terminal 1: pin the local port.
|
|
163
|
+
bun run --cwd packages/relay-server worker:dev --port 18787
|
|
164
|
+
|
|
165
|
+
# Terminal 2: the same wire-contract suite runs against Node AND real workerd.
|
|
166
|
+
YURI_RELAY_WORKER_TEST_URL=ws://127.0.0.1:18787/ws \
|
|
167
|
+
bun run --cwd packages/relay-server test:worker
|
|
168
|
+
|
|
169
|
+
# Real Host/TypeScript Client, E2EE, authenticated HTTP/SSE and remote desktop.
|
|
170
|
+
YURI_RELAY_WORKER_TEST_URL=ws://127.0.0.1:18787/ws \
|
|
171
|
+
bunx vitest run --project @yuriai/web \
|
|
172
|
+
packages/web/server/lib/relay/relay-server.e2e.test.ts -t 'across Workers'
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
Without `YURI_RELAY_WORKER_TEST_URL`, Worker network tests are explicitly skipped;
|
|
176
|
+
adapter/unit tests and the Node protocol half still run. A local pass does not
|
|
177
|
+
prove public DNS, regional connectivity, production quotas or slow-peer behavior.
|
|
178
|
+
|
|
82
179
|
## Install and quick start
|
|
83
180
|
|
|
84
181
|
`yuri-relay` ships as an executable in the public `@yuriai/relay-server` package.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yuriai/relay-server",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.27-beta.11",
|
|
4
4
|
"description": "Self-hosted private relay server for Yuri",
|
|
5
5
|
"private": false,
|
|
6
6
|
"type": "module",
|
|
@@ -40,14 +40,19 @@
|
|
|
40
40
|
"files": [
|
|
41
41
|
"bin",
|
|
42
42
|
"src",
|
|
43
|
+
"wrangler.jsonc",
|
|
43
44
|
"README.md",
|
|
44
45
|
"DOCUMENTATION.md"
|
|
45
46
|
],
|
|
46
47
|
"scripts": {
|
|
47
48
|
"test": "vitest run",
|
|
49
|
+
"test:worker": "vitest run test/worker.test.js test/worker-parity.test.js",
|
|
50
|
+
"worker:dev": "npx --yes wrangler@4.156.1 dev --config wrangler.jsonc --local",
|
|
51
|
+
"worker:build": "npx --yes wrangler@4.156.1 deploy --config wrangler.jsonc --dry-run --outdir dist/worker",
|
|
52
|
+
"worker:deploy": "npx --yes wrangler@4.156.1 deploy --config wrangler.jsonc",
|
|
48
53
|
"test:node": "node test/node-smoke.js",
|
|
49
|
-
"type-check": "node --check src/index.js && node --check src/cli.js && node --check bin/yuri-relay.js && node --check bin/cli-entry.js && node --check src/push/index.js && node --check src/push/server.js && node --check src/push/cli.js && node --check src/push/config.js && node --check src/push/schema.js && node --check src/push/crypto.js && node --check src/push/store.js && node --check src/push/cached-store.js && node --check src/push/store-worker.js && node --check src/push/guard.js && node --check src/push/apns.js && node --check bin/yuri-push-relay.js && node --check src/push/handler.js && node --check src/push/combined.js",
|
|
50
|
-
"lint": "node --check src/index.js && node --check src/cli.js && node --check bin/yuri-relay.js && node --check bin/cli-entry.js && node --check src/push/index.js && node --check src/push/server.js && node --check src/push/cli.js && node --check src/push/config.js && node --check src/push/schema.js && node --check src/push/crypto.js && node --check src/push/store.js && node --check src/push/cached-store.js && node --check src/push/store-worker.js && node --check src/push/guard.js && node --check src/push/apns.js && node --check bin/yuri-push-relay.js && node --check src/push/handler.js && node --check src/push/combined.js",
|
|
54
|
+
"type-check": "node --check src/core.js && node --check src/worker.js && node --check src/worker-socket.js && node --check src/index.js && node --check src/cli.js && node --check bin/yuri-relay.js && node --check bin/cli-entry.js && node --check src/push/index.js && node --check src/push/server.js && node --check src/push/cli.js && node --check src/push/config.js && node --check src/push/schema.js && node --check src/push/crypto.js && node --check src/push/store.js && node --check src/push/cached-store.js && node --check src/push/store-worker.js && node --check src/push/guard.js && node --check src/push/apns.js && node --check bin/yuri-push-relay.js && node --check src/push/handler.js && node --check src/push/combined.js",
|
|
55
|
+
"lint": "node --check src/core.js && node --check src/worker.js && node --check src/worker-socket.js && node --check src/index.js && node --check src/cli.js && node --check bin/yuri-relay.js && node --check bin/cli-entry.js && node --check src/push/index.js && node --check src/push/server.js && node --check src/push/cli.js && node --check src/push/config.js && node --check src/push/schema.js && node --check src/push/crypto.js && node --check src/push/store.js && node --check src/push/cached-store.js && node --check src/push/store-worker.js && node --check src/push/guard.js && node --check src/push/apns.js && node --check bin/yuri-push-relay.js && node --check src/push/handler.js && node --check src/push/combined.js",
|
|
51
56
|
"build:standalone": "bun build --compile --outfile dist/yuri-relay bin/yuri-relay.js"
|
|
52
57
|
},
|
|
53
58
|
"dependencies": {
|
package/src/core.js
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import { Buffer } from 'node:buffer';
|
|
3
|
+
|
|
4
|
+
const CLOSE = { replaced: 4001, duplicate: 4002, stuck: 4003, unavailable: 4008, auth: 4010, limit: 4029, away: 1012, malformed: 1008 };
|
|
5
|
+
const B64 = /^[A-Za-z0-9_-]+$/;
|
|
6
|
+
const SERVER_ID_BYTES = 32;
|
|
7
|
+
export const DEFAULT_RELAY_LIMITS = {
|
|
8
|
+
maxUrlBytes: 4096, maxFieldBytes: 512, maxHosts: 256, maxSockets: 2048, maxConnections: 1000,
|
|
9
|
+
maxClientsPerHost: 100, maxClientsPerIp: 30, maxPendingClients: 30, pendingMs: 15_000,
|
|
10
|
+
maxRawSockets: 4096, maxRawSocketsPerIp: 128,
|
|
11
|
+
graceMs: 30_000, timestampSkewMs: 60_000, replayMs: 120_000, maxReplayEntries: 10_000,
|
|
12
|
+
maxFrameBytes: 128 * 1024, maxQueuedBytesPerConnection: 2 * 1024 * 1024,
|
|
13
|
+
maxGlobalQueuedBytes: 32 * 1024 * 1024, maxBufferedAmount: 2 * 1024 * 1024,
|
|
14
|
+
maxControlQueueEntries: 256, maxControlQueuedBytes: 2 * 1024 * 1024,
|
|
15
|
+
pumpRetryMs: 25, heartbeatMs: 30_000, handshakeMs: 10_000, closeDeadlineMs: 5_000,
|
|
16
|
+
admissionWindowMs: 60_000, maxAdmissionsPerIp: 120,
|
|
17
|
+
maxHostControlAdmissionsPerIp: 30, maxHostControlAdmissionsPerServer: 12, maxAdmissionEntries: 10_000,
|
|
18
|
+
idAttempts: 4,
|
|
19
|
+
};
|
|
20
|
+
const fields = {
|
|
21
|
+
client: new Set(['v', 'role', 'serverId', 'grant']),
|
|
22
|
+
'host-control': new Set(['v', 'role', 'serverId', 'ts', 'sig', 'pk']),
|
|
23
|
+
'host-data': new Set(['v', 'role', 'serverId', 'connectionId', 'ts', 'sig', 'pk']),
|
|
24
|
+
};
|
|
25
|
+
const bytes = (value) => Buffer.byteLength(value, 'utf8');
|
|
26
|
+
const canonical = (jwk) => JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y });
|
|
27
|
+
const b64 = (value, length) => {
|
|
28
|
+
if (typeof value !== 'string' || !B64.test(value)) return null;
|
|
29
|
+
try { const decoded = Buffer.from(value, 'base64url'); return decoded.length === length && decoded.toString('base64url') === value ? decoded : null; } catch { return null; }
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
/** @param {string} encoded */
|
|
33
|
+
const decodeJwk = (encoded) => {
|
|
34
|
+
const raw = b64(encoded, Buffer.byteLength(encoded, 'base64url'));
|
|
35
|
+
if (!raw) return null;
|
|
36
|
+
try {
|
|
37
|
+
const text = raw.toString('utf8'); const jwk = JSON.parse(text);
|
|
38
|
+
if (text !== canonical(jwk) || jwk.kty !== 'EC' || jwk.crv !== 'P-256' || !b64(jwk.x, 32) || !b64(jwk.y, 32)) return null;
|
|
39
|
+
return { jwk };
|
|
40
|
+
} catch { return null; }
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Shared Layer 1 routing engine. Runtimes own HTTP upgrades, TCP and socket I/O.
|
|
45
|
+
* Workers supplies a ws-shaped adapter and enables nodejs_compat for crypto/Buffer.
|
|
46
|
+
*/
|
|
47
|
+
export const createRelayCore = (options = {}) => {
|
|
48
|
+
const limits = { ...DEFAULT_RELAY_LIMITS, ...options.limits };
|
|
49
|
+
if (limits.replayMs < limits.timestampSkewMs * 2 || limits.maxReplayEntries < 1) throw new RangeError('invalid replay limits');
|
|
50
|
+
const clock = { now: Date.now, setTimeout, clearTimeout, setImmediate: (callback) => setTimeout(callback, 0), ...options.clock };
|
|
51
|
+
const randomBytes = options.randomBytes ?? crypto.randomBytes;
|
|
52
|
+
const hosts = new Map(); const replay = new Map(); const admissions = new Map(); const clientIpCounts = new Map();
|
|
53
|
+
const accepted = new Set();
|
|
54
|
+
const counts = { hosts: 0, sockets: 0, controls: 0, clients: 0, pairs: 0, pending: 0, queuedBytes: 0 };
|
|
55
|
+
const reasons = { authRejected: 0, policyRejected: 0, limited: 0, heartbeatReaped: 0, replayRejected: 0 };
|
|
56
|
+
const addReason = (key) => { reasons[key] += 1; };
|
|
57
|
+
const snapshot = () => ({ ...counts, reasons: { ...reasons } });
|
|
58
|
+
const relayPath = options.path ?? '/ws';
|
|
59
|
+
const decrement = (map, key) => { const value = map.get(key) ?? 0; if (value <= 1) map.delete(key); else map.set(key, value - 1); };
|
|
60
|
+
const safeClose = (socket, code, reason = '') => {
|
|
61
|
+
if (socket.readyState === socket.CLOSED) return;
|
|
62
|
+
try {
|
|
63
|
+
if (socket.readyState === socket.OPEN || socket.readyState === socket.CONNECTING) socket.close(code, reason);
|
|
64
|
+
if (socket.readyState === socket.CLOSED) return;
|
|
65
|
+
if (socket.readyState !== socket.OPEN && socket.readyState !== socket.CONNECTING && socket.readyState !== socket.CLOSING) return;
|
|
66
|
+
if (!socket._relayCloseDeadline) socket._relayCloseDeadline = clock.setTimeout(() => {
|
|
67
|
+
socket._relayCloseDeadline = null;
|
|
68
|
+
if (socket.readyState !== socket.CLOSED) socket.terminate();
|
|
69
|
+
}, limits.closeDeadlineMs);
|
|
70
|
+
} catch { socket.terminate(); }
|
|
71
|
+
};
|
|
72
|
+
const purge = () => {
|
|
73
|
+
const now = clock.now();
|
|
74
|
+
for (const [key, expiry] of replay) if (expiry <= now) replay.delete(key);
|
|
75
|
+
for (const [key, record] of admissions) if (record.until <= now) admissions.delete(key);
|
|
76
|
+
};
|
|
77
|
+
const admit = (key, cap) => {
|
|
78
|
+
purge(); let record = admissions.get(key);
|
|
79
|
+
if (!record) {
|
|
80
|
+
if (admissions.size >= limits.maxAdmissionEntries) { addReason('limited'); return false; }
|
|
81
|
+
record = { count: 0, until: clock.now() + limits.admissionWindowMs }; admissions.set(key, record);
|
|
82
|
+
}
|
|
83
|
+
record.count += 1;
|
|
84
|
+
if (record.count > cap) { addReason('limited'); return false; }
|
|
85
|
+
return true;
|
|
86
|
+
};
|
|
87
|
+
const admitUpgrade = (ip, parsed) => {
|
|
88
|
+
if (parsed.role === 'host-control') {
|
|
89
|
+
return admit(`host-control:${ip}`, limits.maxHostControlAdmissionsPerIp)
|
|
90
|
+
&& admit(`host-control-server:${parsed.serverId}`, limits.maxHostControlAdmissionsPerServer);
|
|
91
|
+
}
|
|
92
|
+
return admit(`${parsed.role}:${ip}`, limits.maxAdmissionsPerIp);
|
|
93
|
+
};
|
|
94
|
+
const removeSocket = (socket) => {
|
|
95
|
+
if (!accepted.delete(socket)) return;
|
|
96
|
+
counts.sockets -= 1;
|
|
97
|
+
if (socket._relayHandshake) clock.clearTimeout(socket._relayHandshake);
|
|
98
|
+
if (socket._relayCloseDeadline) clock.clearTimeout(socket._relayCloseDeadline);
|
|
99
|
+
};
|
|
100
|
+
const detachControl = (host, control, { code = CLOSE.away, reason = 'control closed', grace = true } = {}) => {
|
|
101
|
+
if (!control || hosts.get(host.serverId) !== host || host.control !== control || control.epoch !== host.epoch) return;
|
|
102
|
+
host.control = null;
|
|
103
|
+
counts.controls -= 1;
|
|
104
|
+
const queued = control.queuedBytes;
|
|
105
|
+
control.queue = []; control.queuedBytes = 0; control.busy = false;
|
|
106
|
+
counts.queuedBytes = Math.max(0, counts.queuedBytes - queued);
|
|
107
|
+
safeClose(control.socket, code, reason);
|
|
108
|
+
if (grace) beginGrace(host, control.epoch);
|
|
109
|
+
};
|
|
110
|
+
const controlPump = (host, message) => {
|
|
111
|
+
if (!host.control || host.control.epoch !== host.epoch) return;
|
|
112
|
+
const control = host.control; const payload = Buffer.from(JSON.stringify(message));
|
|
113
|
+
if (control.queue.length >= limits.maxControlQueueEntries || control.queuedBytes + payload.length > limits.maxControlQueuedBytes || counts.queuedBytes + payload.length > limits.maxGlobalQueuedBytes) {
|
|
114
|
+
addReason('limited'); detachControl(host, control, { code: CLOSE.limit, reason: 'control queue limit' }); return;
|
|
115
|
+
}
|
|
116
|
+
control.queue.push(payload); control.queuedBytes += payload.length; counts.queuedBytes += payload.length;
|
|
117
|
+
const pump = () => {
|
|
118
|
+
const control = host.control;
|
|
119
|
+
if (!control || control.epoch !== host.epoch || control.busy || !control.queue.length) return;
|
|
120
|
+
if (control.socket.readyState !== control.socket.OPEN) return detachControl(host, control, { code: CLOSE.away, reason: 'control unavailable' });
|
|
121
|
+
control.busy = true; const item = control.queue[0];
|
|
122
|
+
control.socket.send(item, { binary: false }, (error) => {
|
|
123
|
+
if (!host.control || host.control !== control || control.epoch !== host.epoch) return;
|
|
124
|
+
control.busy = false;
|
|
125
|
+
if (error) { detachControl(host, control, { code: CLOSE.away, reason: 'control send failure' }); return; }
|
|
126
|
+
control.queue.shift(); control.queuedBytes -= item.length; counts.queuedBytes = Math.max(0, counts.queuedBytes - item.length); pump();
|
|
127
|
+
});
|
|
128
|
+
};
|
|
129
|
+
pump();
|
|
130
|
+
};
|
|
131
|
+
const releasePump = (entry, pump) => {
|
|
132
|
+
if (pump.retry) clock.clearTimeout(pump.retry);
|
|
133
|
+
const total = pump.bytes; pump.queue = []; pump.bytes = 0; pump.busy = false; pump.retry = null;
|
|
134
|
+
entry.queuedBytes = Math.max(0, entry.queuedBytes - total);
|
|
135
|
+
counts.queuedBytes = Math.max(0, counts.queuedBytes - total);
|
|
136
|
+
};
|
|
137
|
+
const removeClient = (host, entry, code, reason, notify = true) => {
|
|
138
|
+
if (host.clients.get(entry.id) !== entry) return;
|
|
139
|
+
host.clients.delete(entry.id); counts.clients -= 1; decrement(clientIpCounts, entry.ip); if (entry.data) counts.pairs -= 1; else counts.pending -= 1;
|
|
140
|
+
if (entry.pendingTimer) clock.clearTimeout(entry.pendingTimer);
|
|
141
|
+
releasePump(entry, entry.toData); releasePump(entry, entry.toClient);
|
|
142
|
+
setRelayPaused(entry.client, false); setRelayPaused(entry.data, false);
|
|
143
|
+
if (entry.client) safeClose(entry.client, code, reason); if (entry.data) safeClose(entry.data, code, reason);
|
|
144
|
+
if (notify) controlPump(host, { type: 'disconnected', connectionId: entry.id });
|
|
145
|
+
if (!host.control && host.clients.size === 0 && !host.graceTimer && hosts.delete(host.serverId)) counts.hosts -= 1;
|
|
146
|
+
};
|
|
147
|
+
const expireHost = (host, epoch) => {
|
|
148
|
+
if (hosts.get(host.serverId) !== host || host.epoch !== epoch || host.control) return;
|
|
149
|
+
host.graceTimer = null;
|
|
150
|
+
for (const entry of [...host.clients.values()]) removeClient(host, entry, CLOSE.away, 'host went away', false);
|
|
151
|
+
if (hosts.get(host.serverId) === host && hosts.delete(host.serverId)) counts.hosts -= 1;
|
|
152
|
+
};
|
|
153
|
+
const beginGrace = (host, epoch) => {
|
|
154
|
+
if (hosts.get(host.serverId) !== host || host.epoch !== epoch || host.graceTimer) return;
|
|
155
|
+
host.graceTimer = clock.setTimeout(() => expireHost(host, epoch), limits.graceMs);
|
|
156
|
+
};
|
|
157
|
+
const pauseHigh = Math.max(1, Math.min(limits.maxQueuedBytesPerConnection - 1, Math.floor(limits.maxQueuedBytesPerConnection / 2)));
|
|
158
|
+
const pauseLow = Math.min(pauseHigh, Math.floor(limits.maxQueuedBytesPerConnection / 4));
|
|
159
|
+
const sourceOf = (entry, direction) => (direction === 'toData' ? entry.client : entry.data);
|
|
160
|
+
// Pause the fast sender when this direction's queue is above the high watermark.
|
|
161
|
+
const setRelayPaused = (socket, paused) => {
|
|
162
|
+
if (!socket || Boolean(socket._relayPaused) === paused) return;
|
|
163
|
+
if (paused && socket.readyState !== socket.OPEN) return;
|
|
164
|
+
try {
|
|
165
|
+
if (typeof socket.pause === 'function' && typeof socket.resume === 'function') {
|
|
166
|
+
if (paused) socket.pause();
|
|
167
|
+
else socket.resume();
|
|
168
|
+
} else {
|
|
169
|
+
const stream = socket._socket;
|
|
170
|
+
if (stream && typeof stream.pause === 'function') {
|
|
171
|
+
if (paused) stream.pause();
|
|
172
|
+
else stream.resume();
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
} catch { /* pause/resume only apply while OPEN */ }
|
|
176
|
+
socket._relayPaused = paused;
|
|
177
|
+
};
|
|
178
|
+
const applyBackpressure = (entry, direction) => {
|
|
179
|
+
const source = sourceOf(entry, direction);
|
|
180
|
+
if (!source) return;
|
|
181
|
+
const queued = entry[direction].bytes;
|
|
182
|
+
if (queued >= pauseHigh) setRelayPaused(source, true);
|
|
183
|
+
else if (queued <= pauseLow) setRelayPaused(source, false);
|
|
184
|
+
};
|
|
185
|
+
const fairReady = [];
|
|
186
|
+
let fairScheduled = false;
|
|
187
|
+
const requestPump = (host, entry, direction) => {
|
|
188
|
+
const channel = entry[direction];
|
|
189
|
+
if (channel.scheduled) return;
|
|
190
|
+
channel.scheduled = true;
|
|
191
|
+
fairReady.push({ host, entry, direction });
|
|
192
|
+
if (fairScheduled) return;
|
|
193
|
+
fairScheduled = true;
|
|
194
|
+
clock.setImmediate(runFairPump);
|
|
195
|
+
};
|
|
196
|
+
// One frame per ready pair per tick so a single tunnel cannot monopolize the event loop.
|
|
197
|
+
const runFairPump = () => {
|
|
198
|
+
fairScheduled = false;
|
|
199
|
+
const pending = fairReady.length;
|
|
200
|
+
for (let index = 0; index < pending; index += 1) {
|
|
201
|
+
const job = fairReady.shift();
|
|
202
|
+
if (!job) break;
|
|
203
|
+
job.entry[job.direction].scheduled = false;
|
|
204
|
+
sendOne(job.host, job.entry, job.direction);
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
const sendOne = (host, entry, direction) => {
|
|
208
|
+
const channel = entry[direction]; const target = direction === 'toData' ? entry.data : entry.client;
|
|
209
|
+
if (host.clients.get(entry.id) !== entry || channel.busy || !channel.queue.length) return;
|
|
210
|
+
if (!target || target.readyState !== target.OPEN || target.bufferedAmount > limits.maxBufferedAmount) {
|
|
211
|
+
if (!channel.retry) channel.retry = clock.setTimeout(() => { channel.retry = null; requestPump(host, entry, direction); }, limits.pumpRetryMs);
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
channel.busy = true; const item = channel.queue[0];
|
|
215
|
+
target.send(item.data, { binary: item.binary }, (error) => {
|
|
216
|
+
if (host.clients.get(entry.id) !== entry || entry[direction] !== channel) return;
|
|
217
|
+
channel.busy = false;
|
|
218
|
+
if (error) { removeClient(host, entry, CLOSE.limit, 'send failure'); return; }
|
|
219
|
+
channel.queue.shift(); channel.bytes = Math.max(0, channel.bytes - item.data.length); entry.queuedBytes = Math.max(0, entry.queuedBytes - item.data.length); counts.queuedBytes = Math.max(0, counts.queuedBytes - item.data.length);
|
|
220
|
+
applyBackpressure(entry, direction);
|
|
221
|
+
if (channel.queue.length) requestPump(host, entry, direction);
|
|
222
|
+
});
|
|
223
|
+
};
|
|
224
|
+
const enqueue = (host, entry, direction, data, binary) => {
|
|
225
|
+
if (hosts.get(host.serverId) !== host || host.clients.get(entry.id) !== entry) return;
|
|
226
|
+
const payload = Buffer.from(data); const channel = entry[direction];
|
|
227
|
+
if (payload.length > limits.maxFrameBytes || entry.queuedBytes + payload.length > limits.maxQueuedBytesPerConnection || counts.queuedBytes + payload.length > limits.maxGlobalQueuedBytes) { addReason('limited'); removeClient(host, entry, CLOSE.limit, 'queue limit'); return; }
|
|
228
|
+
channel.queue.push({ data: payload, binary }); channel.bytes += payload.length; entry.queuedBytes += payload.length; counts.queuedBytes += payload.length;
|
|
229
|
+
applyBackpressure(entry, direction);
|
|
230
|
+
requestPump(host, entry, direction);
|
|
231
|
+
};
|
|
232
|
+
const bindClient = (host, entry, socket) => {
|
|
233
|
+
entry.client = socket;
|
|
234
|
+
socket.on('message', (data, binary) => enqueue(host, entry, 'toData', data, binary));
|
|
235
|
+
socket.on('close', () => removeClient(host, entry, 1000, '', true)); socket.on('error', () => {});
|
|
236
|
+
};
|
|
237
|
+
const bindData = (host, entry, socket) => {
|
|
238
|
+
entry.data = socket; counts.pending -= 1; counts.pairs += 1; if (entry.pendingTimer) clock.clearTimeout(entry.pendingTimer);
|
|
239
|
+
socket.on('message', (data, binary) => enqueue(host, entry, 'toClient', data, binary));
|
|
240
|
+
socket.on('close', () => { if (host.clients.get(entry.id) === entry && entry.data === socket) removeClient(host, entry, CLOSE.away, 'host data closed'); }); socket.on('error', () => {});
|
|
241
|
+
requestPump(host, entry, 'toData');
|
|
242
|
+
};
|
|
243
|
+
const parse = (requestUrl) => {
|
|
244
|
+
if (!requestUrl || bytes(requestUrl) > limits.maxUrlBytes) return null;
|
|
245
|
+
let url; try { url = new URL(requestUrl, 'http://relay'); } catch { return null; }
|
|
246
|
+
if (url.pathname !== relayPath) return null;
|
|
247
|
+
const role = url.searchParams.get('role'); const allowed = Object.hasOwn(fields, role) ? fields[role] : null;
|
|
248
|
+
if (!allowed || url.searchParams.get('v') !== '1') return null;
|
|
249
|
+
for (const [key, value] of url.searchParams) if (!allowed.has(key) || url.searchParams.getAll(key).length !== 1 || bytes(value) > limits.maxFieldBytes) return null;
|
|
250
|
+
for (const key of allowed) if (key !== 'grant' && !url.searchParams.has(key)) return null;
|
|
251
|
+
const serverId = url.searchParams.get('serverId');
|
|
252
|
+
if (!b64(serverId, SERVER_ID_BYTES)) return null;
|
|
253
|
+
const connectionId = url.searchParams.get('connectionId');
|
|
254
|
+
if (connectionId && !b64(connectionId, 16)) return null;
|
|
255
|
+
return { role, serverId, connectionId, params: url.searchParams };
|
|
256
|
+
};
|
|
257
|
+
const authenticate = (parsed) => {
|
|
258
|
+
if (parsed.role === 'client') return true;
|
|
259
|
+
const ts = parsed.params.get('ts'); const sig = parsed.params.get('sig'); const pk = parsed.params.get('pk');
|
|
260
|
+
if (!/^(0|[1-9][0-9]{0,15})$/.test(ts ?? '')) return false;
|
|
261
|
+
const timestamp = Number(ts); if (!Number.isSafeInteger(timestamp) || Math.abs(clock.now() - timestamp) > limits.timestampSkewMs) return false;
|
|
262
|
+
const signature = b64(sig, 64); const publicKey = decodeJwk(pk);
|
|
263
|
+
if (!signature || !publicKey) return false;
|
|
264
|
+
const id = crypto.createHash('sha256').update(canonical(publicKey.jwk)).digest('base64url'); if (id !== parsed.serverId) return false;
|
|
265
|
+
const key = `${parsed.serverId}.${parsed.role}.${parsed.connectionId ?? ''}.${ts}`;
|
|
266
|
+
purge(); if (replay.has(key) || replay.size >= limits.maxReplayEntries) { addReason('replayRejected'); return false; }
|
|
267
|
+
const message = `${ts}.${parsed.serverId}.${parsed.role}.${parsed.connectionId ?? ''}`;
|
|
268
|
+
try {
|
|
269
|
+
if (!crypto.verify('SHA256', Buffer.from(message), { key: publicKey.jwk, format: 'jwk', dsaEncoding: 'ieee-p1363' }, signature)) return false;
|
|
270
|
+
} catch { return false; }
|
|
271
|
+
replay.set(key, clock.now() + limits.replayMs); return true;
|
|
272
|
+
};
|
|
273
|
+
const idFor = (host) => {
|
|
274
|
+
for (let attempt = 0; attempt < limits.idAttempts; attempt += 1) { const id = Buffer.from(randomBytes(16)).toString('base64url'); if (id.length === 22 && !host.clients.has(id)) return id; }
|
|
275
|
+
return null;
|
|
276
|
+
};
|
|
277
|
+
const attach = (socket, parsed, ip) => {
|
|
278
|
+
socket._relayRole = parsed.role; socket._relayAlive = true;
|
|
279
|
+
socket.on('pong', () => { socket._relayAlive = true; });
|
|
280
|
+
if (parsed.role === 'host-control') {
|
|
281
|
+
let host = hosts.get(parsed.serverId);
|
|
282
|
+
if (!host && counts.hosts >= limits.maxHosts) { addReason('limited'); return safeClose(socket, CLOSE.limit, 'host limit'); }
|
|
283
|
+
if (!host) { host = { serverId: parsed.serverId, clients: new Map(), control: null, epoch: 0, graceTimer: null }; hosts.set(parsed.serverId, host); counts.hosts += 1; }
|
|
284
|
+
if (host.control) { const previous = host.control; host.epoch += 1; for (const entry of [...host.clients.values()]) removeClient(host, entry, CLOSE.replaced, 'control replaced', false); host.epoch -= 1; detachControl(host, previous, { code: CLOSE.replaced, reason: 'control replaced', grace: false }); }
|
|
285
|
+
if (host.graceTimer) { clock.clearTimeout(host.graceTimer); host.graceTimer = null; }
|
|
286
|
+
host.epoch += 1; const epoch = host.epoch; host.control = { socket, epoch, queue: [], queuedBytes: 0, busy: false }; counts.controls += 1;
|
|
287
|
+
socket.on('close', () => detachControl(host, host.control?.socket === socket ? host.control : null, { code: CLOSE.away, reason: 'control closed' })); socket.on('error', () => {});
|
|
288
|
+
controlPump(host, { type: 'sync', connectionIds: [...host.clients.keys()] }); return;
|
|
289
|
+
}
|
|
290
|
+
if (parsed.role === 'client') {
|
|
291
|
+
const host = hosts.get(parsed.serverId);
|
|
292
|
+
if (!host) return safeClose(socket, CLOSE.unavailable, 'host unavailable');
|
|
293
|
+
if (counts.clients >= limits.maxConnections || host.clients.size >= limits.maxClientsPerHost || counts.pending >= limits.maxPendingClients || (clientIpCounts.get(ip) ?? 0) >= limits.maxClientsPerIp) { addReason('limited'); return safeClose(socket, CLOSE.limit, 'client limit'); }
|
|
294
|
+
const id = idFor(host); if (!id) { addReason('limited'); return safeClose(socket, CLOSE.limit, 'id collision'); }
|
|
295
|
+
const entry = { id, ip, client: null, data: null, queuedBytes: 0, toData: { queue: [], bytes: 0, busy: false, retry: null, scheduled: false }, toClient: { queue: [], bytes: 0, busy: false, retry: null, scheduled: false }, pendingTimer: null };
|
|
296
|
+
host.clients.set(id, entry); counts.clients += 1; counts.pending += 1; clientIpCounts.set(ip, (clientIpCounts.get(ip) ?? 0) + 1); bindClient(host, entry, socket);
|
|
297
|
+
entry.pendingTimer = clock.setTimeout(() => { if (host.clients.get(id) === entry && !entry.data) removeClient(host, entry, CLOSE.limit, 'pending timeout'); }, limits.pendingMs);
|
|
298
|
+
controlPump(host, { type: 'connected', connectionId: id }); return;
|
|
299
|
+
}
|
|
300
|
+
const host = hosts.get(parsed.serverId); const entry = host?.clients.get(parsed.connectionId);
|
|
301
|
+
if (!host || !entry || entry.data) return safeClose(socket, CLOSE.duplicate, 'data attach');
|
|
302
|
+
bindData(host, entry, socket);
|
|
303
|
+
};
|
|
304
|
+
const admitConnection = (requestUrl, ip) => {
|
|
305
|
+
const parsed = parse(requestUrl);
|
|
306
|
+
if (!parsed) {
|
|
307
|
+
if (!admit(`malformed:${ip}`, limits.maxAdmissionsPerIp)) return { code: CLOSE.limit };
|
|
308
|
+
addReason('policyRejected'); return { code: CLOSE.malformed };
|
|
309
|
+
}
|
|
310
|
+
if (!admitUpgrade(ip, parsed)) return { code: CLOSE.limit };
|
|
311
|
+
if (!authenticate(parsed)) { addReason('authRejected'); return { code: CLOSE.auth }; }
|
|
312
|
+
if (counts.sockets >= limits.maxSockets) { addReason('limited'); return { code: CLOSE.limit }; }
|
|
313
|
+
return { parsed };
|
|
314
|
+
};
|
|
315
|
+
const accept = (socket, parsed, ip) => {
|
|
316
|
+
accepted.add(socket); counts.sockets += 1;
|
|
317
|
+
socket.on('close', () => removeSocket(socket));
|
|
318
|
+
options.onSocketAccepted?.({ socket, role: parsed.role });
|
|
319
|
+
attach(socket, parsed, ip);
|
|
320
|
+
};
|
|
321
|
+
const heartbeat = () => {
|
|
322
|
+
purge();
|
|
323
|
+
for (const socket of accepted) {
|
|
324
|
+
if (socket.readyState !== socket.OPEN) continue;
|
|
325
|
+
if (socket._relayPaused) socket._relayAlive = true;
|
|
326
|
+
if (!socket._relayAlive) { addReason('heartbeatReaped'); safeClose(socket, socket._relayRole === 'host-control' ? CLOSE.stuck : CLOSE.away, 'heartbeat'); continue; }
|
|
327
|
+
socket._relayAlive = false;
|
|
328
|
+
try { socket.ping(); } catch { safeClose(socket, CLOSE.away, 'heartbeat'); }
|
|
329
|
+
}
|
|
330
|
+
};
|
|
331
|
+
const dispose = () => {
|
|
332
|
+
for (const host of hosts.values()) { if (host.graceTimer) clock.clearTimeout(host.graceTimer); if (host.control) detachControl(host, host.control, { code: CLOSE.away, reason: 'server stopping', grace: false }); for (const entry of [...host.clients.values()]) removeClient(host, entry, CLOSE.away, 'server stopping', false); }
|
|
333
|
+
hosts.clear(); replay.clear(); admissions.clear(); clientIpCounts.clear(); counts.hosts = 0; counts.controls = 0; counts.clients = 0; counts.pairs = 0; counts.pending = 0; counts.queuedBytes = 0;
|
|
334
|
+
for (const socket of accepted) { if (socket._relayCloseDeadline) clock.clearTimeout(socket._relayCloseDeadline); socket.terminate(); }
|
|
335
|
+
accepted.clear(); counts.sockets = 0; fairReady.length = 0;
|
|
336
|
+
};
|
|
337
|
+
return { limits, admitConnection, accept, reject: (socket, code) => safeClose(socket, code, 'rejected'), heartbeat, dispose, getSnapshot: snapshot, recordLimit: () => addReason('limited') };
|
|
338
|
+
};
|
package/src/index.js
CHANGED
|
@@ -1,35 +1,7 @@
|
|
|
1
|
-
import crypto from 'node:crypto';
|
|
2
1
|
import http from 'node:http';
|
|
3
2
|
import { isIP } from 'node:net';
|
|
4
3
|
import { WebSocketServer } from 'ws';
|
|
5
|
-
|
|
6
|
-
const CLOSE = { replaced: 4001, duplicate: 4002, stuck: 4003, unavailable: 4008, auth: 4010, limit: 4029, away: 1012, malformed: 1008 };
|
|
7
|
-
const B64 = /^[A-Za-z0-9_-]+$/;
|
|
8
|
-
const SERVER_ID_BYTES = 32;
|
|
9
|
-
const DEFAULT_LIMITS = {
|
|
10
|
-
maxUrlBytes: 4096, maxFieldBytes: 512, maxHosts: 256, maxSockets: 2048, maxConnections: 1000,
|
|
11
|
-
maxClientsPerHost: 100, maxClientsPerIp: 30, maxPendingClients: 30, pendingMs: 15_000,
|
|
12
|
-
maxRawSockets: 4096, maxRawSocketsPerIp: 128,
|
|
13
|
-
graceMs: 30_000, timestampSkewMs: 60_000, replayMs: 120_000, maxReplayEntries: 10_000,
|
|
14
|
-
maxFrameBytes: 128 * 1024, maxQueuedBytesPerConnection: 2 * 1024 * 1024,
|
|
15
|
-
maxGlobalQueuedBytes: 32 * 1024 * 1024, maxBufferedAmount: 2 * 1024 * 1024,
|
|
16
|
-
maxControlQueueEntries: 256, maxControlQueuedBytes: 2 * 1024 * 1024,
|
|
17
|
-
pumpRetryMs: 25, heartbeatMs: 30_000, handshakeMs: 10_000, closeDeadlineMs: 5_000,
|
|
18
|
-
admissionWindowMs: 60_000, maxAdmissionsPerIp: 120,
|
|
19
|
-
maxHostControlAdmissionsPerIp: 30, maxHostControlAdmissionsPerServer: 12, maxAdmissionEntries: 10_000,
|
|
20
|
-
idAttempts: 4,
|
|
21
|
-
};
|
|
22
|
-
const fields = {
|
|
23
|
-
client: new Set(['v', 'role', 'serverId', 'grant']),
|
|
24
|
-
'host-control': new Set(['v', 'role', 'serverId', 'ts', 'sig', 'pk']),
|
|
25
|
-
'host-data': new Set(['v', 'role', 'serverId', 'connectionId', 'ts', 'sig', 'pk']),
|
|
26
|
-
};
|
|
27
|
-
const bytes = (value) => Buffer.byteLength(value, 'utf8');
|
|
28
|
-
const canonical = (jwk) => JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y });
|
|
29
|
-
const b64 = (value, length) => {
|
|
30
|
-
if (typeof value !== 'string' || !B64.test(value)) return null;
|
|
31
|
-
try { const decoded = Buffer.from(value, 'base64url'); return decoded.length === length && decoded.toString('base64url') === value ? decoded : null; } catch { return null; }
|
|
32
|
-
};
|
|
4
|
+
import { createRelayCore } from './core.js';
|
|
33
5
|
|
|
34
6
|
export const resolveRelayClientIp = (request, trustProxy = false) => {
|
|
35
7
|
const remoteAddress = request.socket.remoteAddress ?? 'unknown';
|
|
@@ -41,279 +13,18 @@ export const resolveRelayClientIp = (request, trustProxy = false) => {
|
|
|
41
13
|
|
|
42
14
|
export const formatRelayWsUrl = (host, port, relayPath) => `ws://${isIP(host) === 6 ? `[${host}]` : host}:${port}${relayPath}`;
|
|
43
15
|
|
|
44
|
-
/** @param {string} encoded */
|
|
45
|
-
const decodeJwk = (encoded) => {
|
|
46
|
-
const raw = b64(encoded, Buffer.byteLength(encoded, 'base64url'));
|
|
47
|
-
if (!raw) return null;
|
|
48
|
-
try {
|
|
49
|
-
const text = raw.toString('utf8'); const jwk = JSON.parse(text);
|
|
50
|
-
if (text !== canonical(jwk) || jwk.kty !== 'EC' || jwk.crv !== 'P-256' || !b64(jwk.x, 32) || !b64(jwk.y, 32)) return null;
|
|
51
|
-
return { jwk, key: crypto.createPublicKey({ key: jwk, format: 'jwk' }) };
|
|
52
|
-
} catch { return null; }
|
|
53
|
-
};
|
|
54
|
-
|
|
55
16
|
/**
|
|
56
17
|
* Creates the Layer 1 self-hosted relay. It routes opaque Layer 2/3 frames.
|
|
57
|
-
* @param {
|
|
18
|
+
* @param {import('./index.js').Options} options
|
|
58
19
|
*/
|
|
59
20
|
export const createPrivateRelayServer = (options = {}) => {
|
|
60
|
-
const limits = { ...DEFAULT_LIMITS, ...options.limits };
|
|
61
|
-
if (limits.replayMs < limits.timestampSkewMs * 2 || limits.maxReplayEntries < 1) throw new RangeError('invalid replay limits');
|
|
62
21
|
const clock = { now: Date.now, setTimeout, clearTimeout, setInterval, clearInterval, setImmediate, ...options.clock };
|
|
63
|
-
const
|
|
64
|
-
const
|
|
65
|
-
const
|
|
66
|
-
const counts = { hosts: 0, sockets: 0, rawSockets: 0, controls: 0, clients: 0, pairs: 0, pending: 0, queuedBytes: 0 };
|
|
67
|
-
const reasons = { authRejected: 0, policyRejected: 0, limited: 0, heartbeatReaped: 0, replayRejected: 0 };
|
|
68
|
-
let server = null; let wss = null; let heartbeat = null; let startPromise = null; let stopPromise = null; let abortStart = null; let state = 'idle'; let generation = 0;
|
|
69
|
-
const addReason = (key) => { reasons[key] += 1; };
|
|
70
|
-
const snapshot = () => ({ state, ...counts, reasons: { ...reasons } });
|
|
22
|
+
const core = createRelayCore({ ...options, clock });
|
|
23
|
+
const { limits } = core;
|
|
24
|
+
const rawSockets = new Set(); const rawIpCounts = new Map();
|
|
71
25
|
const resolveClientIp = options.resolveClientIp ?? ((request) => resolveRelayClientIp(request, options.trustProxy));
|
|
72
26
|
const relayPath = options.path ?? '/ws';
|
|
73
|
-
|
|
74
|
-
const safeClose = (socket, code, reason = '') => {
|
|
75
|
-
if (socket.readyState === socket.CLOSED) return;
|
|
76
|
-
try {
|
|
77
|
-
if (socket.readyState === socket.OPEN || socket.readyState === socket.CONNECTING) socket.close(code, reason);
|
|
78
|
-
if (socket.readyState === socket.CLOSED) return;
|
|
79
|
-
if (socket.readyState !== socket.OPEN && socket.readyState !== socket.CONNECTING && socket.readyState !== socket.CLOSING) return;
|
|
80
|
-
if (!socket._relayCloseDeadline) socket._relayCloseDeadline = clock.setTimeout(() => {
|
|
81
|
-
socket._relayCloseDeadline = null;
|
|
82
|
-
if (socket.readyState !== socket.CLOSED) socket.terminate();
|
|
83
|
-
}, limits.closeDeadlineMs);
|
|
84
|
-
} catch { socket.terminate(); }
|
|
85
|
-
};
|
|
86
|
-
const purge = () => {
|
|
87
|
-
const now = clock.now();
|
|
88
|
-
for (const [key, expiry] of replay) if (expiry <= now) replay.delete(key);
|
|
89
|
-
for (const [key, record] of admissions) if (record.until <= now) admissions.delete(key);
|
|
90
|
-
};
|
|
91
|
-
const admit = (key, cap) => {
|
|
92
|
-
purge(); let record = admissions.get(key);
|
|
93
|
-
if (!record) {
|
|
94
|
-
if (admissions.size >= limits.maxAdmissionEntries) { addReason('limited'); return false; }
|
|
95
|
-
record = { count: 0, until: clock.now() + limits.admissionWindowMs }; admissions.set(key, record);
|
|
96
|
-
}
|
|
97
|
-
record.count += 1;
|
|
98
|
-
if (record.count > cap) { addReason('limited'); return false; }
|
|
99
|
-
return true;
|
|
100
|
-
};
|
|
101
|
-
const admitUpgrade = (ip, parsed) => {
|
|
102
|
-
if (parsed.role === 'host-control') {
|
|
103
|
-
return admit(`host-control:${ip}`, limits.maxHostControlAdmissionsPerIp)
|
|
104
|
-
&& admit(`host-control-server:${parsed.serverId}`, limits.maxHostControlAdmissionsPerServer);
|
|
105
|
-
}
|
|
106
|
-
return admit(`${parsed.role}:${ip}`, limits.maxAdmissionsPerIp);
|
|
107
|
-
};
|
|
108
|
-
const removeSocket = (socket) => {
|
|
109
|
-
if (!accepted.delete(socket)) return;
|
|
110
|
-
counts.sockets -= 1;
|
|
111
|
-
if (socket._relayHandshake) clock.clearTimeout(socket._relayHandshake);
|
|
112
|
-
if (socket._relayCloseDeadline) clock.clearTimeout(socket._relayCloseDeadline);
|
|
113
|
-
};
|
|
114
|
-
const detachControl = (host, control, { code = CLOSE.away, reason = 'control closed', grace = true } = {}) => {
|
|
115
|
-
if (!control || hosts.get(host.serverId) !== host || host.control !== control || control.epoch !== host.epoch) return;
|
|
116
|
-
host.control = null;
|
|
117
|
-
counts.controls -= 1;
|
|
118
|
-
const queued = control.queuedBytes;
|
|
119
|
-
control.queue = []; control.queuedBytes = 0; control.busy = false;
|
|
120
|
-
counts.queuedBytes = Math.max(0, counts.queuedBytes - queued);
|
|
121
|
-
safeClose(control.socket, code, reason);
|
|
122
|
-
if (grace) beginGrace(host, control.epoch);
|
|
123
|
-
};
|
|
124
|
-
const controlPump = (host, message) => {
|
|
125
|
-
if (!host.control || host.control.epoch !== host.epoch) return;
|
|
126
|
-
const control = host.control; const payload = Buffer.from(JSON.stringify(message));
|
|
127
|
-
if (control.queue.length >= limits.maxControlQueueEntries || control.queuedBytes + payload.length > limits.maxControlQueuedBytes || counts.queuedBytes + payload.length > limits.maxGlobalQueuedBytes) {
|
|
128
|
-
addReason('limited'); detachControl(host, control, { code: CLOSE.limit, reason: 'control queue limit' }); return;
|
|
129
|
-
}
|
|
130
|
-
control.queue.push(payload); control.queuedBytes += payload.length; counts.queuedBytes += payload.length;
|
|
131
|
-
const pump = () => {
|
|
132
|
-
const control = host.control;
|
|
133
|
-
if (!control || control.epoch !== host.epoch || control.busy || !control.queue.length) return;
|
|
134
|
-
if (control.socket.readyState !== control.socket.OPEN) return detachControl(host, control, { code: CLOSE.away, reason: 'control unavailable' });
|
|
135
|
-
control.busy = true; const item = control.queue[0];
|
|
136
|
-
control.socket.send(item, { binary: false }, (error) => {
|
|
137
|
-
if (!host.control || host.control !== control || control.epoch !== host.epoch) return;
|
|
138
|
-
control.busy = false;
|
|
139
|
-
if (error) { detachControl(host, control, { code: CLOSE.away, reason: 'control send failure' }); return; }
|
|
140
|
-
control.queue.shift(); control.queuedBytes -= item.length; counts.queuedBytes = Math.max(0, counts.queuedBytes - item.length); pump();
|
|
141
|
-
});
|
|
142
|
-
};
|
|
143
|
-
pump();
|
|
144
|
-
};
|
|
145
|
-
const releasePump = (entry, pump) => {
|
|
146
|
-
if (pump.retry) clock.clearTimeout(pump.retry);
|
|
147
|
-
const total = pump.bytes; pump.queue = []; pump.bytes = 0; pump.busy = false; pump.retry = null;
|
|
148
|
-
entry.queuedBytes = Math.max(0, entry.queuedBytes - total);
|
|
149
|
-
counts.queuedBytes = Math.max(0, counts.queuedBytes - total);
|
|
150
|
-
};
|
|
151
|
-
const removeClient = (host, entry, code, reason, notify = true) => {
|
|
152
|
-
if (host.clients.get(entry.id) !== entry) return;
|
|
153
|
-
host.clients.delete(entry.id); counts.clients -= 1; decrement(clientIpCounts, entry.ip); if (entry.data) counts.pairs -= 1; else counts.pending -= 1;
|
|
154
|
-
if (entry.pendingTimer) clock.clearTimeout(entry.pendingTimer);
|
|
155
|
-
releasePump(entry, entry.toData); releasePump(entry, entry.toClient);
|
|
156
|
-
setRelayPaused(entry.client, false); setRelayPaused(entry.data, false);
|
|
157
|
-
if (entry.client) safeClose(entry.client, code, reason); if (entry.data) safeClose(entry.data, code, reason);
|
|
158
|
-
if (notify) controlPump(host, { type: 'disconnected', connectionId: entry.id });
|
|
159
|
-
if (!host.control && host.clients.size === 0 && !host.graceTimer && hosts.delete(host.serverId)) counts.hosts -= 1;
|
|
160
|
-
};
|
|
161
|
-
const expireHost = (host, epoch) => {
|
|
162
|
-
if (hosts.get(host.serverId) !== host || host.epoch !== epoch || host.control) return;
|
|
163
|
-
host.graceTimer = null;
|
|
164
|
-
for (const entry of [...host.clients.values()]) removeClient(host, entry, CLOSE.away, 'host went away', false);
|
|
165
|
-
if (hosts.get(host.serverId) === host && hosts.delete(host.serverId)) counts.hosts -= 1;
|
|
166
|
-
};
|
|
167
|
-
const beginGrace = (host, epoch) => {
|
|
168
|
-
if (hosts.get(host.serverId) !== host || host.epoch !== epoch || host.graceTimer) return;
|
|
169
|
-
host.graceTimer = clock.setTimeout(() => expireHost(host, epoch), limits.graceMs);
|
|
170
|
-
};
|
|
171
|
-
const pauseHigh = Math.max(1, Math.min(limits.maxQueuedBytesPerConnection - 1, Math.floor(limits.maxQueuedBytesPerConnection / 2)));
|
|
172
|
-
const pauseLow = Math.min(pauseHigh, Math.floor(limits.maxQueuedBytesPerConnection / 4));
|
|
173
|
-
const sourceOf = (entry, direction) => (direction === 'toData' ? entry.client : entry.data);
|
|
174
|
-
// Pause the fast sender when this direction's queue is above the high watermark.
|
|
175
|
-
const setRelayPaused = (socket, paused) => {
|
|
176
|
-
if (!socket || Boolean(socket._relayPaused) === paused) return;
|
|
177
|
-
if (paused && socket.readyState !== socket.OPEN) return;
|
|
178
|
-
try {
|
|
179
|
-
if (typeof socket.pause === 'function' && typeof socket.resume === 'function') {
|
|
180
|
-
if (paused) socket.pause();
|
|
181
|
-
else socket.resume();
|
|
182
|
-
} else {
|
|
183
|
-
const stream = socket._socket;
|
|
184
|
-
if (stream && typeof stream.pause === 'function') {
|
|
185
|
-
if (paused) stream.pause();
|
|
186
|
-
else stream.resume();
|
|
187
|
-
}
|
|
188
|
-
}
|
|
189
|
-
} catch { /* pause/resume only apply while OPEN */ }
|
|
190
|
-
socket._relayPaused = paused;
|
|
191
|
-
};
|
|
192
|
-
const applyBackpressure = (entry, direction) => {
|
|
193
|
-
const source = sourceOf(entry, direction);
|
|
194
|
-
if (!source) return;
|
|
195
|
-
const queued = entry[direction].bytes;
|
|
196
|
-
if (queued >= pauseHigh) setRelayPaused(source, true);
|
|
197
|
-
else if (queued <= pauseLow) setRelayPaused(source, false);
|
|
198
|
-
};
|
|
199
|
-
const fairReady = [];
|
|
200
|
-
let fairScheduled = false;
|
|
201
|
-
const requestPump = (host, entry, direction) => {
|
|
202
|
-
const channel = entry[direction];
|
|
203
|
-
if (channel.scheduled) return;
|
|
204
|
-
channel.scheduled = true;
|
|
205
|
-
fairReady.push({ host, entry, direction });
|
|
206
|
-
if (fairScheduled) return;
|
|
207
|
-
fairScheduled = true;
|
|
208
|
-
clock.setImmediate(runFairPump);
|
|
209
|
-
};
|
|
210
|
-
// One frame per ready pair per tick so a single tunnel cannot monopolize the event loop.
|
|
211
|
-
const runFairPump = () => {
|
|
212
|
-
fairScheduled = false;
|
|
213
|
-
const pending = fairReady.length;
|
|
214
|
-
for (let index = 0; index < pending; index += 1) {
|
|
215
|
-
const job = fairReady.shift();
|
|
216
|
-
if (!job) break;
|
|
217
|
-
job.entry[job.direction].scheduled = false;
|
|
218
|
-
sendOne(job.host, job.entry, job.direction);
|
|
219
|
-
}
|
|
220
|
-
};
|
|
221
|
-
const sendOne = (host, entry, direction) => {
|
|
222
|
-
const channel = entry[direction]; const target = direction === 'toData' ? entry.data : entry.client;
|
|
223
|
-
if (host.clients.get(entry.id) !== entry || channel.busy || !channel.queue.length) return;
|
|
224
|
-
if (!target || target.readyState !== target.OPEN || target.bufferedAmount > limits.maxBufferedAmount) {
|
|
225
|
-
if (!channel.retry) channel.retry = clock.setTimeout(() => { channel.retry = null; requestPump(host, entry, direction); }, limits.pumpRetryMs);
|
|
226
|
-
return;
|
|
227
|
-
}
|
|
228
|
-
channel.busy = true; const item = channel.queue[0];
|
|
229
|
-
target.send(item.data, { binary: item.binary }, (error) => {
|
|
230
|
-
if (host.clients.get(entry.id) !== entry || entry[direction] !== channel) return;
|
|
231
|
-
channel.busy = false;
|
|
232
|
-
if (error) { removeClient(host, entry, CLOSE.limit, 'send failure'); return; }
|
|
233
|
-
channel.queue.shift(); channel.bytes = Math.max(0, channel.bytes - item.data.length); entry.queuedBytes = Math.max(0, entry.queuedBytes - item.data.length); counts.queuedBytes = Math.max(0, counts.queuedBytes - item.data.length);
|
|
234
|
-
applyBackpressure(entry, direction);
|
|
235
|
-
if (channel.queue.length) requestPump(host, entry, direction);
|
|
236
|
-
});
|
|
237
|
-
};
|
|
238
|
-
const enqueue = (host, entry, direction, data, binary) => {
|
|
239
|
-
if (hosts.get(host.serverId) !== host || host.clients.get(entry.id) !== entry) return;
|
|
240
|
-
const payload = Buffer.from(data); const channel = entry[direction];
|
|
241
|
-
if (payload.length > limits.maxFrameBytes || entry.queuedBytes + payload.length > limits.maxQueuedBytesPerConnection || counts.queuedBytes + payload.length > limits.maxGlobalQueuedBytes) { addReason('limited'); removeClient(host, entry, CLOSE.limit, 'queue limit'); return; }
|
|
242
|
-
channel.queue.push({ data: payload, binary }); channel.bytes += payload.length; entry.queuedBytes += payload.length; counts.queuedBytes += payload.length;
|
|
243
|
-
applyBackpressure(entry, direction);
|
|
244
|
-
requestPump(host, entry, direction);
|
|
245
|
-
};
|
|
246
|
-
const bindClient = (host, entry, socket) => {
|
|
247
|
-
entry.client = socket;
|
|
248
|
-
socket.on('message', (data, binary) => enqueue(host, entry, 'toData', data, binary));
|
|
249
|
-
socket.on('close', () => removeClient(host, entry, 1000, '', true)); socket.on('error', () => {});
|
|
250
|
-
};
|
|
251
|
-
const bindData = (host, entry, socket) => {
|
|
252
|
-
entry.data = socket; counts.pending -= 1; counts.pairs += 1; if (entry.pendingTimer) clock.clearTimeout(entry.pendingTimer);
|
|
253
|
-
socket.on('message', (data, binary) => enqueue(host, entry, 'toClient', data, binary));
|
|
254
|
-
socket.on('close', () => { if (host.clients.get(entry.id) === entry && entry.data === socket) removeClient(host, entry, CLOSE.away, 'host data closed'); }); socket.on('error', () => {});
|
|
255
|
-
requestPump(host, entry, 'toData');
|
|
256
|
-
};
|
|
257
|
-
const parse = (request) => {
|
|
258
|
-
if (!request.url || bytes(request.url) > limits.maxUrlBytes) return null;
|
|
259
|
-
let url; try { url = new URL(request.url, 'http://relay'); } catch { return null; }
|
|
260
|
-
if (url.pathname !== relayPath) return null;
|
|
261
|
-
const role = url.searchParams.get('role'); const allowed = fields[role];
|
|
262
|
-
if (!allowed || url.searchParams.get('v') !== '1') return null;
|
|
263
|
-
for (const [key, value] of url.searchParams) if (!allowed.has(key) || url.searchParams.getAll(key).length !== 1 || bytes(value) > limits.maxFieldBytes) return null;
|
|
264
|
-
for (const key of allowed) if (key !== 'grant' && !url.searchParams.has(key)) return null;
|
|
265
|
-
const serverId = url.searchParams.get('serverId');
|
|
266
|
-
if (!b64(serverId, SERVER_ID_BYTES)) return null;
|
|
267
|
-
const connectionId = url.searchParams.get('connectionId');
|
|
268
|
-
if (connectionId && !b64(connectionId, 16)) return null;
|
|
269
|
-
return { role, serverId, connectionId, params: url.searchParams };
|
|
270
|
-
};
|
|
271
|
-
const authenticate = (parsed) => {
|
|
272
|
-
if (parsed.role === 'client') return true;
|
|
273
|
-
const ts = parsed.params.get('ts'); const sig = parsed.params.get('sig'); const pk = parsed.params.get('pk');
|
|
274
|
-
if (!/^(0|[1-9][0-9]{0,15})$/.test(ts ?? '')) return false;
|
|
275
|
-
const timestamp = Number(ts); if (!Number.isSafeInteger(timestamp) || Math.abs(clock.now() - timestamp) > limits.timestampSkewMs) return false;
|
|
276
|
-
const signature = b64(sig, 64); const publicKey = decodeJwk(pk);
|
|
277
|
-
if (!signature || !publicKey) return false;
|
|
278
|
-
const id = crypto.createHash('sha256').update(canonical(publicKey.jwk)).digest('base64url'); if (id !== parsed.serverId) return false;
|
|
279
|
-
const key = `${parsed.serverId}.${parsed.role}.${parsed.connectionId ?? ''}.${ts}`;
|
|
280
|
-
purge(); if (replay.has(key) || replay.size >= limits.maxReplayEntries) { addReason('replayRejected'); return false; }
|
|
281
|
-
const message = `${ts}.${parsed.serverId}.${parsed.role}.${parsed.connectionId ?? ''}`;
|
|
282
|
-
if (!crypto.verify('SHA256', Buffer.from(message), { key: publicKey.key, dsaEncoding: 'ieee-p1363' }, signature)) return false;
|
|
283
|
-
replay.set(key, clock.now() + limits.replayMs); return true;
|
|
284
|
-
};
|
|
285
|
-
const idFor = (host) => {
|
|
286
|
-
for (let attempt = 0; attempt < limits.idAttempts; attempt += 1) { const id = Buffer.from(randomBytes(16)).toString('base64url'); if (id.length === 22 && !host.clients.has(id)) return id; }
|
|
287
|
-
return null;
|
|
288
|
-
};
|
|
289
|
-
const attach = (socket, request, parsed) => {
|
|
290
|
-
const ip = resolveClientIp(request); socket._relayRole = parsed.role; socket._relayAlive = true;
|
|
291
|
-
socket.on('pong', () => { socket._relayAlive = true; });
|
|
292
|
-
if (parsed.role === 'host-control') {
|
|
293
|
-
let host = hosts.get(parsed.serverId);
|
|
294
|
-
if (!host && counts.hosts >= limits.maxHosts) { addReason('limited'); return safeClose(socket, CLOSE.limit, 'host limit'); }
|
|
295
|
-
if (!host) { host = { serverId: parsed.serverId, clients: new Map(), control: null, epoch: 0, graceTimer: null }; hosts.set(parsed.serverId, host); counts.hosts += 1; }
|
|
296
|
-
if (host.control) { const previous = host.control; host.epoch += 1; for (const entry of [...host.clients.values()]) removeClient(host, entry, CLOSE.replaced, 'control replaced', false); host.epoch -= 1; detachControl(host, previous, { code: CLOSE.replaced, reason: 'control replaced', grace: false }); }
|
|
297
|
-
if (host.graceTimer) { clock.clearTimeout(host.graceTimer); host.graceTimer = null; }
|
|
298
|
-
host.epoch += 1; const epoch = host.epoch; host.control = { socket, epoch, queue: [], queuedBytes: 0, busy: false }; counts.controls += 1;
|
|
299
|
-
socket.on('close', () => detachControl(host, host.control?.socket === socket ? host.control : null, { code: CLOSE.away, reason: 'control closed' })); socket.on('error', () => {});
|
|
300
|
-
controlPump(host, { type: 'sync', connectionIds: [...host.clients.keys()] }); return;
|
|
301
|
-
}
|
|
302
|
-
if (parsed.role === 'client') {
|
|
303
|
-
const host = hosts.get(parsed.serverId);
|
|
304
|
-
if (!host) return safeClose(socket, CLOSE.unavailable, 'host unavailable');
|
|
305
|
-
if (counts.clients >= limits.maxConnections || host.clients.size >= limits.maxClientsPerHost || counts.pending >= limits.maxPendingClients || (clientIpCounts.get(ip) ?? 0) >= limits.maxClientsPerIp) { addReason('limited'); return safeClose(socket, CLOSE.limit, 'client limit'); }
|
|
306
|
-
const id = idFor(host); if (!id) { addReason('limited'); return safeClose(socket, CLOSE.limit, 'id collision'); }
|
|
307
|
-
const entry = { id, ip, client: null, data: null, queuedBytes: 0, toData: { queue: [], bytes: 0, busy: false, retry: null, scheduled: false }, toClient: { queue: [], bytes: 0, busy: false, retry: null, scheduled: false }, pendingTimer: null };
|
|
308
|
-
host.clients.set(id, entry); counts.clients += 1; counts.pending += 1; clientIpCounts.set(ip, (clientIpCounts.get(ip) ?? 0) + 1); bindClient(host, entry, socket);
|
|
309
|
-
entry.pendingTimer = clock.setTimeout(() => { if (host.clients.get(id) === entry && !entry.data) removeClient(host, entry, CLOSE.limit, 'pending timeout'); }, limits.pendingMs);
|
|
310
|
-
controlPump(host, { type: 'connected', connectionId: id }); return;
|
|
311
|
-
}
|
|
312
|
-
const host = hosts.get(parsed.serverId); const entry = host?.clients.get(parsed.connectionId);
|
|
313
|
-
if (!host || !entry || entry.data) return safeClose(socket, CLOSE.duplicate, 'data attach');
|
|
314
|
-
bindData(host, entry, socket);
|
|
315
|
-
};
|
|
316
|
-
const reject = (request, socket, head, code) => wss.handleUpgrade(request, socket, head, (ws) => safeClose(ws, code, 'rejected'));
|
|
27
|
+
let server = null; let wss = null; let heartbeat = null; let startPromise = null; let stopPromise = null; let abortStart = null; let state = 'idle'; let generation = 0;
|
|
317
28
|
const start = () => {
|
|
318
29
|
if (state === 'running') return Promise.resolve(); if (state === 'stopping') return stopPromise.then(() => start()); if (startPromise) return startPromise;
|
|
319
30
|
state = 'starting'; const localGeneration = ++generation; const localServer = http.createServer((request, response) => {
|
|
@@ -331,24 +42,27 @@ export const createPrivateRelayServer = (options = {}) => {
|
|
|
331
42
|
}); const localWss = new WebSocketServer({ noServer: true, perMessageDeflate: false, maxPayload: limits.maxFrameBytes }); server = localServer; wss = localWss;
|
|
332
43
|
localServer.on('connection', (socket) => {
|
|
333
44
|
const ip = socket.remoteAddress ?? 'unknown';
|
|
334
|
-
if (
|
|
335
|
-
rawSockets.add(socket);
|
|
45
|
+
if (rawSockets.size >= limits.maxRawSockets || (rawIpCounts.get(ip) ?? 0) >= limits.maxRawSocketsPerIp) { core.recordLimit(); socket.destroy(); return; }
|
|
46
|
+
rawSockets.add(socket); rawIpCounts.set(ip, (rawIpCounts.get(ip) ?? 0) + 1);
|
|
336
47
|
socket._relayTcpTimer = clock.setTimeout(() => socket.destroy(), limits.handshakeMs);
|
|
337
|
-
socket.on('close', () => {
|
|
48
|
+
socket.on('close', () => {
|
|
49
|
+
if (socket._relayTcpTimer) clock.clearTimeout(socket._relayTcpTimer);
|
|
50
|
+
if (rawSockets.delete(socket)) {
|
|
51
|
+
const remaining = (rawIpCounts.get(ip) ?? 0) - 1;
|
|
52
|
+
if (remaining > 0) rawIpCounts.set(ip, remaining); else rawIpCounts.delete(ip);
|
|
53
|
+
}
|
|
54
|
+
});
|
|
338
55
|
});
|
|
339
56
|
localServer.on('upgrade', (request, socket, head) => {
|
|
340
57
|
if (socket._relayTcpTimer) { clock.clearTimeout(socket._relayTcpTimer); socket._relayTcpTimer = null; }
|
|
341
|
-
const
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
if (!authenticate(parsed)) { addReason('authRejected'); return reject(request, socket, head, CLOSE.auth); }
|
|
348
|
-
if (counts.sockets >= limits.maxSockets) { addReason('limited'); return reject(request, socket, head, CLOSE.limit); }
|
|
349
|
-
localWss.handleUpgrade(request, socket, head, (ws) => { accepted.add(ws); counts.sockets += 1; ws.on('close', () => removeSocket(ws)); ws._relayHandshake = clock.setTimeout(() => { if (!ws._relayRole) safeClose(ws, CLOSE.malformed, 'handshake timeout'); }, limits.handshakeMs); options.onSocketAccepted?.({ socket: ws, role: parsed.role }); attach(ws, request, parsed); if (ws._relayHandshake) { clock.clearTimeout(ws._relayHandshake); ws._relayHandshake = null; } });
|
|
58
|
+
const ip = resolveClientIp(request);
|
|
59
|
+
const admission = core.admitConnection(request.url, ip);
|
|
60
|
+
localWss.handleUpgrade(request, socket, head, (ws) => {
|
|
61
|
+
if (admission.code) return core.reject(ws, admission.code);
|
|
62
|
+
core.accept(ws, admission.parsed, ip);
|
|
63
|
+
});
|
|
350
64
|
});
|
|
351
|
-
heartbeat = clock.setInterval(
|
|
65
|
+
heartbeat = clock.setInterval(core.heartbeat, limits.heartbeatMs);
|
|
352
66
|
startPromise = new Promise((resolve, rejectStart) => {
|
|
353
67
|
const fail = (error) => { if (localGeneration !== generation) return; localServer.off('listening', ready); cleanupStart(); rejectStart(error); };
|
|
354
68
|
const ready = () => { localServer.off('error', fail); if (localGeneration !== generation || state !== 'starting') return; state = 'running'; resolve(); };
|
|
@@ -365,14 +79,13 @@ export const createPrivateRelayServer = (options = {}) => {
|
|
|
365
79
|
state = 'stopping'; generation += 1; const localServer = server; const localWss = wss;
|
|
366
80
|
stopPromise = new Promise((resolve) => {
|
|
367
81
|
if (heartbeat) { clock.clearInterval(heartbeat); heartbeat = null; }
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
for (const socket of accepted) { if (socket._relayCloseDeadline) clock.clearTimeout(socket._relayCloseDeadline); socket.terminate(); } for (const socket of rawSockets) socket.destroy(); accepted.clear(); rawSockets.clear(); rawIpCounts.clear(); counts.sockets = 0; counts.rawSockets = 0;
|
|
82
|
+
core.dispose();
|
|
83
|
+
for (const socket of rawSockets) socket.destroy(); rawSockets.clear(); rawIpCounts.clear();
|
|
371
84
|
if (!localServer) return resolve(); localWss?.close(); localServer.close(() => resolve()); clock.setTimeout(resolve, 100);
|
|
372
85
|
}).then(() => { if (server === localServer && wss === localWss) { server = null; wss = null; state = 'stopped'; } stopPromise = null; });
|
|
373
86
|
return stopPromise;
|
|
374
87
|
};
|
|
375
|
-
return { start, stop, address: () => server?.address(), get wsUrl() { const address = server?.address(); return address && typeof address === 'object' ? formatRelayWsUrl(options.host ?? '127.0.0.1', address.port, relayPath) : null; }, getSnapshot:
|
|
88
|
+
return { start, stop, address: () => server?.address(), get wsUrl() { const address = server?.address(); return address && typeof address === 'object' ? formatRelayWsUrl(options.host ?? '127.0.0.1', address.port, relayPath) : null; }, getSnapshot: () => ({ state, ...core.getSnapshot(), rawSockets: rawSockets.size }) };
|
|
376
89
|
};
|
|
377
90
|
|
|
378
91
|
export const startPrivateRelayServer = async (options) => { const relay = createPrivateRelayServer(options); await relay.start(); return relay; };
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { EventEmitter } from 'node:events';
|
|
2
|
+
import { Buffer } from 'node:buffer';
|
|
3
|
+
|
|
4
|
+
// Adapt Workers' event-target sockets to the shared engine's ws-shaped boundary.
|
|
5
|
+
// send() completion means runtime acceptance, not TCP drain. Workers exposes
|
|
6
|
+
// neither pause/resume nor bufferedAmount; do not pretend those guarantees exist.
|
|
7
|
+
export class WorkerRelaySocket extends EventEmitter {
|
|
8
|
+
OPEN = 1;
|
|
9
|
+
CLOSED = 3;
|
|
10
|
+
closed = false;
|
|
11
|
+
|
|
12
|
+
constructor(socket) {
|
|
13
|
+
super();
|
|
14
|
+
this.socket = socket;
|
|
15
|
+
socket.binaryType = 'arraybuffer';
|
|
16
|
+
socket.addEventListener('message', ({ data }) => {
|
|
17
|
+
if (this.closed) return;
|
|
18
|
+
const binary = typeof data !== 'string';
|
|
19
|
+
this.emit('message', Buffer.from(data), binary);
|
|
20
|
+
});
|
|
21
|
+
socket.addEventListener('close', ({ code, reason }) => this.finish(code, reason));
|
|
22
|
+
socket.addEventListener('error', () => this.terminate());
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
get readyState() { return this.closed ? this.CLOSED : this.socket.readyState; }
|
|
26
|
+
get bufferedAmount() { return this.socket.bufferedAmount; }
|
|
27
|
+
|
|
28
|
+
send(data, { binary }, callback) {
|
|
29
|
+
let failure;
|
|
30
|
+
try {
|
|
31
|
+
if (this.readyState !== this.OPEN) throw new Error('Relay socket closed');
|
|
32
|
+
this.socket.send(binary ? data : data.toString('utf8'));
|
|
33
|
+
} catch (error) { failure = error; }
|
|
34
|
+
callback(failure);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
close(code, reason) {
|
|
38
|
+
if (!this.closed) this.socket.close(code, reason);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
terminate() {
|
|
42
|
+
try { this.close(1012, 'relay socket ended'); } catch { /* The runtime may already have closed the socket. */ }
|
|
43
|
+
this.finish(1012, 'relay socket ended');
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
finish(code, reason) {
|
|
47
|
+
if (this.closed) return;
|
|
48
|
+
this.closed = true;
|
|
49
|
+
this.emit('close', code, reason);
|
|
50
|
+
this.removeAllListeners();
|
|
51
|
+
}
|
|
52
|
+
}
|
package/src/worker.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { createRelayCore, DEFAULT_RELAY_LIMITS } from './core.js';
|
|
2
|
+
import { WorkerRelaySocket } from './worker-socket.js';
|
|
3
|
+
|
|
4
|
+
const response = (status, body = null, headers = {}) => new Response(body, {
|
|
5
|
+
status, headers: { 'cache-control': 'no-store', ...headers },
|
|
6
|
+
});
|
|
7
|
+
|
|
8
|
+
const readOptions = (env) => {
|
|
9
|
+
const path = env.YURI_RELAY_PATH ?? '/ws';
|
|
10
|
+
if (!path.startsWith('/') || /[?#]/.test(path)) throw new Error('Invalid YURI_RELAY_PATH');
|
|
11
|
+
const limits = JSON.parse(env.YURI_RELAY_LIMITS_JSON ?? '{}');
|
|
12
|
+
if (!limits || Array.isArray(limits) || typeof limits !== 'object') throw new Error('Invalid YURI_RELAY_LIMITS_JSON');
|
|
13
|
+
for (const [key, value] of Object.entries(limits)) {
|
|
14
|
+
if (!Object.hasOwn(DEFAULT_RELAY_LIMITS, key) || !Number.isSafeInteger(value) || value < 1) throw new Error('Invalid Relay limit');
|
|
15
|
+
}
|
|
16
|
+
return { path, limits };
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
// One object per deployment preserves the Node server's global admission and
|
|
20
|
+
// queue limits. Ordinary accepted sockets deliberately keep routing state alive;
|
|
21
|
+
// hibernation requires restoring queues, replay protection and timeout state.
|
|
22
|
+
export class YuriRelay {
|
|
23
|
+
constructor(_state, env) {
|
|
24
|
+
this.options = readOptions(env);
|
|
25
|
+
this.core = createRelayCore(this.options);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
fetch(request) {
|
|
29
|
+
const url = new URL(request.url);
|
|
30
|
+
const upgrade = request.headers.get('Upgrade')?.toLowerCase() === 'websocket';
|
|
31
|
+
if (!upgrade) {
|
|
32
|
+
if ((url.pathname === '/healthz' || url.pathname === '/readyz') && (request.method === 'GET' || request.method === 'HEAD')) {
|
|
33
|
+
return response(200, request.method === 'HEAD' ? null : '{"status":"ok"}', { 'content-type': 'application/json' });
|
|
34
|
+
}
|
|
35
|
+
return response(url.pathname === this.options.path ? 426 : 404);
|
|
36
|
+
}
|
|
37
|
+
if (request.method !== 'GET') return response(405);
|
|
38
|
+
// Cloudflare replaces this header at public ingress. Never trust X-Forwarded-For.
|
|
39
|
+
const ip = request.headers.get('CF-Connecting-IP') ?? 'unknown';
|
|
40
|
+
const admission = this.core.admitConnection(url.pathname + url.search, ip);
|
|
41
|
+
const pair = new WebSocketPair();
|
|
42
|
+
const socket = new WorkerRelaySocket(pair[1]);
|
|
43
|
+
pair[1].accept();
|
|
44
|
+
if (admission.code) this.core.reject(socket, admission.code);
|
|
45
|
+
else this.core.accept(socket, admission.parsed, ip);
|
|
46
|
+
return new Response(null, { status: 101, webSocket: pair[0] });
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export default {
|
|
51
|
+
fetch(request, env) {
|
|
52
|
+
const id = env.YURI_RELAY.idFromName('relay-v1');
|
|
53
|
+
return env.YURI_RELAY.get(id).fetch(request);
|
|
54
|
+
},
|
|
55
|
+
};
|
package/wrangler.jsonc
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://raw.githubusercontent.com/cloudflare/workers-sdk/main/packages/wrangler/config-schema.json",
|
|
3
|
+
"name": "yuri-relay-worker",
|
|
4
|
+
"main": "src/worker.js",
|
|
5
|
+
"compatibility_date": "2026-10-01",
|
|
6
|
+
"compatibility_flags": ["nodejs_compat"],
|
|
7
|
+
"workers_dev": true,
|
|
8
|
+
"preview_urls": false,
|
|
9
|
+
"durable_objects": {
|
|
10
|
+
"bindings": [{ "name": "YURI_RELAY", "class_name": "YuriRelay" }]
|
|
11
|
+
},
|
|
12
|
+
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["YuriRelay"] }],
|
|
13
|
+
"observability": { "enabled": false },
|
|
14
|
+
"vars": { "YURI_RELAY_PATH": "/ws" }
|
|
15
|
+
}
|