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

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Relink IoT
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,150 @@
1
- # Temporary Holding Version
1
+ # Relink for Node-RED
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Connect Node-RED to the same virtual pins as an ESP32, Python script or C++ program on [Relink](https://relink-iot.com). One shared connection gives encrypted UDP, relay fallback, direct device mesh and numeric history summaries. No runtime npm dependencies.
4
+
5
+ Needs Node.js 18+ and Node-RED 3+.
6
+
7
+ ## Available nodes
8
+
9
+ | Node | Purpose |
10
+ |---|---|
11
+ | **Relink connection** | Shared server settings and device credentials; one encrypted UDP endpoint |
12
+ | **relink in** | Receive one pin or all pins from the dashboard and other endpoints |
13
+ | **relink out** | Write a fixed pin or choose a pin from each incoming message |
14
+
15
+ ```text
16
+ ESP32 / Python / C++ ← binary UDP mesh → Relink connection
17
+ │
18
+ relink in → Debug
19
+ relink out ← Inject / Function
20
+ ```
21
+
22
+ The relay supplies peer addresses and handles fallback. Once peers establish a direct path, their pin data can travel directly between endpoints.
23
+
24
+ ## Install
25
+
26
+ In Node-RED: **Menu → Manage palette → Install**, search for `node-red-contrib-relink`, then Install.
27
+
28
+ Or from your Node-RED user directory (normally `~/.node-red`), then restart Node-RED:
29
+
30
+ ```bash
31
+ cd ~/.node-red
32
+ npm install node-red-contrib-relink
33
+ ```
34
+
35
+ The palette's Network category then shows **relink in** and **relink out**.
36
+
37
+ ## 1. Settings
38
+
39
+ Create a test device in Relink and add **V0 Float**, **V1 Integer**, and optionally **V2 ByteArray**. Copy its token and encryption key. Programs sharing both join one device; avoid writing to an actuator unless that is intended.
40
+
41
+ Drag **relink in** onto a flow. Open it, add a **Relink connection**, and enter:
42
+
43
+ | Field | Value |
44
+ |---|---|
45
+ | Server | Your relay hostname or IPv4 address, such as `relink-iot.com` |
46
+ | UDP port | `7445`, unless configured otherwise |
47
+ | API URL | Your API origin, such as `https://relink-iot.com`; do not append `/api` |
48
+ | Device token | From the device page |
49
+ | Encryption key | The device's 64-character hexadecimal key |
50
+ | Direct mesh | Enabled to attempt direct UDP links to the other endpoints |
51
+
52
+ The token and key use Node-RED's credential system, rather than ordinary flow properties. They are omitted from exported example flows. Configure Node-RED's own credential encryption for your installation. A missing or malformed key is rejected; plaintext fallback is not supported.
53
+
54
+ ## 2. Connect
55
+
56
+ Deploy. The status changes from **connecting** to **connected** after the relay's authenticated session handshake. All in/out nodes using one connection share one UDP endpoint. Different connection configurations create separate endpoints.
57
+
58
+ Signed HTTP requests fetch declared pins every 30 seconds. If the API is unavailable at startup, the relay continues to enforce the pin list and direct mesh waits for authorization. After a successful fetch, an API outage retains the previous list. The UDP connection re-registers after relay outages without blocking other flows.
59
+
60
+ Mesh uses Relink's existing binary UDP protocol: a sealed `N` peer list supplies public and LAN candidates, encrypted `H` hellos open the direct path, and `D` batches carry pin values. A short-TTL priming phase precedes public-address punching, matching the host SDK approach. The relay receives `L` link reports to avoid duplicate forwarding. Direct peers use the unsalted device envelope; relay uplink uses its session salt. Existing direct links continue carrying data when the relay session expires. Actual NAT reachability depends on both networks; relay fallback remains available.
61
+
62
+ Pin values, including ByteArray Buffers, are binary on UDP rather than JSON or base64. JSON is used for API metadata and Node-RED flow import/export only. If a dashboard is connected through an ESP32 WebRTC gateway, the gateway can carry this endpoint's mesh values to that browser.
63
+
64
+ ## 3. Handlers: receive values
65
+
66
+ Connect **relink in → Debug**. Leave Pin empty to receive all pins, or enter `V1` to filter.
67
+
68
+ ```javascript
69
+ {
70
+ topic: "V1",
71
+ pin: 1,
72
+ payload: 42,
73
+ dtype: "int32",
74
+ transport: "relay",
75
+ checksum: 123456789
76
+ }
77
+ ```
78
+
79
+ `transport` is `relay` or `p2p`. `payload` is a number, string, or Buffer. No token or encryption key is added to messages. Own writes do not produce a local echo.
80
+
81
+ `msg.dtype` reports the actual wire type of that update. It does not prove the value matched the type selected on the Relink datastream page.
82
+
83
+ ## 4. Loop: write values
84
+
85
+ Connect **Inject → relink out**. Set Inject's numeric payload to `23.5`, select pin `V0` in relink out, and choose **Float**. Click Inject; a dashboard widget or another SDK endpoint on the same device should receive it. For periodic readings, set Inject's repeat interval.
86
+
87
+ Leave the output node's Pin blank for dynamic routing: `msg.pin` takes priority over `msg.topic`. A topic such as `V2` selects pin 2.
88
+
89
+ | Payload / selected type | Wire value |
90
+ |---|---|
91
+ | Whole number, Automatic | Int16 when it fits; otherwise Int32 |
92
+ | Fractional number, Automatic | Float32 |
93
+ | Boolean, Automatic | Int16 0 or 1 |
94
+ | String | UTF-8 text, up to 255 bytes |
95
+ | Buffer | ByteArray, up to 255 bytes |
96
+
97
+ Choose the type explicitly when required by your datastream: for example, a whole-number reading for a Float datastream should use **Float**. Objects, non-finite numbers, out-of-range integers, and oversized values are rejected through Node-RED's Catch mechanism. Values are never silently truncated.
98
+
99
+ ### Integer and binary examples
100
+
101
+ For **V1 Integer**, configure relink out with Pin `V1` and Data type **Int32**, then inject the number `1`. Explicit integer selections reject a fractional payload such as `32.5`.
102
+
103
+ | Explicit selection | Equivalent | Bytes | Range / encoding |
104
+ |---|---|---|---|
105
+ | Int16 | `int16_t`, wire dtype 0 | 2 | −32,768 to 32,767, little-endian |
106
+ | Int32 | `int32_t`, wire dtype 1 | 4 | −2,147,483,648 to 2,147,483,647, little-endian |
107
+ | Float | Float32, wire dtype 2 | 4 | Finite IEEE 754 single-precision, little-endian |
108
+ | String | Wire dtype 3 | Up to 255 | UTF-8 bytes |
109
+ | ByteArray | Wire dtype 4 | Up to 255 | Raw Buffer bytes |
110
+
111
+ The dashboard's generic **Integer** declaration does not currently choose or enforce Int16 versus Int32. In Automatic mode, whole numbers use Int16 when they fit, otherwise Int32; numbers outside Int32 range are rejected. Fractional numbers use Float, regardless of the dashboard declaration.
112
+
113
+ For **V2 ByteArray**, use a Function node connected to relink out with Pin `V2` and Data type **ByteArray**:
114
+
115
+ ```javascript
116
+ msg.payload = Buffer.from([0x00, 0xff, 0x80, 0x01]);
117
+ return msg;
118
+ ```
119
+
120
+ The receiving endpoint gets those exact four bytes. Do not JSON-stringify the Buffer or encode it as base64 before sending it to relink out.
121
+
122
+ Writes are coalesced to the latest value per pin, including during an outage. Pending values are in memory only and cleared on redeploy. Completion means queued, not acknowledged by the destination. High-rate intermediate values may be coalesced. Numeric history uses minute summaries, matching the host SDK protocol.
123
+
124
+ Import **Menu → Import → Examples → node-red-contrib-relink → basic**, or import `examples/basic.json`. It contains no credentials and sends only when Inject is clicked; configure the connection first.
125
+
126
+ The `bytes` example uses a binary Inject payload and V2 ByteArray. Its bytes stay a Buffer throughout the flow and are sent as binary UDP data.
127
+
128
+ ## Known limitations
129
+
130
+ - **Declared datastream types are not enforced end to end.** The signed API supplies allowed pin numbers, without type metadata. Node-RED Automatic mode infers the type from the payload, and relink in decodes the sender's actual wire type. An Integer datastream can therefore receive `32.5` sent by another endpoint as Float. A dashboard slider can display rounded `33` while transmitting `32.50`. Explicit Int16/Int32 on relink out protects that node's own writes, but does not validate other senders. The fix must cover every datastream type across UI, SDKs, relay, and direct P2P. Binary stress-test success does not close this bug.
131
+ - **Intermediate writes can be coalesced.** The latest-value queue makes this a state-update client, rather than a lossless stream of every submitted value. Two writers on the same device/pin also share the relay's rate cap.
132
+ - **Transport status describes the relay connection.** Input messages report their actual path in `msg.transport`. A previously established direct path can continue while the relay reconnects.
133
+ - **Camera frames, browser WebRTC, and firmware flashing are not implemented by this package.** Browser dashboards can still communicate with this endpoint through an ESP32 gateway or the relay. No server wire-format change is required by this package.
134
+ - **Separate-network NAT and ESP32 hardware remain unverified for this package.** Direct UDP and relay interoperability were tested on one machine; network conditions can prevent hole punching.
135
+
136
+ ## Troubleshooting
137
+
138
+ | Symptom | Check |
139
+ |---|---|
140
+ | Relink nodes are missing from the palette | Install in the user directory used by the running Node-RED, then restart it and search for `relink` |
141
+ | Connection stays at connecting | Device token/key, relay hostname, outbound UDP access, and server port |
142
+ | Relay works but direct mesh does not | Enable mesh; verify the API origin and signed pin-list fetch; allow time for peer discovery; some NATs require relay fallback |
143
+ | No pin values arrive | Declare the pin as a datastream, check the input filter, and send from another endpoint; own writes have no local echo |
144
+ | Integer pin receives a fraction | Inspect `msg.dtype` and the sender; see the declared-type enforcement limitation above |
145
+ | A write fails | Connect a Catch node; check pin, payload type, integer range, and the 255-byte text/Buffer limit |
146
+ | Values skip during high-rate traffic | Compare offered and transmitted values; latest values replace intermediate writes, and relay limits apply per device/pin |
147
+
148
+ ## License
149
+
150
+ MIT
@@ -0,0 +1,9 @@
1
+ [
2
+ { "id": "relink-basic", "type": "tab", "label": "Relink basics", "disabled": false, "info": "1. settings: edit the Relink connection with your device token/key; add V0 Float and V1 Integer datastreams. 2. connect: Deploy. 3. handlers: received pins appear in Debug. 4. loop: the Inject sends V0 once a second when enabled." },
3
+ { "id": "relink-device", "type": "relink-connection", "name": "My Relink device", "server": "relink-iot.com", "port": 7445, "apiBase": "https://relink-iot.com", "mesh": true },
4
+ { "id": "relink-in", "type": "relink in", "z": "relink-basic", "name": "Receive all pins", "connection": "relink-device", "pin": "", "x": 180, "y": 120, "wires": [["relink-debug"]] },
5
+ { "id": "relink-debug", "type": "debug", "z": "relink-basic", "name": "Pin values", "active": true, "tosidebar": true, "console": false, "tostatus": false, "complete": "true", "targetType": "full", "x": 440, "y": 120, "wires": [] },
6
+ { "id": "relink-inject", "type": "inject", "z": "relink-basic", "name": "Send 23.5 on V0", "props": [{"p":"payload"},{"p":"topic","vt":"str"}], "repeat": "", "crontab": "", "once": false, "onceDelay": 0.1, "topic": "V0", "payload": "23.5", "payloadType": "num", "x": 190, "y": 200, "wires": [["relink-out"]] },
7
+ { "id": "relink-out", "type": "relink out", "z": "relink-basic", "name": "Write V0", "connection": "relink-device", "pin": "0", "dtype": "float", "x": 450, "y": 200, "wires": [] },
8
+ { "id": "relink-catch", "type": "catch", "z": "relink-basic", "name": "Write errors", "scope": ["relink-out"], "uncaught": false, "x": 190, "y": 280, "wires": [["relink-debug"]] }
9
+ ]
@@ -0,0 +1,8 @@
1
+ [
2
+ { "id": "relink-bytes", "type": "tab", "label": "Relink ByteArray", "disabled": false, "info": "1. settings: declare V2 ByteArray on a test device and fill in the connection credentials. 2. connect: Deploy. 3. handlers: Debug shows received Buffers. 4. loop: click Inject to send bytes; no automatic writes." },
3
+ { "id": "relink-bytes-device", "type": "relink-connection", "name": "My Relink device", "server": "relink-iot.com", "port": 7445, "apiBase": "https://relink-iot.com", "mesh": true },
4
+ { "id": "relink-bytes-in", "type": "relink in", "z": "relink-bytes", "name": "Receive V2 bytes", "connection": "relink-bytes-device", "pin": "2", "x": 180, "y": 100, "wires": [["relink-bytes-debug"]] },
5
+ { "id": "relink-bytes-debug", "type": "debug", "z": "relink-bytes", "name": "Binary buffer", "active": true, "tosidebar": true, "console": false, "tostatus": false, "complete": "true", "targetType": "full", "x": 450, "y": 100, "wires": [] },
6
+ { "id": "relink-bytes-inject", "type": "inject", "z": "relink-bytes", "name": "Send 00 ff 80 01", "props": [{"p":"payload"},{"p":"topic","vt":"str"}], "repeat": "", "crontab": "", "once": false, "onceDelay": 0.1, "topic": "V2", "payload": "[0,255,128,1]", "payloadType": "bin", "x": 190, "y": 180, "wires": [["relink-bytes-out"]] },
7
+ { "id": "relink-bytes-out", "type": "relink out", "z": "relink-bytes", "name": "Write binary V2", "connection": "relink-bytes-device", "pin": "2", "dtype": "bytes", "x": 450, "y": 180, "wires": [] }
8
+ ]
package/lib/client.js ADDED
@@ -0,0 +1,523 @@
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
+
12
+ const MASK48 = (1n << 48n) - 1n;
13
+ const WINDOW_MASK = (1n << 1024n) - 1n;
14
+ const monotonic = () => performance.now();
15
+
16
+ class RelinkClient extends EventEmitter {
17
+ constructor({ token, key, server = "relink-iot.com", port = 7445, apiBase, mesh = true }) {
18
+ super();
19
+ if (typeof token !== "string" || !token.length || Buffer.byteLength(token) > 128 || /[\0\r\n]/.test(token)) throw new Error("A valid device token is required");
20
+ if (typeof key !== "string" || !/^[0-9a-f]{64}$/i.test(key)) throw new Error("Encryption key must contain exactly 64 hexadecimal characters");
21
+ if (typeof server !== "string" || !server || /[\s/]/.test(server)) throw new Error("Server must be a hostname or IPv4 address");
22
+ port = Number(port);
23
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("UDP port must be 1–65535");
24
+ const api = new URL(apiBase || `http://${server}:8000`);
25
+ 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");
26
+ this.token = token;
27
+ this.key = Buffer.from(key, "hex");
28
+ this.deviceId = crc32(Buffer.from(token));
29
+ this.server = server;
30
+ this.port = port;
31
+ // Relay ports tried in turn when the relay stops answering (UDP 7445 is
32
+ // blocked on some networks; the server redirects UDP 443 to the relay).
33
+ this.relayPorts = port === 7445 ? [7445, 443] : [port];
34
+ this.portIdx = 0;
35
+ this.portSince = monotonic();
36
+ this.lastRx = -Infinity;
37
+ this.apiBase = api.origin;
38
+ this.mesh = mesh;
39
+ this.instance = crypto.randomInt(1, 65536);
40
+ this.counter = 0n;
41
+ this.salt = 0;
42
+ this.relayNonce = 0n;
43
+ this.peers = new Map();
44
+ this.allowed = null;
45
+ this.kinds = new Map(); // pin -> declared datastream type (1 int, 2 float, 3 string, 4 bytes)
46
+ this.pending = new Map();
47
+ this.relayPending = new Map();
48
+ this.summaries = new Map();
49
+ this.requests = new Set();
50
+ this.sendQueue = [];
51
+ this.sending = false;
52
+ this.relayHz = 100;
53
+ this.relayOff = false;
54
+ this.connected = false;
55
+ this.running = false;
56
+ this.generation = 0;
57
+ this.lastG = -Infinity;
58
+ this.lastRegister = -Infinity;
59
+ this.lastRelay = -Infinity;
60
+ this.lastLinks = -Infinity;
61
+ this.lastSummary = monotonic();
62
+ this.retry = 500;
63
+ this.state = "disconnected";
64
+ }
65
+
66
+ _status(state) {
67
+ if (this.state !== state) {
68
+ this.state = state;
69
+ this.emit("status", { state, connected: this.connected, peers: this.peerStates() });
70
+ }
71
+ }
72
+
73
+ peerStates() {
74
+ return Object.fromEntries([...this.peers].map(([id, peer]) => [id, this._reachable(peer) ? "p2p" : "relay"]));
75
+ }
76
+
77
+ // heard: its packets reach us. up: a link both ways -- its hellos say it hears
78
+ // us too (old libraries send no confirmation). On mobile data a phone often
79
+ // hears us while we can't hear it; it then sends 'F' pings through the relay
80
+ // with the address our hello reached it at, and we send pins there (reachable).
81
+ _heard(peer) { return !!peer.address && monotonic() - peer.lastRx < 5000; }
82
+ _up(peer) { return this._heard(peer) && (peer.legacy !== false || monotonic() - peer.confAt < 5000); }
83
+ _reachable(peer) { return this._up(peer) || (!!(peer.fwd || peer.candidates?.length) && monotonic() - peer.fwdRx < 5000); }
84
+ _tx(peer) { return this._up(peer) ? peer.address : peer.fwd || peer.candidates?.[0] || peer.address; }
85
+
86
+ // Hello = ['H'][flags][ip:4][port:2 BE]: the address it was sent to, which the
87
+ // receiver hands back in 'F'. Flag bit2 = "we hear you". Older readers stop at flags.
88
+ _hello(remote, ttl = 0, hear = false) {
89
+ const h = Buffer.alloc(8);
90
+ h[0] = 72; h[1] = hear ? 4 : 0;
91
+ const ip = remote.address.split(".").map(Number);
92
+ if (ip.length === 4 && ip.every(n => n >= 0 && n <= 255)) ip.forEach((n, i) => { h[2 + i] = n; });
93
+ h.writeUInt16BE(remote.port, 6);
94
+ this._send(h, remote, ttl);
95
+ }
96
+
97
+ async start() {
98
+ if (this.running) return;
99
+ this.running = true;
100
+ const generation = ++this.generation;
101
+ this._status("connecting");
102
+ try {
103
+ const result = await dns.lookup(this.server, { family: 4 });
104
+ if (!this.running || generation !== this.generation) return;
105
+ this.address = result.address;
106
+ const socket = this.socket = dgram.createSocket("udp4");
107
+ socket.on("error", () => this.emit("warning", new Error("Relink UDP transport error")));
108
+ socket.on("message", (data, remote) => this._receive(data, remote));
109
+ await new Promise((resolve, reject) => {
110
+ const failed = () => reject(new Error("Cannot bind Relink UDP socket"));
111
+ socket.once("error", failed);
112
+ socket.bind(0, "0.0.0.0", () => { socket.removeListener("error", failed); resolve(); });
113
+ });
114
+ if (!this.running || generation !== this.generation) {
115
+ try { socket.close(); } catch (_) { /* already closed during bind */ }
116
+ return;
117
+ }
118
+ // Ask the OS which interface reaches the relay; the first interface
119
+ // may be a Docker/VPN adapter and would break same-LAN punching.
120
+ const probe = dgram.createSocket("udp4");
121
+ let lanAddress = "0.0.0.0";
122
+ try {
123
+ await new Promise((resolve, reject) => { probe.once("error", reject); probe.connect(this.port, this.address, resolve); });
124
+ lanAddress = probe.address().address;
125
+ } finally { try { probe.close(); } catch (_) { /* probe never bound */ } }
126
+ if (!this.running || generation !== this.generation) return;
127
+ this.lan = `${lanAddress}:${socket.address().port}`;
128
+ this._register();
129
+ this.portSince = monotonic();
130
+ this.timer = setInterval(() => this._tick(), 2); // finer than a 100 Hz relay slot
131
+ this.pinsTimer = setInterval(() => this._refreshPins(), 30000);
132
+ await this._refreshPins();
133
+ } catch (_) {
134
+ if (this.running && generation === this.generation) {
135
+ await this.stop();
136
+ throw new Error("Cannot start Relink connection; check server and network");
137
+ }
138
+ }
139
+ }
140
+
141
+ async stop() {
142
+ this.running = false;
143
+ this.generation++;
144
+ clearInterval(this.timer);
145
+ clearInterval(this.pinsTimer);
146
+ for (const request of this.requests) request.destroy();
147
+ this.requests.clear();
148
+ this.pending.clear();
149
+ this.relayPending.clear();
150
+ this.sendQueue.length = 0;
151
+ this.summaries.clear();
152
+ this.peers.clear();
153
+ this.connected = false;
154
+ this.salt = 0;
155
+ this.allowed = null;
156
+ this.offset = undefined;
157
+ const socket = this.socket;
158
+ this.socket = null;
159
+ if (socket) await new Promise(resolve => { try { socket.close(resolve); } catch (_) { resolve(); } });
160
+ this._status("disconnected");
161
+ }
162
+
163
+ _nextNonce() {
164
+ const clock = (BigInt(Math.floor((performance.timeOrigin + performance.now()) * 1000)) - 1700000000000000n) & MASK48;
165
+ this.counter = this.counter + 1n > clock ? this.counter + 1n : clock;
166
+ if (this.counter > MASK48) throw new Error("Relink nonce counter exhausted");
167
+ return (BigInt(this.instance) << 48n) | this.counter;
168
+ }
169
+
170
+ _send(inner, remote, ttl = 0) {
171
+ if (!this.running || !this.socket) return;
172
+ const relay = !remote;
173
+ if (relay && !this.salt && inner[0] !== 82) return;
174
+ const destination = remote || { address: this.address, port: this.port };
175
+ const packet = seal(this.key, this.deviceId, this._nextNonce(), inner, relay ? this.salt : 0);
176
+ if (this.sendQueue.length >= 512) return; // bounded even under socket backpressure
177
+ this.sendQueue.push({ packet, destination, ttl });
178
+ this._drainSend();
179
+ }
180
+
181
+ _drainSend() {
182
+ if (this.sending || !this.socket || !this.sendQueue.length) return;
183
+ const { packet, destination, ttl } = this.sendQueue.shift();
184
+ const socket = this.socket;
185
+ this.sending = true;
186
+ // Serialize sends because TTL applies to the socket, including async DNS/send work.
187
+ const finished = error => {
188
+ try { if (ttl && this.socket === socket) socket.setTTL(64); } catch (_) { /* socket closed */ }
189
+ this.sending = false;
190
+ if (error && this.running) this.emit("warning", new Error("Relink UDP send failed"));
191
+ this._drainSend();
192
+ };
193
+ try {
194
+ if (ttl) socket.setTTL(ttl);
195
+ socket.send(packet, destination.port, destination.address, finished);
196
+ } catch (_) { finished(true); }
197
+ }
198
+
199
+ _register() {
200
+ this.lastRegister = monotonic();
201
+ this._send(Buffer.concat([Buffer.from("R" + this.token), Buffer.from([0]), Buffer.from("MS"), Buffer.from([0]), Buffer.from(this.lan)]));
202
+ }
203
+
204
+ write(pin, value, type = "auto") {
205
+ if (!this.running) throw new Error("Relink connection is not running");
206
+ // The datastream's type wins over Automatic and over the node's choice,
207
+ // so the bytes are right on direct links too (Integer -> Int16 when it fits).
208
+ const kind = this.kinds.get(pinNumber(pin));
209
+ if (kind) {
210
+ const c = coerceKind(kind, value);
211
+ if (!c) throw new Error("Payload doesn't fit this datastream's type");
212
+ value = c.value; type = c.type;
213
+ }
214
+ const entry = encodeEntry(pin, value, type);
215
+ pin = entry[0];
216
+ if (this.allowed && !this.allowed.has(pin)) throw new Error("Pin is not declared in this device's datastreams");
217
+ // One latest value per pin bounds memory during outages, like the relay.
218
+ this.pending.set(pin, entry);
219
+ if (entry[1] <= 2) {
220
+ const v = decodeValue(entry[1], entry.subarray(2));
221
+ const s = this.summaries.get(pin);
222
+ if (s) { s.n++; s.min = Math.min(s.min, v); s.max = Math.max(s.max, v); s.sum += v; s.last = v; }
223
+ else this.summaries.set(pin, { n: 1, min: v, max: v, sum: v, last: v });
224
+ }
225
+ }
226
+
227
+ _batches(entries) {
228
+ const batches = [];
229
+ let batch = [], length = 0;
230
+ for (const entry of entries) {
231
+ if (batch.length && (length + entry.length > 1060 || batch.length === 255)) {
232
+ batches.push(Buffer.concat([Buffer.from([68, batch.length]), ...batch]));
233
+ batch = []; length = 0;
234
+ }
235
+ batch.push(entry); length += entry.length;
236
+ }
237
+ if (batch.length) batches.push(Buffer.concat([Buffer.from([68, batch.length]), ...batch]));
238
+ return batches;
239
+ }
240
+
241
+ _flush(now) {
242
+ const entries = [...this.pending.values()].filter(e => !this.allowed || this.allowed.has(e[0]));
243
+ this.pending.clear();
244
+ const peers = this.allowed && this.mesh ? [...this.peers.values()] : [];
245
+ const direct = peers.length > 0 && peers.every(p => this._reachable(p));
246
+ const relay = !(direct && (this.relayOff || peers.some(p => p.gateway)));
247
+ if (relay) for (const entry of entries) this.relayPending.set(entry[0], entry);
248
+ else this.relayPending.clear();
249
+ // Existing direct paths keep working even when the relay has been offline for a minute.
250
+ // Relay pacing never limits the direct mesh copy.
251
+ for (const body of this._batches(entries)) {
252
+ for (const peer of peers) if (this._reachable(peer)) this._send(body, this._tx(peer));
253
+ }
254
+ if (relay && this.connected && this.salt && this.relayPending.size && (!this.relayHz || now - this.lastRelay >= 1000 / this.relayHz)) {
255
+ // Advance on the schedule, not to `now`: timer jitter would otherwise let two
256
+ // writes share one slot and drop a value at exactly relayHz. Catch-up is capped
257
+ // at half a slot so a late tick never turns into a burst.
258
+ const slot = this.relayHz ? 1000 / this.relayHz : 0;
259
+ this.lastRelay = Math.max(this.lastRelay + slot, now - slot / 2);
260
+ const latest = [...this.relayPending.values()].filter(e => !this.allowed || this.allowed.has(e[0]));
261
+ this.relayPending.clear();
262
+ for (const body of this._batches(latest)) this._send(body);
263
+ }
264
+ }
265
+
266
+ _links(force = false) {
267
+ if (!this.salt) return;
268
+ const links = this.mesh && this.allowed ? [...this.peers].filter(([, p]) => this._reachable(p)).map(([id]) => id).sort((a, b) => a - b) : [];
269
+ const signature = links.join(",");
270
+ if (!force && signature === this.links && monotonic() - this.lastLinks < 25000) return;
271
+ this.links = signature; this.lastLinks = monotonic();
272
+ const body = Buffer.alloc(2 + links.length * 2);
273
+ body[0] = 76; body[1] = links.length;
274
+ links.forEach((id, i) => body.writeUInt16LE(id, 2 + i * 2));
275
+ this._send(body);
276
+ }
277
+
278
+ _summary() {
279
+ const entries = [...this.summaries].filter(([p]) => !this.allowed || this.allowed.has(p));
280
+ // At most 55 entries fit the SDK's MTU budget (19 bytes per pin).
281
+ for (let i = 0; i < entries.length; i += 55) {
282
+ const chunk = entries.slice(i, i + 55);
283
+ const body = Buffer.alloc(2 + 19 * chunk.length);
284
+ body[0] = 77; body[1] = chunk.length;
285
+ chunk.forEach(([pin, s], n) => {
286
+ const p = 2 + n * 19;
287
+ body[p] = pin; body.writeUInt16LE(Math.min(s.n, 65535), p + 1);
288
+ [s.min, s.max, s.sum / s.n, s.last].forEach((v, k) => body.writeFloatLE(v, p + 3 + k * 4));
289
+ });
290
+ this._send(body);
291
+ }
292
+ this.summaries.clear();
293
+ }
294
+
295
+ _tick() {
296
+ if (!this.running) return;
297
+ const now = monotonic();
298
+ // Relay silent (never answered, or 60 s since it last did): its port may
299
+ // be blocked on this network. Move to the next one; same packets go there.
300
+ if (this.relayPorts.length > 1 && now - this.portSince >= 10000 &&
301
+ now - this.lastRx >= (this.connected ? 60000 : 10000)) {
302
+ this.portIdx = (this.portIdx + 1) % this.relayPorts.length;
303
+ this.port = this.relayPorts[this.portIdx];
304
+ this.portSince = now;
305
+ this.connected = false; this.salt = 0; this.retry = 500;
306
+ this.lastRegister = -Infinity; // register now, then every 0.5 s doubling
307
+ this._status("connecting");
308
+ }
309
+ if (this.connected && now - this.lastRx >= 60000) {
310
+ this.connected = false; this.salt = 0; this.retry = 500;
311
+ this._status("connecting");
312
+ }
313
+ if (now - this.lastRegister >= (this.connected ? 25000 : this.retry)) {
314
+ this._register();
315
+ if (!this.connected) this.retry = Math.min(this.retry * 2, 8000);
316
+ }
317
+ if (this.mesh && this.allowed) for (const peer of this.peers.values()) {
318
+ const heard = this._heard(peer);
319
+ // We hear it, it can't hear us: keep our address fresh at its end
320
+ // through the relay ('F' ping) so it can still send to us directly.
321
+ if (heard && !this._up(peer) && this.salt && now - peer.lastPing >= 1000) {
322
+ peer.lastPing = now;
323
+ const f = Buffer.alloc(10);
324
+ f[0] = 70; f.writeUInt16LE(peer.id, 1);
325
+ if (now - peer.reachAt < 5000) peer.reach.copy(f, 3);
326
+ f[9] = 80;
327
+ this._send(f);
328
+ }
329
+ const priming = !heard && now - peer.since < 1500;
330
+ if (now - peer.lastHello < (priming ? 250 : 1000)) continue;
331
+ peer.lastHello = now;
332
+ const destinations = heard ? [peer.address] : peer.candidates;
333
+ destinations.forEach((remote, i) => this._hello(remote, priming && i === 0 ? 2 : 0, heard));
334
+ }
335
+ this._links();
336
+ this._flush(now);
337
+ if (this.salt && this.connected && now - this.lastSummary >= 60000) {
338
+ this._summary(); this.lastSummary = now;
339
+ }
340
+ }
341
+
342
+ _receive(data, remote) {
343
+ if (!this.running) return;
344
+ try {
345
+ if (data.length === 1 && data[0] === 71 && remote.address === this.address) {
346
+ const now = monotonic();
347
+ if (now - this.lastG < 5000) return;
348
+ this.lastG = now; this.salt = 0; this.connected = false;
349
+ this.lastRegister = now - this.retry + crypto.randomInt(0, 5000);
350
+ this._status("connecting");
351
+ return;
352
+ }
353
+ const { nonce, inner } = open(this.key, this.deviceId, data);
354
+ const instance = Number(nonce >> 48n);
355
+ if (instance === 0) {
356
+ if (remote.address !== this.address || nonce <= this.relayNonce || inner.length < 3 || inner.readUInt16LE() !== this.instance) return;
357
+ this.relayNonce = nonce;
358
+ this._server(inner.subarray(2));
359
+ return;
360
+ }
361
+ const peer = this.peers.get(instance);
362
+ if (!this.mesh || !this.allowed || instance === this.instance) return;
363
+ if (!peer) {
364
+ // Sealed by an instance the relay hasn't listed (it just restarted and
365
+ // its 'N' was lost): register now (<= 1/s) to get the list.
366
+ const now = monotonic();
367
+ if (this.connected && now - (this.unknownReg || -Infinity) >= 1000) { this.unknownReg = now; this.lastRegister = -Infinity; }
368
+ return;
369
+ }
370
+ if (!this._fresh(peer, nonce)) return;
371
+ const now = monotonic();
372
+ const wasHeard = this._heard(peer), wasUp = this._up(peer);
373
+ peer.address = { address: remote.address, port: remote.port }; peer.lastRx = now;
374
+ if (inner[0] === 72) {
375
+ peer.gateway = inner.length > 1 && !!(inner[1] & 1);
376
+ if (inner.length >= 8) {
377
+ inner.copy(peer.reach, 0, 2, 8); peer.reachAt = now; peer.legacy = false;
378
+ if (inner[1] & 4) peer.confAt = now;
379
+ } else peer.legacy = true;
380
+ }
381
+ if (!wasHeard) this._hello(peer.address, 0, true);
382
+ if (wasUp !== this._up(peer)) this._links(true);
383
+ if (inner[0] === 68) this._dispatch(decodeBatch(inner, true), "p2p");
384
+ } catch (_) { /* Invalid, forged, or truncated datagrams never reach flows. */ }
385
+ }
386
+
387
+ _fresh(peer, nonce) {
388
+ if (!peer.top || nonce > peer.top) {
389
+ const shift = peer.top ? nonce - peer.top : 1024n;
390
+ peer.bits = shift >= 1024n ? 1n : ((peer.bits << shift) | 1n) & WINDOW_MASK;
391
+ peer.top = nonce; return true;
392
+ }
393
+ const back = peer.top - nonce;
394
+ if (back >= 1024n || ((peer.bits >> back) & 1n)) return false;
395
+ peer.bits |= 1n << back;
396
+ return true;
397
+ }
398
+
399
+ _server(frame) {
400
+ if (frame[0] === 89 && frame.length === 5) {
401
+ const salt = frame.readUInt32LE(1);
402
+ if (!salt) return;
403
+ this.salt = salt; this.lastRx = monotonic();
404
+ this._register();
405
+ // The salted register is now sent; subsequent authenticated replies keep it alive.
406
+ this.connected = true; this.retry = 500; this._status("connected");
407
+ return;
408
+ }
409
+ if (!this.salt) return;
410
+ this.lastRx = monotonic();
411
+ if (frame[0] === 90 && frame.length === 1) { this._refreshPins(); return; } // 'Z': datastreams/types changed
412
+ if (frame[0] === 78) this._peerList(frame);
413
+ else if (frame[0] === 70 && frame.length >= 10 && this.mesh) this._forward(frame);
414
+ else if (frame[0] === 77) this._dispatch(decodeBatch(frame), "relay");
415
+ else if ((frame[0] === 83 || frame[0] === 35) && frame.length >= 3) {
416
+ if (frame[0] === 35 && frame[1] === 15) return;
417
+ this._dispatch([{ pin: frame[1], type: NAMES[frame[2]], value: decodeValue(frame[2], frame.subarray(3)) }], "relay");
418
+ }
419
+ }
420
+
421
+ // ['F'][from:u16 LE][reach_ip:4][reach_port:2 BE][msg] from the relay: a peer
422
+ // that can't reach us directly; reach = where our hello arrived (port 0 = unknown).
423
+ // Node-RED takes no camera / audio, so only the address matters.
424
+ _forward(frame) {
425
+ const peer = this.peers.get(frame.readUInt16LE(1));
426
+ if (!peer) return;
427
+ const was = this._reachable(peer);
428
+ const port = frame.readUInt16BE(7);
429
+ if (port) peer.fwd = { address: [...frame.subarray(3, 7)].join("."), port };
430
+ peer.fwdRx = monotonic();
431
+ if (!was) this._links(true);
432
+ }
433
+
434
+ _peerList(frame) {
435
+ if (frame.length < 2 || frame.length < 2 + frame[1] * 14) return;
436
+ const seen = new Set();
437
+ for (let i = 0; i < frame[1]; i++) {
438
+ const p = 2 + i * 14, id = frame.readUInt16LE(p);
439
+ if (!id || id === this.instance) continue;
440
+ seen.add(id);
441
+ const candidate = offset => ({ address: [...frame.subarray(offset, offset + 4)].join("."), port: frame.readUInt16BE(offset + 4) });
442
+ const candidates = [candidate(p + 2), candidate(p + 8)].filter(a => a.port && a.address !== "0.0.0.0");
443
+ const peer = this.peers.get(id);
444
+ if (peer) peer.candidates = candidates;
445
+ else this.peers.set(id, { id, candidates, since: monotonic(), lastHello: -Infinity, lastRx: -Infinity, gateway: false, top: 0n, bits: 0n,
446
+ legacy: true, confAt: -Infinity, reach: Buffer.alloc(6), reachAt: -Infinity, fwd: null, fwdRx: -Infinity, lastPing: -Infinity });
447
+ }
448
+ for (const id of this.peers.keys()) if (!seen.has(id)) this.peers.delete(id);
449
+ const trailer = 2 + frame[1] * 14;
450
+ if (frame.length >= trailer + 2) this.relayHz = frame.readUInt16LE(trailer);
451
+ this.relayOff = frame.length >= trailer + 3 && !!(frame[trailer + 2] & 1);
452
+ }
453
+
454
+ _dispatch(entries, transport) {
455
+ for (let entry of entries) {
456
+ if (this.allowed && !this.allowed.has(entry.pin)) continue;
457
+ // A direct peer with an old library may still send another type.
458
+ const kind = this.kinds.get(entry.pin);
459
+ if (kind) {
460
+ const c = coerceKind(kind, entry.value);
461
+ if (!c) continue;
462
+ entry = { ...entry, value: c.value, type: c.type };
463
+ }
464
+ this.emit("pin", { ...entry, transport, checksum: this.deviceId });
465
+ }
466
+ }
467
+
468
+ _get(path, headers = {}) {
469
+ const url = new URL(path, this.apiBase);
470
+ return new Promise((resolve, reject) => {
471
+ const request = (url.protocol === "https:" ? https : http).get(url, { headers, timeout: 3000 }, response => {
472
+ let length = 0;
473
+ const chunks = [];
474
+ response.on("data", chunk => {
475
+ length += chunk.length;
476
+ if (length > 65536) request.destroy(new Error("Relink API response too large"));
477
+ else chunks.push(chunk);
478
+ });
479
+ response.on("error", () => reject(new Error("Relink API response interrupted")));
480
+ response.on("end", () => {
481
+ if (response.statusCode !== 200) {
482
+ if (response.statusCode === 401) this.offset = undefined;
483
+ reject(new Error("Relink API request refused"));
484
+ } else {
485
+ try { resolve(JSON.parse(Buffer.concat(chunks).toString())); }
486
+ catch (_) { reject(new Error("Invalid Relink API response")); }
487
+ }
488
+ });
489
+ });
490
+ this.requests.add(request);
491
+ request.on("timeout", () => request.destroy(new Error("Relink API timeout")));
492
+ request.on("error", () => reject(new Error("Relink API unavailable")));
493
+ request.on("close", () => this.requests.delete(request));
494
+ });
495
+ }
496
+
497
+ async _refreshPins() {
498
+ if (!this.running || this.refreshing) return;
499
+ this.refreshing = true;
500
+ const generation = this.generation;
501
+ try {
502
+ if (this.offset === undefined) {
503
+ const result = await this._get("/api/time");
504
+ if (!Number.isFinite(result.t)) throw new Error("Invalid server clock");
505
+ this.offset = result.t - Date.now() / 1000;
506
+ }
507
+ if (!this.running || generation !== this.generation) return;
508
+ const path = `/api/d/${this.deviceId}/allowed-pins`;
509
+ const ts = String(Math.floor(Date.now() / 1000 + this.offset));
510
+ const nonce = crypto.randomBytes(16).toString("hex");
511
+ const mac = crypto.createHmac("sha256", this.key).update(`relink-api-v1\0GET\0${path}\0${ts}\0${nonce}\0`).digest("hex");
512
+ const result = await this._get(path, { "X-Relink-Auth": `${ts}.${nonce}.${mac}` });
513
+ if (!this.running || generation !== this.generation) return;
514
+ if (typeof result.pins !== "string" || !/^-1(?:,\d{1,3})*$/.test(result.pins)) throw new Error("Invalid allowed pin list");
515
+ this.allowed = new Set(result.pins.split(",").slice(1).map(pinNumber));
516
+ this.kinds = parseKinds(result.types); // an old server sends none: nothing converted
517
+ } catch (_) {
518
+ 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"));
519
+ } finally { this.refreshing = false; }
520
+ }
521
+ }
522
+
523
+ module.exports = { RelinkClient };
@@ -0,0 +1,149 @@
1
+ "use strict";
2
+
3
+ const crypto = require("node:crypto");
4
+
5
+ const TYPES = Object.freeze({ int16: 0, int32: 1, float: 2, string: 3, bytes: 4 });
6
+ const NAMES = Object.keys(TYPES);
7
+ const CRC_TABLE = Array.from({ length: 256 }, (_, n) => {
8
+ for (let i = 0; i < 8; i++) n = (n & 1) ? 0xedb88320 ^ (n >>> 1) : n >>> 1;
9
+ return n >>> 0;
10
+ });
11
+
12
+ function crc32(data) {
13
+ let crc = 0xffffffff;
14
+ for (const byte of data) crc = CRC_TABLE[(crc ^ byte) & 255] ^ (crc >>> 8);
15
+ return (crc ^ 0xffffffff) >>> 0;
16
+ }
17
+
18
+ function pinNumber(value) {
19
+ if (typeof value === "string" && /^(?:V)?\d{1,3}$/i.test(value)) value = Number(value.replace(/^v/i, ""));
20
+ if (!Number.isInteger(value) || value < 0 || value > 255) throw new Error("Pin must be V0–V255");
21
+ return value;
22
+ }
23
+
24
+ function encodeEntry(pin, value, type = "auto") {
25
+ pin = pinNumber(pin);
26
+ if (type === "auto") {
27
+ if (Buffer.isBuffer(value)) type = "bytes";
28
+ else if (typeof value === "string") type = "string";
29
+ else if (typeof value === "boolean") type = "int16";
30
+ else if (typeof value === "number") type = Number.isInteger(value) ? (value >= -32768 && value <= 32767 ? "int16" : "int32") : "float";
31
+ else throw new Error("Payload must be a number, boolean, string, or Buffer");
32
+ }
33
+ if (!Object.hasOwn(TYPES, type)) throw new Error("Unsupported Relink data type");
34
+ let body;
35
+ if (type === "bytes" || type === "string") {
36
+ if (type === "bytes" && !Buffer.isBuffer(value)) throw new Error("ByteArray payload must be a Buffer");
37
+ if (type === "string" && typeof value !== "string") throw new Error("String payload must be text");
38
+ const bytes = type === "bytes" ? value : Buffer.from(value, "utf8");
39
+ if (bytes.length > 255) throw new Error("Text and ByteArray values must be at most 255 bytes");
40
+ body = Buffer.concat([Buffer.from([bytes.length]), bytes]);
41
+ } else {
42
+ if (typeof value === "boolean") value = Number(value);
43
+ if (typeof value !== "number" || !Number.isFinite(value)) throw new Error("Numeric payload must be a finite number");
44
+ if (type === "int16" || type === "int32") {
45
+ const min = type === "int16" ? -32768 : -2147483648;
46
+ const max = type === "int16" ? 32767 : 2147483647;
47
+ if (!Number.isInteger(value) || value < min || value > max) throw new Error("Integer payload is outside its data type range");
48
+ body = Buffer.alloc(type === "int16" ? 2 : 4);
49
+ if (type === "int16") body.writeInt16LE(value); else body.writeInt32LE(value);
50
+ } else {
51
+ body = Buffer.alloc(4);
52
+ body.writeFloatLE(value);
53
+ if (!Number.isFinite(body.readFloatLE())) throw new Error("Float payload exceeds float32 range");
54
+ }
55
+ }
56
+ return Buffer.concat([Buffer.from([pin, TYPES[type]]), body]);
57
+ }
58
+
59
+ // Declared datastream kinds from the signed allowed-pins reply ("types": "0:2,1:1").
60
+ const KINDS = Object.freeze({ 1: "int", 2: "float", 3: "string", 4: "bytes" });
61
+
62
+ // The value as the pin's declared type -- same rule as relink_udp and the
63
+ // other libraries: numbers convert (Integer rounds half away from zero and
64
+ // must fit Int32), numbers become text on a String pin, text is accepted on
65
+ // a ByteArray pin. Returns { value, type } with the wire type name, or null
66
+ // when the value can't be the declared type. kind undefined = no conversion.
67
+ function coerceKind(kind, value) {
68
+ if (!kind) return null;
69
+ if (typeof value === "boolean") value = Number(value);
70
+ const isNum = typeof value === "number";
71
+ switch (KINDS[kind]) {
72
+ case "int": {
73
+ if (!isNum || !Number.isFinite(value)) return null;
74
+ let i = Math.sign(value) * Math.round(Math.abs(value));
75
+ if (i === 0) i = 0;
76
+ if (i < -2147483648 || i > 2147483647) return null;
77
+ return { value: i, type: i >= -32768 && i <= 32767 ? "int16" : "int32" };
78
+ }
79
+ case "float": return isNum ? { value: Math.fround(value), type: "float" } : null;
80
+ case "string":
81
+ if (typeof value === "string") return { value, type: "string" };
82
+ return isNum ? { value: Number.isInteger(value) ? String(value) : String(Number(Math.fround(value).toPrecision(6))), type: "string" } : null;
83
+ case "bytes":
84
+ if (Buffer.isBuffer(value)) return { value, type: "bytes" };
85
+ return typeof value === "string" ? { value: Buffer.from(value, "utf8"), type: "bytes" } : null;
86
+ }
87
+ return null;
88
+ }
89
+
90
+ function parseKinds(text) {
91
+ const kinds = new Map();
92
+ for (const item of String(text || "").split(",")) {
93
+ const m = /^(\d{1,3}):([1-4])$/.exec(item);
94
+ if (m && Number(m[1]) <= 255) kinds.set(Number(m[1]), Number(m[2]));
95
+ }
96
+ return kinds;
97
+ }
98
+
99
+ function decodeValue(type, body) {
100
+ if (type === 0 && body.length === 2) return body.readInt16LE();
101
+ if (type === 1 && body.length === 4) return body.readInt32LE();
102
+ if (type === 2 && body.length === 4) {
103
+ const value = body.readFloatLE();
104
+ if (Number.isFinite(value)) return value;
105
+ }
106
+ if (type === 3) return body.toString("utf8");
107
+ if (type === 4) return Buffer.from(body);
108
+ throw new Error("Invalid pin value");
109
+ }
110
+
111
+ // Validate the entire batch before exposing any value to a flow.
112
+ function decodeBatch(data, mesh = false) {
113
+ if (data.length < 2) throw new Error("Truncated pin batch");
114
+ const entries = [];
115
+ let p = 2;
116
+ for (let i = 0; i < data[1]; i++) {
117
+ if (p + 2 > data.length) throw new Error("Truncated pin entry");
118
+ const pin = data[p++], type = data[p++];
119
+ let length;
120
+ if (!mesh || type >= 3) {
121
+ if (p >= data.length) throw new Error("Truncated value length");
122
+ length = data[p++];
123
+ } else length = type === 0 ? 2 : 4;
124
+ if (type > 4 || p + length > data.length) throw new Error("Invalid pin entry");
125
+ entries.push({ pin, type: NAMES[type], value: decodeValue(type, data.subarray(p, p + length)) });
126
+ p += length;
127
+ }
128
+ if (p !== data.length) throw new Error("Unexpected pin batch trailer");
129
+ return entries;
130
+ }
131
+
132
+ function seal(key, deviceId, nonce, inner, salt = 0) {
133
+ const header = Buffer.alloc(12);
134
+ header.writeUInt32LE(deviceId);
135
+ header.writeBigUInt64LE(nonce, 4);
136
+ const iv = Buffer.from(header);
137
+ iv.writeUInt32LE((deviceId ^ salt) >>> 0);
138
+ const cipher = crypto.createCipheriv("chacha20-poly1305", key, iv, { authTagLength: 16 });
139
+ return Buffer.concat([Buffer.from("E"), header, cipher.update(inner), cipher.final(), cipher.getAuthTag()]);
140
+ }
141
+
142
+ function open(key, deviceId, data) {
143
+ if (data.length < 30 || data[0] !== 69 || data.readUInt32LE(1) !== deviceId) throw new Error("Invalid encrypted envelope");
144
+ const decipher = crypto.createDecipheriv("chacha20-poly1305", key, data.subarray(1, 13), { authTagLength: 16 });
145
+ decipher.setAuthTag(data.subarray(-16));
146
+ return { nonce: data.readBigUInt64LE(5), inner: Buffer.concat([decipher.update(data.subarray(13, -16)), decipher.final()]) };
147
+ }
148
+
149
+ module.exports = { crc32, pinNumber, encodeEntry, decodeValue, decodeBatch, seal, open, NAMES, coerceKind, parseKinds };
@@ -0,0 +1,93 @@
1
+ <script type="text/javascript">
2
+ (function() {
3
+ function validPin(v) { return v === "" || /^(?:V)?(?:\d{1,2}|1\d{2}|2[0-4]\d|25[0-5])$/i.test(String(v)); }
4
+ RED.nodes.registerType("relink-connection", {
5
+ category: "config",
6
+ defaults: {
7
+ name: { value: "" },
8
+ server: { value: "relink-iot.com", required: true },
9
+ port: { value: 7445, required: true, validate: function(v) { return /^\d+$/.test(String(v)) && Number(v) > 0 && Number(v) <= 65535; } },
10
+ apiBase: { value: "" },
11
+ mesh: { value: true }
12
+ },
13
+ credentials: { token: { type: "password", required: true }, key: { type: "password", required: true } },
14
+ label: function() { return this.name || this.server; }
15
+ });
16
+ RED.nodes.registerType("relink in", {
17
+ category: "network", color: "#c4d7c0",
18
+ defaults: {
19
+ name: { value: "" },
20
+ connection: { value: "", type: "relink-connection", required: true },
21
+ pin: { value: "", validate: validPin }
22
+ },
23
+ inputs: 0, outputs: 1, icon: "font-awesome/fa-exchange",
24
+ label: function() { return this.name || (this.pin === "" ? "relink in" : "relink V" + String(this.pin).replace(/^v/i, "")); }
25
+ });
26
+ RED.nodes.registerType("relink out", {
27
+ category: "network", color: "#c4d7c0",
28
+ defaults: {
29
+ name: { value: "" },
30
+ connection: { value: "", type: "relink-connection", required: true },
31
+ pin: { value: "", validate: validPin },
32
+ dtype: { value: "auto", required: true }
33
+ },
34
+ inputs: 1, outputs: 0, icon: "font-awesome/fa-exchange", align: "right",
35
+ label: function() { return this.name || (this.pin === "" ? "relink out" : "relink V" + String(this.pin).replace(/^v/i, "")); }
36
+ });
37
+ })();
38
+ </script>
39
+
40
+ <script type="text/html" data-template-name="relink-connection">
41
+ <div class="form-row"><label for="node-config-input-name">Name</label><input type="text" id="node-config-input-name" placeholder="My device"></div>
42
+ <div class="form-row"><label for="node-config-input-server">Server</label><input type="text" id="node-config-input-server" placeholder="relink-iot.com"></div>
43
+ <div class="form-row"><label for="node-config-input-port">UDP port</label><input type="number" id="node-config-input-port" min="1" max="65535"></div>
44
+ <div class="form-row"><label for="node-config-input-apiBase">API URL</label><input type="text" id="node-config-input-apiBase" placeholder="http://relink-iot.com:8000"></div>
45
+ <div class="form-row"><label for="node-config-input-token">Device token</label><input type="password" id="node-config-input-token" autocomplete="new-password"></div>
46
+ <div class="form-row"><label for="node-config-input-key">Encryption key</label><input type="password" id="node-config-input-key" autocomplete="new-password"></div>
47
+ <div class="form-row"><label for="node-config-input-mesh">Direct mesh</label><input type="checkbox" id="node-config-input-mesh" style="display:inline-block;width:auto;vertical-align:middle"></div>
48
+ <div class="form-tips">Copy the token and 64-character key from your Relink device page. Nodes sharing this connection share one endpoint. Leave API URL blank to use http://server:8000, or enter your API's HTTPS origin.</div>
49
+ </script>
50
+
51
+ <script type="text/html" data-template-name="relink in">
52
+ <div class="form-row"><label for="node-input-name">Name</label><input type="text" id="node-input-name"></div>
53
+ <div class="form-row"><label for="node-input-connection">Connection</label><input type="text" id="node-input-connection"></div>
54
+ <div class="form-row"><label for="node-input-pin">Pin</label><input type="text" id="node-input-pin" placeholder="All pins, or V0"></div>
55
+ </script>
56
+
57
+ <script type="text/html" data-template-name="relink out">
58
+ <div class="form-row"><label for="node-input-name">Name</label><input type="text" id="node-input-name"></div>
59
+ <div class="form-row"><label for="node-input-connection">Connection</label><input type="text" id="node-input-connection"></div>
60
+ <div class="form-row"><label for="node-input-pin">Pin</label><input type="text" id="node-input-pin" placeholder="From msg.pin or msg.topic"></div>
61
+ <div class="form-row"><label for="node-input-dtype">Data type</label><select id="node-input-dtype">
62
+ <option value="auto">Automatic</option><option value="int16">Int16</option><option value="int32">Int32</option>
63
+ <option value="float">Float</option><option value="string">String</option><option value="bytes">ByteArray</option>
64
+ </select></div>
65
+ </script>
66
+
67
+ <script type="text/html" data-help-name="relink-connection">
68
+ <p>Connects Node-RED to one Relink device as an encrypted UDP endpoint. Use the same token and key as your ESP32, C++, or Python program to share virtual pins.</p>
69
+ <p>The token and key use Node-RED credentials and are omitted from exported flows. Encryption is required; an invalid key never falls back to plaintext.</p>
70
+ <p>UDP defaults to port 7445. The API URL is an origin, such as <code>https://relink-iot.com</code>, without <code>/api</code>. Signed API requests fetch declared datastreams. Direct mesh starts after that list is available, and falls back to the relay when a peer becomes unreachable.</p>
71
+ <p>This package handles virtual pins and numeric history summaries. It does not flash firmware or receive camera frames.</p>
72
+ </script>
73
+
74
+ <script type="text/html" data-help-name="relink in">
75
+ <p>Receives changes from the dashboard and other endpoints of a Relink device. Leave Pin blank for all pins, or choose V0–V255.</p>
76
+ <h3>Outputs</h3>
77
+ <dl class="message-properties">
78
+ <dt>payload <span class="property-type">number | string | Buffer</span></dt><dd>The pin value. ByteArray values are Buffers.</dd>
79
+ <dt>topic <span class="property-type">string</span></dt><dd>Pin name, for example <code>V0</code>.</dd>
80
+ <dt>pin <span class="property-type">number</span></dt><dd>Pin number, 0–255.</dd>
81
+ <dt>dtype <span class="property-type">string</span></dt><dd>int16, int32, float, string, or bytes.</dd>
82
+ <dt>transport <span class="property-type">string</span></dt><dd>relay or p2p.</dd>
83
+ <dt>checksum <span class="property-type">number</span></dt><dd>The device's numeric identifier.</dd>
84
+ </dl>
85
+ <p>Own writes are not echoed locally. Register the pins as datastreams on the Relink dashboard before using them.</p>
86
+ </script>
87
+
88
+ <script type="text/html" data-help-name="relink out">
89
+ <p>Queues <code>msg.payload</code> as a virtual-pin write. Select a fixed pin, or leave it blank to use <code>msg.pin</code>, then <code>msg.topic</code> (for example <code>V1</code>).</p>
90
+ <p>Automatic type chooses Int16 or Int32 for whole numbers, Float for fractional numbers, String for text, and ByteArray for Buffer. Booleans become 0 or 1. Select Float explicitly for a Float datastream when sending whole numbers.</p>
91
+ <p>Text and ByteArray payloads are limited to 255 bytes. Invalid values trigger a Catch node. During a network outage, the latest queued value per pin is retained in memory; a redeploy clears it. At high input rates, writes to the same pin are coalesced.</p>
92
+ <p>Completion means queued, not delivery confirmed. Sending to a control pin can affect real hardware.</p>
93
+ </script>
@@ -0,0 +1,87 @@
1
+ "use strict";
2
+
3
+ const { RelinkClient } = require("../lib/client");
4
+ const { pinNumber } = require("../lib/protocol");
5
+
6
+ module.exports = function(RED) {
7
+ function Connection(config) {
8
+ RED.nodes.createNode(this, config);
9
+ this.users = new Set();
10
+ this.closed = false;
11
+ this.connectionState = "connecting";
12
+ this.setState = state => {
13
+ this.connectionState = state;
14
+ for (const user of this.users) user.status(statusFor(state));
15
+ };
16
+ try {
17
+ const credentials = this.credentials || {};
18
+ this.client = new RelinkClient({ token: credentials.token, key: credentials.key,
19
+ server: config.server, port: config.port, apiBase: config.apiBase, mesh: config.mesh !== false });
20
+ this.client.setMaxListeners(0); // a shared configuration may feed many input nodes
21
+ this.client.on("status", ({ state }) => this.setState(state));
22
+ this.client.on("warning", error => this.warn(error.message));
23
+ const start = () => this.client.start().catch(error => {
24
+ if (this.closed) return;
25
+ this.setState("connecting"); this.warn(error.message);
26
+ this.retryTimer = setTimeout(start, 5000);
27
+ });
28
+ start();
29
+ } catch (error) { this.connectionState = "error"; this.error(error.message); }
30
+ this.on("close", (removed, done) => {
31
+ this.closed = true;
32
+ clearTimeout(this.retryTimer);
33
+ // Also handle runtimes invoking close with just its completion callback.
34
+ if (typeof removed === "function") done = removed;
35
+ Promise.resolve(this.client && this.client.stop()).then(() => { this.users.clear(); if (done) done(); });
36
+ });
37
+ }
38
+
39
+ function statusFor(state) {
40
+ return { fill: state === "connected" ? "green" : state === "error" ? "red" : "grey",
41
+ shape: state === "connected" ? "dot" : "ring", text: state };
42
+ }
43
+
44
+ function attach(node, config) {
45
+ const connection = RED.nodes.getNode(config.connection);
46
+ if (!connection || !connection.client || connection.connectionState === "error") {
47
+ node.status(statusFor("error")); node.error("Configure a valid Relink connection"); return null;
48
+ }
49
+ connection.users.add(node);
50
+ node.status(statusFor(connection.connectionState));
51
+ node.on("close", () => connection.users.delete(node));
52
+ return connection;
53
+ }
54
+
55
+ function InNode(config) {
56
+ RED.nodes.createNode(this, config);
57
+ const connection = attach(this, config);
58
+ if (!connection) return;
59
+ let pin;
60
+ try { pin = config.pin === "" || config.pin === undefined ? null : pinNumber(config.pin); }
61
+ catch (error) { this.error(error.message); this.status(statusFor("error")); return; }
62
+ const listener = event => {
63
+ if (pin !== null && pin !== event.pin) return;
64
+ this.send({ topic: `V${event.pin}`, payload: event.value, pin: event.pin,
65
+ dtype: event.type, transport: event.transport, checksum: event.checksum });
66
+ };
67
+ connection.client.on("pin", listener);
68
+ this.on("close", () => connection.client.removeListener("pin", listener));
69
+ }
70
+
71
+ function OutNode(config) {
72
+ RED.nodes.createNode(this, config);
73
+ const connection = attach(this, config);
74
+ this.on("input", (msg, send, done) => {
75
+ try {
76
+ if (!connection) throw new Error("Configure a valid Relink connection");
77
+ const selected = config.pin !== "" && config.pin !== undefined ? config.pin : (msg.pin !== undefined ? msg.pin : msg.topic);
78
+ connection.client.write(pinNumber(selected), msg.payload, config.dtype || "auto");
79
+ if (done) done();
80
+ } catch (error) { if (done) done(error); else this.error(error.message, msg); }
81
+ });
82
+ }
83
+
84
+ RED.nodes.registerType("relink-connection", Connection, { credentials: { token: { type: "password" }, key: { type: "password" } } });
85
+ RED.nodes.registerType("relink in", InNode);
86
+ RED.nodes.registerType("relink out", OutNode);
87
+ };
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "node-red-contrib-relink",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Node-RED nodes for Relink IoT virtual pins over encrypted UDP and direct mesh",
5
+ "license": "MIT",
6
+ "engines": {
7
+ "node": ">=18"
8
+ },
9
+ "keywords": [
10
+ "node-red",
11
+ "relink",
12
+ "iot",
13
+ "esp32",
14
+ "virtual-pins"
15
+ ],
16
+ "main": "lib/client.js",
17
+ "files": [
18
+ "lib/",
19
+ "nodes/",
20
+ "examples/",
21
+ "README.md",
22
+ "LICENSE"
23
+ ],
24
+ "scripts": {
25
+ "test": "node --test test/*.test.js"
26
+ },
27
+ "node-red": {
28
+ "version": ">=3.0.0",
29
+ "nodes": {
30
+ "relink": "nodes/relink.js"
31
+ }
32
+ },
33
+ "author": "Relink IoT",
34
+ "homepage": "https://relink-iot.com",
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "git+https://github.com/NonStopBle/Relink-NodeRed.git"
38
+ },
39
+ "bugs": {
40
+ "url": "https://github.com/NonStopBle/Relink-NodeRed/issues"
41
+ },
42
+ "publishConfig": {
43
+ "access": "public"
44
+ },
45
+ "dependencies": {
46
+ "node-red-contrib-relink": "^0.0.0-stage"
47
+ }
48
+ }