@twinsearth/w2m-dsh-plugin 1.1.14 → 1.1.15

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.
@@ -1,1496 +1,1496 @@
1
- /**
2
- * W2M Rabbit relay — node:http / node:https server.
3
- *
4
- * PROTOCOL.md §1 endpoints, §3 SSE, §7 errors
5
- * PROTOCOL-v0.1.2.md §3 deployment params, §4 /healthz, §5 operator token,
6
- * §6 pair rate limit, §7 persistence, §8 SSE hardening.
7
- *
8
- * Zero third-party dependencies: only `node:` builtins.
9
- */
10
-
11
- import http from 'node:http';
12
- import https from 'node:https';
13
- import fs from 'node:fs';
14
- import os from 'node:os';
15
- import path from 'node:path';
16
- import { createHash, randomBytes } from 'node:crypto';
17
-
18
- import {
19
- MAX_FRAME_BYTES,
20
- PROTOCOL_VERSION,
21
- ProtocolError,
22
- RabbitState,
23
- rfc3339,
24
- } from './state.mjs';
25
- import { createJoinChallenges } from './join-challenge.mjs';
26
- import { createAdmission } from './admission.mjs';
27
- import { Persistence } from './persistence.mjs';
28
- import { PeerRegistry } from './peers.mjs';
29
- import { aggregateTask, buildReport } from './report.mjs';
30
- import { renderMetrics, METRICS_CONTENT_TYPE } from './metrics.mjs';
31
- // v0.3.0 §9: request signing. This import is the entire point of the module --
32
- // until the HTTP layer calls it, HMAC support does not exist for any real request.
33
- import { DEFAULT_SKEW_SECONDS, NonceCache, verifyRequest } from '../signing.mjs';
34
- // v0.7.11: per-device Ed25519 verification, tried before the shared secret.
35
- import {
36
- SIGNATURE_HEADER as DEVICE_SIGNATURE_HEADER,
37
- verifyDeviceSignature,
38
- } from '../chatops/device-signing.mjs';
39
-
40
- export const DEFAULT_SSE_KEEPALIVE_MS = 15_000; // §3.2: every 15s a `: keepalive` line
41
- export const DEFAULT_SWEEP_INTERVAL_MS = 1_000;
42
- export const DEFAULT_PAIR_RATE_LIMIT_PER_MINUTE = 5; // v0.1.2 §6
43
- // The window length is a unit and lives with the limiter. Both names are kept: `DEFAULT_WINDOW_MS` is the
44
- // local binding this module uses, and `RATE_LIMIT_WINDOW_MS` is the name this module has always exported.
45
- // `export ... from` would NOT have worked here -- it re-exports without creating a local binding, so the
46
- // constructor below saw `RATE_LIMIT_WINDOW_MS is not defined` while the export itself looked fine.
47
- import { DEFAULT_WINDOW_MS, SlidingWindowRateLimiter } from '../util/rate-limit.mjs';
48
- export { DEFAULT_WINDOW_MS as RATE_LIMIT_WINDOW_MS };
49
- export const DEFAULT_STATE_DIR = path.join(os.homedir(), '.w2m');
50
-
51
- /**
52
- * The environment variable that opts in to printing the operator token on a start that did not
53
- * generate it (MEDIUM-6 of the v0.5.9 review).
54
- *
55
- * The value is printed **once, on the start that generated it**, because that is the only moment at
56
- * which it exists nowhere else yet; every other start has `<state>/operator-token.txt` to read it
57
- * from, and a relay's stdout ends up in journald, a container log or a CI transcript — where a
58
- * credential that authorises dispatching to the whole fleet does not belong. `W2M_PRINT_OPERATOR_TOKEN=1`
59
- * (or `printOperatorToken: true`, which is the same switch for an embedder) restores the old
60
- * behaviour for an operator who genuinely needs it in the log, and says so in the banner when it does.
61
- */
62
- export const PRINT_OPERATOR_TOKEN_ENV = 'W2M_PRINT_OPERATOR_TOKEN';
63
-
64
- /**
65
- * Resolve that opt-in, so the relay and the CLI agree on one answer.
66
- *
67
- * @param {object} [options] Relay options; `printOperatorToken: true` is the programmatic spelling.
68
- * @returns {'option'|'env'|null} Why printing was asked for, or null.
69
- */
70
- export function printOperatorTokenOptIn(options = {}) {
71
- if (options.printOperatorToken === true) return 'option';
72
- const raw = process.env[PRINT_OPERATOR_TOKEN_ENV];
73
- if (raw === '1' || raw === 'true') return 'env';
74
- return null;
75
- }
76
-
77
- /* ------------------------------------------------------------------ */
78
- /* helpers */
79
- /* ------------------------------------------------------------------ */
80
-
81
- /** v0.1.2 §3: `/w2m/` → `/w2m`; '' / '/' → '/'. Never returns a trailing slash. */
82
- export function normalizeBasePath(value) {
83
- if (value === undefined || value === null || value === '') return '/';
84
- let p = String(value).trim();
85
- if (p === '' || p === '/') return '/';
86
- if (!p.startsWith('/')) p = `/${p}`;
87
- p = p.replace(/\/{2,}/g, '/').replace(/\/+$/, '');
88
- return p === '' ? '/' : p;
89
- }
90
-
91
- function normalizePath(pathname) {
92
- if (!pathname) return '/';
93
- return pathname.length > 1 ? pathname.replace(/\/+$/, '') : pathname;
94
- }
95
-
96
- function sendJson(res, status, body, extraHeaders = {}) {
97
- if (res.writableEnded) return undefined;
98
- const payload = Buffer.from(JSON.stringify(body), 'utf8');
99
- res.writeHead(status, {
100
- 'content-type': 'application/json; charset=utf-8',
101
- 'content-length': payload.length,
102
- 'cache-control': 'no-store',
103
- ...extraHeaders,
104
- });
105
- return res.end(payload);
106
- }
107
-
108
- function sendError(res, err) {
109
- if (err instanceof ProtocolError) {
110
- const body = err.toBody();
111
- // §6 just says the 429 "carries retry_after_seconds" without pinning the
112
- // location, so it is emitted both inside error.detail (the §7 shape) and as a
113
- // top-level convenience field. Both are additive.
114
- const retryAfter = err.detail?.retry_after_seconds;
115
- if (typeof retryAfter === 'number') body.retry_after_seconds = retryAfter;
116
- sendJson(res, err.status, body, err.headers ?? {});
117
- return;
118
- }
119
- sendJson(res, 500, {
120
- error: {
121
- code: 'INTERNAL',
122
- message: err?.message ? String(err.message) : 'internal error',
123
- detail: {},
124
- },
125
- });
126
- }
127
-
128
- function bearerToken(req) {
129
- const header = req.headers.authorization;
130
- if (typeof header !== 'string') return null;
131
- const m = /^Bearer\s+(.+)$/i.exec(header.trim());
132
- return m ? m[1].trim() : null;
133
- }
134
-
135
- function firstHeaderValue(value) {
136
- const raw = Array.isArray(value) ? value[0] : value;
137
- if (typeof raw !== 'string') return null;
138
- const first = raw.split(',')[0].trim();
139
- return first === '' ? null : first;
140
- }
141
-
142
- /**
143
- * Read one header case-insensitively from a plain Node headers object.
144
- *
145
- * `signing.mjs` does this internally, but the device-key path needs it before deciding whether that
146
- * module applies at all, so it is needed here too. Node lower-cases incoming header names, and a
147
- * test that builds a request by hand may not, so both spellings are tried.
148
- */
149
- function readHeader(headers, name) {
150
- if (headers === null || headers === undefined) return null;
151
- const found = Object.keys(headers).find((k) => k.toLowerCase() === name);
152
- return found === undefined ? null : firstHeaderValue(headers[found]);
153
- }
154
-
155
- /**
156
- * Read a request body with a hard byte cap.
157
- * @returns {Promise<{tooLarge?:boolean, buffer?:Buffer, aborted?:boolean}>}
158
- */
159
- function readBody(req, limit) {
160
- return new Promise((resolve) => {
161
- const declared = Number(req.headers['content-length']);
162
- if (Number.isFinite(declared) && declared > limit) {
163
- req.resume();
164
- resolve({ tooLarge: true });
165
- return;
166
- }
167
- const chunks = [];
168
- let total = 0;
169
- let settled = false;
170
- const finish = (value) => {
171
- if (settled) return;
172
- settled = true;
173
- resolve(value);
174
- };
175
- req.on('data', (chunk) => {
176
- if (settled) return;
177
- total += chunk.length;
178
- if (total > limit) {
179
- finish({ tooLarge: true });
180
- req.resume();
181
- return;
182
- }
183
- chunks.push(chunk);
184
- });
185
- req.on('end', () => finish({ buffer: Buffer.concat(chunks) }));
186
- req.on('error', () => finish({ aborted: true }));
187
- req.on('aborted', () => finish({ aborted: true }));
188
- });
189
- }
190
-
191
- /**
192
- * Read the raw body bytes with a hard byte cap.
193
- *
194
- * v0.3.0 §9: the body is read exactly ONCE per request and the bytes are kept,
195
- * because an HMAC covers the exact received octets -- re-serialising parsed JSON
196
- * would produce different bytes (key order, whitespace) and break every signature.
197
- */
198
- async function readRawBody(req, limit) {
199
- const body = await readBody(req, limit);
200
- if (body.tooLarge) {
201
- throw new ProtocolError('FRAME_TOO_LARGE', `request frame exceeds ${limit} bytes`, { limit_bytes: limit });
202
- }
203
- if (body.aborted) throw new ProtocolError('BAD_REQUEST', 'request aborted before the body was complete');
204
- return body.buffer;
205
- }
206
-
207
- /** Parse an already-read body buffer as a JSON object. */
208
- function parseJsonBody(buffer) {
209
- const raw = buffer === null || buffer === undefined ? '' : buffer.toString('utf8');
210
- if (raw.trim() === '') return {};
211
- try {
212
- const parsed = JSON.parse(raw);
213
- if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
214
- throw new ProtocolError('BAD_REQUEST', 'request body must be a JSON object');
215
- }
216
- return parsed;
217
- } catch (err) {
218
- if (err instanceof ProtocolError) throw err;
219
- throw new ProtocolError('BAD_REQUEST', 'request body is not valid JSON', { parse_error: String(err.message) });
220
- }
221
- }
222
-
223
- /** Methods that can carry a body the signature must cover. */
224
- function methodHasBody(method) {
225
- return method === 'POST' || method === 'PUT' || method === 'PATCH' || method === 'DELETE';
226
- }
227
-
228
- /* ------------------------------------------------------------------ */
229
- /* request signing (v0.3.0 §9) */
230
- /* ------------------------------------------------------------------ */
231
-
232
- /**
233
- * Operator-facing hints. The `code` says what happened; the hint says what to do
234
- * about it, because "signature mismatch" without a direction is a support ticket.
235
- */
236
- const SIGNATURE_HINTS = Object.freeze({
237
- SIGNATURE_REQUIRED: 'this relay runs with --require-signature; sign the request (PROTOCOL-v0.3.0.md §9)',
238
- SIGNATURE_INCOMPLETE: 'all three of X-W2M-Signature, X-W2M-Timestamp and X-W2M-Nonce must be present together',
239
- SIGNATURE_MISMATCH: 'the signature matches no configured secret — check for a stale or half-rotated secret',
240
- SIGNATURE_EXPIRED: 'the timestamp is outside the accepted clock-skew window — check the sending machine clock',
241
- SIGNATURE_REPLAY: 'this nonce was already used — generate a fresh nonce for every request',
242
- SIGNATURE_BAD_TIMESTAMP: 'X-W2M-Timestamp must be whole unix seconds',
243
- SIGNATURE_BAD_NONCE: 'X-W2M-Nonce must be at least 8 characters',
244
- SIGNING_NOT_CONFIGURED:
245
- 'the relay has --require-signature enabled but no --signing-secret configured; '
246
- + 'this is a RELAY configuration error, not a client problem',
247
- });
248
-
249
- const SIGNATURE_PROTOCOL_CODES = new Set(Object.keys(SIGNATURE_HINTS));
250
-
251
- /** Turn a `verifyRequest` rejection into the §7 error envelope.
252
- * `ProtocolError` resolves the HTTP status from `ERROR_STATUS`, so the mapping
253
- * table lives in exactly one place (state.mjs) instead of being duplicated here. */
254
- function signatureError(decision) {
255
- const code = SIGNATURE_PROTOCOL_CODES.has(decision.code) ? decision.code : 'SIGNATURE_MISMATCH';
256
- return new ProtocolError(code, decision.error, {
257
- code,
258
- reason: decision.error,
259
- hint: SIGNATURE_HINTS[code] ?? null,
260
- });
261
- }
262
-
263
- /**
264
- * Read an optional secret, failing loudly on a value that is present but unusable.
265
- *
266
- * `signing.mjs` calls a silently-disabled secret the failure mode it exists to
267
- * prevent. Treating `signingSecret: 12345` (or `{}`) as "not configured" would do
268
- * exactly that at the wiring layer, so it is an error instead.
269
- */
270
- function readSecretValue(value, label) {
271
- if (value === undefined || value === null || value === '') return null;
272
- if (typeof value !== 'string') {
273
- throw new ProtocolError('BAD_REQUEST',
274
- `${label} must be a non-empty string when provided (got ${typeof value}); `
275
- + 'refusing to silently run without the signing you asked for', { option: label, received_type: typeof value });
276
- }
277
- return value;
278
- }
279
-
280
- /* ------------------------------------------------------------------ */
281
- /* pair rate limiting (v0.1.2 §6) */
282
- /* ------------------------------------------------------------------ */
283
-
284
- /**
285
- * Per-IP sliding window. Successful pairs count too, otherwise a working pairing
286
- * code could be used to flush the failure budget.
287
- */
288
- /*
289
- * The limiter MOVED to `src/util/rate-limit.mjs` in v0.30.0.
290
- *
291
- * It never used anything from this file, and when the approval gate needed the same window, importing it
292
- * from here made an `agent` module depend on the `relay` layer -- which `scripts/layer-model.mjs` refused,
293
- * correctly. `agent` is rank 2 and `relay` is rank 3, so the edge points up; moving the class to `util`
294
- * (rank 0, a leaf) lets both depend on it in the only direction the model allows.
295
- *
296
- * Re-exported rather than merely imported, because `SlidingWindowRateLimiter` and `RATE_LIMIT_WINDOW_MS` are
297
- * part of this module's published surface and `test/relay.test.mjs` imports the class from here.
298
- */
299
- export { SlidingWindowRateLimiter };
300
-
301
- /* ------------------------------------------------------------------ */
302
- /* server */
303
- /* ------------------------------------------------------------------ */
304
-
305
- export class RelayServer {
306
- constructor(options = {}) {
307
- this.options = options;
308
- this.basePath = normalizeBasePath(options.basePath);
309
- this.trustProxy = options.trustProxy === true;
310
- this.frameLimitBytes = options.frameLimitBytes ?? MAX_FRAME_BYTES;
311
- this.keepaliveMs = options.keepaliveMs ?? DEFAULT_SSE_KEEPALIVE_MS;
312
- this.sweepIntervalMs = options.sweepIntervalMs ?? DEFAULT_SWEEP_INTERVAL_MS;
313
- this.pairRateLimitPerMinute = Number.isFinite(options.pairRateLimitPerMinute)
314
- ? options.pairRateLimitPerMinute : DEFAULT_PAIR_RATE_LIMIT_PER_MINUTE;
315
-
316
- // §3: `logger: null` silences. The default writes to STDERR on purpose —
317
- // stdout belongs to protocol output (e.g. the CLI's `--json` line), and mixing
318
- // prose into it breaks `| ConvertFrom-Json` / `| jq`.
319
- this.logger = options.logger === undefined
320
- ? ((msg) => process.stderr.write(`${msg}\n`))
321
- : options.logger;
322
- this.startupMessages = [];
323
-
324
- /* ---- persistence (§7) ---- */
325
- const rawStateDir = options.stateDir ?? (typeof options.state === 'string' ? options.state : null);
326
- const persistEnabled = options.persist !== false && rawStateDir !== '';
327
- const stateDir = persistEnabled
328
- ? path.resolve(rawStateDir === null || rawStateDir === undefined ? DEFAULT_STATE_DIR : String(rawStateDir))
329
- : null;
330
- this.persistence = new Persistence({
331
- dir: stateDir,
332
- now: () => (this.state ? this.state.nowMs() : Date.now()),
333
- });
334
-
335
- /* ---- state ---- */
336
- const injected = options.state && typeof options.state === 'object' ? options.state : null;
337
- this.state = injected ?? new RabbitState({ ...options, persistence: this.persistence });
338
- this.state.setPersistence(this.persistence);
339
-
340
- // v0.3.9: P2P signalling. Ephemeral by design -- see src/relay/peers.mjs.
341
- this.peers = options.peers ?? new PeerRegistry({ nowMs: () => this.state.nowMs() });
342
-
343
- this.relayId = this.state.relayId;
344
- this._startedAtMs = this.state.nowMs();
345
-
346
- /* ---- startup recovery (§7) ---- */
347
- if (this.persistence.enabled) {
348
- const snapshot = this.persistence.loadDevices();
349
- this.persistence.devicesMissing = snapshot.missing;
350
- const ledger = this.persistence.loadLedger();
351
- const revived = this.state.restore({ devices: snapshot.devices, ledger });
352
- this.persistence.revivedDevices = revived.revived_devices;
353
- this.persistence.revivedTasks = revived.revived_tasks;
354
- }
355
-
356
- /* ---- operator token (§5) ---- */
357
- this._initOperatorToken(options);
358
-
359
- /* ---- v0.3.0 §9 request signing ---- */
360
- this.signingSecrets = [
361
- readSecretValue(options.signingSecret, 'signingSecret'),
362
- readSecretValue(options.signingSecretPrevious, 'signingSecretPrevious'),
363
- ].filter((s) => s !== null); // newest first: keyIndex 0 = current, 1 = previous
364
- this.signingConfigured = this.signingSecrets.length > 0;
365
- this.requireSignature = options.requireSignature === true;
366
- /**
367
- * v0.3.3: whether `GET /metrics` exists.
368
- *
369
- * Defaults to off. A monitoring endpoint that appears without being asked for is a surface nobody
370
- * chose, and the operator can turn it on with `--metrics` when a scraper exists.
371
- */
372
- this.metricsEnabled = options.metrics === true;
373
- this.signatureSkewSeconds = Number.isFinite(options.signatureSkewSeconds)
374
- ? options.signatureSkewSeconds : DEFAULT_SKEW_SECONDS;
375
- // One cache per relay instance: replay defence is stateful, and two relays
376
- // sharing a cache would let a nonce blocked on one be replayed on the other.
377
- this.nonceCache = options.nonceCache ?? new NonceCache({
378
- max: options.nonceCacheMax ?? 20_000,
379
- retentionMs: options.nonceCacheRetentionMs ?? 10 * 60_000,
380
- });
381
- this.nonceRetentionMs = options.nonceCacheRetentionMs ?? 10 * 60_000;
382
-
383
- /* ---- /v1/pair rate limit (§6) ---- */
384
- this.pairLimiter = new SlidingWindowRateLimiter({
385
- limit: this.pairRateLimitPerMinute,
386
- windowMs: DEFAULT_WINDOW_MS,
387
- now: () => this.state.nowMs(),
388
- });
389
-
390
- /* ---- transport ---- */
391
- this.tlsCertPath = options.tlsCert ?? null;
392
- this.tlsKeyPath = options.tlsKey ?? null;
393
- if ((this.tlsCertPath && !this.tlsKeyPath) || (!this.tlsCertPath && this.tlsKeyPath)) {
394
- throw new ProtocolError('BAD_REQUEST', 'tlsCert and tlsKey must be provided together', {
395
- tls_cert: this.tlsCertPath, tls_key: this.tlsKeyPath,
396
- });
397
- }
398
- const handler = (req, res) => {
399
- this.handle(req, res).catch((err) => this.reportError(req, res, err));
400
- };
401
- if (this.tlsCertPath) {
402
- let cert;
403
- let key;
404
- try {
405
- cert = fs.readFileSync(this.tlsCertPath);
406
- key = fs.readFileSync(this.tlsKeyPath);
407
- } catch (err) {
408
- // Never silently fall back to plain HTTP: that would be a security downgrade.
409
- throw new ProtocolError('BAD_REQUEST', `cannot read TLS material: ${err.message}`, {
410
- tls_cert: this.tlsCertPath, tls_key: this.tlsKeyPath,
411
- });
412
- }
413
- this.server = https.createServer({ cert, key }, handler);
414
- this.scheme = 'https';
415
- } else {
416
- this.server = http.createServer(handler);
417
- this.scheme = 'http';
418
- }
419
-
420
- // v0.1.2 BUG-1: an externally supplied code must be REGISTERED, not merely
421
- // assigned — otherwise the banner advertises a code /v1/pair does not know.
422
- this.pairingCode = typeof options.pairingCode === 'string' && options.pairingCode.trim() !== ''
423
- ? this.state.registerPairingCode(options.pairingCode, { ttlMs: options.pairingCodeTtlMs })
424
- : this.state.createPairingCode();
425
- this.subscribers = new Set();
426
- this.host = null;
427
- this.port = null;
428
- this._sweepTimer = null;
429
-
430
- // SSE connections are long-lived: never let Node time the request out.
431
- this.server.requestTimeout = options.requestTimeoutMs ?? 0;
432
- this.server.headersTimeout = options.headersTimeoutMs ?? 60_000;
433
-
434
- this._buildStartupMessages();
435
- }
436
-
437
- /**
438
- * Diagnostics sink. `logger: null` is the documented "silent" value, and a
439
- * caller-supplied logger may throw — neither may break a request. (A direct
440
- * `this.logger(...)` call after `res.writeHead()` once threw a TypeError that
441
- * surfaced as "Cannot write headers after they are sent to the client".)
442
- */
443
- _log(message) {
444
- if (typeof this.logger !== 'function') return;
445
- try {
446
- this.logger(message);
447
- } catch { /* a broken logger must never break the relay */ }
448
- }
449
-
450
- /**
451
- * Last-resort error path for a request whose handler rejected.
452
- * Once the status line is on the wire (SSE, streamed report) the response can no
453
- * longer be rewritten — the only honest action is to end the stream, loudly.
454
- */
455
- reportError(req, res, err) {
456
- if (res.headersSent) {
457
- this._log(`[w2m-rabbit] !! error after the response had started on ${req.method} ${req.url}: `
458
- + `${err?.stack ?? err}`);
459
- try { res.end(); } catch { /* already gone */ }
460
- return;
461
- }
462
- sendError(res, err);
463
- }
464
-
465
- _initOperatorToken(options) {
466
- const wantsRequired = options.operatorTokenRequired !== false;
467
- const explicit = options.operatorToken;
468
- const persisted = this.persistence.enabled ? this.persistence.readOperatorToken() : null;
469
- /**
470
- * Why the token may be printed, when it may be: `'generated'` is the one start whose token exists
471
- * nowhere else until this process writes it, and `'option'`/`'env'` are the documented opt-ins.
472
- * @type {'generated'|'option'|'env'|null}
473
- */
474
- this.operatorTokenPrintReason = printOperatorTokenOptIn(options);
475
-
476
- if (!wantsRequired || explicit === '') {
477
- this.operatorToken = null;
478
- this.operatorTokenRequired = false;
479
- this.operatorTokenSource = 'disabled';
480
- this.operatorTokenPrintable = false;
481
- this.operatorTokenPrintReason = null;
482
- return;
483
- }
484
- this.operatorTokenRequired = true;
485
- if (typeof explicit === 'string' && explicit.length > 0) {
486
- this.operatorToken = explicit;
487
- this.operatorTokenSource = 'option';
488
- this.persistence.writeOperatorToken(explicit);
489
- } else if (persisted) {
490
- // §5.1 + §7: keep the token stable across restarts, otherwise every restart
491
- // would silently invalidate the plugin's configured operatorToken.
492
- this.operatorToken = persisted;
493
- this.operatorTokenSource = 'restored';
494
- } else {
495
- this.operatorToken = randomBytes(32).toString('hex');
496
- this.operatorTokenSource = 'generated';
497
- this.persistence.writeOperatorToken(this.operatorToken);
498
- }
499
- // MEDIUM-6: the material is printed only by the start that generated it, or when the operator has
500
- // explicitly asked for it. "The posture, never the material" still holds everywhere else.
501
- if (this.operatorTokenSource === 'generated') {
502
- this.operatorTokenPrintReason = this.operatorTokenPrintReason ?? 'generated';
503
- }
504
- this.operatorTokenPrintable = this.operatorTokenPrintReason !== null;
505
- }
506
-
507
- _buildStartupMessages() {
508
- const m = this.startupMessages;
509
- m.push(`[w2m-rabbit] relay_id=${this.relayId}`);
510
- m.push(`[w2m-rabbit] base_path=${this.basePath}${this.basePath === '/' ? ' (root)' : ''}`);
511
- m.push(`[w2m-rabbit] trust_proxy=${this.trustProxy}${this.trustProxy ? '' : ' (X-Forwarded-* ignored)'}`);
512
- m.push(`[w2m-rabbit] pair_rate_limit=${this.pairRateLimitPerMinute === 0 ? 'disabled' : `${this.pairRateLimitPerMinute}/min/IP`}`);
513
- // §9: report the posture, never the material.
514
- if (this.signingConfigured) {
515
- m.push(`[w2m-rabbit] request signing=ON (${this.signingSecrets.length} secret(s)`
516
- + `${this.signingSecrets.length > 1 ? ', rotation active' : ''})`
517
- + `${this.requireSignature ? ' - REQUIRED: unsigned /v1/* is rejected with 401' : ' - optional: unsigned requests are still accepted'}`);
518
- } else if (this.requireSignature) {
519
- m.push('[w2m-rabbit] !! CONFIGURATION ERROR: --require-signature is set but no --signing-secret was provided. '
520
- + 'Every /v1/* request will fail with 500 SIGNING_NOT_CONFIGURED (this is the RELAY\'s fault, not the client\'s). '
521
- + 'Either set --signing-secret or drop --require-signature.');
522
- } else {
523
- m.push('[w2m-rabbit] request signing=off (no signing secret configured; behaviour is identical to v0.2.3)');
524
- }
525
- if (this.persistence.enabled) {
526
- m.push(`[w2m-rabbit] persistence=on dir=${this.persistence.dir} `
527
- + `revived_devices=${this.persistence.revivedDevices} revived_tasks=${this.persistence.revivedTasks}`);
528
- } else {
529
- m.push('[w2m-rabbit] persistence=off (in-memory only; devices and tasks are lost on restart)');
530
- }
531
- if (this.persistence.devicesCorrupt) {
532
- m.push('[w2m-rabbit] !! WARNING: devices.json was CORRUPT — started from an EMPTY device table; '
533
- + 'every machine must pair again. The damaged file was left untouched.');
534
- }
535
- for (const w of this.persistence.warnings) {
536
- m.push(`[w2m-rabbit] !! ${w.file}: ${w.message}`);
537
- }
538
- if (this.operatorTokenRequired) {
539
- // MEDIUM-6: the token is material, not posture, so it is printed as rarely as it can be — on the
540
- // start that generated it (`operatorTokenSource === 'generated'`) or when `printOperatorToken` /
541
- // `W2M_PRINT_OPERATOR_TOKEN=1` asked for it — and once, never twice. Where it is stored is said in
542
- // every case, including the case where there is nowhere to store it.
543
- //
544
- // DELIBERATE, do not "fix": on that one start the CLI prints the value a second time, in its own
545
- // stdout banner. Two sinks for one start is not a leak — the defect was printing it on *every*
546
- // start, restored ones included — and the box is the documented first-start handoff a human reads
547
- // (docs/DEPLOY.md §2.4, test/crossnetwork.test.mjs). Collapsing the pair would trade a documented
548
- // behaviour for one saved line on one start.
549
- const tokenFile = this.persistence.operatorTokenFile ?? null;
550
- const stored = tokenFile === null
551
- ? 'persistence is off, so this token exists only in this process and cannot be read back later'
552
- : `stored at ${tokenFile} (0600)`;
553
- if (this.operatorTokenPrintable) {
554
- m.push(`[w2m-rabbit] operator token (${this.operatorTokenSource}) - required for POST /v1/task:`);
555
- m.push(`[w2m-rabbit] ${this.operatorToken}`);
556
- m.push(`[w2m-rabbit] printed once because ${this.operatorTokenPrintReason === 'generated'
557
- ? 'this start generated it' : `${this.operatorTokenPrintReason} asked for it (${PRINT_OPERATOR_TOKEN_ENV})`}`
558
- + ` - and ${stored}`);
559
- } else {
560
- m.push(`[w2m-rabbit] operator token (${this.operatorTokenSource}) - required for POST /v1/task, NOT printed`);
561
- m.push(`[w2m-rabbit] read it from ${tokenFile ?? '<state>/operator-token.txt'} - ${stored}`);
562
- m.push(`[w2m-rabbit] set ${PRINT_OPERATOR_TOKEN_ENV}=1 to print it on this start as well`);
563
- }
564
- } else {
565
- m.push('[w2m-rabbit] !! WARNING: OPERATOR TOKEN DISABLED (--operator-token "") - '
566
- + 'any device that can reach this relay can dispatch tasks to the whole group. '
567
- + 'Only acceptable on a trusted LAN / for debugging; /v1/task then requires a device token.');
568
- }
569
- }
570
-
571
- get url() {
572
- if (this.host === null || this.port === null) return null;
573
- const host = this.host.includes(':') ? `[${this.host}]` : this.host;
574
- const prefix = this.basePath === '/' ? '' : this.basePath;
575
- return `${this.scheme}://${host}:${this.port}${prefix}`;
576
- }
577
-
578
- listen({ host = '127.0.0.1', port = 0 } = {}) {
579
- return new Promise((resolve, reject) => {
580
- const onError = (err) => reject(err);
581
- this.server.once('error', onError);
582
- this.server.listen(port, host, () => {
583
- this.server.removeListener('error', onError);
584
- const addr = this.server.address();
585
- this.host = addr.address;
586
- this.port = addr.port;
587
- this._sweepTimer = setInterval(() => {
588
- this.maintenance();
589
- }, this.sweepIntervalMs);
590
- this._sweepTimer.unref?.();
591
- if (this.logger) {
592
- this._log(`[w2m-rabbit] listening on ${this.url} pairing code: ${this.pairingCode}`);
593
- for (const message of this.startupMessages) this._log(message);
594
- }
595
- resolve({
596
- host: this.host,
597
- port: this.port,
598
- url: this.url,
599
- pairingCode: this.pairingCode,
600
- relayId: this.relayId,
601
- basePath: this.basePath,
602
- operatorToken: this.operatorToken,
603
- operatorTokenRequired: this.operatorTokenRequired,
604
- // The CLI prints its own banner, so it has to reach the same conclusion this class did rather
605
- // than re-deriving one from the token's presence (MEDIUM-6).
606
- operatorTokenSource: this.operatorTokenSource,
607
- operatorTokenPrintable: this.operatorTokenPrintable === true,
608
- operatorTokenPrintReason: this.operatorTokenPrintReason ?? null,
609
- scheme: this.scheme,
610
- });
611
- });
612
- });
613
- }
614
-
615
- sweep() {
616
- return this.state.sweepExpired();
617
- }
618
-
619
- close() {
620
- return new Promise((resolve) => {
621
- if (this._sweepTimer) clearInterval(this._sweepTimer);
622
- this._sweepTimer = null;
623
- // v0.4.0: a deferred P2P offer is a pending timer, and a closed relay must not fire one.
624
- this.state.clearPendingOffers?.();
625
- for (const sub of [...this.subscribers]) this._closeSubscriber(sub);
626
- this.server.close(() => resolve());
627
- this.server.closeAllConnections?.();
628
- });
629
- }
630
-
631
- /* ---------------- proxy awareness (v0.1.2 §3) ---------------- */
632
-
633
- /** `X-Forwarded-For` first hop is honoured ONLY under `trustProxy`. */
634
- clientIp(req) {
635
- if (this.trustProxy) {
636
- const forwarded = firstHeaderValue(req.headers['x-forwarded-for']);
637
- if (forwarded) return forwarded;
638
- }
639
- return req.socket?.remoteAddress ?? 'unknown';
640
- }
641
-
642
- /** `X-Forwarded-Proto` is honoured ONLY under `trustProxy`. */
643
- effectiveScheme(req) {
644
- if (this.trustProxy) {
645
- const proto = firstHeaderValue(req.headers['x-forwarded-proto']);
646
- if (proto) return proto.toLowerCase();
647
- }
648
- return this.scheme;
649
- }
650
-
651
- /* ---------------- request dispatch ---------------- */
652
-
653
- async handle(req, res) {
654
- let url;
655
- try {
656
- url = new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`);
657
- } catch {
658
- throw new ProtocolError('BAD_REQUEST', 'malformed request URL');
659
- }
660
- const rawPath = url.pathname;
661
- const method = (req.method ?? 'GET').toUpperCase();
662
-
663
- // §3: strip the deployment prefix, then route. `/healthz` also answers at the
664
- // root because health checks are usually pointed straight at the container.
665
- // `stripped` keeps the literal request path (no trailing-slash normalisation)
666
- // because that is what a signature covers; `path` is the normalised route key.
667
- let stripped;
668
- if (this.basePath === '/') {
669
- stripped = rawPath;
670
- } else if (rawPath === this.basePath) {
671
- stripped = '/';
672
- } else if (rawPath.startsWith(`${this.basePath}/`)) {
673
- stripped = rawPath.slice(this.basePath.length);
674
- } else if (rawPath === '/healthz') {
675
- stripped = '/healthz';
676
- } else {
677
- // Outside the prefix: an explicit 404, never a gateway-style 502.
678
- throw new ProtocolError('NOT_FOUND', `path is outside the configured base path ${this.basePath}`, {
679
- path: rawPath, base_path: this.basePath,
680
- });
681
- }
682
- const path = normalizePath(stripped);
683
- const signedPath = `${stripped}${url.search}`;
684
-
685
- // v0.3.0 §9: read the body ONCE, before routing. An HMAC covers the exact
686
- // received bytes, so no route may consume the stream first and re-serialise.
687
- const rawBody = methodHasBody(method) ? await readRawBody(req, this.frameLimitBytes) : null;
688
- const takeJson = () => parseJsonBody(rawBody);
689
-
690
- /* ---- public endpoints ---- */
691
- // `/healthz` and `/v1/pair` are permanently exempt from signature checks:
692
- // the first is an operations probe that must not need credentials, the second
693
- // is the bootstrap step that happens before the two sides share a secret.
694
- if (method === 'GET' && path === '/healthz') {
695
- return sendJson(res, 200, this.healthBody(req));
696
- }
697
- if (method === 'POST' && path === '/v1/pair') {
698
- this.enforcePairRateLimit(req);
699
- const result = this.state.pair(takeJson());
700
- return sendJson(res, 200, result);
701
- }
702
- /**
703
- * v0.3.3 `/metrics`: machine-readable fleet state for a monitoring system.
704
- *
705
- * Token-free, like `/healthz` and for the same reason: a scraper that needs the operator token
706
- * would put that token in a Prometheus config file, which is a credential in a place nobody
707
- * reviews. It is also exempt from signature checks for the same reason -- there is no secret to
708
- * sign with on the scraper side.
709
- *
710
- * Exposed only when the relay was asked for it (`--metrics`). A monitoring endpoint that appears
711
- * by default is a surface nobody chose, and the whole point of the defaults elsewhere is that the
712
- * relay binds nothing the operator did not ask for.
713
- */
714
- if (method === 'GET' && path === '/metrics') {
715
- if (!this.metricsEnabled) {
716
- // 404 rather than 403: a disabled endpoint should look absent, not forbidden. A 403 tells a
717
- // scanner the surface exists.
718
- throw new ProtocolError('NOT_FOUND', 'metrics are not enabled on this relay', { hint: 'start the relay with --metrics' });
719
- }
720
- const body = renderMetrics(this.state, { nowMs: this.state.nowMs() });
721
- res.writeHead(200, {
722
- 'content-type': METRICS_CONTENT_TYPE,
723
- 'content-length': Buffer.byteLength(body, 'utf8'),
724
- 'cache-control': 'no-store',
725
- });
726
- return res.end(body);
727
- }
728
- // §5: dispatching tasks needs the operator token, not a device token.
729
- if (method === 'POST' && path === '/v1/task') {
730
- const principal = this.authorizeTaskDispatch(req);
731
- this.enforceSignature(req, { method, signedPath, body: rawBody });
732
- const body = takeJson();
733
- if (principal.machine_id && !body.created_by) body.created_by = principal.machine_id;
734
- const result = this.state.createTask(body);
735
- return sendJson(res, 200, result);
736
- }
737
-
738
- /* ---- v1.1.6: reachable WITHOUT a device token ---- */
739
- this.joinChallenges ??= createJoinChallenges({
740
- now: () => this.state.nowMs(),
741
- publicKeyFor: (fingerprint) => this.state.accountKeyFor(fingerprint),
742
- });
743
- if (method === 'GET' && path === '/v1/fleet/admission/challenge') {
744
- const issued = this.joinChallenges.issue(url.searchParams.get('fingerprint') ?? '', url.searchParams.get('machine_id') ?? '');
745
- if (issued.ok !== true) throw new ProtocolError('BAD_REQUEST', 'challenge refused: ' + issued.code, { code: issued.code });
746
- return sendJson(res, 200, { protocol_version: PROTOCOL_VERSION, rabbit_time: this.state.nowIso(), ...issued });
747
- }
748
- if (method === 'POST' && path === '/v1/fleet/admission/request') {
749
- const body = takeJson();
750
- this.admission ??= createAdmission({ now: () => this.state.nowMs() });
751
- const proof = this.joinChallenges.consume({ challenge_id: body.challenge_id, machine_id: body.machine_id, signature: body.signature });
752
- if (proof.ok !== true) throw new ProtocolError('UNAUTHORIZED', 'join proof refused: ' + proof.code, { code: proof.code });
753
- const result = this.admission.requestAdmission({ machine_id: body.machine_id, machine_name: body.machine_name ?? null, account_fingerprint: proof.fingerprint });
754
- return sendJson(res, 200, { protocol_version: PROTOCOL_VERSION, rabbit_time: this.state.nowIso(), ...result });
755
- }
756
-
757
- /* ---- everything below requires `Authorization: Bearer <device_token>` ---- */
758
- const token = bearerToken(req);
759
- const device = token ? this.state.authenticate(token) : null;
760
- if (!device) {
761
- throw new ProtocolError('UNAUTHORIZED', 'missing or invalid device_token', {});
762
- }
763
- this.state.touchDevice(device.machine_id);
764
-
765
- // v0.3.0 §9: writes are always checked (tolerating unsigned unless required);
766
- // reads are only checked when the relay was explicitly told to require
767
- // signatures. See `enforceSignature` for the reasoning.
768
- this.enforceSignature(req, { method, signedPath, body: rawBody });
769
-
770
- if (method === 'GET' && path === '/v1/stream') {
771
- return this.handleStream(req, res, url, device);
772
- }
773
- if (method === 'POST' && path === '/v1/heartbeat') {
774
- const body = takeJson();
775
- body.machine_id = body.machine_id ?? device.machine_id;
776
- const result = this.state.heartbeat(body);
777
- return sendJson(res, 200, result);
778
- }
779
- if (method === 'POST' && path === '/v1/result') {
780
- const body = takeJson();
781
- const result = this.state.submitResult(body);
782
- const { _instanceKey, ...clean } = result;
783
- return sendJson(res, 200, clean);
784
- }
785
- /**
786
- * v1.0.7: the content-addressed blob channel (#1).
787
- *
788
- * ## Why the relay may carry bytes at all
789
- *
790
- * It persists `stdout_sha256` and never the text, and `src/agent/storage.mjs` records why: each machine's
791
- * `memory.jsonl` is the only durable copy of what a command printed. **That invariant is about the relay not
792
- * interpreting content** -- it never decides what bytes mean and never asserts they are authentic.
793
- *
794
- * A blob keyed by its own hash preserves exactly that. The relay still interprets nothing; **the hash is what
795
- * says the bytes are the bytes**, exactly as `stdout_sha256` does for a result. What is new is only that a hash
796
- * the relay already holds can have its bytes fetched from the same place.
797
- *
798
- * ## Why the hash is verified before storing
799
- *
800
- * A content-addressed store that accepts bytes under a key they do not hash to is not content-addressed -- the
801
- * key stops being a claim about the content, and every later reader's verification becomes decorative. So a
802
- * mismatch is **refused (422)**, never stored and never corrected: correcting it would silently re-key a blob
803
- * the caller believes it stored under a different name.
804
- *
805
- * ## Fleet scoping
806
- *
807
- * `putFleetBlob`/`getFleetBlob` reuse `scopeFleetId`, the same rule task dispatch obeys. A blob written by one
808
- * fleet is **not readable by another**, and the read refusal is a 404 rather than a 403: a distinguishable
809
- * "not yours" tells a prober that the hash exists here.
810
- */
811
- /**
812
- * v1.0.9: **which blob this fleet published last** -- the discovery half of the channel.
813
- *
814
- * Checked **before** the `<sha256>` matcher deliberately. The matcher only accepts 64 hex characters, so
815
- * `latest` cannot collide with it today; **the ordering is asserted anyway**, because "these two patterns cannot
816
- * conflict" is exactly the reasoning that produces a shadowed route the day one of them is relaxed.
817
- *
818
- * A fleet that has never published gets a 404 rather than an empty object: "there is no current document" and
819
- * "the current document is nothing" are different statements, and only one of them is true here.
820
- */
821
- if (method === 'GET' && path === '/v1/fleet/blobs/latest') {
822
- const latest = this.state.latestFleetBlob(device);
823
- if (latest === null) {
824
- throw new ProtocolError('NOT_FOUND', 'this fleet has published no blob', {});
825
- }
826
- return sendJson(res, 200, {
827
- protocol_version: PROTOCOL_VERSION,
828
- hash: latest.hash,
829
- bytes: latest.bytes,
830
- published_at: new Date(latest.published_at_ms).toISOString(),
831
- published_by: latest.published_by ?? null,
832
- // Stated in the payload, not only in the docs: a pointer can outlive its blob under oldest-first eviction.
833
- hint: 'a hint, not a guarantee -- a pull may answer 404 if the blob has since been evicted',
834
- });
835
- }
836
-
837
- const blobMatch = /^\/v1\/fleet\/blobs\/([0-9a-f]{64})$/.exec(path);
838
- if (blobMatch !== null) {
839
- const hash = blobMatch[1];
840
- if (method === 'PUT') {
841
- const received = rawBody ?? Buffer.alloc(0);
842
- const actual = createHash('sha256').update(received).digest('hex');
843
- if (actual !== hash) {
844
- throw new ProtocolError('BLOB_HASH_MISMATCH', 'the body does not hash to the key it was sent under', {
845
- expected: hash,
846
- actual,
847
- bytes: received.length,
848
- });
849
- }
850
- const stored = this.state.putFleetBlob(device, received);
851
- if (stored.ok !== true) {
852
- throw new ProtocolError(stored.reason ?? 'BLOB_WRITE_FAILED', stored.detail ?? 'the blob was refused', {
853
- hash,
854
- });
855
- }
856
- return sendJson(res, 201, {
857
- protocol_version: PROTOCOL_VERSION,
858
- ok: true,
859
- hash: stored.hash,
860
- bytes: stored.bytes,
861
- evicted: stored.evicted,
862
- });
863
- }
864
- if (method === 'GET') {
865
- const bytes = this.state.getFleetBlob(device, hash);
866
- if (bytes === null) {
867
- // Same code and shape for "no such blob" and "not your fleet's" -- deliberately indistinguishable.
868
- throw new ProtocolError('NOT_FOUND', 'no such blob is readable by this device', { hash });
869
- }
870
- res.writeHead(200, {
871
- 'content-type': 'application/octet-stream',
872
- 'content-length': bytes.length,
873
- // Same reason as `/metrics`: a memory document must not be cached by an intermediary.
874
- 'cache-control': 'no-store',
875
- });
876
- res.end(bytes);
877
- return true;
878
- }
879
- throw new ProtocolError('BAD_REQUEST', 'a blob is addressed with PUT or GET', { method });
880
- }
881
-
882
- if (method === 'GET' && path === '/v1/devices') {
883
- return sendJson(res, 200, {
884
- protocol_version: PROTOCOL_VERSION,
885
- rabbit_time: this.state.nowIso(),
886
- devices: this.state.listDevices(),
887
- });
888
- }
889
- if (method === 'GET' && path === '/v1/tasks') {
890
- const rawLimit = url.searchParams.get('limit');
891
- let limit = 50;
892
- if (rawLimit !== null) {
893
- limit = Number(rawLimit);
894
- if (!Number.isInteger(limit) || limit < 1) {
895
- throw new ProtocolError('BAD_REQUEST', 'limit must be a positive integer', { limit: rawLimit });
896
- }
897
- }
898
- return sendJson(res, 200, {
899
- protocol_version: PROTOCOL_VERSION,
900
- rabbit_time: this.state.nowIso(),
901
- tasks: this.state.listTasks({ limit }),
902
- });
903
- }
904
-
905
- const taskMatch = /^\/v1\/tasks\/([^/]+)$/.exec(path);
906
- const reportMatch = /^\/v1\/tasks\/([^/]+)\/report$/.exec(path);
907
- // v0.3.0: cross-machine RTT status. The plugin may run on a different machine
908
- // than the agent, so this has to come from the relay, not from a local file.
909
- const agentStatusMatch = /^\/v1\/agents\/([^/]+)\/status$/.exec(path);
910
- // v0.3.9: P2P candidate rendezvous. `/announce` is checked before the read route
911
- // so that a machine literally named "announce" cannot shadow it.
912
- const peerReadMatch = /^\/v1\/peer\/([^/]+)$/.exec(path);
913
- /* ---- v1.1.6 admission ---- */
914
- const admissionDecideMatch = /^\/v1\/fleet\/admission\/([^/]+)\/decide$/.exec(path);
915
- const admissionOneMatch = /^\/v1\/fleet\/admission\/([^/]+)$/.exec(path);
916
- const memberRemoveMatch = /^\/v1\/fleet\/members\/([^/]+)\/remove$/.exec(path);
917
- const removalVoteMatch = /^\/v1\/fleet\/removals\/([^/]+)\/vote$/.exec(path);
918
-
919
- /* ---- v0.3.9 P2P signalling ---- */
920
- if (method === 'POST' && path === '/v1/peer/announce') {
921
- const body = takeJson();
922
- try {
923
- // `device.machine_id`, never `body.machine_id`: a paired machine may only
924
- // announce addresses for itself, or it could aim a peer's punch at a third party.
925
- const result = this.peers.announce(device.machine_id, body);
926
- return sendJson(res, 200, {
927
- protocol_version: PROTOCOL_VERSION,
928
- rabbit_time: this.state.nowIso(),
929
- ...result,
930
- });
931
- } catch (error) {
932
- throw new ProtocolError('BAD_REQUEST', error.message, { code: error.code ?? 'BAD_ANNOUNCEMENT' });
933
- }
934
- }
935
-
936
- if (method === 'GET' && peerReadMatch) {
937
- const machineId = decodeURIComponent(peerReadMatch[1]);
938
- const entry = this.peers.get(machineId);
939
- if (!entry) {
940
- // A named 404 rather than an empty list: "this machine has not announced" and
941
- // "this machine announced nothing reachable" call for different responses, and
942
- // an empty candidate list would send the caller into a punch that cannot work.
943
- throw new ProtocolError('NOT_FOUND', `no live P2P announcement for ${machineId}`, {
944
- machine_id: machineId,
945
- hint: 'the peer must POST /v1/peer/announce first, and announcements expire',
946
- });
947
- }
948
- return sendJson(res, 200, {
949
- protocol_version: PROTOCOL_VERSION,
950
- rabbit_time: this.state.nowIso(),
951
- peer: entry,
952
- });
953
- }
954
-
955
- if (method === 'GET' && agentStatusMatch) {
956
- const machineId = decodeURIComponent(agentStatusMatch[1]);
957
- const status = this.state.deviceStatus(machineId);
958
- if (!status) {
959
- throw new ProtocolError('NOT_FOUND', 'unknown machine_id', { machine_id: machineId });
960
- }
961
- return sendJson(res, 200, {
962
- protocol_version: PROTOCOL_VERSION,
963
- rabbit_time: this.state.nowIso(),
964
- ...status,
965
- });
966
- }
967
-
968
- if (method === 'GET' && reportMatch) {
969
- const taskId = decodeURIComponent(reportMatch[1]);
970
- this.state.sweepExpired();
971
- const format = url.searchParams.get('format') ?? 'json';
972
- const report = buildReport(this.state, taskId, { format });
973
- if (res.writableEnded) return undefined;
974
- res.writeHead(200, {
975
- 'content-type': report.contentType,
976
- 'content-length': Buffer.byteLength(report.body, 'utf8'),
977
- 'cache-control': 'no-store',
978
- });
979
- return res.end(report.body);
980
- }
981
-
982
- if (method === 'GET' && taskMatch) {
983
- const taskId = decodeURIComponent(taskMatch[1]);
984
- this.state.sweepExpired();
985
- const task = this.state.requireTask(taskId);
986
- const aggregate = aggregateTask(this.state, taskId);
987
- return sendJson(res, 200, {
988
- protocol_version: PROTOCOL_VERSION,
989
- rabbit_time: this.state.nowIso(),
990
- task: this.state.taskSummary(task),
991
- leases: [...task.leases.values()],
992
- aggregate,
993
- });
994
- }
995
-
996
-
997
- /* ---- v1.1.6 admission: the caller is always `device.machine_id`, never a body field ---- */
998
- this.admission ??= createAdmission({ now: () => this.state.nowMs() });
999
-
1000
- if (method === 'GET' && path === '/v1/fleet/admission/pending') {
1001
- return sendJson(res, 200, {
1002
- protocol_version: PROTOCOL_VERSION, rabbit_time: this.state.nowIso(),
1003
- pending: this.admission.pendingFor(),
1004
- });
1005
- }
1006
-
1007
- if (method === 'POST' && admissionDecideMatch) {
1008
- const body = takeJson();
1009
- const result = this.admission.decide(decodeURIComponent(admissionDecideMatch[1]), {
1010
- decision: body.decision, decided_by: device.machine_id, auto: body.auto === true,
1011
- });
1012
- if (result.ok !== true) throw new ProtocolError('BAD_REQUEST', 'admission decision refused: ' + result.code, result);
1013
- return sendJson(res, 200, { protocol_version: PROTOCOL_VERSION, rabbit_time: this.state.nowIso(), ...result });
1014
- }
1015
-
1016
- if (method === 'GET' && admissionOneMatch) {
1017
- const request = this.admission.getRequest(decodeURIComponent(admissionOneMatch[1]));
1018
- if (request === null) throw new ProtocolError('NOT_FOUND', 'unknown admission request');
1019
- return sendJson(res, 200, { protocol_version: PROTOCOL_VERSION, rabbit_time: this.state.nowIso(), request });
1020
- }
1021
-
1022
- if (method === 'POST' && memberRemoveMatch) {
1023
- const body = takeJson();
1024
- const result = this.admission.remove(decodeURIComponent(memberRemoveMatch[1]), {
1025
- requested_by: device.machine_id, reason: typeof body.reason === 'string' ? body.reason : null,
1026
- });
1027
- if (result.ok !== true) throw new ProtocolError('BAD_REQUEST', 'removal refused: ' + result.code, result);
1028
- return sendJson(res, 200, { protocol_version: PROTOCOL_VERSION, rabbit_time: this.state.nowIso(), ...result });
1029
- }
1030
-
1031
- if (method === 'POST' && removalVoteMatch) {
1032
- const body = takeJson();
1033
- const result = this.admission.vote(decodeURIComponent(removalVoteMatch[1]), {
1034
- machine_id: device.machine_id, vote: body.vote,
1035
- });
1036
- if (result.ok !== true) throw new ProtocolError('BAD_REQUEST', 'vote refused: ' + result.code, result);
1037
- return sendJson(res, 200, { protocol_version: PROTOCOL_VERSION, rabbit_time: this.state.nowIso(), ...result });
1038
- }
1039
-
1040
- throw new ProtocolError('NOT_FOUND', `no route for ${method} ${path}`, { method, path });
1041
- }
1042
-
1043
- /** §4: the operations answer — "is the relay there, did it restart, are my machines connected". */
1044
- healthBody(req) {
1045
- return {
1046
- ...this.state.stats(),
1047
- // v0.3.9: how many machines currently have a live P2P announcement. Ephemeral,
1048
- // so this drops to 0 by itself when nobody is refreshing.
1049
- ...this.peers.stats(),
1050
- ok: true,
1051
- /**
1052
- * v0.6.2: hoisted out of `persistence` so it cannot be missed by a reader that only looks at
1053
- * the top level. `degraded: true` means this relay is answering requests while failing to record
1054
- * them -- the one relay failure that presents as health. `ok` deliberately stays true: the relay
1055
- * still serves the fleet, and flipping it would turn a recording problem into an outage.
1056
- */
1057
- degraded: this.persistence.enabled && this.persistence.degraded,
1058
- degraded_reason: this.persistence.degraded
1059
- ? `ledger appends are failing (${this.persistence.lastAppendError ?? 'unknown error'}); results are served but not durably recorded`
1060
- : null,
1061
- protocol_version: PROTOCOL_VERSION,
1062
- rabbit_time: this.state.nowIso(),
1063
- uptime_ms: this.state.nowMs() - this._startedAtMs,
1064
- relay_id: this.relayId,
1065
- started_at: rfc3339(this._startedAtMs),
1066
- effective_scheme: this.effectiveScheme(req),
1067
- base_path: this.basePath,
1068
- operator_token_required: this.operatorTokenRequired,
1069
- pair_rate_limit: this.pairRateLimitPerMinute,
1070
- // v0.3.0: fleet-wide latency. Every numeric field is null (never 0) when no
1071
- // machine has reported a FRESH measurement.
1072
- rtt: this.state.rttSummary(),
1073
- // v0.3.0 §9: signature status only — never the secret, not even a prefix.
1074
- signing: {
1075
- configured: this.signingConfigured,
1076
- required: this.requireSignature,
1077
- previous_secret_accepted: this.signingSecrets.length > 1,
1078
- skew_seconds: this.signatureSkewSeconds,
1079
- },
1080
- persistence: this.persistence.describe(),
1081
- };
1082
- }
1083
-
1084
- /* ---------------- request signing (v0.3.0 §9) ---------------- */
1085
-
1086
- /**
1087
- * Should this request be signature-checked at all?
1088
- *
1089
- * RULING (see PROTOCOL-v0.3.0.md §9.4): every WRITE is checked; READS are
1090
- * checked only when `--require-signature` is on.
1091
- *
1092
- * Reads are not checked in the default modes because unsigned reads are
1093
- * accepted anyway, so "verify when a signature happens to be present" would be
1094
- * theatre -- an attacker simply omits the headers -- while adding a brand new
1095
- * way for a poll or an SSE reconnect to fail. What a read leaks is topology,
1096
- * which the device token already gates; what a write can do is change state,
1097
- * which is what replay and tampering actually threaten.
1098
- */
1099
- shouldCheckSignature(method) {
1100
- if (this.requireSignature) return true; // explicit hard mode: nothing is exempt
1101
- const isRead = method === 'GET' || method === 'HEAD' || method === 'OPTIONS';
1102
- return !isRead;
1103
- }
1104
-
1105
- /** Run `verifyRequest` and throw the mapped §7 error on rejection. */
1106
- enforceSignature(req, { method, signedPath, body }) {
1107
- if (!this.shouldCheckSignature(method)) return { skipped: true };
1108
- const decision = this.verifySignature(req, { method, signedPath, body });
1109
- if (decision.ok !== true) throw signatureError(decision);
1110
- return decision;
1111
- }
1112
-
1113
- /**
1114
- * Thin adapter over the frozen `signing.mjs` contract.
1115
- *
1116
- * `path` is the ROUTED path with the query string, NOT the raw request URL: with
1117
- * `--base-path /w2m` the same client must produce the same signature whether a
1118
- * proxy passes `/w2m/v1/result` through or strips it to `/v1/result`. The routed
1119
- * path is the only value both sides agree on in all three deployment forms, so
1120
- * clients sign `/v1/result` and never `https://host/w2m/v1/result`.
1121
- */
1122
- /**
1123
- * Verify a request's signature (v0.7.11).
1124
- *
1125
- * Two mechanisms, and the order between them is the whole design:
1126
- *
1127
- * **1. Per-device Ed25519, when the sender is a device with a stored public key.** This is the
1128
- * one that proves *which* device signed. It is tried **first** because a device key is strictly
1129
- * stronger evidence than a shared secret, and because a device that registered a key must not
1130
- * fall back to the weaker mechanism by accident.
1131
- *
1132
- * **2. HMAC over a shared secret, otherwise.** Every device that paired before v0.7.10 arrives
1133
- * here — which is every device today — and nothing about its behaviour changes.
1134
- *
1135
- * ## Why this converges with no second deployment
1136
- *
1137
- * A device that has not been updated sends no signature header, so mechanism 1 finds no key and
1138
- * mechanism 2 answers exactly as before. A device that *has* been updated sends a signature, its
1139
- * public key is on file from pairing, and it is verified with it. So a fleet updates one machine
1140
- * at a time and each machine gets the strongest mechanism available **to it** the moment it
1141
- * starts sending one — no flag, no rollout step, no coordination.
1142
- *
1143
- * ## What this deliberately does not do
1144
- *
1145
- * It does not **require** a device key. `requireSignature` still means "a signature must be
1146
- * present", and either mechanism satisfies it. Making a *device key* mandatory is a separate,
1147
- * later switch, because turning it on today would refuse all four machines at once.
1148
- */
1149
- verifySignature(req, { method, signedPath, body }) {
1150
- const viaDevice = this.verifyWithDeviceKey(req, { method, signedPath, body });
1151
- if (viaDevice !== null) return viaDevice;
1152
-
1153
- return verifyRequest({
1154
- headers: req.headers, // plain Node object; signing.mjs reads it case-insensitively
1155
- method,
1156
- path: signedPath,
1157
- body: body ?? '',
1158
- secrets: this.signingSecrets,
1159
- nonces: this.nonceCache,
1160
- nowMs: this.state.nowMs(),
1161
- skewSeconds: this.signatureSkewSeconds,
1162
- required: this.requireSignature,
1163
- });
1164
- }
1165
-
1166
- /**
1167
- * Try the per-device Ed25519 path.
1168
- *
1169
- * Returns `null` when the mechanism does not apply — no signature presented, or the signing
1170
- * machine is not a device whose public key we hold — so the caller falls through. Returns a
1171
- * decision when it *does* apply, **including when it fails**: a device that registered a key and
1172
- * then presented a bad signature must not get a second chance through the shared secret, since
1173
- * that would make the stronger mechanism optional for anyone able to produce a malformed one.
1174
- */
1175
- verifyWithDeviceKey(req, { method, signedPath, body }) {
1176
- const header = readHeader(req.headers, DEVICE_SIGNATURE_HEADER);
1177
- if (typeof header !== 'string' || header === '') return null;
1178
-
1179
- const machineId = this.machineIdForRequest(req);
1180
- if (machineId === null) return null;
1181
- const publicKey = this.state.devices.get(machineId)?.public_key;
1182
- if (typeof publicKey !== 'string' || publicKey === '') return null;
1183
-
1184
- const decision = verifyDeviceSignature({
1185
- headers: req.headers,
1186
- publicKeyPem: publicKey,
1187
- method,
1188
- path: signedPath,
1189
- body: body ?? '',
1190
- nowMs: this.state.nowMs(),
1191
- skewSeconds: this.signatureSkewSeconds,
1192
- // `accept`, not `remember` -- the name this class actually exposes. It reports whether the
1193
- // nonce was new, which is exactly the contract `verifyDeviceSignature` expects.
1194
- nonces: (nonce, at) => this.nonceCache.accept(nonce, at),
1195
- });
1196
- if (decision.ok) return { ...decision, machine_id: machineId, keyIndex: null };
1197
- return decision;
1198
- }
1199
-
1200
- /**
1201
- * Which machine a request claims to be, from either credential.
1202
- *
1203
- * An **operator token is not a machine**, so it resolves to `null` and the device path does not
1204
- * apply — consistent with `authorizeTaskDispatch`, which reports `machine_id: null` for an
1205
- * operator. That is why an operator-token request keeps using the shared secret.
1206
- */
1207
- machineIdForRequest(req) {
1208
- const token = bearerToken(req);
1209
- if (!token) return null;
1210
- if (this.operatorToken !== null && token === this.operatorToken) return null;
1211
- return this.state.authenticate(token)?.machine_id ?? null;
1212
- }
1213
-
1214
- /** Periodic maintenance, called by the sweep timer. */
1215
- maintenance() {
1216
- const expired = this.sweep();
1217
- /**
1218
- * v0.9.1: presence expiry, alongside lease expiry.
1219
- *
1220
- * `this.sweep()` writes off lease *holds*; this writes off *presence*. They were conflated, so a
1221
- * machine that stopped existing was only ever noticed when its SSE stream detached — and a
1222
- * half-open stream never detaches.
1223
- */
1224
- const silent = this.state.sweepSilentDevices();
1225
- if (silent.length > 0) {
1226
- this._log(`[w2m-rabbit] marked ${silent.length} silent device(s) offline: `
1227
- + silent.map((s) => `${s.machine_name} (${Math.round(s.silent_ms / 1000)}s)`).join(', '));
1228
- }
1229
- this.pairLimiter.prune();
1230
- this.peers.sweep();
1231
- // Keep the nonce cache from growing without bound in a long-running process.
1232
- this.nonceCache.prune(this.nonceRetentionMs, this.state.nowMs());
1233
- return expired;
1234
- }
1235
-
1236
- /* ---------------- auth helpers ---------------- */
1237
-
1238
- /** §6: every /v1/pair attempt counts, success included. */
1239
- enforcePairRateLimit(req) {
1240
- if (this.pairRateLimitPerMinute <= 0) return;
1241
- const ip = this.clientIp(req);
1242
- const verdict = this.pairLimiter.hit(ip);
1243
- if (verdict.allowed) return;
1244
- const err = new ProtocolError(
1245
- 'RATE_LIMITED',
1246
- `too many /v1/pair attempts from ${ip}: limit is ${verdict.limit} per ${verdict.window_seconds}s`,
1247
- {
1248
- retry_after_seconds: verdict.retry_after_seconds,
1249
- limit: verdict.limit,
1250
- window_seconds: verdict.window_seconds,
1251
- scope: 'pair',
1252
- },
1253
- );
1254
- err.headers = { 'retry-after': String(verdict.retry_after_seconds) };
1255
- throw err;
1256
- }
1257
-
1258
- /**
1259
- * §5: `POST /v1/task` needs the operator token.
1260
- * - required (default): operator token, else 401 OPERATOR_REQUIRED
1261
- * - disabled (`--operator-token ''`): falls back to v1 semantics, i.e. a paired device token
1262
- */
1263
- authorizeTaskDispatch(req) {
1264
- const token = bearerToken(req);
1265
- if (this.operatorTokenRequired) {
1266
- if (!token) {
1267
- throw new ProtocolError(
1268
- 'OPERATOR_REQUIRED',
1269
- 'POST /v1/task requires the operator token. A device_token is machine credentials and cannot '
1270
- + `dispatch tasks; read the operator token from ${this.persistence.operatorTokenFile ?? '<state>/operator-token.txt'} `
1271
- + 'or pass --operator-token / W2M_OPERATOR_TOKEN.',
1272
- { operator_token_file: this.persistence.operatorTokenFile ?? null },
1273
- );
1274
- }
1275
- if (token !== this.operatorToken) {
1276
- const asDevice = this.state.authenticate(token);
1277
- throw new ProtocolError(
1278
- 'OPERATOR_REQUIRED',
1279
- asDevice
1280
- ? 'this is a device_token (machine credentials); dispatching tasks requires the operator_token — '
1281
- + 'they are two different credentials'
1282
- : 'invalid operator token: it does not match the relay operator token',
1283
- {
1284
- device_token_detected: Boolean(asDevice),
1285
- machine_id: asDevice?.machine_id ?? null,
1286
- operator_token_file: this.persistence.operatorTokenFile ?? null,
1287
- },
1288
- );
1289
- }
1290
- return { role: 'operator', machine_id: null };
1291
- }
1292
- const device = token ? this.state.authenticate(token) : null;
1293
- if (!device) {
1294
- throw new ProtocolError(
1295
- 'UNAUTHORIZED',
1296
- 'the operator token requirement is disabled on this relay, but /v1/task still requires a valid device_token',
1297
- {},
1298
- );
1299
- }
1300
- return { role: 'device', machine_id: device.machine_id };
1301
- }
1302
-
1303
- /* ---------------- SSE (§3) ---------------- */
1304
-
1305
- handleStream(req, res, url, device) {
1306
- const machineId = device.machine_id;
1307
- const requested = url.searchParams.get('machine_id');
1308
- if (requested !== null && requested !== machineId) {
1309
- throw new ProtocolError('BAD_REQUEST', 'machine_id does not match the device_token', {
1310
- machine_id: requested, token_machine_id: machineId,
1311
- });
1312
- }
1313
-
1314
- let from = null;
1315
- const seqParam = url.searchParams.get('seq');
1316
- const lastEventId = req.headers['last-event-id'];
1317
- if (seqParam !== null) {
1318
- from = Number(seqParam);
1319
- if (!Number.isInteger(from) || from < 1) {
1320
- throw new ProtocolError('BAD_REQUEST', 'seq must be a positive integer', { seq: seqParam });
1321
- }
1322
- } else if (typeof lastEventId === 'string' && lastEventId.trim() !== '') {
1323
- const last = Number(lastEventId);
1324
- if (!Number.isInteger(last) || last < 0) {
1325
- throw new ProtocolError('BAD_REQUEST', 'Last-Event-ID must be a non-negative integer', { last_event_id: lastEventId });
1326
- }
1327
- from = last + 1;
1328
- }
1329
-
1330
- // §8.5: these two headers are the fix for "connects but no events" behind
1331
- // nginx-style proxies and tunnels, which buffer event streams by default.
1332
- res.writeHead(200, {
1333
- 'content-type': 'text/event-stream; charset=utf-8',
1334
- 'cache-control': 'no-cache, no-transform',
1335
- connection: 'keep-alive',
1336
- 'x-accel-buffering': 'no',
1337
- });
1338
- if (typeof res.flushHeaders === 'function') res.flushHeaders();
1339
-
1340
- const sub = { machineId, res, write: null, timer: null, closed: false };
1341
-
1342
- const writeEvent = (event) => {
1343
- if (res.writableEnded) return;
1344
- res.write(`id: ${event.seq}\nevent: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`);
1345
- };
1346
-
1347
- let live = false;
1348
- const queue = [];
1349
- const deliver = (entry) => {
1350
- if (entry.target && entry.target !== machineId) return;
1351
- writeEvent(entry.event);
1352
- };
1353
- const unsubscribe = this.state.onEvent((entry) => {
1354
- if (!live) { queue.push(entry); return; }
1355
- deliver(entry);
1356
- });
1357
-
1358
- // §3.1: the first frame MUST be `ready`; §8.3 adds `relay_id`.
1359
- const readySeq = this.state.reserveSeq();
1360
- writeEvent({
1361
- type: 'ready',
1362
- seq: readySeq,
1363
- protocol_version: PROTOCOL_VERSION,
1364
- rabbit_time: this.state.nowIso(),
1365
- machine_id: machineId,
1366
- relay_id: this.relayId,
1367
- });
1368
-
1369
- if (from !== null) {
1370
- const oldest = this.state.oldestBufferedSeq();
1371
- const lastBuffered = this.state.lastBufferedSeq();
1372
- // `fromFuture` is judged against EVERY seq this process has allocated (a client
1373
- // can legitimately hold a `ready` seq, which is not buffered), while the
1374
- // reported window bounds describe the replay ring the client can actually use.
1375
- const lastSeq = this.state.lastSeq();
1376
- // Two distinct ways for a cursor to be out of sync with THIS process:
1377
- //
1378
- // from < oldest the cursor is older than the replay window (buffer rot)
1379
- // from > lastSeq+1 the cursor cannot exist here at all. Sequence numbers
1380
- // restart at 1 in every process, so a cursor from a
1381
- // previous relay process is AHEAD of a freshly started
1382
- // relay. This was the silent case: `13 < 1` is false, the
1383
- // client got no notice, `replayEntries(13)` matched
1384
- // nothing, and the agent then reset its cursor to the
1385
- // `ready` seq -- stepping over every event it had missed.
1386
- const tooOld = from < oldest && oldest > 1;
1387
- const fromFuture = from > lastSeq + 1;
1388
- if (tooOld || fromFuture) {
1389
- // §8.4: tell the client where to re-align, not just that replay failed.
1390
- writeEvent({
1391
- type: 'notice',
1392
- seq: this.state.reserveSeq(),
1393
- rabbit_time: this.state.nowIso(),
1394
- level: 'warn',
1395
- code: 'REPLAY_TRUNCATED',
1396
- message: tooOld
1397
- ? `requested seq ${from} is older than the buffer head ${oldest}`
1398
- : `requested seq ${from} is beyond this process' last seq ${lastSeq}: the cursor came from a `
1399
- + 'previous relay process, whose sequence numbering restarted at 1',
1400
- machine_id: machineId,
1401
- requested_seq: from,
1402
- oldest_available_seq: oldest,
1403
- last_available_seq: lastBuffered,
1404
- relay_id: this.relayId,
1405
- reason: tooOld ? 'buffer_truncated' : 'cursor_ahead_of_relay',
1406
- });
1407
- }
1408
- // A cursor from a previous process is meaningless here, so honouring it
1409
- // literally (replay from `from`) would deliver NOTHING and also lose every
1410
- // event that fell into the gap -- not only offers, but `task.cancel`,
1411
- // `notice`, `peer.*`. Re-align to the head of the window instead: the client
1412
- // asked to be resynchronised, and the ring is exactly what we still have.
1413
- const replayFrom = fromFuture ? oldest : from;
1414
- for (const entry of this.state.replayEntries(replayFrom)) deliver(entry);
1415
- }
1416
-
1417
- live = true;
1418
- for (const entry of queue) deliver(entry);
1419
- queue.length = 0;
1420
-
1421
- // §8.6: re-state work this machine was handed while its stream was down.
1422
- //
1423
- // An offer is a single event; if the stream is not connected at that instant
1424
- // -- after a relay restart, a tunnel drop, or any interruption -- the event
1425
- // is lost and the lease waits out its whole window before being swept. The
1426
- // machine is meanwhile online and idle. Re-delivering on connect is what
1427
- // makes a reconnect recover work instead of silently losing it.
1428
- //
1429
- // Only unclaimed leases are re-offered; `running` is excluded so a task that
1430
- // has already begun cannot be handed out a second time and executed twice.
1431
- const redelivered = this.state.redeliverPendingOffers(machineId);
1432
- if (redelivered.count > 0) {
1433
- this._log(`[w2m-rabbit] re-offered ${redelivered.count} pending task(s) to ${machineId} on reconnect`);
1434
- }
1435
-
1436
- // §3.2: `: keepalive` comment every 15s.
1437
- sub.timer = setInterval(() => {
1438
- if (res.writableEnded) return;
1439
- res.write(': keepalive\n\n');
1440
- }, this.keepaliveMs);
1441
- sub.timer.unref?.();
1442
-
1443
- sub.write = writeEvent;
1444
- sub.unsubscribe = unsubscribe;
1445
- this.subscribers.add(sub);
1446
- device.streams = (device.streams ?? 0) + 1;
1447
- // v0.3.0: relay-observed reconnect counter. A first attach is not a reconnect,
1448
- // so the reported `reconnect_attempts` is (attaches - 1).
1449
- this.state.noteStreamConnect(machineId);
1450
-
1451
- const onClose = () => this._closeSubscriber(sub);
1452
- req.on('close', onClose);
1453
- res.on('close', onClose);
1454
- res.on('error', onClose);
1455
- return undefined;
1456
- }
1457
-
1458
- _closeSubscriber(sub) {
1459
- if (!sub || sub.closed) return;
1460
- sub.closed = true;
1461
- this.subscribers.delete(sub);
1462
- if (sub.timer) clearInterval(sub.timer);
1463
- sub.timer = null;
1464
- sub.unsubscribe?.();
1465
- const device = this.state.devices.get(sub.machineId);
1466
- if (device) {
1467
- device.streams = Math.max(0, (device.streams ?? 1) - 1);
1468
- if (device.streams === 0) this.state.setOnline(sub.machineId, false, 'stream_closed');
1469
- }
1470
- if (!sub.res.writableEnded) {
1471
- try { sub.res.end(); } catch { /* already gone */ }
1472
- }
1473
- }
1474
- }
1475
-
1476
- /** Convenience factory. */
1477
- export function createRelayServer(options = {}) {
1478
- return new RelayServer(options);
1479
- }
1480
-
1481
- /** Create + listen in one call. */
1482
- export async function startRelayServer(options = {}) {
1483
- const relay = createRelayServer(options);
1484
- await relay.listen(options);
1485
- return relay;
1486
- }
1487
-
1488
- export {
1489
- Persistence,
1490
- ProtocolError,
1491
- RabbitState,
1492
- MAX_FRAME_BYTES,
1493
- PROTOCOL_VERSION,
1494
- rfc3339,
1495
- };
1496
- export default createRelayServer;
1
+ /**
2
+ * W2M Rabbit relay — node:http / node:https server.
3
+ *
4
+ * PROTOCOL.md §1 endpoints, §3 SSE, §7 errors
5
+ * PROTOCOL-v0.1.2.md §3 deployment params, §4 /healthz, §5 operator token,
6
+ * §6 pair rate limit, §7 persistence, §8 SSE hardening.
7
+ *
8
+ * Zero third-party dependencies: only `node:` builtins.
9
+ */
10
+
11
+ import http from 'node:http';
12
+ import https from 'node:https';
13
+ import fs from 'node:fs';
14
+ import os from 'node:os';
15
+ import path from 'node:path';
16
+ import { createHash, randomBytes } from 'node:crypto';
17
+
18
+ import {
19
+ MAX_FRAME_BYTES,
20
+ PROTOCOL_VERSION,
21
+ ProtocolError,
22
+ RabbitState,
23
+ rfc3339,
24
+ } from './state.mjs';
25
+ import { createJoinChallenges } from './join-challenge.mjs';
26
+ import { createAdmission } from './admission.mjs';
27
+ import { Persistence } from './persistence.mjs';
28
+ import { PeerRegistry } from './peers.mjs';
29
+ import { aggregateTask, buildReport } from './report.mjs';
30
+ import { renderMetrics, METRICS_CONTENT_TYPE } from './metrics.mjs';
31
+ // v0.3.0 §9: request signing. This import is the entire point of the module --
32
+ // until the HTTP layer calls it, HMAC support does not exist for any real request.
33
+ import { DEFAULT_SKEW_SECONDS, NonceCache, verifyRequest } from '../signing.mjs';
34
+ // v0.7.11: per-device Ed25519 verification, tried before the shared secret.
35
+ import {
36
+ SIGNATURE_HEADER as DEVICE_SIGNATURE_HEADER,
37
+ verifyDeviceSignature,
38
+ } from '../chatops/device-signing.mjs';
39
+
40
+ export const DEFAULT_SSE_KEEPALIVE_MS = 15_000; // §3.2: every 15s a `: keepalive` line
41
+ export const DEFAULT_SWEEP_INTERVAL_MS = 1_000;
42
+ export const DEFAULT_PAIR_RATE_LIMIT_PER_MINUTE = 5; // v0.1.2 §6
43
+ // The window length is a unit and lives with the limiter. Both names are kept: `DEFAULT_WINDOW_MS` is the
44
+ // local binding this module uses, and `RATE_LIMIT_WINDOW_MS` is the name this module has always exported.
45
+ // `export ... from` would NOT have worked here -- it re-exports without creating a local binding, so the
46
+ // constructor below saw `RATE_LIMIT_WINDOW_MS is not defined` while the export itself looked fine.
47
+ import { DEFAULT_WINDOW_MS, SlidingWindowRateLimiter } from '../util/rate-limit.mjs';
48
+ export { DEFAULT_WINDOW_MS as RATE_LIMIT_WINDOW_MS };
49
+ export const DEFAULT_STATE_DIR = path.join(os.homedir(), '.w2m');
50
+
51
+ /**
52
+ * The environment variable that opts in to printing the operator token on a start that did not
53
+ * generate it (MEDIUM-6 of the v0.5.9 review).
54
+ *
55
+ * The value is printed **once, on the start that generated it**, because that is the only moment at
56
+ * which it exists nowhere else yet; every other start has `<state>/operator-token.txt` to read it
57
+ * from, and a relay's stdout ends up in journald, a container log or a CI transcript — where a
58
+ * credential that authorises dispatching to the whole fleet does not belong. `W2M_PRINT_OPERATOR_TOKEN=1`
59
+ * (or `printOperatorToken: true`, which is the same switch for an embedder) restores the old
60
+ * behaviour for an operator who genuinely needs it in the log, and says so in the banner when it does.
61
+ */
62
+ export const PRINT_OPERATOR_TOKEN_ENV = 'W2M_PRINT_OPERATOR_TOKEN';
63
+
64
+ /**
65
+ * Resolve that opt-in, so the relay and the CLI agree on one answer.
66
+ *
67
+ * @param {object} [options] Relay options; `printOperatorToken: true` is the programmatic spelling.
68
+ * @returns {'option'|'env'|null} Why printing was asked for, or null.
69
+ */
70
+ export function printOperatorTokenOptIn(options = {}) {
71
+ if (options.printOperatorToken === true) return 'option';
72
+ const raw = process.env[PRINT_OPERATOR_TOKEN_ENV];
73
+ if (raw === '1' || raw === 'true') return 'env';
74
+ return null;
75
+ }
76
+
77
+ /* ------------------------------------------------------------------ */
78
+ /* helpers */
79
+ /* ------------------------------------------------------------------ */
80
+
81
+ /** v0.1.2 §3: `/w2m/` → `/w2m`; '' / '/' → '/'. Never returns a trailing slash. */
82
+ export function normalizeBasePath(value) {
83
+ if (value === undefined || value === null || value === '') return '/';
84
+ let p = String(value).trim();
85
+ if (p === '' || p === '/') return '/';
86
+ if (!p.startsWith('/')) p = `/${p}`;
87
+ p = p.replace(/\/{2,}/g, '/').replace(/\/+$/, '');
88
+ return p === '' ? '/' : p;
89
+ }
90
+
91
+ function normalizePath(pathname) {
92
+ if (!pathname) return '/';
93
+ return pathname.length > 1 ? pathname.replace(/\/+$/, '') : pathname;
94
+ }
95
+
96
+ function sendJson(res, status, body, extraHeaders = {}) {
97
+ if (res.writableEnded) return undefined;
98
+ const payload = Buffer.from(JSON.stringify(body), 'utf8');
99
+ res.writeHead(status, {
100
+ 'content-type': 'application/json; charset=utf-8',
101
+ 'content-length': payload.length,
102
+ 'cache-control': 'no-store',
103
+ ...extraHeaders,
104
+ });
105
+ return res.end(payload);
106
+ }
107
+
108
+ function sendError(res, err) {
109
+ if (err instanceof ProtocolError) {
110
+ const body = err.toBody();
111
+ // §6 just says the 429 "carries retry_after_seconds" without pinning the
112
+ // location, so it is emitted both inside error.detail (the §7 shape) and as a
113
+ // top-level convenience field. Both are additive.
114
+ const retryAfter = err.detail?.retry_after_seconds;
115
+ if (typeof retryAfter === 'number') body.retry_after_seconds = retryAfter;
116
+ sendJson(res, err.status, body, err.headers ?? {});
117
+ return;
118
+ }
119
+ sendJson(res, 500, {
120
+ error: {
121
+ code: 'INTERNAL',
122
+ message: err?.message ? String(err.message) : 'internal error',
123
+ detail: {},
124
+ },
125
+ });
126
+ }
127
+
128
+ function bearerToken(req) {
129
+ const header = req.headers.authorization;
130
+ if (typeof header !== 'string') return null;
131
+ const m = /^Bearer\s+(.+)$/i.exec(header.trim());
132
+ return m ? m[1].trim() : null;
133
+ }
134
+
135
+ function firstHeaderValue(value) {
136
+ const raw = Array.isArray(value) ? value[0] : value;
137
+ if (typeof raw !== 'string') return null;
138
+ const first = raw.split(',')[0].trim();
139
+ return first === '' ? null : first;
140
+ }
141
+
142
+ /**
143
+ * Read one header case-insensitively from a plain Node headers object.
144
+ *
145
+ * `signing.mjs` does this internally, but the device-key path needs it before deciding whether that
146
+ * module applies at all, so it is needed here too. Node lower-cases incoming header names, and a
147
+ * test that builds a request by hand may not, so both spellings are tried.
148
+ */
149
+ function readHeader(headers, name) {
150
+ if (headers === null || headers === undefined) return null;
151
+ const found = Object.keys(headers).find((k) => k.toLowerCase() === name);
152
+ return found === undefined ? null : firstHeaderValue(headers[found]);
153
+ }
154
+
155
+ /**
156
+ * Read a request body with a hard byte cap.
157
+ * @returns {Promise<{tooLarge?:boolean, buffer?:Buffer, aborted?:boolean}>}
158
+ */
159
+ function readBody(req, limit) {
160
+ return new Promise((resolve) => {
161
+ const declared = Number(req.headers['content-length']);
162
+ if (Number.isFinite(declared) && declared > limit) {
163
+ req.resume();
164
+ resolve({ tooLarge: true });
165
+ return;
166
+ }
167
+ const chunks = [];
168
+ let total = 0;
169
+ let settled = false;
170
+ const finish = (value) => {
171
+ if (settled) return;
172
+ settled = true;
173
+ resolve(value);
174
+ };
175
+ req.on('data', (chunk) => {
176
+ if (settled) return;
177
+ total += chunk.length;
178
+ if (total > limit) {
179
+ finish({ tooLarge: true });
180
+ req.resume();
181
+ return;
182
+ }
183
+ chunks.push(chunk);
184
+ });
185
+ req.on('end', () => finish({ buffer: Buffer.concat(chunks) }));
186
+ req.on('error', () => finish({ aborted: true }));
187
+ req.on('aborted', () => finish({ aborted: true }));
188
+ });
189
+ }
190
+
191
+ /**
192
+ * Read the raw body bytes with a hard byte cap.
193
+ *
194
+ * v0.3.0 §9: the body is read exactly ONCE per request and the bytes are kept,
195
+ * because an HMAC covers the exact received octets -- re-serialising parsed JSON
196
+ * would produce different bytes (key order, whitespace) and break every signature.
197
+ */
198
+ async function readRawBody(req, limit) {
199
+ const body = await readBody(req, limit);
200
+ if (body.tooLarge) {
201
+ throw new ProtocolError('FRAME_TOO_LARGE', `request frame exceeds ${limit} bytes`, { limit_bytes: limit });
202
+ }
203
+ if (body.aborted) throw new ProtocolError('BAD_REQUEST', 'request aborted before the body was complete');
204
+ return body.buffer;
205
+ }
206
+
207
+ /** Parse an already-read body buffer as a JSON object. */
208
+ function parseJsonBody(buffer) {
209
+ const raw = buffer === null || buffer === undefined ? '' : buffer.toString('utf8');
210
+ if (raw.trim() === '') return {};
211
+ try {
212
+ const parsed = JSON.parse(raw);
213
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
214
+ throw new ProtocolError('BAD_REQUEST', 'request body must be a JSON object');
215
+ }
216
+ return parsed;
217
+ } catch (err) {
218
+ if (err instanceof ProtocolError) throw err;
219
+ throw new ProtocolError('BAD_REQUEST', 'request body is not valid JSON', { parse_error: String(err.message) });
220
+ }
221
+ }
222
+
223
+ /** Methods that can carry a body the signature must cover. */
224
+ function methodHasBody(method) {
225
+ return method === 'POST' || method === 'PUT' || method === 'PATCH' || method === 'DELETE';
226
+ }
227
+
228
+ /* ------------------------------------------------------------------ */
229
+ /* request signing (v0.3.0 §9) */
230
+ /* ------------------------------------------------------------------ */
231
+
232
+ /**
233
+ * Operator-facing hints. The `code` says what happened; the hint says what to do
234
+ * about it, because "signature mismatch" without a direction is a support ticket.
235
+ */
236
+ const SIGNATURE_HINTS = Object.freeze({
237
+ SIGNATURE_REQUIRED: 'this relay runs with --require-signature; sign the request (PROTOCOL-v0.3.0.md §9)',
238
+ SIGNATURE_INCOMPLETE: 'all three of X-W2M-Signature, X-W2M-Timestamp and X-W2M-Nonce must be present together',
239
+ SIGNATURE_MISMATCH: 'the signature matches no configured secret — check for a stale or half-rotated secret',
240
+ SIGNATURE_EXPIRED: 'the timestamp is outside the accepted clock-skew window — check the sending machine clock',
241
+ SIGNATURE_REPLAY: 'this nonce was already used — generate a fresh nonce for every request',
242
+ SIGNATURE_BAD_TIMESTAMP: 'X-W2M-Timestamp must be whole unix seconds',
243
+ SIGNATURE_BAD_NONCE: 'X-W2M-Nonce must be at least 8 characters',
244
+ SIGNING_NOT_CONFIGURED:
245
+ 'the relay has --require-signature enabled but no --signing-secret configured; '
246
+ + 'this is a RELAY configuration error, not a client problem',
247
+ });
248
+
249
+ const SIGNATURE_PROTOCOL_CODES = new Set(Object.keys(SIGNATURE_HINTS));
250
+
251
+ /** Turn a `verifyRequest` rejection into the §7 error envelope.
252
+ * `ProtocolError` resolves the HTTP status from `ERROR_STATUS`, so the mapping
253
+ * table lives in exactly one place (state.mjs) instead of being duplicated here. */
254
+ function signatureError(decision) {
255
+ const code = SIGNATURE_PROTOCOL_CODES.has(decision.code) ? decision.code : 'SIGNATURE_MISMATCH';
256
+ return new ProtocolError(code, decision.error, {
257
+ code,
258
+ reason: decision.error,
259
+ hint: SIGNATURE_HINTS[code] ?? null,
260
+ });
261
+ }
262
+
263
+ /**
264
+ * Read an optional secret, failing loudly on a value that is present but unusable.
265
+ *
266
+ * `signing.mjs` calls a silently-disabled secret the failure mode it exists to
267
+ * prevent. Treating `signingSecret: 12345` (or `{}`) as "not configured" would do
268
+ * exactly that at the wiring layer, so it is an error instead.
269
+ */
270
+ function readSecretValue(value, label) {
271
+ if (value === undefined || value === null || value === '') return null;
272
+ if (typeof value !== 'string') {
273
+ throw new ProtocolError('BAD_REQUEST',
274
+ `${label} must be a non-empty string when provided (got ${typeof value}); `
275
+ + 'refusing to silently run without the signing you asked for', { option: label, received_type: typeof value });
276
+ }
277
+ return value;
278
+ }
279
+
280
+ /* ------------------------------------------------------------------ */
281
+ /* pair rate limiting (v0.1.2 §6) */
282
+ /* ------------------------------------------------------------------ */
283
+
284
+ /**
285
+ * Per-IP sliding window. Successful pairs count too, otherwise a working pairing
286
+ * code could be used to flush the failure budget.
287
+ */
288
+ /*
289
+ * The limiter MOVED to `src/util/rate-limit.mjs` in v0.30.0.
290
+ *
291
+ * It never used anything from this file, and when the approval gate needed the same window, importing it
292
+ * from here made an `agent` module depend on the `relay` layer -- which `scripts/layer-model.mjs` refused,
293
+ * correctly. `agent` is rank 2 and `relay` is rank 3, so the edge points up; moving the class to `util`
294
+ * (rank 0, a leaf) lets both depend on it in the only direction the model allows.
295
+ *
296
+ * Re-exported rather than merely imported, because `SlidingWindowRateLimiter` and `RATE_LIMIT_WINDOW_MS` are
297
+ * part of this module's published surface and `test/relay.test.mjs` imports the class from here.
298
+ */
299
+ export { SlidingWindowRateLimiter };
300
+
301
+ /* ------------------------------------------------------------------ */
302
+ /* server */
303
+ /* ------------------------------------------------------------------ */
304
+
305
+ export class RelayServer {
306
+ constructor(options = {}) {
307
+ this.options = options;
308
+ this.basePath = normalizeBasePath(options.basePath);
309
+ this.trustProxy = options.trustProxy === true;
310
+ this.frameLimitBytes = options.frameLimitBytes ?? MAX_FRAME_BYTES;
311
+ this.keepaliveMs = options.keepaliveMs ?? DEFAULT_SSE_KEEPALIVE_MS;
312
+ this.sweepIntervalMs = options.sweepIntervalMs ?? DEFAULT_SWEEP_INTERVAL_MS;
313
+ this.pairRateLimitPerMinute = Number.isFinite(options.pairRateLimitPerMinute)
314
+ ? options.pairRateLimitPerMinute : DEFAULT_PAIR_RATE_LIMIT_PER_MINUTE;
315
+
316
+ // §3: `logger: null` silences. The default writes to STDERR on purpose —
317
+ // stdout belongs to protocol output (e.g. the CLI's `--json` line), and mixing
318
+ // prose into it breaks `| ConvertFrom-Json` / `| jq`.
319
+ this.logger = options.logger === undefined
320
+ ? ((msg) => process.stderr.write(`${msg}\n`))
321
+ : options.logger;
322
+ this.startupMessages = [];
323
+
324
+ /* ---- persistence (§7) ---- */
325
+ const rawStateDir = options.stateDir ?? (typeof options.state === 'string' ? options.state : null);
326
+ const persistEnabled = options.persist !== false && rawStateDir !== '';
327
+ const stateDir = persistEnabled
328
+ ? path.resolve(rawStateDir === null || rawStateDir === undefined ? DEFAULT_STATE_DIR : String(rawStateDir))
329
+ : null;
330
+ this.persistence = new Persistence({
331
+ dir: stateDir,
332
+ now: () => (this.state ? this.state.nowMs() : Date.now()),
333
+ });
334
+
335
+ /* ---- state ---- */
336
+ const injected = options.state && typeof options.state === 'object' ? options.state : null;
337
+ this.state = injected ?? new RabbitState({ ...options, persistence: this.persistence });
338
+ this.state.setPersistence(this.persistence);
339
+
340
+ // v0.3.9: P2P signalling. Ephemeral by design -- see src/relay/peers.mjs.
341
+ this.peers = options.peers ?? new PeerRegistry({ nowMs: () => this.state.nowMs() });
342
+
343
+ this.relayId = this.state.relayId;
344
+ this._startedAtMs = this.state.nowMs();
345
+
346
+ /* ---- startup recovery (§7) ---- */
347
+ if (this.persistence.enabled) {
348
+ const snapshot = this.persistence.loadDevices();
349
+ this.persistence.devicesMissing = snapshot.missing;
350
+ const ledger = this.persistence.loadLedger();
351
+ const revived = this.state.restore({ devices: snapshot.devices, ledger });
352
+ this.persistence.revivedDevices = revived.revived_devices;
353
+ this.persistence.revivedTasks = revived.revived_tasks;
354
+ }
355
+
356
+ /* ---- operator token (§5) ---- */
357
+ this._initOperatorToken(options);
358
+
359
+ /* ---- v0.3.0 §9 request signing ---- */
360
+ this.signingSecrets = [
361
+ readSecretValue(options.signingSecret, 'signingSecret'),
362
+ readSecretValue(options.signingSecretPrevious, 'signingSecretPrevious'),
363
+ ].filter((s) => s !== null); // newest first: keyIndex 0 = current, 1 = previous
364
+ this.signingConfigured = this.signingSecrets.length > 0;
365
+ this.requireSignature = options.requireSignature === true;
366
+ /**
367
+ * v0.3.3: whether `GET /metrics` exists.
368
+ *
369
+ * Defaults to off. A monitoring endpoint that appears without being asked for is a surface nobody
370
+ * chose, and the operator can turn it on with `--metrics` when a scraper exists.
371
+ */
372
+ this.metricsEnabled = options.metrics === true;
373
+ this.signatureSkewSeconds = Number.isFinite(options.signatureSkewSeconds)
374
+ ? options.signatureSkewSeconds : DEFAULT_SKEW_SECONDS;
375
+ // One cache per relay instance: replay defence is stateful, and two relays
376
+ // sharing a cache would let a nonce blocked on one be replayed on the other.
377
+ this.nonceCache = options.nonceCache ?? new NonceCache({
378
+ max: options.nonceCacheMax ?? 20_000,
379
+ retentionMs: options.nonceCacheRetentionMs ?? 10 * 60_000,
380
+ });
381
+ this.nonceRetentionMs = options.nonceCacheRetentionMs ?? 10 * 60_000;
382
+
383
+ /* ---- /v1/pair rate limit (§6) ---- */
384
+ this.pairLimiter = new SlidingWindowRateLimiter({
385
+ limit: this.pairRateLimitPerMinute,
386
+ windowMs: DEFAULT_WINDOW_MS,
387
+ now: () => this.state.nowMs(),
388
+ });
389
+
390
+ /* ---- transport ---- */
391
+ this.tlsCertPath = options.tlsCert ?? null;
392
+ this.tlsKeyPath = options.tlsKey ?? null;
393
+ if ((this.tlsCertPath && !this.tlsKeyPath) || (!this.tlsCertPath && this.tlsKeyPath)) {
394
+ throw new ProtocolError('BAD_REQUEST', 'tlsCert and tlsKey must be provided together', {
395
+ tls_cert: this.tlsCertPath, tls_key: this.tlsKeyPath,
396
+ });
397
+ }
398
+ const handler = (req, res) => {
399
+ this.handle(req, res).catch((err) => this.reportError(req, res, err));
400
+ };
401
+ if (this.tlsCertPath) {
402
+ let cert;
403
+ let key;
404
+ try {
405
+ cert = fs.readFileSync(this.tlsCertPath);
406
+ key = fs.readFileSync(this.tlsKeyPath);
407
+ } catch (err) {
408
+ // Never silently fall back to plain HTTP: that would be a security downgrade.
409
+ throw new ProtocolError('BAD_REQUEST', `cannot read TLS material: ${err.message}`, {
410
+ tls_cert: this.tlsCertPath, tls_key: this.tlsKeyPath,
411
+ });
412
+ }
413
+ this.server = https.createServer({ cert, key }, handler);
414
+ this.scheme = 'https';
415
+ } else {
416
+ this.server = http.createServer(handler);
417
+ this.scheme = 'http';
418
+ }
419
+
420
+ // v0.1.2 BUG-1: an externally supplied code must be REGISTERED, not merely
421
+ // assigned — otherwise the banner advertises a code /v1/pair does not know.
422
+ this.pairingCode = typeof options.pairingCode === 'string' && options.pairingCode.trim() !== ''
423
+ ? this.state.registerPairingCode(options.pairingCode, { ttlMs: options.pairingCodeTtlMs })
424
+ : this.state.createPairingCode();
425
+ this.subscribers = new Set();
426
+ this.host = null;
427
+ this.port = null;
428
+ this._sweepTimer = null;
429
+
430
+ // SSE connections are long-lived: never let Node time the request out.
431
+ this.server.requestTimeout = options.requestTimeoutMs ?? 0;
432
+ this.server.headersTimeout = options.headersTimeoutMs ?? 60_000;
433
+
434
+ this._buildStartupMessages();
435
+ }
436
+
437
+ /**
438
+ * Diagnostics sink. `logger: null` is the documented "silent" value, and a
439
+ * caller-supplied logger may throw — neither may break a request. (A direct
440
+ * `this.logger(...)` call after `res.writeHead()` once threw a TypeError that
441
+ * surfaced as "Cannot write headers after they are sent to the client".)
442
+ */
443
+ _log(message) {
444
+ if (typeof this.logger !== 'function') return;
445
+ try {
446
+ this.logger(message);
447
+ } catch { /* a broken logger must never break the relay */ }
448
+ }
449
+
450
+ /**
451
+ * Last-resort error path for a request whose handler rejected.
452
+ * Once the status line is on the wire (SSE, streamed report) the response can no
453
+ * longer be rewritten — the only honest action is to end the stream, loudly.
454
+ */
455
+ reportError(req, res, err) {
456
+ if (res.headersSent) {
457
+ this._log(`[w2m-rabbit] !! error after the response had started on ${req.method} ${req.url}: `
458
+ + `${err?.stack ?? err}`);
459
+ try { res.end(); } catch { /* already gone */ }
460
+ return;
461
+ }
462
+ sendError(res, err);
463
+ }
464
+
465
+ _initOperatorToken(options) {
466
+ const wantsRequired = options.operatorTokenRequired !== false;
467
+ const explicit = options.operatorToken;
468
+ const persisted = this.persistence.enabled ? this.persistence.readOperatorToken() : null;
469
+ /**
470
+ * Why the token may be printed, when it may be: `'generated'` is the one start whose token exists
471
+ * nowhere else until this process writes it, and `'option'`/`'env'` are the documented opt-ins.
472
+ * @type {'generated'|'option'|'env'|null}
473
+ */
474
+ this.operatorTokenPrintReason = printOperatorTokenOptIn(options);
475
+
476
+ if (!wantsRequired || explicit === '') {
477
+ this.operatorToken = null;
478
+ this.operatorTokenRequired = false;
479
+ this.operatorTokenSource = 'disabled';
480
+ this.operatorTokenPrintable = false;
481
+ this.operatorTokenPrintReason = null;
482
+ return;
483
+ }
484
+ this.operatorTokenRequired = true;
485
+ if (typeof explicit === 'string' && explicit.length > 0) {
486
+ this.operatorToken = explicit;
487
+ this.operatorTokenSource = 'option';
488
+ this.persistence.writeOperatorToken(explicit);
489
+ } else if (persisted) {
490
+ // §5.1 + §7: keep the token stable across restarts, otherwise every restart
491
+ // would silently invalidate the plugin's configured operatorToken.
492
+ this.operatorToken = persisted;
493
+ this.operatorTokenSource = 'restored';
494
+ } else {
495
+ this.operatorToken = randomBytes(32).toString('hex');
496
+ this.operatorTokenSource = 'generated';
497
+ this.persistence.writeOperatorToken(this.operatorToken);
498
+ }
499
+ // MEDIUM-6: the material is printed only by the start that generated it, or when the operator has
500
+ // explicitly asked for it. "The posture, never the material" still holds everywhere else.
501
+ if (this.operatorTokenSource === 'generated') {
502
+ this.operatorTokenPrintReason = this.operatorTokenPrintReason ?? 'generated';
503
+ }
504
+ this.operatorTokenPrintable = this.operatorTokenPrintReason !== null;
505
+ }
506
+
507
+ _buildStartupMessages() {
508
+ const m = this.startupMessages;
509
+ m.push(`[w2m-rabbit] relay_id=${this.relayId}`);
510
+ m.push(`[w2m-rabbit] base_path=${this.basePath}${this.basePath === '/' ? ' (root)' : ''}`);
511
+ m.push(`[w2m-rabbit] trust_proxy=${this.trustProxy}${this.trustProxy ? '' : ' (X-Forwarded-* ignored)'}`);
512
+ m.push(`[w2m-rabbit] pair_rate_limit=${this.pairRateLimitPerMinute === 0 ? 'disabled' : `${this.pairRateLimitPerMinute}/min/IP`}`);
513
+ // §9: report the posture, never the material.
514
+ if (this.signingConfigured) {
515
+ m.push(`[w2m-rabbit] request signing=ON (${this.signingSecrets.length} secret(s)`
516
+ + `${this.signingSecrets.length > 1 ? ', rotation active' : ''})`
517
+ + `${this.requireSignature ? ' - REQUIRED: unsigned /v1/* is rejected with 401' : ' - optional: unsigned requests are still accepted'}`);
518
+ } else if (this.requireSignature) {
519
+ m.push('[w2m-rabbit] !! CONFIGURATION ERROR: --require-signature is set but no --signing-secret was provided. '
520
+ + 'Every /v1/* request will fail with 500 SIGNING_NOT_CONFIGURED (this is the RELAY\'s fault, not the client\'s). '
521
+ + 'Either set --signing-secret or drop --require-signature.');
522
+ } else {
523
+ m.push('[w2m-rabbit] request signing=off (no signing secret configured; behaviour is identical to v0.2.3)');
524
+ }
525
+ if (this.persistence.enabled) {
526
+ m.push(`[w2m-rabbit] persistence=on dir=${this.persistence.dir} `
527
+ + `revived_devices=${this.persistence.revivedDevices} revived_tasks=${this.persistence.revivedTasks}`);
528
+ } else {
529
+ m.push('[w2m-rabbit] persistence=off (in-memory only; devices and tasks are lost on restart)');
530
+ }
531
+ if (this.persistence.devicesCorrupt) {
532
+ m.push('[w2m-rabbit] !! WARNING: devices.json was CORRUPT — started from an EMPTY device table; '
533
+ + 'every machine must pair again. The damaged file was left untouched.');
534
+ }
535
+ for (const w of this.persistence.warnings) {
536
+ m.push(`[w2m-rabbit] !! ${w.file}: ${w.message}`);
537
+ }
538
+ if (this.operatorTokenRequired) {
539
+ // MEDIUM-6: the token is material, not posture, so it is printed as rarely as it can be — on the
540
+ // start that generated it (`operatorTokenSource === 'generated'`) or when `printOperatorToken` /
541
+ // `W2M_PRINT_OPERATOR_TOKEN=1` asked for it — and once, never twice. Where it is stored is said in
542
+ // every case, including the case where there is nowhere to store it.
543
+ //
544
+ // DELIBERATE, do not "fix": on that one start the CLI prints the value a second time, in its own
545
+ // stdout banner. Two sinks for one start is not a leak — the defect was printing it on *every*
546
+ // start, restored ones included — and the box is the documented first-start handoff a human reads
547
+ // (docs/DEPLOY.md §2.4, test/crossnetwork.test.mjs). Collapsing the pair would trade a documented
548
+ // behaviour for one saved line on one start.
549
+ const tokenFile = this.persistence.operatorTokenFile ?? null;
550
+ const stored = tokenFile === null
551
+ ? 'persistence is off, so this token exists only in this process and cannot be read back later'
552
+ : `stored at ${tokenFile} (0600)`;
553
+ if (this.operatorTokenPrintable) {
554
+ m.push(`[w2m-rabbit] operator token (${this.operatorTokenSource}) - required for POST /v1/task:`);
555
+ m.push(`[w2m-rabbit] ${this.operatorToken}`);
556
+ m.push(`[w2m-rabbit] printed once because ${this.operatorTokenPrintReason === 'generated'
557
+ ? 'this start generated it' : `${this.operatorTokenPrintReason} asked for it (${PRINT_OPERATOR_TOKEN_ENV})`}`
558
+ + ` - and ${stored}`);
559
+ } else {
560
+ m.push(`[w2m-rabbit] operator token (${this.operatorTokenSource}) - required for POST /v1/task, NOT printed`);
561
+ m.push(`[w2m-rabbit] read it from ${tokenFile ?? '<state>/operator-token.txt'} - ${stored}`);
562
+ m.push(`[w2m-rabbit] set ${PRINT_OPERATOR_TOKEN_ENV}=1 to print it on this start as well`);
563
+ }
564
+ } else {
565
+ m.push('[w2m-rabbit] !! WARNING: OPERATOR TOKEN DISABLED (--operator-token "") - '
566
+ + 'any device that can reach this relay can dispatch tasks to the whole group. '
567
+ + 'Only acceptable on a trusted LAN / for debugging; /v1/task then requires a device token.');
568
+ }
569
+ }
570
+
571
+ get url() {
572
+ if (this.host === null || this.port === null) return null;
573
+ const host = this.host.includes(':') ? `[${this.host}]` : this.host;
574
+ const prefix = this.basePath === '/' ? '' : this.basePath;
575
+ return `${this.scheme}://${host}:${this.port}${prefix}`;
576
+ }
577
+
578
+ listen({ host = '127.0.0.1', port = 0 } = {}) {
579
+ return new Promise((resolve, reject) => {
580
+ const onError = (err) => reject(err);
581
+ this.server.once('error', onError);
582
+ this.server.listen(port, host, () => {
583
+ this.server.removeListener('error', onError);
584
+ const addr = this.server.address();
585
+ this.host = addr.address;
586
+ this.port = addr.port;
587
+ this._sweepTimer = setInterval(() => {
588
+ this.maintenance();
589
+ }, this.sweepIntervalMs);
590
+ this._sweepTimer.unref?.();
591
+ if (this.logger) {
592
+ this._log(`[w2m-rabbit] listening on ${this.url} pairing code: ${this.pairingCode}`);
593
+ for (const message of this.startupMessages) this._log(message);
594
+ }
595
+ resolve({
596
+ host: this.host,
597
+ port: this.port,
598
+ url: this.url,
599
+ pairingCode: this.pairingCode,
600
+ relayId: this.relayId,
601
+ basePath: this.basePath,
602
+ operatorToken: this.operatorToken,
603
+ operatorTokenRequired: this.operatorTokenRequired,
604
+ // The CLI prints its own banner, so it has to reach the same conclusion this class did rather
605
+ // than re-deriving one from the token's presence (MEDIUM-6).
606
+ operatorTokenSource: this.operatorTokenSource,
607
+ operatorTokenPrintable: this.operatorTokenPrintable === true,
608
+ operatorTokenPrintReason: this.operatorTokenPrintReason ?? null,
609
+ scheme: this.scheme,
610
+ });
611
+ });
612
+ });
613
+ }
614
+
615
+ sweep() {
616
+ return this.state.sweepExpired();
617
+ }
618
+
619
+ close() {
620
+ return new Promise((resolve) => {
621
+ if (this._sweepTimer) clearInterval(this._sweepTimer);
622
+ this._sweepTimer = null;
623
+ // v0.4.0: a deferred P2P offer is a pending timer, and a closed relay must not fire one.
624
+ this.state.clearPendingOffers?.();
625
+ for (const sub of [...this.subscribers]) this._closeSubscriber(sub);
626
+ this.server.close(() => resolve());
627
+ this.server.closeAllConnections?.();
628
+ });
629
+ }
630
+
631
+ /* ---------------- proxy awareness (v0.1.2 §3) ---------------- */
632
+
633
+ /** `X-Forwarded-For` first hop is honoured ONLY under `trustProxy`. */
634
+ clientIp(req) {
635
+ if (this.trustProxy) {
636
+ const forwarded = firstHeaderValue(req.headers['x-forwarded-for']);
637
+ if (forwarded) return forwarded;
638
+ }
639
+ return req.socket?.remoteAddress ?? 'unknown';
640
+ }
641
+
642
+ /** `X-Forwarded-Proto` is honoured ONLY under `trustProxy`. */
643
+ effectiveScheme(req) {
644
+ if (this.trustProxy) {
645
+ const proto = firstHeaderValue(req.headers['x-forwarded-proto']);
646
+ if (proto) return proto.toLowerCase();
647
+ }
648
+ return this.scheme;
649
+ }
650
+
651
+ /* ---------------- request dispatch ---------------- */
652
+
653
+ async handle(req, res) {
654
+ let url;
655
+ try {
656
+ url = new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`);
657
+ } catch {
658
+ throw new ProtocolError('BAD_REQUEST', 'malformed request URL');
659
+ }
660
+ const rawPath = url.pathname;
661
+ const method = (req.method ?? 'GET').toUpperCase();
662
+
663
+ // §3: strip the deployment prefix, then route. `/healthz` also answers at the
664
+ // root because health checks are usually pointed straight at the container.
665
+ // `stripped` keeps the literal request path (no trailing-slash normalisation)
666
+ // because that is what a signature covers; `path` is the normalised route key.
667
+ let stripped;
668
+ if (this.basePath === '/') {
669
+ stripped = rawPath;
670
+ } else if (rawPath === this.basePath) {
671
+ stripped = '/';
672
+ } else if (rawPath.startsWith(`${this.basePath}/`)) {
673
+ stripped = rawPath.slice(this.basePath.length);
674
+ } else if (rawPath === '/healthz') {
675
+ stripped = '/healthz';
676
+ } else {
677
+ // Outside the prefix: an explicit 404, never a gateway-style 502.
678
+ throw new ProtocolError('NOT_FOUND', `path is outside the configured base path ${this.basePath}`, {
679
+ path: rawPath, base_path: this.basePath,
680
+ });
681
+ }
682
+ const path = normalizePath(stripped);
683
+ const signedPath = `${stripped}${url.search}`;
684
+
685
+ // v0.3.0 §9: read the body ONCE, before routing. An HMAC covers the exact
686
+ // received bytes, so no route may consume the stream first and re-serialise.
687
+ const rawBody = methodHasBody(method) ? await readRawBody(req, this.frameLimitBytes) : null;
688
+ const takeJson = () => parseJsonBody(rawBody);
689
+
690
+ /* ---- public endpoints ---- */
691
+ // `/healthz` and `/v1/pair` are permanently exempt from signature checks:
692
+ // the first is an operations probe that must not need credentials, the second
693
+ // is the bootstrap step that happens before the two sides share a secret.
694
+ if (method === 'GET' && path === '/healthz') {
695
+ return sendJson(res, 200, this.healthBody(req));
696
+ }
697
+ if (method === 'POST' && path === '/v1/pair') {
698
+ this.enforcePairRateLimit(req);
699
+ const result = this.state.pair(takeJson());
700
+ return sendJson(res, 200, result);
701
+ }
702
+ /**
703
+ * v0.3.3 `/metrics`: machine-readable fleet state for a monitoring system.
704
+ *
705
+ * Token-free, like `/healthz` and for the same reason: a scraper that needs the operator token
706
+ * would put that token in a Prometheus config file, which is a credential in a place nobody
707
+ * reviews. It is also exempt from signature checks for the same reason -- there is no secret to
708
+ * sign with on the scraper side.
709
+ *
710
+ * Exposed only when the relay was asked for it (`--metrics`). A monitoring endpoint that appears
711
+ * by default is a surface nobody chose, and the whole point of the defaults elsewhere is that the
712
+ * relay binds nothing the operator did not ask for.
713
+ */
714
+ if (method === 'GET' && path === '/metrics') {
715
+ if (!this.metricsEnabled) {
716
+ // 404 rather than 403: a disabled endpoint should look absent, not forbidden. A 403 tells a
717
+ // scanner the surface exists.
718
+ throw new ProtocolError('NOT_FOUND', 'metrics are not enabled on this relay', { hint: 'start the relay with --metrics' });
719
+ }
720
+ const body = renderMetrics(this.state, { nowMs: this.state.nowMs() });
721
+ res.writeHead(200, {
722
+ 'content-type': METRICS_CONTENT_TYPE,
723
+ 'content-length': Buffer.byteLength(body, 'utf8'),
724
+ 'cache-control': 'no-store',
725
+ });
726
+ return res.end(body);
727
+ }
728
+ // §5: dispatching tasks needs the operator token, not a device token.
729
+ if (method === 'POST' && path === '/v1/task') {
730
+ const principal = this.authorizeTaskDispatch(req);
731
+ this.enforceSignature(req, { method, signedPath, body: rawBody });
732
+ const body = takeJson();
733
+ if (principal.machine_id && !body.created_by) body.created_by = principal.machine_id;
734
+ const result = this.state.createTask(body);
735
+ return sendJson(res, 200, result);
736
+ }
737
+
738
+ /* ---- v1.1.6: reachable WITHOUT a device token ---- */
739
+ this.joinChallenges ??= createJoinChallenges({
740
+ now: () => this.state.nowMs(),
741
+ publicKeyFor: (fingerprint) => this.state.accountKeyFor(fingerprint),
742
+ });
743
+ const admissionPollMatch = /^\/v1\/fleet\/admission\/([^/]+)$/.exec(path);
744
+ if (method === 'GET' && admissionPollMatch && url.searchParams.get('poll_token') !== null) {
745
+ this.admission ??= createAdmission({ now: () => this.state.nowMs() });
746
+ const polled = this.admission.poll(decodeURIComponent(admissionPollMatch[1]), url.searchParams.get('poll_token'));
747
+ if (polled.ok !== true) throw new ProtocolError('NOT_FOUND', 'unknown admission request');
748
+ return sendJson(res, 200, { protocol_version: PROTOCOL_VERSION, rabbit_time: this.state.nowIso(), ...polled });
749
+ }
750
+ if (method === 'GET' && path === '/v1/fleet/admission/challenge') {
751
+ const issued = this.joinChallenges.issue(url.searchParams.get('fingerprint') ?? '', url.searchParams.get('machine_id') ?? '');
752
+ if (issued.ok !== true) throw new ProtocolError('BAD_REQUEST', 'challenge refused: ' + issued.code, { code: issued.code });
753
+ return sendJson(res, 200, { protocol_version: PROTOCOL_VERSION, rabbit_time: this.state.nowIso(), ...issued });
754
+ }
755
+ if (method === 'POST' && path === '/v1/fleet/admission/request') {
756
+ const body = takeJson();
757
+ this.admission ??= createAdmission({ now: () => this.state.nowMs() });
758
+ const proof = this.joinChallenges.consume({ challenge_id: body.challenge_id, machine_id: body.machine_id, signature: body.signature });
759
+ if (proof.ok !== true) throw new ProtocolError('UNAUTHORIZED', 'join proof refused: ' + proof.code, { code: proof.code });
760
+ const result = this.admission.requestAdmission({ machine_id: body.machine_id, machine_name: body.machine_name ?? null, account_fingerprint: proof.fingerprint });
761
+ return sendJson(res, 200, { protocol_version: PROTOCOL_VERSION, rabbit_time: this.state.nowIso(), ...result });
762
+ }
763
+
764
+ /* ---- everything below requires `Authorization: Bearer <device_token>` ---- */
765
+ const token = bearerToken(req);
766
+ const device = token ? this.state.authenticate(token) : null;
767
+ if (!device) {
768
+ throw new ProtocolError('UNAUTHORIZED', 'missing or invalid device_token', {});
769
+ }
770
+ this.state.touchDevice(device.machine_id);
771
+
772
+ // v0.3.0 §9: writes are always checked (tolerating unsigned unless required);
773
+ // reads are only checked when the relay was explicitly told to require
774
+ // signatures. See `enforceSignature` for the reasoning.
775
+ this.enforceSignature(req, { method, signedPath, body: rawBody });
776
+
777
+ if (method === 'GET' && path === '/v1/stream') {
778
+ return this.handleStream(req, res, url, device);
779
+ }
780
+ if (method === 'POST' && path === '/v1/heartbeat') {
781
+ const body = takeJson();
782
+ body.machine_id = body.machine_id ?? device.machine_id;
783
+ const result = this.state.heartbeat(body);
784
+ return sendJson(res, 200, result);
785
+ }
786
+ if (method === 'POST' && path === '/v1/result') {
787
+ const body = takeJson();
788
+ const result = this.state.submitResult(body);
789
+ const { _instanceKey, ...clean } = result;
790
+ return sendJson(res, 200, clean);
791
+ }
792
+ /**
793
+ * v1.0.7: the content-addressed blob channel (#1).
794
+ *
795
+ * ## Why the relay may carry bytes at all
796
+ *
797
+ * It persists `stdout_sha256` and never the text, and `src/agent/storage.mjs` records why: each machine's
798
+ * `memory.jsonl` is the only durable copy of what a command printed. **That invariant is about the relay not
799
+ * interpreting content** -- it never decides what bytes mean and never asserts they are authentic.
800
+ *
801
+ * A blob keyed by its own hash preserves exactly that. The relay still interprets nothing; **the hash is what
802
+ * says the bytes are the bytes**, exactly as `stdout_sha256` does for a result. What is new is only that a hash
803
+ * the relay already holds can have its bytes fetched from the same place.
804
+ *
805
+ * ## Why the hash is verified before storing
806
+ *
807
+ * A content-addressed store that accepts bytes under a key they do not hash to is not content-addressed -- the
808
+ * key stops being a claim about the content, and every later reader's verification becomes decorative. So a
809
+ * mismatch is **refused (422)**, never stored and never corrected: correcting it would silently re-key a blob
810
+ * the caller believes it stored under a different name.
811
+ *
812
+ * ## Fleet scoping
813
+ *
814
+ * `putFleetBlob`/`getFleetBlob` reuse `scopeFleetId`, the same rule task dispatch obeys. A blob written by one
815
+ * fleet is **not readable by another**, and the read refusal is a 404 rather than a 403: a distinguishable
816
+ * "not yours" tells a prober that the hash exists here.
817
+ */
818
+ /**
819
+ * v1.0.9: **which blob this fleet published last** -- the discovery half of the channel.
820
+ *
821
+ * Checked **before** the `<sha256>` matcher deliberately. The matcher only accepts 64 hex characters, so
822
+ * `latest` cannot collide with it today; **the ordering is asserted anyway**, because "these two patterns cannot
823
+ * conflict" is exactly the reasoning that produces a shadowed route the day one of them is relaxed.
824
+ *
825
+ * A fleet that has never published gets a 404 rather than an empty object: "there is no current document" and
826
+ * "the current document is nothing" are different statements, and only one of them is true here.
827
+ */
828
+ if (method === 'GET' && path === '/v1/fleet/blobs/latest') {
829
+ const latest = this.state.latestFleetBlob(device);
830
+ if (latest === null) {
831
+ throw new ProtocolError('NOT_FOUND', 'this fleet has published no blob', {});
832
+ }
833
+ return sendJson(res, 200, {
834
+ protocol_version: PROTOCOL_VERSION,
835
+ hash: latest.hash,
836
+ bytes: latest.bytes,
837
+ published_at: new Date(latest.published_at_ms).toISOString(),
838
+ published_by: latest.published_by ?? null,
839
+ // Stated in the payload, not only in the docs: a pointer can outlive its blob under oldest-first eviction.
840
+ hint: 'a hint, not a guarantee -- a pull may answer 404 if the blob has since been evicted',
841
+ });
842
+ }
843
+
844
+ const blobMatch = /^\/v1\/fleet\/blobs\/([0-9a-f]{64})$/.exec(path);
845
+ if (blobMatch !== null) {
846
+ const hash = blobMatch[1];
847
+ if (method === 'PUT') {
848
+ const received = rawBody ?? Buffer.alloc(0);
849
+ const actual = createHash('sha256').update(received).digest('hex');
850
+ if (actual !== hash) {
851
+ throw new ProtocolError('BLOB_HASH_MISMATCH', 'the body does not hash to the key it was sent under', {
852
+ expected: hash,
853
+ actual,
854
+ bytes: received.length,
855
+ });
856
+ }
857
+ const stored = this.state.putFleetBlob(device, received);
858
+ if (stored.ok !== true) {
859
+ throw new ProtocolError(stored.reason ?? 'BLOB_WRITE_FAILED', stored.detail ?? 'the blob was refused', {
860
+ hash,
861
+ });
862
+ }
863
+ return sendJson(res, 201, {
864
+ protocol_version: PROTOCOL_VERSION,
865
+ ok: true,
866
+ hash: stored.hash,
867
+ bytes: stored.bytes,
868
+ evicted: stored.evicted,
869
+ });
870
+ }
871
+ if (method === 'GET') {
872
+ const bytes = this.state.getFleetBlob(device, hash);
873
+ if (bytes === null) {
874
+ // Same code and shape for "no such blob" and "not your fleet's" -- deliberately indistinguishable.
875
+ throw new ProtocolError('NOT_FOUND', 'no such blob is readable by this device', { hash });
876
+ }
877
+ res.writeHead(200, {
878
+ 'content-type': 'application/octet-stream',
879
+ 'content-length': bytes.length,
880
+ // Same reason as `/metrics`: a memory document must not be cached by an intermediary.
881
+ 'cache-control': 'no-store',
882
+ });
883
+ res.end(bytes);
884
+ return true;
885
+ }
886
+ throw new ProtocolError('BAD_REQUEST', 'a blob is addressed with PUT or GET', { method });
887
+ }
888
+
889
+ if (method === 'GET' && path === '/v1/devices') {
890
+ return sendJson(res, 200, {
891
+ protocol_version: PROTOCOL_VERSION,
892
+ rabbit_time: this.state.nowIso(),
893
+ devices: this.state.listDevices(),
894
+ });
895
+ }
896
+ if (method === 'GET' && path === '/v1/tasks') {
897
+ const rawLimit = url.searchParams.get('limit');
898
+ let limit = 50;
899
+ if (rawLimit !== null) {
900
+ limit = Number(rawLimit);
901
+ if (!Number.isInteger(limit) || limit < 1) {
902
+ throw new ProtocolError('BAD_REQUEST', 'limit must be a positive integer', { limit: rawLimit });
903
+ }
904
+ }
905
+ return sendJson(res, 200, {
906
+ protocol_version: PROTOCOL_VERSION,
907
+ rabbit_time: this.state.nowIso(),
908
+ tasks: this.state.listTasks({ limit }),
909
+ });
910
+ }
911
+
912
+ const taskMatch = /^\/v1\/tasks\/([^/]+)$/.exec(path);
913
+ const reportMatch = /^\/v1\/tasks\/([^/]+)\/report$/.exec(path);
914
+ // v0.3.0: cross-machine RTT status. The plugin may run on a different machine
915
+ // than the agent, so this has to come from the relay, not from a local file.
916
+ const agentStatusMatch = /^\/v1\/agents\/([^/]+)\/status$/.exec(path);
917
+ // v0.3.9: P2P candidate rendezvous. `/announce` is checked before the read route
918
+ // so that a machine literally named "announce" cannot shadow it.
919
+ const peerReadMatch = /^\/v1\/peer\/([^/]+)$/.exec(path);
920
+ /* ---- v1.1.6 admission ---- */
921
+ const admissionDecideMatch = /^\/v1\/fleet\/admission\/([^/]+)\/decide$/.exec(path);
922
+ const memberRemoveMatch = /^\/v1\/fleet\/members\/([^/]+)\/remove$/.exec(path);
923
+ const removalVoteMatch = /^\/v1\/fleet\/removals\/([^/]+)\/vote$/.exec(path);
924
+
925
+ /* ---- v0.3.9 P2P signalling ---- */
926
+ if (method === 'POST' && path === '/v1/peer/announce') {
927
+ const body = takeJson();
928
+ try {
929
+ // `device.machine_id`, never `body.machine_id`: a paired machine may only
930
+ // announce addresses for itself, or it could aim a peer's punch at a third party.
931
+ const result = this.peers.announce(device.machine_id, body);
932
+ return sendJson(res, 200, {
933
+ protocol_version: PROTOCOL_VERSION,
934
+ rabbit_time: this.state.nowIso(),
935
+ ...result,
936
+ });
937
+ } catch (error) {
938
+ throw new ProtocolError('BAD_REQUEST', error.message, { code: error.code ?? 'BAD_ANNOUNCEMENT' });
939
+ }
940
+ }
941
+
942
+ if (method === 'GET' && peerReadMatch) {
943
+ const machineId = decodeURIComponent(peerReadMatch[1]);
944
+ const entry = this.peers.get(machineId);
945
+ if (!entry) {
946
+ // A named 404 rather than an empty list: "this machine has not announced" and
947
+ // "this machine announced nothing reachable" call for different responses, and
948
+ // an empty candidate list would send the caller into a punch that cannot work.
949
+ throw new ProtocolError('NOT_FOUND', `no live P2P announcement for ${machineId}`, {
950
+ machine_id: machineId,
951
+ hint: 'the peer must POST /v1/peer/announce first, and announcements expire',
952
+ });
953
+ }
954
+ return sendJson(res, 200, {
955
+ protocol_version: PROTOCOL_VERSION,
956
+ rabbit_time: this.state.nowIso(),
957
+ peer: entry,
958
+ });
959
+ }
960
+
961
+ if (method === 'GET' && agentStatusMatch) {
962
+ const machineId = decodeURIComponent(agentStatusMatch[1]);
963
+ const status = this.state.deviceStatus(machineId);
964
+ if (!status) {
965
+ throw new ProtocolError('NOT_FOUND', 'unknown machine_id', { machine_id: machineId });
966
+ }
967
+ return sendJson(res, 200, {
968
+ protocol_version: PROTOCOL_VERSION,
969
+ rabbit_time: this.state.nowIso(),
970
+ ...status,
971
+ });
972
+ }
973
+
974
+ if (method === 'GET' && reportMatch) {
975
+ const taskId = decodeURIComponent(reportMatch[1]);
976
+ this.state.sweepExpired();
977
+ const format = url.searchParams.get('format') ?? 'json';
978
+ const report = buildReport(this.state, taskId, { format });
979
+ if (res.writableEnded) return undefined;
980
+ res.writeHead(200, {
981
+ 'content-type': report.contentType,
982
+ 'content-length': Buffer.byteLength(report.body, 'utf8'),
983
+ 'cache-control': 'no-store',
984
+ });
985
+ return res.end(report.body);
986
+ }
987
+
988
+ if (method === 'GET' && taskMatch) {
989
+ const taskId = decodeURIComponent(taskMatch[1]);
990
+ this.state.sweepExpired();
991
+ const task = this.state.requireTask(taskId);
992
+ const aggregate = aggregateTask(this.state, taskId);
993
+ return sendJson(res, 200, {
994
+ protocol_version: PROTOCOL_VERSION,
995
+ rabbit_time: this.state.nowIso(),
996
+ task: this.state.taskSummary(task),
997
+ leases: [...task.leases.values()],
998
+ aggregate,
999
+ });
1000
+ }
1001
+
1002
+
1003
+ /* ---- v1.1.6 admission: the caller is always `device.machine_id`, never a body field ---- */
1004
+ this.admission ??= createAdmission({ now: () => this.state.nowMs() });
1005
+
1006
+ if (method === 'GET' && path === '/v1/fleet/admission/pending') {
1007
+ return sendJson(res, 200, {
1008
+ protocol_version: PROTOCOL_VERSION, rabbit_time: this.state.nowIso(),
1009
+ pending: this.admission.pendingFor(),
1010
+ });
1011
+ }
1012
+
1013
+ if (method === 'POST' && admissionDecideMatch) {
1014
+ const body = takeJson();
1015
+ const result = this.admission.decide(decodeURIComponent(admissionDecideMatch[1]), {
1016
+ decision: body.decision, decided_by: device.machine_id, auto: body.auto === true,
1017
+ });
1018
+ if (result.ok !== true) throw new ProtocolError('BAD_REQUEST', 'admission decision refused: ' + result.code, result);
1019
+ return sendJson(res, 200, { protocol_version: PROTOCOL_VERSION, rabbit_time: this.state.nowIso(), ...result });
1020
+ }
1021
+
1022
+ if (method === 'POST' && memberRemoveMatch) {
1023
+ const body = takeJson();
1024
+ const result = this.admission.remove(decodeURIComponent(memberRemoveMatch[1]), {
1025
+ requested_by: device.machine_id, reason: typeof body.reason === 'string' ? body.reason : null,
1026
+ });
1027
+ if (result.ok !== true) throw new ProtocolError('BAD_REQUEST', 'removal refused: ' + result.code, result);
1028
+ return sendJson(res, 200, { protocol_version: PROTOCOL_VERSION, rabbit_time: this.state.nowIso(), ...result });
1029
+ }
1030
+
1031
+ if (method === 'POST' && removalVoteMatch) {
1032
+ const body = takeJson();
1033
+ const result = this.admission.vote(decodeURIComponent(removalVoteMatch[1]), {
1034
+ machine_id: device.machine_id, vote: body.vote,
1035
+ });
1036
+ if (result.ok !== true) throw new ProtocolError('BAD_REQUEST', 'vote refused: ' + result.code, result);
1037
+ return sendJson(res, 200, { protocol_version: PROTOCOL_VERSION, rabbit_time: this.state.nowIso(), ...result });
1038
+ }
1039
+
1040
+ throw new ProtocolError('NOT_FOUND', `no route for ${method} ${path}`, { method, path });
1041
+ }
1042
+
1043
+ /** §4: the operations answer — "is the relay there, did it restart, are my machines connected". */
1044
+ healthBody(req) {
1045
+ return {
1046
+ ...this.state.stats(),
1047
+ // v0.3.9: how many machines currently have a live P2P announcement. Ephemeral,
1048
+ // so this drops to 0 by itself when nobody is refreshing.
1049
+ ...this.peers.stats(),
1050
+ ok: true,
1051
+ /**
1052
+ * v0.6.2: hoisted out of `persistence` so it cannot be missed by a reader that only looks at
1053
+ * the top level. `degraded: true` means this relay is answering requests while failing to record
1054
+ * them -- the one relay failure that presents as health. `ok` deliberately stays true: the relay
1055
+ * still serves the fleet, and flipping it would turn a recording problem into an outage.
1056
+ */
1057
+ degraded: this.persistence.enabled && this.persistence.degraded,
1058
+ degraded_reason: this.persistence.degraded
1059
+ ? `ledger appends are failing (${this.persistence.lastAppendError ?? 'unknown error'}); results are served but not durably recorded`
1060
+ : null,
1061
+ protocol_version: PROTOCOL_VERSION,
1062
+ rabbit_time: this.state.nowIso(),
1063
+ uptime_ms: this.state.nowMs() - this._startedAtMs,
1064
+ relay_id: this.relayId,
1065
+ started_at: rfc3339(this._startedAtMs),
1066
+ effective_scheme: this.effectiveScheme(req),
1067
+ base_path: this.basePath,
1068
+ operator_token_required: this.operatorTokenRequired,
1069
+ pair_rate_limit: this.pairRateLimitPerMinute,
1070
+ // v0.3.0: fleet-wide latency. Every numeric field is null (never 0) when no
1071
+ // machine has reported a FRESH measurement.
1072
+ rtt: this.state.rttSummary(),
1073
+ // v0.3.0 §9: signature status only — never the secret, not even a prefix.
1074
+ signing: {
1075
+ configured: this.signingConfigured,
1076
+ required: this.requireSignature,
1077
+ previous_secret_accepted: this.signingSecrets.length > 1,
1078
+ skew_seconds: this.signatureSkewSeconds,
1079
+ },
1080
+ persistence: this.persistence.describe(),
1081
+ };
1082
+ }
1083
+
1084
+ /* ---------------- request signing (v0.3.0 §9) ---------------- */
1085
+
1086
+ /**
1087
+ * Should this request be signature-checked at all?
1088
+ *
1089
+ * RULING (see PROTOCOL-v0.3.0.md §9.4): every WRITE is checked; READS are
1090
+ * checked only when `--require-signature` is on.
1091
+ *
1092
+ * Reads are not checked in the default modes because unsigned reads are
1093
+ * accepted anyway, so "verify when a signature happens to be present" would be
1094
+ * theatre -- an attacker simply omits the headers -- while adding a brand new
1095
+ * way for a poll or an SSE reconnect to fail. What a read leaks is topology,
1096
+ * which the device token already gates; what a write can do is change state,
1097
+ * which is what replay and tampering actually threaten.
1098
+ */
1099
+ shouldCheckSignature(method) {
1100
+ if (this.requireSignature) return true; // explicit hard mode: nothing is exempt
1101
+ const isRead = method === 'GET' || method === 'HEAD' || method === 'OPTIONS';
1102
+ return !isRead;
1103
+ }
1104
+
1105
+ /** Run `verifyRequest` and throw the mapped §7 error on rejection. */
1106
+ enforceSignature(req, { method, signedPath, body }) {
1107
+ if (!this.shouldCheckSignature(method)) return { skipped: true };
1108
+ const decision = this.verifySignature(req, { method, signedPath, body });
1109
+ if (decision.ok !== true) throw signatureError(decision);
1110
+ return decision;
1111
+ }
1112
+
1113
+ /**
1114
+ * Thin adapter over the frozen `signing.mjs` contract.
1115
+ *
1116
+ * `path` is the ROUTED path with the query string, NOT the raw request URL: with
1117
+ * `--base-path /w2m` the same client must produce the same signature whether a
1118
+ * proxy passes `/w2m/v1/result` through or strips it to `/v1/result`. The routed
1119
+ * path is the only value both sides agree on in all three deployment forms, so
1120
+ * clients sign `/v1/result` and never `https://host/w2m/v1/result`.
1121
+ */
1122
+ /**
1123
+ * Verify a request's signature (v0.7.11).
1124
+ *
1125
+ * Two mechanisms, and the order between them is the whole design:
1126
+ *
1127
+ * **1. Per-device Ed25519, when the sender is a device with a stored public key.** This is the
1128
+ * one that proves *which* device signed. It is tried **first** because a device key is strictly
1129
+ * stronger evidence than a shared secret, and because a device that registered a key must not
1130
+ * fall back to the weaker mechanism by accident.
1131
+ *
1132
+ * **2. HMAC over a shared secret, otherwise.** Every device that paired before v0.7.10 arrives
1133
+ * here — which is every device today — and nothing about its behaviour changes.
1134
+ *
1135
+ * ## Why this converges with no second deployment
1136
+ *
1137
+ * A device that has not been updated sends no signature header, so mechanism 1 finds no key and
1138
+ * mechanism 2 answers exactly as before. A device that *has* been updated sends a signature, its
1139
+ * public key is on file from pairing, and it is verified with it. So a fleet updates one machine
1140
+ * at a time and each machine gets the strongest mechanism available **to it** the moment it
1141
+ * starts sending one — no flag, no rollout step, no coordination.
1142
+ *
1143
+ * ## What this deliberately does not do
1144
+ *
1145
+ * It does not **require** a device key. `requireSignature` still means "a signature must be
1146
+ * present", and either mechanism satisfies it. Making a *device key* mandatory is a separate,
1147
+ * later switch, because turning it on today would refuse all four machines at once.
1148
+ */
1149
+ verifySignature(req, { method, signedPath, body }) {
1150
+ const viaDevice = this.verifyWithDeviceKey(req, { method, signedPath, body });
1151
+ if (viaDevice !== null) return viaDevice;
1152
+
1153
+ return verifyRequest({
1154
+ headers: req.headers, // plain Node object; signing.mjs reads it case-insensitively
1155
+ method,
1156
+ path: signedPath,
1157
+ body: body ?? '',
1158
+ secrets: this.signingSecrets,
1159
+ nonces: this.nonceCache,
1160
+ nowMs: this.state.nowMs(),
1161
+ skewSeconds: this.signatureSkewSeconds,
1162
+ required: this.requireSignature,
1163
+ });
1164
+ }
1165
+
1166
+ /**
1167
+ * Try the per-device Ed25519 path.
1168
+ *
1169
+ * Returns `null` when the mechanism does not apply — no signature presented, or the signing
1170
+ * machine is not a device whose public key we hold — so the caller falls through. Returns a
1171
+ * decision when it *does* apply, **including when it fails**: a device that registered a key and
1172
+ * then presented a bad signature must not get a second chance through the shared secret, since
1173
+ * that would make the stronger mechanism optional for anyone able to produce a malformed one.
1174
+ */
1175
+ verifyWithDeviceKey(req, { method, signedPath, body }) {
1176
+ const header = readHeader(req.headers, DEVICE_SIGNATURE_HEADER);
1177
+ if (typeof header !== 'string' || header === '') return null;
1178
+
1179
+ const machineId = this.machineIdForRequest(req);
1180
+ if (machineId === null) return null;
1181
+ const publicKey = this.state.devices.get(machineId)?.public_key;
1182
+ if (typeof publicKey !== 'string' || publicKey === '') return null;
1183
+
1184
+ const decision = verifyDeviceSignature({
1185
+ headers: req.headers,
1186
+ publicKeyPem: publicKey,
1187
+ method,
1188
+ path: signedPath,
1189
+ body: body ?? '',
1190
+ nowMs: this.state.nowMs(),
1191
+ skewSeconds: this.signatureSkewSeconds,
1192
+ // `accept`, not `remember` -- the name this class actually exposes. It reports whether the
1193
+ // nonce was new, which is exactly the contract `verifyDeviceSignature` expects.
1194
+ nonces: (nonce, at) => this.nonceCache.accept(nonce, at),
1195
+ });
1196
+ if (decision.ok) return { ...decision, machine_id: machineId, keyIndex: null };
1197
+ return decision;
1198
+ }
1199
+
1200
+ /**
1201
+ * Which machine a request claims to be, from either credential.
1202
+ *
1203
+ * An **operator token is not a machine**, so it resolves to `null` and the device path does not
1204
+ * apply — consistent with `authorizeTaskDispatch`, which reports `machine_id: null` for an
1205
+ * operator. That is why an operator-token request keeps using the shared secret.
1206
+ */
1207
+ machineIdForRequest(req) {
1208
+ const token = bearerToken(req);
1209
+ if (!token) return null;
1210
+ if (this.operatorToken !== null && token === this.operatorToken) return null;
1211
+ return this.state.authenticate(token)?.machine_id ?? null;
1212
+ }
1213
+
1214
+ /** Periodic maintenance, called by the sweep timer. */
1215
+ maintenance() {
1216
+ const expired = this.sweep();
1217
+ /**
1218
+ * v0.9.1: presence expiry, alongside lease expiry.
1219
+ *
1220
+ * `this.sweep()` writes off lease *holds*; this writes off *presence*. They were conflated, so a
1221
+ * machine that stopped existing was only ever noticed when its SSE stream detached — and a
1222
+ * half-open stream never detaches.
1223
+ */
1224
+ const silent = this.state.sweepSilentDevices();
1225
+ if (silent.length > 0) {
1226
+ this._log(`[w2m-rabbit] marked ${silent.length} silent device(s) offline: `
1227
+ + silent.map((s) => `${s.machine_name} (${Math.round(s.silent_ms / 1000)}s)`).join(', '));
1228
+ }
1229
+ this.pairLimiter.prune();
1230
+ this.peers.sweep();
1231
+ // Keep the nonce cache from growing without bound in a long-running process.
1232
+ this.nonceCache.prune(this.nonceRetentionMs, this.state.nowMs());
1233
+ return expired;
1234
+ }
1235
+
1236
+ /* ---------------- auth helpers ---------------- */
1237
+
1238
+ /** §6: every /v1/pair attempt counts, success included. */
1239
+ enforcePairRateLimit(req) {
1240
+ if (this.pairRateLimitPerMinute <= 0) return;
1241
+ const ip = this.clientIp(req);
1242
+ const verdict = this.pairLimiter.hit(ip);
1243
+ if (verdict.allowed) return;
1244
+ const err = new ProtocolError(
1245
+ 'RATE_LIMITED',
1246
+ `too many /v1/pair attempts from ${ip}: limit is ${verdict.limit} per ${verdict.window_seconds}s`,
1247
+ {
1248
+ retry_after_seconds: verdict.retry_after_seconds,
1249
+ limit: verdict.limit,
1250
+ window_seconds: verdict.window_seconds,
1251
+ scope: 'pair',
1252
+ },
1253
+ );
1254
+ err.headers = { 'retry-after': String(verdict.retry_after_seconds) };
1255
+ throw err;
1256
+ }
1257
+
1258
+ /**
1259
+ * §5: `POST /v1/task` needs the operator token.
1260
+ * - required (default): operator token, else 401 OPERATOR_REQUIRED
1261
+ * - disabled (`--operator-token ''`): falls back to v1 semantics, i.e. a paired device token
1262
+ */
1263
+ authorizeTaskDispatch(req) {
1264
+ const token = bearerToken(req);
1265
+ if (this.operatorTokenRequired) {
1266
+ if (!token) {
1267
+ throw new ProtocolError(
1268
+ 'OPERATOR_REQUIRED',
1269
+ 'POST /v1/task requires the operator token. A device_token is machine credentials and cannot '
1270
+ + `dispatch tasks; read the operator token from ${this.persistence.operatorTokenFile ?? '<state>/operator-token.txt'} `
1271
+ + 'or pass --operator-token / W2M_OPERATOR_TOKEN.',
1272
+ { operator_token_file: this.persistence.operatorTokenFile ?? null },
1273
+ );
1274
+ }
1275
+ if (token !== this.operatorToken) {
1276
+ const asDevice = this.state.authenticate(token);
1277
+ throw new ProtocolError(
1278
+ 'OPERATOR_REQUIRED',
1279
+ asDevice
1280
+ ? 'this is a device_token (machine credentials); dispatching tasks requires the operator_token — '
1281
+ + 'they are two different credentials'
1282
+ : 'invalid operator token: it does not match the relay operator token',
1283
+ {
1284
+ device_token_detected: Boolean(asDevice),
1285
+ machine_id: asDevice?.machine_id ?? null,
1286
+ operator_token_file: this.persistence.operatorTokenFile ?? null,
1287
+ },
1288
+ );
1289
+ }
1290
+ return { role: 'operator', machine_id: null };
1291
+ }
1292
+ const device = token ? this.state.authenticate(token) : null;
1293
+ if (!device) {
1294
+ throw new ProtocolError(
1295
+ 'UNAUTHORIZED',
1296
+ 'the operator token requirement is disabled on this relay, but /v1/task still requires a valid device_token',
1297
+ {},
1298
+ );
1299
+ }
1300
+ return { role: 'device', machine_id: device.machine_id };
1301
+ }
1302
+
1303
+ /* ---------------- SSE (§3) ---------------- */
1304
+
1305
+ handleStream(req, res, url, device) {
1306
+ const machineId = device.machine_id;
1307
+ const requested = url.searchParams.get('machine_id');
1308
+ if (requested !== null && requested !== machineId) {
1309
+ throw new ProtocolError('BAD_REQUEST', 'machine_id does not match the device_token', {
1310
+ machine_id: requested, token_machine_id: machineId,
1311
+ });
1312
+ }
1313
+
1314
+ let from = null;
1315
+ const seqParam = url.searchParams.get('seq');
1316
+ const lastEventId = req.headers['last-event-id'];
1317
+ if (seqParam !== null) {
1318
+ from = Number(seqParam);
1319
+ if (!Number.isInteger(from) || from < 1) {
1320
+ throw new ProtocolError('BAD_REQUEST', 'seq must be a positive integer', { seq: seqParam });
1321
+ }
1322
+ } else if (typeof lastEventId === 'string' && lastEventId.trim() !== '') {
1323
+ const last = Number(lastEventId);
1324
+ if (!Number.isInteger(last) || last < 0) {
1325
+ throw new ProtocolError('BAD_REQUEST', 'Last-Event-ID must be a non-negative integer', { last_event_id: lastEventId });
1326
+ }
1327
+ from = last + 1;
1328
+ }
1329
+
1330
+ // §8.5: these two headers are the fix for "connects but no events" behind
1331
+ // nginx-style proxies and tunnels, which buffer event streams by default.
1332
+ res.writeHead(200, {
1333
+ 'content-type': 'text/event-stream; charset=utf-8',
1334
+ 'cache-control': 'no-cache, no-transform',
1335
+ connection: 'keep-alive',
1336
+ 'x-accel-buffering': 'no',
1337
+ });
1338
+ if (typeof res.flushHeaders === 'function') res.flushHeaders();
1339
+
1340
+ const sub = { machineId, res, write: null, timer: null, closed: false };
1341
+
1342
+ const writeEvent = (event) => {
1343
+ if (res.writableEnded) return;
1344
+ res.write(`id: ${event.seq}\nevent: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`);
1345
+ };
1346
+
1347
+ let live = false;
1348
+ const queue = [];
1349
+ const deliver = (entry) => {
1350
+ if (entry.target && entry.target !== machineId) return;
1351
+ writeEvent(entry.event);
1352
+ };
1353
+ const unsubscribe = this.state.onEvent((entry) => {
1354
+ if (!live) { queue.push(entry); return; }
1355
+ deliver(entry);
1356
+ });
1357
+
1358
+ // §3.1: the first frame MUST be `ready`; §8.3 adds `relay_id`.
1359
+ const readySeq = this.state.reserveSeq();
1360
+ writeEvent({
1361
+ type: 'ready',
1362
+ seq: readySeq,
1363
+ protocol_version: PROTOCOL_VERSION,
1364
+ rabbit_time: this.state.nowIso(),
1365
+ machine_id: machineId,
1366
+ relay_id: this.relayId,
1367
+ });
1368
+
1369
+ if (from !== null) {
1370
+ const oldest = this.state.oldestBufferedSeq();
1371
+ const lastBuffered = this.state.lastBufferedSeq();
1372
+ // `fromFuture` is judged against EVERY seq this process has allocated (a client
1373
+ // can legitimately hold a `ready` seq, which is not buffered), while the
1374
+ // reported window bounds describe the replay ring the client can actually use.
1375
+ const lastSeq = this.state.lastSeq();
1376
+ // Two distinct ways for a cursor to be out of sync with THIS process:
1377
+ //
1378
+ // from < oldest the cursor is older than the replay window (buffer rot)
1379
+ // from > lastSeq+1 the cursor cannot exist here at all. Sequence numbers
1380
+ // restart at 1 in every process, so a cursor from a
1381
+ // previous relay process is AHEAD of a freshly started
1382
+ // relay. This was the silent case: `13 < 1` is false, the
1383
+ // client got no notice, `replayEntries(13)` matched
1384
+ // nothing, and the agent then reset its cursor to the
1385
+ // `ready` seq -- stepping over every event it had missed.
1386
+ const tooOld = from < oldest && oldest > 1;
1387
+ const fromFuture = from > lastSeq + 1;
1388
+ if (tooOld || fromFuture) {
1389
+ // §8.4: tell the client where to re-align, not just that replay failed.
1390
+ writeEvent({
1391
+ type: 'notice',
1392
+ seq: this.state.reserveSeq(),
1393
+ rabbit_time: this.state.nowIso(),
1394
+ level: 'warn',
1395
+ code: 'REPLAY_TRUNCATED',
1396
+ message: tooOld
1397
+ ? `requested seq ${from} is older than the buffer head ${oldest}`
1398
+ : `requested seq ${from} is beyond this process' last seq ${lastSeq}: the cursor came from a `
1399
+ + 'previous relay process, whose sequence numbering restarted at 1',
1400
+ machine_id: machineId,
1401
+ requested_seq: from,
1402
+ oldest_available_seq: oldest,
1403
+ last_available_seq: lastBuffered,
1404
+ relay_id: this.relayId,
1405
+ reason: tooOld ? 'buffer_truncated' : 'cursor_ahead_of_relay',
1406
+ });
1407
+ }
1408
+ // A cursor from a previous process is meaningless here, so honouring it
1409
+ // literally (replay from `from`) would deliver NOTHING and also lose every
1410
+ // event that fell into the gap -- not only offers, but `task.cancel`,
1411
+ // `notice`, `peer.*`. Re-align to the head of the window instead: the client
1412
+ // asked to be resynchronised, and the ring is exactly what we still have.
1413
+ const replayFrom = fromFuture ? oldest : from;
1414
+ for (const entry of this.state.replayEntries(replayFrom)) deliver(entry);
1415
+ }
1416
+
1417
+ live = true;
1418
+ for (const entry of queue) deliver(entry);
1419
+ queue.length = 0;
1420
+
1421
+ // §8.6: re-state work this machine was handed while its stream was down.
1422
+ //
1423
+ // An offer is a single event; if the stream is not connected at that instant
1424
+ // -- after a relay restart, a tunnel drop, or any interruption -- the event
1425
+ // is lost and the lease waits out its whole window before being swept. The
1426
+ // machine is meanwhile online and idle. Re-delivering on connect is what
1427
+ // makes a reconnect recover work instead of silently losing it.
1428
+ //
1429
+ // Only unclaimed leases are re-offered; `running` is excluded so a task that
1430
+ // has already begun cannot be handed out a second time and executed twice.
1431
+ const redelivered = this.state.redeliverPendingOffers(machineId);
1432
+ if (redelivered.count > 0) {
1433
+ this._log(`[w2m-rabbit] re-offered ${redelivered.count} pending task(s) to ${machineId} on reconnect`);
1434
+ }
1435
+
1436
+ // §3.2: `: keepalive` comment every 15s.
1437
+ sub.timer = setInterval(() => {
1438
+ if (res.writableEnded) return;
1439
+ res.write(': keepalive\n\n');
1440
+ }, this.keepaliveMs);
1441
+ sub.timer.unref?.();
1442
+
1443
+ sub.write = writeEvent;
1444
+ sub.unsubscribe = unsubscribe;
1445
+ this.subscribers.add(sub);
1446
+ device.streams = (device.streams ?? 0) + 1;
1447
+ // v0.3.0: relay-observed reconnect counter. A first attach is not a reconnect,
1448
+ // so the reported `reconnect_attempts` is (attaches - 1).
1449
+ this.state.noteStreamConnect(machineId);
1450
+
1451
+ const onClose = () => this._closeSubscriber(sub);
1452
+ req.on('close', onClose);
1453
+ res.on('close', onClose);
1454
+ res.on('error', onClose);
1455
+ return undefined;
1456
+ }
1457
+
1458
+ _closeSubscriber(sub) {
1459
+ if (!sub || sub.closed) return;
1460
+ sub.closed = true;
1461
+ this.subscribers.delete(sub);
1462
+ if (sub.timer) clearInterval(sub.timer);
1463
+ sub.timer = null;
1464
+ sub.unsubscribe?.();
1465
+ const device = this.state.devices.get(sub.machineId);
1466
+ if (device) {
1467
+ device.streams = Math.max(0, (device.streams ?? 1) - 1);
1468
+ if (device.streams === 0) this.state.setOnline(sub.machineId, false, 'stream_closed');
1469
+ }
1470
+ if (!sub.res.writableEnded) {
1471
+ try { sub.res.end(); } catch { /* already gone */ }
1472
+ }
1473
+ }
1474
+ }
1475
+
1476
+ /** Convenience factory. */
1477
+ export function createRelayServer(options = {}) {
1478
+ return new RelayServer(options);
1479
+ }
1480
+
1481
+ /** Create + listen in one call. */
1482
+ export async function startRelayServer(options = {}) {
1483
+ const relay = createRelayServer(options);
1484
+ await relay.listen(options);
1485
+ return relay;
1486
+ }
1487
+
1488
+ export {
1489
+ Persistence,
1490
+ ProtocolError,
1491
+ RabbitState,
1492
+ MAX_FRAME_BYTES,
1493
+ PROTOCOL_VERSION,
1494
+ rfc3339,
1495
+ };
1496
+ export default createRelayServer;