-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathmain.js
More file actions
executable file
·3028 lines (2947 loc) · 119 KB
/
Copy pathmain.js
File metadata and controls
executable file
·3028 lines (2947 loc) · 119 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
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
/*
* Created with @iobroker/create-adapter v2.0.2
*/
// The adapter-core module gives you access to the core ioBroker functions
// you need to create an adapter
const utils = require('@iobroker/adapter-core');
const axios = require('axios').default;
const qs = require('qs');
const crypto = require('crypto');
const Json2iob = require('json2iob');
const getPwd = require('./lib/rsaKey');
const tough = require('tough-cookie');
const { HttpsCookieAgent } = require('http-cookie-agent/http');
const { JSDOM } = require('jsdom');
const fs = require('fs');
const { sep } = require('path');
const { tmpdir } = require('os');
const dhlDecrypt = require('./lib/dhldecrypt');
const { loginDhlNew: dhlLoginNew } = require('./lib/dhlLogin');
const { loginDPD: dpdLoginSoap, fetchDPDParcels: dpdFetchParcels } = require('./lib/dpdLogin');
const { classifyGlsDeliveryStatus } = require('./lib/glsStatus');
class Parcel extends utils.Adapter {
/**
* @param {Partial<utils.AdapterOptions>} [options={}]
*/
constructor(options) {
super({
...options,
name: 'parcel',
});
this.on('ready', this.onReady.bind(this));
this.on('stateChange', this.onStateChange.bind(this));
this.on('unload', this.onUnload.bind(this));
this.json2iob = new Json2iob(this);
this.sessions = {};
this.mergedJson = [];
this.inDelivery = [];
this.notDelivered = [];
this.mergedJsonObject = {};
this.images = {};
this.alreadySentMessages = {};
this.ignoredPath = [];
this.firstStart = true;
this.delivery_status = {
ERROR: -1,
UNKNOWN: 5,
REGISTERED: 10,
IN_PREPARATION: 20,
IN_TRANSIT: 30,
OUT_FOR_DELIVERY: 40,
DELIVERED: 1,
};
this.tmpDir = tmpdir();
this.requestClient = axios.create();
}
/**
* Is called when databases are connected and adapter received configuration.
*/
async onReady() {
// Reset the connection indicator during startup
this.setState('info.connection', false, true);
if (this.config.interval < 0.5) {
this.log.info('Set interval to minimum 0.5');
this.config.interval = 0.5;
}
this.cookieJar = new tough.CookieJar();
const cookieState = await this.getStateAsync('auth.cookie');
if (cookieState && cookieState.val) {
this.cookieJar = tough.CookieJar.fromJSON(cookieState.val);
}
this.requestClient = axios.create({
withCredentials: true,
httpsAgent: new HttpsCookieAgent({ cookies: { jar: this.cookieJar }, rejectUnauthorized: false }),
});
// Reichere jeden axios-Fehler mit Method/URL/Status an, sonst kommen im Log
// nur nichtssagende "Error: read ECONNRESET"-Zeilen an.
this.requestClient.interceptors.response.use(
(res) => res,
(error) => {
try {
const cfg = error.config || {};
const method = (cfg.method || 'GET').toUpperCase();
const url = cfg.url || '';
const status = error.response && error.response.status;
const code = error.code || (status ? `HTTP ${status}` : 'NO_RESPONSE');
const msg = error.message || 'unknown';
error.contextInfo = `${method} ${url} → ${code} (${msg})`;
} catch {
// don't obscure the original error if annotation fails
}
return Promise.reject(error);
},
);
if (this.config.amzActive !== false && this.config.amzusername && this.config.amzpassword) {
this.log.info('Login to Amazon');
await this.loginAmz();
}
if (this.config.dhlActive !== false) {
if (this.config.dhlCode && this.config.dhlCode.startsWith('dhllogin://')) {
this.log.info('Login to DHL via new dhllogin:// code');
await this.loginDhlNew();
} else {
const dhlSessionState = await this.getStateAsync('auth.dhlSession');
if (dhlSessionState && dhlSessionState.val) {
this.log.info('Use existing DHL session. If this fails please delete auth.dhlSession');
this.sessions['dhl'] = JSON.parse(String(dhlSessionState.val));
await this.refreshToken();
await this.createDHLStates();
}
}
}
if (this.config.dpdActive !== false && this.config.dpdusername && this.config.dpdpassword) {
const dpdSessionState = await this.getStateAsync('auth.dpdSession');
if (dpdSessionState && dpdSessionState.val) {
try {
const parsed = JSON.parse(String(dpdSessionState.val));
if (parsed && parsed.SessionToken && parsed.cloudUserID != null) {
this.log.info('Reuse existing DPD session (SessionFullState will verify).');
this.sessions['dpd'] = parsed;
}
} catch {
// fall through to fresh login
}
}
if (!this.sessions['dpd']) {
this.log.info('Login to DPD');
await this.loginDPD();
}
}
if (this.config.t17Active !== false && this.config.t17username && this.config.t17password) {
this.log.info('Login to T17 User');
await this.login17T();
}
if (this.config.aliUsername && this.config.aliPassword) {
this.log.info('Login to AliExpres');
await this.loginAli();
}
if (this.config.t17ApiActive !== false && this.config['17trackKey']) {
this.sessions['17track'] = this.config['17trackKey'];
this.login17TApi();
this.setState('info.connection', true, true);
}
if (this.config.glsActive !== false && this.config.glsusername && this.config.glspassword) {
const glsSessionState = await this.getStateAsync('auth.glsSession');
if (glsSessionState && glsSessionState.val) {
try {
const parsed = JSON.parse(String(glsSessionState.val));
if (parsed && parsed.refresh_token) {
this.log.info('Reuse existing GLS session, refresh token…');
this.sessions['gls'] = parsed;
this.glstoken = parsed.access_token;
await this.refreshGLSToken();
}
} catch {
// fall through to fresh login
}
}
if (!this.sessions['gls']) {
this.log.info('Login to GLS');
await this.loginGLS();
}
}
if (this.config.upsActive !== false && this.config.upsusername && this.config.upspassword) {
this.log.info('Login to UPS');
await this.loginUPS();
}
if (this.config.hermesActive !== false && this.config.hermesusername && this.config.hermespassword) {
this.log.info('Login to Hermes');
await this.loginHermes();
}
this.updateInterval = null;
this.reLoginTimeout = null;
this.refreshTokenTimeout = null;
this.subscribeStates('*');
if (Object.keys(this.sessions).length > 0) {
this.log.debug('Starting updateProvider with sessions: ' + JSON.stringify(Object.keys(this.sessions)));
await this.updateProvider();
this.updateInterval = setInterval(async () => {
this.firstStart = false;
await this.updateProvider();
}, this.config.interval * 60 * 1000);
this.refreshTokenInterval = setInterval(() => {
this.refreshToken();
}, 29 * 60 * 1000);
} else {
this.log.warn('No login session found');
}
}
async loginDhlNew() {
const sessionData = await dhlLoginNew({
requestClient: this.requestClient.bind(this),
dhlCode: this.config.dhlCode,
log: this.log,
});
if (!sessionData) {
return;
}
this.sessions['dhl'] = sessionData;
await this.cookieJar.setCookie('dhli=' + sessionData.id_token + '; path=/; domain=dhl.de', 'https:/dhl.de');
await this.cookieJar.setCookie('dhli=' + sessionData.id_token + '; path=/; domain=www.dhl.de', 'https:/www.dhl.de');
this.setState('info.connection', true, true);
this.setState('auth.cookie', JSON.stringify(this.cookieJar.toJSON()), true);
await this.createDHLStates();
await this.extendObject('auth.dhlSession', {
type: 'state',
common: {
name: 'DHL Session',
type: 'string',
role: 'json',
read: true,
write: false,
},
native: {},
});
this.setState('auth.dhlSession', JSON.stringify(sessionData), true);
this.dhlLoginSuccess = true;
}
/**
* Loggt einen HTTP-Fehler mit Kontext (Provider, Method, URL, Status, Body-Preview).
* Ersatz für die vielen `this.log.error(error)`-Stellen, die sonst nur nichtssagende
* "Error: read ECONNRESET"-Zeilen produzieren.
*
* Erkennt automatisch, ob es sich um einen echten Axios-Fehler (mit `.config` oder
* `.response`) oder um einen normalen JS-Error (JSON.parse, DOM, IO) handelt und
* gibt entsprechend den vollen HTTP-Kontext oder nur Message + Stack aus. So
* werden Parse-/State-Exceptions nicht mehr fälschlich als "GET → NO_RESPONSE"
* geloggt.
*
* @param {string} scope - Provider-Kürzel bzw. Ort, z.B. "GLS/login" oder "DHL/fetch"
* @param {any} error - der geworfene Fehler
*/
logAxiosError(scope, error) {
if (!error) {
this.log.error(`[${scope}] Unknown error (falsy)`);
return;
}
const isAxiosError = !!(error.config || error.response || error.request || error.isAxiosError);
if (!isAxiosError) {
this.log.error(`[${scope}] ${error.message || String(error)}`);
if (this.log.debug && error.stack) {
this.log.debug(`[${scope}] stack: ${error.stack}`);
}
return;
}
const cfg = (error.config || {});
const method = (cfg.method || 'GET').toUpperCase();
const url = cfg.url || '';
const status = error.response && error.response.status;
const code = error.code || (status ? `HTTP ${status}` : 'NO_RESPONSE');
const msg = error.message || 'unknown';
this.log.error(`[${scope}] ${method} ${url} → ${code} (${msg})`);
if (error.response && error.response.data) {
let body = error.response.data;
if (typeof body !== 'string') {
try { body = JSON.stringify(body); } catch { body = String(body); }
}
if (body && body.length) {
this.log.error(`[${scope}] body: ${body.length > 500 ? body.slice(0, 500) + '…' : body}`);
}
}
if (this.log.debug && error.stack) {
this.log.debug(`[${scope}] stack: ${error.stack}`);
}
}
async loginAli() {
const loginData = await this.requestClient({
method: 'get',
url: 'https://passport.aliexpress.com/mini_login.htm?lang=de_de&appName=aebuyer&appEntrance=default&styleType=auto&bizParams=¬LoadSsoView=false¬KeepLogin=false&isMobile=false&cssLink=https://i.alicdn.com/noah-static/4.0.2/common/css/reset-havana.css&cssUrl=https://i.alicdn.com/noah-static/4.0.2/common/css/reset-havana-new-page.css&showMobilePwdLogin=false&defaultCountryCode=DE&ut=&rnd=0.9085151696364684',
headers: {
'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="100", "Google Chrome";v="100"',
'sec-ch-ua-mobile': '?0',
'sec-ch-ua-platform': '"macOS"',
'upgrade-insecure-requests': '1',
'user-agent':
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.20 Safari/537.36',
accept:
'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
'sec-fetch-site': 'same-site',
'sec-fetch-mode': 'navigate',
'sec-fetch-dest': 'iframe',
referer: 'https://login.aliexpress.com/',
'accept-language': 'de',
},
})
.then(async (res) => {
this.log.debug(JSON.stringify(res.data));
if (res.data.indexOf('window.viewData = ') !== -1) {
try {
const loginData = res.data.split('window.viewData = ')[1].split(';')[0].replace(/\\/g, '');
return JSON.parse(loginData).loginFormData;
} catch (error) {
this.logAxiosError('AliExpress/login', error);
}
} else {
this.log.error('Failed Step 1 Aliexpress');
}
})
.catch((error) => {
this.logAxiosError('AliExpress/login', error);
if (error.response) {
this.log.error(JSON.stringify(error.response.data));
}
});
if (!loginData) {
return;
}
if (!this.config.aliMfa) {
loginData.loginId = this.config.aliUsername;
loginData.password2 = getPwd(this.config.aliPassword);
await this.requestClient({
method: 'post',
url: 'https://passport.aliexpress.com/newlogin/login.do?appName=aebuyer&fromSite=13&_bx-v=2.0.39',
headers: {
'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="100", "Google Chrome";v="100"',
accept: 'application/json, text/plain, */*',
'content-type': 'application/x-www-form-urlencoded',
'sec-ch-ua-mobile': '?0',
'user-agent':
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.20 Safari/537.36',
'sec-ch-ua-platform': '"macOS"',
origin: 'https://login.aliexpress.com',
'sec-fetch-site': 'same-site',
'sec-fetch-mode': 'cors',
'sec-fetch-dest': 'empty',
referer: 'https://login.aliexpress.com/',
'accept-language': 'de',
},
data: qs.stringify(loginData),
})
.then(async (res) => {
if (res.data.url && res.data.url.indexOf('punish') !== -1) {
this.log.error('Failed because of captcha');
}
// this.log.debug(JSON.stringify(res.data));
})
.catch((error) => {
this.logAxiosError('AliExpress/login', error);
if (error.response) {
this.log.error(JSON.stringify(error.response.data));
}
});
await this.requestClient({
method: 'get',
url: 'https://www.aliexpress.com/p/order/index.html',
})
.then(async (res) => {
// this.log.debug(JSON.stringify(res.data));
res.data.indexOf('Session has expired') !== -1
? this.log.error('Session has expired')
: this.log.info('Login to Aliexpress successful');
})
.catch(async (error) => {
this.logAxiosError('AliExpress/verify', error);
});
} else {
this.log.warn('AliExpress MFA login is not supported');
}
}
async loginAmz() {
await this.setObjectNotExistsAsync('amazon', {
type: 'device',
common: {
name: 'Amazon Tracking',
},
native: {},
});
await this.setObjectNotExistsAsync('amazon.json', {
type: 'state',
common: {
name: 'Json Sendungen',
write: false,
read: true,
type: 'string',
role: 'json',
},
native: {},
});
// Check if we have a pending verification code to submit
const verificationState = await this.getStateAsync('auth.amzVerification');
if (verificationState && verificationState.val && this.config.amzotp) {
this.log.info('Found pending Amazon verification. Submitting code...');
try {
const verification = JSON.parse(verificationState.val);
const form = verification.form;
form['code'] = this.config.amzotp;
form['action'] = 'code';
this.log.debug('Verify URL: ' + verification.url);
this.log.debug('Verify form: ' + JSON.stringify(form));
const verifyResult = await this.requestClient({
method: 'post',
url: verification.url,
headers: {
'content-type': 'application/x-www-form-urlencoded',
accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
origin: 'https://www.amazon.de',
'accept-language': 'de-DE,de;q=0.9',
'user-agent':
'Mozilla/5.0 (iPhone; CPU iPhone OS 16_7_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148',
referer: verification.url,
},
data: qs.stringify(form),
});
await this.setStateAsync('auth.amzVerification', '', true);
if (verifyResult.data && verifyResult.data.indexOf('js-yo-main-content') !== -1) {
this.log.info('Amazon verification successful');
this.sessions['amz'] = true;
this.setState('info.connection', true, true);
this.setState('auth.cookie', JSON.stringify(this.cookieJar.toJSON()), true);
return;
}
if (verifyResult.data && verifyResult.data.indexOf('order') !== -1) {
this.log.info('Amazon verification successful');
this.sessions['amz'] = true;
this.setState('info.connection', true, true);
this.setState('auth.cookie', JSON.stringify(this.cookieJar.toJSON()), true);
return;
}
this.log.error('Amazon verification code was not accepted. Please restart and try again.');
this.log.debug(verifyResult.data);
} catch (error) {
this.log.error('Failed to submit Amazon verification code');
this.logAxiosError('Amazon/login', error);
if (error.response) {
this.log.debug('Verification error response: ' + (typeof error.response.data === 'string' ? error.response.data : JSON.stringify(error.response.data)));
}
await this.setStateAsync('auth.amzVerification', '', true);
try {
delete this.cookieJar.store.idx['amazon.de'];
delete this.cookieJar.store.idx['www.amazon.de'];
this.setState('auth.cookie', JSON.stringify(this.cookieJar.toJSON()), true);
this.log.info('Amazon Cookies gelöscht. Bitte Adapter neu starten.');
} catch { /* ignore */ }
}
return;
}
// Clear old Amazon cookies if user requested it (login problems)
if (this.config.amzResetCookies) {
this.log.info('Amazon Cookies werden gelöscht (Option in Einstellungen)');
try {
delete this.cookieJar.store.idx['amazon.de'];
delete this.cookieJar.store.idx['www.amazon.de'];
this.setState('auth.cookie', JSON.stringify(this.cookieJar.toJSON()), true);
} catch { /* ignore */ }
}
let amzResponseUrl = '';
let body = await this.requestClient({
method: 'get',
maxBodyLength: Infinity,
url: 'https://www.amazon.de/ap/signin?_encoding=UTF8&accountStatusPolicy=P1&openid.assoc_handle=deflex&openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.identity=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.mode=checkid_setup&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&openid.ns.pape=http%3A%2F%2Fspecs.openid.net%2Fextensions%2Fpape%2F1.0&openid.pape.max_auth_age=0&openid.return_to=https%3A%2F%2Fwww.amazon.de%2Fgp%2Fcss%2Forder-history%3Fie%3DUTF8%26ref_%3Dnav_orders_first&pageId=webcs-yourorder&showRmrMe=1',
headers: {
accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'accept-charset': 'utf-8',
'sec-fetch-site': 'none',
'accept-language': 'de-DE,de;q=0.9',
'cache-control': 'no-store',
'sec-fetch-mode': 'navigate',
'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_7_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148',
},
})
.then(async (res) => {
amzResponseUrl = res.request?.res?.responseUrl || res.request?.responseURL || '';
this.log.debug('Amazon signin response URL: ' + amzResponseUrl);
this.log.debug(JSON.stringify(res.data));
return res.data;
})
.catch((error) => {
this.log.error('Amazon first login step failed');
this.log.error(
'https://www.amazon.de/ap/signin?openid.return_to=https://www.amazon.de/ap/maplanding&openid.oa2.code_challenge_method=S256&openid.assoc_handle=amzn_mshop_ios_v2_de&openid.identity=http://specs.openid.net/auth/2.0/identifier_select&pageId=amzn_mshop_ios_v2_de&openid.ns.oa2=http://www.amazon.com/ap/ext/oauth/2&openid.claimed_id=http://specs.openid.net/auth/2.0/identifier_select&openid.mode=checkid_setup&openid.oa2.client_id=device:42334146314239333737364334463941393135443746313136363446434238302341334e5748585451344542435a53&openid.oa2.code_challenge=ig2YgHP3AoncuKG0ks5pgr1HUhzwvlST-tuIY2Chi2M&openid.ns.pape=http://specs.openid.net/extensions/pape/1.0&openid.oa2.scope=device_auth_access&openid.ns=http://specs.openid.net/auth/2.0&openid.pape.max_auth_age=0&openid.oa2.response_type=code',
);
this.logAxiosError('Amazon/login', error);
if (error.response) {
this.log.error(JSON.stringify(error.response.data));
}
});
if (body && body.indexOf('untrusted-app-sign-in-continue-button-announce') !== -1) {
this.log.info('Amazon untrustet app warning detected');
const form = this.extractHidden(body);
delete form['sessionChallengeAck'];
delete form['ue_back'];
delete form['undefined'];
body = await this.requestClient({
method: 'post',
maxBodyLength: Infinity,
url: 'https://www.amazon.de/ap/signin',
headers: {
accept:
'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
'accept-language': 'de',
'cache-control': 'no-cache',
'content-type': 'application/x-www-form-urlencoded',
},
data: form,
})
.then(async (res) => {
this.log.debug(JSON.stringify(res.data));
if (res.data.indexOf('/errors/validateCaptcha') !== -1) {
this.log.error('Captcha detected');
return;
}
return res.data;
})
.catch((error) => {
this.log.error('Amazon untrustet app warning failed');
this.logAxiosError('Amazon/login', error);
if (error.response) {
this.log.error(JSON.stringify(error.response.data));
}
});
}
let form = this.extractHidden(body);
let postUrl = this.extractFormAction(body) || amzResponseUrl || 'https://www.amazon.de/ap/signin';
// Handle Unified Claim Collection page (new Amazon login flow)
// Keep ALL fields, add email, POST to get password page, then continue with password POST.
if (form.appAction === 'SIGNIN_CLAIM_COLLECT' || (body && body.indexOf('FullPageUnifiedClaimCollect') !== -1)) {
this.log.info('Amazon Unified Claim Collection page detected');
// Extract any form action (not just name="signIn")
const anyFormAction = body.match(/<form[^>]*action=["']([^"']*)["']/i);
if (anyFormAction) {
let actionUrl = anyFormAction[1].replace(/&/g, '&');
if (actionUrl.startsWith('/')) actionUrl = 'https://www.amazon.de' + actionUrl;
postUrl = actionUrl;
}
// Remove only webAuthn and ue_back, keep everything else
delete form['webAuthnGetArbForAutofill'];
delete form['webAuthnGetParametersForAutofill'];
delete form['webAuthnChallengeIdForAutofill'];
delete form['ue_back'];
delete form['undefined'];
form.email = this.config.amzusername;
this.log.debug('Unified Claim Collection POST to: ' + postUrl);
body = await this.requestClient({
method: 'post',
maxBodyLength: Infinity,
url: postUrl,
headers: {
'content-type': 'application/x-www-form-urlencoded',
accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'sec-fetch-site': 'same-origin',
'accept-language': 'de-DE,de;q=0.9',
'sec-fetch-mode': 'navigate',
origin: 'https://www.amazon.de',
'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_7_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148',
referer: postUrl,
},
data: qs.stringify(form),
})
.then(async (res) => {
amzResponseUrl = res.request?.res?.responseUrl || res.request?.responseURL || amzResponseUrl;
this.log.debug('Unified email POST successful. Response URL: ' + amzResponseUrl);
return res.data;
})
.catch((error) => {
this.log.error('Unified email POST failed');
this.logAxiosError('Amazon/login', error);
if (error.response) {
this.log.error(JSON.stringify(error.response.data));
}
return null;
});
if (!body) return;
form = this.extractHidden(body);
postUrl = this.extractFormAction(body) || amzResponseUrl || postUrl;
this.log.debug('After Unified email POST - postUrl: ' + postUrl);
}
// ax/claim: email-only page (2-step). ap/signin: email+password on same page.
// Detect by checking if body contains a visible password input field
const isTwoStep = body.indexOf('type="password"') === -1;
if (isTwoStep && form.email !== this.config.amzusername) {
form.email = this.config.amzusername;
body = await this.requestClient({
method: 'post',
maxBodyLength: Infinity,
url: postUrl,
headers: {
'content-type': 'application/x-www-form-urlencoded',
accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'sec-fetch-site': 'same-origin',
'accept-language': 'de-DE,de;q=0.9',
'sec-fetch-mode': 'navigate',
origin: 'https://www.amazon.de',
'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_7_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148',
referer: postUrl,
'sec-fetch-dest': 'document',
},
data: qs.stringify(form),
})
.then(async (res) => {
this.log.silly(JSON.stringify(res.data));
this.log.debug('Username successfully posted');
const form = this.extractHidden(res.data);
if (Object.keys(form).length <= 3) {
this.log.error('Password form too short');
this.log.error(res.data);
}
return res.data;
})
.catch((error) => {
this.log.error('Failed to post username');
this.logAxiosError('Amazon/login', error);
if (error.response) {
this.log.error(JSON.stringify(error.response.data));
}
try {
delete this.cookieJar.store.idx['amazon.de'];
delete this.cookieJar.store.idx['www.amazon.de'];
this.setState('auth.cookie', JSON.stringify(this.cookieJar.toJSON()), true);
this.log.info('Amazon Cookies gelöscht nach Login-Fehler. Bitte Adapter neu starten.');
} catch { /* ignore */ }
});
form = this.extractHidden(body);
postUrl = this.extractFormAction(body) || postUrl;
}
delete form['='];
delete form['undefined'];
this.log.debug('Post form : ' + JSON.stringify(form));
form.rememberMe = 'true';
form.password = this.config.amzpassword;
this.log.debug('Post with password');
await this.requestClient({
method: 'post',
url: postUrl,
headers: {
accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'content-type': 'application/x-www-form-urlencoded',
origin: 'https://www.amazon.de',
'accept-language': 'de-de',
'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_8 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148',
referer: postUrl,
},
data: form,
})
.then(async (res) => {
this.log.silly(JSON.stringify(res.data));
this.log.debug('Password successfully posted');
if (res.data.indexOf('js-yo-main-content') !== -1) {
this.log.info('Relogin to Amazon successful');
this.sessions['amz'] = true;
this.setState('info.connection', true, true);
this.setState('auth.cookie', JSON.stringify(this.cookieJar.toJSON()), true);
return;
}
if (res.data.indexOf('auth-mfa-otpcode') !== -1) {
this.log.info('Found MFA token login');
const form = this.extractHidden(res.data);
// delete form['ue_back'];
// delete form['sessionChallengeAck'];
delete form['undefined'];
form.deviceId = form.deviceId || '';
form.otpCode = this.config.amzotp;
form.rememberDevice = true;
await this.requestClient({
method: 'post',
url: 'https://www.amazon.de/ap/signin',
headers: {
'content-type': 'application/x-www-form-urlencoded',
accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'sec-fetch-site': 'same-origin',
'accept-language': 'de-DE,de;q=0.9',
'sec-fetch-mode': 'navigate',
origin: 'https://www.amazon.de',
'user-agent':
'Mozilla/5.0 (iPhone; CPU iPhone OS 16_7_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148',
referer: 'https://' + res.request.host + res.request.path,
'sec-fetch-dest': 'document',
},
data: qs.stringify(form),
})
.then(async (res) => {
this.log.silly(JSON.stringify(res.data));
this.log.debug('MFA successfully posted');
if (res.data.indexOf('js-yo-main-content') !== -1) {
this.log.info('Login to Amazon successful');
this.sessions['amz'] = true;
this.setState('info.connection', true, true);
this.setState('auth.cookie', JSON.stringify(this.cookieJar.toJSON()), true);
await this.setObjectNotExistsAsync('amazon', {
type: 'device',
common: {
name: 'Amazon Tracking',
},
native: {},
});
return;
}
this.log.error(
'MFA: Login to Amazon failed. Enter correct MFA Code from SMS or App. Or check you account and login manually to Amazon',
);
this.setState('info.connection', false, true);
})
.catch(async (error) => {
this.log.error('MFA: Failed to post https://www.amazon.de/ap/signin');
if (error.response) {
this.setState('info.connection', false, true);
this.log.error(JSON.stringify(error.response.data));
}
this.logAxiosError('Amazon/login', error);
});
return;
}
if (res.data.indexOf('Amazon Anmelden') !== -1) {
this.log.error('Login to Amazon failed, please login to Amazon manually and check the login');
if (res.data.indexOf('captcha-placeholder') !== -1) {
this.log.warn(
'Amazon Captcha erkannt. Bitte öffne https://www.amazon.de im Browser auf dem gleichen Gerät/IP, melde dich ab und wieder an um das Captcha zu lösen. Danach den Adapter neu starten.',
);
}
this.log.error(
'Login to Amazon failed. Please check credentials and restart the adapter.',
);
delete this.cookieJar.store.idx['amazon.de'];
delete this.cookieJar.store.idx['www.amazon.de'];
this.setState('info.connection', false, true);
return;
}
if (res.data.indexOf('Zurücksetzen des Passworts erforderlich') !== -1) {
this.log.error('Zurücksetzen des Passworts erforderlich');
return;
}
if (res.data.indexOf('transactionapproval') !== -1 || res.data.indexOf('Enter verification code') !== -1 || res.data.indexOf('Bestätigungscode eingeben') !== -1 || res.data.indexOf('verification-code-form') !== -1) {
this.log.info('Amazon SMS verification required. A code was sent to your phone.');
this.log.info('Please enter the code in the adapter settings (OTP field) and restart the adapter.');
const form = this.extractHidden(res.data);
delete form['undefined'];
// extractHidden collects all forms - 'action' gets overwritten to 'resend' by later forms
form['action'] = 'code';
delete form['resendContactType'];
delete form['timerMessage'];
delete form['timerComplete'];
// Extract actual form action from response page
const cvfActionMatch = res.data.match(/<form[^>]*action=["']([^"']*)["']/i);
let verifyUrl = 'https://www.amazon.de/ap/cvf/verify';
if (cvfActionMatch) {
verifyUrl = cvfActionMatch[1].replace(/&/g, '&');
if (verifyUrl.startsWith('/')) verifyUrl = 'https://www.amazon.de' + verifyUrl;
}
this.log.debug('CVF verify URL: ' + verifyUrl);
const verification = {
url: verifyUrl,
form: form,
};
await this.setObjectNotExistsAsync('auth.amzVerification', {
type: 'state',
common: { name: 'Amazon Verification Data', write: false, read: true, type: 'string', role: 'json' },
native: {},
});
await this.setStateAsync('auth.amzVerification', JSON.stringify(verification), true);
this.setState('auth.cookie', JSON.stringify(this.cookieJar.toJSON()), true);
return;
}
if (res.data.indexOf('auth-select-device-form"') !== -1) {
this.log.info('SMS code or call form found. If you do not receive a SMS then login to Amazon and trigger the SMS code');
const form = this.extractHidden(res.data);
delete form['undefined'];
form['action'] = 'code';
delete form['resendContactType'];
delete form['timerMessage'];
delete form['timerComplete'];
const selectActionMatch = res.data.match(/<form[^>]*action=["']([^"']*)["']/i);
let verifyUrl = 'https://www.amazon.de/ap/cvf/verify';
if (selectActionMatch) {
verifyUrl = selectActionMatch[1].replace(/&/g, '&');
if (verifyUrl.startsWith('/')) verifyUrl = 'https://www.amazon.de' + verifyUrl;
}
this.log.debug('Select device verify URL: ' + verifyUrl);
const verification = {
url: verifyUrl,
form: form,
};
await this.setObjectNotExistsAsync('auth.amzVerification', {
type: 'state',
common: { name: 'Amazon Verification Data', write: false, read: true, type: 'string', role: 'json' },
native: {},
});
await this.setStateAsync('auth.amzVerification', JSON.stringify(verification), true);
this.setState('auth.cookie', JSON.stringify(this.cookieJar.toJSON()), true);
this.log.info('Please enter the SMS code in the adapter settings (OTP field) and restart the adapter.');
return;
}
if (res.data.indexOf('isRedirectForWhatsapp') !== -1 || res.data.indexOf('cvf/approval') !== -1) {
this.log.info('Amazon WhatsApp-Verifizierung erkannt. Versuche WhatsApp-Code anzufordern...');
// Extract the form action URL for WhatsApp redirect
const whatsappMatch = res.data.match(/action="([^"]*isRedirectForWhatsapp[^"]*)"/);
if (whatsappMatch) {
let whatsappUrl = whatsappMatch[1].replace(/&/g, '&');
if (whatsappUrl.startsWith('/')) {
whatsappUrl = 'https://www.amazon.de' + whatsappUrl;
}
const whatsappRes = await this.requestClient({
method: 'post',
url: whatsappUrl,
headers: {
'content-type': 'application/x-www-form-urlencoded',
accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
origin: 'https://www.amazon.de',
'accept-language': 'de-de',
'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_8 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148',
},
data: '',
}).catch((error) => {
this.log.error('WhatsApp redirect failed: ' + error.message);
return null;
});
if (whatsappRes && whatsappRes.data) {
this.log.debug('WhatsApp response: ' + whatsappRes.data.substring(0, 2000));
// After WhatsApp redirect we should get a verification code form
const form = this.extractHidden(whatsappRes.data);
delete form['undefined'];
form['action'] = 'code';
delete form['resendContactType'];
delete form['timerMessage'];
delete form['timerComplete'];
// Extract actual form action URL from response
const formActionMatch = whatsappRes.data.match(/<form[^>]*action=["']([^"']*)["']/i);
let verifyUrl;
if (formActionMatch) {
verifyUrl = formActionMatch[1].replace(/&/g, '&');
if (verifyUrl.startsWith('/')) {
verifyUrl = 'https://www.amazon.de' + verifyUrl;
}
} else {
// Fallback: use response URL or approval URL
verifyUrl = whatsappRes.request?.res?.responseUrl || 'https://www.amazon.de/ap/cvf/verify';
}
this.log.info('Verify URL: ' + verifyUrl);
const verification = { url: verifyUrl, form: form };
await this.setObjectNotExistsAsync('auth.amzVerification', {
type: 'state',
common: { name: 'Amazon Verification Data', write: false, read: true, type: 'string', role: 'json' },
native: {},
});
await this.setStateAsync('auth.amzVerification', JSON.stringify(verification), true);
this.setState('auth.cookie', JSON.stringify(this.cookieJar.toJSON()), true);
this.log.info('Amazon WhatsApp-Code wurde angefordert. Bitte den Code in den Adaptereinstellungen (OTP Feld) eingeben und den Adapter neu starten.');
}
} else {
this.log.warn('Amazon WhatsApp-Verifizierung erkannt, aber kein Formular gefunden. Bitte manuell bei Amazon einloggen.');
}
return;
}
if (res.data.indexOf('captcha') !== -1 || res.data.indexOf('Löse das Rätsel, um dein Konto zu schützen') !== -1 || res.data.indexOf('cvf_captcha') !== -1) {
this.log.warn('Amazon Captcha erkannt. Bitte öffne https://www.amazon.de im Browser auf dem gleichen Gerät/IP, melde dich ab und wieder an um das Captcha zu lösen. Danach den Adapter neu starten.');
this.setState('info.connection', false, true);
return;
}
this.log.error('Unknown Error: Login to Amazon failed, please login to Amazon and check your credentials');
this.log.info(res.data);
try {
delete this.cookieJar.store.idx['amazon.de'];
delete this.cookieJar.store.idx['www.amazon.de'];
this.setState('auth.cookie', JSON.stringify(this.cookieJar.toJSON()), true);
this.log.info('Amazon Cookies gelöscht. Bitte Adapter neu starten.');
} catch { /* ignore */ }
this.setState('info.connection', false, true);
return;
})
.catch(async (error) => {
this.log.error('Failed to post with password to https://www.amazon.de/ap/signin');
if (error.response) {
this.setState('info.connection', false, true);
this.log.error(JSON.stringify(error.response.data));
}
this.logAxiosError('Amazon/login', error);
try {
delete this.cookieJar.store.idx['amazon.de'];
delete this.cookieJar.store.idx['www.amazon.de'];
this.setState('auth.cookie', JSON.stringify(this.cookieJar.toJSON()), true);
this.log.info('Amazon Cookies gelöscht nach Login-Fehler. Bitte Adapter neu starten.');
} catch { /* ignore */ }
});
}
// ------- DPD (SOAP) -------
// Der eigentliche SOAP-Flow liegt in lib/dpdLogin.js (analog zu lib/dhlLogin.js).
// Hier nur die Adapter-Klebeschicht: Session-Persistenz, State-Objekte,
// Retry-Kaskade zwischen Fetch und Re-Login.
/**
* Löscht die DPD-Session aus dem laufenden Prozess UND aus dem persistierten
* `auth.dpdSession`-State, damit weder ein aktuell laufender Fetch noch der
* nächste Adapter-Start eine ungültige Session weiter benutzt.
*/
async clearDPDSession() {
delete this.sessions['dpd'];
try {
await this.setStateAsync('auth.dpdSession', '', true);
} catch {
/* noop */
}
}
async loginDPD(silent) {
const session = await dpdLoginSoap({
requestClient: this.requestClient,
username: this.config.dpdusername,
password: this.config.dpdpassword,
log: this.log,
});
if (!session) {
await this.clearDPDSession();
return;
}
this.sessions['dpd'] = session;
!silent && this.log.info('Login to DPD successful (SOAP)');
await this.setObjectNotExistsAsync('dpd', {
type: 'device',
common: { name: 'DPD Tracking' },
native: {},
});
await this.setObjectNotExistsAsync('dpd.json', {
type: 'state',
common: { name: 'Json Sendungen', write: false, read: true, type: 'string', role: 'json' },
native: {},
});
await this.setObjectNotExistsAsync('auth.dpdSession', {
type: 'state',
common: { name: 'DPD SOAP Session', write: false, read: true, type: 'string', role: 'json' },
native: {},
});
this.setState('auth.dpdSession', JSON.stringify(session), true);
this.setState('info.connection', true, true);
}
/**
* Holt die aktuelle Sendungsliste. Bei ungültiger Session wird einmalig
* ein Re-Login versucht.
*/
async fetchDPDParcels(retry) {
const session = this.sessions['dpd'];
if (!session || !session.SessionToken) {
this.log.debug('fetchDPDParcels: keine Session, überspringe');
return null;
}
const result = await dpdFetchParcels({
requestClient: this.requestClient,
session,
log: this.log,
});
if (!result) return null;
if (result.status === 'ok') {
if (result.sessionToken) {
session.SessionToken = result.sessionToken;
this.setState('auth.dpdSession', JSON.stringify(session), true);
}
return result.data;
}
if (result.status === 'invalid-session') {
if (retry) {
this.log.error(`[DPD/fetch] error after re-login: ${result.errorCode || 'unknown'}`);
await this.clearDPDSession();
return null;
}
this.log.info(`[DPD/fetch] session invalid (${result.errorCode || 'unknown'}), attempting re-login`);
await this.loginDPD(true);
if (this.sessions['dpd']) {
return this.fetchDPDParcels(true);
}
return null;
}
// status === 'error' — vom Modul bereits geloggt
return null;
}
async loginGLS(silent) {
// Azure AD B2C Authorization-Code + PKCE flow — nachgebaut aus der GLS-App v6.3.0.
// Werte aus res/raw/msal_config_prod.json der APK.
const CLIENT_ID = 'b990fae6-1647-426b-b0a9-d51fcfed4fc8';
const REDIRECT_URI = 'msauth://com.gls.glsappde.consumer/ulmVfvzqq5hHvhon9Kh4lu9Esy8%3D';
const AUTHORITY = 'https://login.gls-group.net/login.gls-group.net';
const POLICY = 'B2C_1A_PROD_DE_DF_SOCIAL_DEFAULT';
const SCOPES = [
'openid',