-
Notifications
You must be signed in to change notification settings - Fork 13
/
fetch.test.js
2531 lines (2244 loc) · 103 KB
/
fetch.test.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
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
/* Copyright (c) 2020, VRAI Labs and/or its affiliates. All rights reserved.
*
* This software is licensed under the Apache License, Version 2.0 (the
* "License") as published by the Apache Software Foundation.
*
* You may not use this file except in compliance with the License. You may
* obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
let axios = require("axios");
let puppeteer = require("puppeteer");
let jsdom = require("mocha-jsdom");
let decodeJWT = require("jsonwebtoken").decode;
let verifyJWT = require("jsonwebtoken").verify;
let jwksClient = require("jwks-rsa");
let { default: AuthHttpRequestFetch } = require("../lib/build/fetch");
let AuthHttpRequest = require("../index.js").default;
let assert = require("assert");
let {
delay,
checkIfIdRefreshIsCleared,
checkIfDuplicateCookieHandlingIsEnabled,
getNumberOfTimesRefreshCalled,
startST,
startSTWithJWTEnabled,
getNumberOfTimesGetSessionCalled,
BASE_URL,
BASE_URL_FOR_ST,
coreTagEqualToOrAfter,
checkIfJWTIsEnabled,
addBrowserConsole,
resetAuthHttpRequestFetch,
checkIfV3AccessTokenIsSupported
} = require("./utils");
const { spawn } = require("child_process");
let { ProcessState, PROCESS_STATE } = require("../lib/build/processState");
/* TODO:
- User passed config should be sent as well
- session should not exist when user's session fully expires - use doesSessionExist & check localstorage is empty
- while logged in, test that APIs that there is proper change in id refresh cookie
- tests APIs that don't require authentication work after logout - with-credentials don't get sent.
- if not logged in, test that API that requires auth throws session expired
- Test everything without and without interception
- If user provides withCredentials as false or whatever, then app should not add it
- Cross origin API requests to API that requires Auth
- Cross origin API request to APi that doesn't require auth
- Proper change in anti-csrf token once access token resets
- Refresh API custom headers are working
- allow-credentials should not be sent by our SDK by default.
- User passed config should be sent as well
*/
describe("Fetch AuthHttpRequest class tests", function () {
let v3AccessTokenSupported;
jsdom({
url: "http://localhost"
});
before(async function () {
spawn(
"./test/startServer",
[process.env.INSTALL_PATH, process.env.NODE_PORT === undefined ? 8080 : process.env.NODE_PORT],
{
// stdio: "inherit"
}
);
await new Promise(r => setTimeout(r, 1000));
v3AccessTokenSupported = await checkIfV3AccessTokenIsSupported();
});
after(async function () {
let instance = axios.create();
await instance.post(BASE_URL_FOR_ST + "/after");
try {
await instance.get(BASE_URL_FOR_ST + "/stop");
} catch (err) {}
});
beforeEach(async function () {
resetAuthHttpRequestFetch();
global.document = {};
ProcessState.getInstance().reset();
let instance = axios.create();
await instance.post(BASE_URL_FOR_ST + "/beforeeach");
await instance.post("http://localhost.org:8082/beforeeach"); // for cross domain
await instance.post(BASE_URL + "/beforeeach");
});
it("testing with fetch for init check in doRequest", async function () {
let failed = false;
try {
await AuthHttpRequestFetch.doRequest(async () => {});
failed = true;
} catch (err) {
if (err.message !== "init function not called") {
failed = true;
}
}
if (failed) {
throw Error("test failed");
}
});
it("testing with fetch for init check in attemptRefreshingSession", async function () {
let failed = false;
try {
await AuthHttpRequest.attemptRefreshingSession();
failed = true;
} catch (err) {}
if (failed) {
throw Error("test failed");
}
});
it("testing with fetch api methods without config", async function () {
AuthHttpRequest.init({
apiDomain: BASE_URL
});
let getResponse = await fetch(`${BASE_URL}/testing`, {
method: "GET"
});
let postResponse = await fetch(`${BASE_URL}/testing`, {
method: "POST"
});
let deleteResponse = await fetch(`${BASE_URL}/testing`, {
method: "DELETE"
});
let putResponse = await fetch(`${BASE_URL}/testing`, {
method: "PUT"
});
let doRequestResponse = await fetch(`${BASE_URL}/testing`, { method: "GET" });
getResponse = await getResponse.text();
putResponse = await putResponse.text();
postResponse = await postResponse.text();
deleteResponse = await deleteResponse.text();
doRequestResponse = await doRequestResponse.text();
let expectedResponse = "success";
assert.strictEqual(getResponse, expectedResponse);
assert.strictEqual(putResponse, expectedResponse);
assert.strictEqual(postResponse, expectedResponse);
assert.strictEqual(deleteResponse, expectedResponse);
assert.strictEqual(doRequestResponse, expectedResponse);
});
it("testing with fetch api methods with config", async function () {
AuthHttpRequest.init({
apiDomain: BASE_URL
});
let testing = "testing";
let getResponse = await fetch(`${BASE_URL}/${testing}`, { method: "GET", headers: { testing } });
let postResponse = await fetch(`${BASE_URL}/${testing}`, { method: "post", headers: { testing } });
let deleteResponse = await fetch(`${BASE_URL}/${testing}`, { method: "delete", headers: { testing } });
let putResponse = await fetch(`${BASE_URL}/${testing}`, { method: "put", headers: { testing } });
let doRequestResponse1 = await fetch(`${BASE_URL}/${testing}`, {
method: "GET",
headers: { testing }
});
let doRequestResponse2 = await fetch(`${BASE_URL}/${testing}`, {
method: "GET",
headers: { testing }
});
let getResponseHeader = getResponse.headers.get(testing);
getResponse = await getResponse.text();
let putResponseHeader = putResponse.headers.get(testing);
putResponse = await putResponse.text();
let postResponseHeader = postResponse.headers.get(testing);
postResponse = await postResponse.text();
let deleteResponseHeader = deleteResponse.headers.get(testing);
deleteResponse = await deleteResponse.text();
let doRequestResponseHeader1 = doRequestResponse1.headers.get(testing);
doRequestResponse1 = await doRequestResponse1.text();
let doRequestResponseHeader2 = doRequestResponse2.headers.get(testing);
doRequestResponse2 = await doRequestResponse2.text();
let expectedResponse = "success";
assert.strictEqual(getResponse, expectedResponse);
assert.strictEqual(getResponseHeader, testing);
assert.strictEqual(putResponse, expectedResponse);
assert.strictEqual(putResponseHeader, testing);
assert.strictEqual(postResponse, expectedResponse);
assert.strictEqual(postResponseHeader, testing);
assert.strictEqual(deleteResponse, expectedResponse);
assert.strictEqual(deleteResponseHeader, testing);
assert.strictEqual(doRequestResponse1, expectedResponse);
assert.strictEqual(doRequestResponseHeader1, testing);
assert.strictEqual(doRequestResponse2, expectedResponse);
assert.strictEqual(doRequestResponseHeader2, testing);
});
it("testing with fetch api methods that doesn't exists", async function () {
AuthHttpRequest.init({
apiDomain: BASE_URL
});
let getResponse = await fetch(`${BASE_URL}/fail`, {
method: "GET"
});
let postResponse = await fetch(`${BASE_URL}/fail`, {
method: "POST"
});
let deleteResponse = await fetch(`${BASE_URL}/fail`, {
method: "DELETE"
});
let putResponse = await fetch(`${BASE_URL}/fail`, {
method: "PUT"
});
let doRequestResponse1 = await fetch(`${BASE_URL}/fail`, { method: "GET" });
let doRequestResponse2 = await fetch(`${BASE_URL}/fail`, { method: "GET" });
let getResponseCode = getResponse.status;
let putResponseCode = putResponse.status;
let postResponseCode = postResponse.status;
let deleteResponseCode = deleteResponse.status;
let doRequestResponseCode1 = doRequestResponse1.status;
let doRequestResponseCode2 = doRequestResponse2.status;
let expectedStatusCode = 404;
assert.strictEqual(getResponseCode, expectedStatusCode);
assert.strictEqual(putResponseCode, expectedStatusCode);
assert.strictEqual(postResponseCode, expectedStatusCode);
assert.strictEqual(deleteResponseCode, expectedStatusCode);
assert.strictEqual(doRequestResponseCode1, expectedStatusCode);
assert.strictEqual(doRequestResponseCode2, expectedStatusCode);
});
it("test refresh session with fetch", async function () {
await startST(3);
const browser = await puppeteer.launch({
args: ["--no-sandbox", "--disable-setuid-sandbox"]
});
try {
const page = await browser.newPage();
await page.goto(BASE_URL + "/index.html", { waitUntil: "load" });
await page.addScriptTag({ path: `./bundle/bundle.js`, type: "text/javascript" });
await page.evaluate(async () => {
let BASE_URL = "http://localhost.org:8080";
supertokens.init({
apiDomain: BASE_URL
});
let userId = "testing-supertokens-website";
let loginResponse = await fetch(`${BASE_URL}/login`, {
method: "post",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({ userId })
});
assertEqual(await loginResponse.text(), userId);
//delay for 5 seconds for access token validity expiry
await delay(5);
//check that the number of times the refreshAPI was called is 0
assertEqual(await getNumberOfTimesRefreshCalled(), 0);
let getResponse = await fetch(`${BASE_URL}/`);
//check that the response to getSession was success
assertEqual(await getResponse.text(), userId);
//check that the number of time the refreshAPI was called is 1
assertEqual(await getNumberOfTimesRefreshCalled(), 1);
});
} finally {
await browser.close();
}
});
it("test duplicate access cookies makes refresh throw a 500 error in case backend doesn't have olderCookieDomain set", async function () {
await startST(3);
const browser = await puppeteer.launch({
args: ["--no-sandbox", "--disable-setuid-sandbox"]
});
try {
const page = await browser.newPage();
await page.goto(BASE_URL + "/index.html", { waitUntil: "load" });
await page.addScriptTag({ path: `./bundle/bundle.js`, type: "text/javascript" });
await page.evaluate(async () => {
let BASE_URL = "http://localhost.org:8080";
supertokens.init({
apiDomain: BASE_URL
});
let userId = "testing-supertokens-website";
let loginResponse = await fetch(`${BASE_URL}/login`, {
method: "post",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({ userId })
});
assertEqual(await loginResponse.text(), userId);
});
let cookies = await page.cookies();
let accessTokenValue = cookies.filter(c => c.name === "sAccessToken")[0].value;
await page.setCookie({
name: "sAccessToken",
path: "/",
value: accessTokenValue,
domain: ".localhost.org"
});
if (!(await checkIfDuplicateCookieHandlingIsEnabled())) {
await page.evaluate(async () => {
await supertokens.attemptRefreshingSession();
});
} else {
await page.evaluate(async () => {
try {
await supertokens.attemptRefreshingSession();
throw new Error("test failed");
} catch (err) {
assertEqual(err.status, 500);
let responseText = await err.text();
let textContainsCorrectMessage = responseText.includes(
"The request contains multiple session cookies."
);
assertEqual(true, textContainsCorrectMessage);
}
});
}
} finally {
await browser.close();
}
});
it("test duplicate refresh cookies makes refresh throw a 500 error in case backend doesn't have olderCookieDomain set", async function () {
await startST(3);
const browser = await puppeteer.launch({
args: ["--no-sandbox", "--disable-setuid-sandbox"]
});
try {
const page = await browser.newPage();
await page.goto(BASE_URL + "/index.html", { waitUntil: "load" });
await page.addScriptTag({ path: `./bundle/bundle.js`, type: "text/javascript" });
await page.evaluate(async () => {
let BASE_URL = "http://localhost.org:8080";
supertokens.init({
apiDomain: BASE_URL
});
let userId = "testing-supertokens-website";
let loginResponse = await fetch(`${BASE_URL}/login`, {
method: "post",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({ userId })
});
assertEqual(await loginResponse.text(), userId);
});
let cookies = await page.cookies(BASE_URL + "/auth/session/refresh");
let refreshTokenValue = cookies.filter(c => c.name === "sRefreshToken")[0].value;
await page.setCookie({
name: "sRefreshToken",
path: "/",
value: refreshTokenValue,
domain: ".localhost.org"
});
if (!(await checkIfDuplicateCookieHandlingIsEnabled())) {
console.log("Skipping testing with duplicate refresh cookies");
await page.evaluate(async () => {
await supertokens.attemptRefreshingSession();
});
} else {
console.log("Testing duplicate refresh cookies");
await page.evaluate(async () => {
try {
await supertokens.attemptRefreshingSession();
throw new Error("test failed");
} catch (err) {
assertEqual(err.status, 500);
let responseText = await err.text();
let textContainsCorrectMessage = responseText.includes(
"The request contains multiple session cookies."
);
assertEqual(true, textContainsCorrectMessage);
}
});
}
} finally {
await browser.close();
}
});
it("test refresh session without refresh token and only access token clears all tokens", async function () {
await startST(3);
const browser = await puppeteer.launch({
args: ["--no-sandbox", "--disable-setuid-sandbox"]
});
try {
const page = await browser.newPage();
await page.goto(BASE_URL + "/index.html", { waitUntil: "load" });
await page.addScriptTag({ path: `./bundle/bundle.js`, type: "text/javascript" });
await page.evaluate(async () => {
let BASE_URL = "http://localhost.org:8080";
supertokens.init({
apiDomain: BASE_URL
});
let userId = "testing-supertokens-website";
let loginResponse = await fetch(`${BASE_URL}/login`, {
method: "post",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({ userId })
});
assertEqual(await loginResponse.text(), userId);
});
await page.deleteCookie({
name: "sRefreshToken",
path: "/auth/session/refresh"
});
await page.evaluate(async () => {
let attemptRefresh = await supertokens.attemptRefreshingSession();
assertEqual(attemptRefresh, false);
});
let cookies = await page.cookies();
if (!(await checkIfDuplicateCookieHandlingIsEnabled())) {
assert(cookies.length === 2); // just st-las-access-token-update should be there
} else {
assert(cookies.length === 1); // just st-las-access-token-update should be there
}
} finally {
await browser.close();
}
});
it("test session after signing key change", async function () {
// We can have access tokens valid for longer than the signing key update interval
await startST(100, true, "0.002");
const browser = await puppeteer.launch({
args: ["--no-sandbox", "--disable-setuid-sandbox"]
});
try {
const page = await browser.newPage();
await page.goto(BASE_URL + "/index.html", { waitUntil: "load" });
// page.on('console', console.log);
await page.addScriptTag({ path: `./bundle/bundle.js`, type: "text/javascript" });
await page.evaluate(async coreSupportsMultipleSignigKeys => {
let BASE_URL = "http://localhost.org:8080";
supertokens.init({
apiDomain: BASE_URL
});
let userId = "testing-supertokens-website";
let loginResponse = await fetch(`${BASE_URL}/login`, {
method: "post",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({ userId })
});
assertEqual(await loginResponse.text(), userId);
//delay for 11 seconds for access token signing key to change
assertEqual(await getNumberOfTimesRefreshCalled(), 0);
await delay(11);
//check that the number of times the refreshAPI was called is 0
assertEqual(await getNumberOfTimesRefreshCalled(), 0);
const promises = [];
for (let i = 0; i < 250; i++) {
promises.push(fetch(`${BASE_URL}/`).catch(() => {}));
}
await Promise.all(promises);
assertEqual(await getNumberOfTimesRefreshCalled(), coreSupportsMultipleSignigKeys ? 0 : 1);
}, coreTagEqualToOrAfter("3.6.0"));
} finally {
await browser.close();
}
});
it("test sameSite is none if using iframe", async function () {
await startST(3);
const browser = await puppeteer.launch({
args: ["--no-sandbox", "--disable-setuid-sandbox"]
});
try {
const page = await browser.newPage();
await page.goto(BASE_URL + "/index.html", { waitUntil: "load" });
await page.addScriptTag({ path: `./bundle/bundle.js`, type: "text/javascript" });
await page.evaluate(async () => {
let BASE_URL = "http://localhost.org:8080";
supertokens.init({
apiDomain: BASE_URL,
isInIframe: true
});
let userId = "testing-supertokens-website";
await fetch(`${BASE_URL}/login`, {
method: "post",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({ userId })
});
});
let cookies = await page.cookies();
assert(cookies.length === 0);
} finally {
await browser.close();
}
});
it("test rid is there", async function () {
await startST(3);
const browser = await puppeteer.launch({
args: ["--no-sandbox", "--disable-setuid-sandbox"]
});
try {
const page = await browser.newPage();
await page.goto(BASE_URL + "/index.html", { waitUntil: "load" });
await page.addScriptTag({ path: `./bundle/bundle.js`, type: "text/javascript" });
await page.evaluate(async () => {
let BASE_URL = "http://localhost.org:8080";
supertokens.init({
apiDomain: BASE_URL
});
let userId = "testing-supertokens-website";
let loginResponse = await fetch(`${BASE_URL}/login`, {
method: "post",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({ userId })
});
assertEqual(await loginResponse.text(), userId);
let getResponse = await fetch(`${BASE_URL}/check-rid`);
assertEqual(await getResponse.text(), "success");
});
} finally {
await browser.close();
}
});
it("signout with expired access token", async function () {
await startST();
const browser = await puppeteer.launch({
args: ["--no-sandbox", "--disable-setuid-sandbox"]
});
try {
const page = await browser.newPage();
await page.goto(BASE_URL + "/index.html", { waitUntil: "load" });
await page.addScriptTag({ path: `./bundle/bundle.js`, type: "text/javascript" });
await page.evaluate(async () => {
let BASE_URL = "http://localhost.org:8080";
supertokens.init({
apiDomain: BASE_URL
});
let userId = "testing-supertokens-website";
let loginResponse = await fetch(`${BASE_URL}/login`, {
method: "post",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({ userId })
});
assertEqual(await loginResponse.text(), userId);
await delay(5);
assertEqual(await getNumberOfTimesRefreshCalled(), 0);
await supertokens.signOut();
assertEqual(await getNumberOfTimesRefreshCalled(), 1);
assertEqual(await supertokens.doesSessionExist(), false);
});
} finally {
await browser.close();
}
});
it("signout with not expired access token", async function () {
await startST();
const browser = await puppeteer.launch({
args: ["--no-sandbox", "--disable-setuid-sandbox"]
});
try {
const page = await browser.newPage();
await page.goto(BASE_URL + "/index.html", { waitUntil: "load" });
await page.addScriptTag({ path: `./bundle/bundle.js`, type: "text/javascript" });
await page.evaluate(async () => {
let BASE_URL = "http://localhost.org:8080";
supertokens.init({
apiDomain: BASE_URL
});
let userId = "testing-supertokens-website";
let loginResponse = await fetch(`${BASE_URL}/login`, {
method: "post",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({ userId })
});
assertEqual(await loginResponse.text(), userId);
assertEqual(await getNumberOfTimesRefreshCalled(), 0);
await supertokens.signOut();
assertEqual(await getNumberOfTimesRefreshCalled(), 0);
assertEqual(await supertokens.doesSessionExist(), false);
});
} finally {
await browser.close();
}
});
// it("refresh session via reading of frontend info using fetch", async function () {
// await startST();
// const browser = await puppeteer.launch({
// args: ["--no-sandbox", "--disable-setuid-sandbox"]
// });
// try {
// const page = await browser.newPage();
// await page.goto(BASE_URL + "/index.html", { waitUntil: "load" });
// await page.addScriptTag({ path: `./bundle/bundle.js`, type: "text/javascript" });
// await page.evaluate(async () => {
// let BASE_URL = "http://localhost.org:8080";
// supertokens.init({
// apiDomain: BASE_URL
// });
// let userId = "testing-supertokens-website";
// let loginResponse = await fetch(`${BASE_URL}/login`, {
// method: "post",
// headers: {
// Accept: "application/json",
// "Content-Type": "application/json"
// },
// body: JSON.stringify({ userId })
// });
// assertEqual(await loginResponse.text(), userId);
// let testResponse1 = await fetch(`${BASE_URL}/update-jwt`, {
// method: "post",
// headers: {
// Accept: "application/json",
// "Content-Type": "application/json"
// },
// body: JSON.stringify({ key: "data" })
// });
// await delay(3);
// assertEqual(await getNumberOfTimesRefreshCalled(), 0);
// let data = await supertokens.getAccessTokenPayloadSecurely();
// assertEqual(await getNumberOfTimesRefreshCalled(), 1);
// assertEqual(data.key === "data", true);
// let data2 = await supertokens.getAccessTokenPayloadSecurely();
// assertEqual(data2.key === "data", true);
// assertEqual(await getNumberOfTimesRefreshCalled(), 1);
// });
// } finally {
// await browser.close();
// }
// });
//test custom headers are being sent when logged in and when not*****
it("test with fetch that custom headers are being sent", async function () {
await startST();
const browser = await puppeteer.launch({
args: ["--no-sandbox", "--disable-setuid-sandbox"]
});
try {
const page = await browser.newPage();
await page.goto(BASE_URL + "/index.html", { waitUntil: "load" });
await page.addScriptTag({ path: `./bundle/bundle.js`, type: "text/javascript" });
await page.evaluate(async () => {
let BASE_URL = "http://localhost.org:8080";
supertokens.init({
apiDomain: BASE_URL
});
let userId = "testing-supertokens-website";
//send loing request
let loginResponse = await fetch(`${BASE_URL}/login`, {
method: "post",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({ userId })
});
assertEqual(await loginResponse.text(), userId);
//send api request with custom headers and check that they are set
let testResponse = await fetch(`${BASE_URL}/testing`, {
method: "post",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
testing: "testValue"
}
});
// check that output is success
assertEqual(await testResponse.text(), "success");
//check that the custom headers are present
assertEqual(await testResponse.headers.get("testing"), "testValue");
//send logout request
let logoutResponse = await fetch(`${BASE_URL}/logout`, {
method: "post",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({ userId })
});
assertEqual(await logoutResponse.text(), "success");
let testResponse2 = await fetch(`${BASE_URL}/testing`, {
method: "post",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
testing: "testValue"
}
});
// check that output is success
assertEqual(await testResponse2.text(), "success");
//check that the custom headers are present
assertEqual(await testResponse2.headers.get("testing"), "testValue");
});
} finally {
await browser.close();
}
});
//testing doesSessionExist works fine when user is logged in******
it("test with fetch that doesSessionExist works fine when the user is logged in", async function () {
await startST(5);
const browser = await puppeteer.launch({
args: ["--no-sandbox", "--disable-setuid-sandbox"]
});
try {
const page = await browser.newPage();
await page.goto(BASE_URL + "/index.html", { waitUntil: "load" });
await page.addScriptTag({ path: `./bundle/bundle.js`, type: "text/javascript" });
await page.evaluate(async () => {
let BASE_URL = "http://localhost.org:8080";
supertokens.init({
apiDomain: BASE_URL
});
let userId = "testing-supertokens-website";
//send loing request
let loginResponse = await fetch(`${BASE_URL}/login`, {
method: "post",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({ userId })
});
assertEqual(await loginResponse.text(), userId);
assertEqual(await supertokens.doesSessionExist(), true);
});
} finally {
await browser.close();
}
});
//session should not exist when user calls log out - use doesSessionExist & check localstorage is empty
it("test with fetch session should not exist when user calls log out", async function () {
await startST(5);
const browser = await puppeteer.launch({
args: ["--no-sandbox", "--disable-setuid-sandbox"]
});
try {
const page = await browser.newPage();
await page.goto(BASE_URL + "/index.html", { waitUntil: "load" });
await page.addScriptTag({ path: `./bundle/bundle.js`, type: "text/javascript" });
await page.evaluate(async () => {
function getAntiCSRFromCookie() {
let value = "; " + document.cookie;
let parts = value.split("; sAntiCsrf=");
if (parts.length >= 2) {
let last = parts.pop();
if (last !== undefined) {
return last;
}
}
return null;
}
let BASE_URL = "http://localhost.org:8080";
supertokens.init({
apiDomain: BASE_URL
});
let userId = "testing-supertokens-website";
// send api request to login
let loginResponse = await fetch(`${BASE_URL}/login`, {
method: "post",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({ userId })
});
assertEqual(await loginResponse.text(), userId);
assertEqual(await supertokens.doesSessionExist(), true);
assertEqual(getAntiCSRFromCookie() !== null, true);
let userIdFromToken = await supertokens.getUserId();
assertEqual(userIdFromToken, userId);
// send api request to logout
let logoutResponse = await fetch(`${BASE_URL}/logout`, {
method: "post",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({ userId })
});
assertEqual(await logoutResponse.text(), "success");
assertEqual(await supertokens.doesSessionExist(), false);
assertEqual(getAntiCSRFromCookie() === null, true);
try {
await supertokens.getUserId();
throw new Error("test failed");
} catch (err) {
assertEqual(err.message, "No session exists");
}
try {
await supertokens.getAccessTokenPayloadSecurely();
throw new Error("test failed");
} catch (err) {
assertEqual(err.message, "No session exists");
}
});
} finally {
await browser.close();
}
});
// testing attemptRefreshingSession works fine******
it("test with fetch that attemptRefreshingSession is working correctly", async function () {
await startST(5);
const browser = await puppeteer.launch({
args: ["--no-sandbox", "--disable-setuid-sandbox"]
});
try {
const page = await browser.newPage();
await page.goto(BASE_URL + "/index.html", { waitUntil: "load" });
await page.addScriptTag({ path: `./bundle/bundle.js`, type: "text/javascript" });
await page.evaluate(async () => {
let BASE_URL = "http://localhost.org:8080";
supertokens.init({
apiDomain: BASE_URL
});
let userId = "testing-supertokens-website";
// send api request to login
let loginResponse = await fetch(`${BASE_URL}/login`, {
method: "post",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({ userId })
});
assertEqual(await loginResponse.text(), userId);
await delay(5);
let attemptRefresh = await supertokens.attemptRefreshingSession();
assertEqual(attemptRefresh, true);
//check that the number of times the refresh API was called is 1
assertEqual(await getNumberOfTimesRefreshCalled(), 1);
let getSessionResponse = await fetch(`${BASE_URL}/`);
assertEqual(await getSessionResponse.text(), userId);
//check that the number of times the refresh API was called is still 1
assertEqual(await getNumberOfTimesRefreshCalled(), 1);
});
} finally {
await browser.close();
}
});
// multiple API calls in parallel when access token is expired (100 of them) and only 1 refresh should be called*****
it("test with fetch that multiple API calls in parallel when access token is expired, only 1 refresh should be called", async function () {
await startST(15);
const browser = await puppeteer.launch({
args: ["--no-sandbox", "--disable-setuid-sandbox"]
});
try {
const page = await browser.newPage();
await page.goto(BASE_URL + "/index.html", { waitUntil: "load" });
await page.addScriptTag({ path: `./bundle/bundle.js`, type: "text/javascript" });
await page.evaluate(async () => {
let BASE_URL = "http://localhost.org:8080";
supertokens.init({
apiDomain: BASE_URL
});
let userId = "testing-supertokens-website";
// send api request to login
let loginResponse = await fetch(`${BASE_URL}/login`, {
method: "post",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({ userId })
});
assertEqual(await loginResponse.text(), userId);
assertEqual(await getNumberOfTimesRefreshCalled(), 0);
// wait for 7 seconds so that the accesstoken expires
await delay(17);
let promises = [];
let n = 100;
// create an array of 100 get session promises
for (let i = 0; i < n; i++) {
promises.push(
fetch(`${BASE_URL}/`, { method: "GET", headers: { "Cache-Control": "no-cache, private" } })
);
}
// send 100 get session requests
let multipleGetSessionResponse = await Promise.all(promises);
//check that reponse of all requests are success
let noOfResponeSuccesses = 0;
for (let i = 0; i < multipleGetSessionResponse.length; i++) {
assertEqual(await multipleGetSessionResponse[i].text(), userId);
noOfResponeSuccesses += 1;
}
//check that the number of times refresh is called is 1
assertEqual(await getNumberOfTimesRefreshCalled(), 1);
assertEqual(noOfResponeSuccesses, n);
});
} finally {
await browser.close();
}
});
// - Things should work if anti-csrf is disabled.******
it("test with fetch that things should work correctly if anti-csrf is disabled", async function () {
await startST(3, false);
const browser = await puppeteer.launch({
args: ["--no-sandbox", "--disable-setuid-sandbox"]
});
try {
const page = await browser.newPage();
await page.goto(BASE_URL + "/index.html", { waitUntil: "load" });
await page.addScriptTag({ path: `./bundle/bundle.js`, type: "text/javascript" });
await page.evaluate(async () => {
let BASE_URL = "http://localhost.org:8080";
supertokens.init({
apiDomain: BASE_URL
});
let userId = "testing-supertokens-website";