node-red-contrib-ccu 4.8.0 → 4.9.0

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/CHANGELOG.md CHANGED
@@ -5,6 +5,27 @@ Notable changes to node-red-contrib-ccu. Format follows
5
5
  user-visible symptom and the cause, not the commit list (the release notes
6
6
  append commits automatically).
7
7
 
8
+ ## 4.9.0 (2026-11-09)
9
+
10
+ ### Added
11
+
12
+ - **Pairing with an openccu-lite system from the connection node.** A
13
+ Node-RED that does not run on the system no longer needs a token copied
14
+ from the system's API tokens page: _Pair with the system_ asks the system
15
+ at the configured address for access, the dialog shows a six-digit code,
16
+ an administrator compares and approves it on the system's Status page, and
17
+ the dialog fills in the token and the fingerprint of the system's
18
+ certificate (and TLS, where the system redirects to https). After the
19
+ deploy the metadata API and lite-rpc accept exactly that certificate, so
20
+ the system's own self-signed certificate works without _Ignore invalid TLS
21
+ Certificates_; another certificate is refused before the token is sent. A
22
+ rejection, an expired request, a CCU or nothing at the address, pairing
23
+ switched off on the system or a request from outside its local networks
24
+ are said in the dialog. Closing the dialog withdraws a pending request.
25
+ Node-RED on the system itself (RedMatic on openccu-lite) is unchanged: it
26
+ configures itself, the dialog shows no pairing there and the runtime
27
+ refuses a pairing request for a local connection.
28
+
8
29
  ## 4.8.0 (2026-10-29)
9
30
 
10
31
  Less memory: the connection's own bookkeeping no longer grows with the
package/README.md CHANGED
@@ -49,9 +49,15 @@ CCU-Jack keep their own connections.
49
49
  - Node-RED **on the system** (RedMatic from its addon catalogue): lite-rpc with RedMatic's own token, which the system
50
50
  mints for it from RedMatic's manifest (RedMatic 9.15.1 or later); the names come with the system's read-only token.
51
51
  Nothing to configure. An older RedMatic has no such token and connects the CCU way, the log says so.
52
- - Node-RED **elsewhere**: an API token of the system goes into the connection node's **openccu-lite token** field -
53
- for lite-rpc it needs the `rpc:*` scope of what the flow does (`rpc:read` for events and reads, `rpc:operate` for
54
- `setValue`, `rpc:configure` for paramsets and links, `rpc:admin` for the rest; the rpc node may call anything).
52
+ - Node-RED **elsewhere**: enter the system's address and press **Pair with the system** in the connection node. The
53
+ dialog shows a six-digit code; an administrator compares it on the system's Status page and approves the request.
54
+ The token and the fingerprint of the system's certificate are filled in, TLS is switched on where the system
55
+ offers https, and after the deploy the connection accepts exactly that certificate - no "ignore invalid
56
+ certificates" needed for the system's own self-signed one. Pairing asks for devices at the _administer_ level (the
57
+ rpc node may call any method) and for reading the names. Alternatively an API token made on the system goes into
58
+ the **openccu-lite token** field by hand - for lite-rpc it needs the `rpc:*` scope of what the flow does
59
+ (`rpc:read` for events and reads, `rpc:operate` for `setValue`, `rpc:configure` for paramsets and links,
60
+ `rpc:admin` for the rest).
55
61
  - **System variables, programs and HM-Script do not exist there.** The `ccu-sysvar`, `ccu-program`, `ccu-script` and
56
62
  `ccu-poll` nodes stay in the flows and answer every message with an error.
57
63
 
@@ -1,4 +1,19 @@
1
1
  <script type="text/javascript">
