node-miio 0.3.0 → 0.5.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.
Files changed (174) hide show
  1. package/.claude/settings.json +5 -0
  2. package/.claude/skills/release/SKILL.md +73 -0
  3. package/AGENTS.md +25 -2
  4. package/CONTRIBUTING.md +41 -87
  5. package/LICENSE.md +28 -0
  6. package/README.md +86 -44
  7. package/dist/cli/commands/cloud/devices.d.ts +10 -0
  8. package/dist/cli/commands/cloud/devices.js +71 -0
  9. package/dist/cli/commands/cloud/devices.js.map +1 -0
  10. package/dist/cli/commands/cloud/login.d.ts +8 -0
  11. package/dist/cli/commands/cloud/login.js +63 -0
  12. package/dist/cli/commands/cloud/login.js.map +1 -0
  13. package/dist/cli/commands/cloud/logout.d.ts +4 -0
  14. package/dist/cli/commands/cloud/logout.js +14 -0
  15. package/dist/cli/commands/cloud/logout.js.map +1 -0
  16. package/dist/cli/commands/cloud.d.ts +5 -0
  17. package/dist/cli/commands/cloud.js +49 -0
  18. package/dist/cli/commands/cloud.js.map +1 -0
  19. package/dist/cli/commands/configure.d.ts +18 -0
  20. package/dist/cli/commands/control.d.ts +4 -0
  21. package/dist/cli/commands/discover.d.ts +9 -0
  22. package/dist/cli/commands/inspect.d.ts +4 -0
  23. package/dist/cli/commands/miot-spec.d.ts +10 -0
  24. package/dist/cli/commands/protocol/call.d.ts +9 -0
  25. package/dist/cli/commands/protocol/json-dump.d.ts +8 -0
  26. package/dist/cli/commands/protocol/packet.d.ts +8 -0
  27. package/dist/cli/commands/protocol.d.ts +5 -0
  28. package/dist/cli/commands/tokens/update.d.ts +9 -0
  29. package/dist/cli/commands/tokens.d.ts +5 -0
  30. package/dist/cli/device-finder.d.ts +3 -0
  31. package/dist/cli/index.d.ts +2 -0
  32. package/dist/cli/index.js +2 -0
  33. package/dist/cli/index.js.map +1 -1
  34. package/dist/cli/log.d.ts +9 -0
  35. package/dist/cli/prompt.d.ts +11 -0
  36. package/dist/cli/prompt.js +42 -0
  37. package/dist/cli/prompt.js.map +1 -0
  38. package/dist/cli/terminal_qr.d.ts +7 -0
  39. package/dist/cli/terminal_qr.js +14 -0
  40. package/dist/cli/terminal_qr.js.map +1 -0
  41. package/dist/lib/check_result.d.ts +6 -0
  42. package/dist/lib/cloud/client.d.ts +142 -0
  43. package/dist/lib/cloud/client.js +282 -0
  44. package/dist/lib/cloud/client.js.map +1 -0
  45. package/dist/lib/cloud/crypto.d.ts +56 -0
  46. package/dist/lib/cloud/crypto.js +128 -0
  47. package/dist/lib/cloud/crypto.js.map +1 -0
  48. package/dist/lib/cloud/errors.d.ts +26 -0
  49. package/dist/lib/cloud/errors.js +50 -0
  50. package/dist/lib/cloud/errors.js.map +1 -0
  51. package/dist/lib/cloud/http.d.ts +55 -0
  52. package/dist/lib/cloud/http.js +159 -0
  53. package/dist/lib/cloud/http.js.map +1 -0
  54. package/dist/lib/cloud/index.d.ts +5 -0
  55. package/dist/lib/cloud/index.js +22 -0
  56. package/dist/lib/cloud/index.js.map +1 -0
  57. package/dist/lib/cloud/login.d.ts +57 -0
  58. package/dist/lib/cloud/login.js +352 -0
  59. package/dist/lib/cloud/login.js.map +1 -0
  60. package/dist/lib/cloud/session_store.d.ts +27 -0
  61. package/dist/lib/cloud/session_store.js +71 -0
  62. package/dist/lib/cloud/session_store.js.map +1 -0
  63. package/dist/lib/connect_to_device.d.ts +10 -0
  64. package/dist/lib/device.d.ts +151 -0
  65. package/dist/lib/device.js +53 -19
  66. package/dist/lib/device.js.map +1 -1
  67. package/dist/lib/device_info.d.ts +66 -0
  68. package/dist/lib/device_info.js +23 -10
  69. package/dist/lib/device_info.js.map +1 -1
  70. package/dist/lib/devices/air-monitor.d.ts +8 -0
  71. package/dist/lib/devices/air-purifier.d.ts +40 -0
  72. package/dist/lib/devices/capabilities/battery-level.d.ts +22 -0
  73. package/dist/lib/devices/capabilities/buzzer.d.ts +33 -0
  74. package/dist/lib/devices/capabilities/changeable-led-brightness.d.ts +35 -0
  75. package/dist/lib/devices/capabilities/colorable.d.ts +21 -0
  76. package/dist/lib/devices/capabilities/dimmable.d.ts +21 -0
  77. package/dist/lib/devices/capabilities/mode.d.ts +21 -0
  78. package/dist/lib/devices/capabilities/power.d.ts +21 -0
  79. package/dist/lib/devices/capabilities/sensor.d.ts +15 -0
  80. package/dist/lib/devices/capabilities/switchable-led.d.ts +35 -0
  81. package/dist/lib/devices/chuangmi.plug.v1.d.ts +31 -0
  82. package/dist/lib/devices/eyecare-lamp2.d.ts +91 -0
  83. package/dist/lib/devices/gateway/86sw1.d.ts +7 -0
  84. package/dist/lib/devices/gateway/86sw2.d.ts +7 -0
  85. package/dist/lib/devices/gateway/ctrl_ln1.d.ts +8 -0
  86. package/dist/lib/devices/gateway/ctrl_ln2.d.ts +8 -0
  87. package/dist/lib/devices/gateway/ctrl_neutral1.d.ts +8 -0
  88. package/dist/lib/devices/gateway/ctrl_neutral2.d.ts +8 -0
  89. package/dist/lib/devices/gateway/cube.d.ts +6 -0
  90. package/dist/lib/devices/gateway/developer-api.d.ts +15 -0
  91. package/dist/lib/devices/gateway/light-channel.d.ts +10 -0
  92. package/dist/lib/devices/gateway/light-mixin.d.ts +2 -0
  93. package/dist/lib/devices/gateway/magnet.d.ts +6 -0
  94. package/dist/lib/devices/gateway/magnet2.d.ts +5 -0
  95. package/dist/lib/devices/gateway/motion.d.ts +6 -0
  96. package/dist/lib/devices/gateway/motion2.d.ts +6 -0
  97. package/dist/lib/devices/gateway/plug.d.ts +6 -0
  98. package/dist/lib/devices/gateway/sensor_ht.d.ts +5 -0
  99. package/dist/lib/devices/gateway/subdevice.d.ts +70 -0
  100. package/dist/lib/devices/gateway/subdevices.d.ts +49 -0
  101. package/dist/lib/devices/gateway/switch.d.ts +6 -0
  102. package/dist/lib/devices/gateway/switch2.d.ts +6 -0
  103. package/dist/lib/devices/gateway/voltage.d.ts +23 -0
  104. package/dist/lib/devices/gateway/weather.d.ts +5 -0
  105. package/dist/lib/devices/gateway.d.ts +98 -0
  106. package/dist/lib/devices/humidifier.d.ts +20 -0
  107. package/dist/lib/devices/philips-light-bulb.d.ts +8 -0
  108. package/dist/lib/devices/power-plug.d.ts +30 -0
  109. package/dist/lib/devices/power-strip.d.ts +7 -0
  110. package/dist/lib/devices/vacuums/dreamevacuum.d.ts +81 -0
  111. package/dist/lib/devices/vacuums/dreamevacuum.js +10 -2
  112. package/dist/lib/devices/vacuums/dreamevacuum.js.map +1 -1
  113. package/dist/lib/devices/vacuums/mijiavacuum.d.ts +4 -0
  114. package/dist/lib/devices/vacuums/miot-vacuum.d.ts +130 -0
  115. package/dist/lib/devices/vacuums/miot-vacuum.js +2 -0
  116. package/dist/lib/devices/vacuums/miot-vacuum.js.map +1 -1
  117. package/dist/lib/devices/vacuums/vacuum.d.ts +276 -0
  118. package/dist/lib/devices/vacuums/vacuum.js +82 -0
  119. package/dist/lib/devices/vacuums/vacuum.js.map +1 -1
  120. package/dist/lib/devices/vacuums/vacuum_device.d.ts +17 -0
  121. package/dist/lib/devices/vacuums/vacuum_device.js +14 -0
  122. package/dist/lib/devices/vacuums/vacuum_device.js.map +1 -0
  123. package/dist/lib/devices/vacuums/vacuum_errors.d.ts +10 -0
  124. package/dist/lib/devices/vacuums/vacuum_errors.js +25 -0
  125. package/dist/lib/devices/vacuums/vacuum_errors.js.map +1 -0
  126. package/dist/lib/devices/vacuums/vacuum_modes.d.ts +51 -0
  127. package/dist/lib/devices/vacuums/viomivacuum.d.ts +76 -0
  128. package/dist/lib/devices/vacuums/viomivacuum.js +2 -0
  129. package/dist/lib/devices/vacuums/viomivacuum.js.map +1 -1
  130. package/dist/lib/devices/yeelight.color.d.ts +3 -0
  131. package/dist/lib/devices/yeelight.d.ts +159 -0
  132. package/dist/lib/devices/yeelight.mono.d.ts +3 -0
  133. package/dist/lib/discovery.d.ts +53 -0
  134. package/dist/lib/events.d.ts +18 -0
  135. package/dist/lib/events.js +3 -0
  136. package/dist/lib/events.js.map +1 -0
  137. package/dist/lib/index.d.ts +60 -0
  138. package/dist/lib/index.js +18 -1
  139. package/dist/lib/index.js.map +1 -1
  140. package/dist/lib/info_from_hostname.d.ts +13 -0
  141. package/dist/lib/logger.d.ts +43 -0
  142. package/dist/lib/logger.js +62 -0
  143. package/dist/lib/logger.js.map +1 -0
  144. package/dist/lib/management.d.ts +53 -0
  145. package/dist/lib/maps/map_watcher.d.ts +71 -0
  146. package/dist/lib/maps/map_watcher.js +127 -0
  147. package/dist/lib/maps/map_watcher.js.map +1 -0
  148. package/dist/lib/maps/roborock_map.d.ts +83 -0
  149. package/dist/lib/maps/roborock_map.js +269 -0
  150. package/dist/lib/maps/roborock_map.js.map +1 -0
  151. package/dist/lib/miio_error.d.ts +12 -0
  152. package/dist/lib/miot/miot_api.d.ts +54 -0
  153. package/dist/lib/miot/miot_spec.d.ts +114 -0
  154. package/dist/lib/miot/spec_client.d.ts +125 -0
  155. package/dist/lib/miot/spec_client.js +2 -2
  156. package/dist/lib/miot/spec_client.js.map +1 -1
  157. package/dist/lib/models.d.ts +271 -0
  158. package/dist/lib/network.d.ts +58 -0
  159. package/dist/lib/network.js +5 -2
  160. package/dist/lib/network.js.map +1 -1
  161. package/dist/lib/packet.d.ts +21 -0
  162. package/dist/lib/placeholder.d.ts +7 -0
  163. package/dist/lib/protocol.d.ts +299 -0
  164. package/dist/lib/safeish_json.d.ts +7 -0
  165. package/dist/lib/tokens.d.ts +12 -0
  166. package/dist/types/abstract-things/climate/index.d.ts +431 -0
  167. package/dist/types/abstract-things/electricals/index.d.ts +5 -0
  168. package/dist/types/abstract-things/index.d.ts +206 -0
  169. package/dist/types/abstract-things/lights/index.d.ts +14 -0
  170. package/dist/types/abstract-things/values/index.d.ts +12 -0
  171. package/docs/cloud.md +74 -0
  172. package/docs/devices/vacuum.md +9 -1
  173. package/package.json +7 -3
  174. package/snapshots/vacuum-specs.json.gz +0 -0
