@workos/authkit-session 0.3.4 → 0.5.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 (88) hide show
  1. package/README.md +111 -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/encryption/ironWebcryptoEncryption.d.ts +2 -1
  7. package/dist/core/encryption/ironWebcryptoEncryption.d.ts.map +1 -1
  8. package/dist/core/encryption/ironWebcryptoEncryption.js +2 -2
  9. package/dist/core/encryption/ironWebcryptoEncryption.js.map +1 -1
  10. package/dist/core/errors.d.ts +9 -0
  11. package/dist/core/errors.d.ts.map +1 -1
  12. package/dist/core/errors.js +18 -0
  13. package/dist/core/errors.js.map +1 -1
  14. package/dist/core/pkce/cookieName.d.ts +17 -0
  15. package/dist/core/pkce/cookieName.d.ts.map +1 -0
  16. package/dist/core/pkce/cookieName.js +26 -0
  17. package/dist/core/pkce/cookieName.js.map +1 -0
  18. package/dist/core/pkce/cookieOptions.d.ts +34 -0
  19. package/dist/core/pkce/cookieOptions.d.ts.map +1 -0
  20. package/dist/core/pkce/cookieOptions.js +53 -0
  21. package/dist/core/pkce/cookieOptions.js.map +1 -0
  22. package/dist/core/pkce/generateAuthorizationUrl.d.ts +46 -0
  23. package/dist/core/pkce/generateAuthorizationUrl.d.ts.map +1 -0
  24. package/dist/core/pkce/generateAuthorizationUrl.js +85 -0
  25. package/dist/core/pkce/generateAuthorizationUrl.js.map +1 -0
  26. package/dist/core/pkce/state.d.ts +53 -0
  27. package/dist/core/pkce/state.d.ts.map +1 -0
  28. package/dist/core/pkce/state.js +91 -0
  29. package/dist/core/pkce/state.js.map +1 -0
  30. package/dist/core/session/CookieSessionStorage.d.ts +25 -15
  31. package/dist/core/session/CookieSessionStorage.d.ts.map +1 -1
  32. package/dist/core/session/CookieSessionStorage.js +20 -27
  33. package/dist/core/session/CookieSessionStorage.js.map +1 -1
  34. package/dist/core/session/TokenManager.js +2 -2
  35. package/dist/core/session/TokenManager.js.map +1 -1
  36. package/dist/core/session/serializeCookie.d.ts +13 -0
  37. package/dist/core/session/serializeCookie.d.ts.map +1 -0
  38. package/dist/core/session/serializeCookie.js +32 -0
  39. package/dist/core/session/serializeCookie.js.map +1 -0
  40. package/dist/core/session/types.d.ts +76 -2
  41. package/dist/core/session/types.d.ts.map +1 -1
  42. package/dist/index.d.ts +2 -1
  43. package/dist/index.d.ts.map +1 -1
  44. package/dist/index.js +5 -1
  45. package/dist/index.js.map +1 -1
  46. package/dist/operations/AuthOperations.d.ts +15 -13
  47. package/dist/operations/AuthOperations.d.ts.map +1 -1
  48. package/dist/operations/AuthOperations.js +22 -34
  49. package/dist/operations/AuthOperations.js.map +1 -1
  50. package/dist/service/AuthService.d.ts +64 -15
  51. package/dist/service/AuthService.d.ts.map +1 -1
  52. package/dist/service/AuthService.js +171 -70
  53. package/dist/service/AuthService.js.map +1 -1
  54. package/dist/service/factory.d.ts.map +1 -1
  55. package/dist/service/factory.js +4 -3
  56. package/dist/service/factory.js.map +1 -1
  57. package/dist/utils.d.ts +16 -0
  58. package/dist/utils.d.ts.map +1 -1
  59. package/dist/utils.js +23 -0
  60. package/dist/utils.js.map +1 -1
  61. package/package.json +23 -20
  62. package/src/core/AuthKitCore.spec.ts +109 -0
  63. package/src/core/AuthKitCore.ts +55 -4
  64. package/src/core/encryption/ironWebcryptoEncryption.spec.ts +62 -0
  65. package/src/core/encryption/ironWebcryptoEncryption.ts +2 -2
  66. package/src/core/errors.spec.ts +33 -142
  67. package/src/core/errors.ts +21 -0
  68. package/src/core/pkce/cookieName.spec.ts +56 -0
  69. package/src/core/pkce/cookieName.ts +27 -0
  70. package/src/core/pkce/cookieOptions.spec.ts +144 -0
  71. package/src/core/pkce/cookieOptions.ts +61 -0
  72. package/src/core/pkce/generateAuthorizationUrl.ts +123 -0
  73. package/src/core/pkce/pkce.spec.ts +175 -0
  74. package/src/core/pkce/state.spec.ts +216 -0
  75. package/src/core/pkce/state.ts +120 -0
  76. package/src/core/session/CookieSessionStorage.spec.ts +79 -3
  77. package/src/core/session/CookieSessionStorage.ts +56 -36
  78. package/src/core/session/TokenManager.ts +2 -2
  79. package/src/core/session/serializeCookie.ts +33 -0
  80. package/src/core/session/types.ts +83 -2
  81. package/src/index.ts +11 -0
  82. package/src/operations/AuthOperations.spec.ts +107 -62
  83. package/src/operations/AuthOperations.ts +34 -40
  84. package/src/service/AuthService.spec.ts +750 -97
  85. package/src/service/AuthService.ts +210 -72
  86. package/src/service/factory.spec.ts +4 -3
  87. package/src/service/factory.ts +6 -3
  88. 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,187 @@ 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 + cookieName and writes under the derived per-flow name', async () => {
