-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathindex.js
444 lines (400 loc) · 14.5 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
const crypto = require('crypto');
const is = require('is');
const got = require('got');
const randomize = require('randomatic');
const sortObject = require('sort-keys-recursive');
const debug = require('debug')('@tuyapi/cloud');
const NodeRSA = require('node-rsa');
const {v4: uuidv4} = require('uuid');
// Error object
class TuyaCloudRequestError extends Error {
constructor(options) {
super();
this.code = options.code;
this.message = options.message;
}
}
/**
* A TuyaCloud object.
* Providing `apiEtVersion` option means that the new sign mechanism (HMAC-SHA256)
* instead of old (MD5) will be used. This also makes `secret2` and `certSign` mandatory.
* @class
* @param {Object} options construction options
* @param {String} options.key API key
* @param {String} options.secret API secret
* @param {String} [options.apiEtVersion]
* Tag existing in new mobile api version (as const '0.0.1'),
* @param {String} [options.secret2]
* Second API secret token, stored in BMP file (mandatory if apiEtVersion is specified)
* @param {String} [options.certSign]
* App certificate SHA256 (mandatory if apiEtVersion is specified)
* @param {String} [options.region='AZ'] region (AZ=Americas, AY=Asia, EU=Europe, IN=India) - or a region saved earlier
* @param {String} [options.endpoint] endpoint stored after a former loginEx call (mostly together with sid and region)
* @param {String} [options.deviceID] ID of device calling API (defaults to a random value)
* @param {String} [options.ttid] app id (defaults to 'tuya'), alternative is "smart_life" depending on used App
* @param {String} [options.sid] session id if obtained in the past to reuse (optional)
* @example <caption>Using the MD5 signing mechanism:</caption>
* const api = new Cloud({key: 'your-api-key', secret: 'your-api-secret'})
* @example <caption>Using the HMAC-SHA256 signing mechanism:</caption>
* const api = new Cloud({key: 'your-api-key', secret: 'your-api-secret',
* apiEtVersion: '0.0.1', secret2: 'your-apm-secret2',
* certSign: 'your-api-cert-sign'})
*/
function TuyaCloud(options) {
// Set to empty object if undefined
options = is.undefined(options) ? {} : options;
// Key and secret
if (!options.key || !options.secret ||
options.key.length !== 20 || options.secret.length !== 32) {
throw new Error('Invalid format for key or secret.');
} else {
this.key = options.key;
this.secret = options.secret;
}
// New API: check mandatory params
if (options.apiEtVersion) {
debug('using new API');
if (!options.secret2 || !options.certSign ||
// OEM apps (such as Ledvance and Sylvania) use the single letter "A" instead of a certificate signature.
options.secret2.length !== 32 || (options.certSign.length !== 95 && (options.certSign.length != 1 || options.certSign != 'A'))) {
throw new Error('New API: invalid format for secret2 or certSign');
} else {
this.keyHmac = options.certSign + '_' + options.secret2 + '_' + options.secret;
this.apiEtVersion = options.apiEtVersion;
this.ttid = options.ttid || 'tuya';
debug('key HMAC: ' + this.keyHmac);
}
}
// Device ID
if (is.undefined(options.deviceID)) {
this.deviceID = randomize('a0', 44, options);
} else {
this.deviceID = options.deviceID;
}
// Endpoint
if (!is.undefined(options.endpoint) && !is.undefined(options.region)) {
this.endpoint = options.endpoint;
this.region = options.region;
}
// Region
else if (is.undefined(options.region) || options.region === 'AZ') {
this.region = 'AZ';
this.endpoint = 'https://a1.tuyaus.com/api.json';
} else if (options.region === 'AY') {
this.region = 'AY';
this.endpoint = 'https://a1.tuyacn.com/api.json';
} else if (options.region === 'EU') {
this.region = 'EU';
this.endpoint = 'https://a1.tuyaeu.com/api.json';
} else if (options.region === 'IN') {
this.region = 'IN';
this.endpoint = 'https://a1.tuyain.com/api.json';
} else {
throw new Error('Bad region identifier.');
}
// Session ID
if (!is.undefined(options.sid)) {
this.sid = options.sid;
}
}
/**
* Slices and dices an MD5 digest
* to conform to Tuya's spec.
* Don't ask why this is needed.
* @param {String} data to hash
* @returns {String} resulting digest
* @private
*/
TuyaCloud.prototype._mobileHash = function (data) {
const preHash = md5(data);
return preHash.slice(8, 16) +
preHash.slice(0, 8) +
preHash.slice(24, 32) +
preHash.slice(16, 24);
};
/**
* Sends an API request
* @param {Object} options
* request options
* @param {String} options.action
* API action to invoke (for example, 'tuya.cloud.device.token.create')
* @param {Object} [options.data={}]
* data to send in the request body
* @param {String} [options.gid]
* Group ID URL GET param (necessary for device-related actions)
* @param {String} [options.version='1.0']
* API version to use for the request (some IR related calls require '5.0' as version)
* @param {Boolean} [options.requiresSID=true]
* set to false if the request doesn't require a session ID
* @example
* // generate a new token
* api.request({action: 'tuya.m.device.token.create',
* data: {'timeZone': '-05:00'}}).then(token => console.log(token))
* @returns {Promise<Object>} A Promise that contains the response body parsed as JSON
*/
TuyaCloud.prototype.request = async function (options) {
// Set to empty object if undefined
options = is.undefined(options) ? {} : options;
// Check arguments
if (is.undefined(options.requiresSID)) {
options.requiresSID = true;
}
if (!options.action) {
throw new Error('Must specify an action to call.');
}
// Must have SID if we need it later
if (!this.sid && options.requiresSID) {
throw new Error('Must call login() first.');
}
const d = new Date();
const pairs = {a: options.action,
deviceId: this.deviceID,
os: 'Android',
lang: 'en',
v: options.version || '1.0',
clientId: this.key,
time: Math.round(d.getTime() / 1000)};
if (options.data) {
pairs.postData = JSON.stringify(options.data);
}
if (options.gid) {
pairs.gid = options.gid;
}
if (this.apiEtVersion) {
pairs.et = this.apiEtVersion;
pairs.ttid = this.ttid;
pairs.appVersion = '3.8.5';
pairs.appRnVersion = '5.11';
pairs.platform = 'Android';
pairs.requestId = uuidv4();
}
if (options.requiresSID) {
pairs.sid = this.sid;
}
// Generate signature for request
const valuesToSign = ['a', 'v', 'lat', 'lon', 'lang', 'deviceId', 'imei',
'imsi', 'appVersion', 'ttid', 'isH5', 'h5Token', 'os',
'clientId', 'postData', 'time', 'requestId', 'n4h5', 'sid',
'sp', 'et'];
const sortedPairs = sortObject(pairs);
let strToSign = '';
// Create string to sign
for (const key in sortedPairs) {
if (!valuesToSign.includes(key) || is.empty(pairs[key])) {
continue;
} else if (key === 'postData') {
if (strToSign) {
strToSign += '||';
}
strToSign += key;
strToSign += '=';
strToSign += this._mobileHash(pairs[key]);
} else {
if (strToSign) {
strToSign += '||';
}
strToSign += key;
strToSign += '=';
strToSign += pairs[key];
}
}
if (this.apiEtVersion) {
// New API, use HMAC-SHA256
debug('strToSign: ' + strToSign);
pairs.sign = crypto.createHmac('sha256', this.keyHmac)
.update(strToSign).digest('hex');
} else {
// Add secret
strToSign += '||';
strToSign += this.secret;
debug('strToSign: ' + strToSign);
// Sign string
pairs.sign = md5(strToSign);
}
try {
debug('Sending parameters:');
debug(JSON.stringify(pairs));
const apiResult = await got(this.endpoint, {
searchParams: pairs,
timeout: {
request: 10000
}
});
const data = JSON.parse(apiResult.body);
debug('Received response:');
debug(apiResult.body);
if (data.success === false) {
throw new TuyaCloudRequestError({code: data.errorCode, message: data.errorMsg});
}
return data.result;
} catch (err) {
throw err;
}
};
/**
* Helper to register a new user. If user already exists, it instead attempts to log in.
* @param {Object} options
* register options
* @param {String} options.email
* email to register
* @param {String} options.password
* password for new user
* @example
* api.register({email: '[email protected]',
password: 'example-password'})
.then(sid => console.log('Session ID: ', sid))
* @returns {Promise<String>} A Promise that contains the session ID
*/
TuyaCloud.prototype.register = async function (options) {
try {
const apiResult = await this.request({action: 'tuya.m.user.email.register',
data: {countryCode: this.region,
email: options.email,
passwd: md5(options.password)},
requiresSID: false});
this.sid = apiResult.sid;
return this.sid;
} catch (err) {
if (err.code === 'USER_NAME_IS_EXIST') {
return this.login(options);
}
throw err;
}
};
/**
* Helper to log in a user.
* @param {Object} options
* register options
* @param {String} options.email
* user's email
* @param {String} options.password
* user's password
* @param {String} options.returnFullLoginResponse
* true to return the full login response, false to return just the session ID* @example
* api.login({email: '[email protected]',
password: 'example-password'}).then(sid => console.log('Session ID: ', sid))
* @returns {Promise<String|Object>} A Promise that contains the session ID
*/
TuyaCloud.prototype.login = async function (options) {
try {
const apiResult = await this.request({action: 'tuya.m.user.email.password.login',
data: {countryCode: this.region,
email: options.email,
passwd: md5(options.password)},
requiresSID: false});
this.sid = apiResult.sid;
if (is.boolean(options.returnFullLoginResponse) && options.returnFullLoginResponse) {
return apiResult;
}
return this.sid;
} catch (err) {
throw err;
}
};
/**
* Helper to log in a user using enhanced login process (using empheral asymmetric RSA key)
* @param {Object} options
* register options
* @param {String} options.email
* user's email
* @param {String} options.password
* user's password
* @param {String} options.returnFullLoginResponse
* true to return the full login response, false to return just the session ID
* api.loginEx({email: '[email protected]',
password: 'example-password'}).then(sid => console.log('Session ID: ', sid))
* @returns {Promise<String|Object>} A Promise that contains the session ID
*/
TuyaCloud.prototype.loginEx = async function (options) {
try {
// Get token and empheral RSA public key
const token = await this.request({action: 'tuya.m.user.email.token.create',
data: {countryCode: this.region,
email: options.email},
requiresSID: false});
// Create RSA public key: match the settings from mobile app (no padding)
const key = new NodeRSA({}, {
encryptionScheme: {
scheme: 'pkcs1',
padding: crypto.constants.RSA_NO_PADDING
}
});
key.importKey({
n: token.publicKey,
e: Number(token.exponent)
}, 'components-public');
const encryptedPass = key.encrypt(Buffer.from(md5(options.password)), 'hex');
const apiResult = await this.request({action: 'tuya.m.user.email.password.login',
data: {countryCode: this.region,
email: options.email,
passwd: encryptedPass,
ifencrypt: 1,
options: {group: 1},
token: token.token},
requiresSID: false});
// Change endpoint if necessary
// (the SID will only be vaild in endpoint given in response)
if (apiResult.domain.mobileApiUrl &&
!this.endpoint.startsWith(apiResult.domain.mobileApiUrl)) {
debug('Changing endpoints after logging: %s -> %s/api.json',
this.endpoint, apiResult.domain.mobileApiUrl);
this.endpoint = apiResult.domain.mobileApiUrl + '/api.json';
this.region = apiResult.domain.regionCode;
}
this.sid = apiResult.sid;
if (is.boolean(options.returnFullLoginResponse) && options.returnFullLoginResponse) {
return apiResult;
}
return this.sid;
} catch (err) {
throw err;
}
};
/**
* Helper to wait for device(s) to be registered.
* It's possible to register multiple devices at once,
* so this returns an array.
* @param {Object} options
* options
* @param {String} options.token
* token being registered
* @param {Number} [options.devices=1]
* number of devices to wait for
* @example
* api.waitForToken({token: token.token}).then(result => {
* let device = result[0];
* console.log('Params:');
* console.log(JSON.stringify({id: device['id'], localKey: device['localKey']}));
* });
* @returns {Promise<Array>} A Promise that contains an array of registered devices
*/
TuyaCloud.prototype.waitForToken = function (options) {
if (!options.devices) {
options.devices = 1;
}
return new Promise(async (resolve, reject) => {
for (let i = 0; i < 200; i++) {
try {
/* eslint-disable-next-line no-await-in-loop */
const tokenResult = await this.request({action: 'tuya.m.device.list.token',
data: {token: options.token}});
if (tokenResult.length >= options.devices) {
return resolve(tokenResult);
}
// Wait for 200 ms
/* eslint-disable-next-line no-await-in-loop */
await delay(200);
} catch (err) {
reject(err);
}
}
reject(new Error('Timed out waiting for device(s) to connect to cloud'));
});
};
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function md5(data) {
return crypto.createHash('md5').update(data).digest('hex');
}
module.exports = TuyaCloud;