homebridge-cync-app 0.0.2

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 (50) hide show
  1. package/.editorconfig +10 -0
  2. package/CHANGELOG.md +33 -0
  3. package/LICENSE +176 -0
  4. package/README.md +67 -0
  5. package/config.schema.json +39 -0
  6. package/dist/cync/config-client.d.ts +77 -0
  7. package/dist/cync/config-client.js +222 -0
  8. package/dist/cync/config-client.js.map +1 -0
  9. package/dist/cync/cync-client.d.ts +76 -0
  10. package/dist/cync/cync-client.js +236 -0
  11. package/dist/cync/cync-client.js.map +1 -0
  12. package/dist/cync/tcp-client.d.ts +33 -0
  13. package/dist/cync/tcp-client.js +59 -0
  14. package/dist/cync/tcp-client.js.map +1 -0
  15. package/dist/cync/token-store.d.ts +16 -0
  16. package/dist/cync/token-store.js +39 -0
  17. package/dist/cync/token-store.js.map +1 -0
  18. package/dist/cync/types.d.ts +1 -0
  19. package/dist/cync/types.js +2 -0
  20. package/dist/cync/types.js.map +1 -0
  21. package/dist/index.d.ts +7 -0
  22. package/dist/index.js +10 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/platform.d.ts +29 -0
  25. package/dist/platform.js +143 -0
  26. package/dist/platform.js.map +1 -0
  27. package/dist/platformAccessory.d.ts +13 -0
  28. package/dist/platformAccessory.js +17 -0
  29. package/dist/platformAccessory.js.map +1 -0
  30. package/dist/settings.d.ts +2 -0
  31. package/dist/settings.js +3 -0
  32. package/dist/settings.js.map +1 -0
  33. package/docs/cync-api-notes.md +168 -0
  34. package/docs/cync-client-contract.md +172 -0
  35. package/docs/cync-device-model.md +129 -0
  36. package/eslint.config.js +41 -0
  37. package/homebridge-cync-app-v0.0.1.zip +0 -0
  38. package/nodemon.json +12 -0
  39. package/package.json +56 -0
  40. package/src/@types/homebridge-lib.d.ts +14 -0
  41. package/src/cync/config-client.ts +370 -0
  42. package/src/cync/cync-client.ts +408 -0
  43. package/src/cync/tcp-client.ts +88 -0
  44. package/src/cync/token-store.ts +50 -0
  45. package/src/cync/types.ts +0 -0
  46. package/src/index.ts +12 -0
  47. package/src/platform.ts +209 -0
  48. package/src/platformAccessory.ts +18 -0
  49. package/src/settings.ts +3 -0
  50. package/tsconfig.json +24 -0
