node-red-contrib-ccu 4.8.0 → 4.10.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,50 @@ 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.10.0 (2026-11-09)
9
+
10
+ ### Changed
11
+
12
+ - **openccu-lite: the names come from occulite-client's live copy.** The
13
+ connection's own HTTP client for the metadata API (snapshot, change
14
+ stream, re-reads) is gone; names, rooms and functions now come from
15
+ occulite-client, in the ReGa shape as before. Where the connection node
16
+ has its own token (as pairing makes it), one client serves the names and
17
+ the interfaces - one connection to the system instead of two. Where the
18
+ names and the interfaces have different credentials (RedMatic on the
19
+ system: the system's read-only token for the names, RedMatic's own token
20
+ for lite-rpc) or the interfaces go the CCU way, a names-only client follows
21
+ the names and opens no lite-rpc stream of its own.
22
+
23
+ ### Fixed
24
+
25
+ - **openccu-lite: a system that did not answer the first connect of the
26
+ lite-rpc client is connected later.** The client was given up after a
27
+ failed first connect while the log said it kept trying; now a new client
28
+ is opened after 5 s, growing to a minute. A refused credential, or a system
29
+ that is not openccu-lite, still ends it with a message.
30
+
31
+ ## 4.9.0 (2026-11-09)
32
+
33
+ ### Added
34
+
35
+ - **Pairing with an openccu-lite system from the connection node.** A
36
+ Node-RED that does not run on the system no longer needs a token copied
37
+ from the system's API tokens page: _Pair with the system_ asks the system
38
+ at the configured address for access, the dialog shows a six-digit code,
39
+ an administrator compares and approves it on the system's Status page, and
40
+ the dialog fills in the token and the fingerprint of the system's
41
+ certificate (and TLS, where the system redirects to https). After the
42
+ deploy the metadata API and lite-rpc accept exactly that certificate, so
43
+ the system's own self-signed certificate works without _Ignore invalid TLS
44
+ Certificates_; another certificate is refused before the token is sent. A
45
+ rejection, an expired request, a CCU or nothing at the address, pairing
46
+ switched off on the system or a request from outside its local networks
47
+ are said in the dialog. Closing the dialog withdraws a pending request.
48
+ Node-RED on the system itself (RedMatic on openccu-lite) is unchanged: it
49
+ configures itself, the dialog shows no pairing there and the runtime
50
+ refuses a pairing request for a local connection.
51
+
8
52
  ## 4.8.0 (2026-10-29)
9
53
 
10
54
  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
@@ -692,6 +732,8 @@ module.exports = function (RED) {
692
732
  ? config.connectionType
693
733
  : 'auto';
694
734
  this.liteToken = config.metaToken || lite.readAddonToken();
735
+ // the enabled interfaces, for startMeta()'s choice of one client for names and interfaces
736
+ this.liteConfig = config;
695
737
  this.lite = null;
696
738
  this.liteIfaces = [];
697
739
  this.metaMode = false;
@@ -1613,6 +1655,7 @@ module.exports = function (RED) {
1613
1655
  port: this.metaPort,
1614
1656
  tls: Boolean(this.tlsEnabled),
1615
1657
  insecure: Boolean(this.inSecure),
1658
+ fingerprint256: this.fingerprint256,
1616
1659
  logger: this.logger,
1617
1660
  });
1618
1661
  }
@@ -1756,14 +1799,24 @@ module.exports = function (RED) {
1756
1799
  );
1757
1800
  }
1758
1801
 
