-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathindex.test.ts
More file actions
1569 lines (1385 loc) · 62.3 KB
/
index.test.ts
File metadata and controls
1569 lines (1385 loc) · 62.3 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
/*
* Copyright (c) 2022, Salesforce, Inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import Auth, {AuthData} from './'
import {waitFor} from '@testing-library/react'
import jwt from 'jsonwebtoken'
import {helpers, ShopperCustomersTypes, ShopperCustomers} from 'commerce-sdk-isomorphic'
import * as utils from '../utils'
import {SLAS_SECRET_PLACEHOLDER} from '../constant'
import {ShopperLoginTypes} from 'commerce-sdk-isomorphic'
import {
DEFAULT_SLAS_REFRESH_TOKEN_REGISTERED_TTL,
DEFAULT_SLAS_REFRESH_TOKEN_GUEST_TTL
} from './index'
import {RequireKeys} from '../hooks/types'
const baseCustomer: RequireKeys<ShopperCustomersTypes.Customer, 'login'> = {
customerId: 'customerId',
login: 'test@test.com'
}
// Use memory storage for all our storage types.
jest.mock('./storage', () => {
const originalModule = jest.requireActual('./storage')
return {
...originalModule,
CookieStorage: originalModule.MemoryStorage,
LocalStorage: originalModule.MemoryStorage
}
})
jest.mock('commerce-sdk-isomorphic', () => {
const originalModule = jest.requireActual('commerce-sdk-isomorphic')
return {
...originalModule,
helpers: {
refreshAccessToken: jest.fn().mockResolvedValue(''),
loginGuestUser: jest.fn().mockResolvedValue(''),
loginGuestUserPrivate: jest.fn().mockResolvedValue(''),
loginRegisteredUserB2C: jest.fn().mockResolvedValue(''),
logout: jest.fn().mockResolvedValue(''),
handleTokenResponse: jest.fn().mockResolvedValue(''),
loginIDPUser: jest.fn().mockResolvedValue(''),
authorizeIDP: jest.fn().mockResolvedValue({
url: 'https://example.com/authorize?code_challenge=test&redirect_uri=test',
codeVerifier: 'test-code-verifier'
}),
authorizePasswordless: jest.fn().mockResolvedValue(''),
getPasswordLessAccessToken: jest.fn().mockResolvedValue(''),
createCodeVerifier: jest.fn().mockReturnValue('test-code-verifier'),
generateCodeChallenge: jest.fn().mockResolvedValue('test-code-challenge')
},
ShopperLogin: jest.fn().mockImplementation((config) => ({
clientConfig: {
parameters: {
organizationId: 'organizationId',
clientId: 'clientId',
siteId: 'siteId'
},
fetchOptions: {
credentials: config?.fetchOptions?.credentials || 'same-origin'
}
},
getPasswordResetToken: jest.fn().mockResolvedValue({}),
resetPassword: jest.fn().mockResolvedValue({})
}))
}
})
jest.mock('../utils', () => {
const originalModule = jest.requireActual('../utils')
return {
...originalModule,
__esModule: true,
onClient: () => true,
getParentOrigin: jest.fn().mockResolvedValue(''),
isOriginTrusted: () => false,
getDefaultCookieAttributes: () => {},
isAbsoluteUrl: () => true
}
})
/** The auth data we store has a slightly different shape than what we use. */
type StoredAuthData = Omit<AuthData, 'refresh_token'> & {refresh_token_guest?: string}
const config = {
clientId: 'clientId',
organizationId: 'organizationId',
shortCode: 'shortCode',
siteId: 'siteId',
proxy: 'proxy',
redirectURI: 'redirectURI',
logger: console,
passwordlessLoginCallbackURI: 'passwordlessLoginCallbackURI'
}
const configSLASPrivate = {
...config,
enablePWAKitPrivateClient: true
}
const JWTNotExpired = jwt.sign(
{
exp: Math.floor(Date.now() / 1000) + 1000,
sub: `cc-slas::zzrf_001::scid:xxxxxx::usid:usid`,
isb: `uido:ecom::upn:test@gmail.com::uidn:firstname lastname::gcid:guestuserid::rcid:rcid::chid:siteId`
},
'secret'
)
const JWTExpired = jwt.sign(
{
exp: Math.floor(Date.now() / 1000) - 1000,
sub: `cc-slas::zzrf_001::scid:xxxxxx::usid:usid`,
isb: `uido:ecom::upn:test@gmail.com::uidn:firstname lastname::gcid:guestuserid::rcid:rcid::chid:siteId`
},
'secret'
)
const FAKE_SLAS_EXPIRY = DEFAULT_SLAS_REFRESH_TOKEN_REGISTERED_TTL - 1
const TOKEN_RESPONSE: ShopperLoginTypes.TokenResponse = {
access_token:
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJjYy1zbGFzOjp6enJmXzAwMTo6c2NpZDpjOWM0NWJmZC0wZWQzLTRhYTIteHh4eC00MGY4ODk2MmI4MzY6OnVzaWQ6YjQ4NjUyMzMtZGU5Mi00MDM5LXh4eHgtYWEyZGZjOGMxZWE1IiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJpc2IiOiJ1aWRvOmVjb206OnVwbjpHdWVzdHx8am9obi5kb2VAZXhhbXBsZS5jb206OnVpZG46Sm9obiBEb2U6OmdjaWQ6Z3Vlc3QtMTIzNDU6OnJjaWQ6cmVnaXN0ZXJlZC02Nzg5MCIsImRudCI6InRlc3QifQ.9yKtUb22ExO-Q4VNQRAyIgTm63l3x5z45Uu1FIQa5dQ',
customer_id: 'customer_id_xyz',
enc_user_id: 'enc_user_id_xyz',
expires_in: 1800,
id_token: 'id_token_xyz',
refresh_token: 'refresh_token_xyz',
token_type: 'Bearer',
usid: 'usid_xyz',
idp_access_token: 'idp_access_token_xyz',
// test that this is authoritative and not set to
// `DEFAULT_SLAS_REFRESH_TOKEN_REGISTERED_TTL` when config.refreshTokenRegisteredCookieTTL is not set
refresh_token_expires_in: FAKE_SLAS_EXPIRY
}
describe('Auth', () => {
beforeEach(() => {
jest.clearAllMocks()
})
test('get/set storage value', () => {
const auth = new Auth(config)
const refreshToken = 'test refresh token'
const accessToken = 'test access token'
// @ts-expect-error private method
auth.set('refresh_token_guest', refreshToken)
// @ts-expect-error private method
auth.set('access_token', accessToken)
expect(auth.get('refresh_token_guest')).toBe(refreshToken)
expect(auth.get('access_token')).toBe(accessToken)
// @ts-expect-error private property
expect([...auth.stores['cookie'].map.keys()]).toEqual([`cc-nx-g_siteId`])
// @ts-expect-error private property
expect([...auth.stores['local'].map.keys()]).toEqual([`access_token_siteId`])
})
test('set registered refresh token will clear guest refresh token, vise versa', () => {
const auth = new Auth(config)
const refreshTokenGuest = 'guest'
const refreshTokenRegistered = 'registered'
// @ts-expect-error private method
auth.set('refresh_token_guest', refreshTokenGuest)
// @ts-expect-error private method
auth.set('refresh_token_registered', refreshTokenRegistered)
expect(auth.get('refresh_token_guest')).toBe('')
// @ts-expect-error private method
auth.set('refresh_token_guest', refreshTokenGuest)
expect(auth.get('refresh_token_registered')).toBe('')
})
test('this.data returns the storage value', () => {
const auth = new Auth(config)
const sample: StoredAuthData = {
refresh_token_guest: 'refresh_token_guest',
access_token: 'access_token',
customer_id: 'customer_id',
enc_user_id: 'enc_user_id',
expires_in: 1800,
id_token: 'id_token',
idp_access_token: 'idp_access_token',
token_type: 'Bearer',
usid: 'usid',
customer_type: 'guest',
refresh_token_expires_in: FAKE_SLAS_EXPIRY
}
// Convert stored format to exposed format
const result = {...sample, refresh_token: 'refresh_token_guest'}
delete result.refresh_token_guest
Object.keys(sample).forEach((key) => {
// @ts-expect-error private method
auth.set(key, sample[key])
})
// @ts-expect-error private method
expect(auth.data).toEqual(result)
})
test('isTokenExpired', () => {
const auth = new Auth(config)
// @ts-expect-error private method
expect(auth.isTokenExpired(JWTNotExpired)).toBe(false)
// @ts-expect-error private method
expect(auth.isTokenExpired(JWTExpired)).toBe(true)
// @ts-expect-error private method
expect(() => auth.isTokenExpired()).toThrow()
})
test('getAccessToken from local store', () => {
const auth = new Auth(config)
// @ts-expect-error private method
auth.set('access_token', 'token')
// @ts-expect-error private method
expect(auth.getAccessToken()).toBe('token')
})
test('use SFRA token over local store token if present', () => {
const customerId = 'customerId'
const customerType = 'guest'
const customerTypeUpperCase = 'Guest'
const usid = 'usid'
const sfraJWT = jwt.sign(
{
exp: Math.floor(Date.now() / 1000) + 1000,
isb: `uido:slas::upn:${customerTypeUpperCase}::uidn:Guest User::gcid:${customerId}::chid:siteId`,
sub: `cc-slas::realm::scid:scid::usid:${usid}`
},
'secret'
)
const auth = new Auth(config)
// @ts-expect-error private method
auth.set('access_token', 'token')
// @ts-expect-error private method
auth.set('access_token_sfra', sfraJWT)
// @ts-expect-error private method
expect(auth.getAccessToken()).toBe(sfraJWT)
expect(auth.get('access_token_sfra')).toBeFalsy()
// Check that local store is updated
expect(auth.get('access_token')).toBe(sfraJWT)
expect(auth.get('customer_id')).toBe(customerId)
expect(auth.get('customer_type')).toBe(customerType)
expect(auth.get('usid')).toBe(usid)
})
test('access token is cleared if SFRA sends refresh', () => {
const auth = new Auth(config)
// @ts-expect-error private method
auth.set('access_token', 'token')
// @ts-expect-error private method
auth.set('access_token_sfra', 'refresh')
// @ts-expect-error private method
expect(auth.getAccessToken()).toBeFalsy()
expect(auth.get('access_token_sfra')).toBeFalsy()
})
test('clear SFRA auth tokens', () => {
const auth = new Auth(config)
// @ts-expect-error private method
auth.set('access_token_sfra', '123')
// @ts-expect-error private method
auth.clearSFRAAuthToken()
expect(auth.get('access_token_sfra')).toBeFalsy()
})
test('site switch clears auth storage', () => {
const auth = new Auth(config)
// @ts-expect-error private method
auth.set('access_token', '123')
// @ts-expect-error private method
auth.set('refresh_token_guest', '456')
const switchSiteConfig = {...config, siteId: 'another site'}
const newAuth = new Auth(switchSiteConfig)
expect(newAuth.get('access_token')).not.toBe('123')
expect(newAuth.get('refresh_token_guest')).not.toBe('456')
})
test('ready - re-use pendingToken', async () => {
const auth = new Auth(config)
const data = {
refresh_token: 'refresh_token_guest',
access_token: 'access_token',
customer_id: 'customer_id',
enc_user_id: 'enc_user_id',
expires_in: 1800,
id_token: 'id_token',
idp_access_token: 'idp_access_token',
token_type: 'token_type',
usid: 'usid',
customer_type: 'guest'
}
// @ts-expect-error private method
auth.pendingToken = Promise.resolve(data)
await expect(auth.ready()).resolves.toEqual(data)
})
test('ready - re-use valid access token', async () => {
const auth = new Auth(config)
const data: StoredAuthData = {
refresh_token_guest: 'refresh_token_guest',
access_token: JWTNotExpired,
customer_id: 'customer_id',
enc_user_id: 'enc_user_id',
expires_in: 1800,
id_token: 'id_token',
idp_access_token: 'idp_access_token',
token_type: 'Bearer',
usid: 'usid',
customer_type: 'guest',
refresh_token_expires_in: FAKE_SLAS_EXPIRY
}
// Convert stored format to exposed format
const result = {...data, refresh_token: 'refresh_token_guest'}
delete result.refresh_token_guest
Object.keys(data).forEach((key) => {
// @ts-expect-error private method
auth.set(key, data[key])
})
await expect(auth.ready()).resolves.toEqual(result)
// @ts-expect-error private method
expect(auth.pendingToken).toBeUndefined()
})
test('ready - use `fetchedToken` and short circuit network request', async () => {
const fetchedToken = jwt.sign(
{
sub: `cc-slas::zzrf_001::scid:xxxxxx::usid:usid`,
isb: `uido:ecom::upn:test@gmail.com::uidn:firstname lastname::gcid:guestuserid::rcid:rcid::chid:siteId`
},
'secret'
)
const auth = new Auth({...config, fetchedToken})
jest.spyOn(auth, 'queueRequest')
await auth.ready()
// The "unbound method" isn't being called, so the rule isn't applicable
// eslint-disable-next-line @typescript-eslint/unbound-method
expect(auth.queueRequest).not.toHaveBeenCalled()
// @ts-expect-error private method
expect(auth.pendingToken).toBeUndefined()
})
test('ready - use `fetchedToken` and auth data is populated for registered user', async () => {
const usid = 'usidddddd'
const customerId = 'customerIddddddd'
const fetchedToken = jwt.sign(
{
sub: `cc-slas::zzrf_001::scid:xxxxxx::usid:${usid}`,
isb: `uido:ecom::upn:test@gmail.com::uidn:firstname lastname::gcid:guestuserid::rcid:${customerId}::chid:siteId`
},
'secret'
)
const auth = new Auth({...config, fetchedToken})
await auth.ready()
expect(auth.get('access_token')).toBe(fetchedToken)
expect(auth.get('customer_id')).toBe(customerId)
expect(auth.get('usid')).toBe(usid)
expect(auth.get('customer_type')).toBe('registered')
})
test('ready - use `fetchedToken` and auth data is populated for guest user', async () => {
// isb: `uido:slas::upn:Guest::uidn:Guest User::gcid:bclrdGlbIZlHaRxHsZlWYYxHwZ::chid: `
const usid = 'usidddddd'
const customerId = 'customerIddddddd'
const fetchedToken = jwt.sign(
{
sub: `cc-slas::zzrf_001::scid:xxxxxx::usid:${usid}`,
isb: `uido:ecom::upn:Guest::uidn:firstname lastname::gcid:${customerId}::rcid:registeredCid::chid:siteId`
},
'secret'
)
const auth = new Auth({...config, fetchedToken})
await auth.ready()
expect(auth.get('access_token')).toBe(fetchedToken)
expect(auth.get('customer_id')).toBe(customerId)
expect(auth.get('usid')).toBe(usid)
expect(auth.get('customer_type')).toBe('guest')
})
test('ready - use refresh token when access token is expired', async () => {
const auth = new Auth(config)
// To simulate real-world scenario, let's first test with a good valid token
const data: StoredAuthData = {
refresh_token_guest: 'refresh_token_guest',
access_token: JWTNotExpired,
customer_id: 'customer_id',
enc_user_id: 'enc_user_id',
expires_in: 1800,
id_token: 'id_token',
idp_access_token: 'idp_access_token',
token_type: 'Bearer',
usid: 'usid',
customer_type: 'guest',
refresh_token_expires_in: 0
}
Object.keys(data).forEach((key) => {
// @ts-expect-error private method
auth.set(key, data[key])
})
await auth.ready()
expect(helpers.refreshAccessToken).not.toHaveBeenCalled()
// And then now test with an _expired_ token
// @ts-expect-error private method
auth.set('access_token', JWTExpired)
await auth.ready()
expect(helpers.refreshAccessToken).toHaveBeenCalled()
})
test('ready - use refresh token when access token is expired with slas private client', async () => {
const auth = new Auth(configSLASPrivate)
await auth.ready()
expect(helpers.refreshAccessToken).not.toHaveBeenCalled()
// And then now test with an _expired_ token and a refresh token
// @ts-expect-error private method
auth.set('access_token', JWTExpired)
// @ts-expect-error private method
auth.set('refresh_token_guest', 'refresh_token')
await auth.ready()
expect(helpers.refreshAccessToken).toHaveBeenCalled()
const funcArg = (helpers.refreshAccessToken as jest.Mock).mock.calls[0][0]
expect(funcArg).toMatchObject({credentials: {clientSecret: SLAS_SECRET_PLACEHOLDER}})
})
test('ready - PKCE flow', async () => {
const auth = new Auth(config)
await auth.ready()
expect(helpers.loginGuestUser).toHaveBeenCalled()
})
test('ready - throw error and discard refresh token if refresh token is invalid', async () => {
// Force the mock to throw just for this test
const refreshAccessTokenSpy = jest.spyOn(helpers, 'refreshAccessToken')
refreshAccessTokenSpy.mockRejectedValueOnce({
response: {
json: () => {
return {
status_code: 404,
message: 'test'
}
}
}
})
// To simulate real-world scenario, let's start with an expired access token
const data: StoredAuthData = {
refresh_token_guest: 'refresh_token_guest',
access_token: JWTExpired,
customer_id: 'customer_id',
enc_user_id: 'enc_user_id',
expires_in: 1800,
id_token: 'id_token',
idp_access_token: 'idp_access_token',
token_type: 'Bearer',
usid: 'usid',
customer_type: 'guest',
refresh_token_expires_in: 30 * 24 * 3600
}
const auth = new Auth(config)
Object.keys(data).forEach((key) => {
// @ts-expect-error private method
auth.set(key, data[key])
})
await auth.ready()
// The call to loginGuestUser only executes when refreshAccessToken fails
expect(refreshAccessTokenSpy).toHaveBeenCalled()
expect(auth.get('refresh_token_guest')).toBe('')
expect(helpers.loginGuestUser).toHaveBeenCalled()
})
test('loginGuestUser', async () => {
const auth = new Auth(config)
await auth.loginGuestUser()
expect(helpers.loginGuestUser).toHaveBeenCalled()
})
test('loginGuestUser can pass along custom parameters', async () => {
const parameters = {c_test: 'custom parameter'}
const auth = new Auth(config)
await auth.loginGuestUser(parameters)
// The first argument is the SLAS config, which we don't need to verify in this case
// We only want to see that the custom parameters were included in the second argument
expect(helpers.loginGuestUser).toHaveBeenCalledWith(
expect.objectContaining({
parameters: expect.objectContaining({c_test: 'custom parameter'})
})
)
})
test('register only sends custom parameters to registered login', async () => {
const registerCustomerSpy = jest
.spyOn(ShopperCustomers.prototype, 'registerCustomer')
.mockImplementation()
const auth = new Auth(config)
const inputToRegister = {
customer: baseCustomer,
password: 'test',
someOtherParameter: 'this should not be passed to login',
c_test: 'custom parameter'
}
await auth.register(inputToRegister)
// Body should only include credentials. No other parameters
expect(registerCustomerSpy).toHaveBeenCalledWith(
expect.objectContaining({body: {customer: baseCustomer, password: 'test'}})
)
// We don't need to verify the first and third parameters as they correspond to the SLAS client and mandatory parameters
// The second argument is credentials
// We want to see that only the custom parameters were included in the fourth argument and not any other parameters
expect(helpers.loginRegisteredUserB2C).toHaveBeenCalledWith(
expect.objectContaining({
body: {c_test: 'custom parameter'}
})
)
})
test.each([
{defaultDnt: true, dw_dnt: NaN, expected: {dnt: true}},
{defaultDnt: false, dw_dnt: NaN, expected: {dnt: false}},
{defaultDnt: undefined, dw_dnt: NaN, expected: {dnt: false}},
{defaultDnt: true, dw_dnt: 0, expected: {dnt: false}},
{defaultDnt: false, dw_dnt: 1, expected: {dnt: true}},
{defaultDnt: false, dw_dnt: 0, expected: {dnt: false}}
])(
'dnt flag is set correctly for defaultDnt=`$defaultDnt`, dw_dnt=`$dw_dnt`, expected=`$expected`',
async ({defaultDnt, dw_dnt, expected}) => {
const auth = new Auth({
...config,
defaultDnt
})
// Set the correct cookie value based on dw_dnt
if (!isNaN(dw_dnt)) {
// @ts-expect-error private method
auth.set('dw_dnt', String(dw_dnt))
}
await auth.loginGuestUser()
expect(helpers.loginGuestUser).toHaveBeenCalledWith(
expect.objectContaining({
parameters: expect.objectContaining(expected)
})
)
}
)
test.each([
// auth config | expected return value
[undefined, DEFAULT_SLAS_REFRESH_TOKEN_REGISTERED_TTL, true],
[undefined, DEFAULT_SLAS_REFRESH_TOKEN_REGISTERED_TTL, false],
[0, DEFAULT_SLAS_REFRESH_TOKEN_REGISTERED_TTL, false],
[-1, DEFAULT_SLAS_REFRESH_TOKEN_REGISTERED_TTL, false],
[
DEFAULT_SLAS_REFRESH_TOKEN_REGISTERED_TTL + 1,
DEFAULT_SLAS_REFRESH_TOKEN_REGISTERED_TTL,
false
],
[900, 900, false]
])(
'refreshTokenRegisteredCookieTTL is set correctly for refreshTokenRegisteredCookieTTLValue=`%p`, expected=`%s`',
async (refreshTokenRegisteredCookieTTL, expected, hasNoResponseValue) => {
// Mock the loginRegisteredUserB2C helper to return a token response
TOKEN_RESPONSE.refresh_token_expires_in = hasNoResponseValue
? 0
: DEFAULT_SLAS_REFRESH_TOKEN_REGISTERED_TTL
;(helpers.loginRegisteredUserB2C as jest.Mock).mockResolvedValueOnce(TOKEN_RESPONSE)
const auth = new Auth({...config, refreshTokenRegisteredCookieTTL})
// Call the public method because the getter for refresh_token_expires_in is private
await auth.loginRegisteredUserB2C({username: 'test', password: 'test'})
expect(Number(auth.get('refresh_token_expires_in'))).toBe(expected)
}
)
test.each([
// auth config | expected return value
[undefined, DEFAULT_SLAS_REFRESH_TOKEN_GUEST_TTL, true],
[undefined, DEFAULT_SLAS_REFRESH_TOKEN_GUEST_TTL, false],
[0, DEFAULT_SLAS_REFRESH_TOKEN_GUEST_TTL, false],
[-1, DEFAULT_SLAS_REFRESH_TOKEN_GUEST_TTL, false],
[DEFAULT_SLAS_REFRESH_TOKEN_GUEST_TTL + 1, DEFAULT_SLAS_REFRESH_TOKEN_GUEST_TTL, false],
[900, 900, false]
])(
'refreshTokenGuestCookieTTL is set correctly for refreshTokenGuestCookieTTLValue=`%p`, expected=`%s`',
async (refreshTokenGuestCookieTTL, expected, hasNoResponseValue) => {
// Mock the loginRegisteredUserB2C helper to return a token response
TOKEN_RESPONSE.refresh_token_expires_in = hasNoResponseValue
? 0
: DEFAULT_SLAS_REFRESH_TOKEN_GUEST_TTL
;(helpers.loginGuestUser as jest.Mock).mockResolvedValueOnce(TOKEN_RESPONSE)
const auth = new Auth({...config, refreshTokenGuestCookieTTL})
// Call the public method because the getter for refresh_token_expires_in is private
await auth.loginGuestUser()
expect(Number(auth.get('refresh_token_expires_in'))).toBe(expected)
}
)
describe('USID expiry matches refresh token expiry', () => {
let setSpy: jest.SpyInstance
beforeEach(() => {
setSpy = jest.spyOn(Auth.prototype as any, 'set')
})
afterEach(() => {
setSpy.mockRestore()
})
test('USID is set with expiry matching guest refresh token expiry', async () => {
const customTTL = 1800 // 30 minutes
const auth = new Auth({...config, refreshTokenGuestCookieTTL: customTTL})
// Mock the helper to return token response
const tokenResponse: ShopperLoginTypes.TokenResponse = {
...TOKEN_RESPONSE,
refresh_token_expires_in: customTTL
}
;(helpers.loginGuestUser as jest.Mock).mockResolvedValueOnce(tokenResponse)
await auth.loginGuestUser()
// Verify USID was set with expiry
const usidSetCall = setSpy.mock.calls.find((call) => call[0] === 'usid')
expect(usidSetCall).toBeDefined()
expect(usidSetCall[1]).toBe(tokenResponse.usid)
expect(usidSetCall[2]).toMatchObject({
expires: expect.any(Date)
})
// Verify the expiry date matches the refresh token expiry
const refreshTokenSetCall = setSpy.mock.calls.find(
(call) => call[0] === 'refresh_token_guest'
)
expect(refreshTokenSetCall).toBeDefined()
expect(refreshTokenSetCall[2]).toMatchObject({
expires: expect.any(Date)
})
// Both should have the same expiry date
expect(usidSetCall[2].expires).toEqual(refreshTokenSetCall[2].expires)
})
test('USID is set with expiry matching registered refresh token expiry', async () => {
const customTTL = 7200 // 2 hours
const auth = new Auth({...config, refreshTokenRegisteredCookieTTL: customTTL})
// Mock the helper to return token response
const tokenResponse: ShopperLoginTypes.TokenResponse = {
...TOKEN_RESPONSE,
refresh_token_expires_in: customTTL
}
;(helpers.loginRegisteredUserB2C as jest.Mock).mockResolvedValueOnce(tokenResponse)
await auth.loginRegisteredUserB2C({username: 'test', password: 'test'})
// Verify USID was set with expiry
const usidSetCall = setSpy.mock.calls.find((call) => call[0] === 'usid')
expect(usidSetCall).toBeDefined()
expect(usidSetCall[1]).toBe(tokenResponse.usid)
expect(usidSetCall[2]).toMatchObject({
expires: expect.any(Date)
})
// Verify the expiry date matches the refresh token expiry
const refreshTokenSetCall = setSpy.mock.calls.find(
(call) => call[0] === 'refresh_token_registered'
)
expect(refreshTokenSetCall).toBeDefined()
expect(refreshTokenSetCall[2]).toMatchObject({
expires: expect.any(Date)
})
// Both should have the same expiry date
expect(usidSetCall[2].expires).toEqual(refreshTokenSetCall[2].expires)
})
test('USID expiry uses default guest TTL when no override is provided', async () => {
const auth = new Auth(config)
// Mock the helper to return token response with no refresh_token_expires_in
const tokenResponse = {
...TOKEN_RESPONSE,
refresh_token_expires_in: undefined
} as unknown as ShopperLoginTypes.TokenResponse
;(helpers.loginGuestUser as jest.Mock).mockResolvedValueOnce(tokenResponse)
await auth.loginGuestUser()
// Verify USID was set with expiry
const usidSetCall = setSpy.mock.calls.find((call) => call[0] === 'usid')
expect(usidSetCall).toBeDefined()
expect(usidSetCall[2]).toMatchObject({
expires: expect.any(Date)
})
// Verify the expiry date matches the default guest TTL
const expectedExpiryDate = new Date(
Date.now() + DEFAULT_SLAS_REFRESH_TOKEN_GUEST_TTL * 1000
)
expect(usidSetCall[2].expires.getTime()).toBeCloseTo(expectedExpiryDate.getTime(), -2) // Within 100ms
})
test('USID expiry uses default registered TTL when no override is provided', async () => {
const auth = new Auth(config)
// Mock the helper to return token response with no refresh_token_expires_in
const tokenResponse = {
...TOKEN_RESPONSE,
refresh_token_expires_in: undefined
} as unknown as ShopperLoginTypes.TokenResponse
;(helpers.loginRegisteredUserB2C as jest.Mock).mockResolvedValueOnce(tokenResponse)
await auth.loginRegisteredUserB2C({username: 'test', password: 'test'})
// Verify USID was set with expiry
const usidSetCall = setSpy.mock.calls.find((call) => call[0] === 'usid')
expect(usidSetCall).toBeDefined()
expect(usidSetCall[2]).toMatchObject({
expires: expect.any(Date)
})
// Verify the expiry date matches the default registered TTL
const expectedExpiryDate = new Date(
Date.now() + DEFAULT_SLAS_REFRESH_TOKEN_REGISTERED_TTL * 1000
)
expect(usidSetCall[2].expires.getTime()).toBeCloseTo(expectedExpiryDate.getTime(), -2) // Within 100ms
})
test('USID expiry uses response TTL when provided and no override', async () => {
const responseTTL = 3600 // 1 hour
const auth = new Auth(config)
// Mock the helper to return token response with custom refresh_token_expires_in
const tokenResponse: ShopperLoginTypes.TokenResponse = {
...TOKEN_RESPONSE,
refresh_token_expires_in: responseTTL
}
;(helpers.loginGuestUser as jest.Mock).mockResolvedValueOnce(tokenResponse)
await auth.loginGuestUser()
// Verify USID was set with expiry
const usidSetCall = setSpy.mock.calls.find((call) => call[0] === 'usid')
expect(usidSetCall).toBeDefined()
expect(usidSetCall[2]).toMatchObject({
expires: expect.any(Date)
})
// Verify the expiry date matches the response TTL
const expectedExpiryDate = new Date(Date.now() + responseTTL * 1000)
expect(usidSetCall[2].expires.getTime()).toBeCloseTo(expectedExpiryDate.getTime(), -2) // Within 100ms
})
test('USID expiry respects override TTL when provided', async () => {
const overrideTTL = 900 // 15 minutes
const responseTTL = 3600 // 1 hour (should be ignored)
const auth = new Auth({...config, refreshTokenGuestCookieTTL: overrideTTL})
// Mock the helper to return token response with different refresh_token_expires_in
const tokenResponse: ShopperLoginTypes.TokenResponse = {
...TOKEN_RESPONSE,
refresh_token_expires_in: responseTTL
}
;(helpers.loginGuestUser as jest.Mock).mockResolvedValueOnce(tokenResponse)
await auth.loginGuestUser()
// Verify USID was set with expiry
const usidSetCall = setSpy.mock.calls.find((call) => call[0] === 'usid')
expect(usidSetCall).toBeDefined()
expect(usidSetCall[2]).toMatchObject({
expires: expect.any(Date)
})
// Verify the expiry date matches the override TTL, not the response TTL
const expectedExpiryDate = new Date(Date.now() + overrideTTL * 1000)
expect(usidSetCall[2].expires.getTime()).toBeCloseTo(expectedExpiryDate.getTime(), -2) // Within 100ms
})
})
test('loginGuestUser with slas private', async () => {
const auth = new Auth(configSLASPrivate)
await auth.loginGuestUser()
expect(helpers.loginGuestUserPrivate).toHaveBeenCalled()
const funcArg = (helpers.loginGuestUserPrivate as jest.Mock).mock.calls[0][0]
expect(funcArg).toMatchObject({credentials: {clientSecret: SLAS_SECRET_PLACEHOLDER}})
})
test('loginGuestUser throws error when API has error', async () => {
// Force the mock to throw just for this test
const loginGuestUserSpy = jest.spyOn(helpers, 'loginGuestUser')
loginGuestUserSpy.mockRejectedValueOnce(new Error('test'))
const auth = new Auth(config)
await expect(auth.loginGuestUser()).rejects.toThrow()
expect(helpers.loginGuestUser).toHaveBeenCalled()
})
test('loginRegisteredUserB2C', async () => {
const auth = new Auth(config)
await auth.loginRegisteredUserB2C({
username: 'test',
password: 'test'
})
expect(helpers.loginRegisteredUserB2C).toHaveBeenCalled()
const functionArg = (helpers.loginRegisteredUserB2C as jest.Mock).mock.calls[0][0]
expect(functionArg).toMatchObject({
credentials: {username: 'test', password: 'test'}
})
})
test('loginRegisteredUserB2C with slas private', async () => {
const auth = new Auth(configSLASPrivate)
await auth.loginRegisteredUserB2C({
username: 'test',
password: 'test'
})
expect(helpers.loginRegisteredUserB2C).toHaveBeenCalled()
const functionArg = (helpers.loginRegisteredUserB2C as jest.Mock).mock.calls[0][0]
expect(functionArg).toMatchObject({
credentials: {
username: 'test',
password: 'test',
clientSecret: SLAS_SECRET_PLACEHOLDER
}
})
})
test('loginRegisteredUserB2C can pass along custom parameters', async () => {
const body = {
username: 'test',
password: 'test',
customParameters: {c_test: 'custom parameter'}
}
const auth = new Auth(config)
await auth.loginRegisteredUserB2C(body)
// We don't need to verify the first and third parameters as they correspond to the SLAS client and mandatory parameters
// The second argument is credentials, including the client secret
// The fourth argument is custom parameters
// We only want to see that the custom parameters were included in the fourth argument
expect(helpers.loginRegisteredUserB2C).toHaveBeenCalledWith(
expect.objectContaining({
body: {c_test: 'custom parameter'}
})
)
})
test('loginIDPUser calls isomorphic loginIDPUser', async () => {
const auth = new Auth(config)
await auth.loginIDPUser({redirectURI: 'redirectURI', code: 'test'})
expect(helpers.loginIDPUser).toHaveBeenCalled()
const functionArg = (helpers.loginIDPUser as jest.Mock).mock.calls[0][0]
expect(functionArg).toMatchObject({
parameters: {redirectURI: 'redirectURI', code: 'test'}
})
})
test('loginIDPUser adds clientSecret to parameters when using private client', async () => {
const auth = new Auth(configSLASPrivate)
await auth.loginIDPUser({redirectURI: 'test', code: 'test'})
expect(helpers.loginIDPUser).toHaveBeenCalled()
const functionArg = (helpers.loginIDPUser as jest.Mock).mock.calls[0][0]
expect(functionArg).toMatchObject({
credentials: {
clientSecret: SLAS_SECRET_PLACEHOLDER
}
})
})
test('authorizeIDP calls helpers.authorizeIDP and handles client-side navigation', async () => {
const auth = new Auth(config)
const result = await auth.authorizeIDP({
redirectURI: 'redirectURI',
hint: 'test',
c_customParam: 'customParam'
})
expect(helpers.authorizeIDP).toHaveBeenCalled()
const functionArg = (helpers.authorizeIDP as jest.Mock).mock.calls[0][0]
expect(functionArg).toMatchObject({
parameters: expect.objectContaining({
redirectURI: 'redirectURI',
hint: 'test',
c_customParam: 'customParam'
})
})
// Should return the result from helpers.authorizeIDP
expect(result).toHaveProperty('url')
expect(result).toHaveProperty('codeVerifier')
})
test('authorizeIDP works with private client configuration', async () => {
const auth = new Auth(configSLASPrivate)
const result = await auth.authorizeIDP({redirectURI: 'test', hint: 'test'})
expect(helpers.authorizeIDP).toHaveBeenCalled()
expect(result).toHaveProperty('url')
expect(result).toHaveProperty('codeVerifier')
})
test.each([
[
'with all parameters specified',
{callbackURI: 'callbackURI', userid: 'userid', mode: 'callback', locale: 'en-US'},
{
callbackURI: 'callbackURI',
userid: 'userid',
mode: 'callback',
locale: 'en-US'
}
],
[
'defaults mode to callback when not specified',
{userid: 'userid'},
{userid: 'userid', mode: 'callback'}
],
[
'defaults callbackURI to passwordlessLoginCallbackURI when not specified',
{userid: 'userid'},
{
userid: 'userid',
mode: 'callback',
callbackURI: configSLASPrivate.passwordlessLoginCallbackURI
}
],
['with mode email', {userid: 'userid', mode: 'email'}, {userid: 'userid', mode: 'email'}]
])('authorizePasswordless %s', async (_, input: any, expectedParams: any) => {
const auth = new Auth(configSLASPrivate)
// @ts-expect-error private method
auth.set('usid', 'test-usid-value')
await auth.authorizePasswordless(input)
expect(helpers.authorizePasswordless).toHaveBeenCalled()
const functionArg = (helpers.authorizePasswordless as jest.Mock).mock.calls[0][0]
expect(functionArg).toMatchObject({
credentials: {
clientSecret: SLAS_SECRET_PLACEHOLDER
},
parameters: {
...expectedParams,
usid: 'test-usid-value'
}
})
})
test('authorizePasswordless without usid', async () => {
const auth = new Auth(configSLASPrivate)
await auth.authorizePasswordless({userid: 'userid'})
expect(helpers.authorizePasswordless).toHaveBeenCalled()
const functionArg = (helpers.authorizePasswordless as jest.Mock).mock.calls[0][0]
expect(functionArg).toMatchObject({
parameters: {
userid: 'userid',
mode: 'callback',
callbackURI: configSLASPrivate.passwordlessLoginCallbackURI
}
})
// Verify usid is not in parameters when not set
expect(functionArg.parameters.usid).toBeUndefined()
})
test('authorizePasswordless without passwordlessLoginCallbackURI in config', async () => {
const configWithoutCallback = {
...configSLASPrivate,
passwordlessLoginCallbackURI: undefined
}
const auth = new Auth(configWithoutCallback)
await auth.authorizePasswordless({userid: 'userid'})
expect(helpers.authorizePasswordless).toHaveBeenCalled()
const functionArg = (helpers.authorizePasswordless as jest.Mock).mock.calls[0][0]
// callbackURI should not be in parameters when not configured
expect(functionArg.parameters.callbackURI).toBeUndefined()
})
test('authorizePasswordless throws error on non-200 response', async () => {
const auth = new Auth(configSLASPrivate)
const mockErrorResponse = {
status: 400,
json: jest.fn().mockResolvedValue({message: 'Invalid request'})
}
;(helpers.authorizePasswordless as jest.Mock).mockResolvedValueOnce(mockErrorResponse)
await expect(auth.authorizePasswordless({userid: 'userid'})).rejects.toThrow(
'400 Invalid request'
)
})