2
+ // pairing with an openccu-lite system: the request the open dialog runs, withdrawn when it closes
3
+ let ccuActivePairing = null;
4
+ const ccuStopPairing = withdraw => {
5
+ if (!ccuActivePairing) {
6
+ return;
7
+ }
8
+
9
+ clearTimeout(ccuActivePairing.timer);
10
+ if (withdraw && ccuActivePairing.id) {
11
+ $.ajax({url: 'ccu/pair/' + ccuActivePairing.id, type: 'DELETE'});
12
+ }
13
+
14
+ ccuActivePairing = null;
15
+ };
16
+
2
17
  RED.nodes.registerType('ccu-connection', {
3
18
  category: 'config',
4
19
  defaults: {
@@ -48,12 +63,22 @@
48
63
  // credentials (flows_cred.json, encrypted, never exported), not in the flow
49
64
  credentials: {
50
65
  password: {type: 'password'},
51
- metaToken: {type: 'password'}
66
+ metaToken: {type: 'password'},
67
+ // the system's certificate as pinned at pairing - no secret, shown in the dialog
68
+ fingerprint256: {type: 'text'}
52
69
  },
53
70
  label() {
54
71
  return this.name || this.host;
55
72
  },
56
73
 
74
+ oneditsave() {
75
+ ccuStopPairing(true);
76
+ },
77
+
78
+ oneditcancel() {
79
+ ccuStopPairing(true);
80
+ },
81
+
57
82
  oneditprepare() {
58
83
  // pre-4.3.0 config nodes have neither property - show the defaults
59
84
  // the runtime uses rather than an unchecked box / empty field
@@ -164,10 +189,129 @@
164
189
  $('#node-config-auth-fields, #node-config-auth-hint').toggle(!local);
165
190
  $('#node-config-input-username, #node-config-input-password').closest('.form-row').toggle(!local);
166
191
  $('#node-config-auth-local').toggle(local);
192
+ // on the system itself the connection configures itself: nothing to pair
193
+ $('#node-config-pair, #node-config-pair-status').toggle(!local);
194
+ $('#node-config-pair-local').toggle(local);
167
195
  };
168
196
  $nodeConfigInputHost.on('change keyup', showAuthRows);
169
197
  showAuthRows();
170
198
 
199
+ // pairing with an openccu-lite system (lib/pairing.js): the runtime asks the system, the
200
+ // dialog shows the code, an administrator approves it on the system's Status page, and
201
+ // the token and the pinned certificate land in the fields - then the user deploys
202
+ const $pair = $('#node-config-pair');
203
+ const $pairStatus = $('#node-config-pair-status');
204
+ const pairIdle = $pairStatus.html();
205
+ const pairButton = () => $pair.text(ccuActivePairing ? 'Cancel pairing' : 'Pair with the system');
206
+ const pairSay = text => $pairStatus.text(text);
207
+
208
+ const pairShow = view => {
209
+ switch (view.state) {
210
+ case 'waiting': {
211
+ $pairStatus.empty().append('Code ', $('<b>').text(view.code), ' - approve it on the Status page of the system:');
212
+ $pairStatus.append(' ', $('<a target="_blank" rel="noopener">').attr('href', view.url + '/').text(view.url));
213
+ return true;
214
+ }
215
+
216
+ case 'approved': {
217
+ $('#node-config-input-metaToken').val(view.token);
218
+ $('#node-config-input-fingerprint256').val(view.fingerprint256 || '');
219
+ $('#node-config-input-tls').prop('checked', Boolean(view.tls));
220
+ $('#node-config-input-metaPort').val(view.port || '');
221
+ if (view.fingerprint256) {
222
+ $('#node-config-input-inSecure').prop('checked', false);
223
+ }
224
+
225
+ pairSay('Paired as "' + view.name + '"' + (view.fingerprint256 ? ', the certificate of the system pinned' : ' (plain HTTP, no certificate to pin)') + '. Deploy to use it.');
226
+ return false;
227
+ }
228
+
229
+ case 'failed':
230
+ case 'cancelled': {
231
+ pairSay(view.message || 'Pairing failed.');
232
+ return false;
233
+ }
234
+
235
+ default: {
236
+ pairSay('Asking the system ...');
237
+ return true;
238
+ }
239
+ }
240
+ };
241
+
242
+ const pairPoll = () => {
243
+ const pairing = ccuActivePairing;
244
+ if (!pairing) {
245
+ return;
246
+ }
247
+
248
+ $.getJSON('ccu/pair/' + pairing.id)
249
+ .done(view => {
250
+ if (ccuActivePairing !== pairing) {
251
+ return;
252
+ }
253
+
254
+ if (pairShow(view)) {
255
+ pairing.timer = setTimeout(pairPoll, 1000);
256
+ } else {
257
+ ccuStopPairing(false);
258
+ pairButton();
259
+ }
260
+ })
261
+ .fail(xhr => {
262
+ if (ccuActivePairing !== pairing) {
263
+ return;
264
+ }
265
+
266
+ pairSay((xhr.responseJSON && xhr.responseJSON.message) || 'Pairing failed: ' + xhr.statusText);
267
+ ccuStopPairing(false);
268
+ pairButton();
269
+ });
270
+ };
271
+
272
+ $pair.on('click', () => {
273
+ if (ccuActivePairing) {
274
+ ccuStopPairing(true);
275
+ $pairStatus.html(pairIdle);
276
+ pairButton();
277
+ return;
278
+ }
279
+
280
+ ccuActivePairing = {id: null, timer: null};
281
+ const pairing = ccuActivePairing;
282
+ pairButton();
283
+ pairSay('Asking the system ...');
284
+ $.ajax({
285
+ url: 'ccu/pair',
286
+ type: 'POST',
287
+ contentType: 'application/json',
288
+ dataType: 'json',
289
+ data: JSON.stringify({
290
+ host: $nodeConfigInputHost.val(),
291
+ tls: $('#node-config-input-tls').is(':checked'),
292
+ port: $('#node-config-input-metaPort').val()
293
+ })
294
+ })
295
+ .done(answer => {
296
+ if (ccuActivePairing !== pairing) {
297
+ $.ajax({url: 'ccu/pair/' + answer.id, type: 'DELETE'});
298
+ return;
299
+ }
300
+
301
+ pairing.id = answer.id;
302
+ pairPoll();
303
+ })
304
+ .fail(xhr => {
305
+ if (ccuActivePairing !== pairing) {
306
+ return;
307
+ }
308
+
309
+ pairSay((xhr.responseJSON && xhr.responseJSON.message) || 'Pairing failed: ' + xhr.statusText);
310
+ ccuStopPairing(false);
311
+ pairButton();
312
+ });
313
+ });
314
+
171
315
  // task 9: re-read the device table of the deployed connection
172
316
  const $reread = $('#node-config-reread');
173
317
  const $rereadStatus = $('#node-config-reread-status');
@@ -321,10 +465,23 @@
321
465
  <option value="ccu">CCU: directly, with callbacks (XML-RPC/BIN-RPC) - on openccu-lite too</option>
322
466
  </select>
323
467
  </div>
468
+ <div class="form-row">
469
+ <label for="node-config-pair"><i class="icon-tag"></i> openccu-lite pairing</label>
470
+ <div style="width: 70%; display: inline-block; vertical-align: text-top;">
471
+ <button type="button" class="red-ui-button" id="node-config-pair">Pair with the system</button><br>
472
+ <small id="node-config-pair-status">For an openccu-lite system on the network: asks it for access, shows a code to approve on its Status page, and fills the token and the certificate below. Deploy afterwards.</small>
473
+ <small id="node-config-pair-local" style="display: none;">Node-RED runs on the system itself: the connection configures itself, nothing to pair.</small>
474
+ </div>
475
+ </div>
324
476
  <div class="form-row">
325
477
  <label for="node-config-input-metaToken"><i class="icon-tag"></i> openccu-lite token</label>
326
478
  <input type="password" id="node-config-input-metaToken" placeholder="olt_...">
327
- <small>Only for openccu-lite (a CCU ignores this). Leave empty when Node-RED runs on the system itself (RedMatic).</small>
479
+ <small>Only for openccu-lite (a CCU ignores this): filled by pairing, or a token made on the system's API tokens page. Leave empty when Node-RED runs on the system itself (RedMatic).</small>
480
+ </div>
481
+ <div class="form-row">
482
+ <label for="node-config-input-fingerprint256"><i class="icon-tag"></i> Pinned certificate</label>
483
+ <input type="text" id="node-config-input-fingerprint256" placeholder="SHA-256, filled by pairing">
484
+ <small>With TLS, the openccu-lite connection accepts exactly this certificate of the system (no need to ignore invalid certificates). Empty: the usual certificate checks.</small>
328
485
  </div>
329
486
  <div class="form-row">
330
487
  <label for="node-config-input-metaPort"><i class="icon-tag"></i> openccu-lite port</label>
@@ -19,6 +19,7 @@ const {Rega} = require('homematic-rega'); // ES module - require(esm) needs Node
19
19
  const metaProvider = require('./lib/metaprovider.js');
20
20
  const {InitRetry, retryDelay, RETRY_INTERVAL} = require('./lib/initretry.js');
21
21
  const lite = require('./lib/lite.js');
22
+ const {Pairings} = require('./lib/pairing.js');
22
23
  const {writeJsonAtomic, DebouncedSave} = require('./lib/cachefile.js');
23
24
  const {SubscriptionIndex, matches: filterMatches} = require('./lib/subscriptions.js');
24
25
  const xmlrpc = require('homematic-xmlrpc');
@@ -165,6 +166,42 @@ module.exports = function (RED) {
165
166
  .catch((error) => res.status(500).send(JSON.stringify({error: error.message})));
166
167
  });
167
168
 
169
+ // pairing with an openccu-lite system from the connection node's dialog (lib/pairing.js) - for a
170
+ // Node-RED elsewhere; on the system itself the connection configures itself and pairs nothing
171
+ const pairings = new Pairings({
172
+ load: lite.load,
173
+ isLocal: (host) => isLocalCcu(host),
174
+ appVersion: pkg.version,
175
+ logger: {
176
+ info: (message) => RED.log.info('ccu: ' + message),
177
+ warn: (message) => RED.log.warn('ccu: ' + message),
178
+ },
179
+ });
180
+
181
+ RED.httpAdmin.post('/ccu/pair', RED.auth.needsPermission('ccu.write'), (request, res) => {
182
+ const {host, tls, port} = request.body;
183
+ try {
184
+ const id = pairings.start({host, tls: tls === true || tls === 'true', port});
185
+ res.status(202).json({id});
186
+ } catch (error) {
187
+ res.status(error.status).json({error: error.code, message: error.message});
188
+ }
189
+ });
190
+
191
+ RED.httpAdmin.get('/ccu/pair/:id', RED.auth.needsPermission('ccu.write'), (request, res) => {
192
+ const view = pairings.get(request.params.id);
193
+ if (view) {
194
+ res.status(200).json(view);
195
+ } else {
196
+ res.status(404).json({error: 'not-found', message: 'No such pairing request (it ended or was withdrawn).'});
197
+ }
198
+ });
199
+
200
+ RED.httpAdmin.delete('/ccu/pair/:id', RED.auth.needsPermission('ccu.write'), (request, res) => {
201
+ pairings.cancel(request.params.id);
202
+ res.status(204).end();
203
+ });
204
+
168
205
  RED.httpAdmin.get('/ccu', RED.auth.needsPermission('ccu.read'), (request, res) => {
169
206
  if (request.query.config && request.query.config !== '_ADD_') {
170
207
  const config = RED.nodes.getNode(request.query.config);
@@ -683,6 +720,9 @@ module.exports = function (RED) {
683
720
  this.inSecure = inSecure;
684
721
  this.metaPort = Number.parseInt(config.metaPort, 10) || (tls ? 443 : 80);
685
722
  this.metaToken = config.metaToken || metaProvider.readLocalToken();
723
+ // the system's certificate as pinned at pairing (the dialog fills it): the metadata
724
+ // api and lite-rpc accept exactly that one, whatever "ignore invalid certificates" says
725
+ this.fingerprint256 = tls ? String((this.credentials && this.credentials.fingerprint256) || '').trim() : '';
686
726
  // task 14: the way to the interfaces on openccu-lite - `auto` (the default) goes through
687
727
  // the system's lite-rpc where the system is openccu-lite and a credential allows it,
688
728
  // `openccu-lite` insists on it, `ccu` keeps the direct connection with callbacks there
@@ -1613,6 +1653,7 @@ module.exports = function (RED) {
1613
1653
  port: this.metaPort,
1614
1654
  tls: Boolean(this.tlsEnabled),
1615
1655
  insecure: Boolean(this.inSecure),
1656
+ fingerprint256: this.fingerprint256,
1616
1657
  logger: this.logger,
1617
1658
  });
1618
1659
  }
@@ -1763,6 +1804,7 @@ module.exports = function (RED) {
1763
1804
  port: this.metaPort,
1764
1805
  tls: Boolean(this.tlsEnabled),
1765
1806
  insecure: Boolean(this.inSecure),
1807
+ fingerprint256: this.fingerprint256,
1766
1808
  token: this.metaToken,
1767
1809
  logger: this.logger,
1768
1810
  onNames: (names) => {
@@ -2618,6 +2660,7 @@ module.exports = function (RED) {
2618
2660
  url,
2619
2661
  token: this.liteToken,
2620
2662
  insecure: Boolean(this.inSecure),
2663
+ fingerprint256: this.fingerprint256,
2621
2664
  interfaces: ifaces,
2622
2665
  initId: (iface) => this.liteInitId(iface),
2623
2666
  logger: this.logger,
@@ -4927,6 +4970,7 @@ module.exports = function (RED) {
4927
4970
  credentials: {
4928
4971
  password: {type: 'password'},
4929
4972
  metaToken: {type: 'password'},
4973
+ fingerprint256: {type: 'text'},
4930
4974
  },
4931
4975
  });
4932
4976
  };
package/nodes/lib/lite.js CHANGED
@@ -38,15 +38,15 @@ let modules = null;
38
38
 
39
39
  /**
40
40
  * occulite-client, loaded once. Throws with a readable message where it cannot be loaded.
41
- * @returns {{OccuLite: Function, callbackEvents: Function, nodeTransport: Function}}
41
+ * @returns {{OccuLite: Function, callbackEvents: Function, nodeTransport: Function, pair: Function, probe: Function}}
42
42
  */
43
43
  function load() {
44
44
  if (!modules) {
45
45
  try {
46
46
  const {OccuLite} = require('occulite-client');
47
47
  const {callbackEvents} = require('occulite-client/callbacks');
48
- const {nodeTransport} = require('occulite-client/node');
49
- modules = {OccuLite, callbackEvents, nodeTransport};
48
+ const {nodeTransport, pair, probe} = require('occulite-client/node');
49
+ modules = {OccuLite, callbackEvents, nodeTransport, pair, probe};
50
50
  } catch (error) {
51
51
  throw new Error(
52
52
  'occulite-client cannot be loaded (' +
@@ -203,12 +203,27 @@ function tierAwareTransport(transport) {
203
203
  };
204
204
  }
205
205
 
206
+ /**
207
+ * The certificate trust for occulite-client's transport: the fingerprint pinned at pairing, else
208
+ * any certificate where the node says so, else Node's own store.
209
+ * @param {{fingerprint256?: string, insecure?: boolean}} options
210
+ * @returns {object}
211
+ */
212
+ function trustOf({fingerprint256, insecure}) {
213
+ if (fingerprint256) {
214
+ return {fingerprint256};
215
+ }
216
+
217
+ return insecure ? {insecure: true} : {};
218
+ }
219
+
206
220
  class LiteConnection {
207
221
  /**
208
222
  * @param {object} options
209
223
  * @param {string} options.url the system, scheme and authority
210
224
  * @param {string} options.token the credential
211
225
  * @param {boolean} [options.insecure] accept any certificate
226
+ * @param {string} [options.fingerprint256] accept exactly this certificate (pinned at pairing; wins over insecure)
212
227
  * @param {string[]} options.interfaces the interfaces to follow (the enabled ones lite-rpc carries)
213
228
  * @param {function(string): string} options.initId the init id the connection's callback table expects per interface
214
229
  * @param {function(string, *, Array, Function)} options.onCallback (method, err, params, answer): a callback server's call
@@ -249,7 +264,7 @@ class LiteConnection {
249
264
  const clientOptions = {
250
265
  url: this.options.url,
251
266
  auth: {token: this.options.token},
252
- transport: tierAwareTransport(nodeTransport(this.options.insecure ? {insecure: true} : {})),
267
+ transport: tierAwareTransport(nodeTransport(trustOf(this.options))),
253
268
  interfaces: this.interfaces,
254
269
  values: true,
255
270
  meta: false,
@@ -357,6 +372,7 @@ module.exports = {
357
372
  readAddonToken,
358
373
  liteValue,
359
374
  tierAwareTransport,
375
+ trustOf,
360
376
  translateError,
361
377
  isFault,
362
378
  load,
@@ -24,6 +24,8 @@
24
24
  const fs = require('fs');
25
25
  const http = require('http');
26
26
  const https = require('https');
27
+ const net = require('net');
28
+ const tls = require('tls');
27
29
 
28
30
  const API_PATH = '/api/meta/v1';
29
31
 
@@ -210,28 +212,86 @@ function readLocalToken(file = LOCAL_TOKEN_FILE) {
210
212
  }
211
213
  }
212
214
 
215
+ /** a fingerprint as its bare lower-case hex, for comparing */
216
+ const bareFingerprint = (fingerprint) => String(fingerprint).replace(/:/g, '').toLowerCase();
217
+
218
+ /**
219
+ * A TLS connection that accepts exactly the certificate pinned at pairing (the system's own,
220
+ * usually self-signed): the socket goes to the request only after the handshake and the check, so
221
+ * nothing - the token least of all - is written to another server.
222
+ * @param {string} host
223
+ * @param {number} port
224
+ * @param {string} fingerprint256 colon-separated SHA-256, as pairing returns it
225
+ * @param {number} [timeout] for the connection and the handshake, ms (0: none)
226
+ * @returns {function(object, Function): undefined} for the request's createConnection
227
+ */
228
+ function pinnedConnection(host, port, fingerprint256, timeout) {
229
+ const pin = bareFingerprint(fingerprint256);
230
+ const name = String(host).replace(/^\[|\]$/g, '');
231
+ return (_options, oncreate) => {
232
+ const socket = tls.connect({
233
+ host: name,
234
+ port,
235
+ servername: net.isIP(name) ? undefined : name,
236
+ rejectUnauthorized: false,
237
+ });
238
+ if (timeout > 0) {
239
+ // the request's own timeout starts only once it has the socket, after the handshake
240
+ socket.setTimeout(timeout, () => socket.destroy(new Error('timeout')));
241
+ }
242
+
243
+ socket.once('secureConnect', () => {
244
+ socket.setTimeout(0);
245
+ const seen = socket.getPeerCertificate().fingerprint256;
246
+ if (bareFingerprint(seen) !== pin) {
247
+ socket.destroy();
248
+ oncreate(new Error('the system presents another certificate than the one pinned at pairing'));
249
+ return;
250
+ }
251
+
252
+ oncreate(null, socket);
253
+ });
254
+ socket.once('error', (error) => oncreate(error));
255
+ return undefined;
256
+ };
257
+ }
258
+
213
259
  /**
214
260
  * One HTTP request against the metadata API.
215
261
  * @param {object} options
216
262
  * @returns {Promise<{status: number, headers: object, res: object, body: Promise<string>}>}
217
263
  */
218
264
  function request(options) {
219
- const {host, port, tls, insecure, path, token, timeout = 10000, idleTimeout, accept = 'application/json'} = options;
265
+ const {
266
+ host,
267
+ port,
268
+ tls: useTls,
269
+ insecure,
270
+ fingerprint256,
271
+ path,
272
+ token,
273
+ timeout = 10000,
274
+ idleTimeout,
275
+ accept = 'application/json',
276
+ } = options;
220
277
  return new Promise((resolve, reject) => {
221
278
  const headers = {accept, 'user-agent': 'node-red-contrib-ccu'};
222
279
  if (token) {
223
280
  headers.authorization = 'Bearer ' + token;
224
281
  }
225
282
 
226
- const lib = tls ? https : http;
283
+ const lib = useTls ? https : http;
227
284
  const requestOptions = {
228
285
  host,
229
286
  port,
230
287
  path,
231
288
  method: 'GET',
232
289
  headers,
233
- ...(tls ? {rejectUnauthorized: !insecure} : {}),
290
+ ...(useTls ? {rejectUnauthorized: !insecure} : {}),
234
291
  };
292
+ if (useTls && fingerprint256) {
293
+ requestOptions.createConnection = pinnedConnection(host, port, fingerprint256, timeout);
294
+ }
235
295
  if (timeout > 0) {
236
296
  // as an option, not request.setTimeout(): only this form arms the
237
297
  // timer before the socket is connected, so an unreachable box does
@@ -355,6 +415,7 @@ class MetaProvider {
355
415
  this.port = options.port || (options.tls ? 443 : 80);
356
416
  this.tls = Boolean(options.tls);
357
417
  this.insecure = Boolean(options.insecure);
418
+ this.fingerprint256 = options.fingerprint256 || '';
358
419
  this.token = options.token || '';
359
420
  this.logger = options.logger || SILENT;
360
421
  this.onNames = options.onNames || NOOP;
@@ -452,6 +513,7 @@ class MetaProvider {
452
513
  port: this.port,
453
514
  tls: this.tls,
454
515
  insecure: this.insecure,
516
+ fingerprint256: this.fingerprint256,
455
517
  logger: this.logger,
456
518
  });
457
519
  if (info) {
@@ -495,6 +557,7 @@ class MetaProvider {
495
557
  port: this.port,
496
558
  tls: this.tls,
497
559
  insecure: this.insecure,
560
+ fingerprint256: this.fingerprint256,
498
561
  path: API_PATH + '/snapshot',
499
562
  token: this.token,
500
563
  timeout: this.requestTimeout,
@@ -578,6 +641,7 @@ class MetaProvider {
578
641
  port: this.port,
579
642
  tls: this.tls,
580
643
  insecure: this.insecure,
644
+ fingerprint256: this.fingerprint256,
581
645
  path: API_PATH + '/events/sse?since=' + this.revision,
582
646
  token: this.token,
583
647
  accept: 'text/event-stream',
@@ -738,6 +802,7 @@ module.exports = {
738
802
  detectOutcome,
739
803
  flattenEnum,
740
804
  memberNames,
805
+ pinnedConnection,
741
806
  readLocalToken,
742
807
  refToAddress,
743
808
  refToIface,
@@ -0,0 +1,305 @@
1
+ /* Pairing with an openccu-lite system from the connection node's dialog.
2
+
3
+ A Node-RED that runs elsewhere asks the system for a token instead of
4
+ having one pasted: the dialog sends the address, the runtime finds out
5
+ what answers there (occulite-client's probe - it follows the system's
6
+ redirect to https), asks for access (occulite-client's pair) and shows
7
+ the six-digit code the system's Status page shows too. An administrator
8
+ approves it there; the dialog then gets the token and the fingerprint of
9
+ the certificate the code was bound to, fills the credentials and the user
10
+ deploys. The connection pins that certificate from then on.
11
+
12
+ Node-RED on the system itself (RedMatic on openccu-lite) needs none of
13
+ this: the connection configures itself from the addon's own token, so a
14
+ pairing request for a local connection is refused.
15
+
16
+ One request per id, held in memory: the dialog polls it, and its token is
17
+ handed out once. A request nobody polls any more is withdrawn. */
18
+
19
+ const crypto = require('crypto');
20
+ const os = require('os');
21
+
22
+ /** what the connection asks for: devices up to pairing and deleting them, the names read */
23
+ const ACCESS = {devices: 'administer', names: 'read'};
24
+ const PURPOSE = {
25
+ devices: 'Node-RED flows read and set datapoints; the rpc node may call any method of the interfaces',
26
+ names: 'channel names, rooms and functions in the nodes and their messages',
27
+ };
28
+ const APP = 'node-red-contrib-ccu';
29
+
30
+ /** the system lets a request expire after five minutes; a little longer here, so its own answer comes first */
31
+ const PAIR_TIMEOUT_MS = 6 * 60 * 1000;
32
+ /** a request nobody polled for this long is withdrawn (the dialog was closed) */
33
+ const ABANDON_MS = 60 * 1000;
34
+ /** a settled request is kept this long for the dialog's last poll */
35
+ const KEEP_MS = 2 * 60 * 1000;
36
+
37
+ /** occulite-client's error codes and what the dialog says about them */
38
+ const MESSAGES = {
39
+ rejected: 'The administrator rejected the request (or chose another code).',
40
+ expired: 'Nobody approved the request within five minutes.',
41
+ timeout: 'Nobody approved the request in time.',
42
+ aborted: 'Pairing was cancelled.',
43
+ 'pairing-off': 'Pairing is switched off on the system ("Allow programs to ask for access" on its API tokens page).',
44
+ 'not-local':
45
+ 'The system accepts pairing requests only from its local networks - this Node-RED is outside them (see the firewall settings of the system).',
46
+ limit: 'The system refuses more pairing requests from this address for now - wait ten minutes and try again.',
47
+ certificate: 'The certificate of the system cannot be checked.',
48
+ };
49
+
50
+ /**
51
+ * The address the probe starts from: the host as entered, with the scheme and port the dialog
52
+ * names; without a port the probe goes to http and follows the system's redirect to https.
53
+ * @param {object} options
54
+ * @param {string} options.host
55
+ * @param {boolean} [options.tls]
56
+ * @param {string|number} [options.port]
57
+ * @returns {string}
58
+ */
59
+ function addressOf({host, tls, port}) {
60
+ const name = String(host).trim();
61
+ const bracketed = name.includes(':') && !name.startsWith('[') ? '[' + name + ']' : name;
62
+ const portNumber = Number.parseInt(port, 10);
63
+ if (portNumber > 0) {
64
+ return (tls ? 'https' : 'http') + '://' + bracketed + ':' + portNumber;
65
+ }
66
+
67
+ return tls ? 'https://' + bracketed : bracketed;
68
+ }
69
+
70
+ /**
71
+ * The connection node's settings for the system's URL: TLS and the port when it is not the default.
72
+ * @param {string} url scheme and authority
73
+ * @returns {{tls: boolean, port: string}}
74
+ */
75
+ function settingsOf(url) {
76
+ const parsed = new URL(url);
77
+ return {tls: parsed.protocol === 'https:', port: parsed.port};
78
+ }
79
+
80
+ /**
81
+ * The dialog's message for an error of occulite-client.
82
+ * @param {*} error
83
+ * @returns {{error: string, message: string}}
84
+ */
85
+ function describeError(error) {
86
+ const code = (error && error.name === 'OccuLiteError' && error.code) || (error && error.kind) || 'failed';
87
+ const message = MESSAGES[code] || 'Pairing failed: ' + ((error && error.message) || String(error));
88
+ return {error: code, message};
89
+ }
90
+
91
+ class Pairings {
92
+ /**
93
+ * @param {object} options
94
+ * @param {function(): {pair: Function, probe: Function}} options.load occulite-client's pair and probe
95
+ * @param {function(string): boolean} options.isLocal whether a host is the system Node-RED runs on
96
+ * @param {string} [options.appVersion]
97
+ * @param {string} [options.instance] what the system's Status page names this Node-RED by
98
+ * @param {object} [options.logger] {info, warn}
99
+ * @param {number} [options.pairTimeout]
100
+ * @param {number} [options.abandonAfter]
101
+ * @param {number} [options.keepFor]
102
+ */
103
+ constructor(options) {
104
+ this.load = options.load;
105
+ this.isLocal = options.isLocal;
106
+ this.appVersion = options.appVersion;
107
+ this.instance = options.instance || os.hostname();
108
+ this.logger = options.logger || {info() {}, warn() {}};
109
+ this.pairTimeout = options.pairTimeout || PAIR_TIMEOUT_MS;
110
+ this.abandonAfter = options.abandonAfter || ABANDON_MS;
111
+ this.keepFor = options.keepFor || KEEP_MS;
112
+ this.requests = new Map();
113
+ }
114
+
115
+ /**
116
+ * Starts a pairing. Throws (with `status`) on what is refused at once: no address, a local
117
+ * connection, occulite-client not loadable.
118
+ * @param {object} options
119
+ * @param {string} options.host the address in the dialog
120
+ * @param {boolean} [options.tls]
121
+ * @param {string|number} [options.port] the openccu-lite port of the dialog
122
+ * @returns {string} the request's id
123
+ */
124
+ start({host, tls, port}) {
125
+ if (!host || !String(host).trim()) {
126
+ throw Object.assign(new Error('Enter the address of the system first.'), {status: 400, code: 'host'});
127
+ }
128
+
129
+ if (this.isLocal(String(host).trim())) {
130
+ throw Object.assign(
131
+ new Error(
132
+ 'Node-RED runs on the system itself: the connection configures itself, no pairing is needed.',
133
+ ),
134
+ {status: 409, code: 'local'},
135
+ );
136
+ }
137
+
138
+ let modules;
139
+ try {
140
+ modules = this.load();
141
+ } catch (error) {
142
+ throw Object.assign(new Error(error.message), {status: 500, code: 'unavailable'});
143
+ }
144
+
145
+ const id = crypto.randomBytes(12).toString('hex');
146
+ const request = {
147
+ id,
148
+ state: 'probing',
149
+ controller: new AbortController(),
150
+ polled: Date.now(),
151
+ timer: null,
152
+ };
153
+ this.requests.set(id, request);
154
+ this.watch(request);
155
+ this.run(request, modules, addressOf({host, tls, port}));
156
+ return id;
157
+ }
158
+
159
+ /**
160
+ * The probe, then the pairing; the request's state follows.
161
+ * @param {object} request
162
+ * @param {{pair: Function, probe: Function}} modules
163
+ * @param {string} address
164
+ * @returns {Promise<void>}
165
+ */
166
+ async run(request, {pair, probe}, address) {
167
+ const {signal} = request.controller;
168
+ try {
169
+ const found = await probe(address, {timeout: 5000, signal});
170
+ if (found.kind !== 'openccu-lite') {
171
+ const message =
172
+ found.kind === 'ccu'
173
+ ? 'This is not an openccu-lite system. A CCU pairs no programs - enter its credentials under Authentication instead.'
174
+ : found.reason === 'certificate'
175
+ ? MESSAGES.certificate
176
+ : 'The system does not answer' + (found.reason ? ' (' + found.reason + ').' : '.');
177
+ this.settle(request, {
178
+ state: 'failed',
179
+ error: found.kind === 'ccu' ? 'not-openccu-lite' : 'unreachable',
180
+ message,
181
+ });
182
+ return;
183
+ }
184
+
185
+ const capabilities = (found.info && found.info.capabilities) || {};
186
+ if (capabilities.pairing === false) {
187
+ this.settle(request, {state: 'failed', error: 'pairing-off', message: MESSAGES['pairing-off']});
188
+ return;
189
+ }
190
+
191
+ request.url = found.url;
192
+ request.state = 'requesting';
193
+ const paired = await pair({
194
+ url: found.url,
195
+ app: APP,
196
+ appVersion: this.appVersion,
197
+ instance: this.instance,
198
+ access: ACCESS,
199
+ purpose: PURPOSE,
200
+ signal,
201
+ timeout: this.pairTimeout,
202
+ onCode: (code) => {
203
+ request.code = code;
204
+ request.state = 'waiting';
205
+ this.logger.info('pairing with ' + found.url + ': code ' + code + ', waiting for the approval');
206
+ },
207
+ });
208
+ this.logger.info('paired with ' + found.url + ' as ' + paired.name);
209
+ this.settle(request, {
210
+ state: 'approved',
211
+ token: paired.token,
212
+ fingerprint256: paired.fingerprint256 || '',
213
+ name: paired.name,
214
+ scopes: paired.scopes,
215
+ ...settingsOf(found.url),
216
+ });
217
+ } catch (error) {
218
+ const {error: code, message} = describeError(error);
219
+ if (code !== 'aborted') {
220
+ this.logger.warn('pairing with ' + (request.url || address) + ' failed: ' + message);
221
+ }
222
+
223
+ this.settle(request, {state: code === 'aborted' ? 'cancelled' : 'failed', error: code, message});
224
+ }
225
+ }
226
+
227
+ /**
228
+ * Withdraws a request the dialog stopped polling.
229
+ * @param {object} request
230
+ */
231
+ watch(request) {
232
+ request.timer = setInterval(
233
+ () => {
234
+ if (Date.now() - request.polled > this.abandonAfter) {
235
+ this.cancel(request.id);
236
+ }
237
+ },
238
+ Math.min(this.abandonAfter, 10000),
239
+ );
240
+ request.timer.unref();
241
+ }
242
+
243
+ /**
244
+ * The outcome; the request stays for the dialog's last poll.
245
+ * @param {object} request
246
+ * @param {object} outcome
247
+ */
248
+ settle(request, outcome) {
249
+ clearInterval(request.timer);
250
+ Object.assign(request, outcome);
251
+ request.timer = setTimeout(() => this.requests.delete(request.id), this.keepFor);
252
+ request.timer.unref();
253
+ }
254
+
255
+ /**
256
+ * The dialog's view of a request; the token is in it once.
257
+ * @param {string} id
258
+ * @returns {object|undefined}
259
+ */
260
+ get(id) {
261
+ const request = this.requests.get(id);
262
+ if (!request) {
263
+ return undefined;
264
+ }
265
+
266
+ request.polled = Date.now();
267
+ const view = {state: request.state};
268
+ ['code', 'url', 'error', 'message', 'name', 'fingerprint256', 'tls', 'port', 'token'].forEach((key) => {
269
+ if (request[key] !== undefined) {
270
+ view[key] = request[key];
271
+ }
272
+ });
273
+ if (request.state === 'approved' || request.state === 'failed' || request.state === 'cancelled') {
274
+ clearTimeout(request.timer);
275
+ this.requests.delete(request.id);
276
+ }
277
+
278
+ return view;
279
+ }
280
+
281
+ /**
282
+ * Withdraws a request (the dialog was closed or its button pressed again).
283
+ * @param {string} id
284
+ * @returns {boolean} whether there was one
285
+ */
286
+ cancel(id) {
287
+ const request = this.requests.get(id);
288
+ if (!request) {
289
+ return false;
290
+ }
291
+
292
+ clearInterval(request.timer);
293
+ clearTimeout(request.timer);
294
+ this.requests.delete(id);
295
+ request.controller.abort();
296
+ return true;
297
+ }
298
+
299
+ /** Withdraws every request (Node-RED stops). */
300
+ close() {
301
+ [...this.requests.keys()].forEach((id) => this.cancel(id));
302
+ }
303
+ }
304
+
305
+ module.exports = {Pairings, addressOf, settingsOf, describeError, ACCESS, APP, MESSAGES};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "node-red-contrib-ccu",
3
- "version": "4.8.0",
3
+ "version": "4.9.0",
4
4
  "license": "MIT",
5
5
  "main": "none",
6
6
  "keywords": [