homebridge-lg-thinq-2 2.0.7 → 2.0.9

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
@@ -1,5 +1,27 @@
1
1
  # Change Log
2
2
 
3
+ ## v2.0.9
4
+
5
+ ### Login
6
+
7
+ * When LG locks sign-in for an account (LG message `Need Sign-In Unlock`, usually after several failed sign-ins or a sign-in from a new device), the Homebridge UI, the `thinq` command, and the log now explain what happened and how to unlock it, instead of showing LG's raw message. Documented the error in the README troubleshooting table.
8
+
9
+ ## v2.0.8
10
+
11
+ ### Security
12
+
13
+ * The plugin no longer writes LG credentials to the Homebridge log. When refreshing the access token failed, the error was logged with its request body, which contains the refresh token; other errors could include the access token, or the username and password hash after a failed login. Errors are now logged as a short description (type, message, HTTP status, LG code, and URL without query parameters). Users often share these logs in public issues.
14
+ * The MQTT private key (`key.pem`) is now readable only by the user that runs Homebridge (mode 600, folder 700). Before, any user on the machine could read it. Existing files are fixed on the next start.
15
+ * When LG requires new terms, the plugin now loads the terms of the account's country and language (it always used Vietnam), and logs which terms it accepted on the account's behalf instead of accepting them silently.
16
+
17
+ ### Reliability
18
+
19
+ * A command that failed while the plugin was not waiting for it (microwave and oven commands, and AC mode buttons), for example because LG reported the device as offline, was an unhandled promise rejection, and Homebridge shuts down on those. These commands now log the error instead. Added lint rules (`no-floating-promises`, `no-misused-promises`) so the problem cannot come back.
20
+
21
+ ### Development
22
+
23
+ * Updated development dependencies to clear all `npm audit` reports and Dependabot alerts (16, from critical to low): `handlebars`, `js-yaml`, `browserslist`, `baseline-browser-mapping`, `@babel/core`, `eslint`, `typescript-eslint`, `@humanfs/node`, and `minimatch`. `nodemon` is given `minimatch` 11 through an override, because every 10.x release is affected and nodemon still asks for 10.x. These packages are only used to build and test the plugin and are not part of the published package.
24
+
3
25
  ## v2.0.7
4
26
 
5
27
  ### Security
package/README.md CHANGED
@@ -9,6 +9,7 @@
9
9
  <a href="https://www.npmjs.com/package/homebridge-lg-thinq-2"><img src="https://img.shields.io/npm/dt/homebridge-lg-thinq-2" alt="npm downloads"></a>
10
10
  <a href="https://github.com/santiagosony/homebridge-lg-thinq-2/actions/workflows/build.yml"><img src="https://github.com/santiagosony/homebridge-lg-thinq-2/actions/workflows/build.yml/badge.svg" alt="CI status"></a>
11
11
  <img src="https://img.shields.io/node/v/homebridge-lg-thinq-2" alt="Node.js version">
12
+ <a href="https://socket.dev/npm/package/homebridge-lg-thinq-2"><img src="https://socket.dev/api/badge/npm/package/homebridge-lg-thinq-2" alt="Socket security score"></a>
12
13
  <a href="LICENSE"><img src="https://img.shields.io/github/license/santiagosony/homebridge-lg-thinq-2" alt="License: Apache-2.0"></a>
13
14
  </p>
14
15
 
@@ -217,6 +218,7 @@ Turn on Homebridge **debug mode** (Homebridge UI → Settings) to see detailed l
217
218
  | --- | --- |
218
219
  | `LG pre-login failed: Request failed with status code 403` | LG rejected the login request. Update to version `2.0.3` or later. |
219
220
  | `Request failed with status code 429` or result code `9012` | LG received too many requests. Update to version `2.0.6` or later, and do not set a low `refresh_interval`. |
221
+ | `LG has locked sign-in for this account` (LG message `Need Sign-In Unlock`) | LG locked sign-in, usually after several failed sign-ins or a sign-in from a new device. Sign in to the LG ThinQ app or to your LG account on the LG website and complete the verification LG asks for, then try again. Or get a refresh token with [`thinq auth`](#command-line-tool), which uses LG's sign-in page. |
220
222
  | `Missing required config parameter.` | Set `country`, `language`, and either a `refresh_token` or `username` and `password`. |
221
223
  | `The plugin requires a Node.js version of ...` | Update the plugin. Node.js 26 also needs Homebridge `2.3.0` or later. |
222
224
  | A device is missing | Check that it works in the LG ThinQ app. Legacy devices need `"thinq1": true`. If it is still missing, [request it](https://github.com/santiagosony/homebridge-lg-thinq-2/issues/new/choose). |
@@ -1,4 +1,5 @@
1
1
  import { EventEmitter } from 'events';
2
+ import { describeError } from './lib/errorFormat.js';
2
3
  export function isDeviceOnlineForHomeKit(device) {
3
4
  return device.online !== false;
4
5
  }
@@ -37,6 +38,18 @@ export class BaseDevice extends EventEmitter {
37
38
  }
38
39
  this.updateAccessoryCharacteristic(this.accessory.context.device);
39
40
  }
41
+ /**
42
+ * Runs a device command without waiting for it, and logs it if it fails.
43
+ *
44
+ * Commands can fail, for example when LG reports the device as offline. An
45
+ * unawaited promise that rejects is an unhandled rejection, which makes Homebridge
46
+ * shut down, so every command started without `await` must go through here.
47
+ */
48
+ runInBackground(command, action) {
49
+ command.catch(err => {
50
+ this.logger.error(`[${this.accessory.context.device.name}] ${action} failed:`, describeError(err));
51
+ });
52
+ }
40
53
  get isOnlineForHomeKit() {
41
54
  return isDeviceOnlineForHomeKit(this.accessory.context.device);
42
55
  }
package/dist/cli.js CHANGED
@@ -4,6 +4,7 @@ import { API } from './lib/API.js';
4
4
  import { Auth } from './lib/Auth.js';
5
5
  import { URL } from 'url';
6
6
  import * as readline from 'readline';
7
+ import { describeError } from './lib/errorFormat.js';
7
8
  const makeLogger = () => console;
8
9
  const input = (question) => new Promise((resolve) => {
9
10
  const rl = readline.createInterface(process.stdin, process.stdout);
@@ -38,7 +39,7 @@ program
38
39
  console.info('Your refresh_token:', session.refreshToken);
39
40
  }
40
41
  catch (err) {
41
- console.error(err);
42
+ console.error(describeError(err));
42
43
  }
43
44
  process.exit(0);
44
45
  });
