@workos/authkit-session 0.4.0 → 0.5.1

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 (39) hide show
  1. package/README.md +23 -6
  2. package/dist/core/pkce/cookieName.d.ts +17 -0
  3. package/dist/core/pkce/cookieName.d.ts.map +1 -0
  4. package/dist/core/pkce/cookieName.js +26 -0
  5. package/dist/core/pkce/cookieName.js.map +1 -0
  6. package/dist/core/pkce/cookieOptions.d.ts +0 -2
  7. package/dist/core/pkce/cookieOptions.d.ts.map +1 -1
  8. package/dist/core/pkce/cookieOptions.js +0 -2
  9. package/dist/core/pkce/cookieOptions.js.map +1 -1
  10. package/dist/core/pkce/generateAuthorizationUrl.d.ts +1 -0
  11. package/dist/core/pkce/generateAuthorizationUrl.d.ts.map +1 -1
  12. package/dist/core/pkce/generateAuthorizationUrl.js +5 -2
  13. package/dist/core/pkce/generateAuthorizationUrl.js.map +1 -1
  14. package/dist/core/session/types.d.ts +8 -3
  15. package/dist/core/session/types.d.ts.map +1 -1
  16. package/dist/index.d.ts +1 -0
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +4 -0
  19. package/dist/index.js.map +1 -1
  20. package/dist/service/AuthService.d.ts +13 -7
  21. package/dist/service/AuthService.d.ts.map +1 -1
  22. package/dist/service/AuthService.js +34 -18
  23. package/dist/service/AuthService.js.map +1 -1
  24. package/dist/utils.d.ts +12 -0
  25. package/dist/utils.d.ts.map +1 -1
  26. package/dist/utils.js +26 -0
  27. package/dist/utils.js.map +1 -1
  28. package/package.json +1 -1
  29. package/src/core/pkce/cookieName.spec.ts +56 -0
  30. package/src/core/pkce/cookieName.ts +27 -0
  31. package/src/core/pkce/cookieOptions.ts +0 -3
  32. package/src/core/pkce/generateAuthorizationUrl.ts +6 -6
  33. package/src/core/pkce/pkce.spec.ts +9 -0
  34. package/src/core/session/types.ts +8 -4
  35. package/src/index.ts +8 -0
  36. package/src/service/AuthService.spec.ts +227 -91
  37. package/src/service/AuthService.ts +40 -26
  38. package/src/utils.spec.ts +58 -1
  39. package/src/utils.ts +28 -0
@@ -1,10 +1,8 @@
1
1
  import type { WorkOS } from '@workos-inc/node';
2
2
  import { AuthKitCore } from '../core/AuthKitCore.js';
3
3
  import type { AuthKitConfig } from '../core/config/types.js';
4
- import {
5
- getPKCECookieOptions,
6
- PKCE_COOKIE_NAME,
7
- } from '../core/pkce/cookieOptions.js';
4
+ import { getPKCECookieNameForState } from '../core/pkce/cookieName.js';
5
+ import { getPKCECookieOptions } from '../core/pkce/cookieOptions.js';
8
6
  import { AuthOperations } from '../operations/AuthOperations.js';
