node-red-contrib-tdn-wifi 1.0.3

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/tdn-wifi.js ADDED
@@ -0,0 +1,505 @@
1
+ 'use strict';
2
+
3
+ // node-red-contrib-tdn-wifi
4
+ // Copyright (C) 2026 letis009
5
+ //
6
+ // This program is free software: you can redistribute it and/or modify
7
+ // it under the terms of the GNU Affero General Public License as published by
8
+ // the Free Software Foundation, either version 3 of the License, or
9
+ // (at your option) any later version.
10
+ //
11
+ // This program is distributed in the hope that it will be useful,
12
+ // but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ // GNU Affero General Public License for more details.
15
+ //
16
+ // You should have received a copy of the GNU Affero General Public License
17
+ // along with this program. If not, see <https://www.gnu.org/licenses/>.
18
+
19
+ const { execFile } = require('child_process');
20
+ const { promisify } = require('util');
21
+ const execFileAsync = promisify(execFile);
22
+ const crypto = require('crypto');
23
+ const fs = require('fs');
24
+ const path = require('path');
25
+ const https = require('https');
26
+
27
+ module.exports = function (RED) {
28
+
29
+ function ts() {
30
+ return new Date().toTimeString().slice(0, 8);
31
+ }
32
+
33
+ function escapeHtml(s) {
34
+ return String(s).replace(/[&<>"']/g, (c) => ({
35
+ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;',
36
+ }[c]));
37
+ }
38
+
39
+ // RED.httpNode doesn't guarantee JSON body-parsing middleware for routes a third-party
40
+ // node adds directly (unlike the core http-in node, which parses its own body) — so
41
+ // req.body can be undefined here. If something upstream already parsed it, use that;
42
+ // otherwise read the raw request stream ourselves.
43
+ function readJsonBody(req) {
44
+ return new Promise((resolve, reject) => {
45
+ if (req.body && typeof req.body === 'object') { resolve(req.body); return; }
46
+ let data = '';
47
+ req.on('data', (chunk) => { data += chunk; });
48
+ req.on('end', () => {
49
+ if (!data) { resolve({}); return; }
50
+ try { resolve(JSON.parse(data)); }
51
+ catch (e) { reject(new Error('Invalid JSON body')); }
52
+ });
53
+ req.on('error', reject);
54
+ });
55
+ }
56
+
57
+ // Pure fs check — no subprocess — for the first WiFi-capable interface.
58
+ function detectWifiInterface() {
59
+ try {
60
+ const netDir = '/sys/class/net';
61
+ for (const iface of fs.readdirSync(netDir)) {
62
+ if (fs.existsSync(path.join(netDir, iface, 'wireless'))) return iface;
63
+ }
64
+ } catch (e) { /* not Linux, or /sys unavailable */ }
65
+ return 'wlan0';
66
+ }
67
+
68
+ // ─────────────────────────────────────────────────────────────────────────
69
+ // WIFI CONFIG NODE — tdn-wifi-config
70
+ // A regular node (not a Node-RED "config" node) so it gets a palette icon
71
+ // and can be dragged onto a flow directly — nothing else needs to reference it.
72
+ // ─────────────────────────────────────────────────────────────────────────
73
+ function TdnWifiConfigNode(config) {
74
+ RED.nodes.createNode(this, config);
75
+ const node = this;
76
+
77
+ node.iface = (config.iface || '').trim() || detectWifiInterface();
78
+ // HTTPS URL used for the reachability check; blank = a public anycast IP (no DNS needed)
79
+ node.checkUrl = (config.checkUrl || '').trim() || 'https://1.1.1.1';
80
+ const isLinux = process.platform === 'linux';
81
+
82
+ node._connecting = false;
83
+ node._lastSsid = null;
84
+ node._pollTimer = null;
85
+
86
+ node.log(`[wifi] Starting — platform=${process.platform} iface=${node.iface}`);
87
+ node.status({ fill: 'grey', shape: 'dot', text: `${ts()} Idle` });
88
+
89
+ // ── wpa_cli / ip / resolvectl helpers — all via execFile with argument
90
+ // arrays, never a shell string, so SSID/password content can never be
91
+ // shell-injected. ─────────────────────────────────────────────────────
92
+ async function runWpaCli(...args) {
93
+ const { stdout } = await execFileAsync('wpa_cli', ['-i', node.iface, ...args], { timeout: 10000 });
94
+ return stdout;
95
+ }
96
+
97
+ // Same derivation wpa_passphrase uses: PBKDF2-HMAC-SHA1(passphrase, ssid, 4096, 32).
98
+ // Computing the PSK ourselves means both ssid and psk can be handed to wpa_cli as
99
+ // plain hex — no quoting/escaping of arbitrary password characters required at all.
100
+ function computePsk(ssid, password) {
101
+ return crypto.pbkdf2Sync(password, ssid, 4096, 32, 'sha1').toString('hex');
102
+ }
103
+
104
+ async function getCurrentStatus() {
105
+ const out = await runWpaCli('status');
106
+ const kv = {};
107
+ out.split('\n').forEach((line) => {
108
+ const idx = line.indexOf('=');
109
+ if (idx > 0) kv[line.slice(0, idx).trim()] = line.slice(idx + 1).trim();
110
+ });
111
+ return kv; // { wpa_state, ssid, id, ... }
112
+ }
113
+
114
+ async function scanNetworks() {
115
+ await runWpaCli('scan');
116
+ await new Promise((r) => setTimeout(r, 3000));
117
+ const out = await runWpaCli('scan_results');
118
+
119
+ const bySsid = new Map();
120
+ out.split('\n').forEach((line) => {
121
+ const cols = line.split('\t');
122
+ if (cols.length < 5) return; // header line / banner, not a data row
123
+ const [, , signal, flags, ssid] = cols;
124
+ if (!ssid) return; // hidden/blank SSID — nothing usable to show
125
+ const sig = parseInt(signal, 10);
126
+ const secured = /WPA|WEP/.test(flags);
127
+ const existing = bySsid.get(ssid);
128
+ if (!existing || sig > existing.signal) {
129
+ bySsid.set(ssid, { ssid, signal: sig, secured });
130
+ }
131
+ });
132
+ const networks = [...bySsid.values()].sort((a, b) => b.signal - a.signal);
133
+
134
+ let currentSsid = null;
135
+ try {
136
+ const status = await getCurrentStatus();
137
+ if (status.wpa_state === 'COMPLETED') currentSsid = status.ssid || null;
138
+ } catch (e) { /* leave currentSsid null */ }
139
+
140
+ return { networks, currentSsid };
141
+ }
142
+
143
+ async function connect(ssid, password) {
144
+ if (password.length < 8 || password.length > 63) {
145
+ throw new Error('Password must be 8-63 characters for WPA2/WPA3-Personal');
146
+ }
147
+ const ssidHex = Buffer.from(ssid, 'utf8').toString('hex');
148
+ const pskHex = computePsk(ssid, password);
149
+
150
+ const idOut = await runWpaCli('add_network');
151
+ const netId = idOut.trim().split('\n').pop().trim();
152
+ if (!/^\d+$/.test(netId)) throw new Error(`Unexpected add_network response: ${idOut}`);
153
+
154
+ async function cleanup() {
155
+ try {
156
+ await runWpaCli('remove_network', netId);
157
+ await runWpaCli('save_config');
158
+ } catch (e) {
159
+ node.warn(`[wifi] cleanup remove_network failed: ${e.message}`);
160
+ }
161
+ }
162
+
163
+ try {
164
+ await runWpaCli('set_network', netId, 'ssid', ssidHex);
165
+ await runWpaCli('set_network', netId, 'psk', pskHex);
166
+ await runWpaCli('select_network', netId);
167
+ await runWpaCli('save_config');
168
+
169
+ const deadline = Date.now() + 20000;
170
+ let lastState = 'UNKNOWN';
171
+ while (Date.now() < deadline) {
172
+ await new Promise((r) => setTimeout(r, 1000));
173
+ const status = await getCurrentStatus();
174
+ lastState = status.wpa_state || lastState;
175
+ if (lastState === 'COMPLETED' && status.ssid === ssid) {
176
+ return;
177
+ }
178
+ }
179
+ throw new Error(`Association timed out (last state: ${lastState})`);
180
+ } catch (e) {
181
+ await cleanup();
182
+ throw e;
183
+ }
184
+ }
185
+
186
+ async function getIpInfo() {
187
+ let ip = null;
188
+ const deadline = Date.now() + 15000;
189
+ while (Date.now() < deadline && !ip) {
190
+ try {
191
+ const { stdout } = await execFileAsync('ip', ['-4', '-o', 'addr', 'show', 'dev', node.iface]);
192
+ const m = stdout.match(/inet (\d+\.\d+\.\d+\.\d+)\/(\d+)/);
193
+ if (m) { ip = m[1]; break; }
194
+ } catch (e) { /* ip command failed — retry */ }
195
+ if (!ip) await new Promise((r) => setTimeout(r, 2000));
196
+ }
197
+ if (!ip) {
198
+ try { await execFileAsync('networkctl', ['renew', node.iface]); } catch (e) { /* best effort nudge */ }
199
+ await new Promise((r) => setTimeout(r, 3000));
200
+ try {
201
+ const { stdout } = await execFileAsync('ip', ['-4', '-o', 'addr', 'show', 'dev', node.iface]);
202
+ const m = stdout.match(/inet (\d+\.\d+\.\d+\.\d+)\/(\d+)/);
203
+ if (m) ip = m[1];
204
+ } catch (e) { /* give up — report no IP */ }
205
+ }
206
+
207
+ let gateway = null;
208
+ try {
209
+ const { stdout } = await execFileAsync('ip', ['route', 'show', 'dev', node.iface, 'default']);
210
+ const m = stdout.match(/via (\d+\.\d+\.\d+\.\d+)/);
211
+ if (m) gateway = m[1];
212
+ } catch (e) { /* no default route via this iface */ }
213
+
214
+ let dns = [];
215
+ try {
216
+ const { stdout } = await execFileAsync('resolvectl', ['dns', node.iface]);
217
+ dns = stdout.match(/\d+\.\d+\.\d+\.\d+/g) || [];
218
+ } catch (e) {
219
+ try {
220
+ const resolvConf = fs.readFileSync('/etc/resolv.conf', 'utf8');
221
+ dns = [...resolvConf.matchAll(/^nameserver\s+(\S+)/gm)].map((mm) => mm[1]);
222
+ } catch (e2) { /* give up — report no DNS */ }
223
+ }
224
+
225
+ return { ip, gateway, dns };
226
+ }
227
+
228
+ function checkReachable() {
229
+ return new Promise((resolve) => {
230
+ const start = Date.now();
231
+ const req = https.get(node.checkUrl, { timeout: 5000 }, (res) => {
232
+ res.resume();
233
+ resolve({ reachable: true, url: node.checkUrl, latencyMs: Date.now() - start, statusCode: res.statusCode });
234
+ });
235
+ req.on('timeout', () => { req.destroy(); resolve({ reachable: false, url: node.checkUrl, error: 'timeout' }); });
236
+ req.on('error', (e) => resolve({ reachable: false, url: node.checkUrl, error: e.message }));
237
+ });
238
+ }
239
+
240
+ // ── Background poll so the output port fires on connect/disconnect
241
+ // even if nobody has /wifi-config open (e.g. to trigger an MWA alert). ──
242
+ async function pollStatus() {
243
+ try {
244
+ const status = await getCurrentStatus();
245
+ const ssid = status.wpa_state === 'COMPLETED' ? (status.ssid || null) : null;
246
+ if (ssid !== node._lastSsid) {
247
+ node._lastSsid = ssid;
248
+ if (ssid) {
249
+ node.status({ fill: 'green', shape: 'dot', text: `${ts()} Connected: ${ssid}` });
250
+ node.send({ payload: { event: 'connected', ssid } });
251
+ } else {
252
+ node.status({ fill: 'red', shape: 'ring', text: `${ts()} Disconnected` });
253
+ node.send({ payload: { event: 'disconnected' } });
254
+ }
255
+ }
256
+ } catch (e) {
257
+ // wpa_cli not reachable yet at boot, etc. — don't spam warnings every 30s.
258
+ }
259
+ }
260
+
261
+ if (isLinux) {
262
+ pollStatus();
263
+ node._pollTimer = setInterval(pollStatus, 30000);
264
+ } else {
265
+ node.status({ fill: 'grey', shape: 'ring', text: 'Unsupported platform' });
266
+ node.warn('[wifi] Not running on Linux — /wifi-config will report unsupported');
267
+ }
268
+
269
+ // ── HTTP routes — on RED.httpNode (the runtime surface), not RED.httpAdmin,
270
+ // so this keeps working even if the Node-RED editor/admin API is disabled. ──
271
+ RED.httpNode.get('/wifi-config', (req, res) => {
272
+ if (!isLinux) {
273
+ res.send(`<!DOCTYPE html><html><head><title>WiFi Config</title></head>
274
+ <body style="font-family:sans-serif;text-align:center;padding:40px">
275
+ <h2>Not supported on this platform</h2>
276
+ <p>This page only works on Linux (Raspberry Pi) — this Node-RED instance is running on
277
+ ${escapeHtml(process.platform)}.</p>
278
+ </body></html>`);
279
+ return;
280
+ }
281
+
282
+ res.send(`<!DOCTYPE html>
283
+ <html><head><title>WiFi Config</title><meta charset="utf-8">
284
+ <style>
285
+ body{font-family:sans-serif;max-width:520px;margin:0 auto;padding:24px;background:#f7f7f7;color:#222}
286
+ h2{margin-bottom:4px}
287
+ #iface{color:#888;font-size:13px}
288
+ button{background:#2196f3;color:#fff;border:0;border-radius:6px;padding:8px 16px;font-size:13px;
289
+ cursor:pointer;margin-right:8px}
290
+ button:disabled{background:#aaa;cursor:default}
291
+ #connectBtn{background:#4BA3A8}
292
+ #cancelBtn{background:#888}
293
+ .msg{color:#555;font-size:13px;margin:10px 0}
294
+ #networks{list-style:none;margin:12px 0;padding:0;background:#fff;border:1px solid #ddd;border-radius:6px;
295
+ max-height:260px;overflow-y:auto}
296
+ #networks li{padding:10px 12px;border-bottom:1px solid #eee;font-size:14px;cursor:pointer}
297
+ #networks li:last-child{border-bottom:none}
298
+ #networks li:hover{background:#f0f8ff}
299
+ #connectForm{background:#fff;border:1px solid #ddd;border-radius:6px;padding:16px;margin-top:12px;display:none}
300
+ #connectForm input{width:100%;box-sizing:border-box;padding:8px;font-size:14px;margin:8px 0;
301
+ border:1px solid #ccc;border-radius:4px}
302
+ #result{margin-top:16px}
303
+ #result ul{list-style:none;margin:8px 0;padding:0;background:#fff;border:1px solid #ddd;border-radius:6px}
304
+ #result li{padding:8px 12px;border-bottom:1px solid #eee;font-size:13px}
305
+ #result li:last-child{border-bottom:none}
306
+ </style>
307
+ </head><body>
308
+ <h2>WiFi Configuration <span id="iface"></span></h2>
309
+ <button id="scanBtn">Scan Networks</button>
310
+ <button id="testBtn">Test Connectivity</button>
311
+ <div id="scanMsg" class="msg"></div>
312
+ <ul id="networks"></ul>
313
+
314
+ <div id="connectForm">
315
+ <h3>Connect to <span id="selSsid"></span></h3>
316
+ <input type="password" id="pwInput" placeholder="WiFi password (8-63 characters)">
317
+ <button id="connectBtn" type="button">Connect</button>
318
+ <button id="cancelBtn" type="button">Cancel</button>
319
+ </div>
320
+
321
+ <div id="result"></div>
322
+
323
+ <script>
324
+ function el(id) { return document.getElementById(id); }
325
+ function esc(s) {
326
+ return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) {
327
+ return { '&':'&amp;', '<':'&lt;', '>':'&gt;', '"':'&quot;', "'":'&#39;' }[c];
328
+ });
329
+ }
330
+ function setMsg(id, text, isError) {
331
+ var e = el(id);
332
+ e.textContent = text;
333
+ e.style.color = isError ? '#c0392b' : '#555';
334
+ }
335
+
336
+ function renderNetworks(data) {
337
+ var list = el('networks');
338
+ list.innerHTML = '';
339
+ (data.networks || []).forEach(function (n) {
340
+ var li = document.createElement('li');
341
+ var current = (n.ssid === data.currentSsid) ? ' — connected' : '';
342
+ li.textContent = n.ssid + ' ' + n.signal + ' dBm ' + (n.secured ? '(secured)' : '(open)') + current;
343
+ li.onclick = function () { selectNetwork(n.ssid); };
344
+ list.appendChild(li);
345
+ });
346
+ }
347
+
348
+ function scan() {
349
+ setMsg('scanMsg', 'Scanning… (a few seconds)');
350
+ el('scanBtn').disabled = true;
351
+ fetch('wifi-scan.json').then(function (r) { return r.json(); }).then(function (data) {
352
+ el('scanBtn').disabled = false;
353
+ if (data.error) { setMsg('scanMsg', data.error, true); return; }
354
+ setMsg('scanMsg', data.networks.length + ' network(s) found');
355
+ renderNetworks(data);
356
+ }).catch(function (e) {
357
+ el('scanBtn').disabled = false;
358
+ setMsg('scanMsg', 'Scan failed: ' + e.message, true);
359
+ });
360
+ }
361
+
362
+ function selectNetwork(ssid) {
363
+ el('selSsid').textContent = ssid;
364
+ el('pwInput').value = '';
365
+ el('connectForm').style.display = 'block';
366
+ el('connectForm').dataset.ssid = ssid;
367
+ el('pwInput').focus();
368
+ }
369
+
370
+ function connect() {
371
+ var ssid = el('connectForm').dataset.ssid;
372
+ var password = el('pwInput').value;
373
+ el('connectBtn').disabled = true;
374
+ el('result').innerHTML = '<p>Connecting to ' + esc(ssid) + '… this can take up to 20 seconds.</p>';
375
+ fetch('wifi-connect', {
376
+ method: 'POST',
377
+ headers: { 'Content-Type': 'application/json' },
378
+ body: JSON.stringify({ ssid: ssid, password: password }),
379
+ }).then(function (r) { return r.json(); }).then(function (data) {
380
+ el('connectBtn').disabled = false;
381
+ showResult(data);
382
+ }).catch(function (e) {
383
+ el('connectBtn').disabled = false;
384
+ el('result').innerHTML = '<p style="color:#c0392b">Connect failed: ' + esc(e.message) + '</p>';
385
+ });
386
+ }
387
+
388
+ function showResult(data) {
389
+ if (!data.success) {
390
+ el('result').innerHTML = '<p style="color:#c0392b">Failed: ' + esc(data.error || 'unknown error') + '</p>';
391
+ return;
392
+ }
393
+ var net = data.internet || {};
394
+ var netLine = net.reachable
395
+ ? ('yes (' + net.latencyMs + ' ms)')
396
+ : ('no' + (net.error ? (' — ' + esc(net.error)) : ''));
397
+ el('result').innerHTML =
398
+ '<p style="color:#2e7d32">Connected to ' + esc(data.ssid) + '</p>' +
399
+ '<ul>' +
400
+ '<li>IP: ' + esc(data.ip || '—') + '</li>' +
401
+ '<li>Gateway: ' + esc(data.gateway || '—') + '</li>' +
402
+ '<li>DNS: ' + esc((data.dns || []).join(', ') || '—') + '</li>' +
403
+ '<li>Internet reachable' + (net.url ? ' (' + esc(net.url) + ')' : '') + ': ' + netLine + '</li>' +
404
+ '</ul>';
405
+ el('connectForm').style.display = 'none';
406
+ scan();
407
+ }
408
+
409
+ function testConnectivity() {
410
+ el('result').innerHTML = '<p>Testing…</p>';
411
+ fetch('wifi-status.json').then(function (r) { return r.json(); }).then(showResult);
412
+ }
413
+
414
+ el('scanBtn').onclick = scan;
415
+ el('testBtn').onclick = testConnectivity;
416
+ el('connectBtn').onclick = connect;
417
+ el('cancelBtn').onclick = function () { el('connectForm').style.display = 'none'; };
418
+
419
+ scan();
420
+ </script>
421
+ </body></html>`);
422
+ });
423
+
424
+ RED.httpNode.get('/wifi-scan.json', async (req, res) => {
425
+ if (!isLinux) { res.status(501).json({ error: 'Not supported on this platform (Pi/Linux only)' }); return; }
426
+ try {
427
+ const result = await scanNetworks();
428
+ res.json(result);
429
+ } catch (e) {
430
+ node.warn(`[wifi] scan failed: ${e.message}`);
431
+ res.status(500).json({ error: e.message });
432
+ }
433
+ });
434
+
435
+ RED.httpNode.post('/wifi-connect', async (req, res) => {
436
+ if (!isLinux) { res.status(501).json({ success: false, error: 'Not supported on this platform (Pi/Linux only)' }); return; }
437
+ if (node._connecting) {
438
+ res.status(409).json({ success: false, error: 'A connection attempt is already in progress' });
439
+ return;
440
+ }
441
+
442
+ let body;
443
+ try {
444
+ body = await readJsonBody(req);
445
+ } catch (e) {
446
+ res.status(400).json({ success: false, error: e.message });
447
+ return;
448
+ }
449
+ const ssid = typeof body.ssid === 'string' ? body.ssid.trim() : '';
450
+ const password = typeof body.password === 'string' ? body.password : '';
451
+ if (!ssid) { res.status(400).json({ success: false, error: 'Missing ssid' }); return; }
452
+
453
+ node._connecting = true;
454
+ node.log(`[wifi] Connecting to ${ssid}`);
455
+ node.status({ fill: 'blue', shape: 'dot', text: `${ts()} Connecting to ${ssid}…` });
456
+ try {
457
+ await connect(ssid, password);
458
+ node._lastSsid = ssid;
459
+ const ipInfo = await getIpInfo();
460
+ const net = await checkReachable();
461
+ node.status({ fill: 'green', shape: 'dot', text: `${ts()} Connected: ${ssid}` });
462
+ node.send({ payload: { event: 'connected', ssid, ip: ipInfo.ip } });
463
+ res.json({
464
+ success: true, ssid,
465
+ ip: ipInfo.ip, gateway: ipInfo.gateway, dns: ipInfo.dns,
466
+ internet: net,
467
+ });
468
+ } catch (e) {
469
+ node.warn(`[wifi] connect failed: ${e.message}`);
470
+ node.status({ fill: 'red', shape: 'ring', text: `${ts()} ${e.message}` });
471
+ res.json({ success: false, error: e.message });
472
+ } finally {
473
+ node._connecting = false;
474
+ }
475
+ });
476
+
477
+ RED.httpNode.get('/wifi-status.json', async (req, res) => {
478
+ if (!isLinux) { res.status(501).json({ success: false, error: 'Not supported on this platform (Pi/Linux only)' }); return; }
479
+ try {
480
+ const status = await getCurrentStatus();
481
+ if (status.wpa_state !== 'COMPLETED') {
482
+ res.json({ success: false, error: `Not connected (state: ${status.wpa_state || 'UNKNOWN'})` });
483
+ return;
484
+ }
485
+ const ipInfo = await getIpInfo();
486
+ const net = await checkReachable();
487
+ res.json({
488
+ success: true, ssid: status.ssid,
489
+ ip: ipInfo.ip, gateway: ipInfo.gateway, dns: ipInfo.dns,
490
+ internet: net,
491
+ });
492
+ } catch (e) {
493
+ res.status(500).json({ success: false, error: e.message });
494
+ }
495
+ });
496
+
497
+ node.on('close', (done) => {
498
+ clearInterval(node._pollTimer);
499
+ node.status({});
500
+ done();
501
+ });
502
+ }
503
+
504
+ RED.nodes.registerType('tdn-wifi-config', TdnWifiConfigNode);
505
+ };