homebridge-philips-air-purifier-complete 3.2.4 → 3.3.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 +35 -0
- package/README.md +20 -11
- package/homebridge-ui/public/index.html +100 -35
- package/homebridge-ui/server.js +285 -61
- package/package.json +1 -1
- package/scripts/airplus_setup.py +241 -32
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,41 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
|
|
|
6
6
|
|
|
7
7
|
---
|
|
8
8
|
|
|
9
|
+
## [3.3.0] — 18/06/2026
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- Air+ Cloud login now uses a server-side email + verification code flow by default. This avoids
|
|
14
|
+
the desktop browser deep-link mismatch where users could only copy a `home.id` web-client code,
|
|
15
|
+
which SAP CDC rejects as `invalid_grant` when exchanged with the Philips Air app client.
|
|
16
|
+
- The Homebridge custom UI and `scripts/airplus_setup.py` both support the new OTP flow and then
|
|
17
|
+
reuse the existing device picker/token-file write path.
|
|
18
|
+
|
|
19
|
+
### Changed
|
|
20
|
+
|
|
21
|
+
- Kept the browser redirect-copy login as an advanced fallback in the custom UI and behind
|
|
22
|
+
`python scripts/airplus_setup.py --browser` for CLI users.
|
|
23
|
+
- Added redacted Air+ auth redirect diagnostics when `PHILIPS_AIRPLUS_DEBUG=1` is set, so live
|
|
24
|
+
handshake issues can be traced without writing authorisation codes or login tickets to logs.
|
|
25
|
+
|
|
26
|
+
---
|
|
27
|
+
|
|
28
|
+
## [3.2.5] — 15/06/2026
|
|
29
|
+
|
|
30
|
+
### Fixed
|
|
31
|
+
|
|
32
|
+
- Air+ Cloud login: extract the authorisation code directly from the URL the user pastes —
|
|
33
|
+
whether it is the `com.philips.air://loginredirect?code=…` deep link or the `accounts.home.id`
|
|
34
|
+
consent/proxy page — by parsing the query string, then the URL fragment, then a regex fallback.
|
|
35
|
+
The v3.2.4 approach refetched the proxy page server-side, which could never succeed because the
|
|
36
|
+
authorisation code is bound to the user's authenticated browser session; that refetch is now only
|
|
37
|
+
a last resort. This is the fix for testers who reported the proxy page error after approving access.
|
|
38
|
+
- Air+ Cloud login: reworded the on-screen steps so the `accounts.home.id` URL is presented as an
|
|
39
|
+
equally valid thing to paste, not a fallback, since many desktop browsers never leave the
|
|
40
|
+
`com.philips.air://` URL in the address bar.
|
|
41
|
+
|
|
42
|
+
---
|
|
43
|
+
|
|
9
44
|
## [3.2.4] — 15/06/2026
|
|
10
45
|
|
|
11
46
|
### Fixed
|
package/README.md
CHANGED
|
@@ -351,9 +351,9 @@ Use the Homebridge plugin configuration form to add, edit, or remove CoAP, HTTP,
|
|
|
351
351
|
Air+ cloud devices. The form presents `devices[]` as one tab per purifier, with protocol-specific
|
|
352
352
|
fields shown only when they apply.
|
|
353
353
|
|
|
354
|
-
Air+ cloud devices also need an account token. Open **Plugin Settings**,
|
|
355
|
-
|
|
356
|
-
|
|
354
|
+
Air+ cloud devices also need an account token. Open **Plugin Settings**, enter the Philips account
|
|
355
|
+
email, complete the verification code flow, select the device, then review the new Air+ card and
|
|
356
|
+
click **Save Changes**.
|
|
357
357
|
|
|
358
358
|
The **JSON Config** tab remains supported for direct edits to `devices[]`. Existing v3.1
|
|
359
359
|
installations that still contain `additionalDevicesJson` continue to merge those entries at
|
|
@@ -397,16 +397,19 @@ If your device shows `Network error: NetworkError` on every command, try setting
|
|
|
397
397
|
|
|
398
398
|
1. Install the plugin via the Homebridge UI
|
|
399
399
|
2. Go to **Plugins → Philips Air Purifier → Plugin Settings**
|
|
400
|
-
3.
|
|
401
|
-
4. Click **
|
|
402
|
-
5.
|
|
403
|
-
6.
|
|
404
|
-
7.
|
|
405
|
-
8.
|
|
406
|
-
9. Restart Homebridge
|
|
400
|
+
3. Enter the email address for your Philips Air+ account
|
|
401
|
+
4. Click **Send Code**
|
|
402
|
+
5. Enter the verification code from the email and click **Verify & List Devices**
|
|
403
|
+
6. Click **Add Device** next to your purifier
|
|
404
|
+
7. Review the new Air+ device card and click **Save Changes**
|
|
405
|
+
8. Restart Homebridge
|
|
407
406
|
|
|
408
407
|
Each device needs its own setup run. Run through the wizard once per purifier.
|
|
409
408
|
|
|
409
|
+
The older browser redirect-copy login remains available under
|
|
410
|
+
**Advanced: log in via browser**. Use it only as a fallback; the email verification code flow avoids
|
|
411
|
+
the desktop deep-link mismatch that can produce `invalid_grant` errors.
|
|
412
|
+
|
|
410
413
|
Deleting an Air+ device from the Homebridge form removes it from the Homebridge config only. The
|
|
411
414
|
token file is intentionally left on disk at `~/.homebridge/philips-airplus-{uuid}.json` so an
|
|
412
415
|
accidental delete does not revoke local setup state. Remove that file manually if you are cleaning
|
|
@@ -422,9 +425,15 @@ source .venv/bin/activate
|
|
|
422
425
|
python scripts/airplus_setup.py
|
|
423
426
|
```
|
|
424
427
|
|
|
425
|
-
Follow the on-screen instructions. The script saves a token file to
|
|
428
|
+
Follow the on-screen instructions. The script sends an email verification code, saves a token file to
|
|
426
429
|
`~/.homebridge/philips-airplus-{uuid}.json` and prints the Homebridge config to add.
|
|
427
430
|
|
|
431
|
+
To use the legacy browser redirect-copy fallback instead:
|
|
432
|
+
|
|
433
|
+
```bash
|
|
434
|
+
python scripts/airplus_setup.py --browser
|
|
435
|
+
```
|
|
436
|
+
|
|
428
437
|
---
|
|
429
438
|
|
|
430
439
|
## Connectivity Check (optional)
|
|
@@ -200,9 +200,6 @@
|
|
|
200
200
|
text-align: center;
|
|
201
201
|
}
|
|
202
202
|
|
|
203
|
-
.airplus-step { display: none; }
|
|
204
|
-
.airplus-step.active { display: block; }
|
|
205
|
-
|
|
206
203
|
.airplus-device-grid { display: grid; gap: 10px; }
|
|
207
204
|
|
|
208
205
|
.airplus-device-card {
|
|
@@ -256,18 +253,47 @@
|
|
|
256
253
|
<p style="color: var(--muted); font-size: 13px; margin-bottom: 12px;">
|
|
257
254
|
Use this to add devices from a Philips Air+ cloud account. Your purifier must be registered in the Philips Air+ app.
|
|
258
255
|
</p>
|
|
259
|
-
|
|
260
|
-
|
|
256
|
+
|
|
257
|
+
<div id="airplus-otp-flow">
|
|
258
|
+
<div class="field">
|
|
259
|
+
<label for="airplus-email">Philips account email</label>
|
|
260
|
+
<input id="airplus-email" type="email" autocomplete="email" placeholder="name@example.com">
|
|
261
|
+
</div>
|
|
262
|
+
<div class="toolbar">
|
|
263
|
+
<button id="airplus-send-code" type="button">Send Code</button>
|
|
264
|
+
</div>
|
|
265
|
+
<div id="airplus-code-wrap" hidden>
|
|
266
|
+
<div class="field">
|
|
267
|
+
<label for="airplus-code">Verification code</label>
|
|
268
|
+
<input id="airplus-code" type="text" inputmode="numeric" autocomplete="one-time-code" placeholder="6-digit code">
|
|
269
|
+
</div>
|
|
270
|
+
<div class="toolbar">
|
|
271
|
+
<button id="airplus-verify-code" type="button">Verify & List Devices</button>
|
|
272
|
+
<button class="secondary" type="button" data-airplus-cancel>Cancel</button>
|
|
273
|
+
</div>
|
|
274
|
+
</div>
|
|
275
|
+
</div>
|
|
276
|
+
|
|
277
|
+
<div id="airplus-device-step" hidden>
|
|
278
|
+
<div id="airplus-device-list" class="airplus-device-grid">
|
|
279
|
+
<div class="empty-state">Connecting…</div>
|
|
280
|
+
</div>
|
|
281
|
+
<div class="toolbar" style="margin-top: 10px;">
|
|
282
|
+
<button class="secondary" type="button" data-airplus-cancel>Cancel</button>
|
|
283
|
+
</div>
|
|
261
284
|
</div>
|
|
262
285
|
|
|
263
|
-
<
|
|
264
|
-
<
|
|
286
|
+
<details>
|
|
287
|
+
<summary>Advanced: log in via browser</summary>
|
|
288
|
+
<div class="toolbar">
|
|
289
|
+
<button id="airplus-start" type="button" class="secondary">Open Philips Login</button>
|
|
290
|
+
</div>
|
|
291
|
+
<div id="airplus-browser-flow" hidden>
|
|
265
292
|
<ol style="color: var(--muted); font-size: 13px; padding-left: 20px; margin: 0 0 14px; line-height: 1.7;">
|
|
266
293
|
<li><a id="auth-link" href="#" target="_blank" rel="noopener">Open the Philips login page</a> (a new tab will open automatically — click the link if it didn't).</li>
|
|
267
294
|
<li>Log in to your Philips account and approve access when prompted.</li>
|
|
268
|
-
<li>
|
|
269
|
-
<li>
|
|
270
|
-
<li>If your address bar shows a Philips website (like <em>accounts.home.id</em>), paste that URL here instead — we'll try to extract the code automatically.</li>
|
|
295
|
+
<li>After approving, your browser will try to open the Philips Air app and will land on either an error page or a Philips page (<em>accounts.home.id</em>) — this is expected.</li>
|
|
296
|
+
<li>Copy the <strong style="color: var(--text);">full URL from your browser's address bar</strong> and paste it below. It works whether it starts with <code style="background:#1a1a1a; padding: 1px 4px; border-radius: 3px; font-size: 12px;">com.philips.air://loginredirect?code=…</code> or is an <em>accounts.home.id</em> address — as long as it contains <code style="background:#1a1a1a; padding: 1px 4px; border-radius: 3px; font-size: 12px;">code=…</code>.</li>
|
|
271
297
|
</ol>
|
|
272
298
|
<div class="field">
|
|
273
299
|
<label for="redirect-url">Redirect URL (from your browser's address bar)</label>
|
|
@@ -278,16 +304,7 @@
|
|
|
278
304
|
<button class="secondary" type="button" data-airplus-cancel>Cancel</button>
|
|
279
305
|
</div>
|
|
280
306
|
</div>
|
|
281
|
-
|
|
282
|
-
<div id="airplus-step-2" class="airplus-step">
|
|
283
|
-
<div id="airplus-device-list" class="airplus-device-grid">
|
|
284
|
-
<div class="empty-state">Connecting…</div>
|
|
285
|
-
</div>
|
|
286
|
-
<div class="toolbar" style="margin-top: 10px;">
|
|
287
|
-
<button class="secondary" type="button" data-airplus-cancel>Cancel</button>
|
|
288
|
-
</div>
|
|
289
|
-
</div>
|
|
290
|
-
</div>
|
|
307
|
+
</details>
|
|
291
308
|
</div>
|
|
292
309
|
|
|
293
310
|
<!-- Save -->
|
|
@@ -411,7 +428,7 @@
|
|
|
411
428
|
<div class="section-title">Air+ Cloud</div>
|
|
412
429
|
<div class="field">
|
|
413
430
|
<label>Device UUID</label>
|
|
414
|
-
<input type="text" data-field="airplusDeviceUuid" value="${uuidVal}" placeholder="Filled automatically by
|
|
431
|
+
<input type="text" data-field="airplusDeviceUuid" value="${uuidVal}" placeholder="Filled automatically by Air+ setup">
|
|
415
432
|
</div>
|
|
416
433
|
<div class="field">
|
|
417
434
|
<label>Token File Path</label>
|
|
@@ -599,28 +616,74 @@
|
|
|
599
616
|
|
|
600
617
|
function setAirplusBusy(v) {
|
|
601
618
|
airplusBusy = v;
|
|
602
|
-
document.getElementById('airplus-
|
|
603
|
-
document.getElementById('airplus-
|
|
619
|
+
document.getElementById('airplus-send-code').disabled = v;
|
|
620
|
+
document.getElementById('airplus-verify-code').disabled = v;
|
|
621
|
+
document.getElementById('airplus-start').disabled = v;
|
|
622
|
+
document.getElementById('airplus-continue').disabled = v;
|
|
604
623
|
document.querySelectorAll('[data-airplus-add]').forEach(b => { b.disabled = v; });
|
|
605
624
|
}
|
|
606
625
|
|
|
607
|
-
function setAirplusStep(n) {
|
|
608
|
-
document.querySelectorAll('.airplus-step').forEach(el => el.classList.remove('active'));
|
|
609
|
-
document.getElementById('airplus-step-' + n).classList.add('active');
|
|
610
|
-
}
|
|
611
|
-
|
|
612
626
|
function closeAirplusFlow(showMsg) {
|
|
613
|
-
document.getElementById('airplus-flow').hidden = true;
|
|
614
|
-
document.getElementById('
|
|
627
|
+
document.getElementById('airplus-browser-flow').hidden = true;
|
|
628
|
+
document.getElementById('airplus-device-step').hidden = true;
|
|
629
|
+
document.getElementById('airplus-code-wrap').hidden = true;
|
|
630
|
+
document.getElementById('redirect-url').value = '';
|
|
631
|
+
document.getElementById('airplus-code').value = '';
|
|
615
632
|
document.getElementById('airplus-device-list').innerHTML = '<div class="empty-state">Connecting…</div>';
|
|
616
633
|
if (showMsg) showStatus('Air+ setup cancelled.', 'info');
|
|
617
634
|
}
|
|
618
635
|
|
|
636
|
+
function showAirplusDeviceStep() {
|
|
637
|
+
document.getElementById('airplus-browser-flow').hidden = true;
|
|
638
|
+
document.getElementById('airplus-device-step').hidden = false;
|
|
639
|
+
document.getElementById('airplus-device-list').innerHTML = '<div class="empty-state">Connecting…</div>';
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
async function sendAirplusCode() {
|
|
643
|
+
const email = document.getElementById('airplus-email').value.trim();
|
|
644
|
+
if (!email) {
|
|
645
|
+
showStatus('Enter your Philips account email before sending a code.', 'error');
|
|
646
|
+
return;
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
hideStatus();
|
|
650
|
+
closeAirplusFlow(false);
|
|
651
|
+
setAirplusBusy(true);
|
|
652
|
+
try {
|
|
653
|
+
await req('/auth/otp/send', { email });
|
|
654
|
+
document.getElementById('airplus-code-wrap').hidden = false;
|
|
655
|
+
document.getElementById('airplus-code').focus();
|
|
656
|
+
showStatus('Verification code sent. Check your Philips account email.', 'success');
|
|
657
|
+
} finally {
|
|
658
|
+
setAirplusBusy(false);
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
async function verifyAirplusCode() {
|
|
663
|
+
const code = document.getElementById('airplus-code').value.trim();
|
|
664
|
+
if (!code) {
|
|
665
|
+
showStatus('Enter the verification code before continuing.', 'error');
|
|
666
|
+
return;
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
hideStatus();
|
|
670
|
+
showAirplusDeviceStep();
|
|
671
|
+
setAirplusBusy(true);
|
|
672
|
+
try {
|
|
673
|
+
const result = await req('/auth/otp/verify', { code });
|
|
674
|
+
renderAirplusDevices(result.devices || []);
|
|
675
|
+
} catch (_) {
|
|
676
|
+
document.getElementById('airplus-device-step').hidden = true;
|
|
677
|
+
} finally {
|
|
678
|
+
setAirplusBusy(false);
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
|
|
619
682
|
async function startAirplusSetup() {
|
|
620
683
|
hideStatus();
|
|
621
684
|
setAirplusBusy(true);
|
|
622
|
-
document.getElementById('airplus-flow').hidden = false;
|
|
623
|
-
|
|
685
|
+
document.getElementById('airplus-browser-flow').hidden = false;
|
|
686
|
+
document.getElementById('airplus-device-step').hidden = true;
|
|
624
687
|
|
|
625
688
|
const authWin = window.open('about:blank', '_blank');
|
|
626
689
|
try {
|
|
@@ -643,14 +706,14 @@
|
|
|
643
706
|
}
|
|
644
707
|
|
|
645
708
|
setAirplusBusy(true);
|
|
646
|
-
|
|
647
|
-
document.getElementById('airplus-device-list').innerHTML = '<div class="empty-state">Connecting…</div>';
|
|
709
|
+
showAirplusDeviceStep();
|
|
648
710
|
|
|
649
711
|
try {
|
|
650
712
|
const result = await req('/auth/exchange', { redirectUrl });
|
|
651
713
|
renderAirplusDevices(result.devices || []);
|
|
652
714
|
} catch (_) {
|
|
653
|
-
|
|
715
|
+
document.getElementById('airplus-browser-flow').hidden = false;
|
|
716
|
+
document.getElementById('airplus-device-step').hidden = true;
|
|
654
717
|
} finally {
|
|
655
718
|
setAirplusBusy(false);
|
|
656
719
|
}
|
|
@@ -708,6 +771,8 @@
|
|
|
708
771
|
|
|
709
772
|
document.getElementById('save-btn').addEventListener('click', saveConfig);
|
|
710
773
|
|
|
774
|
+
document.getElementById('airplus-send-code').addEventListener('click', sendAirplusCode);
|
|
775
|
+
document.getElementById('airplus-verify-code').addEventListener('click', verifyAirplusCode);
|
|
711
776
|
document.getElementById('airplus-start').addEventListener('click', startAirplusSetup);
|
|
712
777
|
document.getElementById('airplus-continue').addEventListener('click', exchangeAirplusCode);
|
|
713
778
|
|
package/homebridge-ui/server.js
CHANGED
|
@@ -13,40 +13,36 @@ const REDIRECT_URI = 'com.philips.air://loginredirect';
|
|
|
13
13
|
const OIDC_BASE = 'https://cdc.accounts.home.id/oidc/op/v1.0/' + TENANT;
|
|
14
14
|
const TOKEN_ENDPOINT = OIDC_BASE + '/token';
|
|
15
15
|
const AUTHORIZE_ENDPOINT = OIDC_BASE + '/authorize';
|
|
16
|
+
const GIGYA_BASE = 'https://cdc.accounts.home.id';
|
|
17
|
+
const OTP_SEND_ENDPOINT = '/accounts.auth.otp.email.sendCode';
|
|
18
|
+
const OTP_LOGIN_ENDPOINT = '/accounts.auth.otp.email.login';
|
|
19
|
+
const GET_IDS_ENDPOINT = '/accounts.socialize.getIDs';
|
|
16
20
|
const API_BASE = 'https://prod.eu-da.iot.versuni.com/api';
|
|
17
21
|
const USER_AGENT = 'okhttp/4.12.0 (Android 14; Pixel 7)';
|
|
18
22
|
const SCOPE =
|
|
19
23
|
'openid email profile DI.Account.read DI.Account.write DI.AccountProfile.read DI.AccountProfile.write DI.AccountGeneralConsent.read DI.AccountGeneralConsent.write DI.GeneralConsent.read subscriptions profile_extended consents DI.AccountSubscription.read DI.AccountSubscription.write';
|
|
24
|
+
const DEBUG_AUTH = process.env.PHILIPS_AIRPLUS_DEBUG === '1';
|
|
20
25
|
|
|
21
26
|
class AirPlusSetupServer extends HomebridgePluginUiServer {
|
|
22
27
|
constructor() {
|
|
23
28
|
super();
|
|
24
29
|
this._pkce = null;
|
|
30
|
+
this._otp = null;
|
|
25
31
|
this._tokens = null;
|
|
26
32
|
this.onRequest('/auth/init', this.handleInit.bind(this));
|
|
27
33
|
this.onRequest('/auth/exchange', this.handleExchange.bind(this));
|
|
34
|
+
this.onRequest('/auth/otp/send', this.handleOtpSend.bind(this));
|
|
35
|
+
this.onRequest('/auth/otp/verify', this.handleOtpVerify.bind(this));
|
|
28
36
|
this.onRequest('/auth/save', this.handleSave.bind(this));
|
|
29
37
|
this.ready();
|
|
30
38
|
}
|
|
31
39
|
|
|
32
40
|
async handleInit() {
|
|
33
|
-
const verifier =
|
|
34
|
-
const challenge = crypto.createHash('sha256').update(verifier).digest('base64url');
|
|
35
|
-
const state = crypto.randomBytes(16).toString('hex');
|
|
41
|
+
const { verifier, challenge, state } = this._createPkce();
|
|
36
42
|
|
|
37
43
|
this._pkce = { verifier, state };
|
|
38
44
|
|
|
39
|
-
const
|
|
40
|
-
response_type: 'code',
|
|
41
|
-
client_id: CLIENT_ID,
|
|
42
|
-
redirect_uri: REDIRECT_URI,
|
|
43
|
-
code_challenge: challenge,
|
|
44
|
-
code_challenge_method: 'S256',
|
|
45
|
-
state,
|
|
46
|
-
scope: SCOPE,
|
|
47
|
-
});
|
|
48
|
-
|
|
49
|
-
const authUrl = AUTHORIZE_ENDPOINT + '?' + params.toString();
|
|
45
|
+
const authUrl = AUTHORIZE_ENDPOINT + '?' + this._buildAuthorizeParams(challenge, state).toString();
|
|
50
46
|
return { url: authUrl };
|
|
51
47
|
}
|
|
52
48
|
|
|
@@ -59,11 +55,16 @@ class AirPlusSetupServer extends HomebridgePluginUiServer {
|
|
|
59
55
|
throw new Error('Redirect URL is required');
|
|
60
56
|
}
|
|
61
57
|
|
|
62
|
-
|
|
58
|
+
// The authorisation code lives in the URL the user copied — whether that is the
|
|
59
|
+
// com.philips.air:// deep link or the accounts.home.id consent/proxy page that
|
|
60
|
+
// many desktop browsers land on instead. Parse it directly (query → fragment →
|
|
61
|
+
// regex), mirroring scripts/airplus_setup.py.
|
|
62
|
+
let code = this._extractCode(redirectUrl);
|
|
63
63
|
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
64
|
+
// Last resort: the user pasted a Philips consent page that did not carry the
|
|
65
|
+
// code in its own URL. Fetch it and scan for an embedded deep link. This only
|
|
66
|
+
// works if the page is reachable unauthenticated, so treat failure as benign.
|
|
67
|
+
if (!code && redirectUrl.includes('accounts.home.id')) {
|
|
67
68
|
try {
|
|
68
69
|
const proxyUrl = new URL(redirectUrl);
|
|
69
70
|
const html = await this._httpsGetRaw({
|
|
@@ -74,34 +75,178 @@ class AirPlusSetupServer extends HomebridgePluginUiServer {
|
|
|
74
75
|
const m = html.match(/com\.philips\.air:\/\/loginredirect[^\s"'\\]*code=([^&\s"'\\]+)/);
|
|
75
76
|
if (m) code = decodeURIComponent(m[1]);
|
|
76
77
|
} catch (_) { /* fall through to descriptive error */ }
|
|
78
|
+
}
|
|
77
79
|
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
80
|
+
if (!code) {
|
|
81
|
+
throw new Error(
|
|
82
|
+
'No authorisation code found in that URL. After approving access, copy the ' +
|
|
83
|
+
'full URL from your browser’s address bar and paste it here — it will start ' +
|
|
84
|
+
'with either "com.philips.air://loginredirect?code=…" or an "accounts.home.id" ' +
|
|
85
|
+
'address containing "code=…". If you only see a Philips confirmation page with ' +
|
|
86
|
+
'no "code=" in its address, log in again and copy the URL the moment the page ' +
|
|
87
|
+
'finishes loading.'
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
return this._exchangeCodeAndListDevices(code, this._pkce.verifier);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
async handleOtpSend(payload = {}) {
|
|
95
|
+
const email = String(payload.email || '').trim();
|
|
96
|
+
if (!email) {
|
|
97
|
+
throw new Error('Email address is required');
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const response = await this._gigyaPostJson(OTP_SEND_ENDPOINT, new URLSearchParams({
|
|
101
|
+
apiKey: TENANT,
|
|
102
|
+
email,
|
|
103
|
+
format: 'json',
|
|
104
|
+
}), 'OTP send');
|
|
105
|
+
|
|
106
|
+
const vToken = response.vToken;
|
|
107
|
+
if (!vToken) {
|
|
108
|
+
throw new Error('OTP send did not return a verification token');
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
this._otp = { email, vToken, createdAt: Date.now() };
|
|
112
|
+
return { sent: true };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async handleOtpVerify(payload = {}) {
|
|
116
|
+
const code = String(payload.code || '').trim();
|
|
117
|
+
if (!this._otp || !this._otp.email || !this._otp.vToken) {
|
|
118
|
+
throw new Error('Verification flow has not been initialised. Send a code first.');
|
|
119
|
+
}
|
|
120
|
+
if (!code) {
|
|
121
|
+
throw new Error('Verification code is required');
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const loginResponse = await this._gigyaPostJson(OTP_LOGIN_ENDPOINT, new URLSearchParams({
|
|
125
|
+
apiKey: TENANT,
|
|
126
|
+
email: this._otp.email,
|
|
127
|
+
code,
|
|
128
|
+
vToken: this._otp.vToken,
|
|
129
|
+
format: 'json',
|
|
130
|
+
}), 'OTP verify');
|
|
131
|
+
|
|
132
|
+
const loginToken = loginResponse.sessionInfo && loginResponse.sessionInfo.cookieValue;
|
|
133
|
+
if (!loginToken) {
|
|
134
|
+
throw new Error('OTP verification succeeded but no login token was returned');
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const { verifier, challenge, state } = this._createPkce();
|
|
138
|
+
const authUrl = new URL(AUTHORIZE_ENDPOINT);
|
|
139
|
+
authUrl.search = this._buildAuthorizeParams(challenge, state, { prompt: 'none' }).toString();
|
|
140
|
+
const authLocation = await this._getRedirectLocation(authUrl, 'OIDC authorise');
|
|
141
|
+
const context = this._readUrlParam(authLocation, 'context', AUTHORIZE_ENDPOINT);
|
|
142
|
+
if (!context) {
|
|
143
|
+
throw new Error('OIDC authorise did not return a continuation context');
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const idsResponse = await this._gigyaPostJson(GET_IDS_ENDPOINT, new URLSearchParams({
|
|
147
|
+
APIKey: TENANT,
|
|
148
|
+
includeTicket: 'true',
|
|
149
|
+
format: 'json',
|
|
150
|
+
}), 'Gigya getIDs');
|
|
151
|
+
const gmidTicket = idsResponse.gmidTicket;
|
|
152
|
+
if (!gmidTicket) {
|
|
153
|
+
throw new Error('Gigya getIDs did not return gmidTicket');
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const continueUrl = new URL(authLocation, AUTHORIZE_ENDPOINT);
|
|
157
|
+
continueUrl.searchParams.set('context', context);
|
|
158
|
+
continueUrl.searchParams.set('login_token', loginToken);
|
|
159
|
+
continueUrl.searchParams.set('gmidTicket', gmidTicket);
|
|
160
|
+
continueUrl.searchParams.set('client_id', CLIENT_ID);
|
|
161
|
+
const appRedirect = await this._getRedirectLocation(continueUrl, 'OIDC continue');
|
|
162
|
+
const authCode = this._extractCode(appRedirect);
|
|
163
|
+
if (!authCode) {
|
|
164
|
+
throw new Error('OIDC continue did not return an Air+ authorisation code');
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
this._pkce = { verifier, state };
|
|
168
|
+
const result = await this._exchangeCodeAndListDevices(authCode, verifier);
|
|
169
|
+
this._otp = null;
|
|
170
|
+
return result;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
async handleSave(payload = {}) {
|
|
174
|
+
const { uuid, name } = payload;
|
|
175
|
+
if (!uuid) {
|
|
176
|
+
throw new Error('Device UUID is required');
|
|
177
|
+
}
|
|
178
|
+
if (!this._tokens) {
|
|
179
|
+
throw new Error('No Air+ token is available. Complete the login flow first.');
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const tokenPath = path.join(os.homedir(), '.homebridge', 'philips-airplus-' + uuid + '.json');
|
|
183
|
+
const { access_token, refresh_token, expires_in } = this._tokens;
|
|
184
|
+
const tokenData = {
|
|
185
|
+
access_token,
|
|
186
|
+
refresh_token,
|
|
187
|
+
client_id: CLIENT_ID,
|
|
188
|
+
expires_at: Date.now() / 1000 + expires_in,
|
|
189
|
+
};
|
|
190
|
+
|
|
191
|
+
const tmp = tokenPath + '.tmp';
|
|
192
|
+
fs.mkdirSync(path.dirname(tokenPath), { recursive: true });
|
|
193
|
+
fs.writeFileSync(tmp, JSON.stringify(tokenData, null, 2), { encoding: 'utf8', mode: 0o600 });
|
|
194
|
+
fs.chmodSync(tmp, 0o600);
|
|
195
|
+
fs.renameSync(tmp, tokenPath);
|
|
196
|
+
fs.chmodSync(tokenPath, 0o600);
|
|
197
|
+
|
|
198
|
+
return { success: true, uuid, name: name || 'Philips Air Purifier', tokenFile: tokenPath };
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
_extractCode(redirectUrl) {
|
|
202
|
+
const trimmed = String(redirectUrl || '').trim();
|
|
203
|
+
if (!trimmed) return null;
|
|
204
|
+
|
|
205
|
+
// Normalise the custom scheme so the URL parser accepts it.
|
|
206
|
+
const normalised = trimmed.replace(/^com\.philips\.air:\/\//i, 'https://airplus.local/');
|
|
207
|
+
let parsed = null;
|
|
208
|
+
try { parsed = new URL(normalised); } catch (_) { parsed = null; }
|
|
209
|
+
|
|
210
|
+
if (parsed) {
|
|
211
|
+
const fromQuery = parsed.searchParams.get('code');
|
|
212
|
+
if (fromQuery) return fromQuery;
|
|
213
|
+
// OIDC may return the response in the URL fragment (#code=…&state=…).
|
|
214
|
+
if (parsed.hash && parsed.hash.length > 1) {
|
|
215
|
+
const fromFragment = new URLSearchParams(parsed.hash.slice(1)).get('code');
|
|
216
|
+
if (fromFragment) return fromFragment;
|
|
98
217
|
}
|
|
99
218
|
}
|
|
100
219
|
|
|
220
|
+
// Fallback for unusual encodings the URL parser may not split cleanly.
|
|
221
|
+
const m = trimmed.match(/[?&#]code=([^&\s"'\\]+)/);
|
|
222
|
+
return m ? decodeURIComponent(m[1]) : null;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
_createPkce() {
|
|
226
|
+
const verifier = crypto.randomBytes(48).toString('base64url');
|
|
227
|
+
const challenge = crypto.createHash('sha256').update(verifier).digest('base64url');
|
|
228
|
+
const state = crypto.randomBytes(16).toString('hex');
|
|
229
|
+
return { verifier, challenge, state };
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
_buildAuthorizeParams(challenge, state, extra = {}) {
|
|
233
|
+
return new URLSearchParams({
|
|
234
|
+
response_type: 'code',
|
|
235
|
+
client_id: CLIENT_ID,
|
|
236
|
+
redirect_uri: REDIRECT_URI,
|
|
237
|
+
code_challenge: challenge,
|
|
238
|
+
code_challenge_method: 'S256',
|
|
239
|
+
state,
|
|
240
|
+
scope: SCOPE,
|
|
241
|
+
...extra,
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
async _exchangeCodeAndListDevices(code, verifier) {
|
|
101
246
|
const tokenBody = new URLSearchParams({
|
|
102
247
|
grant_type: 'authorization_code',
|
|
103
248
|
code,
|
|
104
|
-
code_verifier:
|
|
249
|
+
code_verifier: verifier,
|
|
105
250
|
client_id: CLIENT_ID,
|
|
106
251
|
redirect_uri: REDIRECT_URI,
|
|
107
252
|
});
|
|
@@ -122,7 +267,7 @@ class AirPlusSetupServer extends HomebridgePluginUiServer {
|
|
|
122
267
|
|
|
123
268
|
const { access_token, refresh_token, expires_in } = tokenResponse;
|
|
124
269
|
this._tokens = { access_token, refresh_token, expires_in };
|
|
125
|
-
console.log('tokens received');
|
|
270
|
+
console.log('Air+ tokens received');
|
|
126
271
|
|
|
127
272
|
const deviceUrl = new URL(API_BASE + '/da/user/self/device');
|
|
128
273
|
const deviceResponse = await this._httpsRequest({
|
|
@@ -155,32 +300,111 @@ class AirPlusSetupServer extends HomebridgePluginUiServer {
|
|
|
155
300
|
return { devices };
|
|
156
301
|
}
|
|
157
302
|
|
|
158
|
-
async
|
|
159
|
-
const
|
|
160
|
-
|
|
161
|
-
|
|
303
|
+
async _gigyaPostJson(pathname, formBody, label) {
|
|
304
|
+
const raw = await this._httpsRaw({
|
|
305
|
+
hostname: new URL(GIGYA_BASE).hostname,
|
|
306
|
+
path: pathname,
|
|
307
|
+
method: 'POST',
|
|
308
|
+
headers: {
|
|
309
|
+
'Content-Type': 'application/x-www-form-urlencoded',
|
|
310
|
+
'User-Agent': USER_AGENT,
|
|
311
|
+
Accept: 'application/json',
|
|
312
|
+
},
|
|
313
|
+
}, formBody.toString());
|
|
314
|
+
|
|
315
|
+
let parsed;
|
|
316
|
+
try {
|
|
317
|
+
parsed = raw.body ? JSON.parse(raw.body) : {};
|
|
318
|
+
} catch (_e) {
|
|
319
|
+
throw new Error(label + ' returned invalid JSON: ' + raw.body.slice(0, 200));
|
|
162
320
|
}
|
|
163
|
-
|
|
164
|
-
|
|
321
|
+
|
|
322
|
+
if (raw.status < 200 || raw.status >= 300) {
|
|
323
|
+
throw new Error(label + ' failed (HTTP ' + raw.status + '): ' + raw.body);
|
|
165
324
|
}
|
|
325
|
+
if (parsed.errorCode != null && Number(parsed.errorCode) !== 0) {
|
|
326
|
+
throw new Error(label + ' failed: ' + (parsed.errorMessage || parsed.errorDetails || parsed.errorCode));
|
|
327
|
+
}
|
|
328
|
+
return parsed;
|
|
329
|
+
}
|
|
166
330
|
|
|
167
|
-
|
|
168
|
-
const
|
|
169
|
-
const
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
331
|
+
async _getRedirectLocation(url, label) {
|
|
332
|
+
const target = new URL(url);
|
|
333
|
+
const raw = await this._httpsRaw({
|
|
334
|
+
hostname: target.hostname,
|
|
335
|
+
path: target.pathname + target.search,
|
|
336
|
+
method: 'GET',
|
|
337
|
+
headers: {
|
|
338
|
+
'User-Agent': USER_AGENT,
|
|
339
|
+
Accept: '*/*',
|
|
340
|
+
},
|
|
341
|
+
});
|
|
342
|
+
const location = raw.headers.location;
|
|
343
|
+
this._debugLocation(label, raw.status, location);
|
|
344
|
+
if (!location || raw.status < 300 || raw.status >= 400) {
|
|
345
|
+
throw new Error(label + ' did not return an HTTP redirect');
|
|
346
|
+
}
|
|
347
|
+
return location;
|
|
348
|
+
}
|
|
175
349
|
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
350
|
+
_readUrlParam(value, param, baseUrl) {
|
|
351
|
+
try {
|
|
352
|
+
const parsed = new URL(value, baseUrl);
|
|
353
|
+
const fromQuery = parsed.searchParams.get(param);
|
|
354
|
+
if (fromQuery) return fromQuery;
|
|
355
|
+
if (parsed.hash && parsed.hash.length > 1) {
|
|
356
|
+
return new URLSearchParams(parsed.hash.slice(1)).get(param);
|
|
357
|
+
}
|
|
358
|
+
} catch (_e) {
|
|
359
|
+
// Fall through to regex for custom schemes and malformed relative URLs.
|
|
360
|
+
}
|
|
361
|
+
const match = String(value || '').match(new RegExp('[?&#]' + param + '=([^&\\s"\'\\\\]+)'));
|
|
362
|
+
return match ? decodeURIComponent(match[1]) : null;
|
|
363
|
+
}
|
|
182
364
|
|
|
183
|
-
|
|
365
|
+
_debugLocation(label, status, location) {
|
|
366
|
+
if (!DEBUG_AUTH) return;
|
|
367
|
+
let safeLocation = location || '';
|
|
368
|
+
try {
|
|
369
|
+
const parsed = new URL(location, AUTHORIZE_ENDPOINT);
|
|
370
|
+
for (const key of ['code', 'context', 'login_token', 'gmidTicket']) {
|
|
371
|
+
if (parsed.searchParams.has(key)) parsed.searchParams.set(key, '[redacted]');
|
|
372
|
+
}
|
|
373
|
+
if (parsed.hash && parsed.hash.length > 1) {
|
|
374
|
+
const hash = new URLSearchParams(parsed.hash.slice(1));
|
|
375
|
+
for (const key of ['code', 'context', 'login_token', 'gmidTicket']) {
|
|
376
|
+
if (hash.has(key)) hash.set(key, '[redacted]');
|
|
377
|
+
}
|
|
378
|
+
parsed.hash = hash.toString();
|
|
379
|
+
}
|
|
380
|
+
safeLocation = parsed.toString();
|
|
381
|
+
} catch (_e) {
|
|
382
|
+
safeLocation = String(location || '').replace(/(code|context|login_token|gmidTicket)=([^&\s]+)/g, '$1=[redacted]');
|
|
383
|
+
}
|
|
384
|
+
console.log('[Air+ auth debug] ' + label + ' HTTP ' + status + ' Location: ' + safeLocation);
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
_httpsRaw(options, postBody) {
|
|
388
|
+
return new Promise((resolve, reject) => {
|
|
389
|
+
const req = https.request(options, (res) => {
|
|
390
|
+
const chunks = [];
|
|
391
|
+
res.on('data', (chunk) => chunks.push(chunk));
|
|
392
|
+
res.on('end', () => {
|
|
393
|
+
resolve({
|
|
394
|
+
status: res.statusCode,
|
|
395
|
+
headers: res.headers,
|
|
396
|
+
body: Buffer.concat(chunks).toString('utf8'),
|
|
397
|
+
});
|
|
398
|
+
});
|
|
399
|
+
});
|
|
400
|
+
|
|
401
|
+
req.on('error', reject);
|
|
402
|
+
|
|
403
|
+
if (postBody) {
|
|
404
|
+
req.write(postBody);
|
|
405
|
+
}
|
|
406
|
+
req.end();
|
|
407
|
+
});
|
|
184
408
|
}
|
|
185
409
|
|
|
186
410
|
_httpsRequest(options, postBody) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "homebridge-philips-air-purifier-complete",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.3.0",
|
|
4
4
|
"customUi": true,
|
|
5
5
|
"description": "Homebridge plugin for Philips Air Purifier with bundled CoAP control library and Python 3.12+/Node.js 24 support",
|
|
6
6
|
"main": "index.js",
|
package/scripts/airplus_setup.py
CHANGED
|
@@ -11,6 +11,7 @@ Usage:
|
|
|
11
11
|
No external deps required — stdlib only.
|
|
12
12
|
"""
|
|
13
13
|
|
|
14
|
+
import argparse
|
|
14
15
|
import base64
|
|
15
16
|
import hashlib
|
|
16
17
|
import json
|
|
@@ -40,6 +41,10 @@ SCOPES = (
|
|
|
40
41
|
|
|
41
42
|
TOKEN_ENDPOINT = f"{OIDC_ISSUER}/{TENANT}/token"
|
|
42
43
|
AUTHORIZE_ENDPOINT = f"{OIDC_ISSUER}/{TENANT}/authorize"
|
|
44
|
+
CDC_BASE = "https://cdc.accounts.home.id"
|
|
45
|
+
OTP_SEND_ENDPOINT = f"{CDC_BASE}/accounts.auth.otp.email.sendCode"
|
|
46
|
+
OTP_LOGIN_ENDPOINT = f"{CDC_BASE}/accounts.auth.otp.email.login"
|
|
47
|
+
GET_IDS_ENDPOINT = f"{CDC_BASE}/accounts.socialize.getIDs"
|
|
43
48
|
|
|
44
49
|
API_BASE = "https://prod.eu-da.iot.versuni.com/api"
|
|
45
50
|
USER_AGENT = "okhttp/4.12.0 (Android 14; Pixel 7)"
|
|
@@ -53,7 +58,7 @@ def _pkce_pair() -> tuple[str, str]:
|
|
|
53
58
|
return code_verifier, code_challenge
|
|
54
59
|
|
|
55
60
|
|
|
56
|
-
def _build_authorize_url(code_challenge: str, state: str) -> str:
|
|
61
|
+
def _build_authorize_url(code_challenge: str, state: str, prompt: str | None = None) -> str:
|
|
57
62
|
params = {
|
|
58
63
|
"response_type": "code",
|
|
59
64
|
"client_id": CLIENT_ID,
|
|
@@ -63,6 +68,8 @@ def _build_authorize_url(code_challenge: str, state: str) -> str:
|
|
|
63
68
|
"code_challenge_method": "S256",
|
|
64
69
|
"state": state,
|
|
65
70
|
}
|
|
71
|
+
if prompt:
|
|
72
|
+
params["prompt"] = prompt
|
|
66
73
|
return f"{AUTHORIZE_ENDPOINT}?{urllib.parse.urlencode(params)}"
|
|
67
74
|
|
|
68
75
|
|
|
@@ -110,6 +117,152 @@ def _api_get(path: str, access_token: str) -> dict:
|
|
|
110
117
|
raise RuntimeError(f"API GET {path} failed (HTTP {e.code}): {body}") from e
|
|
111
118
|
|
|
112
119
|
|
|
120
|
+
class _NoRedirectHandler(urllib.request.HTTPRedirectHandler):
|
|
121
|
+
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
|
122
|
+
return None
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _open_no_redirect(req: urllib.request.Request) -> tuple[int, dict, bytes]:
|
|
126
|
+
opener = urllib.request.build_opener(_NoRedirectHandler)
|
|
127
|
+
try:
|
|
128
|
+
with opener.open(req, timeout=15) as r:
|
|
129
|
+
return r.status, dict(r.headers), r.read()
|
|
130
|
+
except urllib.error.HTTPError as e:
|
|
131
|
+
body = e.read()
|
|
132
|
+
if 300 <= e.code < 400:
|
|
133
|
+
return e.code, dict(e.headers), body
|
|
134
|
+
raise
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _post_form_json(url: str, data: dict, label: str) -> dict:
|
|
138
|
+
encoded = urllib.parse.urlencode(data).encode()
|
|
139
|
+
req = urllib.request.Request(
|
|
140
|
+
url,
|
|
141
|
+
data=encoded,
|
|
142
|
+
headers={
|
|
143
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
144
|
+
"User-Agent": USER_AGENT,
|
|
145
|
+
"Accept": "application/json",
|
|
146
|
+
},
|
|
147
|
+
method="POST",
|
|
148
|
+
)
|
|
149
|
+
try:
|
|
150
|
+
status, _headers, body = _open_no_redirect(req)
|
|
151
|
+
except urllib.error.HTTPError as e:
|
|
152
|
+
body = e.read().decode(errors="replace")
|
|
153
|
+
raise RuntimeError(f"{label} failed (HTTP {e.code}): {body}") from e
|
|
154
|
+
|
|
155
|
+
text = body.decode(errors="replace")
|
|
156
|
+
if status < 200 or status >= 300:
|
|
157
|
+
raise RuntimeError(f"{label} failed (HTTP {status}): {text}")
|
|
158
|
+
try:
|
|
159
|
+
parsed = json.loads(text or "{}")
|
|
160
|
+
except json.JSONDecodeError as e:
|
|
161
|
+
raise RuntimeError(f"{label} returned invalid JSON: {text[:200]}") from e
|
|
162
|
+
error_code = parsed.get("errorCode")
|
|
163
|
+
try:
|
|
164
|
+
failed = error_code is not None and int(error_code) != 0
|
|
165
|
+
except (TypeError, ValueError):
|
|
166
|
+
failed = error_code is not None
|
|
167
|
+
if failed:
|
|
168
|
+
msg = parsed.get("errorMessage") or parsed.get("errorDetails") or parsed.get("errorCode")
|
|
169
|
+
raise RuntimeError(f"{label} failed: {msg}")
|
|
170
|
+
return parsed
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _get_redirect_location(url: str, label: str) -> str:
|
|
174
|
+
req = urllib.request.Request(
|
|
175
|
+
url,
|
|
176
|
+
headers={
|
|
177
|
+
"User-Agent": USER_AGENT,
|
|
178
|
+
"Accept": "*/*",
|
|
179
|
+
},
|
|
180
|
+
)
|
|
181
|
+
try:
|
|
182
|
+
status, headers, _body = _open_no_redirect(req)
|
|
183
|
+
except urllib.error.HTTPError as e:
|
|
184
|
+
body = e.read().decode(errors="replace")
|
|
185
|
+
raise RuntimeError(f"{label} failed (HTTP {e.code}): {body}") from e
|
|
186
|
+
|
|
187
|
+
location = headers.get("Location") or headers.get("location")
|
|
188
|
+
if not location or status < 300 or status >= 400:
|
|
189
|
+
raise RuntimeError(f"{label} did not return an HTTP redirect")
|
|
190
|
+
print(f"{label}: HTTP {status} redirect with parameters: {_describe_location(location)}")
|
|
191
|
+
return location
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _describe_location(location: str) -> str:
|
|
195
|
+
"""Describe redirect parameters without printing auth codes or login tickets."""
|
|
196
|
+
try:
|
|
197
|
+
parsed = urllib.parse.urlparse(location)
|
|
198
|
+
params = urllib.parse.parse_qs(parsed.query or parsed.fragment)
|
|
199
|
+
names = ", ".join(sorted(params)) or "none"
|
|
200
|
+
path = parsed.path or parsed.netloc or parsed.scheme
|
|
201
|
+
return f"{path} ({names})"
|
|
202
|
+
except Exception:
|
|
203
|
+
return "(unparseable redirect)"
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _read_url_param(value: str, param: str) -> str:
|
|
207
|
+
parsed = urllib.parse.urlparse(value)
|
|
208
|
+
params = urllib.parse.parse_qs(parsed.query or parsed.fragment)
|
|
209
|
+
if params.get(param):
|
|
210
|
+
return params[param][0]
|
|
211
|
+
match = re.search(r"[?&#]" + re.escape(param) + r"=([^&\s\"'\\]+)", value)
|
|
212
|
+
return urllib.parse.unquote(match.group(1)) if match else ""
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _send_otp(email: str) -> str:
|
|
216
|
+
response = _post_form_json(
|
|
217
|
+
OTP_SEND_ENDPOINT,
|
|
218
|
+
{
|
|
219
|
+
"apiKey": TENANT,
|
|
220
|
+
"email": email,
|
|
221
|
+
"format": "json",
|
|
222
|
+
},
|
|
223
|
+
"OTP send",
|
|
224
|
+
)
|
|
225
|
+
v_token = response.get("vToken")
|
|
226
|
+
if not v_token:
|
|
227
|
+
raise RuntimeError("OTP send did not return a verification token.")
|
|
228
|
+
return v_token
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _verify_otp(email: str, code: str, v_token: str) -> str:
|
|
232
|
+
response = _post_form_json(
|
|
233
|
+
OTP_LOGIN_ENDPOINT,
|
|
234
|
+
{
|
|
235
|
+
"apiKey": TENANT,
|
|
236
|
+
"email": email,
|
|
237
|
+
"code": code,
|
|
238
|
+
"vToken": v_token,
|
|
239
|
+
"format": "json",
|
|
240
|
+
},
|
|
241
|
+
"OTP verify",
|
|
242
|
+
)
|
|
243
|
+
session_info = response.get("sessionInfo") or {}
|
|
244
|
+
login_token = session_info.get("cookieValue")
|
|
245
|
+
if not login_token:
|
|
246
|
+
raise RuntimeError("OTP verification succeeded but no login token was returned.")
|
|
247
|
+
return login_token
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _get_gmid_ticket() -> str:
|
|
251
|
+
response = _post_form_json(
|
|
252
|
+
GET_IDS_ENDPOINT,
|
|
253
|
+
{
|
|
254
|
+
"APIKey": TENANT,
|
|
255
|
+
"includeTicket": "true",
|
|
256
|
+
"format": "json",
|
|
257
|
+
},
|
|
258
|
+
"Gigya getIDs",
|
|
259
|
+
)
|
|
260
|
+
gmid_ticket = response.get("gmidTicket")
|
|
261
|
+
if not gmid_ticket:
|
|
262
|
+
raise RuntimeError("Gigya getIDs did not return gmidTicket.")
|
|
263
|
+
return gmid_ticket
|
|
264
|
+
|
|
265
|
+
|
|
113
266
|
def _save_tokens(uuid: str, access_token: str, refresh_token: str, expires_at: float) -> str:
|
|
114
267
|
"""Save token file to ~/.homebridge/philips-airplus-{uuid}.json with 0o600 permissions."""
|
|
115
268
|
homebridge_dir = os.path.join(os.path.expanduser("~"), ".homebridge")
|
|
@@ -161,15 +314,11 @@ def _print_devices(devices: list) -> None:
|
|
|
161
314
|
print(f" {i:<4} {name:<30} {uuid:<40} {model}")
|
|
162
315
|
|
|
163
316
|
|
|
164
|
-
def
|
|
165
|
-
|
|
166
|
-
print("=" * 40)
|
|
167
|
-
|
|
168
|
-
# Step 1: Generate PKCE pair + state
|
|
317
|
+
def _browser_login() -> dict:
|
|
318
|
+
"""Run the fallback browser redirect-copy flow and return the token response."""
|
|
169
319
|
code_verifier, code_challenge = _pkce_pair()
|
|
170
320
|
state = secrets.token_urlsafe(16)
|
|
171
321
|
|
|
172
|
-
# Step 2: Build and print the authorize URL
|
|
173
322
|
auth_url = _build_authorize_url(code_challenge, state)
|
|
174
323
|
print("\nStep 1: Open this URL in your browser and log in to your Philips account:")
|
|
175
324
|
print(f"\n {auth_url}\n")
|
|
@@ -181,27 +330,75 @@ def main() -> int:
|
|
|
181
330
|
print()
|
|
182
331
|
redirect_url = input("Paste the full redirect URL here: ").strip()
|
|
183
332
|
if not redirect_url:
|
|
184
|
-
|
|
185
|
-
return 1
|
|
333
|
+
raise RuntimeError("No URL provided.")
|
|
186
334
|
|
|
187
335
|
# Step 4: Extract the authorisation code
|
|
188
|
-
|
|
189
|
-
code, returned_state = _extract_code_from_redirect(redirect_url)
|
|
190
|
-
except ValueError as e:
|
|
191
|
-
print(f"ERROR: {e}", file=sys.stderr)
|
|
192
|
-
return 1
|
|
336
|
+
code, returned_state = _extract_code_from_redirect(redirect_url)
|
|
193
337
|
|
|
194
338
|
if returned_state and returned_state != state:
|
|
195
339
|
print("WARNING: state mismatch — possible CSRF. Proceeding anyway.", file=sys.stderr)
|
|
196
340
|
|
|
197
|
-
# Step 5: Exchange code for tokens
|
|
198
341
|
print("\nExchanging authorisation code for tokens...")
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
342
|
+
return _exchange_code(code, code_verifier)
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def _otp_login() -> dict:
|
|
346
|
+
"""Run the default email + verification code flow and return the token response."""
|
|
347
|
+
email = input("\nPhilips account email: ").strip()
|
|
348
|
+
if not email:
|
|
349
|
+
raise RuntimeError("No email address provided.")
|
|
350
|
+
|
|
351
|
+
print("Sending verification code...")
|
|
352
|
+
v_token = _send_otp(email)
|
|
353
|
+
print("Verification code sent. Check your Philips account email.")
|
|
354
|
+
|
|
355
|
+
code = input("Verification code: ").strip()
|
|
356
|
+
if not code:
|
|
357
|
+
raise RuntimeError("No verification code provided.")
|
|
204
358
|
|
|
359
|
+
print("Verifying code...")
|
|
360
|
+
login_token = _verify_otp(email, code, v_token)
|
|
361
|
+
|
|
362
|
+
code_verifier, code_challenge = _pkce_pair()
|
|
363
|
+
state = secrets.token_urlsafe(16)
|
|
364
|
+
auth_url = _build_authorize_url(code_challenge, state, prompt="none")
|
|
365
|
+
auth_location = _get_redirect_location(auth_url, "OIDC authorise")
|
|
366
|
+
context = _read_url_param(auth_location, "context")
|
|
367
|
+
if not context:
|
|
368
|
+
raise RuntimeError("OIDC authorise did not return a continuation context.")
|
|
369
|
+
|
|
370
|
+
gmid_ticket = _get_gmid_ticket()
|
|
371
|
+
continue_params = urllib.parse.urlencode({
|
|
372
|
+
"context": context,
|
|
373
|
+
"login_token": login_token,
|
|
374
|
+
"gmidTicket": gmid_ticket,
|
|
375
|
+
"client_id": CLIENT_ID,
|
|
376
|
+
})
|
|
377
|
+
continue_url = f"{AUTHORIZE_ENDPOINT}/continue?{continue_params}"
|
|
378
|
+
app_redirect = _get_redirect_location(continue_url, "OIDC continue")
|
|
379
|
+
auth_code, _returned_state = _extract_code_from_redirect(app_redirect)
|
|
380
|
+
|
|
381
|
+
print("\nExchanging authorisation code for tokens...")
|
|
382
|
+
return _exchange_code(auth_code, code_verifier)
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def _devices_from_response(devices_resp) -> list:
|
|
386
|
+
if isinstance(devices_resp, list):
|
|
387
|
+
return devices_resp
|
|
388
|
+
if isinstance(devices_resp, dict):
|
|
389
|
+
data = devices_resp.get("data")
|
|
390
|
+
if isinstance(data, dict):
|
|
391
|
+
data = data.get("items")
|
|
392
|
+
return (
|
|
393
|
+
devices_resp.get("devices")
|
|
394
|
+
or data
|
|
395
|
+
or devices_resp.get("items")
|
|
396
|
+
or []
|
|
397
|
+
)
|
|
398
|
+
return []
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def _save_selected_device(token_resp: dict) -> int:
|
|
205
402
|
access_token = token_resp.get("access_token")
|
|
206
403
|
refresh_token = token_resp.get("refresh_token")
|
|
207
404
|
expires_in = token_resp.get("expires_in", 3600)
|
|
@@ -221,18 +418,7 @@ def main() -> int:
|
|
|
221
418
|
print(f"ERROR fetching devices: {e}", file=sys.stderr)
|
|
222
419
|
return 1
|
|
223
420
|
|
|
224
|
-
|
|
225
|
-
if isinstance(devices_resp, list):
|
|
226
|
-
devices = devices_resp
|
|
227
|
-
elif isinstance(devices_resp, dict):
|
|
228
|
-
devices = (
|
|
229
|
-
devices_resp.get("devices")
|
|
230
|
-
or devices_resp.get("data")
|
|
231
|
-
or devices_resp.get("items")
|
|
232
|
-
or []
|
|
233
|
-
)
|
|
234
|
-
else:
|
|
235
|
-
devices = []
|
|
421
|
+
devices = _devices_from_response(devices_resp)
|
|
236
422
|
|
|
237
423
|
if not devices:
|
|
238
424
|
print("WARNING: No devices found in your account.")
|
|
@@ -290,5 +476,28 @@ def main() -> int:
|
|
|
290
476
|
return 0
|
|
291
477
|
|
|
292
478
|
|
|
479
|
+
def main() -> int:
|
|
480
|
+
parser = argparse.ArgumentParser(
|
|
481
|
+
description="One-time Philips Air+ setup for Homebridge."
|
|
482
|
+
)
|
|
483
|
+
parser.add_argument(
|
|
484
|
+
"--browser",
|
|
485
|
+
action="store_true",
|
|
486
|
+
help="Use the legacy browser redirect-copy flow instead of email verification code.",
|
|
487
|
+
)
|
|
488
|
+
args = parser.parse_args()
|
|
489
|
+
|
|
490
|
+
print("Philips Air+ Setup")
|
|
491
|
+
print("=" * 40)
|
|
492
|
+
|
|
493
|
+
try:
|
|
494
|
+
token_resp = _browser_login() if args.browser else _otp_login()
|
|
495
|
+
except (RuntimeError, ValueError) as e:
|
|
496
|
+
print(f"ERROR: {e}", file=sys.stderr)
|
|
497
|
+
return 1
|
|
498
|
+
|
|
499
|
+
return _save_selected_device(token_resp)
|
|
500
|
+
|
|
501
|
+
|
|
293
502
|
if __name__ == "__main__":
|
|
294
503
|
sys.exit(main())
|