@@ -0,0 +1,282 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.XiaomiCloud = exports.CLOUD_SERVERS = void 0;
4
+ /*
5
+ * Client of the Xiaomi Cloud API (api.io.mi.com): homes, devices (with their tokens) and map files.
6
+ *
7
+ * Ported from Xiaomi-cloud-tokens-extractor (https://github.com/PiotrMachowski/Xiaomi-cloud-tokens-extractor)
8
+ * and Xiaomi-Cloud-Map-Extractor (https://github.com/PiotrMachowski/Home-Assistant-custom-components-Xiaomi-Cloud-Map-Extractor)
9
+ * Copyright (c) 2020 Piotr Machowski. Licensed under the MIT License.
10
+ */
11
+ const logger_1 = require("../logger");
12
+ const crypto_1 = require("./crypto");
13
+ const errors_1 = require("./errors");
14
+ const http_1 = require("./http");
15
+ const login_1 = require("./login");
16
+ const debug = (0, logger_1.createDebug)("miio:cloud");
17
+ /** The regional servers of the Xiaomi Cloud */
18
+ exports.CLOUD_SERVERS = [
19
+ "cn",
20
+ "de",
21
+ "us",
22
+ "ru",
23
+ "tw",
24
+ "sg",
25
+ "in",
26
+ "i2",
27
+ ];
28
+ /**
29
+ * Client of the Xiaomi Cloud API.
30
+ *
31
+ * ```ts
32
+ * const cloud = await XiaomiCloud.loginWithQrCode({ onQrCode: ({ loginUrl }) => console.log(loginUrl) });
33
+ * const devices = await cloud.getDevices();
34
+ * ```
35
+ */
36
+ class XiaomiCloud {
37
+ session;
38
+ http;
39
+ agent = (0, login_1.generateAgent)();
40
+ /**
41
+ * @param session A session from a previous login (see {@link XiaomiCloud.session})
42
+ * @param options The client options
43
+ */
44
+ constructor(session, options = {}) {
45
+ this.session = session;
46
+ this.http = new http_1.HttpSession(options.fetch);
47
+ }
48
+ /**
49
+ * Logs in with a username (email, phone number or user ID) and password.
50
+ *
51
+ * @param username The username
52
+ * @param password The password
53
+ * @param options Callbacks for the captcha and the email verification
54
+ * @returns The client
55
+ */
56
+ static async loginWithPassword(username, password, options = {}) {
57
+ const session = await (0, login_1.loginWithPassword)(username, password, options);
58
+ return new XiaomiCloud(session, options);
59
+ }
60
+ /**
61
+ * Logs in by scanning a QR code with the Mi Home app.
62
+ *
63
+ * @param options The callback that shows the QR code
64
+ * @returns The client
65
+ */
66
+ static async loginWithQrCode(options) {
67
+ const session = await (0, login_1.loginWithQrCode)(options);
68
+ return new XiaomiCloud(session, options);
69
+ }
70
+ /**
71
+ * @param server The regional server
72
+ * @returns The base URL of the API in that server
73
+ */
74
+ static apiUrl(server) {
75
+ return `https://${server === "cn" ? "" : `${server}.`}api.io.mi.com/app`;
76
+ }
77
+ /**
78
+ * Calls the API (signed and encrypted).
79
+ *
80
+ * @param server The regional server
81
+ * @param path The API path (e.g. `/v2/homeroom/gethome`)
82
+ * @param data The request data
83
+ * @returns The `result` of the response
84
+ */
85
+ async call(server, path, data) {
86
+ const url = XiaomiCloud.apiUrl(server) + path;
87
+ const nonce = (0, crypto_1.generateNonce)();
88
+ const key = (0, crypto_1.signedNonce)(this.session.ssecurity, nonce);
89
+ const fields = (0, crypto_1.encryptParams)(url, "POST", key, nonce, { data: typeof data === "string" ? data : JSON.stringify(data) }, this.session.ssecurity);
90
+ const response = await this.http.request(url, {
91
+ method: "POST",
92
+ query: fields,
93
+ headers: {
94
+ "Accept-Encoding": "identity",
95
+ "User-Agent": this.agent,
96
+ "Content-Type": "application/x-www-form-urlencoded",
97
+ "x-xiaomi-protocal-flag-cli": "PROTOCAL-HTTP2",
98
+ "MIOT-ENCRYPT-ALGORITHM": "ENCRYPT-RC4",
99
+ },
100
+ cookies: {
101
+ userId: this.session.userId,
102
+ yetAnotherServiceToken: this.session.serviceToken,
103
+ serviceToken: this.session.serviceToken,
104
+ locale: "en_GB",
105
+ timezone: "GMT+02:00",
106
+ is_daylight: "1",
107
+ dst_offset: "3600000",
108
+ channel: "MI_APP_STORE",
109
+ },
110
+ });
111
+ if (response.status === 401)
112
+ throw new errors_1.CloudSessionExpiredError();
113
+ if (response.status !== 200) {
114
+ throw new errors_1.CloudApiError(`${path} failed (HTTP ${response.status})`, response.status);
115
+ }
116
+ let json;
117
+ try {
118
+ json = JSON.parse((0, crypto_1.decryptRc4)(key, response.text));
119
+ }
120
+ catch {
121
+ // Errors may come unencrypted
122
+ try {
123
+ json = JSON.parse(response.text);
124
+ }
125
+ catch {
126
+ throw new errors_1.CloudApiError(`${path} returned an unexpected response`);
127
+ }
128
+ }
129
+ if (json.code !== undefined && json.code !== 0) {
130
+ throw new errors_1.CloudApiError(`${path} failed: ${json.message ?? json.code}`, json.code);
131
+ }
132
+ return json.result;
133
+ }
134
+ /**
135
+ * @param server The regional server
136
+ * @returns The homes of the user and the homes shared with them
137
+ */
138
+ async getHomes(server) {
139
+ const homes = [];
140
+ const own = await this.call(server, "/v2/homeroom/gethome", '{"fg": true, "fetch_share": true, "fetch_share_dev": true, "limit": 300, "app_ver": 7}');
141
+ for (const home of own?.homelist ?? []) {
142
+ homes.push({ homeId: String(home.id), owner: this.session.userId });
143
+ }
144
+ const count = await this.call(server, "/v2/user/get_device_cnt", '{ "fetch_own": true, "fetch_share": true}');
145
+ for (const home of count?.share?.share_family ?? []) {
146
+ homes.push({
147
+ homeId: String(home.home_id),
148
+ owner: String(home.home_owner),
149
+ });
150
+ }
151
+ return homes;
152
+ }
153
+ /**
154
+ * @param server The regional server
155
+ * @param home The home
156
+ * @returns The devices of the home
157
+ */
158
+ async getHomeDevices(server, home) {
159
+ const result = await this.call(server, "/v2/home/home_device_list", `{"home_owner": ${home.owner},"home_id": ${home.homeId}, "limit": 200, "get_split_device": true, "support_smart_home": true}`);
160
+ return (result?.device_info ?? []).map((device) => ({
161
+ did: String(device.did),
162
+ name: String(device.name ?? ""),
163
+ model: String(device.model ?? ""),
164
+ token: String(device.token ?? ""),
165
+ localip: optionalString(device.localip),
166
+ mac: optionalString(device.mac),
167
+ isOnline: typeof device.isOnline === "boolean" ? device.isOnline : undefined,
168
+ server,
169
+ homeId: home.homeId,
170
+ homeOwner: home.owner,
171
+ }));
172
+ }
173
+ /**
174
+ * Lists the devices of the account, with their tokens.
175
+ *
176
+ * @param options The options
177
+ * @param options.servers The servers to check (all of them by default)
178
+ * @returns The devices
179
+ */
180
+ async getDevices(options = {}) {
181
+ const devices = new Map();
182
+ for (const server of options.servers ?? exports.CLOUD_SERVERS) {
183
+ let homes;
184
+ try {
185
+ homes = await this.getHomes(server);
186
+ }
187
+ catch (err) {
188
+ if (err instanceof errors_1.CloudSessionExpiredError)
189
+ throw err;
190
+ debug(`Unable to get the homes in ${server}: ${err}`);
191
+ continue;
192
+ }
193
+ const seen = new Set();
194
+ for (const home of homes) {
195
+ if (seen.has(home.homeId))
196
+ continue;
197
+ seen.add(home.homeId);
198
+ try {
199
+ for (const device of await this.getHomeDevices(server, home)) {
200
+ if (!devices.has(device.did))
201
+ devices.set(device.did, device);
202
+ }
203
+ }
204
+ catch (err) {
205
+ if (err instanceof errors_1.CloudSessionExpiredError)
206
+ throw err;
207
+ debug(`Unable to get the devices of home ${home.homeId} in ${server}: ${err}`);
208
+ }
209
+ }
210
+ }
211
+ return [...devices.values()];
212
+ }
213
+ /**
214
+ * Finds a device of the account (e.g. to know its token or its server).
215
+ *
216
+ * @param match The device ID, token or local IP of the device (the first one given that matches)
217
+ * @param match.did The device ID
218
+ * @param match.token The device token
219
+ * @param match.ip The local IP of the device
220
+ * @param options The options of {@link XiaomiCloud.getDevices}
221
+ * @param options.servers The servers to check (all of them by default)
222
+ * @returns The device, if found
223
+ */
224
+ async findDevice(match, options = {}) {
225
+ const devices = await this.getDevices(options);
226
+ const token = match.token?.toLowerCase();
227
+ return ((match.did !== undefined &&
228
+ devices.find((d) => d.did === String(match.did))) ||
229
+ (token && devices.find((d) => d.token.toLowerCase() === token)) ||
230
+ (match.ip && devices.find((d) => d.localip === match.ip)) ||
231
+ undefined);
232
+ }
233
+ /**
234
+ * Downloads a file (e.g. a map file from {@link XiaomiCloud.getMapFileUrl}).
235
+ *
236
+ * @param url The URL
237
+ * @returns The file contents
238
+ */
239
+ async download(url) {
240
+ const response = await this.http.request(url, { timeoutMs: 30_000 });
241
+ if (response.status !== 200) {
242
+ throw new errors_1.CloudError(`Unable to download the file (HTTP ${response.status})`);
243
+ }
244
+ return response.body;
245
+ }
246
+ /**
247
+ * Gets the URL of a map file (Roborock and Xiaomi vacuums). The map name comes from the device (`get_map_v1`).
248
+ *
249
+ * @param server The regional server of the device
250
+ * @param mapName The map name
251
+ * @returns The URL of the (gzipped) map file
252
+ */
253
+ async getMapFileUrl(server, mapName) {
254
+ const result = await this.call(server, "/home/getmapfileurl", `{"obj_name":"${mapName}"}`);
255
+ if (!result?.url)
256
+ throw new errors_1.CloudApiError(`No map file for ${mapName}`);
257
+ return result.url;
258
+ }
259
+ /**
260
+ * Gets the URL of a map file of the newer vacuums (Dreame, Viomi, Roidmi…).
261
+ *
262
+ * @param server The regional server of the device
263
+ * @param did The device ID
264
+ * @param mapName The map name
265
+ * @returns The URL of the map file
266
+ */
267
+ async getInterimFileUrl(server, did, mapName) {
268
+ const result = await this.call(server, "/v2/home/get_interim_file_url", `{"obj_name":"${this.session.userId}/${did}/${mapName}"}`);
269
+ if (!result?.url)
270
+ throw new errors_1.CloudApiError(`No map file for ${mapName}`);
271
+ return result.url;
272
+ }
273
+ }
274
+ exports.XiaomiCloud = XiaomiCloud;
275
+ /**
276
+ * @param value A value of the response
277
+ * @returns The value, if it's a non-empty string
278
+ */
279
+ function optionalString(value) {
280
+ return typeof value === "string" && value ? value : undefined;
281
+ }
282
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../../../src/lib/cloud/client.ts"],"names":[],"mappings":";;;AAAA;;;;;;GAMG;AACH,sCAAwC;AAExC,qCAKkB;AAClB,qCAA+E;AAC/E,iCAAqD;AACrD,mCAOiB;AAEjB,MAAM,KAAK,GAAG,IAAA,oBAAW,EAAC,YAAY,CAAC,CAAC;AAExC,+CAA+C;AAClC,QAAA,aAAa,GAAG;IAC3B,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAA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G;YAAE,MAAM,IAAI,sBAAa,CAAC,mBAAmB,OAAO,EAAE,CAAC,CAAC;QACxE,OAAO,MAAM,CAAC,GAAG,CAAC;IACpB,CAAC;IAED;;;;;;;OAOG;IACH,KAAK,CAAC,iBAAiB,CACrB,MAA4B,EAC5B,GAAW,EACX,OAAe;QAEf,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,IAAI,CAC5B,MAAM,EACN,+BAA+B,EAC/B,gBAAgB,IAAI,CAAC,OAAO,CAAC,MAAM,IAAI,GAAG,IAAI,OAAO,IAAI,CAC1D,CAAC;QACF,IAAI,CAAC,MAAM,EAAE,GAAG;YAAE,MAAM,IAAI,sBAAa,CAAC,mBAAmB,OAAO,EAAE,CAAC,CAAC;QACxE,OAAO,MAAM,CAAC,GAAG,CAAC;IACpB,CAAC;CACF;AAxTD,kCAwTC;AAED;;;GAGG;AACH,SAAS,cAAc,CAAC,KAAc;IACpC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;AAChE,CAAC"}
@@ -0,0 +1,56 @@
1
+ /**
2
+ * RC4 stream cipher, dropping the first `drop` bytes of the keystream (the API uses RC4-drop1024).
3
+ * Implemented in JS because Node.js (OpenSSL 3) no longer ships RC4 by default.
4
+ *
5
+ * @param key The key
6
+ * @param data The data to encrypt or decrypt (RC4 is symmetric)
7
+ * @param drop The number of keystream bytes to discard first
8
+ * @returns The encrypted (or decrypted) data
9
+ */
10
+ export declare function rc4(key: Buffer, data: Buffer, drop?: number): Buffer;
11
+ /**
12
+ * Generates a request nonce: 8 random bytes followed by the current minute (uint32, big-endian).
13
+ *
14
+ * @param now The current time in milliseconds
15
+ * @param random 8 random bytes
16
+ * @returns The nonce (base64)
17
+ */
18
+ export declare function generateNonce(now?: number, random?: NonSharedBuffer): string;
19
+ /**
20
+ * @param ssecurity The `ssecurity` of the session (base64)
21
+ * @param nonce The request nonce (base64)
22
+ * @returns The key of the request: `sha256(ssecurity + nonce)` (base64)
23
+ */
24
+ export declare function signedNonce(ssecurity: string, nonce: string): string;
25
+ /**
26
+ * @param url The full URL of the API call
27
+ * @param method The HTTP method
28
+ * @param key The signed nonce (base64)
29
+ * @param params The request params, in order
30
+ * @returns The `sha1` signature of the request (base64)
31
+ */
32
+ export declare function encSignature(url: string, method: string, key: string, params: Record<string, string>): string;
33
+ /**
34
+ * @param key The signed nonce (base64)
35
+ * @param payload The text to encrypt
36
+ * @returns The encrypted text (base64)
37
+ */
38
+ export declare function encryptRc4(key: string, payload: string): string;
39
+ /**
40
+ * @param key The signed nonce (base64)
41
+ * @param payload The encrypted text (base64)
42
+ * @returns The decrypted text
43
+ */
44
+ export declare function decryptRc4(key: string, payload: string): string;
45
+ /**
46
+ * Signs and encrypts the params of an API call.
47
+ *
48
+ * @param url The full URL of the API call
49
+ * @param method The HTTP method
50
+ * @param key The signed nonce (base64)
51
+ * @param nonce The nonce (base64)
52
+ * @param params The params to send (e.g. `{ data: "{...}" }`)
53
+ * @param ssecurity The `ssecurity` of the session
54
+ * @returns The params to send
55
+ */
56
+ export declare function encryptParams(url: string, method: string, key: string, nonce: string, params: Record<string, string>, ssecurity: string): Record<string, string>;
@@ -0,0 +1,128 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.rc4 = rc4;
7
+ exports.generateNonce = generateNonce;
8
+ exports.signedNonce = signedNonce;
9
+ exports.encSignature = encSignature;
10
+ exports.encryptRc4 = encryptRc4;
11
+ exports.decryptRc4 = decryptRc4;
12
+ exports.encryptParams = encryptParams;
13
+ /*
14
+ * Request signing and encryption of the Xiaomi Cloud API (api.io.mi.com).
15
+ *
16
+ * Ported from Xiaomi-cloud-tokens-extractor (https://github.com/PiotrMachowski/Xiaomi-cloud-tokens-extractor)
17
+ * Copyright (c) 2020 Piotr Machowski. Licensed under the MIT License.
18
+ */
19
+ const node_crypto_1 = __importDefault(require("node:crypto"));
20
+ /**
21
+ * RC4 stream cipher, dropping the first `drop` bytes of the keystream (the API uses RC4-drop1024).
22
+ * Implemented in JS because Node.js (OpenSSL 3) no longer ships RC4 by default.
23
+ *
24
+ * @param key The key
25
+ * @param data The data to encrypt or decrypt (RC4 is symmetric)
26
+ * @param drop The number of keystream bytes to discard first
27
+ * @returns The encrypted (or decrypted) data
28
+ */
29
+ function rc4(key, data, drop = 1024) {
30
+ const s = new Uint8Array(256);
31
+ for (let i = 0; i < 256; i++)
32
+ s[i] = i;
33
+ for (let i = 0, j = 0; i < 256; i++) {
34
+ j = (j + s[i] + key[i % key.length]) & 0xff;
35
+ [s[i], s[j]] = [s[j], s[i]];
36
+ }
37
+ const out = Buffer.alloc(data.length);
38
+ for (let n = 0, i = 0, j = 0; n < drop + data.length; n++) {
39
+ i = (i + 1) & 0xff;
40
+ j = (j + s[i]) & 0xff;
41
+ [s[i], s[j]] = [s[j], s[i]];
42
+ if (n >= drop)
43
+ out[n - drop] = data[n - drop] ^ s[(s[i] + s[j]) & 0xff];
44
+ }
45
+ return out;
46
+ }
47
+ /**
48
+ * Generates a request nonce: 8 random bytes followed by the current minute (uint32, big-endian).
49
+ *
50
+ * @param now The current time in milliseconds
51
+ * @param random 8 random bytes
52
+ * @returns The nonce (base64)
53
+ */
54
+ function generateNonce(now = Date.now(), random = node_crypto_1.default.randomBytes(8)) {
55
+ const minutes = Buffer.alloc(4);
56
+ minutes.writeUInt32BE(Math.floor(now / 60000));
57
+ return Buffer.concat([random, minutes]).toString("base64");
58
+ }
59
+ /**
60
+ * @param ssecurity The `ssecurity` of the session (base64)
61
+ * @param nonce The request nonce (base64)
62
+ * @returns The key of the request: `sha256(ssecurity + nonce)` (base64)
63
+ */
64
+ function signedNonce(ssecurity, nonce) {
65
+ return node_crypto_1.default
66
+ .createHash("sha256")
67
+ .update(Buffer.from(ssecurity, "base64"))
68
+ .update(Buffer.from(nonce, "base64"))
69
+ .digest("base64");
70
+ }
71
+ /**
72
+ * @param url The full URL of the API call
73
+ * @param method The HTTP method
74
+ * @param key The signed nonce (base64)
75
+ * @param params The request params, in order
76
+ * @returns The `sha1` signature of the request (base64)
77
+ */
78
+ function encSignature(url, method, key, params) {
79
+ const path = new URL(url).pathname.replace("/app/", "/");
80
+ const parts = [method.toUpperCase(), path];
81
+ for (const [k, v] of Object.entries(params))
82
+ parts.push(`${k}=${v}`);
83
+ parts.push(key);
84
+ return node_crypto_1.default.createHash("sha1").update(parts.join("&")).digest("base64");
85
+ }
86
+ /**
87
+ * @param key The signed nonce (base64)
88
+ * @param payload The text to encrypt
89
+ * @returns The encrypted text (base64)
90
+ */
91
+ function encryptRc4(key, payload) {
92
+ return rc4(Buffer.from(key, "base64"), Buffer.from(payload)).toString("base64");
93
+ }
94
+ /**
95
+ * @param key The signed nonce (base64)
96
+ * @param payload The encrypted text (base64)
97
+ * @returns The decrypted text
98
+ */
99
+ function decryptRc4(key, payload) {
100
+ return rc4(Buffer.from(key, "base64"), Buffer.from(payload, "base64")).toString("utf8");
101
+ }
102
+ /**
103
+ * Signs and encrypts the params of an API call.
104
+ *
105
+ * @param url The full URL of the API call
106
+ * @param method The HTTP method
107
+ * @param key The signed nonce (base64)
108
+ * @param nonce The nonce (base64)
109
+ * @param params The params to send (e.g. `{ data: "{...}" }`)
110
+ * @param ssecurity The `ssecurity` of the session
111
+ * @returns The params to send
112
+ */
113
+ function encryptParams(url, method, key, nonce, params, ssecurity) {
114
+ const signed = {
115
+ ...params,
116
+ rc4_hash__: encSignature(url, method, key, params),
117
+ };
118
+ const encrypted = {};
119
+ for (const [k, v] of Object.entries(signed))
120
+ encrypted[k] = encryptRc4(key, v);
121
+ return {
122
+ ...encrypted,
123
+ signature: encSignature(url, method, key, encrypted),
124
+ ssecurity,
125
+ _nonce: nonce,
126
+ };
127
+ }
128
+ //# sourceMappingURL=crypto.js.map
@@ -0,0 +1 @@
1
+ {"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M;QACT,UAAU,EAAE,YAAY,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,CAAC;KACnD,CAAC;IACF,MAAM,SAAS,GAA2B,EAAE,CAAC;IAC7C,KAAK,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC;QACzC,SAAS,CAAC,CAAC,CAAC,GAAG,UAAU,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;IACpC,OAAO;QACL,GAAG,SAAS;QACZ,SAAS,EAAE,YAAY,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,SAAS,CAAC;QACpD,SAAS;QACT,MAAM,EAAE,KAAK;KACd,CAAC;AACJ,CAAC"}
@@ -0,0 +1,26 @@
1
+ /** Base class of the errors thrown by the Xiaomi Cloud client */
2
+ export declare class CloudError extends Error {
3
+ constructor(message: string);
4
+ }
5
+ /** The username or password is wrong (or the account can't log in) */
6
+ export declare class CloudAuthError extends CloudError {
7
+ }
8
+ /** Xiaomi asks to solve a captcha, but no `solveCaptcha` callback was provided */
9
+ export declare class CloudCaptchaRequiredError extends CloudError {
10
+ readonly captchaUrl: string;
11
+ constructor(captchaUrl: string);
12
+ }
13
+ /** Xiaomi asks for a verification code (2FA), but no `getVerificationCode` callback was provided */
14
+ export declare class CloudTwoFactorRequiredError extends CloudError {
15
+ readonly notificationUrl: string;
16
+ constructor(notificationUrl: string);
17
+ }
18
+ /** The session is no longer valid: log in again */
19
+ export declare class CloudSessionExpiredError extends CloudError {
20
+ constructor();
21
+ }
22
+ /** The API returned an error */
23
+ export declare class CloudApiError extends CloudError {
24
+ readonly code?: number | string | undefined;
25
+ constructor(message: string, code?: number | string | undefined);
26
+ }
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CloudApiError = exports.CloudSessionExpiredError = exports.CloudTwoFactorRequiredError = exports.CloudCaptchaRequiredError = exports.CloudAuthError = exports.CloudError = void 0;
4
+ /** Base class of the errors thrown by the Xiaomi Cloud client */
5
+ class CloudError extends Error {
6
+ constructor(message) {
7
+ super(message);
8
+ this.name = new.target.name;
9
+ }
10
+ }
11
+ exports.CloudError = CloudError;
12
+ /** The username or password is wrong (or the account can't log in) */
13
+ class CloudAuthError extends CloudError {
14
+ }
15
+ exports.CloudAuthError = CloudAuthError;
16
+ /** Xiaomi asks to solve a captcha, but no `solveCaptcha` callback was provided */
17
+ class CloudCaptchaRequiredError extends CloudError {
18
+ captchaUrl;
19
+ constructor(captchaUrl) {
20
+ super("Xiaomi asks to solve a captcha to log in");
21
+ this.captchaUrl = captchaUrl;
22
+ }
23
+ }
24
+ exports.CloudCaptchaRequiredError = CloudCaptchaRequiredError;
25
+ /** Xiaomi asks for a verification code (2FA), but no `getVerificationCode` callback was provided */
26
+ class CloudTwoFactorRequiredError extends CloudError {
27
+ notificationUrl;
28
+ constructor(notificationUrl) {
29
+ super("Xiaomi asks for a verification code to log in (two-factor authentication)");
30
+ this.notificationUrl = notificationUrl;
31
+ }
32
+ }
33
+ exports.CloudTwoFactorRequiredError = CloudTwoFactorRequiredError;
34
+ /** The session is no longer valid: log in again */
35
+ class CloudSessionExpiredError extends CloudError {
36
+ constructor() {
37
+ super("The Xiaomi Cloud session expired: please log in again");
38
+ }
39
+ }
40
+ exports.CloudSessionExpiredError = CloudSessionExpiredError;
41
+ /** The API returned an error */
42
+ class CloudApiError extends CloudError {
43
+ code;
44
+ constructor(message, code) {
45
+ super(message);
46
+ this.code = code;
47
+ }
48
+ }
49
+ exports.CloudApiError = CloudApiError;
50
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../src/lib/cloud/errors.ts"],"names":[],"mappings":";;;AAAA,iEAAiE;AACjE,MAAa,UAAW,SAAQ,KAAK;IACnC,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC;IAC9B,CAAC;CACF;AALD,gCAKC;AAED,sEAAsE;AACtE,MAAa,cAAe,SAAQ,UAAU;CAAG;AAAjD,wCAAiD;AAEjD,kFAAkF;AAClF,MAAa,yBAA0B,SAAQ,UAAU;IAC3B;IAA5B,YAA4B,UAAkB;QAC5C,KAAK,CAAC,0CAA0C,CAAC,CAAC;QADxB,eAAU,GAAV,UAAU,CAAQ;IAE9C,CAAC;CACF;AAJD,8DAIC;AAED,oGAAoG;AACpG,MAAa,2BAA4B,SAAQ,UAAU;IAC7B;IAA5B,YAA4B,eAAuB;QACjD,KAAK,CACH,2EAA2E,CAC5E,CAAC;QAHwB,oBAAe,GAAf,eAAe,CAAQ;IAInD,CAAC;CACF;AAND,kEAMC;AAED,mDAAmD;AACnD,MAAa,wBAAyB,SAAQ,UAAU;IACtD;QACE,KAAK,CAAC,uDAAuD,CAAC,CAAC;IACjE,CAAC;CACF;AAJD,4DAIC;AAED,gCAAgC;AAChC,MAAa,aAAc,SAAQ,UAAU;IAGzB;IAFlB,YACE,OAAe,EACC,IAAsB;QAEtC,KAAK,CAAC,OAAO,CAAC,CAAC;QAFC,SAAI,GAAJ,IAAI,CAAkB;IAGxC,CAAC;CACF;AAPD,sCAOC"}
@@ -0,0 +1,55 @@
1
+ /** The `fetch` implementation (injectable, so the cloud client can be tested without network) */
2
+ export type FetchLike = (url: string, init?: RequestInit) => Promise<Response>;
3
+ export interface HttpRequestOptions {
4
+ method?: "GET" | "POST";
5
+ /** Params added to the URL's query string */
6
+ query?: Record<string, string>;
7
+ /** Params sent as an `application/x-www-form-urlencoded` body */
8
+ form?: Record<string, string>;
9
+ headers?: Record<string, string>;
10
+ /** Cookies sent with this request only (on top of the session's cookies) */
11
+ cookies?: Record<string, string>;
12
+ /** Follow the redirects (default) or return the redirect response */
13
+ followRedirects?: boolean;
14
+ /** Request timeout in milliseconds (default 15s) */
15
+ timeoutMs?: number;
16
+ }
17
+ export interface HttpResponse {
18
+ status: number;
19
+ /** The final URL, after redirects */
20
+ url: string;
21
+ headers: Headers;
22
+ text: string;
23
+ body: Buffer;
24
+ }
25
+ /**
26
+ * A minimal HTTP session on top of `fetch`, with a cookie jar and manual redirects
27
+ * (so the cookies set on every hop of the login flows are kept).
28
+ */
29
+ export declare class HttpSession {
30
+ private readonly fetchImpl;
31
+ private cookies;
32
+ constructor(fetchImpl?: FetchLike);
33
+ /**
34
+ * @param name The cookie name
35
+ * @param value The cookie value
36
+ * @param domain The domain the cookie applies to (and its subdomains)
37
+ */
38
+ setCookie(name: string, value: string, domain: string): void;
39
+ /**
40
+ * @param name The cookie name
41
+ * @param domain If set, only the cookies of this domain (or its parents) are considered
42
+ * @returns The value of the most recently set matching cookie
43
+ */
44
+ getCookie(name: string, domain?: string): string | undefined;
45
+ request(url: string, options?: HttpRequestOptions): Promise<HttpResponse>;
46
+ private cookieHeader;
47
+ private storeCookies;
48
+ }
49
+ /**
50
+ * Parses a JSON response of account.xiaomi.com, which are prefixed with `&&&START&&&`.
51
+ *
52
+ * @param text The response text
53
+ * @returns The parsed JSON
54
+ */
55
+ export declare function parseXiaomiJson<T = Record<string, unknown>>(text: string): T;