@workos/authkit-session 0.3.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/README.md +94 -27
  2. package/dist/core/AuthKitCore.d.ts +20 -0
  3. package/dist/core/AuthKitCore.d.ts.map +1 -1
  4. package/dist/core/AuthKitCore.js +36 -4
  5. package/dist/core/AuthKitCore.js.map +1 -1
  6. package/dist/core/client/types.d.ts.map +1 -1
  7. package/dist/core/encryption/ironWebcryptoEncryption.d.ts +2 -1
  8. package/dist/core/encryption/ironWebcryptoEncryption.d.ts.map +1 -1
  9. package/dist/core/encryption/ironWebcryptoEncryption.js +2 -2
  10. package/dist/core/encryption/ironWebcryptoEncryption.js.map +1 -1
  11. package/dist/core/errors.d.ts +9 -0
  12. package/dist/core/errors.d.ts.map +1 -1
  13. package/dist/core/errors.js +18 -0
  14. package/dist/core/errors.js.map +1 -1
  15. package/dist/core/pkce/cookieOptions.d.ts +36 -0
  16. package/dist/core/pkce/cookieOptions.d.ts.map +1 -0
  17. package/dist/core/pkce/cookieOptions.js +55 -0
  18. package/dist/core/pkce/cookieOptions.js.map +1 -0
  19. package/dist/core/pkce/generateAuthorizationUrl.d.ts +45 -0
  20. package/dist/core/pkce/generateAuthorizationUrl.d.ts.map +1 -0
  21. package/dist/core/pkce/generateAuthorizationUrl.js +82 -0
  22. package/dist/core/pkce/generateAuthorizationUrl.js.map +1 -0
  23. package/dist/core/pkce/state.d.ts +53 -0
  24. package/dist/core/pkce/state.d.ts.map +1 -0
  25. package/dist/core/pkce/state.js +91 -0
  26. package/dist/core/pkce/state.js.map +1 -0
  27. package/dist/core/session/CookieSessionStorage.d.ts +25 -15
  28. package/dist/core/session/CookieSessionStorage.d.ts.map +1 -1
  29. package/dist/core/session/CookieSessionStorage.js +20 -27
  30. package/dist/core/session/CookieSessionStorage.js.map +1 -1
  31. package/dist/core/session/TokenManager.js +2 -2
  32. package/dist/core/session/TokenManager.js.map +1 -1
  33. package/dist/core/session/serializeCookie.d.ts +13 -0
  34. package/dist/core/session/serializeCookie.d.ts.map +1 -0
  35. package/dist/core/session/serializeCookie.js +32 -0
  36. package/dist/core/session/serializeCookie.js.map +1 -0
  37. package/dist/core/session/types.d.ts +71 -2
  38. package/dist/core/session/types.d.ts.map +1 -1
  39. package/dist/index.d.ts +1 -1
  40. package/dist/index.d.ts.map +1 -1
  41. package/dist/index.js +1 -1
  42. package/dist/index.js.map +1 -1
  43. package/dist/operations/AuthOperations.d.ts +15 -13
  44. package/dist/operations/AuthOperations.d.ts.map +1 -1
  45. package/dist/operations/AuthOperations.js +22 -34
  46. package/dist/operations/AuthOperations.js.map +1 -1
  47. package/dist/service/AuthService.d.ts +58 -15
  48. package/dist/service/AuthService.d.ts.map +1 -1
  49. package/dist/service/AuthService.js +157 -71
  50. package/dist/service/AuthService.js.map +1 -1
  51. package/dist/service/factory.d.ts.map +1 -1
  52. package/dist/service/factory.js +4 -3
  53. package/dist/service/factory.js.map +1 -1
  54. package/dist/utils.d.ts +16 -0
  55. package/dist/utils.d.ts.map +1 -1
  56. package/dist/utils.js +23 -0
  57. package/dist/utils.js.map +1 -1
  58. package/package.json +35 -29
  59. package/src/core/AuthKitCore.spec.ts +109 -0
  60. package/src/core/AuthKitCore.ts +55 -4
  61. package/src/core/client/types.ts +3 -6
  62. package/src/core/encryption/ironWebcryptoEncryption.spec.ts +62 -0
  63. package/src/core/encryption/ironWebcryptoEncryption.ts +2 -2
  64. package/src/core/errors.spec.ts +33 -142
  65. package/src/core/errors.ts +21 -0
  66. package/src/core/pkce/cookieOptions.spec.ts +144 -0
  67. package/src/core/pkce/cookieOptions.ts +64 -0
  68. package/src/core/pkce/generateAuthorizationUrl.ts +123 -0
  69. package/src/core/pkce/pkce.spec.ts +166 -0
  70. package/src/core/pkce/state.spec.ts +216 -0
  71. package/src/core/pkce/state.ts +120 -0
  72. package/src/core/session/CookieSessionStorage.spec.ts +79 -3
  73. package/src/core/session/CookieSessionStorage.ts +60 -39
  74. package/src/core/session/TokenManager.ts +2 -2
  75. package/src/core/session/serializeCookie.ts +33 -0
  76. package/src/core/session/types.ts +79 -2
  77. package/src/index.ts +3 -0
  78. package/src/operations/AuthOperations.spec.ts +107 -62
  79. package/src/operations/AuthOperations.ts +34 -40
  80. package/src/service/AuthService.spec.ts +615 -98
  81. package/src/service/AuthService.ts +198 -73
  82. package/src/service/factory.spec.ts +4 -3
  83. package/src/service/factory.ts +6 -3
  84. package/src/utils.ts +22 -0
