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.
@@ -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.10.0",
4
4
  "license": "MIT",
5
5
  "main": "none",
6
6
  "keywords": [
@@ -54,7 +54,7 @@
54
54
  "homematic-rega": "^2.0.1",
55
55
  "homematic-xmlrpc": "^2.0.0",
56
56
  "mqtt-wildcard": "^3.0.9",
57
- "occulite-client": "^0.3.0"
57
+ "occulite-client": "^0.4.0"
58
58
  },
59
59
  "deprecated": false,
60
60
  "description": "Node-RED Nodes for the Homematic CCU",