node-red-contrib-relink 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/client.js ADDED
@@ -0,0 +1,768 @@
1
+ "use strict";
2
+
3
+ const { EventEmitter } = require("node:events");
4
+ const crypto = require("node:crypto");
5
+ const dgram = require("node:dgram");
6
+ const dns = require("node:dns").promises;
7
+ const http = require("node:http");
8
+ const https = require("node:https");
9
+ const { performance } = require("node:perf_hooks");
10
+ const { crc32, pinNumber, encodeEntry, decodeValue, decodeBatch, seal, open, NAMES, coerceKind, parseKinds } = require("./protocol");
11
+ const { CAM_CHUNK, AUDIO_RATES, AUDIO_PER, ulawEncode, ULAW_DEC, CamAssembly, Resampler } = require("./media");
12
+
13
+ const CAM_SUB_EVERY = 1000; // viewer / listener refreshes its subscribe ('C' / 'a')
14
+ const CAM_SUB_TIMEOUT = 3000; // sender: a viewer that stopped refreshing has left
15
+
16
+ const MASK48 = (1n << 48n) - 1n;
17
+ const WINDOW_MASK = (1n << 1024n) - 1n;
18
+ const monotonic = () => performance.now();
19
+
20
+ class RelinkClient extends EventEmitter {
21
+ constructor({ token, key, server = "relink-iot.com", port = 7445, apiBase, mesh = true }) {
22
+ super();
23
+ if (typeof token !== "string" || !token.length || Buffer.byteLength(token) > 128 || /[\0\r\n]/.test(token)) throw new Error("A valid device token is required");
24
+ if (typeof key !== "string" || !/^[0-9a-f]{64}$/i.test(key)) throw new Error("Encryption key must contain exactly 64 hexadecimal characters");
25
+ if (typeof server !== "string" || !server || /[\s/]/.test(server)) throw new Error("Server must be a hostname or IPv4 address");
26
+ port = Number(port);
27
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("UDP port must be 1–65535");
28
+ const api = new URL(apiBase || `http://${server}:8000`);
29
+ if (!["http:", "https:"].includes(api.protocol) || api.username || api.password || api.search || api.hash || api.pathname !== "/") throw new Error("API URL must be an HTTP or HTTPS origin without credentials or a path");
30
+ this.token = token;
31
+ this.key = Buffer.from(key, "hex");
32
+ this.deviceId = crc32(Buffer.from(token));
33
+ this.server = server;
34
+ this.port = port;
35
+ // Relay ports tried in turn when the relay stops answering (UDP 7445 is
36
+ // blocked on some networks; the server redirects UDP 443 to the relay).
37
+ this.relayPorts = port === 7445 ? [7445, 443] : [port];
38
+ this.portIdx = 0;
39
+ this.portSince = monotonic();
40
+ this.lastRx = -Infinity;
41
+ this.apiBase = api.origin;
42
+ this.mesh = mesh;
43
+ this.instance = crypto.randomInt(1, 65536);
44
+ this.counter = 0n;
45
+ this.salt = 0;
46
+ this.relayNonce = 0n;
47
+ this.peers = new Map();
48
+ this.allowed = null;
49
+ this.kinds = new Map(); // pin -> declared datastream type (1 int, 2 float, 3 string, 4 bytes)
50
+ this.pending = new Map();
51
+ this.relayPending = new Map();
52
+ this.summaries = new Map();
53
+ this.requests = new Set();
54
+ this.sendQueue = [];
55
+ this.sending = false;
56
+ this.relayHz = 100;
57
+ this.relayOff = false;
58
+ this.connected = false;
59
+ this.running = false;
60
+ this.generation = 0;
61
+ this.lastG = -Infinity;
62
+ this.lastRegister = -Infinity;
63
+ this.lastRelay = -Infinity;
64
+ this.lastLinks = -Infinity;
65
+ this.lastSummary = monotonic();
66
+ this.retry = 500;
67
+ this.state = "disconnected";
68
+ // Our public addresses as STUN servers see them. Some networks pick a
69
+ // public IP per destination, so peers hello every one (sent as 'T').
70
+ this.myPublic = [];
71
+ this.lastStun = -Infinity;
72
+ this.stunTid = null;
73
+ // Camera and audio: peer-to-peer only (never through the relay), like
74
+ // the other libraries. Viewer side: pins we watch / listen to.
75
+ this.camWatch = new Set();
76
+ this.camKicked = false; // another viewer took the stream (one at a time)
77
+ this.camAsm = new Map();
78
+ this.lastCamSub = -Infinity;
79
+ this.audListen = new Set();
80
+ this.audQuality = 0; // 0 Voice 8 kHz, 1 Standard 16 kHz, 2 High 48 kHz
81
+ this.lastAudSub = -Infinity;
82
+ // Sender side: the peer that watches our camera, our audio stream state.
83
+ this.camOwner = null;
84
+ this.camFid = 0;
85
+ this.audSid = 0; this.audSeq = 0;
86
+ this.audOut = new Map(); // "pin:quality" -> Resampler
87
+ }
88
+
89
+ _status(state) {
90
+ if (this.state !== state) {
91
+ this.state = state;
92
+ this.emit("status", { state, connected: this.connected, peers: this.peerStates() });
93
+ }
94
+ }
95
+
96
+ peerStates() {
97
+ return Object.fromEntries([...this.peers].map(([id, peer]) => [id, this._reachable(peer) ? "p2p" : "relay"]));
98
+ }
99
+
100
+ // heard: its packets reach us. up: a link both ways -- its hellos say it hears
101
+ // us too (old libraries send no confirmation). On mobile data a phone often
102
+ // hears us while we can't hear it; it then sends 'F' pings through the relay
103
+ // with the address our hello reached it at, and we send pins there (reachable).
104
+ _heard(peer) { return !!peer.address && monotonic() - peer.lastRx < 5000; }
105
+ _up(peer) { return this._heard(peer) && (peer.legacy !== false || monotonic() - peer.confAt < 5000); }
106
+ _reachable(peer) { return this._up(peer) || (!!(peer.fwd || peer.candidates?.length) && monotonic() - peer.fwdRx < 5000); }
107
+ _tx(peer) { return this._up(peer) ? peer.address : peer.fwd || peer.candidates?.[0] || peer.address; }
108
+
109
+ // Hello = ['H'][flags][ip:4][port:2 BE]: the address it was sent to, which the
110
+ // receiver hands back in 'F'. Flag bit2 = "we hear you". Older readers stop at flags.
111
+ _hello(remote, ttl = 0, hear = false) {
112
+ const h = Buffer.alloc(8);
113
+ h[0] = 72; h[1] = hear ? 4 : 0;
114
+ const ip = remote.address.split(".").map(Number);
115
+ if (ip.length === 4 && ip.every(n => n >= 0 && n <= 255)) ip.forEach((n, i) => { h[2 + i] = n; });
116
+ h.writeUInt16BE(remote.port, 6);
117
+ this._send(h, remote, ttl);
118
+ }
119
+
120
+ async start() {
121
+ if (this.running) return;
122
+ this.running = true;
123
+ const generation = ++this.generation;
124
+ this._status("connecting");
125
+ try {
126
+ const result = await dns.lookup(this.server, { family: 4 });
127
+ if (!this.running || generation !== this.generation) return;
128
+ this.address = result.address;
129
+ const socket = this.socket = dgram.createSocket("udp4");
130
+ socket.on("error", () => this.emit("warning", new Error("Relink UDP transport error")));
131
+ socket.on("message", (data, remote) => this._receive(data, remote));
132
+ await new Promise((resolve, reject) => {
133
+ const failed = () => reject(new Error("Cannot bind Relink UDP socket"));
134
+ socket.once("error", failed);
135
+ socket.bind(0, "0.0.0.0", () => { socket.removeListener("error", failed); resolve(); });
136
+ });
137
+ if (!this.running || generation !== this.generation) {
138
+ try { socket.close(); } catch (_) { /* already closed during bind */ }
139
+ return;
140
+ }
141
+ // Ask the OS which interface reaches the relay; the first interface
142
+ // may be a Docker/VPN adapter and would break same-LAN punching.
143
+ const probe = dgram.createSocket("udp4");
144
+ let lanAddress = "0.0.0.0";
145
+ try {
146
+ await new Promise((resolve, reject) => { probe.once("error", reject); probe.connect(this.port, this.address, resolve); });
147
+ lanAddress = probe.address().address;
148
+ } finally { try { probe.close(); } catch (_) { /* probe never bound */ } }
149
+ if (!this.running || generation !== this.generation) return;
150
+ this.lan = `${lanAddress}:${socket.address().port}`;
151
+ this._register();
152
+ this.portSince = monotonic();
153
+ this.timer = setInterval(() => this._tick(), 2); // finer than a 100 Hz relay slot
154
+ this.pinsTimer = setInterval(() => this._refreshPins(), 30000);
155
+ await this._refreshPins();
156
+ } catch (_) {
157
+ if (this.running && generation === this.generation) {
158
+ await this.stop();
159
+ throw new Error("Cannot start Relink connection; check server and network");
160
+ }
161
+ }
162
+ }
163
+
164
+ async stop() {
165
+ this.running = false;
166
+ this.generation++;
167
+ clearInterval(this.timer);
168
+ clearInterval(this.pinsTimer);
169
+ for (const request of this.requests) request.destroy();
170
+ this.requests.clear();
171
+ this.pending.clear();
172
+ this.relayPending.clear();
173
+ this.sendQueue.length = 0;
174
+ this.summaries.clear();
175
+ this.peers.clear();
176
+ this.connected = false;
177
+ this.salt = 0;
178
+ this.allowed = null;
179
+ this.stunTid = null; this.myPublic = []; this.lastStun = -Infinity;
180
+ this.camOwner = null; this.camAsm.clear(); this.audOut.clear();
181
+ this.offset = undefined;
182
+ const socket = this.socket;
183
+ this.socket = null;
184
+ if (socket) await new Promise(resolve => { try { socket.close(resolve); } catch (_) { resolve(); } });
185
+ this._status("disconnected");
186
+ }
187
+
188
+ _nextNonce() {
189
+ const clock = (BigInt(Math.floor((performance.timeOrigin + performance.now()) * 1000)) - 1700000000000000n) & MASK48;
190
+ this.counter = this.counter + 1n > clock ? this.counter + 1n : clock;
191
+ if (this.counter > MASK48) throw new Error("Relink nonce counter exhausted");
192
+ return (BigInt(this.instance) << 48n) | this.counter;
193
+ }
194
+
195
+ _send(inner, remote, ttl = 0) {
196
+ if (!this.running || !this.socket) return;
197
+ const relay = !remote;
198
+ if (relay && !this.salt && inner[0] !== 82) return;
199
+ const destination = remote || { address: this.address, port: this.port };
200
+ const packet = seal(this.key, this.deviceId, this._nextNonce(), inner, relay ? this.salt : 0);
201
+ if (this.sendQueue.length >= 1024) return; // bounded even under socket backpressure
202
+ this.sendQueue.push({ packet, destination, ttl });
203
+ this._drainSend();
204
+ }
205
+
206
+ _drainSend() {
207
+ if (this.sending || !this.socket || !this.sendQueue.length) return;
208
+ const { packet, destination, ttl } = this.sendQueue.shift();
209
+ const socket = this.socket;
210
+ this.sending = true;
211
+ // Serialize sends because TTL applies to the socket, including async DNS/send work.
212
+ const finished = error => {
213
+ try { if (ttl && this.socket === socket) socket.setTTL(64); } catch (_) { /* socket closed */ }
214
+ this.sending = false;
215
+ if (error && this.running) this.emit("warning", new Error("Relink UDP send failed"));
216
+ this._drainSend();
217
+ };
218
+ try {
219
+ if (ttl) socket.setTTL(ttl);
220
+ socket.send(packet, destination.port, destination.address, finished);
221
+ } catch (_) { finished(true); }
222
+ }
223
+
224
+ _register() {
225
+ this.lastRegister = monotonic();
226
+ this._send(Buffer.concat([Buffer.from("R" + this.token), Buffer.from([0]), Buffer.from("MS"), Buffer.from([0]), Buffer.from(this.lan)]));
227
+ if (this.mesh) this._sendPublic(); // a restarted relay lost them
228
+ }
229
+
230
+ // ['T'][k] k x [ip:4][port:2], network order.
231
+ _sendPublic() {
232
+ if (!this.myPublic.length || !this.salt) return;
233
+ const t = Buffer.alloc(2 + 6 * this.myPublic.length);
234
+ t[0] = 84; t[1] = this.myPublic.length;
235
+ this.myPublic.forEach(({ address, port }, i) => {
236
+ address.split(".").forEach((n, k) => { t[2 + i * 6 + k] = Number(n); });
237
+ t.writeUInt16BE(port, 6 + i * 6);
238
+ });
239
+ this._send(t);
240
+ }
241
+
242
+ // Binding requests go out from the main socket: that is the mapping peers need.
243
+ async _stunKick() {
244
+ const tid = crypto.randomBytes(12);
245
+ this.stunTid = tid; this.myPublic = []; // mappings drift: start over
246
+ const req = Buffer.alloc(20);
247
+ req.writeUInt16BE(1, 0); req.writeUInt32BE(0x2112A442, 4); tid.copy(req, 8);
248
+ const servers = [[this.server, 3478], ["stun.l.google.com", 19302], ["stun.cloudflare.com", 3478]];
249
+ await Promise.all(servers.map(async ([host, port]) => {
250
+ try {
251
+ const { address } = await dns.lookup(host, { family: 4 });
252
+ for (let r = 0; r < 2; r++) if (this.socket && this.stunTid === tid) this.socket.send(req, port, address, () => {});
253
+ } catch (_) { /* that STUN server is unreachable; the others may answer */ }
254
+ }));
255
+ }
256
+
257
+ // Binding success: XOR-MAPPED-ADDRESS (or MAPPED-ADDRESS) for our transaction.
258
+ _onStun(b) {
259
+ if (!this.stunTid || b.readUInt32BE(4) !== 0x2112A442 || !b.subarray(8, 20).equals(this.stunTid)) return;
260
+ const len = b.readUInt16BE(2) + 20;
261
+ if (len > b.length) return;
262
+ for (let p = 20; p + 4 <= len;) {
263
+ const type = b.readUInt16BE(p), al = b.readUInt16BE(p + 2), v = p + 4;
264
+ if (v + al > len) break;
265
+ if ((type === 0x0020 || type === 0x0001) && al >= 8 && b[v + 1] === 1) {
266
+ let port = b.readUInt16BE(v + 2), ip = b.readUInt32BE(v + 4);
267
+ if (type === 0x0020) { port ^= 0x2112; ip = (ip ^ 0x2112A442) >>> 0; }
268
+ const address = [ip >>> 24, (ip >>> 16) & 255, (ip >>> 8) & 255, ip & 255].join(".");
269
+ if (this.myPublic.length < 3 && !this.myPublic.some(a => a.address === address && a.port === port)) {
270
+ this.myPublic.push({ address, port });
271
+ this._sendPublic();
272
+ }
273
+ return;
274
+ }
275
+ p = v + ((al + 3) & ~3);
276
+ }
277
+ }
278
+
279
+ write(pin, value, type = "auto") {
280
+ if (!this.running) throw new Error("Relink connection is not running");
281
+ // The datastream's type wins over Automatic and over the node's choice,
282
+ // so the bytes are right on direct links too (Integer -> Int16 when it fits).
283
+ const kind = this.kinds.get(pinNumber(pin));
284
+ if (kind) {
285
+ const c = coerceKind(kind, value, type);
286
+ if (!c) throw new Error("Payload doesn't fit this datastream's type");
287
+ value = c.value; type = c.type;
288
+ }
289
+ const entry = encodeEntry(pin, value, type);
290
+ pin = entry[0];
291
+ if (this.allowed && !this.allowed.has(pin)) throw new Error("Pin is not declared in this device's datastreams");
292
+ // One latest value per pin bounds memory during outages, like the relay.
293
+ this.pending.set(pin, entry);
294
+ if (entry[1] <= 2 || entry[1] === 5 || entry[1] === 6) {
295
+ const v = decodeValue(entry[1], entry.subarray(2));
296
+ const s = this.summaries.get(pin);
297
+ if (s) { s.n++; s.min = Math.min(s.min, v); s.max = Math.max(s.max, v); s.sum += v; s.last = v; }
298
+ else this.summaries.set(pin, { n: 1, min: v, max: v, sum: v, last: v });
299
+ }
300
+ }
301
+
302
+ _batches(entries) {
303
+ const batches = [];
304
+ let batch = [], length = 0;
305
+ for (const entry of entries) {
306
+ if (batch.length && (length + entry.length > 1060 || batch.length === 255)) {
307
+ batches.push(Buffer.concat([Buffer.from([68, batch.length]), ...batch]));
308
+ batch = []; length = 0;
309
+ }
310
+ batch.push(entry); length += entry.length;
311
+ }
312
+ if (batch.length) batches.push(Buffer.concat([Buffer.from([68, batch.length]), ...batch]));
313
+ return batches;
314
+ }
315
+
316
+ _flush(now) {
317
+ const entries = [...this.pending.values()].filter(e => !this.allowed || this.allowed.has(e[0]));
318
+ this.pending.clear();
319
+ const peers = this.allowed && this.mesh ? [...this.peers.values()] : [];
320
+ const direct = peers.length > 0 && peers.every(p => this._reachable(p));
321
+ const relay = !(direct && (this.relayOff || peers.some(p => p.gateway)));
322
+ if (relay) for (const entry of entries) this.relayPending.set(entry[0], entry);
323
+ else this.relayPending.clear();
324
+ // Existing direct paths keep working even when the relay has been offline for a minute.
325
+ // Relay pacing never limits the direct mesh copy.
326
+ for (const body of this._batches(entries)) {
327
+ for (const peer of peers) if (this._reachable(peer)) this._send(body, this._tx(peer));
328
+ }
329
+ if (relay && this.connected && this.salt && this.relayPending.size && (!this.relayHz || now - this.lastRelay >= 1000 / this.relayHz)) {
330
+ // Advance on the schedule, not to `now`: timer jitter would otherwise let two
331
+ // writes share one slot and drop a value at exactly relayHz. Catch-up is capped
332
+ // at half a slot so a late tick never turns into a burst.
333
+ const slot = this.relayHz ? 1000 / this.relayHz : 0;
334
+ this.lastRelay = Math.max(this.lastRelay + slot, now - slot / 2);
335
+ const latest = [...this.relayPending.values()].filter(e => !this.allowed || this.allowed.has(e[0]));
336
+ this.relayPending.clear();
337
+ for (const body of this._batches(latest)) this._send(body);
338
+ }
339
+ }
340
+
341
+ _links(force = false) {
342
+ if (!this.salt) return;
343
+ const links = this.mesh && this.allowed ? [...this.peers].filter(([, p]) => this._reachable(p)).map(([id]) => id).sort((a, b) => a - b) : [];
344
+ const signature = links.join(",");
345
+ if (!force && signature === this.links && monotonic() - this.lastLinks < 25000) return;
346
+ this.links = signature; this.lastLinks = monotonic();
347
+ const body = Buffer.alloc(2 + links.length * 2);
348
+ body[0] = 76; body[1] = links.length;
349
+ links.forEach((id, i) => body.writeUInt16LE(id, 2 + i * 2));
350
+ this._send(body);
351
+ }
352
+
353
+ _summary() {
354
+ const entries = [...this.summaries].filter(([p]) => !this.allowed || this.allowed.has(p));
355
+ // At most 55 entries fit the SDK's MTU budget (19 bytes per pin).
356
+ for (let i = 0; i < entries.length; i += 55) {
357
+ const chunk = entries.slice(i, i + 55);
358
+ const body = Buffer.alloc(2 + 19 * chunk.length);
359
+ body[0] = 77; body[1] = chunk.length;
360
+ chunk.forEach(([pin, s], n) => {
361
+ const p = 2 + n * 19;
362
+ body[p] = pin; body.writeUInt16LE(Math.min(s.n, 65535), p + 1);
363
+ [s.min, s.max, s.sum / s.n, s.last].forEach((v, k) => body.writeFloatLE(v, p + 3 + k * 4));
364
+ });
365
+ this._send(body);
366
+ }
367
+ this.summaries.clear();
368
+ }
369
+
370
+ _tick() {
371
+ if (!this.running) return;
372
+ const now = monotonic();
373
+ // Relay silent (never answered, or 60 s since it last did): its port may
374
+ // be blocked on this network. Move to the next one; same packets go there.
375
+ if (this.relayPorts.length > 1 && now - this.portSince >= 10000 &&
376
+ now - this.lastRx >= (this.connected ? 60000 : 10000)) {
377
+ this.portIdx = (this.portIdx + 1) % this.relayPorts.length;
378
+ this.port = this.relayPorts[this.portIdx];
379
+ this.portSince = now;
380
+ this.connected = false; this.salt = 0; this.retry = 500;
381
+ this.lastRegister = -Infinity; // register now, then every 0.5 s doubling
382
+ this._status("connecting");
383
+ }
384
+ if (this.connected && now - this.lastRx >= 60000) {
385
+ this.connected = false; this.salt = 0; this.retry = 500;
386
+ this._status("connecting");
387
+ }
388
+ if (now - this.lastRegister >= (this.connected ? 25000 : this.retry)) {
389
+ this._register();
390
+ if (!this.connected) this.retry = Math.min(this.retry * 2, 8000);
391
+ }
392
+ if (this.mesh && this.allowed) for (const peer of this.peers.values()) {
393
+ const heard = this._heard(peer);
394
+ // We hear it, it can't hear us: keep our address fresh at its end
395
+ // through the relay ('F' ping) so it can still send to us directly.
396
+ if (heard && !this._up(peer) && this.salt && now - peer.lastPing >= 1000) {
397
+ peer.lastPing = now;
398
+ const f = Buffer.alloc(10);
399
+ f[0] = 70; f.writeUInt16LE(peer.id, 1);
400
+ if (now - peer.reachAt < 5000) peer.reach.copy(f, 3);
401
+ f[9] = 80;
402
+ this._send(f);
403
+ }
404
+ const priming = !heard && now - peer.since < 1500;
405
+ if (now - peer.lastHello < (priming ? 250 : 1000)) continue;
406
+ peer.lastHello = now;
407
+ const destinations = heard ? [peer.address] : peer.candidates;
408
+ destinations.forEach((remote, i) => this._hello(remote, priming && i === 0 ? 2 : 0, heard));
409
+ }
410
+ if (this.mesh && this.connected && now - this.lastStun >= 300000) { this.lastStun = now; this._stunKick(); }
411
+ if (this.mesh && this.allowed && this.salt) {
412
+ if (this.camWatch.size && !this.camKicked && now - this.lastCamSub >= CAM_SUB_EVERY) {
413
+ this.lastCamSub = now; this._ctl(Buffer.from([67, 1]));
414
+ }
415
+ if (this.audListen.size && now - this.lastAudSub >= CAM_SUB_EVERY) {
416
+ this.lastAudSub = now;
417
+ for (const pin of this.audListen) this._ctl(Buffer.from([97, pin, 1, this.audQuality]));
418
+ }
419
+ }
420
+ this._links();
421
+ this._flush(now);
422
+ if (this.salt && this.connected && now - this.lastSummary >= 60000) {
423
+ this._summary(); this.lastSummary = now;
424
+ }
425
+ }
426
+
427
+ _receive(data, remote) {
428
+ if (!this.running) return;
429
+ try {
430
+ if (data.length === 1 && data[0] === 71 && remote.address === this.address) {
431
+ const now = monotonic();
432
+ if (now - this.lastG < 5000) return;
433
+ this.lastG = now; this.salt = 0; this.connected = false;
434
+ this.lastRegister = now - this.retry + crypto.randomInt(0, 5000);
435
+ this._status("connecting");
436
+ return;
437
+ }
438
+ if (data.length >= 32 && data[0] === 1 && data[1] === 1) { this._onStun(data); return; }
439
+ const { nonce, inner } = open(this.key, this.deviceId, data);
440
+ const instance = Number(nonce >> 48n);
441
+ if (instance === 0) {
442
+ if (remote.address !== this.address || nonce <= this.relayNonce || inner.length < 3 || inner.readUInt16LE() !== this.instance) return;
443
+ this.relayNonce = nonce;
444
+ this._server(inner.subarray(2));
445
+ return;
446
+ }
447
+ const peer = this.peers.get(instance);
448
+ if (!this.mesh || !this.allowed || instance === this.instance) return;
449
+ if (!peer) {
450
+ // Sealed by an instance the relay hasn't listed (it just restarted and
451
+ // its 'N' was lost): register now (<= 1/s) to get the list.
452
+ const now = monotonic();
453
+ if (this.connected && now - (this.unknownReg || -Infinity) >= 1000) { this.unknownReg = now; this.lastRegister = -Infinity; }
454
+ return;
455
+ }
456
+ if (!this._fresh(peer, nonce)) return;
457
+ const now = monotonic();
458
+ const wasHeard = this._heard(peer), wasUp = this._up(peer);
459
+ peer.address = { address: remote.address, port: remote.port }; peer.lastRx = now;
460
+ if (inner[0] === 72) {
461
+ peer.gateway = inner.length > 1 && !!(inner[1] & 1);
462
+ if (inner.length >= 8) {
463
+ inner.copy(peer.reach, 0, 2, 8); peer.reachAt = now; peer.legacy = false;
464
+ if (inner[1] & 4) peer.confAt = now;
465
+ } else peer.legacy = true;
466
+ }
467
+ if (!wasHeard) this._hello(peer.address, 0, true);
468
+ if (wasUp !== this._up(peer)) this._links(true);
469
+ if (inner[0] === 68) this._dispatch(decodeBatch(inner, true), "p2p");
470
+ else if (inner[0] === 74) this._camSlice(inner);
471
+ else if (inner[0] === 65 || inner[0] === 119) this._audioIn(inner);
472
+ else if (inner[0] === 67 || (inner[0] === 97 && inner.length >= 3)) this._peerCtl(instance, peer, inner);
473
+ else if (inner[0] === 75 && !this.camKicked) { this.camKicked = true; this.emit("camera-kicked"); }
474
+ } catch (_) { /* Invalid, forged, or truncated datagrams never reach flows. */ }
475
+ }
476
+
477
+ _fresh(peer, nonce) {
478
+ if (!peer.top || nonce > peer.top) {
479
+ const shift = peer.top ? nonce - peer.top : 1024n;
480
+ peer.bits = shift >= 1024n ? 1n : ((peer.bits << shift) | 1n) & WINDOW_MASK;
481
+ peer.top = nonce; return true;
482
+ }
483
+ const back = peer.top - nonce;
484
+ if (back >= 1024n || ((peer.bits >> back) & 1n)) return false;
485
+ peer.bits |= 1n << back;
486
+ return true;
487
+ }
488
+
489
+ _server(frame) {
490
+ if (frame[0] === 89 && frame.length === 5) {
491
+ const salt = frame.readUInt32LE(1);
492
+ if (!salt) return;
493
+ this.salt = salt; this.lastRx = monotonic();
494
+ this._register();
495
+ // The salted register is now sent; subsequent authenticated replies keep it alive.
496
+ this.connected = true; this.retry = 500; this._status("connected");
497
+ return;
498
+ }
499
+ if (!this.salt) return;
500
+ this.lastRx = monotonic();
501
+ if (frame[0] === 90 && frame.length === 1) { this._refreshPins(); return; } // 'Z': datastreams/types changed
502
+ if (frame[0] === 78) this._peerList(frame);
503
+ else if (frame[0] === 70 && frame.length >= 10 && this.mesh) this._forward(frame);
504
+ else if (frame[0] === 77) this._dispatch(decodeBatch(frame), "relay");
505
+ else if ((frame[0] === 83 || frame[0] === 35) && frame.length >= 3) {
506
+ if (frame[0] === 35 && frame[1] === 15) return;
507
+ this._dispatch([{ pin: frame[1], type: NAMES[frame[2]], value: decodeValue(frame[2], frame.subarray(3)) }], "relay");
508
+ }
509
+ }
510
+
511
+ // ['F'][from:u16 LE][reach_ip:4][reach_port:2 BE][msg] from the relay: a peer
512
+ // that can't reach us directly; reach = where our hello arrived (port 0 = unknown).
513
+ // Node-RED takes no camera / audio, so only the address matters.
514
+ _forward(frame) {
515
+ const peer = this.peers.get(frame.readUInt16LE(1));
516
+ if (!peer) return;
517
+ const was = this._reachable(peer);
518
+ const port = frame.readUInt16BE(7);
519
+ if (port) peer.fwd = { address: [...frame.subarray(3, 7)].join("."), port };
520
+ peer.fwdRx = monotonic();
521
+ if (!was) this._links(true);
522
+ const m = frame.subarray(9);
523
+ if (m[0] === 67 || (m[0] === 97 && m.length >= 3)) this._peerCtl(frame.readUInt16LE(1), peer, m);
524
+ }
525
+
526
+ // A camera / audio subscribe to every listed peer: directly when it answers,
527
+ // and always through the relay ('F') too -- on mobile data a peer often can't
528
+ // hear us directly even while we hear it.
529
+ _ctl(msg) {
530
+ const now = monotonic();
531
+ for (const [id, peer] of this.peers) {
532
+ if (this._up(peer)) this._send(msg, peer.address);
533
+ const f = Buffer.alloc(9 + msg.length);
534
+ f[0] = 70; f.writeUInt16LE(id, 1);
535
+ if (now - peer.reachAt < 5000) peer.reach.copy(f, 3);
536
+ msg.copy(f, 9);
537
+ this._send(f);
538
+ }
539
+ }
540
+
541
+ // A viewer's camera subscribe ['C'][on] or a listener's ['a'][pin][on][quality].
542
+ // A viewer that starts watching takes the stream over; the one it replaces gets 'K'.
543
+ _peerCtl(id, peer, m) {
544
+ const now = monotonic();
545
+ if (m[0] === 97) { peer.audQ = m.length >= 4 ? Math.min(m[3], 2) : 0; peer.audRx = m[2] ? now : -Infinity; return; }
546
+ const on = m.length < 2 || !!m[1];
547
+ const starting = on && now - peer.camRx > CAM_SUB_TIMEOUT;
548
+ peer.camRx = on ? now : -Infinity;
549
+ if (starting && this.camOwner !== id) {
550
+ const old = this.peers.get(this.camOwner);
551
+ if (old && this._reachable(old)) { this._send(Buffer.from("K"), this._tx(old)); old.camRx = -Infinity; }
552
+ this.camOwner = id;
553
+ } else if (!on && this.camOwner === id) this.camOwner = null;
554
+ }
555
+
556
+ _camSlice(inner) {
557
+ if (inner.length < 8 || !this.camWatch.has(inner[1])) return;
558
+ const pin = inner[1];
559
+ let asm = this.camAsm.get(pin);
560
+ if (!asm) this.camAsm.set(pin, asm = new CamAssembly());
561
+ const frame = asm.add(inner.readUInt16LE(2), inner.readUInt16LE(4), inner.readUInt16LE(6), inner.subarray(8));
562
+ if (frame) this.emit("camera", { pin, frame, frameId: inner.readUInt16LE(2), checksum: this.deviceId });
563
+ }
564
+
565
+ _audioIn(inner) {
566
+ const pin = inner[1];
567
+ if (!this.audListen.has(pin)) return;
568
+ let samples, rate;
569
+ if (inner[0] === 65 && inner.length > 6) {
570
+ samples = Int16Array.from(inner.subarray(6), b => ULAW_DEC[b]); rate = 8000;
571
+ } else if (inner[0] === 119 && inner.length > 7 && (inner[6] === 1 || inner[6] === 2)) {
572
+ const n = Math.min((inner.length - 7) >> 1, 960);
573
+ samples = new Int16Array(n);
574
+ for (let i = 0; i < n; i++) samples[i] = inner.readInt16LE(7 + 2 * i);
575
+ rate = AUDIO_RATES[inner[6]];
576
+ } else return;
577
+ this.emit("audio", { pin, samples, rate, checksum: this.deviceId });
578
+ }
579
+
580
+ // Viewer: ask the devices on this token for camera frames on pin.
581
+ watchCamera(pin, on = true) {
582
+ pin = pinNumber(pin);
583
+ if (on) { this.camWatch.add(pin); this.camKicked = false; this.lastCamSub = -Infinity; }
584
+ else {
585
+ this.camWatch.delete(pin); this.camAsm.delete(pin);
586
+ if (!this.camWatch.size && this.salt) this._ctl(Buffer.from([67, 0]));
587
+ }
588
+ }
589
+
590
+ // Listener: ask for sound on pin at a quality (0 Voice, 1 Standard, 2 High).
591
+ listenAudio(pin, on = true, quality = this.audQuality) {
592
+ pin = pinNumber(pin);
593
+ this.audQuality = Math.max(0, Math.min(2, quality | 0));
594
+ if (on) { this.audListen.add(pin); this.lastAudSub = -Infinity; }
595
+ else { this.audListen.delete(pin); if (this.salt) this._ctl(Buffer.from([97, pin, 0, this.audQuality])); }
596
+ }
597
+
598
+ // True while a peer watches our camera: check before grabbing a frame.
599
+ cameraWanted() {
600
+ const peer = this.camOwner !== null ? this.peers.get(this.camOwner) : null;
601
+ return !!(peer && this._reachable(peer) && monotonic() - peer.camRx <= CAM_SUB_TIMEOUT);
602
+ }
603
+
604
+ // One JPEG frame to the viewer, in 1024-byte encrypted slices straight to it.
605
+ // false = nobody watches (nothing sent).
606
+ cameraWrite(pin, jpeg) {
607
+ pin = pinNumber(pin);
608
+ if (!Buffer.isBuffer(jpeg)) throw new Error("Camera frame must be a Buffer (JPEG)");
609
+ const cnt = Math.ceil(jpeg.length / CAM_CHUNK);
610
+ if (!cnt || cnt > 400 || !this.cameraWanted()) return false; // 400 KB: the send queue bound
611
+ const to = this._tx(this.peers.get(this.camOwner));
612
+ const fid = this.camFid; this.camFid = (this.camFid + 1) & 0xffff;
613
+ for (let i = 0; i < cnt; i++) {
614
+ const piece = jpeg.subarray(i * CAM_CHUNK, (i + 1) * CAM_CHUNK);
615
+ const h = Buffer.alloc(8);
616
+ h[0] = 74; h[1] = pin; h.writeUInt16LE(fid, 2); h.writeUInt16LE(i, 4); h.writeUInt16LE(cnt, 6);
617
+ this._send(Buffer.concat([h, piece]), to);
618
+ }
619
+ return true;
620
+ }
621
+
622
+ // Signed 16-bit mono samples (Int16Array, array, or s16le Buffer) at rate Hz
623
+ // to every direct peer; each gets the quality it asked for (ESP32s and
624
+ // older listeners: Voice). A partial packet waits for the next call.
625
+ audioWrite(pin, samples, rate = 8000) {
626
+ pin = pinNumber(pin);
627
+ if (Buffer.isBuffer(samples)) samples = new Int16Array(samples.buffer.slice(samples.byteOffset, samples.byteOffset + (samples.length & ~1)));
628
+ if (!Number.isInteger(rate) || rate < 4000 || rate > 192000) throw new Error("Audio rate must be 4000–192000 Hz");
629
+ if (!this.audSid) this.audSid = crypto.randomInt(1, 0xffff) | 1;
630
+ const to = [[], [], []];
631
+ const now = monotonic();
632
+ for (const peer of this.peers.values()) {
633
+ if (!this._reachable(peer)) continue;
634
+ // A peer that asked for a quality in the last 3 s gets it; others Voice.
635
+ to[now - peer.audRx <= CAM_SUB_TIMEOUT ? peer.audQ : 0].push(this._tx(peer));
636
+ }
637
+ let sent = 0;
638
+ for (let q = 0; q < 3; q++) {
639
+ const key = `${pin}:${q}`;
640
+ if (!to[q].length) { this.audOut.delete(key); continue; }
641
+ let o = this.audOut.get(key);
642
+ if (!o || o.inRate !== rate) this.audOut.set(key, o = new Resampler(rate, AUDIO_RATES[q]));
643
+ o.push(samples);
644
+ const per = AUDIO_PER[q];
645
+ while (o.pend.length >= per) {
646
+ const chunk = o.pend.splice(0, per);
647
+ let pkt;
648
+ if (q === 0) {
649
+ pkt = Buffer.alloc(6 + per); pkt[0] = 65;
650
+ chunk.forEach((x, i) => { pkt[6 + i] = ulawEncode(x); });
651
+ } else {
652
+ pkt = Buffer.alloc(7 + 2 * per); pkt[0] = 119; pkt[6] = q;
653
+ chunk.forEach((x, i) => pkt.writeInt16LE(x, 7 + 2 * i));
654
+ }
655
+ pkt[1] = pin; pkt.writeUInt16LE(this.audSid, 2); pkt.writeUInt16LE(this.audSeq, 4);
656
+ this.audSeq = (this.audSeq + 1) & 0xffff;
657
+ for (const a of to[q]) this._send(pkt, a);
658
+ sent++;
659
+ }
660
+ }
661
+ return sent;
662
+ }
663
+
664
+ _peerList(frame) {
665
+ if (frame.length < 2 || frame.length < 2 + frame[1] * 14) return;
666
+ const seen = new Set();
667
+ for (let i = 0; i < frame[1]; i++) {
668
+ const p = 2 + i * 14, id = frame.readUInt16LE(p);
669
+ if (!id || id === this.instance) continue;
670
+ seen.add(id);
671
+ const candidate = offset => ({ address: [...frame.subarray(offset, offset + 4)].join("."), port: frame.readUInt16BE(offset + 4) });
672
+ const candidates = [candidate(p + 2), candidate(p + 8)].filter(a => a.port && a.address !== "0.0.0.0");
673
+ const peer = this.peers.get(id);
674
+ if (peer) peer.candidates = candidates;
675
+ else this.peers.set(id, { id, candidates, since: monotonic(), lastHello: -Infinity, lastRx: -Infinity, gateway: false, top: 0n, bits: 0n,
676
+ legacy: true, confAt: -Infinity, reach: Buffer.alloc(6), reachAt: -Infinity, fwd: null, fwdRx: -Infinity, lastPing: -Infinity,
677
+ camRx: -Infinity, audQ: 0, audRx: -Infinity });
678
+ }
679
+ for (const id of this.peers.keys()) if (!seen.has(id)) this.peers.delete(id);
680
+ const trailer = 2 + frame[1] * 14;
681
+ if (frame.length >= trailer + 2) this.relayHz = frame.readUInt16LE(trailer);
682
+ this.relayOff = frame.length >= trailer + 3 && !!(frame[trailer + 2] & 1);
683
+ // Extension: [x] x [instance:u16][k] k x [ip:4][port:2] -- a peer's other
684
+ // public addresses (its network picks one per destination); hello each.
685
+ let q = trailer + 3;
686
+ if (q < frame.length) {
687
+ const x = frame[q++];
688
+ for (let i = 0; i < x && q + 3 <= frame.length; i++) {
689
+ const peer = this.peers.get(frame.readUInt16LE(q)), k = frame[q + 2];
690
+ q += 3;
691
+ for (let j = 0; j < k && q + 6 <= frame.length; j++, q += 6) {
692
+ const a = { address: [...frame.subarray(q, q + 4)].join("."), port: frame.readUInt16BE(q + 4) };
693
+ if (peer && a.port && !peer.candidates.some(c => c.address === a.address && c.port === a.port)) peer.candidates.push(a);
694
+ }
695
+ }
696
+ }
697
+ }
698
+
699
+ _dispatch(entries, transport) {
700
+ for (let entry of entries) {
701
+ if (this.allowed && !this.allowed.has(entry.pin)) continue;
702
+ // A direct peer with an old library may still send another type.
703
+ const kind = this.kinds.get(entry.pin);
704
+ if (kind) {
705
+ const c = coerceKind(kind, entry.value, entry.type);
706
+ if (!c) continue;
707
+ entry = { ...entry, value: c.value, type: c.type };
708
+ }
709
+ this.emit("pin", { ...entry, transport, checksum: this.deviceId });
710
+ }
711
+ }
712
+
713
+ _get(path, headers = {}) {
714
+ const url = new URL(path, this.apiBase);
715
+ return new Promise((resolve, reject) => {
716
+ const request = (url.protocol === "https:" ? https : http).get(url, { headers, timeout: 3000 }, response => {
717
+ let length = 0;
718
+ const chunks = [];
719
+ response.on("data", chunk => {
720
+ length += chunk.length;
721
+ if (length > 65536) request.destroy(new Error("Relink API response too large"));
722
+ else chunks.push(chunk);
723
+ });
724
+ response.on("error", () => reject(new Error("Relink API response interrupted")));
725
+ response.on("end", () => {
726
+ if (response.statusCode !== 200) {
727
+ if (response.statusCode === 401) this.offset = undefined;
728
+ reject(new Error("Relink API request refused"));
729
+ } else {
730
+ try { resolve(JSON.parse(Buffer.concat(chunks).toString())); }
731
+ catch (_) { reject(new Error("Invalid Relink API response")); }
732
+ }
733
+ });
734
+ });
735
+ this.requests.add(request);
736
+ request.on("timeout", () => request.destroy(new Error("Relink API timeout")));
737
+ request.on("error", () => reject(new Error("Relink API unavailable")));
738
+ request.on("close", () => this.requests.delete(request));
739
+ });
740
+ }
741
+
742
+ async _refreshPins() {
743
+ if (!this.running || this.refreshing) return;
744
+ this.refreshing = true;
745
+ const generation = this.generation;
746
+ try {
747
+ if (this.offset === undefined) {
748
+ const result = await this._get("/api/time");
749
+ if (!Number.isFinite(result.t)) throw new Error("Invalid server clock");
750
+ this.offset = result.t - Date.now() / 1000;
751
+ }
752
+ if (!this.running || generation !== this.generation) return;
753
+ const path = `/api/d/${this.deviceId}/allowed-pins`;
754
+ const ts = String(Math.floor(Date.now() / 1000 + this.offset));
755
+ const nonce = crypto.randomBytes(16).toString("hex");
756
+ const mac = crypto.createHmac("sha256", this.key).update(`relink-api-v1\0GET\0${path}\0${ts}\0${nonce}\0`).digest("hex");
757
+ const result = await this._get(path, { "X-Relink-Auth": `${ts}.${nonce}.${mac}` });
758
+ if (!this.running || generation !== this.generation) return;
759
+ if (typeof result.pins !== "string" || !/^-1(?:,\d{1,3})*$/.test(result.pins)) throw new Error("Invalid allowed pin list");
760
+ this.allowed = new Set(result.pins.split(",").slice(1).map(pinNumber));
761
+ this.kinds = parseKinds(result.types); // an old server sends none: nothing converted
762
+ } catch (_) {
763
+ if (this.running && generation === this.generation) this.emit("warning", new Error("Cannot refresh Relink datastreams; keeping the previous list and using relay until mesh is authorized"));
764
+ } finally { this.refreshing = false; }
765
+ }
766
+ }
767
+
768
+ module.exports = { RelinkClient };