@@ -1,10 +1,15 @@
1
+ import sessionEncryption from '../core/encryption/ironWebcryptoEncryption.js';
2
+ import {
3
+ OAuthStateMismatchError,
4
+ PKCECookieMissingError,
5
+ } from '../core/errors.js';
1
6
  import { AuthService } from './AuthService.js';
2
7
 
3
8
  const mockConfig = {
4
9
  clientId: 'test-client-id',
5
10
  apiKey: 'test-api-key',
6
- redirectUri: 'http://localhost:3000/callback',
7
- cookiePassword: 'test-password-that-is-32-chars-long!!',
11
+ redirectUri: 'https://app.example.com/callback',
12
+ cookiePassword: 'this-is-a-test-password-that-is-32-characters-long!',
8
13
  cookieName: 'wos-session',
9
14
  };
10
15
 
@@ -23,32 +28,87 @@ const mockUser = {
23
28
  metadata: {},
24
29
  } as const;
25
30
 
26
- const mockStorage = {
27
- getSession: async () => 'encrypted-session-data',
28
- saveSession: async () => ({ response: 'updated-response' }),
29
- clearSession: async () => ({
30
- response: 'cleared-response',
31
- headers: { 'Set-Cookie': 'wos-session=; Path=/; Max-Age=0' },
32
- }),
33
- };
34
-
35
- const mockClient = {
36
- userManagement: {
37
- getJwksUrl: () => 'https://api.workos.com/sso/jwks/test-client-id',
38
- getAuthorizationUrl: ({ screenHint }: any) =>
39
- `https://api.workos.com/sso/authorize?screen_hint=${screenHint || ''}`,
40
- authenticateWithCode: async ({ code }: any) => ({
41
- accessToken: `access-${code}`,
42
- refreshToken: `refresh-${code}`,
43
- user: mockUser,
44
- impersonator: undefined,
31
+ /**
32
+ * Storage mock that remembers the last value passed to setCookie so
33
+ * handleCallback's getCookie read sees what sign-in wrote. Exposes the most
34
+ * recent options per cookie name for path/scope assertions.
35
+ */
36
+ function makeStorage(initialSession: string | null = 'encrypted-session-data') {
37
+ const cookies = new Map<string, string>();
38
+ const lastSetOptions = new Map<string, any>();
39
+ const lastClearOptions = new Map<string, any>();
40
+ return {
41
+ cookies,
42
+ lastSetOptions,
43
+ lastClearOptions,
44
+ getSession: async () => initialSession,
45
+ getCookie: async (_req: any, name: string) => cookies.get(name) ?? null,
46
+ setCookie: async (_res: any, name: string, value: string, options: any) => {
47
+ cookies.set(name, value);
48
+ lastSetOptions.set(name, options);
49
+ return {
50
+ headers: {
51
+ 'Set-Cookie': `${name}=${value}; Path=${options.path}; Max-Age=${options.maxAge}`,
52
+ },
53
+ };
54
+ },
55
+ clearCookie: async (_res: any, name: string, options: any) => {
56
+ lastClearOptions.set(name, options);
57
+ cookies.delete(name);
58
+ return {
59
+ headers: {
60
+ 'Set-Cookie': `${name}=; Path=${options.path}; Max-Age=0`,
61
+ },
62
+ };
63
+ },
64
+ saveSession: async () => ({
65
+ response: 'updated-response',
66
+ headers: { 'Set-Cookie': 'wos-session=encrypted; Path=/; Max-Age=3600' },
45
67
  }),
46
- getLogoutUrl: ({ sessionId }: any) =>
47
- `https://api.workos.com/sso/logout?session_id=${sessionId}`,
48
- },
49
- };
50
-
51
- const mockEncryption = {
68
+ clearSession: async () => ({
69
+ response: 'cleared-response',
70
+ headers: { 'Set-Cookie': 'wos-session=; Path=/; Max-Age=0' },
71
+ }),
72
+ };
73
+ }
74
+
75
+ const testVerifier = 'test-verifier-abcdefghijklmnopqrstuvwxyz1234567890';
76
+
77
+ function makeClient(capture?: { authCall?: Record<string, unknown> }) {
78
+ return {
79
+ userManagement: {
80
+ getJwksUrl: () => 'https://api.workos.com/sso/jwks/test-client-id',
81
+ getAuthorizationUrl: (opts: any) => {
82
+ const params = new URLSearchParams({
83
+ state: opts.state ?? '',
84
+ screen_hint: opts.screenHint ?? '',
85
+ });
86
+ return `https://api.workos.com/sso/authorize?${params.toString()}`;
87
+ },
88
+ authenticateWithCode: async (opts: any) => {
89
+ if (capture) capture.authCall = opts;
90
+ return {
91
+ accessToken: `access-${opts.code}`,
92
+ refreshToken: `refresh-${opts.code}`,
93
+ user: mockUser,
94
+ impersonator: undefined,
95
+ };
96
+ },
97
+ getLogoutUrl: ({ sessionId }: any) =>
98
+ `https://api.workos.com/sso/logout?session_id=${sessionId}`,
99
+ },
100
+ pkce: {
101
+ generate: async () => ({
102
+ codeVerifier: testVerifier,
103
+ codeChallenge: 'test-challenge',
104
+ codeChallengeMethod: 'S256',
105
+ }),
106
+ },
107
+ };
108
+ }
109
+
110
+ // For withAuth / getSession tests — returns a decrypted Session-shaped blob.
111
+ const mockEncryptionSessionShape = {
52
112
  sealData: async () => 'encrypted-session-data',
53
113
  unsealData: async () => ({
54
114
  accessToken: 'test-access-token',
@@ -60,13 +120,15 @@ const mockEncryption = {
60
120
 
61
121
  describe('AuthService', () => {
62
122
  let service: AuthService<any, any>;
123
+ let storage: ReturnType<typeof makeStorage>;
63
124
 
64
125
  beforeEach(() => {
126
+ storage = makeStorage();
65
127
  service = new AuthService(
66
128
  mockConfig as any,
67
- mockStorage as any,
68
- mockClient as any,
69
- mockEncryption as any,
129
+ storage as any,
130
+ makeClient() as any,
131
+ mockEncryptionSessionShape as any,
70
132
  );
71
133
  });
72
134
 
@@ -78,15 +140,12 @@ describe('AuthService', () => {
78
140
 
79
141
  describe('withAuth()', () => {
80
142
  it('returns null user when no session exists', async () => {
81
- const emptyStorage = {
82
- ...mockStorage,
83
- getSession: async () => null,
84
- };
143
+ const emptyStorage = makeStorage(null);
85
144
  const testService = new AuthService(
86
145
  mockConfig as any,
87
146
  emptyStorage as any,
88
- mockClient as any,
89
- mockEncryption as any,
147
+ makeClient() as any,
148
+ mockEncryptionSessionShape as any,
90
149
  );
91
150
 
92
151
  const result = await testService.withAuth('request');
@@ -104,8 +163,8 @@ describe('AuthService', () => {
104
163
  };
105
164
  const testService = new AuthService(
106
165
  mockConfig as any,
107
- mockStorage as any,
108
- mockClient as any,
166
+ storage as any,
167
+ makeClient() as any,
109
168
  failingEncryption as any,
110
169
  );
111
170
 
@@ -124,15 +183,12 @@ describe('AuthService', () => {
124
183
  });
125
184
 
126
185
  it('returns null when no session exists', async () => {
127
- const emptyStorage = {
128
- ...mockStorage,
129
- getSession: async () => null,
130
- };
186
+ const emptyStorage = makeStorage(null);
131
187
  const testService = new AuthService(
132
188
  mockConfig as any,
133
189
  emptyStorage as any,
134
- mockClient as any,
135
- mockEncryption as any,
190
+ makeClient() as any,
191
+ mockEncryptionSessionShape as any,
136
192
  );
137
193
 
138
194
  const result = await testService.getSession('request');
@@ -167,27 +223,90 @@ describe('AuthService', () => {
167
223
  });
168
224
  });
169
225
 
170
- describe('getAuthorizationUrl()', () => {
171
- it('delegates to operations', async () => {
172
- const result = await service.getAuthorizationUrl();
226
+ describe('createAuthorization()', () => {
227
+ it('returns url and writes the verifier cookie via storage.setCookie', async () => {
228
+ const realStorage = makeStorage();
229
+ const realService = new AuthService(
230
+ mockConfig as any,
231
+ realStorage as any,
232
+ makeClient() as any,
233
+ sessionEncryption,
234
+ );
235
+
236
+ const result = await realService.createAuthorization('res');
173
237
 
174
- expect(result).toContain('authorize');
238
+ expect(result.url).toContain('authorize');
239
+ expect(realStorage.cookies.get('wos-auth-verifier')).toBeTruthy();
240
+ expect(result.headers?.['Set-Cookie']).toContain('wos-auth-verifier=');
241
+ expect(realStorage.lastSetOptions.get('wos-auth-verifier')?.path).toBe(
242
+ '/',
243
+ );
175
244
  });
176
245
  });
177
246
 
178
- describe('getSignInUrl()', () => {
179
- it('returns sign-in URL', async () => {
180
- const result = await service.getSignInUrl();
247
+ describe('createSignIn()', () => {
248
+ it('returns sign-in URL and writes the verifier cookie', async () => {
249
+ const realStorage = makeStorage();
250
+ const realService = new AuthService(
251
+ mockConfig as any,
252
+ realStorage as any,
253
+ makeClient() as any,
254
+ sessionEncryption,
255
+ );
181
256
 
182
- expect(result).toContain('screen_hint=sign-in');
257
+ const result = await realService.createSignIn('res');
258
+
259
+ expect(result.url).toContain('screen_hint=sign-in');
260
+ expect(realStorage.cookies.get('wos-auth-verifier')).toBeTruthy();
183
261
  });
184
262
  });
185
263
 
186
- describe('getSignUpUrl()', () => {
187
- it('returns sign-up URL', async () => {
188
- const result = await service.getSignUpUrl();
264
+ describe('createSignUp()', () => {
265
+ it('returns sign-up URL and writes the verifier cookie', async () => {
266
+ const realStorage = makeStorage();
267
+ const realService = new AuthService(
268
+ mockConfig as any,
269
+ realStorage as any,
270
+ makeClient() as any,
271
+ sessionEncryption,
272
+ );
273
+
274
+ const result = await realService.createSignUp('res');
189
275
 
190
- expect(result).toContain('screen_hint=sign-up');
276
+ expect(result.url).toContain('screen_hint=sign-up');
277
+ expect(realStorage.cookies.get('wos-auth-verifier')).toBeTruthy();
278
+ });
279
+ });
280
+
281
+ describe('clearPendingVerifier()', () => {
282
+ it('emits a delete cookie with Path=/', async () => {
283
+ const realStorage = makeStorage();
284
+ const realService = new AuthService(
285
+ mockConfig as any,
286
+ realStorage as any,
287
+ makeClient() as any,
288
+ sessionEncryption,
289
+ );
290
+
291
+ await realService.clearPendingVerifier('res');
292
+
293
+ expect(realStorage.lastClearOptions.get('wos-auth-verifier')?.path).toBe(
294
+ '/',
295
+ );
296
+ });
297
+
298
+ it('accepts undefined response for headers-only adapters', async () => {
299
+ const realStorage = makeStorage();
300
+ const realService = new AuthService(
301
+ mockConfig as any,
302
+ realStorage as any,
303
+ makeClient() as any,
304
+ sessionEncryption,
305
+ );
306
+
307
+ const result = await realService.clearPendingVerifier(undefined);
308
+
309
+ expect(result.headers?.['Set-Cookie']).toContain('wos-auth-verifier=');
191
310
  });
192
311
  });
193
312
 
@@ -195,73 +314,471 @@ describe('AuthService', () => {
195
314
  it('returns WorkOS client', () => {
196
315
  const result = service.getWorkOS();
197
316
 
198
- expect(result).toBe(mockClient);
317
+ expect(result).toBeDefined();
318
+ expect(typeof (result as any).userManagement.getJwksUrl).toBe('function');
199
319
  });
200
320
  });
201
321
 
202
322
  describe('handleCallback()', () => {
203
- it('authenticates and creates session', async () => {
204
- const result = await service.handleCallback('request', 'response', {
205
- code: 'auth-code-123',
323
+ it('round-trips through createSignIn → handleCallback', async () => {
324
+ const capture: { authCall?: Record<string, unknown> } = {};
325
+ const realStorage = makeStorage();
326
+ const realService = new AuthService(
327
+ mockConfig as any,
328
+ realStorage as any,
329
+ makeClient(capture) as any,
330
+ sessionEncryption,
331
+ );
332
+
333
+ await realService.createAuthorization('res', {
334
+ returnPathname: '/dashboard',
335
+ state: 'my.custom.state',
206
336
  });
337
+ const sealedState = realStorage.cookies.get('wos-auth-verifier')!;
207
338
 
208
- expect(result.authResponse.accessToken).toBe('access-auth-code-123');
209
- expect(result.returnPathname).toBe('/');
210
- expect(result.response).toBe('updated-response');
339
+ const result = await realService.handleCallback('req', 'res', {
340
+ code: 'auth-code-xyz',
341
+ state: sealedState,
342
+ });
343
+
344
+ expect(result.authResponse.accessToken).toBe('access-auth-code-xyz');
345
+ expect(result.returnPathname).toBe('/dashboard');
346
+ expect(result.state).toBe('my.custom.state');
347
+ expect(capture.authCall?.codeVerifier).toBe(testVerifier);
211
348
  });
212
349
 
213
- it('decodes returnPathname from state', async () => {
214
- const state = btoa(JSON.stringify({ returnPathname: '/dashboard' }));
350
+ it('returns both session and verifier-delete Set-Cookie as a string[]', async () => {
351
+ const realStorage = makeStorage();
352
+ const realService = new AuthService(
353
+ mockConfig as any,
354
+ realStorage as any,
355
+ makeClient() as any,
356
+ sessionEncryption,
357
+ );
215
358
 
216
- const result = await service.handleCallback('request', 'response', {
217
- code: 'auth-code-123',
218
- state,
359
+ await realService.createAuthorization('res');
360
+ const sealedState = realStorage.cookies.get('wos-auth-verifier')!;
361
+
362
+ const result = await realService.handleCallback('req', 'res', {
363
+ code: 'code',
364
+ state: sealedState,
219
365
  });
220
366
 
221
- expect(result.returnPathname).toBe('/dashboard');
367
+ const setCookie = result.headers?.['Set-Cookie'];
368
+ expect(Array.isArray(setCookie)).toBe(true);
369
+ expect(setCookie).toHaveLength(2);
370
+ expect(
371
+ (setCookie as string[]).some(c => c.startsWith('wos-session=')),
372
+ ).toBe(true);
373
+ expect(
374
+ (setCookie as string[]).some(c => c.startsWith('wos-auth-verifier=')),
375
+ ).toBe(true);
376
+ expect(
377
+ (setCookie as string[]).find(c => c.startsWith('wos-auth-verifier=')),
378
+ ).toContain('Max-Age=0');
379
+ });
380
+
381
+ it('merges lowercase set-cookie headers into an array (case-insensitive)', async () => {
382
+ // Regression: adapters that normalize through Headers objects emit
383
+ // lowercase `set-cookie`.
384
+ const realStorage = makeStorage();
385
+ const lowerStorage = {
386
+ ...realStorage,
387
+ setCookie: async (
388
+ _res: any,
389
+ name: string,
390
+ value: string,
391
+ options: any,
392
+ ) => {
393
+ realStorage.cookies.set(name, value);
394
+ realStorage.lastSetOptions.set(name, options);
395
+ return {
396
+ headers: {
397
+ 'set-cookie': `${name}=${value}; Path=${options.path}; Max-Age=${options.maxAge}`,
398
+ },
399
+ };
400
+ },
401
+ clearCookie: async (_res: any, name: string, options: any) => {
402
+ realStorage.lastClearOptions.set(name, options);
403
+ realStorage.cookies.delete(name);
404
+ return {
405
+ headers: {
406
+ 'set-cookie': `${name}=; Path=${options.path}; Max-Age=0`,
407
+ },
408
+ };
409
+ },
410
+ saveSession: async () => ({
411
+ response: 'updated-response',
412
+ headers: {
413
+ 'set-cookie': 'wos-session=encrypted; Path=/; Max-Age=3600',
414
+ },
415
+ }),
416
+ };
417
+ const realService = new AuthService(
418
+ mockConfig as any,
419
+ lowerStorage as any,
420
+ makeClient() as any,
421
+ sessionEncryption,
422
+ );
423
+
424
+ await realService.createAuthorization('res');
425
+ const sealedState = realStorage.cookies.get('wos-auth-verifier')!;
426
+
427
+ const result = await realService.handleCallback('req', 'res', {
428
+ code: 'code',
429
+ state: sealedState,
430
+ });
431
+
432
+ const setCookie = result.headers?.['set-cookie'];
433
+ expect(Array.isArray(setCookie)).toBe(true);
434
+ expect(setCookie).toHaveLength(2);
435
+ expect(
436
+ (setCookie as string[]).some(c => c.startsWith('wos-session=')),
437
+ ).toBe(true);
438
+ expect(
439
+ (setCookie as string[]).some(c => c.startsWith('wos-auth-verifier=')),
440
+ ).toBe(true);
222
441
  });
223
442
 
224
- it('treats invalid state as custom state', async () => {
225
- const result = await service.handleCallback('request', 'response', {
226
- code: 'auth-code-123',
227
- state: 'invalid-state',
443
+ it('emits the verifier-delete cookie with Path=/', async () => {
444
+ const realStorage = makeStorage();
445
+ const realService = new AuthService(
446
+ mockConfig as any,
447
+ realStorage as any,
448
+ makeClient() as any,
449
+ sessionEncryption,
450
+ );
451
+
452
+ await realService.createAuthorization('res');
453
+ const sealedState = realStorage.cookies.get('wos-auth-verifier')!;
454
+
455
+ await realService.handleCallback('req', 'res', {
456
+ code: 'code',
457
+ state: sealedState,
458
+ });
459
+
460
+ expect(realStorage.lastClearOptions.get('wos-auth-verifier')?.path).toBe(
461
+ '/',
462
+ );
463
+ });
464
+
465
+ it('throws OAuthStateMismatchError when storage cookie differs from url state', async () => {
466
+ const realStorage = makeStorage();
467
+ const realService = new AuthService(
468
+ mockConfig as any,
469
+ realStorage as any,
470
+ makeClient() as any,
471
+ sessionEncryption,
472
+ );
473
+
474
+ await realService.createAuthorization('res');
475
+ const sealedState = realStorage.cookies.get('wos-auth-verifier')!;
476
+ // Tamper the stored cookie after sign-in
477
+ realStorage.cookies.set(
478
+ 'wos-auth-verifier',
479
+ sealedState.slice(0, -2) + 'XX',
480
+ );
481
+
482
+ await expect(
483
+ realService.handleCallback('req', 'res', {
484
+ code: 'code',
485
+ state: sealedState,
486
+ }),
487
+ ).rejects.toThrow(OAuthStateMismatchError);
488
+ });
489
+
490
+ it('throws PKCECookieMissingError when storage has no verifier cookie', async () => {
491
+ const realStorage = makeStorage();
492
+ const realService = new AuthService(
493
+ mockConfig as any,
494
+ realStorage as any,
495
+ makeClient() as any,
496
+ sessionEncryption,
497
+ );
498
+
499
+ await realService.createAuthorization('res');
500
+ const sealedState = realStorage.cookies.get('wos-auth-verifier')!;
501
+ realStorage.cookies.delete('wos-auth-verifier');
502
+
503
+ await expect(
504
+ realService.handleCallback('req', 'res', {
505
+ code: 'code',
506
+ state: sealedState,
507
+ }),
508
+ ).rejects.toThrow(PKCECookieMissingError);
509
+ });
510
+
511
+ it('throws OAuthStateMismatchError when state is undefined', async () => {
512
+ const realStorage = makeStorage();
513
+ const realService = new AuthService(
514
+ mockConfig as any,
515
+ realStorage as any,
516
+ makeClient() as any,
517
+ sessionEncryption,
518
+ );
519
+
520
+ await realService.createAuthorization('res');
521
+
522
+ await expect(
523
+ realService.handleCallback('req', 'res', {
524
+ code: 'code',
525
+ state: undefined,
526
+ }),
527
+ ).rejects.toThrow(OAuthStateMismatchError);
528
+ });
529
+
530
+ it('defaults returnPathname to "/" when the sealed state omits it', async () => {
531
+ const realStorage = makeStorage();
532
+ const realService = new AuthService(
533
+ mockConfig as any,
534
+ realStorage as any,
535
+ makeClient() as any,
536
+ sessionEncryption,
537
+ );
538
+
539
+ await realService.createAuthorization('res');
540
+ const sealedState = realStorage.cookies.get('wos-auth-verifier')!;
541
+
542
+ const result = await realService.handleCallback('req', 'res', {
543
+ code: 'c',
544
+ state: sealedState,
228
545
  });
229
546
 
230
547
  expect(result.returnPathname).toBe('/');
231
- expect(result.state).toBe('invalid-state');
232
548
  });
233
549
 
234
- it('parses new format with internal.userState', async () => {
235
- // Create URL-safe base64 internal state
236
- const internal = btoa(JSON.stringify({ returnPathname: '/profile' }))
237
- .replace(/\+/g, '-')
238
- .replace(/\//g, '_')
239
- .replace(/=+$/, '');
240
- const state = `${internal}.my-custom-state`;
241
-
242
- const result = await service.handleCallback('request', 'response', {
243
- code: 'auth-code-123',
244
- state,
550
+ it('best-effort clears the verifier cookie on OAuthStateMismatchError', async () => {
551
+ const realStorage = makeStorage();
552
+ const realService = new AuthService(
553
+ mockConfig as any,
554
+ realStorage as any,
555
+ makeClient() as any,
556
+ sessionEncryption,
557
+ );
558
+
559
+ await realService.createAuthorization('res');
560
+ const sealedState = realStorage.cookies.get('wos-auth-verifier')!;
561
+ realStorage.cookies.set(
562
+ 'wos-auth-verifier',
563
+ sealedState.slice(0, -2) + 'XX',
564
+ );
565
+
566
+ await expect(
567
+ realService.handleCallback('req', 'res', {
568
+ code: 'code',
569
+ state: sealedState,
570
+ }),
571
+ ).rejects.toThrow(OAuthStateMismatchError);
572
+
573
+ expect(realStorage.lastClearOptions.get('wos-auth-verifier')?.path).toBe(
574
+ '/',
575
+ );
576
+ });
577
+
578
+ it('emits a scheme-agnostic (secure=false, sameSite=lax) delete on pre-unseal failure', async () => {
579
+ // Covers the end-to-end case that motivates the schemeAgnostic flag:
580
+ // sign-in used an http:// redirectUri override (secure=false), then
581
+ // the callback hits a pre-unseal error (state mismatch) — we don't
582
+ // know the override at that point, so the fallback delete must drop
583
+ // Secure so the browser accepts the Set-Cookie over http://.
584
+ const realStorage = makeStorage();
585
+ const realService = new AuthService(
586
+ { ...mockConfig, cookieSameSite: 'lax' } as any,
587
+ realStorage as any,
588
+ makeClient() as any,
589
+ sessionEncryption,
590
+ );
591
+
592
+ await realService.createAuthorization('res', {
593
+ redirectUri: 'http://localhost:3000/callback',
245
594
  });
595
+ // Confirm the original set was secure=false (the scenario we're
596
+ // proving we can still clean up).
597
+ expect(realStorage.lastSetOptions.get('wos-auth-verifier')?.secure).toBe(
598
+ false,
599
+ );
600
+ const sealedState = realStorage.cookies.get('wos-auth-verifier')!;
601
+ realStorage.cookies.set(
602
+ 'wos-auth-verifier',
603
+ sealedState.slice(0, -2) + 'XX',
604
+ );
605
+
606
+ await expect(
607
+ realService.handleCallback('req', 'res', {
608
+ code: 'code',
609
+ state: sealedState,
610
+ }),
611
+ ).rejects.toThrow(OAuthStateMismatchError);
612
+
613
+ const clearOpts = realStorage.lastClearOptions.get('wos-auth-verifier');
614
+ expect(clearOpts?.secure).toBe(false);
615
+ expect(clearOpts?.sameSite).toBe('lax');
616
+ expect(clearOpts?.path).toBe('/');
617
+ });
618
+
619
+ it('keeps Secure on scheme-agnostic delete when sameSite=none (Secure is required)', async () => {
620
+ const realStorage = makeStorage();
621
+ const realService = new AuthService(
622
+ { ...mockConfig, cookieSameSite: 'none' } as any,
623
+ realStorage as any,
624
+ makeClient() as any,
625
+ sessionEncryption,
626
+ );
627
+
628
+ await realService.createAuthorization('res');
629
+ const sealedState = realStorage.cookies.get('wos-auth-verifier')!;
630
+ realStorage.cookies.set(
631
+ 'wos-auth-verifier',
632
+ sealedState.slice(0, -2) + 'XX',
633
+ );
634
+
635
+ await expect(
636
+ realService.handleCallback('req', 'res', {
637
+ code: 'code',
638
+ state: sealedState,
639
+ }),
640
+ ).rejects.toThrow(OAuthStateMismatchError);
641
+
642
+ const clearOpts = realStorage.lastClearOptions.get('wos-auth-verifier');
643
+ expect(clearOpts?.secure).toBe(true);
644
+ expect(clearOpts?.sameSite).toBe('none');
645
+ });
646
+
647
+ it('best-effort clears the verifier cookie on PKCECookieMissingError', async () => {
648
+ const realStorage = makeStorage();
649
+ const realService = new AuthService(
650
+ mockConfig as any,
651
+ realStorage as any,
652
+ makeClient() as any,
653
+ sessionEncryption,
654
+ );
655
+
656
+ await realService.createAuthorization('res');
657
+ const sealedState = realStorage.cookies.get('wos-auth-verifier')!;
658
+ realStorage.cookies.delete('wos-auth-verifier');
659
+
660
+ await expect(
661
+ realService.handleCallback('req', 'res', {
662
+ code: 'code',
663
+ state: sealedState,
664
+ }),
665
+ ).rejects.toThrow(PKCECookieMissingError);
666
+
667
+ expect(realStorage.lastClearOptions.get('wos-auth-verifier')?.path).toBe(
668
+ '/',
669
+ );
670
+ });
671
+
672
+ it('best-effort clears the verifier cookie when authenticateWithCode throws', async () => {
673
+ const realStorage = makeStorage();
674
+ const throwingClient = makeClient();
675
+ throwingClient.userManagement.authenticateWithCode = async () => {
676
+ throw new Error('WorkOS exchange failed');
677
+ };
678
+ const realService = new AuthService(
679
+ mockConfig as any,
680
+ realStorage as any,
681
+ throwingClient as any,
682
+ sessionEncryption,
683
+ );
684
+
685
+ await realService.createAuthorization('res');
686
+ const sealedState = realStorage.cookies.get('wos-auth-verifier')!;
687
+
688
+ await expect(
689
+ realService.handleCallback('req', 'res', {
690
+ code: 'code',
691
+ state: sealedState,
692
+ }),
693
+ ).rejects.toThrow('WorkOS exchange failed');
694
+
695
+ expect(realStorage.lastClearOptions.get('wos-auth-verifier')?.path).toBe(
696
+ '/',
697
+ );
698
+ });
699
+
700
+ it('best-effort clears the verifier cookie when saveSession throws', async () => {
701
+ const realStorage = makeStorage();
702
+ realStorage.saveSession = async () => {
703
+ throw new Error('storage write failed');
704
+ };
705
+ const realService = new AuthService(
706
+ mockConfig as any,
707
+ realStorage as any,
708
+ makeClient() as any,
709
+ sessionEncryption,
710
+ );
711
+
712
+ await realService.createAuthorization('res');
713
+ const sealedState = realStorage.cookies.get('wos-auth-verifier')!;
714
+
715
+ await expect(
716
+ realService.handleCallback('req', 'res', {
717
+ code: 'code',
718
+ state: sealedState,
719
+ }),
720
+ ).rejects.toThrow('storage write failed');
246
721
 
247
- expect(result.returnPathname).toBe('/profile');
248
- expect(result.state).toBe('my-custom-state');
722
+ expect(realStorage.lastClearOptions.get('wos-auth-verifier')?.path).toBe(
723
+ '/',
724
+ );
249
725
  });
250
726
 
251
- it('handles user state with dots', async () => {
252
- const internal = btoa(JSON.stringify({ returnPathname: '/dashboard' }))
253
- .replace(/\+/g, '-')
254
- .replace(/\//g, '_')
255
- .replace(/=+$/, '');
256
- const state = `${internal}.user.state.with.dots`;
727
+ it('swallows clearCookie errors so the original failure propagates', async () => {
728
+ const realStorage = makeStorage();
729
+ const throwingClient = makeClient();
730
+ throwingClient.userManagement.authenticateWithCode = async () => {
731
+ throw new Error('original exchange failure');
732
+ };
733
+ realStorage.clearCookie = async () => {
734
+ throw new Error('clearCookie blew up');
735
+ };
736
+ const realService = new AuthService(
737
+ mockConfig as any,
738
+ realStorage as any,
739
+ throwingClient as any,
740
+ sessionEncryption,
741
+ );
742
+
743
+ await realService.createAuthorization('res');
744
+ const sealedState = realStorage.cookies.get('wos-auth-verifier')!;
257
745
 
258
- const result = await service.handleCallback('request', 'response', {
259
- code: 'auth-code-123',
260
- state,
746
+ await expect(
747
+ realService.handleCallback('req', 'res', {
748
+ code: 'code',
749
+ state: sealedState,
750
+ }),
751
+ ).rejects.toThrow('original exchange failure');
752
+ });
753
+
754
+ it('round-trips redirectUri override through the sealed state into the clear cookie', async () => {
755
+ const realStorage = makeStorage();
756
+ const realService = new AuthService(
757
+ mockConfig as any,
758
+ realStorage as any,
759
+ makeClient() as any,
760
+ sessionEncryption,
761
+ );
762
+
763
+ // Override with an http:// URL so the `secure` attribute differs from
764
+ // the https:// default — proves handleCallback used the override.
765
+ await realService.createAuthorization('res', {
766
+ redirectUri: 'http://localhost:3000/callback',
261
767
  });
768
+ const sealedState = realStorage.cookies.get('wos-auth-verifier')!;
262
769
 
263
- expect(result.returnPathname).toBe('/dashboard');
264
- expect(result.state).toBe('user.state.with.dots');
770
+ expect(realStorage.lastSetOptions.get('wos-auth-verifier')?.secure).toBe(
771
+ false,
772
+ );
773
+
774
+ await realService.handleCallback('req', 'res', {
775
+ code: 'code',
776
+ state: sealedState,
777
+ });
778
+
779
+ expect(
780
+ realStorage.lastClearOptions.get('wos-auth-verifier')?.secure,
781
+ ).toBe(false);
265
782
  });
266
783
  });
267
784
  });