forked from RooCodeInc/Roo-Code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebAuthService.spec.ts
More file actions
1272 lines (1031 loc) · 38.5 KB
/
WebAuthService.spec.ts
File metadata and controls
1272 lines (1031 loc) · 38.5 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
// npx vitest run src/__tests__/auth/WebAuthService.spec.ts
import crypto from "crypto"
import type { Mock } from "vitest"
import type { ExtensionContext } from "vscode"
import { WebAuthService } from "../WebAuthService.js"
import { RefreshTimer } from "../RefreshTimer.js"
import { getClerkBaseUrl, getRooCodeApiUrl } from "../config.js"
import { getUserAgent } from "../utils.js"
vi.mock("crypto")
vi.mock("../RefreshTimer")
vi.mock("../config")
vi.mock("../utils")
const mockFetch = vi.fn()
global.fetch = mockFetch
vi.mock("vscode", () => ({
window: {
showInformationMessage: vi.fn(),
showErrorMessage: vi.fn(),
},
env: {
openExternal: vi.fn(),
uriScheme: "vscode",
},
Uri: {
parse: vi.fn((uri: string) => ({ toString: () => uri })),
},
}))
describe("WebAuthService", () => {
let authService: WebAuthService
let mockTimer: {
start: Mock
stop: Mock
reset: Mock
}
let mockLog: Mock
let mockContext: {
subscriptions: { push: Mock }
secrets: {
get: Mock
store: Mock
delete: Mock
onDidChange: Mock
}
globalState: {
get: Mock
update: Mock
}
extension: {
packageJSON: {
version: string
publisher: string
name: string
}
}
}
beforeEach(() => {
// Reset all mocks
vi.clearAllMocks()
// Setup mock context with proper subscriptions array
mockContext = {
subscriptions: {
push: vi.fn(),
},
secrets: {
get: vi.fn().mockResolvedValue(undefined),
store: vi.fn().mockResolvedValue(undefined),
delete: vi.fn().mockResolvedValue(undefined),
onDidChange: vi.fn().mockReturnValue({ dispose: vi.fn() }),
},
globalState: {
get: vi.fn().mockReturnValue(undefined),
update: vi.fn().mockResolvedValue(undefined),
},
extension: {
packageJSON: {
version: "1.0.0",
publisher: "Datacoves",
name: "datacoves-copilot",
},
},
}
// Setup timer mock
mockTimer = {
start: vi.fn(),
stop: vi.fn(),
reset: vi.fn(),
}
const MockedRefreshTimer = vi.mocked(RefreshTimer)
MockedRefreshTimer.mockImplementation(() => mockTimer as unknown as RefreshTimer)
// Setup config mocks - use production URL by default to maintain existing test behavior
vi.mocked(getClerkBaseUrl).mockReturnValue("https://clerk.roocode.com")
vi.mocked(getRooCodeApiUrl).mockReturnValue("https://api.test.com")
// Setup utils mock
vi.mocked(getUserAgent).mockReturnValue("Roo-Code 1.0.0")
// Setup crypto mock
vi.mocked(crypto.randomBytes).mockReturnValue(Buffer.from("test-random-bytes") as never)
// Setup log mock
mockLog = vi.fn()
authService = new WebAuthService(mockContext as unknown as ExtensionContext, mockLog)
})
afterEach(() => {
vi.clearAllMocks()
})
describe("constructor", () => {
it("should initialize with correct default values", () => {
expect(authService.getState()).toBe("initializing")
expect(authService.isAuthenticated()).toBe(false)
expect(authService.hasActiveSession()).toBe(false)
expect(authService.getSessionToken()).toBeUndefined()
expect(authService.getUserInfo()).toBeNull()
})
it("should create RefreshTimer with correct configuration", () => {
expect(RefreshTimer).toHaveBeenCalledWith({
callback: expect.any(Function),
successInterval: 50_000,
initialBackoffMs: 1_000,
maxBackoffMs: 300_000,
})
})
it("should use console.log as default logger", () => {
const serviceWithoutLog = new WebAuthService(mockContext as unknown as ExtensionContext)
// Can't directly test console.log usage, but constructor should not throw
expect(serviceWithoutLog).toBeInstanceOf(WebAuthService)
})
})
describe("initialize", () => {
it("should handle credentials change and setup event listener", async () => {
await authService.initialize()
expect(mockContext.subscriptions.push).toHaveBeenCalled()
expect(mockContext.secrets.onDidChange).toHaveBeenCalled()
})
it("should not initialize twice", async () => {
await authService.initialize()
const firstCallCount = vi.mocked(mockContext.secrets.onDidChange).mock.calls.length
await authService.initialize()
expect(mockContext.secrets.onDidChange).toHaveBeenCalledTimes(firstCallCount)
expect(mockLog).toHaveBeenCalledWith("[auth] initialize() called after already initialized")
})
it("should transition to logged-out when no credentials exist", async () => {
mockContext.secrets.get.mockResolvedValue(undefined)
const authStateChangedSpy = vi.fn()
authService.on("auth-state-changed", authStateChangedSpy)
await authService.initialize()
expect(authService.getState()).toBe("logged-out")
expect(authStateChangedSpy).toHaveBeenCalledWith({
state: "logged-out",
previousState: "initializing",
})
})
it("should transition to attempting-session when valid credentials exist", async () => {
const credentials = {
clientToken: "test-token",
sessionId: "test-session",
}
mockContext.secrets.get.mockResolvedValue(JSON.stringify(credentials))
const authStateChangedSpy = vi.fn()
authService.on("auth-state-changed", authStateChangedSpy)
await authService.initialize()
expect(authService.getState()).toBe("attempting-session")
expect(authStateChangedSpy).toHaveBeenCalledWith({
state: "attempting-session",
previousState: "initializing",
})
expect(mockTimer.start).toHaveBeenCalled()
})
it("should handle invalid credentials gracefully", async () => {
mockContext.secrets.get.mockResolvedValue("invalid-json")
const authStateChangedSpy = vi.fn()
authService.on("auth-state-changed", authStateChangedSpy)
await authService.initialize()
expect(authService.getState()).toBe("logged-out")
expect(mockLog).toHaveBeenCalledWith("[auth] Failed to parse stored credentials:", expect.any(Error))
})
it("should handle credentials change events", async () => {
let onDidChangeCallback: (e: { key: string }) => void
mockContext.secrets.onDidChange.mockImplementation((callback: (e: { key: string }) => void) => {
onDidChangeCallback = callback
return { dispose: vi.fn() }
})
await authService.initialize()
// Simulate credentials change event
const newCredentials = {
clientToken: "new-token",
sessionId: "new-session",
}
mockContext.secrets.get.mockResolvedValue(JSON.stringify(newCredentials))
const authStateChangedSpy = vi.fn()
authService.on("auth-state-changed", authStateChangedSpy)
onDidChangeCallback!({ key: "clerk-auth-credentials" })
await new Promise((resolve) => setTimeout(resolve, 0)) // Wait for async handling
expect(authStateChangedSpy).toHaveBeenCalled()
})
})
describe("login", () => {
beforeEach(async () => {
await authService.initialize()
})
it("should generate state and open external URL", async () => {
const mockOpenExternal = vi.fn()
const vscode = await import("vscode")
vi.mocked(vscode.env.openExternal).mockImplementation(mockOpenExternal)
await authService.login()
expect(crypto.randomBytes).toHaveBeenCalledWith(16)
expect(mockContext.globalState.update).toHaveBeenCalledWith(
"clerk-auth-state",
"746573742d72616e646f6d2d6279746573",
)
expect(mockOpenExternal).toHaveBeenCalledWith(
expect.objectContaining({
toString: expect.any(Function),
}),
)
})
it("should use package.json values for redirect URI with default sign-in endpoint", async () => {
const mockOpenExternal = vi.fn()
const vscode = await import("vscode")
vi.mocked(vscode.env.openExternal).mockImplementation(mockOpenExternal)
await authService.login()
const expectedUrl =
"https://api.test.com/extension/sign-in?state=746573742d72616e646f6d2d6279746573&auth_redirect=vscode%3A%2F%2FDatacoves.datacoves-copilot"
expect(mockOpenExternal).toHaveBeenCalledWith(
expect.objectContaining({
toString: expect.any(Function),
}),
)
// Verify the actual URL
const calledUri = mockOpenExternal.mock.calls[0]?.[0]
expect(calledUri.toString()).toBe(expectedUrl)
})
it("should use provider signup URL when useProviderSignup is true", async () => {
const mockOpenExternal = vi.fn()
const vscode = await import("vscode")
vi.mocked(vscode.env.openExternal).mockImplementation(mockOpenExternal)
await authService.login(undefined, true)
const expectedUrl =
"https://api.test.com/extension/provider-sign-up?state=746573742d72616e646f6d2d6279746573&auth_redirect=vscode%3A%2F%2FDatacoves.datacoves-copilot"
expect(mockOpenExternal).toHaveBeenCalledWith(
expect.objectContaining({
toString: expect.any(Function),
}),
)
// Verify the actual URL
const calledUri = mockOpenExternal.mock.calls[0]?.[0]
expect(calledUri.toString()).toBe(expectedUrl)
})
it("should handle errors during login", async () => {
vi.mocked(crypto.randomBytes).mockImplementation(() => {
throw new Error("Crypto error")
})
await expect(authService.login()).rejects.toThrow("Failed to initiate Roo Code Cloud authentication")
expect(mockLog).toHaveBeenCalledWith("[auth] Error initiating Roo Code Cloud auth: Error: Crypto error")
})
})
describe("handleCallback", () => {
beforeEach(async () => {
await authService.initialize()
})
it("should handle invalid parameters", async () => {
const vscode = await import("vscode")
const mockShowInfo = vi.fn()
vi.mocked(vscode.window.showInformationMessage).mockImplementation(mockShowInfo)
await authService.handleCallback(null, "state")
expect(mockShowInfo).toHaveBeenCalledWith("Invalid Roo Code Cloud sign in url")
await authService.handleCallback("code", null)
expect(mockShowInfo).toHaveBeenCalledWith("Invalid Roo Code Cloud sign in url")
})
it("should validate state parameter", async () => {
mockContext.globalState.get.mockReturnValue("stored-state")
await expect(authService.handleCallback("code", "different-state")).rejects.toThrow(
"Failed to handle Roo Code Cloud callback",
)
expect(mockLog).toHaveBeenCalledWith("[auth] State mismatch in callback")
})
it("should successfully handle valid callback", async () => {
const storedState = "valid-state"
mockContext.globalState.get.mockReturnValue(storedState)
// Mock successful Clerk sign-in response
const mockResponse = {
ok: true,
json: () =>
Promise.resolve({
response: { created_session_id: "session-123" },
}),
headers: {
get: (header: string) => (header === "authorization" ? "Bearer token-123" : null),
},
}
mockFetch.mockResolvedValue(mockResponse)
const vscode = await import("vscode")
const mockShowInfo = vi.fn()
vi.mocked(vscode.window.showInformationMessage).mockImplementation(mockShowInfo)
await authService.handleCallback("auth-code", storedState)
expect(mockContext.secrets.store).toHaveBeenCalledWith(
"clerk-auth-credentials",
JSON.stringify({
clientToken: "Bearer token-123",
sessionId: "session-123",
organizationId: null,
}),
)
expect(mockShowInfo).toHaveBeenCalledWith("Successfully authenticated with Roo Code Cloud")
})
it("should store provider model when provided in callback", async () => {
const storedState = "valid-state"
mockContext.globalState.get.mockReturnValue(storedState)
// Mock successful Clerk sign-in response
const mockResponse = {
ok: true,
json: () =>
Promise.resolve({
response: { created_session_id: "session-123" },
}),
headers: {
get: (header: string) => (header === "authorization" ? "Bearer token-123" : null),
},
}
mockFetch.mockResolvedValue(mockResponse)
const vscode = await import("vscode")
const mockShowInfo = vi.fn()
vi.mocked(vscode.window.showInformationMessage).mockImplementation(mockShowInfo)
await authService.handleCallback("auth-code", storedState, null, "xai/grok-code-fast-1")
expect(mockContext.globalState.update).toHaveBeenCalledWith("roo-provider-model", "xai/grok-code-fast-1")
expect(mockContext.globalState.update).toHaveBeenCalledWith("roo-auth-skip-model", undefined)
expect(mockLog).toHaveBeenCalledWith("[auth] Stored provider model: xai/grok-code-fast-1")
})
it("should set skip model flag when provider model is NOT provided in callback", async () => {
const storedState = "valid-state"
mockContext.globalState.get.mockReturnValue(storedState)
// Mock successful Clerk sign-in response
const mockResponse = {
ok: true,
json: () =>
Promise.resolve({
response: { created_session_id: "session-123" },
}),
headers: {
get: (header: string) => (header === "authorization" ? "Bearer token-123" : null),
},
}
mockFetch.mockResolvedValue(mockResponse)
const vscode = await import("vscode")
const mockShowInfo = vi.fn()
vi.mocked(vscode.window.showInformationMessage).mockImplementation(mockShowInfo)
// Call without provider model
await authService.handleCallback("auth-code", storedState, null)
expect(mockContext.globalState.update).toHaveBeenCalledWith("roo-auth-skip-model", true)
expect(mockLog).toHaveBeenCalledWith("[auth] No provider model selected during signup")
})
it("should handle Clerk API errors", async () => {
const storedState = "valid-state"
mockContext.globalState.get.mockReturnValue(storedState)
mockFetch.mockResolvedValue({
ok: false,
status: 400,
statusText: "Bad Request",
})
const authStateChangedSpy = vi.fn()
authService.on("auth-state-changed", authStateChangedSpy)
await expect(authService.handleCallback("auth-code", storedState)).rejects.toThrow(
"Failed to handle Roo Code Cloud callback",
)
expect(authStateChangedSpy).toHaveBeenCalled()
})
})
describe("logout", () => {
beforeEach(async () => {
await authService.initialize()
})
it("should clear credentials and call Clerk logout", async () => {
// Set up credentials first by simulating a login state
const credentials = {
clientToken: "test-token",
sessionId: "test-session",
}
// Manually set the credentials in the service
authService["credentials"] = credentials
// Mock successful logout response
mockFetch.mockResolvedValue({ ok: true })
const vscode = await import("vscode")
const mockShowInfo = vi.fn()
vi.mocked(vscode.window.showInformationMessage).mockImplementation(mockShowInfo)
await authService.logout()
expect(mockContext.secrets.delete).toHaveBeenCalledWith("clerk-auth-credentials")
expect(mockContext.globalState.update).toHaveBeenCalledWith("clerk-auth-state", undefined)
expect(mockFetch).toHaveBeenCalledWith(
"https://clerk.roocode.com/v1/client/sessions/test-session/remove",
expect.objectContaining({
method: "POST",
headers: expect.objectContaining({
Authorization: "Bearer test-token",
}),
}),
)
expect(mockShowInfo).toHaveBeenCalledWith("Logged out from Roo Code Cloud")
})
it("should handle logout without credentials", async () => {
const vscode = await import("vscode")
const mockShowInfo = vi.fn()
vi.mocked(vscode.window.showInformationMessage).mockImplementation(mockShowInfo)
await authService.logout()
expect(mockContext.secrets.delete).toHaveBeenCalled()
expect(mockFetch).not.toHaveBeenCalled()
expect(mockShowInfo).toHaveBeenCalledWith("Logged out from Roo Code Cloud")
})
it("should handle Clerk logout errors gracefully", async () => {
// Set up credentials first by simulating a login state
const credentials = {
clientToken: "test-token",
sessionId: "test-session",
}
// Manually set the credentials in the service
authService["credentials"] = credentials
// Mock failed logout response
mockFetch.mockRejectedValue(new Error("Network error"))
const vscode = await import("vscode")
const mockShowInfo = vi.fn()
vi.mocked(vscode.window.showInformationMessage).mockImplementation(mockShowInfo)
await authService.logout()
expect(mockLog).toHaveBeenCalledWith("[auth] Error calling clerkLogout:", expect.any(Error))
expect(mockShowInfo).toHaveBeenCalledWith("Logged out from Roo Code Cloud")
})
})
describe("state management", () => {
it("should return correct state", () => {
expect(authService.getState()).toBe("initializing")
})
it("should return correct authentication status", async () => {
await authService.initialize()
expect(authService.isAuthenticated()).toBe(false)
// Create a new service instance with credentials
const credentials = {
clientToken: "test-token",
sessionId: "test-session",
}
mockContext.secrets.get.mockResolvedValue(JSON.stringify(credentials))
const authenticatedService = new WebAuthService(mockContext as unknown as ExtensionContext, mockLog)
await authenticatedService.initialize()
expect(authenticatedService.isAuthenticated()).toBe(true)
expect(authenticatedService.hasActiveSession()).toBe(false)
})
it("should return session token only for active sessions", () => {
expect(authService.getSessionToken()).toBeUndefined()
// Manually set state to active-session for testing
// This would normally happen through refreshSession
authService["state"] = "active-session"
authService["sessionToken"] = "test-jwt"
expect(authService.getSessionToken()).toBe("test-jwt")
})
it("should return correct values for new methods", async () => {
await authService.initialize()
expect(authService.hasOrIsAcquiringActiveSession()).toBe(false)
// Create a new service instance with credentials (attempting-session)
const credentials = {
clientToken: "test-token",
sessionId: "test-session",
}
mockContext.secrets.get.mockResolvedValue(JSON.stringify(credentials))
const attemptingService = new WebAuthService(mockContext as unknown as ExtensionContext, mockLog)
await attemptingService.initialize()
expect(attemptingService.hasOrIsAcquiringActiveSession()).toBe(true)
expect(attemptingService.hasActiveSession()).toBe(false)
// Manually set state to active-session for testing
attemptingService["state"] = "active-session"
expect(attemptingService.hasOrIsAcquiringActiveSession()).toBe(true)
expect(attemptingService.hasActiveSession()).toBe(true)
})
})
describe("session refresh", () => {
beforeEach(async () => {
// Set up with credentials
const credentials = {
clientToken: "test-token",
sessionId: "test-session",
}
mockContext.secrets.get.mockResolvedValue(JSON.stringify(credentials))
await authService.initialize()
})
it("should refresh session successfully", async () => {
// Mock successful token creation and user info fetch
mockFetch
.mockResolvedValueOnce({
ok: true,
json: () => Promise.resolve({ jwt: "new-jwt-token" }),
})
.mockResolvedValueOnce({
ok: true,
json: () =>
Promise.resolve({
response: {
first_name: "John",
last_name: "Doe",
image_url: "https://example.com/avatar.jpg",
primary_email_address_id: "email-1",
email_addresses: [{ id: "email-1", email_address: "john@example.com" }],
},
}),
})
const authStateChangedSpy = vi.fn()
const userInfoSpy = vi.fn()
authService.on("auth-state-changed", authStateChangedSpy)
authService.on("user-info", userInfoSpy)
// Trigger refresh by calling the timer callback
const timerCallback = vi.mocked(RefreshTimer).mock.calls[0]?.[0]?.callback
await timerCallback?.()
// Wait for async operations to complete
await new Promise((resolve) => setTimeout(resolve, 0))
expect(authService.getState()).toBe("active-session")
expect(authService.hasActiveSession()).toBe(true)
expect(authService.getSessionToken()).toBe("new-jwt-token")
expect(authStateChangedSpy).toHaveBeenCalledWith({
state: "active-session",
previousState: "attempting-session",
})
expect(userInfoSpy).toHaveBeenCalledWith({
userInfo: {
id: undefined,
name: "John Doe",
email: "john@example.com",
picture: "https://example.com/avatar.jpg",
extensionBridgeEnabled: true,
},
})
})
it("should handle invalid client token error", async () => {
// Mock 401 response (invalid token)
mockFetch.mockResolvedValue({
ok: false,
status: 401,
statusText: "Unauthorized",
})
const timerCallback = vi.mocked(RefreshTimer).mock.calls[0]?.[0]?.callback
await expect(timerCallback?.()).rejects.toThrow()
expect(mockContext.secrets.delete).toHaveBeenCalledWith("clerk-auth-credentials")
expect(mockLog).toHaveBeenCalledWith("[auth] Invalid/Expired client token: clearing credentials")
})
it("should handle network errors during refresh", async () => {
mockFetch.mockRejectedValue(new Error("Network error"))
const timerCallback = vi.mocked(RefreshTimer).mock.calls[0]?.[0]?.callback
await expect(timerCallback?.()).rejects.toThrow("Network error")
expect(mockLog).toHaveBeenCalledWith("[auth] Failed to refresh session", expect.any(Error))
})
it("should transition to inactive-session on first attempt failure", async () => {
// Mock failed token creation response
mockFetch.mockResolvedValue({
ok: false,
status: 500,
statusText: "Internal Server Error",
})
const authStateChangedSpy = vi.fn()
authService.on("auth-state-changed", authStateChangedSpy)
// Verify we start in attempting-session state
expect(authService.getState()).toBe("attempting-session")
expect(authService["isFirstRefreshAttempt"]).toBe(true)
const timerCallback = vi.mocked(RefreshTimer).mock.calls[0]?.[0]?.callback
await expect(timerCallback?.()).rejects.toThrow()
// Should transition to inactive-session after first failure
expect(authService.getState()).toBe("inactive-session")
expect(authService["isFirstRefreshAttempt"]).toBe(false)
expect(authStateChangedSpy).toHaveBeenCalledWith({
state: "inactive-session",
previousState: "attempting-session",
})
})
it("should not transition to inactive-session on subsequent failures", async () => {
// First, transition to inactive-session by failing the first attempt
mockFetch.mockResolvedValue({
ok: false,
status: 500,
statusText: "Internal Server Error",
})
const timerCallback = vi.mocked(RefreshTimer).mock.calls[0]?.[0]?.callback
await expect(timerCallback?.()).rejects.toThrow()
// Verify we're now in inactive-session
expect(authService.getState()).toBe("inactive-session")
expect(authService["isFirstRefreshAttempt"]).toBe(false)
const authStateChangedSpy = vi.fn()
authService.on("auth-state-changed", authStateChangedSpy)
// Subsequent failure should not trigger another transition
await expect(timerCallback?.()).rejects.toThrow()
expect(authService.getState()).toBe("inactive-session")
expect(authStateChangedSpy).not.toHaveBeenCalled()
})
it("should clear credentials on 401 during first refresh attempt (bug fix)", async () => {
// Mock 401 response during first refresh attempt
mockFetch.mockResolvedValue({
ok: false,
status: 401,
statusText: "Unauthorized",
})
const authStateChangedSpy = vi.fn()
authService.on("auth-state-changed", authStateChangedSpy)
const timerCallback = vi.mocked(RefreshTimer).mock.calls[0]?.[0]?.callback
await expect(timerCallback?.()).rejects.toThrow()
// Should clear credentials (not just transition to inactive-session)
expect(mockContext.secrets.delete).toHaveBeenCalledWith("clerk-auth-credentials")
expect(mockLog).toHaveBeenCalledWith("[auth] Invalid/Expired client token: clearing credentials")
// Simulate credentials cleared event
mockContext.secrets.get.mockResolvedValue(undefined)
await authService["handleCredentialsChange"]()
expect(authService.getState()).toBe("logged-out")
expect(authStateChangedSpy).toHaveBeenCalledWith({
state: "logged-out",
previousState: "attempting-session",
})
})
})
describe("user info", () => {
it("should return null initially", () => {
expect(authService.getUserInfo()).toBeNull()
})
it("should parse user info correctly for personal accounts", async () => {
// Set up with credentials for personal account (no organizationId)
const credentials = {
clientToken: "test-token",
sessionId: "test-session",
organizationId: null,
}
mockContext.secrets.get.mockResolvedValue(JSON.stringify(credentials))
await authService.initialize()
// Clear previous mock calls
mockFetch.mockClear()
// Mock successful responses
mockFetch
.mockResolvedValueOnce({
ok: true,
json: () => Promise.resolve({ jwt: "jwt-token" }),
})
.mockResolvedValueOnce({
ok: true,
json: () =>
Promise.resolve({
response: {
first_name: "Jane",
last_name: "Smith",
image_url: "https://example.com/jane.jpg",
primary_email_address_id: "email-2",
email_addresses: [
{ id: "email-1", email_address: "jane.old@example.com" },
{ id: "email-2", email_address: "jane@example.com" },
],
},
}),
})
const timerCallback = vi.mocked(RefreshTimer).mock.calls[0]?.[0]?.callback
await timerCallback?.()
// Wait for async operations to complete
await new Promise((resolve) => setTimeout(resolve, 0))
const userInfo = authService.getUserInfo()
expect(userInfo).toEqual({
id: undefined,
name: "Jane Smith",
email: "jane@example.com",
picture: "https://example.com/jane.jpg",
extensionBridgeEnabled: true,
})
})
it("should parse user info correctly for organization accounts", async () => {
// Set up with credentials for organization account
const credentials = {
clientToken: "test-token",
sessionId: "test-session",
organizationId: "org_1",
}
mockContext.secrets.get.mockResolvedValue(JSON.stringify(credentials))
await authService.initialize()
// Clear previous mock calls
mockFetch.mockClear()
// Mock successful responses
mockFetch
.mockResolvedValueOnce({
ok: true,
json: () => Promise.resolve({ jwt: "jwt-token" }),
})
.mockResolvedValueOnce({
ok: true,
json: () =>
Promise.resolve({
response: {
first_name: "Jane",
last_name: "Smith",
image_url: "https://example.com/jane.jpg",
primary_email_address_id: "email-2",
email_addresses: [
{ id: "email-1", email_address: "jane.old@example.com" },
{ id: "email-2", email_address: "jane@example.com" },
],
},
}),
})
.mockResolvedValueOnce({
ok: true,
json: () =>
Promise.resolve({
response: [
{
id: "org_member_id_1",
role: "member",
organization: {
id: "org_1",
name: "Org 1",
},
},
],
}),
})
const timerCallback = vi.mocked(RefreshTimer).mock.calls[0]?.[0]?.callback
await timerCallback?.()
// Wait for async operations to complete
await new Promise((resolve) => setTimeout(resolve, 0))
const userInfo = authService.getUserInfo()
expect(userInfo).toEqual({
id: undefined,
name: "Jane Smith",
email: "jane@example.com",
picture: "https://example.com/jane.jpg",
extensionBridgeEnabled: false,
organizationId: "org_1",
organizationName: "Org 1",
organizationRole: "member",
organizationImageUrl: undefined,
})
})
it("should handle missing user info fields", async () => {
// Set up with credentials for personal account (no organizationId)
const credentials = {
clientToken: "test-token",
sessionId: "test-session",
organizationId: null,
}
mockContext.secrets.get.mockResolvedValue(JSON.stringify(credentials))
await authService.initialize()
// Clear previous mock calls
mockFetch.mockClear()
// Mock responses with minimal data
mockFetch
.mockResolvedValueOnce({
ok: true,
json: () => Promise.resolve({ jwt: "jwt-token" }),
})
.mockResolvedValueOnce({
ok: true,
json: () =>
Promise.resolve({
response: {
first_name: "John",
last_name: "Doe",
},
}),
})
const timerCallback = vi.mocked(RefreshTimer).mock.calls[0]?.[0]?.callback
await timerCallback?.()
// Wait for async operations to complete
await new Promise((resolve) => setTimeout(resolve, 0))
const userInfo = authService.getUserInfo()
expect(userInfo).toEqual({
id: undefined,
name: "John Doe",
email: undefined,
picture: undefined,
extensionBridgeEnabled: true,
})
})
})
describe("event emissions", () => {
it("should emit auth-state-changed event for logged-out", async () => {
const authStateChangedSpy = vi.fn()
authService.on("auth-state-changed", authStateChangedSpy)
await authService.initialize()
expect(authStateChangedSpy).toHaveBeenCalledWith({
state: "logged-out",
previousState: "initializing",
})
})
it("should emit auth-state-changed event for attempting-session", async () => {
const credentials = {
clientToken: "test-token",
sessionId: "test-session",
}
mockContext.secrets.get.mockResolvedValue(JSON.stringify(credentials))
const authStateChangedSpy = vi.fn()
authService.on("auth-state-changed", authStateChangedSpy)
await authService.initialize()
expect(authStateChangedSpy).toHaveBeenCalledWith({
state: "attempting-session",
previousState: "initializing",
})
})
it("should emit auth-state-changed event for active-session", async () => {
// Set up with credentials
const credentials = {
clientToken: "test-token",
sessionId: "test-session",
}
mockContext.secrets.get.mockResolvedValue(JSON.stringify(credentials))
await authService.initialize()
// Clear previous mock calls
mockFetch.mockClear()
// Mock both the token creation and user info fetch
mockFetch
.mockResolvedValueOnce({
ok: true,
json: () => Promise.resolve({ jwt: "jwt-token" }),
})
.mockResolvedValueOnce({
ok: true,
json: () =>
Promise.resolve({
response: {
first_name: "Test",
last_name: "User",
},
}),
})
const authStateChangedSpy = vi.fn()
authService.on("auth-state-changed", authStateChangedSpy)
const timerCallback = vi.mocked(RefreshTimer).mock.calls[0]?.[0]?.callback
await timerCallback?.()
// Wait for async operations to complete
await new Promise((resolve) => setTimeout(resolve, 0))
expect(authStateChangedSpy).toHaveBeenCalledWith({
state: "active-session",
previousState: "attempting-session",