1802
+ // one client for names and interfaces where the lite-rpc credential reads the names too
1803
+ // (the connection node's own token, as pairing makes it); a names-only client of its own
1804
+ // where they differ (RedMatic: the system's local token for the names, the addon token
1805
+ // for lite-rpc) or where the interfaces go another way
1806
+ const shared =
1807
+ Boolean(this.metaToken) &&
1808
+ this.metaToken === this.liteToken &&
1809
+ this.liteInterfaces(this.liteConfig, true).length > 0;
1759
1810
  return new Promise((resolve) => {
1760
- const done = setTimeout(resolve, 5000);
1811
+ const done = setTimeout(resolve, shared ? 0 : 5000);
1761
1812
  this.meta = new metaProvider.MetaProvider({
1762
1813
  host: this.host,
1763
1814
  port: this.metaPort,
1764
1815
  tls: Boolean(this.tlsEnabled),
1765
1816
  insecure: Boolean(this.inSecure),
1817
+ fingerprint256: this.fingerprint256,
1766
1818
  token: this.metaToken,
1819
+ shared,
1767
1820
  logger: this.logger,
1768
1821
  onNames: (names) => {
1769
1822
  this.applyMetaNames(names);
@@ -2528,12 +2581,14 @@ module.exports = function (RED) {
2528
2581
  * lite-rpc carries (not CUxD, not CCU-Jack), on an openccu-lite system, with a credential,
2529
2582
  * unless the connection type says `ccu`.
2530
2583
  * @param {object} config the node's config
2584
+ * @param {boolean} [quiet] no log line for a CCU by choice (startMeta's look ahead, which runs
2585
+ * with the system detected and a credential at hand)
2531
2586
  * @returns {string[]}
2532
2587
  */
2533
- liteInterfaces(config) {
2588
+ liteInterfaces(config, quiet = false) {
2534
2589
  const enabled = lite.LITE_INTERFACES.filter((iface) => config[this.ifaceTypes[iface].conf + 'Enabled']);
2535
2590
  if (this.connectionType === 'ccu') {
2536
- if (this.metaMode) {
2591
+ if (this.metaMode && !quiet) {
2537
2592
  this.logger.info(
2538
2593
  'openccu-lite: the direct connection with callbacks by choice (connection type CCU) - the interfaces are reached on their own ports',
2539
2594
  );
@@ -2618,7 +2673,15 @@ module.exports = function (RED) {
2618
2673
  url,
2619
2674
  token: this.liteToken,
2620
2675
  insecure: Boolean(this.inSecure),
2676
+ fingerprint256: this.fingerprint256,
2621
2677
  interfaces: ifaces,
2678
+ // the names from the same client (startMeta decided it): its live copy to the provider
2679
+ meta: Boolean(this.meta && this.meta.shared),
2680
+ onBox: (box) => {
2681
+ if (this.meta && this.meta.shared) {
2682
+ this.meta.attach(box);
2683
+ }
2684
+ },
2622
2685
  initId: (iface) => this.liteInitId(iface),
2623
2686
  logger: this.logger,
2624
2687
  createClient: this.liteCreateClient,
@@ -4927,6 +4990,7 @@ module.exports = function (RED) {
4927
4990
  credentials: {
4928
4991
  password: {type: 'password'},
4929
4992
  metaToken: {type: 'password'},
4993
+ fingerprint256: {type: 'text'},
4930
4994
  },
4931
4995
  });
4932
4996
  };
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 (' +
@@ -167,40 +167,18 @@ function liteValue(value, jsonDouble) {
167
167
  return value;
168
168
  }
169
169
 
170
- const RPC_TIERS = ['rpc:operate', 'rpc:configure', 'rpc:admin'];
171
-
172
170
  /**
173
- * occulite-client B-3: the client decides "names only" from the literal `rpc:read` in
174
- * GET /api/auth/v1/state, but a token made with a higher tier (rpc:admin, say) carries that tier
175
- * alone - the system includes the lower ones. The transport spells `rpc:read` out for the client
176
- * where a tier implies it. Goes once the package fixes it.
177
- * @param {object} transport occulite-client's Transport
178
- * @returns {object} the same transport
171
+ * The certificate trust for occulite-client's transport: the fingerprint pinned at pairing, else
172
+ * any certificate where the node says so, else Node's own store.
173
+ * @param {{fingerprint256?: string, insecure?: boolean}} options
174
+ * @returns {object}
179
175
  */
180
- function tierAwareTransport(transport) {
181
- return {
182
- request: (method, url, headers, body, signal) =>
183
- transport.request(method, url, headers, body, signal).then((response) => {
184
- if (response.status !== 200 || !/\/api\/auth\/v1\/state(\?|$)/.test(String(url))) {
185
- return response;
186
- }
187
-
188
- let parsed;
189
- try {
190
- parsed = JSON.parse(response.body);
191
- } catch {
192
- return response;
193
- }
194
-
195
- const scopes = Array.isArray(parsed && parsed.scopes) ? parsed.scopes : [];
196
- if (scopes.includes('rpc:read') || !scopes.some((scope) => RPC_TIERS.includes(scope))) {
197
- return response;
198
- }
176
+ function trustOf({fingerprint256, insecure}) {
177
+ if (fingerprint256) {
178
+ return {fingerprint256};
179
+ }
199
180
 
200
- return {...response, body: JSON.stringify({...parsed, scopes: [...scopes, 'rpc:read']})};
201
- }),
202
- stream: (url, headers, signal) => transport.stream(url, headers, signal),
203
- };
181
+ return insecure ? {insecure: true} : {};
204
182
  }
205
183
 
206
184
  class LiteConnection {
@@ -209,6 +187,7 @@ class LiteConnection {
209
187
  * @param {string} options.url the system, scheme and authority
210
188
  * @param {string} options.token the credential
211
189
  * @param {boolean} [options.insecure] accept any certificate
190
+ * @param {string} [options.fingerprint256] accept exactly this certificate (pinned at pairing; wins over insecure)
212
191
  * @param {string[]} options.interfaces the interfaces to follow (the enabled ones lite-rpc carries)
213
192
  * @param {function(string): string} options.initId the init id the connection's callback table expects per interface
214
193
  * @param {function(string, *, Array, Function)} options.onCallback (method, err, params, answer): a callback server's call
@@ -218,6 +197,10 @@ class LiteConnection {
218
197
  * @param {object} options.logger {debug, info, warn, error}
219
198
  * @param {number} [options.timeout] per request, ms
220
199
  * @param {Function} [options.createClient] for tests, in place of new OccuLite()
200
+ * @param {boolean} [options.meta] the client keeps the live copy of the names too (one client for both)
201
+ * @param {function(object)} [options.onBox] every client this connection opens, before it connects
202
+ * @param {number} [options.retryMin] the first wait before a failed connect is tried again, ms
203
+ * @param {number} [options.retryMax] the longest wait, ms
221
204
  */
222
205
  constructor(options) {
223
206
  this.options = options;
@@ -227,6 +210,9 @@ class LiteConnection {
227
210
  this.server = null;
228
211
  this.closed = false;
229
212
  this.ready = false;
213
+ this.retryTimeout = null;
214
+ this.retryMin = options.retryMin === undefined ? 5000 : options.retryMin;
215
+ this.retryMax = options.retryMax === undefined ? 60000 : options.retryMax;
230
216
  }
231
217
 
232
218
  /**
@@ -238,27 +224,70 @@ class LiteConnection {
238
224
  }
239
225
 
240
226
  /**
241
- * Opens the client. Resolves once the first picture is loaded, rejects with the client's
242
- * reason (unauthenticated, forbidden, unreachable, timeout ...); the stream keeps trying by
243
- * itself afterwards.
227
+ * Opens the client. Resolves once the first picture is loaded. occulite-client (0.4) does not
228
+ * try a failed connect again (its streams only reconnect once connected), so a system that
229
+ * did not answer (unreachable, timeout, still starting) gets a new client after a wait,
230
+ * growing to a minute; a refused credential, or a system that is not openccu-lite, rejects.
244
231
  * @returns {Promise<void>}
245
232
  */
246
233
  start() {
234
+ return new Promise((resolve, reject) => {
235
+ let attempt = 0;
236
+ const connect = () => {
237
+ this.retryTimeout = null;
238
+ this.open().then(resolve, (error) => {
239
+ if (this.closed) {
240
+ reject(error);
241
+ return;
242
+ }
243
+
244
+ const kind = kindOf(error);
245
+ if (kind === 'unauthenticated' || kind === 'forbidden' || kind === 'unsupported') {
246
+ reject(error);
247
+ return;
248
+ }
249
+
250
+ const delay = Math.min(this.retryMin * 2 ** attempt, this.retryMax);
251
+ attempt += 1;
252
+ this.logger[attempt === 1 ? 'warn' : 'debug'](
253
+ 'lite-rpc: ' + (error.message || error) + ' - connecting again in ' + delay / 1000 + ' s',
254
+ );
255
+ this.retryTimeout = setTimeout(connect, delay);
256
+ });
257
+ };
258
+
259
+ connect();
260
+ });
261
+ }
262
+
263
+ /**
264
+ * One client: the stream's events into the callback table, the first picture.
265
+ * @returns {Promise<void>}
266
+ */
267
+ open() {
268
+ if (this.box) {
269
+ this.box.close();
270
+ }
271
+
247
272
  const {OccuLite, callbackEvents, nodeTransport} = load();
248
273
  const debug = (message) => this.logger.debug('occulite-client: ' + message);
249
274
  const clientOptions = {
250
275
  url: this.options.url,
251
276
  auth: {token: this.options.token},
252
- transport: tierAwareTransport(nodeTransport(this.options.insecure ? {insecure: true} : {})),
277
+ transport: nodeTransport(trustOf(this.options)),
253
278
  interfaces: this.interfaces,
254
279
  values: true,
255
- meta: false,
280
+ meta: Boolean(this.options.meta),
256
281
  devices: true,
257
282
  timeout: this.options.timeout || 30000,
258
283
  log: {debug, info: debug, warn: debug, error: debug},
259
284
  };
260
285
  const box = this.options.createClient ? this.options.createClient(clientOptions) : new OccuLite(clientOptions);
261
286
  this.box = box;
287
+ if (this.options.onBox) {
288
+ this.options.onBox(box);
289
+ }
290
+
262
291
  box.on('status', (event) => {
263
292
  if (this.closed || this.box !== box) {
264
293
  return;
@@ -342,6 +371,8 @@ class LiteConnection {
342
371
  close() {
343
372
  this.closed = true;
344
373
  this.ready = false;
374
+ clearTimeout(this.retryTimeout);
375
+ this.retryTimeout = null;
345
376
  if (this.box) {
346
377
  this.box.close();
347
378
  this.box = null;
@@ -356,7 +387,7 @@ module.exports = {
356
387
  CALLBACK_METHODS,
357
388
  readAddonToken,
358
389
  liteValue,
359
- tierAwareTransport,
390
+ trustOf,
360
391
  translateError,
361
392
  isFault,
362
393
  load,