9
7
  import type {
10
8
  AuthResult,
@@ -16,6 +14,7 @@ import type {
16
14
  SessionEncryption,
17
15
  SessionStorage,
18
16
  } from '../core/session/types.js';
17
+ import { sanitizeReturnPathname } from '../utils.js';
19
18
 
20
19
  /**
21
20
  * Merge two `HeadersBag` values. `Set-Cookie` matching is case-insensitive;
@@ -229,15 +228,15 @@ export class AuthService<TRequest, TResponse> {
229
228
  response: TResponse | undefined,
230
229
  options: GetAuthorizationUrlOptions = {},
231
230
  ): Promise<CreateAuthorizationResult<TResponse>> {
232
- const { url, sealedState, cookieOptions } =
231
+ const { url, sealedState, cookieName, cookieOptions } =
233
232
  await this.operations.createAuthorization(options);
234
233
  const write = await this.storage.setCookie(
235
234
  response,
236
- PKCE_COOKIE_NAME,
235
+ cookieName,
237
236
  sealedState,
238
237
  cookieOptions,
239
238
  );
240
- return { url, ...write };
239
+ return { url, cookieName, ...write };
241
240
  }
242
241
 
243
242
  /**
@@ -267,24 +266,28 @@ export class AuthService<TRequest, TResponse> {
267
266
  }
268
267
 
269
268
  /**
270
- * Emit a `Set-Cookie` header that clears the PKCE verifier cookie.
269
+ * Emit a `Set-Cookie` header that clears the PKCE verifier cookie
270
+ * for the flow identified by `state`.
271
271
  *
272
- * Use on any exit path where a sign-in was started (verifier cookie
273
- * written) but `handleCallback` will not run to clear it — OAuth error
274
- * responses, missing `code`, early bail-outs.
272
+ * **Breaking change in 0.5.0.** The `state` option is now required
273
+ * — the per-flow cookie naming scheme has no single "legacy" name
274
+ * to clear. Callers typically read `state` from the callback URL;
275
+ * when `state` is absent (malformed callback), do not call this
276
+ * method. The 10-minute PKCE TTL cleans up orphans.
275
277
  *
276
278
  * Pass `options.redirectUri` on requests that used a per-request
277
- * `redirectUri` override at sign-in time, so the delete cookie's computed
278
- * attributes (notably `secure`) match what was originally set.
279
+ * `redirectUri` override at sign-in time, so the delete cookie's
280
+ * computed attributes (notably `secure`) match the original set.
279
281
  */
280
282
  async clearPendingVerifier(
281
283
  response: TResponse | undefined,
282
- options?: Pick<GetAuthorizationUrlOptions, 'redirectUri'>,
284
+ options: { state: string; redirectUri?: string },
283
285
  ): Promise<{ response?: TResponse; headers?: HeadersBag }> {
286
+ const cookieName = getPKCECookieNameForState(options.state);
284
287
  return this.storage.clearCookie(
285
288
  response,
286
- PKCE_COOKIE_NAME,
287
- getPKCECookieOptions(this.config, options?.redirectUri),
289
+ cookieName,
290
+ getPKCECookieOptions(this.config, options.redirectUri),
288
291
  );
289
292
  }
290
293
 
@@ -321,7 +324,12 @@ export class AuthService<TRequest, TResponse> {
321
324
  state: string | undefined;
322
325
  },
323
326
  ) {
324
- const cookieValue = await this.storage.getCookie(request, PKCE_COOKIE_NAME);
327
+ const cookieName = options.state
328
+ ? getPKCECookieNameForState(options.state)
329
+ : null;
330
+ const cookieValue = cookieName
331
+ ? await this.storage.getCookie(request, cookieName)
332
+ : null;
325
333
 
326
334
  let unsealed;
327
335
  try {
@@ -337,7 +345,7 @@ export class AuthService<TRequest, TResponse> {
337
345
  // case so the Set-Cookie is accepted over http:// callbacks too.
338
346
  // The `sameSite: 'none'` case already forces Secure on both set and
339
347
  // clear, so there's no scheme-mismatch risk there.
340
- await this.bestEffortClearVerifier(response, undefined, {
348
+ await this.bestEffortClearVerifier(response, cookieName, undefined, {
341
349
  schemeAgnostic: true,
342
350
  });
343
351
  throw err;
@@ -363,21 +371,25 @@ export class AuthService<TRequest, TResponse> {
363
371
 
364
372
  const encryptedSession = await this.core.encryptSession(session);
365
373
  const save = await this.storage.saveSession(response, encryptedSession);
366
- const clear = await this.storage.clearCookie(
367
- save.response ?? response,
368
- PKCE_COOKIE_NAME,
369
- clearOptions,
370
- );
374
+
375
+ let clear: { response?: TResponse; headers?: HeadersBag } = {};
376
+ if (cookieName) {
377
+ clear = await this.storage.clearCookie(
378
+ save.response ?? response,
379
+ cookieName,
380
+ clearOptions,
381
+ );
382
+ }
371
383
 
372
384
  return {
373
385
  response: clear.response ?? save.response,
374
386
  headers: mergeHeaderBags(save.headers, clear.headers),
375
- returnPathname: returnPathname ?? '/',
387
+ returnPathname: sanitizeReturnPathname(returnPathname),
376
388
  state: customState,
377
389
  authResponse,
378
390
  };
379
391
  } catch (err) {
380
- await this.bestEffortClearVerifier(response, redirectUri);
392
+ await this.bestEffortClearVerifier(response, cookieName, redirectUri);
381
393
  throw err;
382
394
  }
383
395
  }
@@ -397,15 +409,17 @@ export class AuthService<TRequest, TResponse> {
397
409
  */
398
410
  private async bestEffortClearVerifier(
399
411
  response: TResponse | undefined,
412
+ cookieName: string | null,
400
413
  redirectUri: string | undefined,
401
414
  { schemeAgnostic = false }: { schemeAgnostic?: boolean } = {},
402
415
  ): Promise<void> {
416
+ if (!cookieName) return; // nothing to clear — no state on the URL.
403
417
  const options = getPKCECookieOptions(this.config, redirectUri);
404
418
  if (schemeAgnostic && options.sameSite === 'lax') {
405
419
  options.secure = false;
406
420
  }
407
421
  try {
408
- await this.storage.clearCookie(response, PKCE_COOKIE_NAME, options);
422
+ await this.storage.clearCookie(response, cookieName, options);
409
423
  } catch {
410
424
  // Swallow: cleanup is opportunistic; callers get the original error.
411
425
  }
package/src/utils.spec.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { once } from './utils.js';
1
+ import { once, sanitizeReturnPathname } from './utils.js';
2
2
 
3
3
  describe('utils', () => {
4
4
  describe('once', () => {
@@ -9,4 +9,61 @@ describe('utils', () => {
9
9
  expect(fn()).toEqual(1); // test it's the same on every call
10
10
  });
11
11
  });
12
+
13
+ describe('sanitizeReturnPathname (CWE-601 open-redirect protection)', () => {
14
+ it.each([
15
+ ['absolute URL to evil host', 'https://evil.com/steal'],
16
+ ['absolute http URL', 'http://evil.com/steal'],
17
+ ['protocol-relative URL', '//evil.com/steal'],
18
+ ['backslash smuggle', '/\\evil.com/path'],
19
+ ['double-backslash', '\\\\evil.com/path'],
20
+ ['javascript: scheme', 'javascript:alert(1)'],
21
+ ['data: scheme', 'data:text/html,<script>alert(1)</script>'],
22
+ ['tab smuggling', '/\tevil.com'],
23
+ ['newline smuggling', '/\nevil.com'],
24
+ ['carriage-return smuggling', '/\revil.com'],
25
+ ['url-encoded slashes', '%2f%2fevil.com/steal'],
26
+ ['double-encoded slashes', '%252f%252fevil.com/steal'],
27
+ ['userinfo smuggling', 'https://user:pass@evil.com/path'],
28
+ ['leading-whitespace protocol-relative', ' //evil.com'],
29
+ ['ftp scheme', 'ftp://evil.com'],
30
+ ['null-byte injection', '/path%00.evil.com'],
31
+ ])('neutralizes %s to a same-origin relative path', (_desc, payload) => {
32
+ const result = sanitizeReturnPathname(payload);
33
+ const resolved = new URL(result, 'https://trusted.example.com');
34
+ expect(resolved.origin).toBe('https://trusted.example.com');
35
+ });
36
+
37
+ it.each([
38
+ ['/dashboard'],
39
+ ['/dashboard?tab=settings'],
40
+ ['/dashboard#billing'],
41
+ ['/docs/api?v=2#auth'],
42
+ ])('preserves legitimate path %s', path => {
43
+ expect(sanitizeReturnPathname(path)).toBe(path);
44
+ });
45
+
46
+ it.each([[undefined], [null], [''], [42], [{}]])(
47
+ 'falls back to `/` for %p',
48
+ input => {
49
+ expect(sanitizeReturnPathname(input)).toBe('/');
50
+ },
51
+ );
52
+
53
+ it('accepts a custom fallback', () => {
54
+ expect(sanitizeReturnPathname(undefined, '/login')).toBe('/login');
55
+ });
56
+
57
+ it('sanitizes an unsafe custom fallback — the fallback is not trusted either', () => {
58
+ expect(sanitizeReturnPathname(undefined, '//evil.com')).toBe('/');
59
+ expect(sanitizeReturnPathname(undefined, 'https://evil.com/x')).toBe(
60
+ '/x',
61
+ );
62
+ });
63
+
64
+ it('backstops to `/` when both input and fallback are unusable', () => {
65
+ expect(sanitizeReturnPathname(undefined, '')).toBe('/');
66
+ expect(sanitizeReturnPathname(null, null as unknown as string)).toBe('/');
67
+ });
68
+ });
12
69
  });
package/src/utils.ts CHANGED
@@ -41,3 +41,31 @@ export function constantTimeEqual(a: Uint8Array, b: Uint8Array): boolean {
41
41
  for (let i = 0; i < a.length; i++) diff |= a[i]! ^ b[i]!;
42
42
  return diff === 0;
43
43
  }
44
+
45
+ /**
46
+ * Normalize an untrusted return-path candidate (e.g. decoded from OAuth
47
+ * state) to a same-origin relative URL. The returned value always begins
48
+ * with exactly one `/`, safe to emit directly as a `Location` header.
49
+ *
50
+ * Parsing against a throwaway origin lets the WHATWG URL parser strip any
51
+ * smuggled host, scheme, backslash, tab, or newline; the leading-slash
52
+ * normalization defuses `//evil.com`-style protocol-relative redirects
53
+ * (CWE-601). `fallback` is sanitized by the same pipeline so a hostile
54
+ * fallback can't reopen the hole.
55
+ */
56
+ export function sanitizeReturnPathname(
57
+ input: unknown,
58
+ fallback: string = '/',
59
+ ): string {
60
+ for (const candidate of [input, fallback]) {
61
+ if (typeof candidate !== 'string' || candidate.length === 0) continue;
62
+ try {
63
+ const parsed = new URL(candidate, 'https://placeholder.invalid');
64
+ const path = '/' + parsed.pathname.replace(/^\/+/, '');
65
+ return `${path}${parsed.search}${parsed.hash}`;
66
+ } catch {
67
+ // Unparseable; try the next candidate.
68
+ }
69
+ }
70
+ return '/';
71
+ }