node-miio 0.3.0 → 0.4.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 (45) hide show
  1. package/.claude/settings.json +5 -0
  2. package/.claude/skills/release/SKILL.md +62 -0
  3. package/AGENTS.md +8 -0
  4. package/LICENSE.md +28 -0
  5. package/README.md +43 -37
  6. package/dist/cli/commands/cloud/devices.js +71 -0
  7. package/dist/cli/commands/cloud/devices.js.map +1 -0
  8. package/dist/cli/commands/cloud/login.js +63 -0
  9. package/dist/cli/commands/cloud/login.js.map +1 -0
  10. package/dist/cli/commands/cloud/logout.js +14 -0
  11. package/dist/cli/commands/cloud/logout.js.map +1 -0
  12. package/dist/cli/commands/cloud.js +49 -0
  13. package/dist/cli/commands/cloud.js.map +1 -0
  14. package/dist/cli/index.js +2 -0
  15. package/dist/cli/index.js.map +1 -1
  16. package/dist/cli/prompt.js +42 -0
  17. package/dist/cli/prompt.js.map +1 -0
  18. package/dist/cli/terminal_qr.js +14 -0
  19. package/dist/cli/terminal_qr.js.map +1 -0
  20. package/dist/lib/cloud/client.js +285 -0
  21. package/dist/lib/cloud/client.js.map +1 -0
  22. package/dist/lib/cloud/crypto.js +128 -0
  23. package/dist/lib/cloud/crypto.js.map +1 -0
  24. package/dist/lib/cloud/errors.js +50 -0
  25. package/dist/lib/cloud/errors.js.map +1 -0
  26. package/dist/lib/cloud/http.js +159 -0
  27. package/dist/lib/cloud/http.js.map +1 -0
  28. package/dist/lib/cloud/index.js +22 -0
  29. package/dist/lib/cloud/index.js.map +1 -0
  30. package/dist/lib/cloud/login.js +352 -0
  31. package/dist/lib/cloud/login.js.map +1 -0
  32. package/dist/lib/cloud/session_store.js +71 -0
  33. package/dist/lib/cloud/session_store.js.map +1 -0
  34. package/dist/lib/devices/vacuums/vacuum.js +80 -0
  35. package/dist/lib/devices/vacuums/vacuum.js.map +1 -1
  36. package/dist/lib/index.js +14 -1
  37. package/dist/lib/index.js.map +1 -1
  38. package/dist/lib/maps/map_watcher.js +130 -0
  39. package/dist/lib/maps/map_watcher.js.map +1 -0
  40. package/dist/lib/maps/roborock_map.js +269 -0
  41. package/dist/lib/maps/roborock_map.js.map +1 -0
  42. package/docs/cloud.md +74 -0
  43. package/docs/devices/vacuum.md +9 -1
  44. package/package.json +2 -1
  45. package/snapshots/vacuum-specs.json.gz +0 -0