@@ -84,7 +85,7 @@ program
84
85
  console.info('Your refresh_token:', session.refreshToken);
85
86
  }
86
87
  catch (err) {
87
- console.error(err);
88
+ console.error(describeError(err));
88
89
  }
89
90
  process.exit(0);
90
91
  });
@@ -3,6 +3,7 @@ import { ValueType } from '../lib/DeviceModel.js';
3
3
  import { normalizeBoolean, normalizeNumber } from '../utils/normalize.js';
4
4
  import { cToF, fToC } from '../utils/temperature.js';
5
5
  import { hasSnapshotKey, snapshotBoolean, snapshotNumber } from './helpers.js';
6
+ import { describeError } from '../lib/errorFormat.js';
6
7
  export var ACModelType;
7
8
  (function (ACModelType) {
8
9
  ACModelType["AWHP"] = "AWHP";
@@ -62,7 +63,7 @@ function convertTemperatureCelsiusFromLGToHomekit(temperature, device, config, l
62
63
  }
63
64
  }
64
65
  catch (e) {
65
- logger.warn('Temperature mapping lookup failed, falling back to direct conversion.', e);
66
+ logger.warn('Temperature mapping lookup failed, falling back to direct conversion.', describeError(e));
66
67
  }
67
68
  const c = Math.round(fToC(tempNum) * 100) / 100;
68
69
  return c;
@@ -83,7 +84,7 @@ function convertTemperatureCelsiusFromHomekitToLG(temperatureInCelsius, device,
83
84
  }
84
85
  }
85
86
  catch (e) {
86
- logger.warn('Temperature mapping lookup failed, falling back to direct conversion.', e);
87
+ logger.warn('Temperature mapping lookup failed, falling back to direct conversion.', describeError(e));
87
88
  }
88
89
  return temperatureInFahrenheit;
89
90
  }
@@ -494,11 +495,11 @@ export default class AirConditioner extends BaseDevice {
494
495
  if (this.temperatureKeepAliveFailureCount >= AIR_CONDITIONER_TEMPERATURE_KEEP_ALIVE_MAX_FAILURES) {
495
496
  const message = `[${device.name}] AC temperature keep-alive command failed `
496
497
  + `${this.temperatureKeepAliveFailureCount} consecutive times; disabling keep-alive for this device.`;
497
- this.logger.debug(message, error);
498
+ this.logger.debug(message, describeError(error));
498
499
  this.stopTemperatureKeepAlive();
499
500
  return;
500
501
  }
501
- this.logger.debug(`[${device.name}] AC temperature keep-alive command failed; will retry.`, error);
502
+ this.logger.debug(`[${device.name}] AC temperature keep-alive command failed; will retry.`, describeError(error));
502
503
  }
503
504
  setupTemperatureSensorService(accessory) {
504
505
  const { Service: { TemperatureSensor, }, Characteristic, } = this.platform;
@@ -747,7 +748,7 @@ export default class AirConditioner extends BaseDevice {
747
748
  updateAccessoryCharacteristic();
748
749
  }
749
750
  catch (error) {
750
- this.logger.error(errorMessage, error);
751
+ this.logger.error(errorMessage, describeError(error));
751
752
  }
752
753
  }