228
+ const realStorage = makeStorage();
229
+ const authService = new AuthService(
230
+ mockConfig as any,
231
+ realStorage as any,
232
+ makeClient() as any,
233
+ sessionEncryption,
234
+ );
235
+
236
+ const { url, cookieName, headers } = await authService.createSignIn(
237
+ undefined,
238
+ {
239
+ returnPathname: '/foo',
240
+ },
241
+ );
242
+ expect(url).toMatch(/^https:\/\//);
243
+ expect(cookieName).toMatch(/^wos-auth-verifier-[0-9a-f]{8}$/);
244
+
245
+ // Storage must have been called with the derived name, not the legacy name.
246
+ expect(realStorage.cookies.has('wos-auth-verifier')).toBe(false);
247
+ expect(realStorage.cookies.get(cookieName)).toBeTruthy();
248
+
249
+ // Set-Cookie header reflects the same name.
250
+ const setCookie = Array.isArray(headers?.['Set-Cookie'])
251
+ ? headers!['Set-Cookie'].join('\n')
252
+ : (headers?.['Set-Cookie'] ?? '');
253
+ expect(setCookie).toContain(`${cookieName}=`);
254
+ });
255
+
256
+ it('isolates concurrent flows: two sign-ins produce two distinct cookies', async () => {
257
+ const realStorage = makeStorage();
258
+ const authService = new AuthService(
259
+ mockConfig as any,
260
+ realStorage as any,
261
+ makeClient() as any,
262
+ sessionEncryption,
263
+ );
264
+
265
+ const a = await authService.createSignIn(undefined, {
266
+ returnPathname: '/a',
267
+ });
268
+ const b = await authService.createSignIn(undefined, {
269
+ returnPathname: '/b',
270
+ });
271
+ expect(a.cookieName).not.toBe(b.cookieName);
272
+ expect(realStorage.cookies.get(a.cookieName)).toBeTruthy();
273
+ expect(realStorage.cookies.get(b.cookieName)).toBeTruthy();
274
+ });
275
+
276
+ it('returns url and writes the verifier cookie via storage.setCookie', async () => {
277
+ const realStorage = makeStorage();
278
+ const realService = new AuthService(
279
+ mockConfig as any,
280
+ realStorage as any,
281
+ makeClient() as any,
282
+ sessionEncryption,
283
+ );
284
+
285
+ const result = await realService.createAuthorization('res');
286
+
287
+ expect(result.url).toContain('authorize');
288
+ expect(realStorage.cookies.get(result.cookieName)).toBeTruthy();
289
+ expect(result.headers?.['Set-Cookie']).toContain(`${result.cookieName}=`);
290
+ expect(realStorage.lastSetOptions.get(result.cookieName)?.path).toBe('/');
291
+ });
292
+ });
293
+
294
+ describe('createSignIn()', () => {
295
+ it('returns sign-in URL and writes the verifier cookie', async () => {
296
+ const realStorage = makeStorage();
297
+ const realService = new AuthService(
298
+ mockConfig as any,
299
+ realStorage as any,
300
+ makeClient() as any,
301
+ sessionEncryption,
302
+ );
303
+
304
+ const result = await realService.createSignIn('res');
173
305
 
174
- expect(result).toContain('authorize');
306
+ expect(result.url).toContain('screen_hint=sign-in');
307
+ expect(realStorage.cookies.get(result.cookieName)).toBeTruthy();
175
308
  });
176
309
  });
