forked from Apollon77/alexa-cookie
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalexa-cookie.js
More file actions
789 lines (709 loc) · 33.6 KB
/
Copy pathalexa-cookie.js
File metadata and controls
789 lines (709 loc) · 33.6 KB
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
/**
* partly based on Amazon Alexa Remote Control (PLAIN shell)
* http://blog.loetzimmer.de/2017/10/amazon-alexa-hort-auf-die-shell-echo.html AND on
* https://github.com/thorsten-gehrig/alexa-remote-control
* and much enhanced ...
*/
const https = require('https');
const querystring = require('querystring');
const url = require('url');
const os = require('os');
const cookieTools = require('cookie');
const amazonProxy = require('./lib/proxy.js');
const defaultAmazonPage = 'amazon.de';
const defaultUserAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36';
const defaultUserAgentLinux = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36';
//const defaultUserAgentMacOs = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36';
const defaultAcceptLanguage = 'de-DE';
const apiCallVersion = '2.2.485407.0';
const apiCallUserAgent = 'AmazonWebView/Amazon Alexa/2.2.485407.0/iOS/15.5/iPhone';
const defaultAppName = 'ioBroker Alexa2';
const csrfOptions = [
'/api/language',
'/spa/index.html',
'/api/devices-v2/device?cached=false',
'/templates/oobe/d-device-pick.handlebars',
'/api/strings'
];
function AlexaCookie() {
if (!(this instanceof AlexaCookie)) return new AlexaCookie();
let proxyServer;
let _options;
let Cookie = '';
const addCookies = (Cookie, headers) => {
if (!headers || !headers['set-cookie']) return Cookie;
const cookies = cookieTools.parse(Cookie || '');
for (let cookie of headers['set-cookie']) {
cookie = cookie.match(/^([^=]+)=([^;]+);.*/);
if (cookie && cookie.length === 3) {
if (cookie[1] === 'ap-fid' && cookie[2] === '""') continue;
if (cookies[cookie[1]] && cookies[cookie[1]] !== cookie[2]) {
_options.logger && _options.logger(`Alexa-Cookie: Update Cookie ${cookie[1]} = ${cookie[2]}`);
} else if (!cookies[cookie[1]]) {
_options.logger && _options.logger(`Alexa-Cookie: Add Cookie ${cookie[1]} = ${cookie[2]}`);
}
cookies[cookie[1]] = cookie[2];
}
}
Cookie = '';
for (const name of Object.keys(cookies)) {
Cookie += `${name}=${cookies[name]}; `;
}
Cookie = Cookie.replace(/[; ]*$/, '');
return Cookie;
};
const request = (options, info, callback) => {
_options.logger && _options.logger(`Alexa-Cookie: Sending Request with ${JSON.stringify(options)}`);
if (typeof info === 'function') {
callback = info;
info = {
requests: []
};
}
let removeContentLength;
if (options.headers && options.headers['Content-Length']) {
if (!options.body) delete options.headers['Content-Length'];
} else if (options.body) {
if (!options.headers) options.headers = {};
options.headers['Content-Length'] = options.body.length;
removeContentLength = true;
}
const req = https.request(options, (res) => {
let body = '';
info.requests.push({options: options, response: res});
if (options.followRedirects !== false && res.statusCode >= 300 && res.statusCode < 400) {
_options.logger && _options.logger(`Alexa-Cookie: Response (${res.statusCode})${res.headers.location ? ` - Redirect to ${res.headers.location}` : ''}`);
//options.url = res.headers.location;
const u = url.parse(res.headers.location);
if (u.host) options.host = u.host;
options.path = u.path;
options.method = 'GET';
options.body = '';
options.headers.Cookie = Cookie = addCookies(Cookie, res.headers);
res.socket && res.socket.end();
return request(options, info, callback);
} else {
_options.logger && _options.logger(`Alexa-Cookie: Response (${res.statusCode})`);
res.on('data', (chunk) => {
body += chunk;
});
res.on('end', () => {
if (removeContentLength) delete options.headers['Content-Length'];
res.socket && res.socket.end();
callback && callback(0, res, body, info);
});
}
});
req.on('error', (e) => {
if (typeof callback === 'function' && callback.length >= 2) {
return callback(e, null, null, info);
}
});
if (options && options.body) {
req.write(options.body);
}
req.end();
};
const getFields = body => {
body = body.replace(/[\n\r]/g, ' ');
let re = /^.*?("hidden"\s*name=".*$)/;
const ar = re.exec(body);
if (!ar || ar.length < 2) return {};
let h;
re = /.*?name="([^"]+)"[\s^\s]*value="([^"]+).*?"/g;
const data = {};
while ((h = re.exec(ar[1])) !== null) {
if (h[1] !== 'rememberMe') {
data[h[1]] = h[2];
}
}
return data;
};
const initConfig = () => {
_options.amazonPage = _options.amazonPage || defaultAmazonPage;
if (_options.formerRegistrationData && _options.formerRegistrationData.amazonPage) _options.amazonPage = _options.formerRegistrationData.amazonPage;
_options.logger && _options.logger(`Alexa-Cookie: Use as Login-Amazon-URL: ${_options.amazonPage}`);
_options.baseAmazonPage = _options.baseAmazonPage || 'amazon.com';
_options.logger && _options.logger(`Alexa-Cookie: Use as Base-Amazon-URL: ${_options.baseAmazonPage}`);
_options.deviceAppName = _options.deviceAppName || defaultAppName;
_options.logger && _options.logger(`Alexa-Cookie: Use as Device-App-Name: ${_options.deviceAppName}`);
if (!_options.baseAmazonPageHandle && _options.baseAmazonPageHandle !== '') {
const amazonDomain = _options.baseAmazonPage.substr(_options.baseAmazonPage.lastIndexOf('.') + 1);
if (amazonDomain === 'jp') {
_options.baseAmazonPageHandle = `_${amazonDomain}`;
}
else if (amazonDomain !== 'com') {
//_options.baseAmazonPageHandle = '_' + amazonDomain;
_options.baseAmazonPageHandle = '';
}
else {
_options.baseAmazonPageHandle = '';
}
}
if (!_options.userAgent) {
const platform = os.platform();
if (platform === 'win32') {
_options.userAgent = defaultUserAgent;
}
/*else if (platform === 'darwin') {
_options.userAgent = defaultUserAgentMacOs;
}*/
else {
_options.userAgent = defaultUserAgentLinux;
}
}
_options.logger && _options.logger(`Alexa-Cookie: Use as User-Agent: ${_options.userAgent}`);
_options.acceptLanguage = _options.acceptLanguage || defaultAcceptLanguage;
_options.logger && _options.logger(`Alexa-Cookie: Use as Accept-Language: ${_options.acceptLanguage}`);
if (_options.setupProxy && !_options.proxyOwnIp) {
_options.logger && _options.logger('Alexa-Cookie: Own-IP Setting missing for Proxy. Disabling!');
_options.setupProxy = false;
}
if (_options.setupProxy) {
_options.setupProxy = true;
_options.proxyPort = _options.proxyPort || 0;
_options.proxyListenBind = _options.proxyListenBind || '0.0.0.0';
_options.logger && _options.logger(`Alexa-Cookie: Proxy-Mode enabled if needed: ${_options.proxyOwnIp}:${_options.proxyPort} to listen on ${_options.proxyListenBind}`);
} else {
_options.setupProxy = false;
_options.logger && _options.logger('Alexa-Cookie: Proxy mode disabled');
}
_options.proxyLogLevel = _options.proxyLogLevel || 'warn';
_options.amazonPageProxyLanguage = _options.amazonPageProxyLanguage || 'de_DE';
if (_options.formerRegistrationData) _options.proxyOnly = true;
};
const getCSRFFromCookies = (cookie, _options, callback) => {
// get CSRF
const csrfUrls = csrfOptions;
function csrfTry() {
const path = csrfUrls.shift();
const options = {
'host': `alexa.${_options.amazonPage}`,
'path': path,
'method': 'GET',
'headers': {
'DNT': '1',
'User-Agent': _options.userAgent,
'Connection': 'keep-alive',
'Referer': `https://alexa.${_options.amazonPage}/spa/index.html`,
'Cookie': cookie,
'Accept': '*/*',
'Origin': `https://alexa.${_options.amazonPage}`
}
};
_options.logger && _options.logger(`Alexa-Cookie: Step 4: get CSRF via ${path}`);
request(options, (error, response) => {
cookie = addCookies(cookie, response ? response.headers : null);
const ar = /csrf=([^;]+)/.exec(cookie);
const csrf = ar ? ar[1] : undefined;
_options.logger && _options.logger(`Alexa-Cookie: Result: csrf=${csrf}, Cookie=${cookie}`);
if (!csrf && csrfUrls.length) {
csrfTry();
return;
}
callback && callback(null, {
cookie: cookie,
csrf: csrf
});
});
}
csrfTry();
};
this.generateAlexaCookie = (email, password, __options, callback) => {
if (email !== undefined && typeof email !== 'string') {
callback = __options;
__options = password;
password = email;
email = null;
}
if (password !== undefined && typeof password !== 'string') {
callback = __options;
__options = password;
password = null;
}
if (typeof __options === 'function') {
callback = __options;
__options = {};
}
_options = __options;
if (!email || !password) {
__options.proxyOnly = true;
}
initConfig();
if (!_options.proxyOnly) {
// get first cookie and write redirection target into referer
const options = {
host: `alexa.${_options.amazonPage}`,
path: '',
method: 'GET',
headers: {
'DNT': '1',
'Upgrade-Insecure-Requests': '1',
'User-Agent': _options.userAgent,
'Accept-Language': _options.acceptLanguage,
'Connection': 'keep-alive',
'Accept': '*/*'
},
};
_options.logger && _options.logger('Alexa-Cookie: Step 1: get first cookie and authentication redirect');
request(options, (error, response, body, info) => {
if (error) {
callback && callback(error, null);
return;
}
const lastRequestOptions = info.requests[info.requests.length - 1].options;
// login empty to generate session
Cookie = addCookies(Cookie, response.headers);
const options = {
host: `www.${_options.amazonPage}`,
path: '/ap/signin',
method: 'POST',
headers: {
'DNT': '1',
'Upgrade-Insecure-Requests': '1',
'User-Agent': _options.userAgent,
'Accept-Language': _options.acceptLanguage,
'Connection': 'keep-alive',
'Content-Type': 'application/x-www-form-urlencoded',
'Referer': `https://${lastRequestOptions.host}${lastRequestOptions.path}`,
'Cookie': Cookie,
'Accept': '*/*'
},
gzip: true,
body: querystring.stringify(getFields(body))
};
_options.logger && _options.logger('Alexa-Cookie: Step 2: login empty to generate session');
request(options, (error, response, body) => {
if (error) {
callback && callback(error, null);
return;
}
// login with filled out form
// !!! referer now contains session in URL
options.host = `www.${_options.amazonPage}`;
options.path = '/ap/signin';
options.method = 'POST';
options.headers.Cookie = Cookie = addCookies(Cookie, response.headers);
const ar = options.headers.Cookie.match(/session-id=([^;]+)/);
options.headers.Referer = `https://www.${_options.amazonPage}/ap/signin/${ar[1]}`;
options.body = getFields(body);
options.body.email = email || '';
options.body.password = password || '';
options.body = querystring.stringify(options.body, null, null, {encodeURIComponent: encodeURIComponent});
_options.logger && _options.logger('Alexa-Cookie: Step 3: login with filled form, referer contains session id');
request(options, (error, response, body, info) => {
if (error) {
callback && callback(error, null);
return;
}
const lastRequestOptions = info.requests[info.requests.length - 1].options;
// check whether the login has been successful or exit otherwise
if (!lastRequestOptions.host.startsWith('alexa') || !lastRequestOptions.path.endsWith('.html')) {
let errMessage = 'Login unsuccessfull. Please check credentials.';
const amazonMessage = body.match(/auth-warning-message-box[\S\s]*"a-alert-heading">([^<]*)[\S\s]*<li><[^>]*>\s*([^<\n]*)\s*</);
if (amazonMessage && amazonMessage[1] && amazonMessage[2]) {
errMessage = `Amazon-Login-Error: ${amazonMessage[1]}: ${amazonMessage[2]}`;
}
if (_options.setupProxy) {
if (proxyServer) {
errMessage += ` You can try to get the cookie manually by opening http://${_options.proxyOwnIp}:${_options.proxyPort}/ with your browser.`;
} else {
amazonProxy.initAmazonProxy(_options, prepareResult,
(server) => {
if (!server) {
return callback && callback(new Error('Proxy could not be initialized'), null);
}
proxyServer = server;
if (!_options.proxyPort || _options.proxyPort === 0) {
_options.proxyPort = proxyServer.address().port;
}
errMessage += ` You can try to get the cookie manually by opening http://${_options.proxyOwnIp}:${_options.proxyPort}/ with your browser.`;
callback && callback(new Error(errMessage), null);
}
);
return;
}
}
callback && callback(new Error(errMessage), null);
return;
}
return getCSRFFromCookies(Cookie, _options, callback);
});
});
});
} else {
amazonProxy.initAmazonProxy(_options, prepareResult, (server) => {
if (!server) {
callback && callback(new Error('Proxy Server could not be initialized. Check Logs.'), null);
return;
}
proxyServer = server;
if (!_options.proxyPort || _options.proxyPort === 0) {
_options.proxyPort = proxyServer.address().port;
}
const errMessage = `You can try to get the cookie manually by opening http://${_options.proxyOwnIp}:${_options.proxyPort}/ with your browser.`;
callback && callback(new Error(errMessage), null);
});
}
function prepareResult(err, data) {
if (err || !data.authorization_code) {
callback && callback(err, data.loginCookie);
return;
}
handleTokenRegistration(_options, data, callback);
}
};
this.getDeviceAppName = () => {
return (_options && _options.deviceAppName) || defaultAppName;
};
const handleTokenRegistration = (_options, loginData, callback) => {
_options.logger && _options.logger(`Handle token registration Start: ${JSON.stringify(loginData)}`);
loginData.deviceAppName = _options.deviceAppName;
let deviceSerial;
if (!_options.formerRegistrationData || !_options.formerRegistrationData.deviceSerial) {
const deviceSerialBuffer = Buffer.alloc(16);
for (let i = 0; i < 16; i++) {
deviceSerialBuffer.writeUInt8(Math.floor(Math.random() * 255), i);
}
deviceSerial = deviceSerialBuffer.toString('hex');
} else {
_options.logger && _options.logger('Proxy Init: reuse deviceSerial from former data');
deviceSerial = _options.formerRegistrationData.deviceSerial;
}
loginData.deviceSerial = deviceSerial;
const cookies = cookieTools.parse(loginData.loginCookie);
Cookie = loginData.loginCookie;
/*
Register App
*/
const registerData = {
'requested_extensions': [
'device_info',
'customer_info'
],
'cookies': {
'website_cookies': [
/*{
"Value": cookies["session-id-time"],
"Name": "session-id-time"
}*/
],
'domain': `.${_options.baseAmazonPage}`
},
'registration_data': {
'domain': 'Device',
'app_version': apiCallVersion,
'device_type': 'A2IVLV5VM2W81',
'device_name': '%FIRST_NAME%\u0027s%DUPE_STRATEGY_1ST%ioBroker Alexa2',
'os_version': '15.5',
'device_serial': deviceSerial,
'device_model': 'iPhone',
'app_name': _options.deviceAppName,
'software_version': '1'
},
'auth_data': {
// Filled below
},
'user_context_map': {
'frc': cookies.frc
},
'requested_token_type': [
'bearer',
'mac_dms',
'website_cookies'
]
};
if (loginData.accessToken) {
registerData.auth_data = {
'access_token': loginData.accessToken
};
} else if (loginData.authorization_code && loginData.verifier) {
registerData.auth_data = {
'client_id' : loginData.deviceId,
'authorization_code' : loginData.authorization_code,
'code_verifier' : loginData.verifier,
'code_algorithm' : 'SHA-256',
'client_domain' : 'DeviceLegacy'
};
}
for (const key of Object.keys(cookies)) {
registerData.cookies.website_cookies.push({
'Value': cookies[key],
'Name': key
});
}
const options = {
host: `api.${_options.baseAmazonPage}`,
path: '/auth/register',
method: 'POST',
headers: {
'User-Agent': apiCallUserAgent,
'Accept-Language': _options.acceptLanguage,
'Accept-Charset': 'utf-8',
'Connection': 'keep-alive',
'Content-Type': 'application/json',
'Cookie': loginData.loginCookie,
'Accept': 'application/json',
'x-amzn-identity-auth-domain': `api.${_options.baseAmazonPage}`
},
body: JSON.stringify(registerData)
};
_options.logger && _options.logger('Alexa-Cookie: Register App');
_options.logger && _options.logger(JSON.stringify(options));
request(options, (error, response, body) => {
if (error) {
callback && callback(error, null);
return;
}
try {
if (typeof body !== 'object') body = JSON.parse(body);
} catch (err) {
_options.logger && _options.logger(`Register App Response: ${JSON.stringify(body)}`);
callback && callback(err, null);
return;
}
_options.logger && _options.logger(`Register App Response: ${JSON.stringify(body)}`);
if (!body.response || !body.response.success || !body.response.success.tokens || !body.response.success.tokens.bearer) {
callback && callback(new Error('No tokens in Register response'), null);
return;
}
Cookie = addCookies(Cookie, response.headers);
loginData.refreshToken = body.response.success.tokens.bearer.refresh_token;
loginData.tokenDate = Date.now();
loginData.macDms = body.response.success.tokens.mac_dms;
if (body.response.success.tokens.website_cookies && Array.isArray(body.response.success.tokens.website_cookies)) {
const newCookies = [];
body.response.success.tokens.website_cookies.forEach(cookie => {
newCookies.push(`${cookie.Name}=${cookie.Value};`);
});
Cookie = addCookies(Cookie, {'set-cookie': newCookies});
}
/*
Get Amazon Marketplace Country
*/
const options = {
host: `alexa.${_options.baseAmazonPage}`,
path: `/api/users/me?platform=ios&version=${apiCallVersion}`,
method: 'GET',
headers: {
'User-Agent': apiCallUserAgent,
'Accept-Language': _options.acceptLanguage,
'Accept-Charset': 'utf-8',
'Connection': 'keep-alive',
'Accept': 'application/json',
'Cookie': Cookie
}
};
_options.logger && _options.logger('Alexa-Cookie: Get User data');
_options.logger && _options.logger(JSON.stringify(options));
request(options, (error, response, body) => {
if (!error) {
try {
if (typeof body !== 'object') body = JSON.parse(body);
} catch (err) {
_options.logger && _options.logger(`Get User data Response: ${JSON.stringify(body)}`);
callback && callback(err, null);
return;
}
_options.logger && _options.logger(`Get User data Response: ${JSON.stringify(body)}`);
Cookie = addCookies(Cookie, response.headers);
if (body.marketPlaceDomainName) {
const pos = body.marketPlaceDomainName.indexOf('.');
if (pos !== -1) _options.amazonPage = body.marketPlaceDomainName.substr(pos + 1);
}
loginData.amazonPage = _options.amazonPage;
} else if (error && (!_options || !_options.amazonPage)) {
callback && callback(error, null);
return;
} else if (error && (!_options.formerRegistrationData || !_options.formerRegistrationData.amazonPage) && _options.amazonPage) {
_options.logger && _options.logger(`Continue with externally set amazonPage: ${_options.amazonPage}`);
} else if (error) {
_options.logger && _options.logger('Ignore error while getting user data and amazonPage because previously set amazonPage is available');
}
loginData.loginCookie = Cookie;
getLocalCookies(loginData.amazonPage, loginData.refreshToken, (err, localCookie) => {
if (err) {
callback && callback(err, null);
}
loginData.localCookie = localCookie;
getCSRFFromCookies(loginData.localCookie, _options, (err, resData) => {
if (err) {
callback && callback(new Error(`Error getting csrf for ${loginData.amazonPage}`), null);
return;
}
loginData.localCookie = resData.cookie;
loginData.csrf = resData.csrf;
delete loginData.accessToken;
delete loginData.authorization_code;
delete loginData.verifier;
_options.logger && _options.logger(`Final Registration Result: ${JSON.stringify(loginData)}`);
callback && callback(null, loginData);
});
});
});
});
};
const getLocalCookies = (amazonPage, refreshToken, callback) => {
Cookie = ''; // Reset because we are switching domains
/*
Token Exchange to Amazon Country Page
*/
const exchangeParams = {
'di.os.name': 'iOS',
'app_version': apiCallVersion,
'domain': `.${amazonPage}`,
'source_token': refreshToken,
'requested_token_type': 'auth_cookies',
'source_token_type': 'refresh_token',
'di.hw.version': 'iPhone',
'di.sdk.version': '6.12.3',
'cookies': Buffer.from(`{„cookies“:{".${amazonPage}":[]}}`).toString('base64'),
'app_name': _options.deviceAppName || defaultAppName,
'di.os.version': '15.5'
};
const options = {
host: `www.${amazonPage}`,
path: '/ap/exchangetoken/cookies',
method: 'POST',
headers: {
'User-Agent': apiCallUserAgent,
'Accept-Language': _options.acceptLanguage,
'Accept-Charset': 'utf-8',
'Connection': 'keep-alive',
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': '*/*'
},
body: querystring.stringify(exchangeParams, null, null, {
encodeURIComponent: encodeURIComponent
})
};
_options.logger && _options.logger(`Alexa-Cookie: Exchange tokens for ${amazonPage}`);
_options.logger && _options.logger(JSON.stringify(options));
request(options, (error, response, body) => {
if (error) {
callback && callback(error, null);
return;
}
try {
if (typeof body !== 'object') body = JSON.parse(body);
} catch (err) {
_options.logger && _options.logger(`Exchange Token Response: ${JSON.stringify(body)}`);
callback && callback(err, null);
return;
}
_options.logger && _options.logger(`Exchange Token Response: ${JSON.stringify(body)}`);
if (!body.response || !body.response.tokens || !body.response.tokens.cookies) {
callback && callback(new Error('No cookies in Exchange response'), null);
return;
}
if (!body.response.tokens.cookies[`.${amazonPage}`]) {
callback && callback(new Error(`No cookies for ${amazonPage} in Exchange response`), null);
return;
}
Cookie = addCookies(Cookie, response.headers);
const cookies = cookieTools.parse(Cookie);
body.response.tokens.cookies[`.${amazonPage}`].forEach((cookie) => {
if (cookies[cookie.Name] && cookies[cookie.Name] !== cookie.Value) {
_options.logger && _options.logger(`Alexa-Cookie: Update Cookie ${cookie.Name} = ${cookie.Value}`);
} else if (!cookies[cookie.Name]) {
_options.logger && _options.logger(`Alexa-Cookie: Add Cookie ${cookie.Name} = ${cookie.Value}`);
}
cookies[cookie.Name] = cookie.Value;
});
let localCookie = '';
for (const name of Object.keys(cookies)) {
localCookie += `${name}=${cookies[name]}; `;
}
localCookie = localCookie.replace(/[; ]*$/, '');
callback && callback(null, localCookie);
});
};
this.refreshAlexaCookie = (__options, callback) => {
if (!__options || !__options.formerRegistrationData || !__options.formerRegistrationData.loginCookie || !__options.formerRegistrationData.refreshToken) {
callback && callback(new Error('No former registration data provided for Cookie Refresh'), null);
return;
}
if (typeof __options === 'function') {
callback = __options;
__options = {};
}
_options = __options;
__options.proxyOnly = true;
initConfig();
const refreshData = {
'app_name': _options.deviceAppName || defaultAppName,
'app_version': apiCallVersion,
'di.sdk.version': '6.12.3',
'source_token': _options.formerRegistrationData.refreshToken,
'package_name': 'com.amazon.echo',
'di.hw.version': 'iPhone',
'platform': 'iOS',
'requested_token_type': 'access_token',
'source_token_type': 'refresh_token',
'di.os.name': 'iOS',
'di.os.version': '15.5',
'current_version': '6.12.3'
};
const options = {
host: `api.${_options.baseAmazonPage}`,
path: '/auth/token',
method: 'POST',
headers: {
'User-Agent': apiCallUserAgent,
'Accept-Language': _options.acceptLanguage,
'Accept-Charset': 'utf-8',
'Connection': 'keep-alive',
'Content-Type': 'application/x-www-form-urlencoded',
'Cookie': _options.formerRegistrationData.loginCookie,
'Accept': 'application/json',
'x-amzn-identity-auth-domain': `api.${_options.baseAmazonPage}`
},
body: querystring.stringify(refreshData)
};
Cookie = _options.formerRegistrationData.loginCookie;
_options.logger && _options.logger('Alexa-Cookie: Refresh Token');
_options.logger && _options.logger(JSON.stringify(options));
request(options, (error, response, body) => {
if (error) {
callback && callback(error, null);
return;
}
try {
if (typeof body !== 'object') body = JSON.parse(body);
} catch (err) {
_options.logger && _options.logger(`Refresh Token Response: ${JSON.stringify(body)}`);
callback && callback(err, null);
return;
}
_options.logger && _options.logger(`Refresh Token Response: ${JSON.stringify(body)}`);
_options.formerRegistrationData.loginCookie = addCookies(_options.formerRegistrationData.loginCookie, response.headers);
if (!body.access_token) {
callback && callback(new Error('No new access token in Refresh Token response'), null);
return;
}
_options.formerRegistrationData.loginCookie = addCookies(Cookie, response.headers);
_options.formerRegistrationData.accessToken = body.access_token;
getLocalCookies(_options.baseAmazonPage, _options.formerRegistrationData.refreshToken, (err, comCookie) => {
if (err) {
callback && callback(err, null);
}
// Restore frc and map-md
const initCookies = cookieTools.parse(_options.formerRegistrationData.loginCookie);
let newCookie = `frc=${initCookies.frc}; `;
newCookie += `map-md=${initCookies['map-md']}; `;
newCookie += comCookie;
_options.formerRegistrationData.loginCookie = newCookie;
handleTokenRegistration(_options, _options.formerRegistrationData, callback);
});
});
};
this.stopProxyServer = (callback) => {
if (proxyServer) {
proxyServer.close(() => {
callback && callback();
});
}
proxyServer = null;
};
}
module.exports = AlexaCookie();