753
754
  /**
@@ -829,7 +830,7 @@ export default class AirConditioner extends BaseDevice {
829
830
  this.updateAccessoryFanV2Characteristic();
830
831
  }
831
832
  catch (error) {
832
- this.logger.error('Error setting fan state:', error);
833
+ this.logger.error('Error setting fan state:', describeError(error));
833
834
  }
834
835
  }
835
836
  /**
@@ -1119,7 +1120,7 @@ export default class AirConditioner extends BaseDevice {
1119
1120
  this.updateAccessoryLedControlCharacteristic();
1120
1121
  }
1121
1122
  catch (error) {
1122
- this.logger.error('Error setting light state:', error);
1123
+ this.logger.error('Error setting light state:', describeError(error));
1123
1124
  }
1124
1125
  }
1125
1126
  /**
@@ -1145,7 +1146,7 @@ export default class AirConditioner extends BaseDevice {
1145
1146
  await this.setOpMode(this.accessory.context.device.id, opMode);
1146
1147
  }
1147
1148
  catch (error) {
1148
- this.logger.error('Error setting target state:', error);
1149
+ this.logger.error('Error setting target state:', describeError(error));
1149
1150
  }
1150
1151
  }
1151
1152
  async setActive(value) {
@@ -1169,7 +1170,7 @@ export default class AirConditioner extends BaseDevice {
1169
1170
  }
1170
1171
  }
1171
1172
  catch (error) {
1172
- this.logger.error('Error setting active state:', error);
1173
+ this.logger.error('Error setting active state:', describeError(error));
1173
1174
  }
1174
1175
  }
1175
1176
  /**
@@ -1223,7 +1224,7 @@ export default class AirConditioner extends BaseDevice {
1223
1224
  return;
1224
1225
  }
1225
1226
  catch (error) {
1226
- this.logger.error('Error setting target temperature:', error);
1227
+ this.logger.error('Error setting target temperature:', describeError(error));
1227
1228
  }
1228
1229
  }
1229
1230
  /**
@@ -1266,7 +1267,7 @@ export default class AirConditioner extends BaseDevice {
1266
1267
  this.accessory.context.device.data.snapshot['airState.windStrength'] = windStrength;
1267
1268
  }
1268
1269
  catch (error) {
1269
- this.logger.error('Error setting fan speed:', error);
1270
+ this.logger.error('Error setting fan speed:', describeError(error));
1270
1271
  }
1271
1272
  }
1272
1273
  async setSwingMode(value) {
@@ -1291,7 +1292,7 @@ export default class AirConditioner extends BaseDevice {
1291
1292
  this.updateAccessoryFanV2Characteristic();
1292
1293
  }
1293
1294
  catch (error) {
1294
- this.logger.error('Error setting swing mode:', error);
1295
+ this.logger.error('Error setting swing mode:', describeError(error));
1295
1296
  }
1296
1297
  }
1297
1298
  async setOpMode(deviceId, opMode) {
@@ -1332,7 +1333,7 @@ export default class AirConditioner extends BaseDevice {
1332
1333
  return this.Status.opMode === opMode;
1333
1334
  }))
1334
1335
  .onSet((value) => {
1335
- this.handleButtonOpmode(value, opMode);
1336
+ this.runInBackground(this.handleButtonOpmode(value, opMode), 'Mode button command');
1336
1337
  });
1337
1338
  this.serviceLabelButtons.addLinkedService(serviceButton);
1338
1339
  }
@@ -93,7 +93,7 @@ export default class Microwave extends BaseDevice {
93
93
  .onSet((value) => {
94
94
  this.ventSpeed = value;
95
95
  if (this.ventSpeed !== snapshotNumber(this.Status.data, 'mwoVentSpeedLevel')) {
96
- this.sendLightVentCommand();
96
+ this.runInBackground(this.sendLightVentCommand(), 'Light and vent command');
97
97
  }
98
98
  });
99
99
  this.serviceHood.getCharacteristic(Characteristic.RotationSpeed).onGet(this.onlineGet(() => {
@@ -101,7 +101,7 @@ export default class Microwave extends BaseDevice {
101
101
  return this.ventSpeed;
102
102
  })).onSet((value) => {
103
103
  this.ventSpeed = value;
104
- this.sendLightVentCommand();
104
+ this.runInBackground(this.sendLightVentCommand(), 'Light and vent command');
105
105
  });
106
106
  this.serviceHood.getCharacteristic(Characteristic.RotationSpeed)
107
107
  .setProps({
@@ -118,11 +118,11 @@ export default class Microwave extends BaseDevice {
118
118
  const enabled = normalizeBoolean(value);
119
119
  if (!enabled) {
120
120
  this.lampLevel = 0;
121
- this.sendLightVentCommand();
121
+ this.runInBackground(this.sendLightVentCommand(), 'Light and vent command');
122
122
  }
123
123
  else {
124
124
  this.lampLevel = 2;
125
- this.sendLightVentCommand();
125
+ this.runInBackground(this.sendLightVentCommand(), 'Light and vent command');
126
126
  }
127
127
  }).onGet(this.onlineGet(() => hasNonZeroSnapshotNumber(this.Status.data, 'mwoLampLevel')));
128
128
  this.serviceLight.getCharacteristic(Characteristic.Brightness).onGet(this.onlineGet(() => {
@@ -131,7 +131,7 @@ export default class Microwave extends BaseDevice {
131
131
  })).onSet((value) => {
132
132
  this.lampLevel = value;
133
133
  if (this.lampLevel !== snapshotNumber(this.Status.data, 'mwoLampLevel')) {
134
- this.sendLightVentCommand();
134
+ this.runInBackground(this.sendLightVentCommand(), 'Light and vent command');
135
135
  }
136
136
  });
137
137
  this.serviceLight.getCharacteristic(Characteristic.Brightness)
@@ -153,7 +153,7 @@ export default class Microwave extends BaseDevice {
153
153
  || hasNonZeroSnapshotNumber(this.Status.data, 'mwoLampLevel')) {
154
154
  this.lampLevel = 0;
155
155
  this.ventSpeed = 0;
156
- this.sendLightVentCommand();
156
+ this.runInBackground(this.sendLightVentCommand(), 'Light and vent command');
157
157
  }
158
158
  setTimeout(() => {
159
159
  this.offSwitch.updateCharacteristic(this.platform.Characteristic.On, false);
@@ -195,7 +195,7 @@ export default class Microwave extends BaseDevice {
195
195
  const enabled = normalizeBoolean(value);
196
196
  if (!enabled) {
197
197
  if (isInitialCookingState(this.Status.data, 'LWOState')) {
198
- this.stopOven();
198
+ this.runInBackground(this.stopOven(), 'Stop command');
199
199
  this.timeOut = 1500;
200
200
  setTimeout(() => {
201
201
  this.timeOut = 0;
@@ -206,7 +206,7 @@ export default class Microwave extends BaseDevice {
206
206
  || hasNonZeroSnapshotNumber(this.Status.data, 'mwoLampLevel')) {
207
207
  this.lampLevel = 0;
208
208
  this.ventSpeed = 0;
209
- this.sendLightVentCommand();
209
+ this.runInBackground(this.sendLightVentCommand(), 'Light and vent command');
210
210
  }
211
211
  }, this.timeOut);
212
212
  }
@@ -214,7 +214,7 @@ export default class Microwave extends BaseDevice {
214
214
  if (snapshotNumber(this.Status.data, 'mwoVentSpeedLevel') === 0 || snapshotNumber(this.Status.data, 'mwoLampLevel') === 0) {
215
215
  this.lampLevel = 2;
216
216
  this.ventSpeed = 2;
217
- this.sendLightVentCommand();
217
+ this.runInBackground(this.sendLightVentCommand(), 'Light and vent command');
218
218
  }
219
219
  }
220
220
  });
@@ -395,13 +395,13 @@ export default class Microwave extends BaseDevice {
395
395
  this.ovenTimerService.getCharacteristic(Characteristic.Active).onGet(this.onlineGet(() => this.remainTime() !== 0 ? 1 : 0)).onSet((value) => {
396
396
  const enabled = normalizeBoolean(value);
397
397
  if (!enabled) {
398
- this.stopOven();
398
+ this.runInBackground(this.stopOven(), 'Stop command');
399
399
  this.ovenTimerService.updateCharacteristic(Characteristic.Active, 0);
400
400
  this.ovenTimerService.updateCharacteristic(Characteristic.RemainingDuration, 0);
401
401
  this.ovenTimerService.updateCharacteristic(Characteristic.InUse, 0);
402
402
  }
403
403
  else {
404
- this.sendOvenCommand();
404
+ this.runInBackground(this.sendOvenCommand(), 'Cooking command');
405
405
  }
406
406
  });
407
407
  this.ovenTimerService.setCharacteristic(Characteristic.InUse, this.remainTime() > 0 ? Characteristic.InUse.IN_USE : Characteristic.InUse.NOT_IN_USE);
@@ -432,13 +432,13 @@ export default class Microwave extends BaseDevice {
432
432
  const enabled = normalizeBoolean(value);
433
433
  if (!enabled) {
434
434
  this.timerAlarmSec = 0;
435
- this.sendTimerCommand(0);
435
+ this.runInBackground(this.sendTimerCommand(0), 'Timer command');
436
436
  this.ovenAlarmService.updateCharacteristic(Characteristic.Active, 0);
437
437
  this.ovenAlarmService.updateCharacteristic(Characteristic.RemainingDuration, 0);
438
438
  this.ovenAlarmService.updateCharacteristic(Characteristic.InUse, 0);
439
439
  }
440
440
  else {
441
- this.sendTimerCommand(this.timerAlarmSec);
441
+ this.runInBackground(this.sendTimerCommand(this.timerAlarmSec), 'Timer command');
442
442
  this.ovenAlarmService.updateCharacteristic(Characteristic.Active, 1);
443
443
  this.ovenAlarmService.updateCharacteristic(Characteristic.RemainingDuration, this.timerAlarmSec);
444
444
  this.ovenAlarmService.updateCharacteristic(Characteristic.InUse, 1);
@@ -625,7 +625,7 @@ export default class Microwave extends BaseDevice {
625
625
  }).onSet((value) => {
626
626
  const enabled = normalizeBoolean(value);
627
627
  if (enabled) {
628
- this.stopOven();
628
+ this.runInBackground(this.stopOven(), 'Stop command');
629
629
  }
630
630
  setTimeout(() => {
631
631
  this.cancelSwitch.updateCharacteristic(this.platform.Characteristic.On, false);
@@ -642,7 +642,7 @@ export default class Microwave extends BaseDevice {
642
642
  }).onSet((value) => {
643
643
  const enabled = normalizeBoolean(value);
644
644
  if (enabled) {
645
- this.sendOvenCommand();
645
+ this.runInBackground(this.sendOvenCommand(), 'Cooking command');
646
646
  setTimeout(() => {
647
647
  this.startOvenSwitch.updateCharacteristic(this.platform.Characteristic.On, false);
648
648
  }, 1000);
@@ -671,7 +671,7 @@ export default class Microwave extends BaseDevice {
671
671
  .onSet((value) => {
672
672
  const enabled = normalizeBoolean(value);
673
673
  if (!enabled) {
674
- this.stopOven();
674
+ this.runInBackground(this.stopOven(), 'Stop command');
675
675
  }
676
676
  else {
677
677
  this.pauseUpdate = true;
@@ -147,10 +147,10 @@ export default class Oven extends BaseDevice {
147
147
  this.ovenService.getCharacteristic(this.platform.Characteristic.Active).onGet(this.onlineGet(() => this.ovenServiceActive())).onSet((value) => {
148
148
  const enabled = normalizeBoolean(value);
149
149
  if (!enabled) {
150
- this.stopOven();
150
+ this.runInBackground(this.stopOven(), 'Stop command');
151
151
  }
152
152
  else {
153
- this.sendOvenCommand();
153
+ this.runInBackground(this.sendOvenCommand(), 'Cooking command');
154
154
  }
155
155
  });
156
156
  this.ovenService
@@ -265,13 +265,13 @@ export default class Oven extends BaseDevice {
265
265
  this.ovenTimerService.getCharacteristic(Characteristic.Active).onGet(this.onlineGet(() => this.remainTime() !== 0 ? 1 : 0)).onSet((value) => {
266
266
  const enabled = normalizeBoolean(value);
267
267
  if (!enabled) {
268
- this.stopOven();
268
+ this.runInBackground(this.stopOven(), 'Stop command');
269
269
  this.ovenTimerService.updateCharacteristic(Characteristic.Active, 0);
270
270
  this.ovenTimerService.updateCharacteristic(Characteristic.RemainingDuration, 0);
271
271
  this.ovenTimerService.updateCharacteristic(Characteristic.InUse, 0);
272
272
  }
273
273
  else {
274
- this.sendOvenCommand();
274
+ this.runInBackground(this.sendOvenCommand(), 'Cooking command');
275
275
  }
276
276
  });
277
277
  this.ovenTimerService.setCharacteristic(Characteristic.InUse, this.remainTime() > 0 ? Characteristic.InUse.IN_USE : Characteristic.InUse.NOT_IN_USE);
@@ -302,13 +302,13 @@ export default class Oven extends BaseDevice {
302
302
  const enabled = normalizeBoolean(value);
303
303
  if (!enabled) {
304
304
  this.timerAlarmSec = 0;
305
- this.sendTimerCommand(0);
305
+ this.runInBackground(this.sendTimerCommand(0), 'Timer command');
306
306
  this.ovenAlarmService.updateCharacteristic(Characteristic.Active, 0);
307
307
  this.ovenAlarmService.updateCharacteristic(Characteristic.RemainingDuration, 0);
308
308
  this.ovenAlarmService.updateCharacteristic(Characteristic.InUse, 0);
309
309
  }
310
310
  else {
311
- this.sendTimerCommand(this.timerAlarmSec);
311
+ this.runInBackground(this.sendTimerCommand(this.timerAlarmSec), 'Timer command');
312
312
  this.ovenAlarmService.updateCharacteristic(Characteristic.Active, 1);
313
313
  this.ovenAlarmService.updateCharacteristic(Characteristic.RemainingDuration, this.timerAlarmSec);
314
314
  this.ovenAlarmService.updateCharacteristic(Characteristic.InUse, 1);
@@ -442,7 +442,7 @@ export default class Oven extends BaseDevice {
442
442
  }).onSet((value) => {
443
443
  const enabled = normalizeBoolean(value);
444
444
  if (enabled) {
445
- this.stopOven();
445
+ this.runInBackground(this.stopOven(), 'Stop command');
446
446
  }
447
447
  setTimeout(() => {
448
448
  this.cancelSwitch.updateCharacteristic(this.platform.Characteristic.On, false);
@@ -474,7 +474,7 @@ export default class Oven extends BaseDevice {
474
474
  }).onSet((value) => {
475
475
  const enabled = normalizeBoolean(value);
476
476
  if (enabled) {
477
- this.sendOvenCommand();
477
+ this.runInBackground(this.sendOvenCommand(), 'Cooking command');
478
478
  setTimeout(() => {
479
479
  this.startOvenSwitch.updateCharacteristic(this.platform.Characteristic.On, false);
480
480
  }, 1000);
@@ -550,7 +550,7 @@ export default class Oven extends BaseDevice {
550
550
  .onSet((value) => {
551
551
  const enabled = normalizeBoolean(value);
552
552
  if (!enabled) {
553
- this.stopOven();
553
+ this.runInBackground(this.stopOven(), 'Stop command');
554
554
  }
555
555
  else {
556
556
  this.pauseUpdate = true;
package/dist/lib/API.js CHANGED
@@ -8,6 +8,7 @@ import { ManualProcessNeeded, MonitorError, NotConnectedError, TokenExpiredError
8
8
  import crypto from 'crypto';
9
9
  import axios from 'axios';
10
10
  import { createNoopLogger } from './noopLogger.js';
11
+ import { describeError } from './errorFormat.js';
11
12
  /**
12
13
  * ThinQ result codes returned for commands a device simply does not support
13
14
  * (for example the AC temperature keep-alive on models that reject it). The
@@ -115,19 +116,25 @@ export class API {
115
116
  return await this.refreshNewToken().then(async () => {
116
117
  return await this.request(method, uri, data, true);
117
118
  }).catch((err) => {
118
- this.logger.error('refresh new token error: ', err);
119
+ this.logger.error('refresh new token error: ', describeError(err));
119
120
  return {};
120
121
  });
121
122
  }
122
123
  else if (err instanceof ManualProcessNeeded) {
123
124
  // Handle manual process errors (e.g., new terms agreement)
124
- this.logger.warn('Handling new term agreement... If you keep getting this message, ' + err.message);
125
+ this.logger.warn('LG asks to accept new terms. If you keep getting this message, ' + err.message);
125
126
  await this.auth.handleNewTerm(this.session.accessToken)
126
- .then(() => {
127
- this.logger.warn('LG new term agreement is accepted.');
127
+ .then((acceptedTerms) => {
128
+ if (acceptedTerms.length) {
129
+ this.logger.warn('Accepted new LG terms on behalf of your account so the plugin keeps working: '
130
+ + acceptedTerms.join(', ') + '. You can review them in the LG ThinQ app.');
131
+ }
132
+ else {
133
+ this.logger.warn('LG asked for new terms, but none were pending for your account.');
134
+ }
128
135
  })
129
136
  .catch(err => {
130
- this.logger.error(err);
137
+ this.logger.error(describeError(err));
131
138
  });
132
139
  if (!retry) {
133
140
  // Retry the request once
@@ -157,7 +164,7 @@ export class API {
157
164
  }
158
165
  }
159
166
  else {
160
- this.logger.error('request error: ', err);
167
+ this.logger.error('request error: ', describeError(err));
161
168
  }
162
169
  return {};
163
170
  }
package/dist/lib/Auth.js CHANGED
@@ -7,6 +7,7 @@ import * as constants from './constants.js';
7
7
  import { BROWSER_USER_AGENT, requestClient } from './request.js';
8
8
  import { Session } from './Session.js';
9
9
  import { createNoopLogger } from './noopLogger.js';
10
+ import { describeError } from './errorFormat.js';
10
11
  function recordValue(value) {
11
12
  return value !== null && typeof value === 'object' ? value : null;
12
13
  }
@@ -45,6 +46,16 @@ export function authErrorMessage(err, fallback) {
45
46
  || (errorCause(err) ? authErrorMessage(errorCause(err), fallback) : null)
46
47
  || fallback;
47
48
  }
49
+ export const SIGN_IN_UNLOCK_MESSAGE = 'LG has locked sign-in for this account and asks to unlock it '
50
+ + '(LG message: "Need Sign-In Unlock"). This usually happens after several failed sign-ins or a sign-in '
51
+ + 'from a new device. Sign in to the LG ThinQ app or to your LG account on the LG website and complete '
52
+ + 'the verification LG asks for, then try again. You can also get a refresh token with the "thinq auth" '
53
+ + 'command, which uses the LG sign-in page.';
54
+ // LG answers sign-ins to a locked account with a message like
55
+ // "Need Sign-In Unlock:420:<masked email>:Y".
56
+ export function isSignInUnlockRequired(message) {
57
+ return typeof message === 'string' && /sign-?in\s*unlock/i.test(message);
58
+ }
48
59
  function authError(context, err) {
49
60
  const message = authErrorMessage(err, 'Request failed.');
50
61
  const error = new AuthenticationError(`${context}: ${message}`);
@@ -120,6 +131,9 @@ export class Auth {
120
131
  if (code === 'MS.001.03') {
121
132
  throw new AuthenticationError('Your account was already used to registered in ' + message + '.');
122
133
  }
134
+ if (isSignInUnlockRequired(message)) {
135
+ throw new AuthenticationError(SIGN_IN_UNLOCK_MESSAGE);
136
+ }
123
137
  throw new AuthenticationError(message);
124
138
  });
125
139
  // dynamic get secret key for emp signature
@@ -212,9 +226,17 @@ export class Auth {
212
226
  *
213
227
  * @param accessToken - The access token for the session.
214
228
  */