package/.editorconfig ADDED
@@ -0,0 +1,10 @@
1
+ # Root EditorConfig
2
+ root = true
3
+
4
+ [*]
5
+ indent_style = tab
6
+ indent_size = 4
7
+ end_of_line = lf
8
+ charset = utf-8
9
+ insert_final_newline = true
10
+ trim_trailing_whitespace = true
package/CHANGELOG.md ADDED
@@ -0,0 +1,33 @@
1
+ # Changelog
2
+
3
+ ## v0.0.2 – Cloud 2FA + device discovery
4
+
5
+ **Release Date:** 2025-11-23
6
+
7
+ ### Added
8
+ - Cync cloud 2FA login flow using email + password + one-time code.
9
+ - Persistent token storage and automatic session restore on Homebridge restart.
10
+ - Cloud configuration fetch via `/user/{userId}/subscribe/devices`.
11
+ - Per-mesh property probe via `/product/{productId}/device/{meshId}/property`.
12
+ - Device discovery from `bulbsArray` and mapping into Homebridge accessories.
13
+ - Accessory UUIDs seeded from mesh ID + stable device ID for consistent caching.
14
+ - Automatic accessory naming using Cync `displayName` (e.g. “Lower Outlet”, “Upper Outlet”).
15
+
16
+ ### Changed
17
+ - Replaced the previous “dummy switch” with real Cync devices from the cloud.
18
+ - Tightened logging around login, token restore, and cloud configuration loading.
19
+ - Ensured all new TypeScript code is lint-clean (`no-explicit-any`, strict typing).
20
+
21
+ ### Known limitations
22
+ - LAN / TCP control path is still stubbed: `On` characteristic logs requests but does not yet send real commands to devices.
23
+ - Only basic on/off outlets have been exercised; lights/scenes/groups are not yet modelled as HomeKit accessories.
24
+ - Token expiry / refresh is not yet implemented; a full re-login may be required if the token is revoked or expires.
25
+
26
+ ## 0.0.1 – Initial Cync scaffold
27
+ **Release Date:** 2025-11-22
28
+
29
+ ### Added
30
+ - Initial Homebridge platform plugin scaffold for controlling Cync devices via the Cync app account.
31
+ - Basic TypeScript project setup (ESLint, `tsconfig`, build scripts).
32
+ - Platform registration and minimal logging to verify plugin loads correctly in Homebridge.
33
+ - Configuration schema wiring for the Homebridge UI (basic fields for Cync account and options).
package/LICENSE ADDED
@@ -0,0 +1,176 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
package/README.md ADDED
@@ -0,0 +1,67 @@
1
+ # homebridge-cync-app
2
+ Homebridge plugin that integrates your GE Cync account (via the Cync app/API) and exposes all supported devices: plugs, lights, switches, etc.
3
+
4
+ It currently supports:
5
+
6
+ - Email + password + 2FA (one-time code) login
7
+ - Persistent token storage in the Homebridge storage path
8
+ - Discovery of Cync “meshes” and devices from the cloud
9
+ - Exposing Cync outlets as HomeKit switches with their Cync `displayName`
10
+
11
+ ## Installation
12
+
13
+ 1. Install via Homebridge UI (Plugins tab) or from the command line:
14
+
15
+ ```
16
+ npm install -g homebridge-cync-app
17
+ ```
18
+ 2. Restart Homebridge.
19
+
20
+ ## Configuration
21
+
22
+ Add a platform entry to your Homebridge `config.json`:
23
+
24
+ ```
25
+ {
26
+ "platforms": [
27
+ {
28
+ "platform": "CyncAppPlatform",
29
+ "name": "Cync App (Dev)",
30
+ "username": "you@example.com",
31
+ "password": "your-cync-password",
32
+ "twoFactor": "123456"
33
+ }
34
+ ]
35
+ }
36
+ ```
37
+ ### 2FA flow
38
+
39
+ 1. Start with no twoFactor field (or leave it empty).
40
+
41
+ 2. Start Homebridge:
42
+ - The plugin asks Cync to send a 2FA code to your email.
43
+ - In the log you’ll see:
44
+ - Cync: starting 2FA handshake for ...
45
+ - Cync: 2FA code sent to your email...
46
+
47
+ 3. Copy the code from your email.
48
+
49
+ 4. Add "twoFactor": "123456" (replace with your real code) to the plugin config and restart Homebridge.
50
+
51
+ 5. On successful login:
52
+ - The plugin stores an access token in the Homebridge storage path.
53
+ - On future restarts, it logs:
54
+ - CyncClient: using stored token for userId=...
55
+ - Cync: restored session from stored token; userId=...
56
+ - No further 2FA input is needed unless the token expires or is revoked.
57
+
58
+ ## Project Status & Roadmap
59
+ - **0.0.1** – Initial scaffold, basic Homebridge platform, config wiring, and logging.
60
+ - **0.0.2** - Cync cloud login and device list discovery.
61
+ - ✅ 2FA cloud login and token persistence
62
+ - ✅ Cloud discovery of meshes and outlets
63
+ - ✅ Basic HomeKit switch accessories with real Cync names
64
+ - **0.0.3+ (planned)** – Individual accessories for switches, plugs, and lights; per-device control.
65
+ - ⏳ TCP / LAN control path (actually turning devices on/off)
66
+ - ⏳ Support for lights, scenes, and groups
67
+ - ⏳ Token refresh / expiry handling
@@ -0,0 +1,39 @@
1
+ {
2
+ "pluginAlias": "CyncAppPlatform",
3
+ "pluginType": "platform",
4
+
5
+ "schema": {
6
+ "type": "object",
7
+ "properties": {
8
+ "name": {
9
+ "title": "Name",
10
+ "type": "string",
11
+ "default": "Cync",
12
+ "description": "Name of the platform as shown in Homebridge."
13
+ },
14
+ "username": {
15
+ "title": "Cync Email",
16
+ "type": "string",
17
+ "format": "email",
18
+ "description": "Email address you use to sign in to the Cync app."
19
+ },
20
+ "password": {
21
+ "title": "Cync Password",
22
+ "type": "string",
23
+ "format": "password",
24
+ "description": "Password for your Cync account."
25
+ },
26
+ "twoFactor": {
27
+ "title": "Two-Factor Code (OTP)",
28
+ "type": "string",
29
+ "pattern": "^[0-9]{6}$",
30
+ "description": "Temporary 6-digit code emailed by Cync when you sign in. Leave blank normally; only needed when performing a fresh login."
31
+ }
32
+ },
33
+ "required": [
34
+ "name",
35
+ "username",
36
+ "password"
37
+ ]
38
+ }
39
+ }
@@ -0,0 +1,77 @@
1
+ export interface CyncLoginSession {
2
+ accessToken: string;
3
+ userId: string;
4
+ raw: unknown;
5
+ }
6
+ export interface CyncDevice {
7
+ id: string;
8
+ name?: string;
9
+ product_id?: string;
10
+ device_id?: string;
11
+ mac?: string;
12
+ sn?: string;
13
+ [key: string]: unknown;
14
+ }
15
+ export interface CyncDeviceMesh {
16
+ id: string;
17
+ name?: string;
18
+ product_id: string;
19
+ access_key?: string;
20
+ mac?: string;
21
+ properties?: Record<string, unknown>;
22
+ devices?: CyncDevice[];
23
+ [key: string]: unknown;
24
+ }
25
+ export interface CyncCloudConfig {
26
+ meshes: CyncDeviceMesh[];
27
+ }
28
+ /**
29
+ * Very small logger interface so we can accept either the Homebridge log
30
+ * object or console.* functions in tests.
31
+ */
32
+ export interface CyncLogger {
33
+ debug(message: string, ...args: unknown[]): void;
34
+ info(message: string, ...args: unknown[]): void;
35
+ warn(message: string, ...args: unknown[]): void;
36
+ error(message: string, ...args: unknown[]): void;
37
+ }
38
+ export declare class ConfigClient {
39
+ private readonly log;
40
+ private accessToken;
41
+ private userId;
42
+ constructor(logger?: CyncLogger);
43
+ /**
44
+ * Request that Cync send a one-time 2FA verification code to the given email.
45
+ *
46
+ * This MUST be called before loginWithTwoFactor() for accounts that require 2FA.
47
+ * The user reads the code from their email and provides it to loginWithTwoFactor.
48
+ */
49
+ sendTwoFactorCode(email: string): Promise<void>;
50
+ /**
51
+ * Perform the actual 2FA login and capture the access token + userId.
52
+ *
53
+ * You are expected to first call sendTwoFactorCode(), then prompt the user
54
+ * for the emailed OTP code, then call loginWithTwoFactor() with that code.
55
+ *
56
+ * The access token is used for subsequent getCloudConfig() / getDeviceProperties() calls.
57
+ */
58
+ loginWithTwoFactor(email: string, password: string, otpCode: string): Promise<CyncLoginSession>;
59
+ /**
60
+ * Fetch the list of meshes/devices for the current user from the cloud.
61
+ *
62
+ * This roughly matches CyncCloudAPI.get_devices() from cync-lan, but in a
63
+ * simplified, single-call interface.
64
+ */
65
+ getCloudConfig(): Promise<CyncCloudConfig>;
66
+ /**
67
+ * Convenience to fetch the properties object for a single device.
68
+ */
69
+ getDeviceProperties(productId: string, deviceId: string): Promise<Record<string, unknown>>;
70
+ restoreSession(accessToken: string, userId: string): void;
71
+ getSessionSnapshot(): {
72
+ accessToken: string | null;
73
+ userId: string | null;
74
+ };
75
+ private ensureSession;
76
+ private static randomLoginResource;
77
+ }
@@ -0,0 +1,222 @@
1
+ // src/cync/config-client.ts
2
+ // Cync cloud configuration & login client.
3
+ // Handles 2FA email flow and basic device/config queries against api.gelighting.com.
4
+ //
5
+ // This is intentionally low-level and stateless-ish: CyncClient is expected to
6
+ // own an instance of this class and persist the resulting session info.
7
+ const CYNC_API_BASE = 'https://api.gelighting.com/v2/';
8
+ const CORP_ID = '1007d2ad150c4000';
9
+ const defaultLogger = {
10
+ debug: (...args) => console.debug('[cync-config]', ...args),
11
+ info: (...args) => console.info('[cync-config]', ...args),
12
+ warn: (...args) => console.warn('[cync-config]', ...args),
13
+ error: (...args) => console.error('[cync-config]', ...args),
14
+ };
15
+ export class ConfigClient {
16
+ log;
17
+ // These are populated after a successful 2FA login.
18
+ accessToken = null;
19
+ userId = null;
20
+ constructor(logger) {
21
+ this.log = logger ?? defaultLogger;
22
+ }
23
+ /**
24
+ * Request that Cync send a one-time 2FA verification code to the given email.
25
+ *
26
+ * This MUST be called before loginWithTwoFactor() for accounts that require 2FA.
27
+ * The user reads the code from their email and provides it to loginWithTwoFactor.
28
+ */
29
+ async sendTwoFactorCode(email) {
30
+ const url = `${CYNC_API_BASE}two_factor/email/verifycode`;
31
+ this.log.debug(`Requesting Cync 2FA code for ${email}…`);
32
+ const body = {
33
+ corp_id: CORP_ID,
34
+ email,
35
+ local_lang: 'en-us',
36
+ };
37
+ const res = (await fetch(url, {
38
+ method: 'POST',
39
+ headers: {
40
+ 'Content-Type': 'application/json',
41
+ },
42
+ body: JSON.stringify(body),
43
+ }));
44
+ if (!res.ok) {
45
+ const text = await res.text().catch(() => '');
46
+ this.log.error(`Cync 2FA request failed: HTTP ${res.status} ${res.statusText} ${text}`);
47
+ throw new Error(`Cync 2FA request failed with status ${res.status}`);
48
+ }
49
+ this.log.info('Cync 2FA email request succeeded.');
50
+ }
51
+ /**
52
+ * Perform the actual 2FA login and capture the access token + userId.
53
+ *
54
+ * You are expected to first call sendTwoFactorCode(), then prompt the user
55
+ * for the emailed OTP code, then call loginWithTwoFactor() with that code.
56
+ *
57
+ * The access token is used for subsequent getCloudConfig() / getDeviceProperties() calls.
58
+ */
59
+ async loginWithTwoFactor(email, password, otpCode) {
60
+ const url = `${CYNC_API_BASE}user_auth/two_factor`;
61
+ this.log.debug('Logging into Cync with 2FA for %s…', email);
62
+ const body = {
63
+ corp_id: CORP_ID,
64
+ email,
65
+ password,
66
+ two_factor: otpCode,
67
+ // Matches the reference implementations: random 16-char string.
68
+ resource: ConfigClient.randomLoginResource(),
69
+ };
70
+ const res = (await fetch(url, {
71
+ method: 'POST',
72
+ headers: {
73
+ 'Content-Type': 'application/json',
74
+ },
75
+ body: JSON.stringify(body),
76
+ }));
77
+ const json = await res.json().catch(async () => {
78
+ const text = await res.text().catch(() => '');
79
+ throw new Error(`Cync login returned non-JSON payload: ${text}`);
80
+ });
81
+ if (!res.ok) {
82
+ this.log.error('Cync login failed: HTTP %d %s %o', res.status, res.statusText, json);
83
+ const errBody = json;
84
+ throw new Error(errBody.error?.msg ??
85
+ `Cync login failed with status ${res.status} ${res.statusText}`);
86
+ }
87
+ const obj = json;
88
+ this.log.debug('Cync login response: keys=%o', Object.keys(obj));
89
+ // Accept both snake_case and camelCase, and both string/number user_id.
90
+ const accessTokenRaw = obj.access_token ?? obj.accessToken;
91
+ const userIdRaw = obj.user_id ?? obj.userId;
92
+ const accessToken = typeof accessTokenRaw === 'string' && accessTokenRaw.length > 0
93
+ ? accessTokenRaw
94
+ : undefined;
95
+ const userId = userIdRaw !== undefined && userIdRaw !== null
96
+ ? String(userIdRaw)
97
+ : undefined;
98
+ if (!accessToken || !userId) {
99
+ this.log.error('Cync login missing access_token or user_id: %o', json);
100
+ throw new Error('Cync login response missing access_token or user_id');
101
+ }
102
+ this.accessToken = accessToken;
103
+ this.userId = userId;
104
+ this.log.info('Cync login successful; userId=%s', userId);
105
+ return {
106
+ accessToken,
107
+ userId,
108
+ raw: json,
109
+ };
110
+ }
111
+ /**
112
+ * Fetch the list of meshes/devices for the current user from the cloud.
113
+ *
114
+ * This roughly matches CyncCloudAPI.get_devices() from cync-lan, but in a
115
+ * simplified, single-call interface.
116
+ */
117
+ async getCloudConfig() {
118
+ this.ensureSession();
119
+ const devicesUrl = `${CYNC_API_BASE}user/${this.userId}/subscribe/devices`;
120
+ const headers = {
121
+ 'Access-Token': this.accessToken,
122
+ };
123
+ this.log.debug('Fetching Cync devices from %s', devicesUrl);
124
+ const res = (await fetch(devicesUrl, {
125
+ method: 'GET',
126
+ headers,
127
+ }));
128
+ const json = await res.json().catch(async () => {
129
+ const text = await res.text().catch(() => '');
130
+ throw new Error(`Cync devices returned non-JSON payload: ${text}`);
131
+ });
132
+ if (!res.ok) {
133
+ this.log.error('Cync devices call failed: HTTP %d %s %o', res.status, res.statusText, json);
134
+ const errBody = json;
135
+ const msg = errBody.error?.msg ?? 'Unknown error from Cync devices API';
136
+ throw new Error(msg);
137
+ }
138
+ // DEBUG: log high-level shape without dumping any secrets.
139
+ if (Array.isArray(json)) {
140
+ this.log.debug('Cync devices payload: top-level array length=%d; first item keys=%o', json.length, json.length > 0 ? Object.keys(json[0]) : []);
141
+ }
142
+ else if (json && typeof json === 'object') {
143
+ this.log.debug('Cync devices payload: top-level object keys=%o', Object.keys(json));
144
+ }
145
+ else {
146
+ this.log.debug('Cync devices payload: top-level type=%s', typeof json);
147
+ }
148
+ // Some Cync responses wrap arrays; others are raw arrays.
149
+ let meshes = [];
150
+ if (Array.isArray(json)) {
151
+ meshes = json;
152
+ }
153
+ else if (json && typeof json === 'object') {
154
+ const obj = json;
155
+ // Best guess: devices may be under a named property.
156
+ // We just log for now; once we see the payload, we can wire this properly.
157
+ this.log.debug('Cync devices payload (object) example values for known keys=%o', {
158
+ dataType: typeof obj.data,
159
+ devicesType: typeof obj.devices,
160
+ meshesType: typeof obj.meshes,
161
+ });
162
+ // Temporary: if there's a "data" array, treat that as meshes.
163
+ if (Array.isArray(obj.data)) {
164
+ meshes = obj.data;
165
+ }
166
+ else if (Array.isArray(obj.meshes)) {
167
+ meshes = obj.meshes;
168
+ }
169
+ }
170
+ return { meshes };
171
+ }
172
+ /**
173
+ * Convenience to fetch the properties object for a single device.
174
+ */
175
+ async getDeviceProperties(productId, deviceId) {
176
+ this.ensureSession();
177
+ const url = `${CYNC_API_BASE}product/${encodeURIComponent(productId)}/device/${encodeURIComponent(deviceId)}/property`;
178
+ const res = (await fetch(url, {
179
+ method: 'GET',
180
+ headers: {
181
+ 'Access-Token': this.accessToken,
182
+ },
183
+ }));
184
+ const json = await res.json().catch(async () => {
185
+ const text = await res.text().catch(() => '');
186
+ throw new Error(`Cync properties returned non-JSON payload: ${text}`);
187
+ });
188
+ if (!res.ok) {
189
+ this.log.error('Cync properties call failed: HTTP %d %s %o', res.status, res.statusText, json);
190
+ const errBody = json;
191
+ const msg = errBody.error?.msg ?? `Cync properties failed with ${res.status}`;
192
+ throw new Error(msg);
193
+ }
194
+ // We keep this as a loose record; callers can shape it as needed.
195
+ return json;
196
+ }
197
+ restoreSession(accessToken, userId) {
198
+ this.accessToken = accessToken;
199
+ this.userId = userId;
200
+ this.log.info('Cync: restored session from stored token; userId=%s', userId);
201
+ }
202
+ getSessionSnapshot() {
203
+ return {
204
+ accessToken: this.accessToken,
205
+ userId: this.userId,
206
+ };
207
+ }
208
+ ensureSession() {
209
+ if (!this.accessToken || !this.userId) {
210
+ throw new Error('Cync session not initialised. Call loginWithTwoFactor() first.');
211
+ }
212
+ }
213
+ static randomLoginResource() {
214
+ const chars = 'abcdefghijklmnopqrstuvwxyz';
215
+ let out = '';
216
+ for (let i = 0; i < 16; i += 1) {
217
+ out += chars.charAt(Math.floor(Math.random() * chars.length));
218
+ }
219
+ return out;
220
+ }
221
+ }
222
+ //# sourceMappingURL=config-client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config-client.js","sourceRoot":"","sources":["../../src/cync/config-client.ts"],"names":[],"mappings":"AAAA,4BAA4B;AAC5B,2CAA2C;AAC3C,qFAAqF;AACrF,EAAE;AACF,+EAA+E;AAC/E,wEAAwE;AAExE,MAAM,aAAa,GAAG,gCAAgC,CAAC;AACvD,MAAM,OAAO,GAAG,kBAAkB,CAAC;AAiEnC,MAAM,aAAa,GAAe;IACjC,KAAK,EAAE,CAAC,GAAG,IAAe,EAAE,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,eAAe,EAAE,GAAG,IAAI,CAAC;IACtE,IAAI,EAAE,CAAC,GAAG,IAAe,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,eAAe,EAAE,GAAG,IAAI,CAAC;IACpE,IAAI,EAAE,CAAC,GAAG,IAAe,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,eAAe,EAAE,GAAG,IAAI,CAAC;IACpE,KAAK,EAAE,CAAC,GAAG,IAAe,EAAE,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,eAAe,EAAE,GAAG,IAAI,CAAC;CACtE,CA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