-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathindex.test.ts
More file actions
902 lines (812 loc) · 36.1 KB
/
index.test.ts
File metadata and controls
902 lines (812 loc) · 36.1 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
/*
* 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, ShopperLogin} 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 {ApiClientConfigParams, 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(''),
authorizePasswordless: jest.fn().mockResolvedValue(''),
getPasswordLessAccessToken: jest.fn().mockResolvedValue('')
},
ShopperCustomers: jest.fn().mockImplementation(() => {
return {
updateCustomerPassword: () => {}
}
})
}
})
jest.mock('../utils', () => ({
__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 configPasswordlessSms = {
clientId: 'clientId',
organizationId: 'organizationId',
shortCode: 'shortCode',
siteId: 'siteId',
proxy: 'proxy',
redirectURI: 'redirectURI',
logger: console
}
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: 'token_type_abc',
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: 'token_type',
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: 'token_type',
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: 'token_type',
usid: 'usid',
customer_type: 'guest',
refresh_token_expires_in: 'refresh_token_expires_in'
}
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)
// 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: 'token_type',
usid: 'usid',
customer_type: 'guest',
refresh_token_expires_in: 30 * 24 * 3600
}
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()
const funcArg = (helpers.refreshAccessToken as jest.Mock).mock.calls[0][2]
expect(funcArg).toMatchObject({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: 'token_type',
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.each([
// When user has not selected DNT pref
[true, undefined, {dnt: true}],
[false, undefined, {dnt: false}],
[undefined, undefined, {dnt: false}],
// When user has selected DNT, the dw_dnt cookie sets dnt
[true, '0', {dnt: false}],
[false, '1', {dnt: true}],
[false, '0', {dnt: false}]
])(
'dnt flag is set correctly for defaultDnt=`%p`, dw_dnt=`%i`, expected=`%s`',
async (defaultDnt, dw_dnt, expected) => {
const auth = new Auth({...config, defaultDnt})
if (dw_dnt) {
// @ts-expect-error private method
auth.set('dw_dnt', dw_dnt)
}
await auth.loginGuestUser()
expect(helpers.loginGuestUser).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining(expected)
)
const expectedDnt = 'dnt' in expected ? expected.dnt : false
const dntPref = auth.getDnt({
includeDefaults: true
})
expect(dntPref).toBe(expectedDnt)
}
)
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
? undefined
: 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
? undefined
: 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)
}
)
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][2]
expect(funcArg).toMatchObject({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][1]
expect(functionArg).toMatchObject({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][1]
expect(functionArg).toMatchObject({
username: 'test',
password: 'test',
clientSecret: SLAS_SECRET_PLACEHOLDER
})
})
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][2]
expect(functionArg).toMatchObject({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][1]
expect(functionArg).toMatchObject({
clientSecret: SLAS_SECRET_PLACEHOLDER
})
})
test('authorizeIDP calls isomorphic authorizeIDP', async () => {
const auth = new Auth(config)
await auth.authorizeIDP({redirectURI: 'redirectURI', hint: 'test'})
expect(helpers.authorizeIDP).toHaveBeenCalled()
const functionArg = (helpers.authorizeIDP as jest.Mock).mock.calls[0][1]
expect(functionArg).toMatchObject({redirectURI: 'redirectURI', hint: 'test'})
})
test('authorizeIDP adds clientSecret to parameters when using private client', async () => {
const auth = new Auth(configSLASPrivate)
await auth.authorizeIDP({redirectURI: 'test', hint: 'test'})
expect(helpers.authorizeIDP).toHaveBeenCalled()
const privateClient = (helpers.authorizeIDP as jest.Mock).mock.calls[0][2]
expect(privateClient).toBe(true)
})
test('authorizePasswordless calls isomorphic authorizePasswordless', async () => {
const auth = new Auth(config)
await auth.authorizePasswordless({
callbackURI: 'callbackURI',
userid: 'userid',
mode: 'callback'
})
expect(helpers.authorizePasswordless).toHaveBeenCalled()
const functionArg = (helpers.authorizePasswordless as jest.Mock).mock.calls[0][2]
expect(functionArg).toMatchObject({
callbackURI: 'callbackURI',
userid: 'userid',
mode: 'callback'
})
})
test('authorizePasswordless sets mode to sms as configured', async () => {
const auth = new Auth(configPasswordlessSms)
await auth.authorizePasswordless({userid: 'userid', mode: 'sms'})
expect(helpers.authorizePasswordless).toHaveBeenCalled()
const functionArg = (helpers.authorizePasswordless as jest.Mock).mock.calls[0][2]
expect(functionArg).toMatchObject({userid: 'userid', mode: 'sms'})
})
test('getPasswordLessAccessToken calls isomorphic getPasswordLessAccessToken', async () => {
const auth = new Auth(config)
await auth.getPasswordLessAccessToken({pwdlessLoginToken: '12345678'})
expect(helpers.getPasswordLessAccessToken).toHaveBeenCalled()
const functionArg = (helpers.getPasswordLessAccessToken as jest.Mock).mock.calls[0][2]
expect(functionArg).toMatchObject({pwdlessLoginToken: '12345678'})
})
test('logout as registered user calls isomorphic logout', async () => {
const auth = new Auth(config)
// @ts-expect-error private method
// simulate logging in as login function is mocked
auth.set('customer_type', 'registered')
await auth.logout()
expect(helpers.logout).toHaveBeenCalled()
expect(helpers.loginGuestUser).toHaveBeenCalled()
})
test('logout as guest user does not call isomorphic logout', async () => {
const auth = new Auth(config)
await auth.logout()
expect(helpers.logout).not.toHaveBeenCalled()
expect(helpers.loginGuestUser).toHaveBeenCalled()
})
test('updateCustomerPassword calls registered login', async () => {
const auth = new Auth(config)
await auth.updateCustomerPassword({
customer: baseCustomer,
password: 'test123',
currentPassword: 'test12',
shouldReloginCurrentSession: true
})
expect(helpers.loginRegisteredUserB2C).toHaveBeenCalled()
})
test('PWA private client mode takes priority', async () => {
const auth = new Auth({...configSLASPrivate, clientSecret: 'someSecret'})
await auth.loginGuestUser()
expect(helpers.loginGuestUserPrivate).toHaveBeenCalled()
const funcArg = (helpers.loginGuestUserPrivate as jest.Mock).mock.calls[0][2]
expect(funcArg).toMatchObject({clientSecret: SLAS_SECRET_PLACEHOLDER})
})
test('Can set a client secret', async () => {
const auth = new Auth({...config, clientSecret: 'someSecret'})
await auth.loginGuestUser()
expect(helpers.loginGuestUserPrivate).toHaveBeenCalled()
const funcArg = (helpers.loginGuestUserPrivate as jest.Mock).mock.calls[0][2]
expect(funcArg).toMatchObject({clientSecret: 'someSecret'})
})
test('running on the server uses a shared context memory store', () => {
const refreshTokenGuest = 'guest'
// Mock running on the server so shared context storage is used.
// @ts-expect-error read-only property
utils.onClient = () => false
// Create a new auth instance and set its guest token.
const authA = new Auth({...config, siteId: 'siteA'})
// @ts-expect-error private method
authA.set('refresh_token_guest', refreshTokenGuest)
// @ts-expect-error private property
expect([...authA.stores['memory'].map.keys()]).toEqual([`cc-nx-g_siteA`])
// Create a second auth instance and ensure that its memory store has previous
// guest tokens set from the first store (this emulates a second lambda request.)
const authB = new Auth({...config, siteId: 'siteB'})
// @ts-expect-error private method
authB.set('refresh_token_guest', refreshTokenGuest)
// @ts-expect-error private property
expect([...authB.stores['memory'].map.keys()]).toEqual([`cc-nx-g_siteA`, `cc-nx-g_siteB`])
// Set mock value back to expected.
// @ts-expect-error read-only property
utils.onClient = () => true
})
test.each([
// When user has not selected DNT pref
[true, '1'],
[false, '0'],
[null, '0']
])('setDNT(true) results dw_dnt=1', async (newDntPref, expectedDwDnt) => {
const auth = new Auth({...config, siteId: 'siteA'})
await auth.setDnt(newDntPref)
expect(auth.get('dw_dnt')).toBe(expectedDwDnt)
})
test('setDNT(null) results in defaultDnt if defaultDnt is defined', async () => {
const auth = new Auth({...config, siteId: 'siteA', defaultDnt: true})
await auth.setDnt(null)
expect(auth.get('dw_dnt')).toBe('1')
})
test('setDNT(true) sets cookie with an expiration time', async () => {
const setDntSpiedOn = jest.spyOn(Auth.prototype as any, 'set')
const auth = new Auth({...config, siteId: 'siteA'})
await auth.setDnt(true)
expect(setDntSpiedOn).toHaveBeenLastCalledWith(
'dw_dnt',
'1',
expect.objectContaining({expires: expect.any(Number)})
)
})
test('setDNT(false) sets cookie with an expiration time', async () => {
const setDntSpiedOn = jest.spyOn(Auth.prototype as any, 'set')
const auth = new Auth({...config, siteId: 'siteA'})
await auth.setDnt(false)
expect(setDntSpiedOn).toHaveBeenLastCalledWith(
'dw_dnt',
'0',
expect.objectContaining({expires: expect.any(Number)})
)
})
test('setDNT(null) sets cookie WITHOUT an expiration time', async () => {
const setDntSpiedOn = jest.spyOn(Auth.prototype as any, 'set')
const auth = new Auth({...config, siteId: 'siteA'})
await auth.setDnt(null)
await waitFor(() => {
expect(setDntSpiedOn).not.toHaveBeenCalledWith(
'dw_dnt',
'1',
expect.objectContaining({expires: expect.any(Number)})
)
})
})
test('getDnt() returns undefined if token and cookie value is conflicting', async () => {
const getSpiedOn = jest.spyOn(Auth.prototype as any, 'get')
const parseSlasJWTSpiedOn = jest.spyOn(Auth.prototype as any, 'parseSlasJWT')
parseSlasJWTSpiedOn.mockReturnValue({
dnt: '1'
})
getSpiedOn.mockReturnValue('0')
const auth = new Auth({...config, siteId: 'siteA'})
auth.getDnt()
await waitFor(() => {
expect(auth.getDnt()).toBeUndefined()
})
})
})
describe('Auth service sends credentials fetch option to the ShopperLogin API', () => {
beforeEach(() => {
jest.clearAllMocks()
})
test('Adds fetch options with credentials when not defined in config', async () => {
const auth = new Auth(config)
await auth.loginGuestUser()
// Ensure the helper method was called
expect(helpers.loginGuestUser).toHaveBeenCalled()
expect(helpers.loginGuestUser).toHaveBeenCalledTimes(1)
// Check that the correct parameters were passed to the helper
const callArguments = (helpers.loginGuestUser as jest.Mock).mock.calls[0]
expect(callArguments).toBeDefined()
expect(callArguments.length).toBeGreaterThan(0)
const shopperLogin: ShopperLogin<ApiClientConfigParams> = callArguments[0]
expect(shopperLogin).toBeDefined()
expect(shopperLogin.clientConfig).toBeDefined()
expect(shopperLogin.clientConfig.fetchOptions).toBeDefined()
// Ensure fetch options include the expected credentials
expect(shopperLogin.clientConfig.fetchOptions.credentials).toBe('same-origin')
})
test('Does not override the credentials in fetch options if already exists', async () => {
const configWithFetchOptions = {
...config,
fetchOptions: {
credentials: 'include'
}
}
const auth = new Auth(configWithFetchOptions)
await auth.loginGuestUser()
// Ensure the helper method was called
expect(helpers.loginGuestUser).toHaveBeenCalled()
expect(helpers.loginGuestUser).toHaveBeenCalledTimes(1)
// Check that the correct parameters were passed to the helper
const callArguments = (helpers.loginGuestUser as jest.Mock).mock.calls[0]
expect(callArguments).toBeDefined()
expect(callArguments.length).toBeGreaterThan(0)
const shopperLogin: ShopperLogin<ApiClientConfigParams> = callArguments[0]
expect(shopperLogin).toBeDefined()
expect(shopperLogin.clientConfig).toBeDefined()
expect(shopperLogin.clientConfig.fetchOptions).toBeDefined()
// Ensure fetch options include the expected credentials
expect(shopperLogin.clientConfig.fetchOptions.credentials).toBe('include')
})
test('Adds credentials to the fetch options if it is missing', async () => {
const configWithFetchOptions = {
...config,
fetchOptions: {
cache: 'no-cache'
}
}
const auth = new Auth(configWithFetchOptions)
await auth.loginGuestUser()
// Ensure the helper method was called
expect(helpers.loginGuestUser).toHaveBeenCalled()
expect(helpers.loginGuestUser).toHaveBeenCalledTimes(1)
// Check that the correct parameters were passed to the helper
const callArguments = (helpers.loginGuestUser as jest.Mock).mock.calls[0]
expect(callArguments).toBeDefined()
expect(callArguments.length).toBeGreaterThan(0)
const shopperLogin: ShopperLogin<ApiClientConfigParams> = callArguments[0]
expect(shopperLogin).toBeDefined()
expect(shopperLogin.clientConfig).toBeDefined()
expect(shopperLogin.clientConfig.fetchOptions).toBeDefined()
// Ensure fetch options include the expected credentials
expect(shopperLogin.clientConfig.fetchOptions.credentials).toBe('same-origin')
})
})