229
+ /**
230
+ * Accepts the LG terms that the account has not accepted yet, which LG requires
231
+ * before it answers API requests again.
232
+ *
233
+ * @returns The accepted terms as `type:id:language` entries; empty if none were pending.
234
+ */
215
235
  async handleNewTerm(accessToken) {
216
236
  const showTermUrl = 'common/showTerms?callback_url=lgaccount.lgsmartthinq:/updateTerms'
217
- + '&country=VN&language=en-VN&division=ha:T20&terms_display_type=3&svc_list=SVC202';
237
+ + '&country=' + encodeURIComponent(this.gateway.country_code)
238
+ + '&language=' + encodeURIComponent(this.gateway.language_code)
239
+ + '&division=ha:T20&terms_display_type=3&svc_list=SVC202';
218
240
  const showTermHtml = await requestClient.get(this.gateway.login_base_url + showTermUrl, {
219
241
  headers: {
220
242
  'X-Login-Session': accessToken,
@@ -238,17 +260,18 @@ export class Auth {
238
260
  const infoTerms = await requestClient.get(this.gateway.emp_base_url + termInfoUrl, { headers }).then(res => {
239
261
  return res.data.info.terms;
240
262
  });
241
- const newTermAgreeNeeded = infoTerms.filter((term) => {
263
+ const newTerms = infoTerms.filter((term) => {
242
264
  return accountTerms.indexOf(term.termsID) === -1;
243
265
  }).map((term) => {
244
266
  return [term.termsType, term.termsID, term.defaultLang].join(':');
245
- }).join(',');
246
- if (newTermAgreeNeeded) {
267
+ });
268
+ if (newTerms.length) {
247
269
  const updateAccountTermUrl = 'emp/v2.0/account/user/terms';
248
- await requestClient.post(this.gateway.emp_base_url + updateAccountTermUrl, qs.stringify({ terms: newTermAgreeNeeded }), {
270
+ await requestClient.post(this.gateway.emp_base_url + updateAccountTermUrl, qs.stringify({ terms: newTerms.join(',') }), {
249
271
  headers,
250
272
  });
251
273
  }
274
+ return newTerms;
252
275
  }
253
276
  /**
254
277
  * Retrieves the JSession ID for ThinQ v1 API compatibility.
@@ -281,7 +304,7 @@ export class Auth {
281
304
  ? 'Please open the native LG App and sign in to your account to see what happened,'
282
305
  + ' maybe new agreement need your accept. Then try restarting Homebridge.'
283
306
  : err.message);
284
- this.logger.debug(err);
307
+ this.logger.debug(describeError(err, { stack: true }));
285
308
  this.logger.info('Failed to login to old thinq v1 gateway. See debug logs for more details. Continuing anyways.');
286
309
  });
287
310
  }
package/dist/lib/ThinQ.js CHANGED
@@ -11,6 +11,7 @@ import { coerceCommandPayload } from './commandPayload.js';
11
11
  import { loadMqttConnectionSetup, prepareMqttConnection, retryMqttRegistration, } from './mqttCertificate.js';
12
12
  import { wireMqttDeviceEvents } from './mqttConnection.js';
13
13
  import { pollThinQ1MonitorResult, registerThinQ1WorkId, unregisterThinQ1WorkId, } from './thinq1Monitor.js';
14
+ import { describeError } from './errorFormat.js';
14
15
  export class ThinQ {
15
16
  platform;
16
17
  config;
@@ -98,7 +99,7 @@ export class ThinQ {
98
99
  thinq1DeviceControl(device, key, value) {
99
100
  const data = Helper.prepareControlData(device, key, value);
100
101
  return this.api.thinq1PostRequest('rti/rtiControl', data).catch(err => {
101
- this.logger.error('Unknown Error: ', err);
102
+ this.logger.error('Unknown Error: ', describeError(err));
102
103
  });
103
104
  }
104
105
  async deviceControl(device, values, command = 'Set', ctrlKey = 'basicCtrl', ctrlPath = 'control-sync') {
@@ -0,0 +1,96 @@
1
+ import axios from 'axios';
2
+ const MAX_CAUSE_DEPTH = 3;
3
+ function isRecord(value) {
4
+ return typeof value === 'object' && value !== null;
5
+ }
6
+ function stringValue(value) {
7
+ if (typeof value === 'string' && value.trim()) {
8
+ return value;
9
+ }
10
+ if (typeof value === 'number') {
11
+ return String(value);
12
+ }
13
+ return undefined;
14
+ }
15
+ function urlWithoutQuery(url, baseURL) {
16
+ if (!url) {
17
+ return undefined;
18
+ }
19
+ try {
20
+ const parsed = new URL(url, baseURL);
21
+ return parsed.origin + parsed.pathname;
22
+ }
23
+ catch {
24
+ return url.split('?')[0];
25
+ }
26
+ }
27
+ function lgResponseDetails(data) {
28
+ if (!isRecord(data)) {
29
+ return [];
30
+ }
31
+ const error = isRecord(data.error) ? data.error : undefined;
32
+ const details = [];
33
+ const resultCode = stringValue(data.resultCode) ?? stringValue(error?.code);
34
+ const message = stringValue(error?.message)
35
+ ?? stringValue(data.message)
36
+ ?? stringValue(data.error_description)
37
+ ?? stringValue(data.returnMsg);
38
+ if (resultCode) {
39
+ details.push('LG code ' + resultCode);
40
+ }
41
+ if (message) {
42
+ details.push('LG message "' + message + '"');
43
+ }
44
+ return details;
45
+ }
46
+ // The plugin's own error classes do not set `name`, so fall back to the class name.
47
+ function errorName(err) {
48
+ return err.name !== 'Error' ? err.name : (err.constructor?.name || 'Error');
49
+ }
50
+ function describeOne(err) {
51
+ if (axios.isAxiosError(err)) {
52
+ const details = [];
53
+ if (err.response?.status) {
54
+ details.push('HTTP ' + err.response.status);
55
+ }
56
+ if (err.code) {
57
+ details.push(err.code);
58
+ }
59
+ details.push(...lgResponseDetails(err.response?.data));
60
+ const url = urlWithoutQuery(err.config?.url, err.config?.baseURL);
61
+ if (url) {
62
+ details.push((err.config?.method ?? 'get').toUpperCase() + ' ' + url);
63
+ }
64
+ return `${err.name}: ${err.message}` + (details.length ? ` (${details.join(', ')})` : '');
65
+ }
66
+ if (err instanceof Error) {
67
+ return `${errorName(err)}: ${err.message}`;
68
+ }
69
+ if (typeof err === 'string') {
70
+ return err;
71
+ }
72
+ return 'Non-error value: ' + Object.prototype.toString.call(err);
73
+ }
74
+ /**
75
+ * Describes an error for logging, without the data of the request that failed.
76
+ *
77
+ * axios errors carry the whole request configuration: headers with the LG access
78
+ * token, and bodies with the refresh token or the password hash. Logging the error
79
+ * object (or an error whose `cause` is one) prints all of that, and users share
80
+ * Homebridge logs in public issues. Log this description instead.
81
+ */
82
+ export function describeError(err, options = {}) {
83
+ const lines = [];
84
+ let current = err;
85
+ for (let depth = 0; depth <= MAX_CAUSE_DEPTH && current !== undefined && current !== null; depth++) {
86
+ const prefix = depth === 0 ? '' : 'Caused by: ';
87
+ lines.push(prefix + describeOne(current));
88
+ if (options.stack && current instanceof Error && current.stack) {
89
+ const frames = current.stack.split('\n').filter(line => line.trimStart().startsWith('at '));
90
+ lines.push(...frames);
91
+ }
92
+ current = current instanceof Error ? current.cause : undefined;
93
+ }
94
+ return lines.join('\n');
95
+ }
96
+ //# sourceMappingURL=errorFormat.js.map
@@ -2,6 +2,7 @@ import * as FS from 'fs';
2
2
  import * as Path from 'path';
3
3
  import forge from 'node-forge';
4
4
  import { URL } from 'url';
5
+ import { describeError } from './errorFormat.js';
5
6
  export const ATS_ROOT_CA_URL = 'https://www.amazontrust.com/repository/AmazonRootCA1.pem';
6
7
  export const LG_ROOT_CA_URL = 'https://support.sectigo.com/sfc/servlet.shepherd/version/download/0683l00000G9fLm';
7
8
  export const LEGACY_ROOT_CA_URL = 'https://www.websecurity.digicert.com/content/dam/websitesecurity/digitalassets/desktop/pdfs/roots/' +
@@ -91,23 +92,31 @@ export function mqttCertificatePaths(mqttDir) {
91
92
  certPath: Path.join(mqttDir, 'cert.pem'),
92
93
  };
93
94
  }
94
- export async function writeIfChanged(path, content) {
95
+ // The private key authenticates the plugin to LG's MQTT broker: only the Homebridge user may read it.
96
+ export const MQTT_PRIVATE_FILE_MODE = 0o600;
97
+ export const MQTT_DIRECTORY_MODE = 0o700;
98
+ export async function writeIfChanged(path, content, mode) {
95
99
  try {
96
100
  const existing = await FS.promises.readFile(path, 'utf8').catch(() => null);
97
101
  if (existing !== content) {
98
- await FS.promises.writeFile(path, content, 'utf8');
102
+ await FS.promises.writeFile(path, content, { encoding: 'utf8', mode });
99
103
  }
100
104
  }
101
105
  catch (err) {
102
- await FS.promises.writeFile(path, content, 'utf8');
106
+ await FS.promises.writeFile(path, content, { encoding: 'utf8', mode });
107
+ }
108
+ // `mode` only applies when the file is created; also fix files written by older versions.
109
+ if (mode !== undefined) {
110
+ await FS.promises.chmod(path, mode);
103
111
  }
104
112
  }
105
113
  export async function writeMqttCertificateFiles(options) {
106
114
  const { mqttDir, rootCA, privateKey, certificatePem } = options;
107
- await FS.promises.mkdir(mqttDir, { recursive: true });
115
+ await FS.promises.mkdir(mqttDir, { recursive: true, mode: MQTT_DIRECTORY_MODE });
116
+ await FS.promises.chmod(mqttDir, MQTT_DIRECTORY_MODE);
108
117
  const paths = mqttCertificatePaths(mqttDir);
109
118
  await writeIfChanged(paths.caPath, rootCA);
110
- await writeIfChanged(paths.keyPath, privateKey);
119
+ await writeIfChanged(paths.keyPath, privateKey, MQTT_PRIVATE_FILE_MODE);
111
120
  await writeIfChanged(paths.certPath, certificatePem);
112
121
  return paths;
113
122
  }
@@ -142,7 +151,7 @@ export async function retryMqttRegistration(options) {
142
151
  }
143
152
  catch (err) {
144
153
  tried--;
145
- logger.debug('mqtt err:', err);
154
+ logger.debug('mqtt err:', describeError(err));
146
155
  if (tried > 0) {
147
156
  logger.debug('Cannot start MQTT, retrying in 5s.');
148
157
  await delay(retryDelayMs);
@@ -1,8 +1,11 @@
1
+ import { describeError } from './errorFormat.js';
1
2
  export const MQTT_OFFLINE_RECONNECT_DELAY_MS = 60000;
2
3
  export function wireMqttDeviceEvents(options) {
3
- const { device, logger, mqttServer, subscriptions, onMessage, reconnect, scheduleReconnect = (handler, delayMs) => setTimeout(handler, delayMs), } = options;
4
+ const { device, logger, mqttServer, subscriptions, onMessage, reconnect, scheduleReconnect = (handler, delayMs) => setTimeout(() => {
5
+ void handler();
6
+ }, delayMs), } = options;
4
7
  device.on('error', (err) => {
5
- logger.error('mqtt err:', err);
8
+ logger.error('mqtt err:', describeError(err));
6
9
  });
7
10
  device.on('connect', () => {
8
11
  logger.info('Successfully connected to the MQTT server.');
@@ -18,7 +21,7 @@ export function wireMqttDeviceEvents(options) {
18
21
  parsedPayload = JSON.parse(payloadText);
19
22
  }
20
23
  catch (err) {
21
- logger.error('mqtt message parse error:', err);
24
+ logger.error('mqtt message parse error:', describeError(err));
22
25
  logger.debug('mqtt invalid message received:', payloadText);
23
26
  return;
24
27
  }
@@ -30,7 +33,7 @@ export function wireMqttDeviceEvents(options) {
30
33
  logger.info('MQTT disconnected, retrying in 60 seconds!');
31
34
  scheduleReconnect(() => {
32
35
  reconnect().catch(err => {
33
- logger.error('mqtt reconnect failed:', err);
36
+ logger.error('mqtt reconnect failed:', describeError(err));
34
37
  });
35
38
  }, MQTT_OFFLINE_RECONNECT_DELAY_MS);
36
39
  });
package/dist/platform.js CHANGED
@@ -7,6 +7,7 @@ import { createOrRestoreDeviceAccessory, pendingAccessoryIds, removeStaleAccesso
7
7
  import { applyConfiguredDeviceOverrides, configuredDevices, hasRequiredThinQConfig, isThinQ1Enabled, refreshIntervalMs, } from './platformConfig.js';
8
8
  import { DISCOVERY_RETRY_DELAY_MS, isRetryableDiscoveryError, prepareDiscoveredDevice, } from './platformDiscovery.js';
9
9
  import { accessoriesForPlatform, clearMonitorIntervals, hasEnabledThinQ1Accessories, startThinQ1Monitor, startThinQ2Monitor, } from './platformMonitor.js';
10
+ import { describeError } from './lib/errorFormat.js';
10
11
  /**
11
12
  * LGThinQHomebridgePlatform
12
13
  * This class serves as the main entry point for the Homebridge plugin. It handles
@@ -59,7 +60,7 @@ export class LGThinQHomebridgePlatform {
59
60
  this.logThinQReadyError(err);
60
61
  });
61
62
  };
62
- this.api.on('didFinishLaunching', async () => {
63
+ this.api.on('didFinishLaunching', () => {
63
64
  log.debug('Executed didFinishLaunching callback');
64
65
  didFinishLaunching();
65
66
  });
@@ -107,7 +108,7 @@ export class LGThinQHomebridgePlatform {
107
108
  }
108
109
  logDiscoveryError(err) {
109
110
  this.log.error(err.message);
110
- this.log.debug(err);
111
+ this.log.debug(describeError(err, { stack: true }));
111
112
  }
112
113
  /**
113
114
  * Discovers devices from the ThinQ API and registers them as Homebridge accessories.
@@ -2,6 +2,7 @@ import { Helper } from './helper.js';
2
2
  import { NotConnectedError } from './errors/index.js';
3
3
  import { PlatformType } from './lib/constants.js';
4
4
  import { isDeviceEnabled } from './platformConfig.js';
5
+ import { describeError } from './lib/errorFormat.js';
5
6
  export const DISCOVERY_RETRY_DELAY_MS = 30000;
6
7
  const defaultDeviceAccessoryResolver = {
7
8
  make: device => Helper.make(device),
@@ -16,7 +17,7 @@ export function unregisterUnsupportedDevice(options) {
16
17
  thinq.unregister(device).then(() => {
17
18
  log.debug(device.id, '- unregistered!');
18
19
  }).catch(err => {
19
- log.debug(device.id, '- unregister failed:', err);
20
+ log.debug(device.id, '- unregister failed:', describeError(err));
20
21
  });
21
22
  }
22
23
  export async function prepareDiscoveredDevice(options) {
@@ -1,5 +1,6 @@
1
1
  import { ManualProcessNeeded } from './errors/index.js';
2
2
  import { PlatformType } from './lib/constants.js';
3
+ import { describeError } from './lib/errorFormat.js';
3
4
  export function accessoriesForPlatform(accessories, platform) {
4
5
  return accessories.filter(accessory => accessory.context.device.platform === platform);
5
6
  }
@@ -54,7 +55,7 @@ export async function startThinQ2Monitor(options) {
54
55
  const { log, thinq, events, intervalTime, monitorIntervals } = options;
55
56
  const thinq2Interval = setInterval(() => {
56
57
  pollThinQ2Devices({ thinq, events }).catch(err => {
57
- log.debug('ThinQ2 polling failed:', err);
58
+ log.debug('ThinQ2 polling failed:', describeError(err));
58
59
  });
59
60
  }, intervalTime);
60
61
  monitorIntervals.push(thinq2Interval);
@@ -70,23 +71,20 @@ export function startThinQ1Monitor(options) {
70
71
  ? configuredRefreshInterval
71
72
  : intervalTime / 1000;
72
73
  log.info('Start polling device data every ' + refreshSeconds + ' seconds.');
73
- const interval = setInterval(async () => {
74
- try {
75
- await pollThinQ1Accessories({
76
- thinq,
77
- accessories,
78
- events,
79
- enableThinQ1,
80
- });
81
- }
82
- catch (err) {
74
+ const interval = setInterval(() => {
75
+ pollThinQ1Accessories({
76
+ thinq,
77
+ accessories,
78
+ events,
79
+ enableThinQ1,
80
+ }).catch(err => {
83
81
  handleThinQ1PollError({
84
82
  err,
85
83
  log,
86
84
  interval,
87
85
  monitorIntervals,
88
86
  });
89
- }
87
+ });
90
88
  }, intervalTime);
91
89
  monitorIntervals.push(interval);
92
90
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "displayName": "Homebridge LG ThinQ 2",
3
3
  "name": "homebridge-lg-thinq-2",
4
- "version": "2.0.7",
4
+ "version": "2.0.9",
5
5
  "description": "Community-maintained continuation of homebridge-lg-thinq: a Homebridge plugin for controlling/monitoring LG ThinQ devices via the LG ThinQ platform.",
6
6
  "license": "Apache-2.0",
7
7
  "type": "module",
@@ -91,6 +91,9 @@
91
91
  },
92
92
  "node-persist": "^4.0.4",
93
93
  "brace-expansion": "^5.0.13",
94
- "ws": "^8.23.0"
94
+ "ws": "^8.23.0",
95
+ "nodemon": {
96
+ "minimatch": "^11.0.9"
97
+ }
95
98
  }
96
99
  }