177
310
 
178
- describe('getSignInUrl()', () => {
179
- it('returns sign-in URL', async () => {
180
- const result = await service.getSignInUrl();
311
+ describe('createSignUp()', () => {
312
+ it('returns sign-up URL and writes the verifier cookie', async () => {
313
+ const realStorage = makeStorage();
314
+ const realService = new AuthService(
315
+ mockConfig as any,
316
+ realStorage as any,
317
+ makeClient() as any,
318
+ sessionEncryption,
319
+ );
320
+
321
+ const result = await realService.createSignUp('res');
181
322
 
182
- expect(result).toContain('screen_hint=sign-in');
323
+ expect(result.url).toContain('screen_hint=sign-up');
324
+ expect(realStorage.cookies.get(result.cookieName)).toBeTruthy();
183
325
  });
184
326
  });
185
327
 
186
- describe('getSignUpUrl()', () => {
187
- it('returns sign-up URL', async () => {
188
- const result = await service.getSignUpUrl();
328
+ describe('clearPendingVerifier()', () => {
329
+ it('emits a delete cookie with Path=/', async () => {
330
+ const realStorage = makeStorage();
331
+ const realService = new AuthService(
332
+ mockConfig as any,
333
+ realStorage as any,
334
+ makeClient() as any,
335
+ sessionEncryption,
336
+ );
337
+
338
+ const { cookieName } = await realService.createSignIn(undefined);
339
+ const sealedState = realStorage.cookies.get(cookieName)!;
340
+
341
+ await realService.clearPendingVerifier('res', { state: sealedState });
342
+
343
+ expect(realStorage.lastClearOptions.get(cookieName)?.path).toBe('/');
344
+ });
345
+
346
+ it('accepts undefined response for headers-only adapters', async () => {
347
+ const realStorage = makeStorage();
348
+ const realService = new AuthService(
349
+ mockConfig as any,
350
+ realStorage as any,
351
+ makeClient() as any,
352
+ sessionEncryption,
353
+ );
354
+
355
+ const { cookieName } = await realService.createSignIn(undefined);
356
+ const sealedState = realStorage.cookies.get(cookieName)!;
357
+
358
+ const result = await realService.clearPendingVerifier(undefined, {
359
+ state: sealedState,
360
+ });
361
+
362
+ expect(result.headers?.['Set-Cookie']).toContain(`${cookieName}=`);
363
+ });
364
+
365
+ it('clears the flow-specific cookie derived from state', async () => {
366
+ const realStorage = makeStorage();
367
+ const realService = new AuthService(
368
+ mockConfig as any,
369
+ realStorage as any,
370
+ makeClient() as any,
371
+ sessionEncryption,
372
+ );
373
+
374
+ const { cookieName } = await realService.createSignIn(undefined);
375
+ const sealedState = realStorage.cookies.get(cookieName)!;
376
+
377
+ const clearCookieSpy = vi.spyOn(realStorage, 'clearCookie');
378
+ await realService.clearPendingVerifier(undefined, { state: sealedState });
379
+
380
+ expect(clearCookieSpy).toHaveBeenCalledWith(
381
+ undefined,
382
+ cookieName,
383
+ expect.any(Object),
384
+ );
385
+ });
386
+
387
+ it('threads redirectUri into the cookie options', async () => {
388
+ const realStorage = makeStorage();
389
+ const realService = new AuthService(
390
+ mockConfig as any,
391
+ realStorage as any,
392
+ makeClient() as any,
393
+ sessionEncryption,
394
+ );
395
+
396
+ const { cookieName } = await realService.createSignIn(undefined, {
397
+ redirectUri: 'https://custom.example/cb',
398
+ });
399
+ const sealedState = realStorage.cookies.get(cookieName)!;
189
400
 
190
- expect(result).toContain('screen_hint=sign-up');
401
+ await realService.clearPendingVerifier(undefined, {
402
+ state: sealedState,
403
+ redirectUri: 'https://custom.example/cb',
404
+ });
405
+
406
+ expect(realStorage.lastClearOptions.get(cookieName)?.path).toBe('/');
191
407
  });
192
408
  });
193
409
 
@@ -195,73 +411,510 @@ describe('AuthService', () => {
195
411
  it('returns WorkOS client', () => {
196
412
  const result = service.getWorkOS();
197
413
 
198
- expect(result).toBe(mockClient);
414
+ expect(result).toBeDefined();
415
+ expect(typeof (result as any).userManagement.getJwksUrl).toBe('function');
199
416
  });
200
417
  });
201
418
 
202
419
  describe('handleCallback()', () => {
203
- it('authenticates and creates session', async () => {
204
- const result = await service.handleCallback('request', 'response', {
205
- code: 'auth-code-123',
420
+ it('round-trips through createSignIn → handleCallback', async () => {
421
+ const capture: { authCall?: Record<string, unknown> } = {};
422
+ const realStorage = makeStorage();
423
+ const realService = new AuthService(
424
+ mockConfig as any,
425
+ realStorage as any,
426
+ makeClient(capture) as any,
427
+ sessionEncryption,
428
+ );
429
+
430
+ const { cookieName } = await realService.createAuthorization('res', {
431
+ returnPathname: '/dashboard',
432
+ state: 'my.custom.state',
206
433
  });
434
+ const sealedState = realStorage.cookies.get(cookieName)!;
207
435
 
208
- expect(result.authResponse.accessToken).toBe('access-auth-code-123');
209
- expect(result.returnPathname).toBe('/');
210
- expect(result.response).toBe('updated-response');
436
+ const result = await realService.handleCallback('req', 'res', {
437
+ code: 'auth-code-xyz',
438
+ state: sealedState,
439
+ });
440
+
441
+ expect(result.authResponse.accessToken).toBe('access-auth-code-xyz');
442
+ expect(result.returnPathname).toBe('/dashboard');
443
+ expect(result.state).toBe('my.custom.state');
444
+ expect(capture.authCall?.codeVerifier).toBe(testVerifier);
211
445
  });
212
446
 
213
- it('decodes returnPathname from state', async () => {
214
- const state = btoa(JSON.stringify({ returnPathname: '/dashboard' }));
447
+ it('returns both session and verifier-delete Set-Cookie as a string[]', async () => {
448
+ const realStorage = makeStorage();
449
+ const realService = new AuthService(
450
+ mockConfig as any,
451
+ realStorage as any,
452
+ makeClient() as any,
453
+ sessionEncryption,
454
+ );
455
+
456
+ const { cookieName } = await realService.createAuthorization('res');
457
+ const sealedState = realStorage.cookies.get(cookieName)!;
215
458
 
216
- const result = await service.handleCallback('request', 'response', {
217
- code: 'auth-code-123',
218
- state,
459
+ const result = await realService.handleCallback('req', 'res', {
460
+ code: 'code',
461
+ state: sealedState,
219
462
  });
220
463
 
221
- expect(result.returnPathname).toBe('/dashboard');
464
+ const setCookie = result.headers?.['Set-Cookie'];
465
+ expect(Array.isArray(setCookie)).toBe(true);
466
+ expect(setCookie).toHaveLength(2);
467
+ expect(
468
+ (setCookie as string[]).some(c => c.startsWith('wos-session=')),
469
+ ).toBe(true);
470
+ expect(
471
+ (setCookie as string[]).some(c => c.startsWith(`${cookieName}=`)),
472
+ ).toBe(true);
473
+ expect(
474
+ (setCookie as string[]).find(c => c.startsWith(`${cookieName}=`)),
475
+ ).toContain('Max-Age=0');
222
476
  });
223
477
 
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',
478
+ it('merges lowercase set-cookie headers into an array (case-insensitive)', async () => {
479
+ // Regression: adapters that normalize through Headers objects emit
480
+ // lowercase `set-cookie`.
481
+ const realStorage = makeStorage();
482
+ const lowerStorage = {
483
+ ...realStorage,
484
+ setCookie: async (
485
+ _res: any,
486
+ name: string,
487
+ value: string,
488
+ options: any,
489
+ ) => {
490
+ realStorage.cookies.set(name, value);
491
+ realStorage.lastSetOptions.set(name, options);
492
+ return {
493
+ headers: {
494
+ 'set-cookie': `${name}=${value}; Path=${options.path}; Max-Age=${options.maxAge}`,
495
+ },
496
+ };
497
+ },
498
+ clearCookie: async (_res: any, name: string, options: any) => {
499
+ realStorage.lastClearOptions.set(name, options);
500
+ realStorage.cookies.delete(name);
501
+ return {
502
+ headers: {
503
+ 'set-cookie': `${name}=; Path=${options.path}; Max-Age=0`,
504
+ },
505
+ };
506
+ },
507
+ saveSession: async () => ({
508
+ response: 'updated-response',
509
+ headers: {
510
+ 'set-cookie': 'wos-session=encrypted; Path=/; Max-Age=3600',
511
+ },
512
+ }),
513
+ };
514
+ const realService = new AuthService(
515
+ mockConfig as any,
516
+ lowerStorage as any,
517
+ makeClient() as any,
518
+ sessionEncryption,
519
+ );
520
+
521
+ const { cookieName } = await realService.createAuthorization('res');
522
+ const sealedState = realStorage.cookies.get(cookieName)!;
523
+
524
+ const result = await realService.handleCallback('req', 'res', {
525
+ code: 'code',
526
+ state: sealedState,
527
+ });
528
+
529
+ const setCookie = result.headers?.['set-cookie'];
530
+ expect(Array.isArray(setCookie)).toBe(true);
531
+ expect(setCookie).toHaveLength(2);
532
+ expect(
533
+ (setCookie as string[]).some(c => c.startsWith('wos-session=')),
534
+ ).toBe(true);
535
+ expect(
536
+ (setCookie as string[]).some(c => c.startsWith(`${cookieName}=`)),
537
+ ).toBe(true);
538
+ });
539
+
540
+ it('emits the verifier-delete cookie with Path=/', async () => {
541
+ const realStorage = makeStorage();
542
+ const realService = new AuthService(
543
+ mockConfig as any,
544
+ realStorage as any,
545
+ makeClient() as any,
546
+ sessionEncryption,
547
+ );
548
+
549
+ const { cookieName } = await realService.createAuthorization('res');
550
+ const sealedState = realStorage.cookies.get(cookieName)!;
551
+
552
+ await realService.handleCallback('req', 'res', {
553
+ code: 'code',
554
+ state: sealedState,
555
+ });
556
+
557
+ expect(realStorage.lastClearOptions.get(cookieName)?.path).toBe('/');
558
+ });
559
+
560
+ it('throws OAuthStateMismatchError when storage cookie differs from url state', async () => {
561
+ const realStorage = makeStorage();
562
+ const realService = new AuthService(
563
+ mockConfig as any,
564
+ realStorage as any,
565
+ makeClient() as any,
566
+ sessionEncryption,
567
+ );
568
+
569
+ const { cookieName } = await realService.createAuthorization('res');
570
+ const sealedState = realStorage.cookies.get(cookieName)!;
571
+ // Tamper the stored cookie under the derived name that
572
+ // handleCallback reads.
573
+ realStorage.cookies.set(cookieName, sealedState.slice(0, -2) + 'XX');
574
+
575
+ await expect(
576
+ realService.handleCallback('req', 'res', {
577
+ code: 'code',
578
+ state: sealedState,
579
+ }),
580
+ ).rejects.toThrow(OAuthStateMismatchError);
581
+ });
582
+
583
+ it('throws PKCECookieMissingError when storage has no verifier cookie', async () => {
584
+ const realStorage = makeStorage();
585
+ const realService = new AuthService(
586
+ mockConfig as any,
587
+ realStorage as any,
588
+ makeClient() as any,
589
+ sessionEncryption,
590
+ );
591
+
592
+ const { cookieName } = await realService.createAuthorization('res');
593
+ const sealedState = realStorage.cookies.get(cookieName)!;
594
+ // Delete the derived-name cookie so handleCallback's read finds
595
+ // nothing — the scenario under test.
596
+ realStorage.cookies.delete(cookieName);
597
+
598
+ await expect(
599
+ realService.handleCallback('req', 'res', {
600
+ code: 'code',
601
+ state: sealedState,
602
+ }),
603
+ ).rejects.toThrow(PKCECookieMissingError);
604
+ });
605
+
606
+ it('throws OAuthStateMismatchError when state is undefined', async () => {
607
+ const realStorage = makeStorage();
608
+ const realService = new AuthService(
609
+ mockConfig as any,
610
+ realStorage as any,
611
+ makeClient() as any,
612
+ sessionEncryption,
613
+ );
614
+
615
+ await realService.createAuthorization('res');
616
+
617
+ await expect(
618
+ realService.handleCallback('req', 'res', {
619
+ code: 'code',
620
+ state: undefined,
621
+ }),
622
+ ).rejects.toThrow(OAuthStateMismatchError);
623
+ });
624
+
625
+ it('defaults returnPathname to "/" when the sealed state omits it', async () => {
626
+ const realStorage = makeStorage();
627
+ const realService = new AuthService(
628
+ mockConfig as any,
629
+ realStorage as any,
630
+ makeClient() as any,
631
+ sessionEncryption,
632
+ );
633
+
634
+ const { cookieName } = await realService.createAuthorization('res');
635
+ const sealedState = realStorage.cookies.get(cookieName)!;
636
+
637
+ const result = await realService.handleCallback('req', 'res', {
638
+ code: 'c',
639
+ state: sealedState,
228
640
  });
229
641
 
230
642
  expect(result.returnPathname).toBe('/');
231
- expect(result.state).toBe('invalid-state');
232
643
  });
233
644
 
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`;
645
+ it('best-effort clears the verifier cookie on OAuthStateMismatchError', async () => {
646
+ const realStorage = makeStorage();
647
+ const realService = new AuthService(
648
+ mockConfig as any,
649
+ realStorage as any,
650
+ makeClient() as any,
651
+ sessionEncryption,
652
+ );
653
+
654
+ const { cookieName } = await realService.createAuthorization('res');
655
+ const sealedState = realStorage.cookies.get(cookieName)!;
656
+ realStorage.cookies.set(cookieName, sealedState.slice(0, -2) + 'XX');
657
+
658
+ await expect(
659
+ realService.handleCallback('req', 'res', {
660
+ code: 'code',
661
+ state: sealedState,
662
+ }),
663
+ ).rejects.toThrow(OAuthStateMismatchError);
664
+
665
+ expect(realStorage.lastClearOptions.get(cookieName)?.path).toBe('/');
666
+ });
667
+
668
+ it('emits a scheme-agnostic (secure=false, sameSite=lax) delete on pre-unseal failure', async () => {
669
+ // Covers the end-to-end case that motivates the schemeAgnostic flag:
670
+ // sign-in used an http:// redirectUri override (secure=false), then
671
+ // the callback hits a pre-unseal error (state mismatch) — we don't
672
+ // know the override at that point, so the fallback delete must drop
673
+ // Secure so the browser accepts the Set-Cookie over http://.
674
+ const realStorage = makeStorage();
675
+ const realService = new AuthService(
676
+ { ...mockConfig, cookieSameSite: 'lax' } as any,
677
+ realStorage as any,
678
+ makeClient() as any,
679
+ sessionEncryption,
680
+ );
241
681
 
242
- const result = await service.handleCallback('request', 'response', {
243
- code: 'auth-code-123',
244
- state,
682
+ const { cookieName } = await realService.createAuthorization('res', {
683
+ redirectUri: 'http://localhost:3000/callback',
245
684
  });
685
+ // Confirm the original set was secure=false (the scenario we're
686
+ // proving we can still clean up).
687
+ expect(realStorage.lastSetOptions.get(cookieName)?.secure).toBe(false);
688
+ const sealedState = realStorage.cookies.get(cookieName)!;
689
+ realStorage.cookies.set(cookieName, sealedState.slice(0, -2) + 'XX');
690
+
691
+ await expect(
692
+ realService.handleCallback('req', 'res', {
693
+ code: 'code',
694
+ state: sealedState,
695
+ }),
696
+ ).rejects.toThrow(OAuthStateMismatchError);
697
+
698
+ const clearOpts = realStorage.lastClearOptions.get(cookieName);
699
+ expect(clearOpts?.secure).toBe(false);
700
+ expect(clearOpts?.sameSite).toBe('lax');
701
+ expect(clearOpts?.path).toBe('/');
702
+ });
703
+
704
+ it('keeps Secure on scheme-agnostic delete when sameSite=none (Secure is required)', async () => {
705
+ const realStorage = makeStorage();
706
+ const realService = new AuthService(
707
+ { ...mockConfig, cookieSameSite: 'none' } as any,
708
+ realStorage as any,
709
+ makeClient() as any,
710
+ sessionEncryption,
711
+ );
712
+
713
+ const { cookieName } = await realService.createAuthorization('res');
714
+ const sealedState = realStorage.cookies.get(cookieName)!;
715
+ realStorage.cookies.set(cookieName, sealedState.slice(0, -2) + 'XX');
246
716
 
247
- expect(result.returnPathname).toBe('/profile');
248
- expect(result.state).toBe('my-custom-state');
717
+ await expect(
718
+ realService.handleCallback('req', 'res', {
719
+ code: 'code',
720
+ state: sealedState,
721
+ }),
722
+ ).rejects.toThrow(OAuthStateMismatchError);
723
+
724
+ const clearOpts = realStorage.lastClearOptions.get(cookieName);
725
+ expect(clearOpts?.secure).toBe(true);
726
+ expect(clearOpts?.sameSite).toBe('none');
727
+ });
728
+
729
+ it('best-effort clears the verifier cookie on PKCECookieMissingError', async () => {
730
+ const realStorage = makeStorage();
731
+ const realService = new AuthService(
732
+ mockConfig as any,
733
+ realStorage as any,
734
+ makeClient() as any,
735
+ sessionEncryption,
736
+ );
737
+
738
+ const { cookieName } = await realService.createAuthorization('res');
739
+ const sealedState = realStorage.cookies.get(cookieName)!;
740
+ // Delete the derived-name cookie so handleCallback's read returns
741
+ // null and triggers the missing-cookie path under test.
742
+ realStorage.cookies.delete(cookieName);
743
+
744
+ await expect(
745
+ realService.handleCallback('req', 'res', {
746
+ code: 'code',
747
+ state: sealedState,
748
+ }),
749
+ ).rejects.toThrow(PKCECookieMissingError);
750
+
751
+ expect(realStorage.lastClearOptions.get(cookieName)?.path).toBe('/');
752
+ });
753
+
754
+ it('best-effort clears the verifier cookie when authenticateWithCode throws', async () => {
755
+ const realStorage = makeStorage();
756
+ const throwingClient = makeClient();
757
+ throwingClient.userManagement.authenticateWithCode = async () => {
758
+ throw new Error('WorkOS exchange failed');
759
+ };
760
+ const realService = new AuthService(
761
+ mockConfig as any,
762
+ realStorage as any,
763
+ throwingClient as any,
764
+ sessionEncryption,
765
+ );
766
+
767
+ const { cookieName } = await realService.createAuthorization('res');
768
+ const sealedState = realStorage.cookies.get(cookieName)!;
769
+
770
+ await expect(
771
+ realService.handleCallback('req', 'res', {
772
+ code: 'code',
773
+ state: sealedState,
774
+ }),
775
+ ).rejects.toThrow('WorkOS exchange failed');
776
+
777
+ expect(realStorage.lastClearOptions.get(cookieName)?.path).toBe('/');
249
778
  });
250
779
 
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`;
780
+ it('best-effort clears the verifier cookie when saveSession throws', async () => {
781
+ const realStorage = makeStorage();
782
+ realStorage.saveSession = async () => {
783
+ throw new Error('storage write failed');
784
+ };
785
+ const realService = new AuthService(
786
+ mockConfig as any,
787
+ realStorage as any,
788
+ makeClient() as any,
789
+ sessionEncryption,
790
+ );
791
+
792
+ const { cookieName } = await realService.createAuthorization('res');
793
+ const sealedState = realStorage.cookies.get(cookieName)!;
257
794
 
258
- const result = await service.handleCallback('request', 'response', {
259
- code: 'auth-code-123',
260
- state,
795
+ await expect(
796
+ realService.handleCallback('req', 'res', {
797
+ code: 'code',
798
+ state: sealedState,
799
+ }),
800
+ ).rejects.toThrow('storage write failed');
801
+
802
+ expect(realStorage.lastClearOptions.get(cookieName)?.path).toBe('/');
803
+ });
804
+
805
+ it('swallows clearCookie errors so the original failure propagates', async () => {
806
+ const realStorage = makeStorage();
807
+ const throwingClient = makeClient();
808
+ throwingClient.userManagement.authenticateWithCode = async () => {
809
+ throw new Error('original exchange failure');
810
+ };
811
+ realStorage.clearCookie = async () => {
812
+ throw new Error('clearCookie blew up');
813
+ };
814
+ const realService = new AuthService(
815
+ mockConfig as any,
816
+ realStorage as any,
817
+ throwingClient as any,
818
+ sessionEncryption,
819
+ );
820
+
821
+ const { cookieName } = await realService.createAuthorization('res');
822
+ const sealedState = realStorage.cookies.get(cookieName)!;
823
+
824
+ await expect(
825
+ realService.handleCallback('req', 'res', {
826
+ code: 'code',
827
+ state: sealedState,
828
+ }),
829
+ ).rejects.toThrow('original exchange failure');
830
+ });
831
+
832
+ it('round-trips redirectUri override through the sealed state into the clear cookie', async () => {
833
+ const realStorage = makeStorage();
834
+ const realService = new AuthService(
835
+ mockConfig as any,
836
+ realStorage as any,
837
+ makeClient() as any,
838
+ sessionEncryption,
839
+ );
840
+
841
+ // Override with an http:// URL so the `secure` attribute differs from
842
+ // the https:// default — proves handleCallback used the override.
843
+ const { cookieName } = await realService.createAuthorization('res', {
844
+ redirectUri: 'http://localhost:3000/callback',
261
845
  });
846
+ const sealedState = realStorage.cookies.get(cookieName)!;
262
847
 
263
- expect(result.returnPathname).toBe('/dashboard');
264
- expect(result.state).toBe('user.state.with.dots');
848
+ expect(realStorage.lastSetOptions.get(cookieName)?.secure).toBe(false);
849
+
850
+ await realService.handleCallback('req', 'res', {
851
+ code: 'code',
852
+ state: sealedState,
853
+ });
854
+
855
+ expect(realStorage.lastClearOptions.get(cookieName)?.secure).toBe(false);
856
+ });
857
+
858
+ describe('per-flow cookie isolation', () => {
859
+ it('reads and clears the cookie derived from URL state', async () => {
860
+ // Start a flow. createSignIn wrote under the derived name.
861
+ const realStorage = makeStorage();
862
+ const authService = new AuthService(
863
+ mockConfig as any,
864
+ realStorage as any,
865
+ makeClient() as any,
866
+ sessionEncryption,
867
+ );
868
+ const { cookieName } = await authService.createSignIn(undefined);
869
+ const sealedState = realStorage.cookies.get(cookieName)!;
870
+
871
+ const result = await authService.handleCallback(
872
+ 'req' as never,
873
+ 'res' as never,
874
+ { code: 'abc', state: sealedState },
875
+ );
876
+
877
+ const setCookies = Array.isArray(result.headers?.['Set-Cookie'])
878
+ ? (result.headers!['Set-Cookie'] as string[])
879
+ : ([result.headers?.['Set-Cookie']].filter(Boolean) as string[]);
880
+ const deleteLine = setCookies.find(c => c.startsWith(`${cookieName}=`));
881
+ expect(deleteLine).toBeDefined();
882
+ expect(deleteLine).toContain('Max-Age=0');
883
+ });
884
+
885
+ it("does not touch another concurrent flow's cookie", async () => {
886
+ const realStorage = makeStorage();
887
+ const authService = new AuthService(
888
+ mockConfig as any,
889
+ realStorage as any,
890
+ makeClient() as any,
891
+ sessionEncryption,
892
+ );
893
+ const a = await authService.createSignIn(undefined, {
894
+ returnPathname: '/a',
895
+ });
896
+ const b = await authService.createSignIn(undefined, {
897
+ returnPathname: '/b',
898
+ });
899
+ const sealedA = realStorage.cookies.get(a.cookieName)!;
900
+
901
+ const result = await authService.handleCallback(
902
+ 'req' as never,
903
+ 'res' as never,
904
+ { code: 'abc', state: sealedA },
905
+ );
906
+
907
+ const setCookies = Array.isArray(result.headers?.['Set-Cookie'])
908
+ ? (result.headers!['Set-Cookie'] as string[])
909
+ : ([result.headers?.['Set-Cookie']].filter(Boolean) as string[]);
910
+ // Flow A's cookie gets a delete. Flow B's cookie must NOT.
911
+ expect(setCookies.some(c => c.startsWith(`${a.cookieName}=`))).toBe(
912
+ true,
913
+ );
914
+ expect(setCookies.some(c => c.startsWith(`${b.cookieName}=`))).toBe(
915
+ false,
916
+ );
917
+ });
265
918
  });
266
919
  });
267
920
  });