homebridge-navilink 1.1.2 → 1.1.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.
Files changed (62) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +1 -0
  3. package/SECURITY.md +3 -3
  4. package/config.schema.json +2 -2
  5. package/dist/api/channel.d.ts +8 -0
  6. package/dist/api/channel.js +45 -26
  7. package/dist/api/circuit-breaker.d.ts +0 -2
  8. package/dist/api/circuit-breaker.js +0 -4
  9. package/dist/api/index.d.ts +1 -0
  10. package/dist/api/index.js +1 -0
  11. package/dist/api/iot-connection.d.ts +39 -0
  12. package/dist/api/iot-connection.js +50 -0
  13. package/dist/api/mqtt-codec.d.ts +13 -1
  14. package/dist/api/mqtt-codec.js +81 -27
  15. package/dist/api/protocol.d.ts +18 -6
  16. package/dist/api/protocol.js +19 -7
  17. package/dist/api/rest.d.ts +15 -0
  18. package/dist/api/rest.js +47 -43
  19. package/dist/control-gate.d.ts +78 -0
  20. package/dist/control-gate.js +133 -0
  21. package/dist/devices/base-accessory.d.ts +21 -10
  22. package/dist/devices/base-accessory.js +35 -31
  23. package/dist/devices/dhw-accessory.js +2 -2
  24. package/dist/devices/heating-accessory.js +3 -2
  25. package/dist/devices/host.d.ts +1 -3
  26. package/dist/devices/power-accessory.js +2 -2
  27. package/dist/devices/probe-accessory.js +3 -4
  28. package/dist/devices/recirculation-accessory.js +2 -2
  29. package/dist/devices/thermostat-accessory.d.ts +16 -2
  30. package/dist/devices/thermostat-accessory.js +54 -19
  31. package/dist/diagnostics/collector.d.ts +3 -2
  32. package/dist/diagnostics/collector.js +16 -8
  33. package/dist/discovery.d.ts +5 -18
  34. package/dist/discovery.js +41 -91
  35. package/dist/platform.d.ts +14 -4
  36. package/dist/platform.js +32 -8
  37. package/dist/session.d.ts +42 -11
  38. package/dist/session.js +181 -116
  39. package/dist/settings.d.ts +29 -0
  40. package/dist/settings.js +30 -1
  41. package/dist/ui-api.d.ts +1 -1
  42. package/dist/ui-api.js +2 -1
  43. package/dist/utils/context.d.ts +16 -0
  44. package/dist/utils/context.js +29 -8
  45. package/dist/utils/errors.d.ts +13 -0
  46. package/dist/utils/errors.js +16 -1
  47. package/dist/utils/index.d.ts +1 -0
  48. package/dist/utils/index.js +1 -0
  49. package/dist/utils/records.d.ts +19 -0
  50. package/dist/utils/records.js +32 -0
  51. package/dist/utils/redact.d.ts +4 -2
  52. package/dist/utils/redact.js +11 -6
  53. package/dist/utils/timing.d.ts +6 -1
  54. package/dist/utils/timing.js +8 -3
  55. package/dist/utils/validators.d.ts +0 -2
  56. package/dist/utils/validators.js +28 -7
  57. package/docs/FEATURES.md +5 -5
  58. package/docs/PROTOCOL.md +23 -10
  59. package/docs/README-DETAILED.md +30 -13
  60. package/homebridge-ui/public/index.js +55 -8
  61. package/homebridge-ui/server.js +9 -18
  62. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,12 @@
1
1
  # Changelog
2
2
 
3
+ ## [1.1.3](https://github.com/tbaur/homebridge-navilink/compare/v1.1.2...v1.1.3) (2026-11-28)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * harden the cloud session, thermostats and settings page ([#52](https://github.com/tbaur/homebridge-navilink/issues/52)) ([2e85505](https://github.com/tbaur/homebridge-navilink/commit/2e85505f3bc061954bb1423fb961d88451e80294))
9
+
3
10
  ## [1.1.2](https://github.com/tbaur/homebridge-navilink/compare/v1.1.1...v1.1.2) (2026-11-27)
4
11
 
5
12
 