@@ -0,0 +1,285 @@
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.XiaomiCloud = exports.CLOUD_SERVERS = void 0;
7
+ /*
8
+ * Client of the Xiaomi Cloud API (api.io.mi.com): homes, devices (with their tokens) and map files.
9
+ *
10
+ * Ported from Xiaomi-cloud-tokens-extractor (https://github.com/PiotrMachowski/Xiaomi-cloud-tokens-extractor)
11
+ * and Xiaomi-Cloud-Map-Extractor (https://github.com/PiotrMachowski/Home-Assistant-custom-components-Xiaomi-Cloud-Map-Extractor)
12
+ * Copyright (c) 2020 Piotr Machowski. Licensed under the MIT License.
13
+ */
14
+ const debug_1 = __importDefault(require("debug"));
15
+ const crypto_1 = require("./crypto");
16
+ const errors_1 = require("./errors");
17
+ const http_1 = require("./http");
18
+ const login_1 = require("./login");
19
+ const debug = (0, debug_1.default)("miio:cloud");
20
+ /** The regional servers of the Xiaomi Cloud */
21
+ exports.CLOUD_SERVERS = [
22
+ "cn",
23
+ "de",
24
+ "us",
25
+ "ru",
26
+ "tw",
27
+ "sg",
28
+ "in",
29
+ "i2",
30
+ ];
31
+ /**
32
+ * Client of the Xiaomi Cloud API.
33
+ *
34
+ * ```ts
35
+ * const cloud = await XiaomiCloud.loginWithQrCode({ onQrCode: ({ loginUrl }) => console.log(loginUrl) });
36
+ * const devices = await cloud.getDevices();
37
+ * ```
38
+ */
39
+ class XiaomiCloud {
40
+ session;
41
+ http;
42
+ agent = (0, login_1.generateAgent)();
43
+ /**
44
+ * @param session A session from a previous login (see {@link XiaomiCloud.session})
45
+ * @param options The client options
46
+ */
47
+ constructor(session, options = {}) {
48
+ this.session = session;
49
+ this.http = new http_1.HttpSession(options.fetch);
50
+ }
51
+ /**
52
+ * Logs in with a username (email, phone number or user ID) and password.
53
+ *
54
+ * @param username The username
55
+ * @param password The password
56
+ * @param options Callbacks for the captcha and the email verification
57
+ * @returns The client
58
+ */
59
+ static async loginWithPassword(username, password, options = {}) {
60
+ const session = await (0, login_1.loginWithPassword)(username, password, options);
61
+ return new XiaomiCloud(session, options);
62
+ }
63
+ /**
64
+ * Logs in by scanning a QR code with the Mi Home app.
65
+ *
66
+ * @param options The callback that shows the QR code
67
+ * @returns The client
68
+ */
69
+ static async loginWithQrCode(options) {
70
+ const session = await (0, login_1.loginWithQrCode)(options);
71
+ return new XiaomiCloud(session, options);
72
+ }
73
+ /**
74
+ * @param server The regional server
75
+ * @returns The base URL of the API in that server
76
+ */
77
+ static apiUrl(server) {
78
+ return `https://${server === "cn" ? "" : `${server}.`}api.io.mi.com/app`;
79
+ }
80
+ /**
81
+ * Calls the API (signed and encrypted).
82
+ *
83
+ * @param server The regional server
84
+ * @param path The API path (e.g. `/v2/homeroom/gethome`)
85
+ * @param data The request data
86
+ * @returns The `result` of the response
87
+ */
88
+ async call(server, path, data) {
89
+ const url = XiaomiCloud.apiUrl(server) + path;
90
+ const nonce = (0, crypto_1.generateNonce)();
91
+ const key = (0, crypto_1.signedNonce)(this.session.ssecurity, nonce);
92
+ const fields = (0, crypto_1.encryptParams)(url, "POST", key, nonce, { data: typeof data === "string" ? data : JSON.stringify(data) }, this.session.ssecurity);
93
+ const response = await this.http.request(url, {
94
+ method: "POST",
95
+ query: fields,
96
+ headers: {
97
+ "Accept-Encoding": "identity",
98
+ "User-Agent": this.agent,
99
+ "Content-Type": "application/x-www-form-urlencoded",
100
+ "x-xiaomi-protocal-flag-cli": "PROTOCAL-HTTP2",
101
+ "MIOT-ENCRYPT-ALGORITHM": "ENCRYPT-RC4",
102
+ },
103
+ cookies: {
104
+ userId: this.session.userId,
105
+ yetAnotherServiceToken: this.session.serviceToken,
106
+ serviceToken: this.session.serviceToken,
107
+ locale: "en_GB",
108
+ timezone: "GMT+02:00",
109
+ is_daylight: "1",
110
+ dst_offset: "3600000",
111
+ channel: "MI_APP_STORE",
112
+ },
113
+ });
114
+ if (response.status === 401)
115
+ throw new errors_1.CloudSessionExpiredError();
116
+ if (response.status !== 200) {
117
+ throw new errors_1.CloudApiError(`${path} failed (HTTP ${response.status})`, response.status);
118
+ }
119
+ let json;
120
+ try {
121
+ json = JSON.parse((0, crypto_1.decryptRc4)(key, response.text));
122
+ }
123
+ catch {
124
+ // Errors may come unencrypted
125
+ try {
126
+ json = JSON.parse(response.text);
127
+ }
128
+ catch {
129
+ throw new errors_1.CloudApiError(`${path} returned an unexpected response`);
130
+ }
131
+ }
132
+ if (json.code !== undefined && json.code !== 0) {
133
+ throw new errors_1.CloudApiError(`${path} failed: ${json.message ?? json.code}`, json.code);
134
+ }
135
+ return json.result;
136
+ }
137
+ /**
138
+ * @param server The regional server
139
+ * @returns The homes of the user and the homes shared with them
140
+ */
141
+ async getHomes(server) {
142
+ const homes = [];
143
+ const own = await this.call(server, "/v2/homeroom/gethome", '{"fg": true, "fetch_share": true, "fetch_share_dev": true, "limit": 300, "app_ver": 7}');
144
+ for (const home of own?.homelist ?? []) {
145
+ homes.push({ homeId: String(home.id), owner: this.session.userId });
146
+ }
147
+ const count = await this.call(server, "/v2/user/get_device_cnt", '{ "fetch_own": true, "fetch_share": true}');
148
+ for (const home of count?.share?.share_family ?? []) {
149
+ homes.push({
150
+ homeId: String(home.home_id),
151
+ owner: String(home.home_owner),
152
+ });
153
+ }
154
+ return homes;
155
+ }
156
+ /**
157
+ * @param server The regional server
158
+ * @param home The home
159
+ * @returns The devices of the home
160
+ */
161
+ async getHomeDevices(server, home) {
162
+ 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}`);
163
+ return (result?.device_info ?? []).map((device) => ({
164
+ did: String(device.did),
165
+ name: String(device.name ?? ""),
166
+ model: String(device.model ?? ""),
167
+ token: String(device.token ?? ""),
168
+ localip: optionalString(device.localip),
169
+ mac: optionalString(device.mac),
170
+ isOnline: typeof device.isOnline === "boolean" ? device.isOnline : undefined,
171
+ server,
172
+ homeId: home.homeId,
173
+ homeOwner: home.owner,
174
+ }));
175
+ }
176
+ /**
177
+ * Lists the devices of the account, with their tokens.
178
+ *
179
+ * @param options The options
180
+ * @param options.servers The servers to check (all of them by default)
181
+ * @returns The devices
182
+ */
183
+ async getDevices(options = {}) {
184
+ const devices = new Map();
185
+ for (const server of options.servers ?? exports.CLOUD_SERVERS) {
186
+ let homes;
187
+ try {
188
+ homes = await this.getHomes(server);
189
+ }
190
+ catch (err) {
191
+ if (err instanceof errors_1.CloudSessionExpiredError)
192
+ throw err;
193
+ debug(`Unable to get the homes in ${server}: ${err}`);
194
+ continue;
195
+ }
196
+ const seen = new Set();
197
+ for (const home of homes) {
198
+ if (seen.has(home.homeId))
199
+ continue;
200
+ seen.add(home.homeId);
201
+ try {
202
+ for (const device of await this.getHomeDevices(server, home)) {
203
+ if (!devices.has(device.did))
204
+ devices.set(device.did, device);
205
+ }
206
+ }
207
+ catch (err) {
208
+ if (err instanceof errors_1.CloudSessionExpiredError)
209
+ throw err;
210
+ debug(`Unable to get the devices of home ${home.homeId} in ${server}: ${err}`);
211
+ }
212
+ }
213
+ }
214
+ return [...devices.values()];
215
+ }
216
+ /**
217
+ * Finds a device of the account (e.g. to know its token or its server).
218
+ *
219
+ * @param match The device ID, token or local IP of the device (the first one given that matches)
220
+ * @param match.did The device ID
221
+ * @param match.token The device token
222
+ * @param match.ip The local IP of the device
223
+ * @param options The options of {@link XiaomiCloud.getDevices}
224
+ * @param options.servers The servers to check (all of them by default)
225
+ * @returns The device, if found
226
+ */
227
+ async findDevice(match, options = {}) {
228
+ const devices = await this.getDevices(options);
229
+ const token = match.token?.toLowerCase();
230
+ return ((match.did !== undefined &&
231
+ devices.find((d) => d.did === String(match.did))) ||
232
+ (token && devices.find((d) => d.token.toLowerCase() === token)) ||
233
+ (match.ip && devices.find((d) => d.localip === match.ip)) ||
234
+ undefined);
235
+ }
236
+ /**
237
+ * Downloads a file (e.g. a map file from {@link XiaomiCloud.getMapFileUrl}).
238
+ *
239
+ * @param url The URL
240
+ * @returns The file contents
241
+ */
242
+ async download(url) {
243
+ const response = await this.http.request(url, { timeoutMs: 30_000 });
244
+ if (response.status !== 200) {
245
+ throw new errors_1.CloudError(`Unable to download the file (HTTP ${response.status})`);
246
+ }
247
+ return response.body;
248
+ }
249
+ /**
250
+ * Gets the URL of a map file (Roborock and Xiaomi vacuums). The map name comes from the device (`get_map_v1`).
251
+ *
252
+ * @param server The regional server of the device
253
+ * @param mapName The map name
254
+ * @returns The URL of the (gzipped) map file
255
+ */
256
+ async getMapFileUrl(server, mapName) {
257
+ const result = await this.call(server, "/home/getmapfileurl", `{"obj_name":"${mapName}"}`);
258
+ if (!result?.url)
259
+ throw new errors_1.CloudApiError(`No map file for ${mapName}`);
260
+ return result.url;
261
+ }
262
+ /**
263
+ * Gets the URL of a map file of the newer vacuums (Dreame, Viomi, Roidmi…).
264
+ *
265
+ * @param server The regional server of the device
266
+ * @param did The device ID
267
+ * @param mapName The map name
268
+ * @returns The URL of the map file
269
+ */
270
+ async getInterimFileUrl(server, did, mapName) {
271
+ const result = await this.call(server, "/v2/home/get_interim_file_url", `{"obj_name":"${this.session.userId}/${did}/${mapName}"}`);
272
+ if (!result?.url)
273
+ throw new errors_1.CloudApiError(`No map file for ${mapName}`);
274
+ return result.url;
275
+ }
276
+ }
277
+ exports.XiaomiCloud = XiaomiCloud;
278
+ /**
279
+ * @param value A value of the response
280
+ * @returns The value, if it's a non-empty string
281
+ */
282
+ function optionalString(value) {
283
+ return typeof value === "string" && value ? value : undefined;
284
+ }
285
+ //# sourceMapp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QAAQ,CAAC,MAAM,KAAK,GAAG,EAAE,CAAC;YAC5B,MAAM,IAAI,mBAAU,CAClB,qCAAqC,QAAQ,CAAC,MAAM,GAAG,CACxD,CAAC;QACJ,CAAC;QACD,OAAO,QAAQ,CAAC,IAAI,CAAC;IACvB,CAAC;IAED;;;;;;OAMG;IACH,KAAK,CAAC,aAAa,CACjB,MAA4B,EAC5B,OAAe;QAEf,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,IAAI,CAC5B,MAAM,EACN,qBAAqB,EACrB,gBAAgB,OAAO,IAAI,CAC5B,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;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,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
+ {"version":3,"file":"crypto.js","sourceRoot":"","sources":["../../../src/lib/cloud/crypto.ts"],"names":[],"mappings":";;;;;AAiBA,kBAeC;AASD,sCAOC;AAOD,kCAMC;AASD,oCAWC;AAOD,gCAIC;AAOD,gCAKC;AAaD,sCAqBC;AA1ID;;;;;GAKG;AACH,8DAAiC;AAEjC;;;;;;;;GAQG;AACH,SAAgB,GAAG,CAAC,GAAW,EAAE,IAAY,EAAE,IAAI,GAAG,IAAI;IACxD,MAAM,CAAC,GAAG,IAAI,UAAU,CAAC,GAAG,CAAC,CAAC;IAC9B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE;QAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;IACvC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC;QACpC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC,GAAG,GAAG,CAAC,MAAM,CAAC,CAAC,GAAG,IAAI,CAAC;QAC5C,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC9B,CAAC;IACD,MAAM,GAAG,GAA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ACR,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,QAAQ,CAAC,EAC1B,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,QAAQ,CAAC,CAC/B,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;AACrB,CAAC;AAED;;;;;;;;;;GAUG;AACH,SAAgB,aAAa,CAC3B,GAAW,EACX,MAAc,EACd,GAAW,EACX,KAAa,EACb,MAA8B,EAC9B,SAAiB;IAEjB,MAAM,MAAM,GAA2B;QACrC,GAAG,MAAM;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,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,159 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.HttpSession = void 0;
4
+ exports.parseXiaomiJson = parseXiaomiJson;
5
+ const MAX_REDIRECTS = 10;
6
+ /**
7
+ * A minimal HTTP session on top of `fetch`, with a cookie jar and manual redirects
8
+ * (so the cookies set on every hop of the login flows are kept).
9
+ */
10
+ class HttpSession {
11
+ fetchImpl;
12
+ cookies = [];
13
+ constructor(fetchImpl = fetch) {
14
+ this.fetchImpl = fetchImpl;
15
+ }
16
+ /**
17
+ * @param name The cookie name
18
+ * @param value The cookie value
19
+ * @param domain The domain the cookie applies to (and its subdomains)
20
+ */
21
+ setCookie(name, value, domain) {
22
+ domain = domain.replace(/^\./, "");
23
+ this.cookies = this.cookies.filter((c) => !(c.name === name && c.domain === domain));
24
+ this.cookies.push({ name, value, domain });
25
+ }
26
+ /**
27
+ * @param name The cookie name
28
+ * @param domain If set, only the cookies of this domain (or its parents) are considered
29
+ * @returns The value of the most recently set matching cookie
30
+ */
31
+ getCookie(name, domain) {
32
+ const host = domain?.replace(/^\./, "");
33
+ return this.cookies
34
+ .filter((c) => c.name === name && (!host || domainMatches(host, c.domain)))
35
+ .at(-1)?.value;
36
+ }
37
+ async request(url, options = {}) {
38
+ let method = options.method ?? "GET";
39
+ let body = options.form
40
+ ? new URLSearchParams(options.form).toString()
41
+ : undefined;
42
+ let current = withQuery(url, options.query);
43
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
44
+ const headers = { ...options.headers };
45
+ if (body !== undefined) {
46
+ headers["Content-Type"] = "application/x-www-form-urlencoded";
47
+ }
48
+ const cookie = this.cookieHeader(current, options.cookies);
49
+ if (cookie)
50
+ headers["Cookie"] = cookie;
51
+ const response = await this.fetchImpl(current, {
52
+ method,
53
+ headers,
54
+ body,
55
+ redirect: "manual",
56
+ signal: AbortSignal.timeout(options.timeoutMs ?? 15_000),
57
+ });
58
+ this.storeCookies(current, response.headers);
59
+ const location = response.headers.get("location");
60
+ if (options.followRedirects !== false &&
61
+ response.status >= 300 &&
62
+ response.status < 400 &&
63
+ location) {
64
+ current = new URL(location, current).toString();
65
+ if (response.status !== 307 && response.status !== 308) {
66
+ method = "GET";
67
+ body = undefined;
68
+ }
69
+ continue;
70
+ }
71
+ const buffer = Buffer.from(await response.arrayBuffer());
72
+ return {
73
+ status: response.status,
74
+ url: current,
75
+ headers: response.headers,
76
+ body: buffer,
77
+ text: buffer.toString("utf8"),
78
+ };
79
+ }
80
+ throw new Error(`Too many redirects (${url})`);
81
+ }
82
+ cookieHeader(url, extra = {}) {
83
+ const host = new URL(url).hostname;
84
+ const values = new Map();
85
+ for (const c of this.cookies) {
86
+ if (domainMatches(host, c.domain))
87
+ values.set(c.name, c.value);
88
+ }
89
+ for (const [name, value] of Object.entries(extra))
90
+ values.set(name, value);
91
+ return [...values].map(([name, value]) => `${name}=${value}`).join("; ");
92
+ }
93
+ storeCookies(url, headers) {
94
+ const host = new URL(url).hostname;
95
+ for (const header of headers.getSetCookie?.() ?? []) {
96
+ const [pair, ...attributes] = header.split(";");
97
+ const separator = pair.indexOf("=");
98
+ if (separator <= 0)
99
+ continue;
100
+ const name = pair.slice(0, separator).trim();
101
+ const value = pair.slice(separator + 1).trim();
102
+ let domain = host;
103
+ let expired = false;
104
+ for (const attribute of attributes) {
105
+ const [key, attrValue = ""] = attribute.split("=");
106
+ switch (key.trim().toLowerCase()) {
107
+ case "domain":
108
+ domain = attrValue.trim().replace(/^\./, "") || host;
109
+ break;
110
+ case "max-age":
111
+ expired ||= Number(attrValue) <= 0;
112
+ break;
113
+ case "expires":
114
+ expired ||= Date.parse(attrValue) < Date.now();
115
+ break;
116
+ }
117
+ }
118
+ if (expired) {
119
+ this.cookies = this.cookies.filter((c) => !(c.name === name && c.domain === domain));
120
+ }
121
+ else {
122
+ this.setCookie(name, value, domain);
123
+ }
124
+ }
125
+ }
126
+ }
127
+ exports.HttpSession = HttpSession;
128
+ /**
129
+ * @param host The host of the request
130
+ * @param domain The domain of the cookie
131
+ * @returns Whether the cookie applies to the host
132
+ */
133
+ function domainMatches(host, domain) {
134
+ return host === domain || host.endsWith(`.${domain}`);
135
+ }
136
+ /**
137
+ * @param url The URL
138
+ * @param query The params to add to the query string
139
+ * @returns The URL with the params
140
+ */
141
+ function withQuery(url, query) {
142
+ if (!query)
143
+ return url;
144
+ const target = new URL(url);
145
+ for (const [key, value] of Object.entries(query)) {
146
+ target.searchParams.set(key, value);
147
+ }
148
+ return target.toString();
149
+ }
150
+ /**
151
+ * Parses a JSON response of account.xiaomi.com, which are prefixed with `&&&START&&&`.
152
+ *
153
+ * @param text The response text
154
+ * @returns The parsed JSON
155
+ */
156
+ function parseXiaomiJson(text) {
157
+ return JSON.parse(text.replace("&&&START&&&", ""));
158
+ }
159
+ //# sourceMappingURL=http.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http.js","sourceRoot":"","sources":["../../../src/lib/cloud/http.ts"],"names":[],"mappings":";;;AAwMA,0CAEC;AAxKD,MAAM,aAAa,GAAG,EAAE,CAAC;AAEzB;;;GAGG;AACH,MAAa,WAAW;IAGO;IAFrB,OAAO,GAAa,E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