package/README.md CHANGED
@@ -86,6 +86,7 @@ Any Navien appliance that the NaviLink app controls. Confirmed on an NCB-240E (f
86
86
  4. **A recirculation switch that is not offered.** No pump is fitted, or it is not commissioned
87
87
  5. **`rate limited`.** The cloud rate-limits control. The plugin pauses and retries on the next press
88
88
  6. **`Circuit breaker CLOSED -> OPEN`.** Sign-in is paused; tiles stay No Response until the cloud recovers
89
+ 7. **`Boiler: not reporting`.** The cloud is up but that appliance stopped answering. Check the gateway in the NaviLink app; the tiles come back on their own with `reporting again`
89
90
 
90
91
  The [full troubleshooting list](docs/README-DETAILED.md#troubleshooting) covers more, including what Off on the hot water tile does once you allow power-off.
91
92
 
package/SECURITY.md CHANGED
@@ -26,8 +26,8 @@ If those are not acceptable, this plugin is not for you, and that is a reasonabl
26
26
  ## Security Measures
27
27
 
28
28
  - **Credentials in one place.** The password is read from configuration, used to sign in, and held only in memory. It is never written to a log, never placed in an accessory's cache, never sent anywhere except Navien's sign-in endpoint over HTTPS, and never passed to a script as a command-line argument.
29
- - **Redaction by shape, not by name.** `src/utils/redact.ts` matches JWTs, AWS key ids, signed-URL parameters and credential-shaped JSON fields by their *form*. A field name list would miss a token in a response shape nobody anticipated; this does not.
30
- - **Masked identifiers in the log.** The account address is debug only, and appears as `s…e@example.com`. Appliance lines use the name you configured. A gateway MAC is logged only as a fallback, as `gateway …E5F6` (last four characters). Discovery warnings use that fallback too: the cloud's own appliance label is often a room, so it stays on the settings page and out of the log. Both the configured name and the masked MAC identify you, and a Homebridge log gets pasted into issues. `options.accessoryPrefix` is a room-shaped name: it is length-capped and stripped of control characters the same way, and it never appears in structured diagnostics (those emit a boolean: set or not).
29
+ - **Redaction by name and by shape.** `src/utils/redact.ts` removes the values of known credential fields (`password`, `accessToken`, `secretKey`, the signed-URL parameters and so on) wherever the key survives, and removes JWTs and AWS key ids by their *form* wherever they appear. The field list catches a secret whose value looks like anything; the shapes catch a token in a response nobody anticipated. The settings page's server applies the same function a second time to everything it hands the browser.
30
+ - **Masked identifiers in the log.** The account address is debug only, and appears as `s…e@example.com`. Appliance lines use the name you configured. A gateway MAC is logged only as a fallback, as `gateway …E5F6` (last four characters). Discovery warnings use that fallback too: the cloud's own appliance label is often a room, so it stays on the settings page and out of the log. Both the configured name and the masked MAC identify you, and a Homebridge log gets pasted into issues. A configured name that contains the gateway's own MAC (an earlier settings page could write one) is masked to `gateway …E5F6` before it reaches a tile or the log, and the settings page no longer falls back to the id for a blank name. `options.accessoryPrefix` is a room-shaped name: it is length-capped and stripped of control characters the same way, and it never appears in structured diagnostics (those emit a boolean: set or not).
31
31
  - **The accessory cache holds identity, not credentials.** Homebridge persists `{mac}:{channel}` as `deviceId` so a restart adopts the same tile. That file is plain JSON and is included in diagnostic bundles, so it must never hold the password, a token or a signed AWS URL. The MAC is the appliance's address in every MQTT topic. HomeKit serial numbers are opaque generated values, not the MAC.
32
32
  - **HomeKit serial numbers are opaque generated values,** not the gateway MAC. The Home app displays them, so they reach screenshots.
33
33
  - **Input validation.** Config is checked at startup. A missing account, or a `devices` value that is not a list, disables the platform without unregistering accessories. A bad appliance entry is skipped. Appliance names and `options.accessoryPrefix` are stripped of control characters and length-capped before they reach a log line or a characteristic.
@@ -35,7 +35,7 @@ If those are not acceptable, this plugin is not for you, and that is a reasonabl
35
35
  - **A rejected credential stops the session.** Retrying a wrong password is how an account gets locked; the plugin declines to do it.
36
36
  - **Minimal dependencies.** One at runtime: Homebridge's own UI helper. The MQTT client is in this repository, for a protocol reason ([PROTOCOL.md](docs/PROTOCOL.md)) that also reduces supply-chain surface.
37
37
  - **Dependencies audited.** CI runs `npm audit` on the runtime tree and OSV-Scanner on the full tree.
38
- - **A CI step rejects credential-shaped strings** in the published docs, fixtures, schema and issue templates, so a token cannot be committed by accident. Unit tests that hold fake JWTs are outside that scan on purpose.
38
+ - **A CI step rejects credential-shaped strings** in the docs, source, tests, fixtures, schema, settings UI, scripts, `dist/` and workflow files, so a token cannot be committed by accident. Tests that need a credential's shape assemble it at runtime (`tests/helpers/secrets.ts`), so no committed file holds one.
39
39
  - **Opt-in diagnostics are logs only.** `options.diagnosticsInterval` writes a periodic health line from in-memory counters. It never makes a network call, never appears in HomeKit, and the structured JSON (`options.structuredLogs`) omits credentials, appliance names and the accessory prefix string.
40
40
 
41
41
  ## The settings page
@@ -99,9 +99,9 @@
99
99
  "type": "string",
100
100
  "minLength": 3,
101
101
  "maxLength": 20,
102
- "pattern": "^[0-9a-fA-F]{12}:([1-9]|[12][0-9]|3[0-2])$",
102
+ "pattern": "^([0-9a-fA-F]{12}|([0-9a-fA-F]{2}[:-]){5}[0-9a-fA-F]{2}):([1-9]|[12][0-9]|3[0-2])$",
103
103
  "examples": ["a1b2c3d4e5f6:1"],
104
- "description": "Stable identity: twelve hex digits and the channel, as the settings page writes it (lowercase, no separators). Changing it detaches the accessories from their HomeKit rooms and automations."
104
+ "description": "Stable identity: the gateway MAC and the channel. The settings page writes twelve lowercase hex digits with no separators; a MAC written with colons or hyphens is accepted and names the same appliance. Changing it detaches the accessories from their HomeKit rooms and automations."
105
105
  },
106
106
  "name": {
107
107
  "title": "Name",
@@ -92,3 +92,11 @@ export declare function decodeChannel(input: {
92
92
  status: ChannelStatus;
93
93
  now?: number;
94
94
  }): ChannelObservation | undefined;
95
+ /**
96
+ * How many units a channel description reports, bounded to {@link MAX_UNITS}.
97
+ *
98
+ * The only reader of `unitCount` for a request. The status request asks for
99
+ * units `1..unitCount`, so the bound has to apply here, where the request is
100
+ * built, and not only where an observation is decoded.
101
+ */
102
+ export declare function unitCountOf(description: Readonly<Record<string, unknown>> | undefined): number;
@@ -34,7 +34,9 @@ exports.hasDomesticHotWater = hasDomesticHotWater;
34
34
  exports.hasSpaceHeating = hasSpaceHeating;
35
35
  exports.hasUsableHeatingLoop = hasUsableHeatingLoop;
36
36
  exports.decodeChannel = decodeChannel;
37
+ exports.unitCountOf = unitCountOf;
37
38
  const settings_1 = require("../settings");
39
+ const records_1 = require("../utils/records");
38
40
  const temperature_1 = require("../utils/temperature");
39
41
  /**
40
42
  * `unitType` to family.
@@ -101,18 +103,18 @@ function isAbsentProbe(raw) {
101
103
  }
102
104
  /** Read the channel descriptions out of a `channelinfo` frame. */
103
105
  function parseChannelInfo(frame) {
104
- const list = asRecord(asRecord(asRecord(frame)?.response)?.channelInfo)?.channelList;
106
+ const list = (0, records_1.asRecord)((0, records_1.asRecord)((0, records_1.asRecord)(frame)?.response)?.channelInfo)?.channelList;
105
107
  if (!Array.isArray(list)) {
106
108
  return [];
107
109
  }
108
110
  const found = new Map();
109
111
  for (const entry of list) {
110
- const wrapper = asRecord(entry);
111
- const channel = asRecord(wrapper?.channel) ?? wrapper;
112
+ const wrapper = (0, records_1.asRecord)(entry);
113
+ const channel = (0, records_1.asRecord)(wrapper?.channel) ?? wrapper;
112
114
  if (channel === undefined) {
113
115
  continue;
114
116
  }
115
- const channelNumber = readInteger(wrapper?.channelNumber ?? channel.channelNumber);
117
+ const channelNumber = (0, records_1.readInteger)(wrapper?.channelNumber ?? channel.channelNumber);
116
118
  if (channelNumber === undefined) {
117
119
  continue;
118
120
  }
@@ -124,12 +126,12 @@ function parseChannelInfo(frame) {
124
126
  }
125
127
  /** Read the channel state out of a `channelstatus` frame. */
126
128
  function parseChannelStatus(frame) {
127
- const wrapper = asRecord(asRecord(asRecord(frame)?.response)?.channelStatus);
129
+ const wrapper = (0, records_1.asRecord)((0, records_1.asRecord)((0, records_1.asRecord)(frame)?.response)?.channelStatus);
128
130
  if (wrapper === undefined) {
129
131
  return undefined;
130
132
  }
131
- const channel = asRecord(wrapper.channel) ?? wrapper;
132
- const channelNumber = readInteger(wrapper.channelNumber);
133
+ const channel = (0, records_1.asRecord)(wrapper.channel) ?? wrapper;
134
+ const channelNumber = (0, records_1.readInteger)(wrapper.channelNumber);
133
135
  if (channelNumber === undefined) {
134
136
  return undefined;
135
137
  }
@@ -144,7 +146,7 @@ function scaleOf(info) {
144
146
  }
145
147
  /** The family an appliance belongs to, from either frame. */
146
148
  function familyOf(raw) {
147
- const unitType = readInteger(raw.unitType);
149
+ const unitType = (0, records_1.readInteger)(raw.unitType);
148
150
  return (unitType === undefined ? undefined : FAMILY_BY_UNIT_TYPE[unitType]) ?? 'UNKNOWN';
149
151
  }
150
152
  /**
@@ -193,8 +195,8 @@ function hasUsableHeatingLoop(description) {
193
195
  if (!isFlagOn(description.heatControl)) {
194
196
  return false;
195
197
  }
196
- const min = readInteger(description.setupHeatTempMin);
197
- const max = readInteger(description.setupHeatTempMax);
198
+ const min = (0, records_1.readInteger)(description.setupHeatTempMin);
199
+ const max = (0, records_1.readInteger)(description.setupHeatTempMax);
198
200
  return min !== undefined && max !== undefined && max > min;
199
201
  }
200
202
  /**
@@ -222,7 +224,7 @@ function decodeChannel(input) {
222
224
  channelNumber: status.channelNumber,
223
225
  family: familyOf(description),
224
226
  scale,
225
- unitCount: clampUnitCount(readInteger(description.unitCount) ?? readInteger(state.unitCount)),
227
+ unitCount: clampUnitCount((0, records_1.readInteger)(description.unitCount) ?? (0, records_1.readInteger)(state.unitCount)),
226
228
  power: isFlagOn(state.powerStatus),
227
229
  heating: isFlagOn(state.heatStatus),
228
230
  // The enable flag, not the burner. No field in this frame distinguishes
@@ -260,12 +262,12 @@ function decodeChannel(input) {
260
262
  }
261
263
  /** Every unit status the frame named, skipping entries that are not objects. */
262
264
  function unitStatusList(state) {
263
- const list = asRecord(state.unitInfo)?.unitStatusList;
265
+ const list = (0, records_1.asRecord)(state.unitInfo)?.unitStatusList;
264
266
  if (!Array.isArray(list)) {
265
267
  return [];
266
268
  }
267
269
  return list.flatMap((entry) => {
268
- const record = asRecord(entry);
270
+ const record = (0, records_1.asRecord)(entry);
269
271
  return record === undefined ? [] : [record];
270
272
  });
271
273
  }
@@ -283,14 +285,14 @@ function firstUnitStatus(state) {
283
285
  /** The first unit reporting a non-zero error, or the first unit if none is. */
284
286
  function firstFaultedUnit(state) {
285
287
  const units = unitStatusList(state);
286
- return units.find((unit) => (readInteger(unit.errorCode) ?? 0) !== 0) ?? units[0];
288
+ return units.find((unit) => ((0, records_1.readInteger)(unit.errorCode) ?? 0) !== 0) ?? units[0];
287
289
  }
288
290
  function readUnitReadings(unit, faulted = unit) {
289
291
  const readings = {
290
- errorCode: readInteger(faulted?.errorCode) ?? 0,
291
- subErrorCode: readInteger(faulted?.subErrorCode) ?? 0,
292
+ errorCode: (0, records_1.readInteger)(faulted?.errorCode) ?? 0,
293
+ subErrorCode: (0, records_1.readInteger)(faulted?.subErrorCode) ?? 0,
292
294
  };
293
- const controllerVersion = readInteger(unit?.controllerVersion);
295
+ const controllerVersion = (0, records_1.readInteger)(unit?.controllerVersion);
294
296
  if (controllerVersion !== undefined) {
295
297
  readings.controllerVersion = controllerVersion;
296
298
  }
@@ -308,6 +310,30 @@ function clampUnitCount(value) {
308
310
  }
309
311
  return Math.min(value, settings_1.MAX_UNITS);
310
312
  }
313
+ /**
314
+ * How many units a channel description reports, bounded to {@link MAX_UNITS}.
315
+ *
316
+ * The only reader of `unitCount` for a request. The status request asks for
317
+ * units `1..unitCount`, so the bound has to apply here, where the request is
318
+ * built, and not only where an observation is decoded.
319
+ */
320
+ function unitCountOf(description) {
321
+ return clampUnitCount((0, records_1.readInteger)(description?.unitCount));
322
+ }
323
+ /** The readings an appliance may or may not report, set only when it does. */
324
+ const OPTIONAL_READINGS = [
325
+ 'dhwSetpoint',
326
+ 'dhwMin',
327
+ 'dhwMax',
328
+ 'heatSetpoint',
329
+ 'heatMin',
330
+ 'heatMax',
331
+ 'dhwOutlet',
332
+ 'dhwInlet',
333
+ 'heatSupply',
334
+ 'heatReturn',
335
+ 'outdoor',
336
+ ];
311
337
  /**
312
338
  * Copy only the defined entries.
313
339
  *
@@ -318,17 +344,10 @@ function clampUnitCount(value) {
318
344
  * what the appliance actually reported.
319
345
  */
320
346
  function assignDefined(target, values) {
321
- for (const [key, value] of Object.entries(values)) {
347
+ for (const key of OPTIONAL_READINGS) {
348
+ const value = values[key];
322
349
  if (value !== undefined) {
323
350
  target[key] = value;
324
351
  }
325
352
  }
326
353
  }
327
- function asRecord(value) {
328
- return typeof value === 'object' && value !== null && !Array.isArray(value)
329
- ? value
330
- : undefined;
331
- }
332
- function readInteger(value) {
333
- return typeof value === 'number' && Number.isFinite(value) ? Math.trunc(value) : undefined;
334
- }
@@ -106,6 +106,4 @@ export declare class CircuitBreaker {
106
106
  * re-opens the breaker so the probe slot cannot wedge.
107
107
  */
108
108
  execute<T>(fn: () => Promise<T>, isFailure?: (error: unknown) => boolean): Promise<T>;
109
- /** Create a wrapped version of a function with circuit breaker protection. */
110
- wrap<T extends unknown[], R>(fn: (...args: T) => Promise<R>, isFailure?: (error: unknown) => boolean): (...args: T) => Promise<R>;
111
109
  }
@@ -213,9 +213,5 @@ class CircuitBreaker {
213
213
  throw error;
214
214
  }
215
215
  }
216
- /** Create a wrapped version of a function with circuit breaker protection. */
217
- wrap(fn, isFailure) {
218
- return (...args) => this.execute(() => fn(...args), isFailure);
219
- }
220
216
  }
221
217
  exports.CircuitBreaker = CircuitBreaker;
@@ -10,6 +10,7 @@ export * from './channel';
10
10
  export * from './circuit-breaker';
11
11
  export * from './http';
12
12
  export * from './identity';
13
+ export * from './iot-connection';
13
14
  export * from './mqtt';
14
15
  export * from './mqtt-codec';
15
16
  export * from './protocol';
package/dist/api/index.js CHANGED
@@ -26,6 +26,7 @@ __exportStar(require("./channel"), exports);
26
26
  __exportStar(require("./circuit-breaker"), exports);
27
27
  __exportStar(require("./http"), exports);
28
28
  __exportStar(require("./identity"), exports);
29
+ __exportStar(require("./iot-connection"), exports);
29
30
  __exportStar(require("./mqtt"), exports);
30
31
  __exportStar(require("./mqtt-codec"), exports);
31
32
  __exportStar(require("./protocol"), exports);
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Copyright (c) 2026 tbaur
3
+ *
4
+ * Licensed under the Apache License, Version 2.0
5
+ * See LICENSE file for full license text
6
+ *
7
+ * @fileoverview Opening an AWS IoT connection, with the signature fallback.
8
+ *
9
+ * The SigV4 rule for a default port has two defensible readings: sign the
10
+ * bare host, or sign `host:443`. The wrong one fails as a silently rejected
11
+ * upgrade that looks exactly like a bad password. The bare host is what the
12
+ * verified endpoint wants, so it is tried first, and `host:443` second.
13
+ *
14
+ * The session and discovery both need this, and they used to carry a copy
15
+ * each. One copy means the order, the logging and the clean-up on failure
16
+ * cannot drift apart.
17
+ */
18
+ import type { PluginLogger } from '../types';
19
+ import { MqttConnection, type MqttConnectionOptions } from './mqtt';
20
+ /** What one attempt to open a connection needs. */
21
+ export interface OpenIotConnectionInput {
22
+ log: PluginLogger;
23
+ /** Options for every attempt. This sets `signHostWithPort` itself. */
24
+ options: Omit<MqttConnectionOptions, 'signHostWithPort'>;
25
+ /** Injected in tests so no socket is opened. */
26
+ createConnection?: ((options: MqttConnectionOptions) => MqttConnection) | undefined;
27
+ /** Wire handlers before connecting, so a message that arrives early is not missed. */
28
+ prepare(connection: MqttConnection): void;
29
+ /** Subscribe once connected. A failure here moves on to the next signature. */
30
+ subscribe(connection: MqttConnection): Promise<void>;
31
+ }
32
+ /**
33
+ * Open, connect and subscribe, trying both host signatures.
34
+ *
35
+ * Resolves with the first connection that is connected and subscribed. A
36
+ * connection that fails is closed before the next is tried, so a refused
37
+ * fallback never leaves a socket behind. Rejects with the last failure.
38
+ */
39
+ export declare function openIotConnection(input: OpenIotConnectionInput): Promise<MqttConnection>;
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright (c) 2026 tbaur
4
+ *
5
+ * Licensed under the Apache License, Version 2.0
6
+ * See LICENSE file for full license text
7
+ *
8
+ * @fileoverview Opening an AWS IoT connection, with the signature fallback.
9
+ *
10
+ * The SigV4 rule for a default port has two defensible readings: sign the
11
+ * bare host, or sign `host:443`. The wrong one fails as a silently rejected
12
+ * upgrade that looks exactly like a bad password. The bare host is what the
13
+ * verified endpoint wants, so it is tried first, and `host:443` second.
14
+ *
15
+ * The session and discovery both need this, and they used to carry a copy
16
+ * each. One copy means the order, the logging and the clean-up on failure
17
+ * cannot drift apart.
18
+ */
19
+ Object.defineProperty(exports, "__esModule", { value: true });
20
+ exports.openIotConnection = openIotConnection;
21
+ const errors_1 = require("../utils/errors");
22
+ const labels_1 = require("../utils/labels");
23
+ const mqtt_1 = require("./mqtt");
24
+ /**
25
+ * Open, connect and subscribe, trying both host signatures.
26
+ *
27
+ * Resolves with the first connection that is connected and subscribed. A
28
+ * connection that fails is closed before the next is tried, so a refused
29
+ * fallback never leaves a socket behind. Rejects with the last failure.
30
+ */
31
+ async function openIotConnection(input) {
32
+ let lastError;
33
+ for (const signHostWithPort of [false, true]) {
34
+ const options = { ...input.options, signHostWithPort };
35
+ const connection = input.createConnection?.(options) ?? new mqtt_1.MqttConnection(options);
36
+ input.prepare(connection);
37
+ try {
38
+ await connection.connect();
39
+ await input.subscribe(connection);
40
+ return connection;
41
+ }
42
+ catch (error) {
43
+ lastError = error;
44
+ connection.close();
45
+ input.log.debug(`${labels_1.MQTT_CHANNEL} connect failed with host${signHostWithPort ? ':443' : ''} signature: `
46
+ + (0, errors_1.describeError)(error));
47
+ }
48
+ }
49
+ throw lastError instanceof Error ? lastError : new Error('could not open the MQTT connection');
50
+ }
@@ -165,9 +165,15 @@ export declare function encodeDisconnect(): Uint8Array;
165
165
  * length field itself. A decoder that assumed one frame is one packet works
166
166
  * perfectly on a quiet connection and corrupts under load, which is the worst
167
167
  * possible failure schedule.
168
+ *
169
+ * Received bytes are kept as a list of chunks and joined only once a whole
170
+ * packet is present. Joining on every arrival would copy a large packet's
171
+ * prefix again for each fragment, which is quadratic in the number of
172
+ * fragments.
168
173
  */
169
174
  export declare class PacketDecoder {
170
- private buffer;
175
+ private chunks;
176
+ private length;
171
177
  /**
172
178
  * Add received bytes and return every complete packet now available.
173
179
  *
@@ -178,4 +184,10 @@ export declare class PacketDecoder {
178
184
  push(chunk: Uint8Array): DecodedPacket[];
179
185
  /** Bytes held pending the rest of a packet. Exposed for tests and diagnostics. */
180
186
  get pending(): number;
187
+ /** The first `count` bytes, without consuming them. */
188
+ private peek;
189
+ /** Remove and return the first `count` bytes. Copies only when they span chunks. */
190
+ private take;
191
+ /** Copy `count` bytes from the front of the chunk list, optionally consuming them. */
192
+ private copyOut;
181
193
  }
@@ -320,9 +320,15 @@ function decodeBody(type, flags, body) {
320
320
  * length field itself. A decoder that assumed one frame is one packet works
321
321
  * perfectly on a quiet connection and corrupts under load, which is the worst
322
322
  * possible failure schedule.
323
+ *
324
+ * Received bytes are kept as a list of chunks and joined only once a whole
325
+ * packet is present. Joining on every arrival would copy a large packet's
326
+ * prefix again for each fragment, which is quadratic in the number of
327
+ * fragments.
323
328
  */
324
329
  class PacketDecoder {
325
- buffer = new Uint8Array(0);
330
+ chunks = [];
331
+ length = 0;
326
332
  /**
327
333
  * Add received bytes and return every complete packet now available.
328
334
  *
@@ -331,47 +337,95 @@ class PacketDecoder {
331
337
  * way to resynchronise, because MQTT has no frame delimiter to scan for.
332
338
  */
333
339
  push(chunk) {
334
- this.buffer = this.buffer.length === 0
335
- ? chunk
336
- : concat(this.buffer, chunk);
340
+ if (chunk.length > 0) {
341
+ this.chunks.push(chunk);
342
+ this.length += chunk.length;
343
+ }
337
344
  const packets = [];
338
- let offset = 0;
339
345
  for (;;) {
340
- const header = this.buffer[offset];
346
+ // The fixed header is at most five bytes: the type byte and a varint
347
+ // of up to four. Only those are joined to read it.
348
+ const head = this.peek(Math.min(5, this.length));
349
+ const header = head[0];
341
350
  if (header === undefined) {
342
351
  break;
343
352
  }
344
- const length = readRemainingLength(this.buffer, offset + 1);
345
- if (length === undefined) {
353
+ const remaining = readRemainingLength(head, 1);
354
+ if (remaining === undefined) {
346
355
  break;
347
356
  }
348
- if (length.value > exports.MAX_PACKET_BYTES) {
349
- throw new errors_1.ProtocolError(`packet of ${length.value} bytes exceeds the ${exports.MAX_PACKET_BYTES} byte limit`);
357
+ if (remaining.value > exports.MAX_PACKET_BYTES) {
358
+ throw new errors_1.ProtocolError(`packet of ${remaining.value} bytes exceeds the ${exports.MAX_PACKET_BYTES} byte limit`);
350
359
  }
351
- const start = offset + 1 + length.bytes;
352
- const end = start + length.value;
353
- if (end > this.buffer.length) {
360
+ const headerBytes = 1 + remaining.bytes;
361
+ const total = headerBytes + remaining.value;
362
+ if (this.length < total) {
354
363
  break;
355
364
  }
356
- packets.push(decodeBody(header >> 4, header & 0x0F, this.buffer.subarray(start, end)));
357
- offset = end;
358
- }
359
- // Retained rather than copied when nothing was consumed, so a large packet
360
- // arriving in many small frames does not re-copy its prefix each time.
361
- if (offset > 0) {
362
- this.buffer = this.buffer.subarray(offset);
365
+ const bytes = this.take(total);
366
+ packets.push(decodeBody(header >> 4, header & 0x0F, bytes.subarray(headerBytes)));
363
367
  }
364
368
  return packets;
365
369
  }
366
370
  /** Bytes held pending the rest of a packet. Exposed for tests and diagnostics. */
367
371
  get pending() {
368
- return this.buffer.length;
372
+ return this.length;
373
+ }
374
+ /** The first `count` bytes, without consuming them. */
375
+ peek(count) {
376
+ const first = this.chunks[0];
377
+ if (first === undefined || count === 0) {
378
+ return new Uint8Array(0);
379
+ }
380
+ if (first.length >= count) {
381
+ return first.subarray(0, count);
382
+ }
383
+ return this.copyOut(count, false);
384
+ }
385
+ /** Remove and return the first `count` bytes. Copies only when they span chunks. */
386
+ take(count) {
387
+ const first = this.chunks[0];
388
+ if (first !== undefined && first.length >= count) {
389
+ if (first.length === count) {
390
+ this.chunks.shift();
391
+ }
392
+ else {
393
+ this.chunks[0] = first.subarray(count);
394
+ }
395
+ this.length -= count;
396
+ return first.subarray(0, count);
397
+ }
398
+ return this.copyOut(count, true);
399
+ }
400
+ /** Copy `count` bytes from the front of the chunk list, optionally consuming them. */
401
+ copyOut(count, consume) {
402
+ const out = new Uint8Array(count);
403
+ let written = 0;
404
+ let index = 0;
405
+ while (written < count) {
406
+ const chunk = this.chunks[index];
407
+ if (chunk === undefined) {
408
+ break;
409
+ }
410
+ const used = Math.min(chunk.length, count - written);
411
+ out.set(chunk.subarray(0, used), written);
412
+ written += used;
413
+ if (consume) {
414
+ if (used === chunk.length) {
415
+ this.chunks.shift();
416
+ }
417
+ else {
418
+ this.chunks[0] = chunk.subarray(used);
419
+ }
420
+ }
421
+ else {
422
+ index += 1;
423
+ }
424
+ }
425
+ if (consume) {
426
+ this.length -= written;
427
+ }
428
+ return out;
369
429
  }
370
430
  }
371
431
  exports.PacketDecoder = PacketDecoder;
372
- function concat(left, right) {
373
- const merged = new Uint8Array(left.length + right.length);
374
- merged.set(left, 0);
375
- merged.set(right, left.length);
376
- return merged;
377
- }
@@ -63,10 +63,8 @@ export declare const Command: {
63
63
  readonly DHW_TEMPERATURE: 33554435;
64
64
  /** Set the space-heating water setpoint. */
65
65
  readonly HEAT_TEMPERATURE: 33554436;
66
- /** Start, stop or warm up the recirculation pump. */
66
+ /** Start or stop the recirculation pump. */
67
67
  readonly ON_DEMAND: 33554437;
68
- /** Set the recirculation setpoint. */
69
- readonly RECIRCULATION_TEMPERATURE: 33554439;
70
68
  };
71
69
  /**
72
70
  * The `control.mode` string that accompanies each write command.
@@ -83,7 +81,6 @@ export declare const ControlMode: {
83
81
  readonly DHW_TEMPERATURE: "DHWTemperature";
84
82
  readonly HEAT_TEMPERATURE: "heatTemperature";
85
83
  readonly ON_DEMAND: "onDemand";
86
- readonly RECIRCULATION_TEMPERATURE: "recirculation";
87
84
  };
88
85
  /**
89
86
  * The appliance's boolean encoding.
@@ -96,13 +93,28 @@ export declare const OnOff: {
96
93
  readonly ON: 1;
97
94
  readonly OFF: 2;
98
95
  };
99
- /** On-demand recirculation takes a third value the other flags do not. */
100
- export declare const ON_DEMAND_WARMUP = 3;
101
96
  /** What one request needs to address a gateway. */
102
97
  export interface RequestContext extends TopicIdentity {
103
98
  /** The opaque discriminator from the device list. Often an empty string. */
104
99
  additionalValue: string;
105
100
  }
101
+ /** What the device list says about one gateway, as far as addressing goes. */
102
+ export interface GatewayAddress {
103
+ macAddress: string;
104
+ deviceType: number;
105
+ homeSeq: string;
106
+ additionalValue: string;
107
+ }
108
+ /**
109
+ * The context every request to one gateway carries.
110
+ *
111
+ * Built in one place for the session and for discovery, so the two cannot
112
+ * disagree about how a gateway is addressed.
113
+ */
114
+ export declare function requestContextFor(gateway: GatewayAddress, session: {
115
+ userSeq: string;
116
+ clientId: string;
117
+ }): RequestContext;
106
118
  /** A frame ready to publish: where it goes, and what it says. */
107
119
  export interface OutboundFrame {
108
120
  topic: string;
@@ -34,7 +34,8 @@
34
34
  * this plugin sends can be asserted on byte for byte in a test.
35
35
  */
36
36
  Object.defineProperty(exports, "__esModule", { value: true });
37
- exports.ON_DEMAND_WARMUP = exports.OnOff = exports.ControlMode = exports.Command = exports.PROTOCOL_VERSION = void 0;
37
+ exports.OnOff = exports.ControlMode = exports.Command = exports.PROTOCOL_VERSION = void 0;
38
+ exports.requestContextFor = requestContextFor;
38
39
  exports.channelInfoRequest = channelInfoRequest;
39
40
  exports.channelStatusRequest = channelStatusRequest;
40
41
  exports.controlRequest = controlRequest;
@@ -75,10 +76,8 @@ exports.Command = {
75
76
  DHW_TEMPERATURE: 0x0200_0003,
76
77
  /** Set the space-heating water setpoint. */
77
78
  HEAT_TEMPERATURE: 0x0200_0004,
78
- /** Start, stop or warm up the recirculation pump. */
79
+ /** Start or stop the recirculation pump. */
79
80
  ON_DEMAND: 0x0200_0005,
80
- /** Set the recirculation setpoint. */
81
- RECIRCULATION_TEMPERATURE: 0x0200_0007,
82
81
  };
83
82
  /**
84
83
  * The `control.mode` string that accompanies each write command.
@@ -95,7 +94,6 @@ exports.ControlMode = {
95
94
  DHW_TEMPERATURE: 'DHWTemperature',
96
95
  HEAT_TEMPERATURE: 'heatTemperature',
97
96
  ON_DEMAND: 'onDemand',
98
- RECIRCULATION_TEMPERATURE: 'recirculation',
99
97
  };
100
98
  /**
101
99
  * The appliance's boolean encoding.
@@ -108,8 +106,22 @@ exports.OnOff = {
108
106
  ON: 1,
109
107
  OFF: 2,
110
108
  };
111
- /** On-demand recirculation takes a third value the other flags do not. */
112
- exports.ON_DEMAND_WARMUP = 3;
109
+ /**
110
+ * The context every request to one gateway carries.
111
+ *
112
+ * Built in one place for the session and for discovery, so the two cannot
113
+ * disagree about how a gateway is addressed.
114
+ */
115
+ function requestContextFor(gateway, session) {
116
+ return {
117
+ macAddress: gateway.macAddress,
118
+ deviceType: gateway.deviceType,
119
+ homeSeq: gateway.homeSeq,
120
+ additionalValue: gateway.additionalValue,
121
+ userSeq: session.userSeq,
122
+ clientId: session.clientId,
123
+ };
124
+ }
113
125
  /** The envelope, with the caller's request inside it. */
114
126
  function envelope(input) {
115
127
  const { context, request, requestTopic, responseTopic } = input;
@@ -165,3 +165,18 @@ export declare class NaviLinkRest {
165
165
  */
166
166
  private readListedDevice;
167
167
  }
168
+ /**
169
+ * Read the firmware of each gateway, skipping any that will not say.
170
+ *
171
+ * Firmware is a nicety, so one gateway's failure is a debug line and not a
172
+ * reason to lose the others'. Shared by the session and by discovery, which
173
+ * both want the same map.
174
+ */
175
+ export declare function readFirmwareFor(rest: Pick<NaviLinkRest, 'readFirmware'>, log: PluginLogger, input: {
176
+ email: string;
177
+ accessToken: string;
178
+ gateways: readonly {
179
+ macAddress: string;
180
+ additionalValue: string;
181
+ }[];
182
+ }): Promise<Map<string, string>>;