@workos/authkit-session 0.3.4 → 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 (82) 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/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/cookieOptions.d.ts +36 -0
  15. package/dist/core/pkce/cookieOptions.d.ts.map +1 -0
  16. package/dist/core/pkce/cookieOptions.js +55 -0
  17. package/dist/core/pkce/cookieOptions.js.map +1 -0
  18. package/dist/core/pkce/generateAuthorizationUrl.d.ts +45 -0
  19. package/dist/core/pkce/generateAuthorizationUrl.d.ts.map +1 -0
  20. package/dist/core/pkce/generateAuthorizationUrl.js +82 -0
  21. package/dist/core/pkce/generateAuthorizationUrl.js.map +1 -0
  22. package/dist/core/pkce/state.d.ts +53 -0
  23. package/dist/core/pkce/state.d.ts.map +1 -0
  24. package/dist/core/pkce/state.js +91 -0
  25. package/dist/core/pkce/state.js.map +1 -0
  26. package/dist/core/session/CookieSessionStorage.d.ts +25 -15
  27. package/dist/core/session/CookieSessionStorage.d.ts.map +1 -1
  28. package/dist/core/session/CookieSessionStorage.js +20 -27
  29. package/dist/core/session/CookieSessionStorage.js.map +1 -1
  30. package/dist/core/session/TokenManager.js +2 -2
  31. package/dist/core/session/TokenManager.js.map +1 -1
  32. package/dist/core/session/serializeCookie.d.ts +13 -0
  33. package/dist/core/session/serializeCookie.d.ts.map +1 -0
  34. package/dist/core/session/serializeCookie.js +32 -0
  35. package/dist/core/session/serializeCookie.js.map +1 -0
  36. package/dist/core/session/types.d.ts +71 -2
  37. package/dist/core/session/types.d.ts.map +1 -1
  38. package/dist/index.d.ts +1 -1
  39. package/dist/index.d.ts.map +1 -1
  40. package/dist/index.js +1 -1
  41. package/dist/index.js.map +1 -1
  42. package/dist/operations/AuthOperations.d.ts +15 -13
  43. package/dist/operations/AuthOperations.d.ts.map +1 -1
  44. package/dist/operations/AuthOperations.js +22 -34
  45. package/dist/operations/AuthOperations.js.map +1 -1
  46. package/dist/service/AuthService.d.ts +58 -15
  47. package/dist/service/AuthService.d.ts.map +1 -1
  48. package/dist/service/AuthService.js +157 -71
  49. package/dist/service/AuthService.js.map +1 -1
  50. package/dist/service/factory.d.ts.map +1 -1
  51. package/dist/service/factory.js +4 -3
  52. package/dist/service/factory.js.map +1 -1
  53. package/dist/utils.d.ts +16 -0
  54. package/dist/utils.d.ts.map +1 -1
  55. package/dist/utils.js +23 -0
  56. package/dist/utils.js.map +1 -1
  57. package/package.json +23 -20
  58. package/src/core/AuthKitCore.spec.ts +109 -0
  59. package/src/core/AuthKitCore.ts +55 -4
  60. package/src/core/encryption/ironWebcryptoEncryption.spec.ts +62 -0
  61. package/src/core/encryption/ironWebcryptoEncryption.ts +2 -2
  62. package/src/core/errors.spec.ts +33 -142
  63. package/src/core/errors.ts +21 -0
  64. package/src/core/pkce/cookieOptions.spec.ts +144 -0
  65. package/src/core/pkce/cookieOptions.ts +64 -0
  66. package/src/core/pkce/generateAuthorizationUrl.ts +123 -0
  67. package/src/core/pkce/pkce.spec.ts +166 -0
  68. package/src/core/pkce/state.spec.ts +216 -0
  69. package/src/core/pkce/state.ts +120 -0
  70. package/src/core/session/CookieSessionStorage.spec.ts +79 -3
  71. package/src/core/session/CookieSessionStorage.ts +56 -36
  72. package/src/core/session/TokenManager.ts +2 -2
  73. package/src/core/session/serializeCookie.ts +33 -0
  74. package/src/core/session/types.ts +79 -2
  75. package/src/index.ts +3 -0
  76. package/src/operations/AuthOperations.spec.ts +107 -62
  77. package/src/operations/AuthOperations.ts +34 -40
  78. package/src/service/AuthService.spec.ts +615 -98
  79. package/src/service/AuthService.ts +198 -73
  80. package/src/service/factory.spec.ts +4 -3
  81. package/src/service/factory.ts +6 -3
  82. package/src/utils.ts +22 -0
@@ -0,0 +1,144 @@
1
+ import type { AuthKitConfig } from '../config/types.js';
2
+ import { getPKCECookieOptions } from './cookieOptions.js';
3
+
4
+ const baseConfig: AuthKitConfig = {
5
+ clientId: 'client_test',
6
+ apiKey: 'sk_test',
7
+ redirectUri: 'https://app.example.com/callback',
8
+ cookiePassword: 'x'.repeat(48),
9
+ } as AuthKitConfig;
10
+
11
+ describe('getPKCECookieOptions', () => {
12
+ describe('sameSite behavior', () => {
13
+ it.each([
14
+ ['strict', 'lax'],
15
+ ['lax', 'lax'],
16
+ ['none', 'none'],
17
+ ] as const)(
18
+ 'maps cookieSameSite=%s to sameSite=%s',
19
+ (configured, expected) => {
20
+ const config = { ...baseConfig, cookieSameSite: configured };
21
+ const opts = getPKCECookieOptions(config);
22
+
23
+ expect(opts.sameSite).toBe(expected);
24
+ },
25
+ );
26
+
27
+ it('defaults to lax when cookieSameSite is undefined', () => {
28
+ const opts = getPKCECookieOptions(baseConfig);
29
+
30
+ expect(opts.sameSite).toBe('lax');
31
+ });
32
+
33
+ it('accepts mixed-case sameSite values', () => {
34
+ const config = { ...baseConfig, cookieSameSite: 'NONE' as any };
35
+ const opts = getPKCECookieOptions(config);
36
+
37
+ expect(opts.sameSite).toBe('none');
38
+ });
39
+ });
40
+
41
+ describe('secure flag', () => {
42
+ it('derives secure=true from https redirectUri', () => {
43
+ const opts = getPKCECookieOptions({
44
+ ...baseConfig,
45
+ redirectUri: 'https://app.example.com/callback',
46
+ });
47
+
48
+ expect(opts.secure).toBe(true);
49
+ });
50
+
51
+ it('derives secure=false from http redirectUri', () => {
52
+ const opts = getPKCECookieOptions({
53
+ ...baseConfig,
54
+ redirectUri: 'http://localhost:3000/callback',
55
+ });
56
+
57
+ expect(opts.secure).toBe(false);
58
+ });
59
+
60
+ it('prefers explicit redirectUri arg over config', () => {
61
+ const opts = getPKCECookieOptions(
62
+ { ...baseConfig, redirectUri: 'https://prod.example.com/callback' },
63
+ 'http://localhost:3000/callback',
64
+ );
65
+
66
+ expect(opts.secure).toBe(false);
67
+ });
68
+
69
+ it('fail-closes to secure=true on invalid URL', () => {
70
+ const opts = getPKCECookieOptions({
71
+ ...baseConfig,
72
+ redirectUri: 'not-a-valid-url',
73
+ });
74
+
75
+ expect(opts.secure).toBe(true);
76
+ });
77
+
78
+ it('forces secure=true when sameSite=none regardless of protocol', () => {
79
+ const opts = getPKCECookieOptions({
80
+ ...baseConfig,
81
+ cookieSameSite: 'none',
82
+ redirectUri: 'http://localhost:3000/callback',
83
+ });
84
+
85
+ expect(opts.secure).toBe(true);
86
+ });
87
+ });
88
+
89
+ describe('invariants', () => {
90
+ it('always sets httpOnly=true', () => {
91
+ const opts = getPKCECookieOptions(baseConfig);
92
+
93
+ expect(opts.httpOnly).toBe(true);
94
+ });
95
+
96
+ it('always sets maxAge=600', () => {
97
+ const opts = getPKCECookieOptions(baseConfig);
98
+
99
+ expect(opts.maxAge).toBe(600);
100
+ });
101
+ });
102
+
103
+ describe('path', () => {
104
+ it.each([
105
+ ['config callback path', 'https://app.example.com/callback'],
106
+ ['nested callback path', 'https://app.example.com/auth/v2/callback'],
107
+ ['host-only', 'https://app.example.com'],
108
+ ['invalid url', 'not-a-valid-url'],
109
+ ])(
110
+ "is always '/' regardless of redirectUri (%s)",
111
+ (_label, redirectUri) => {
112
+ const opts = getPKCECookieOptions({ ...baseConfig, redirectUri });
113
+
114
+ expect(opts.path).toBe('/');
115
+ },
116
+ );
117
+
118
+ it("is '/' even when per-call redirectUri override is supplied", () => {
119
+ const opts = getPKCECookieOptions(
120
+ baseConfig,
121
+ 'https://app.example.com/some/other/path',
122
+ );
123
+
124
+ expect(opts.path).toBe('/');
125
+ });
126
+ });
127
+
128
+ describe('domain passthrough', () => {
129
+ it('includes domain when configured', () => {
130
+ const opts = getPKCECookieOptions({
131
+ ...baseConfig,
132
+ cookieDomain: '.example.com',
133
+ });
134
+
135
+ expect(opts.domain).toBe('.example.com');
136
+ });
137
+
138
+ it('omits domain when not configured', () => {
139
+ const opts = getPKCECookieOptions(baseConfig);
140
+
141
+ expect(opts.domain).toBeUndefined();
142
+ });
143
+ });
144
+ });
@@ -0,0 +1,64 @@
1
+ import type { AuthKitConfig } from '../config/types.js';
2
+ import type { CookieOptions } from '../session/types.js';
3
+
4
+ /** Name of the PKCE verifier cookie on the wire. */
5
+ export const PKCE_COOKIE_NAME = 'wos-auth-verifier';
6
+
7
+ /**
8
+ * PKCE verifier cookie lifetime (seconds). Matches the 10-minute convention
9
+ * used by Arctic, openid-client, Clerk, and Okta for short-lived OAuth state
10
+ * cookies — long enough to accommodate slow sign-ins (out-of-band 2FA, tab
11
+ * switching) and short enough to keep the replay window tight if the sealed
12
+ * blob leaks.
13
+ *
14
+ * The same value is used as both the `Max-Age` cookie attribute and the
15
+ * sealed payload's TTL, so both layers reject a stale blob.
16
+ */
17
+ export const PKCE_COOKIE_MAX_AGE = 600;
18
+
19
+ /**
20
+ * Compute PKCE verifier cookie options from config + the resolved redirect URI.
21
+ *
22
+ * Behavior:
23
+ * - `sameSite: 'strict'` is downgraded to `'lax'` so the cookie survives the
24
+ * cross-site redirect back from WorkOS.
25
+ * - `sameSite: 'none'` is preserved (iframe/embed flows require it).
26
+ * - `secure` is forced to `true` when `sameSite === 'none'` (required by
27
+ * modern browsers). Otherwise it is inferred from the redirect URI's
28
+ * protocol, defaulting fail-closed to `true` on invalid/missing URLs.
29
+ * - `path` is always `/`. The cookie gets sent on every same-origin request
30
+ * during the 10-minute window, which is fine — it's HttpOnly and expires
31
+ * quickly. The tradeoff favors DX: path-scoped cookies are invisible in
32
+ * Chrome DevTools' Application panel from any page outside the scoped
33
+ * path, which makes PKCE wiring look broken even when it works.
34
+ *
35
+ * Internal helper — not exported from the package. Callers get cookie options
36
+ * indirectly via `AuthService.createSignIn` / `clearPendingVerifier`.
37
+ */
38
+ export function getPKCECookieOptions(
39
+ config: AuthKitConfig,
40
+ redirectUri?: string,
41
+ ): CookieOptions {
42
+ const configuredSameSite = (config.cookieSameSite ?? 'lax').toLowerCase();
43
+ const sameSite: 'lax' | 'none' =
44
+ configuredSameSite === 'none' ? 'none' : 'lax';
45
+
46
+ const urlString = redirectUri ?? config.redirectUri;
47
+ let secure = true;
48
+ if (urlString && sameSite !== 'none') {
49
+ try {
50
+ secure = new URL(urlString).protocol === 'https:';
51
+ } catch {
52
+ // Fail-closed: secure stays true.
53
+ }
54
+ }
55
+
56
+ return {
57
+ path: '/',
58
+ httpOnly: true,
59
+ secure,
60
+ sameSite,
61
+ maxAge: PKCE_COOKIE_MAX_AGE,
62
+ ...(config.cookieDomain ? { domain: config.cookieDomain } : {}),
63
+ };
64
+ }
@@ -0,0 +1,123 @@
1
+ import type { WorkOS } from '@workos-inc/node';
2
+ import type { AuthKitConfig } from '../config/types.js';
3
+ import { PKCEPayloadTooLargeError } from '../errors.js';
4
+ import { serializeCookie } from '../session/serializeCookie.js';
5
+ import type {
6
+ CookieOptions,
7
+ GetAuthorizationUrlOptions,
8
+ SessionEncryption,
9
+ } from '../session/types.js';
10
+ import { getPKCECookieOptions, PKCE_COOKIE_NAME } from './cookieOptions.js';
11
+ import { sealState } from './state.js';
12
+
13
+ /**
14
+ * Maximum UTF-8 byte length for caller-supplied `options.state`. Enforced
15
+ * as an early, user-facing check so large custom state fails with a clear
16
+ * error before any crypto work — ahead of the authoritative sealed-cookie
17
+ * length guard below.
18
+ */
19
+ export const PKCE_MAX_STATE_BYTES = 2048;
20
+
21
+ /**
22
+ * Maximum serialized `Set-Cookie` header length (bytes) for the verifier.
23
+ * Browsers start dropping cookies past ~4096 bytes per RFC 6265; 3800
24
+ * leaves headroom for proxies that cap lower and for the handful of
25
+ * cookie attributes whose size isn't known until serialization time
26
+ * (notably `Domain=` when `cookieDomain` is set).
27
+ */
28
+ export const PKCE_MAX_COOKIE_BYTES = 3800;
29
+
30
+ /**
31
+ * Internal authorization-URL generation result.
32
+ *
33
+ * Not exported: AuthService consumes `sealedState` + `cookieOptions` to write
34
+ * the verifier cookie via `storage.setCookie`, then returns only `{ url, response?, headers? }`
35
+ * to callers.
36
+ */
37
+ export interface GeneratedAuthorizationUrl {
38
+ url: string;
39
+ sealedState: string;
40
+ cookieOptions: CookieOptions;
41
+ }
42
+
43
+ /**
44
+ * Generate a WorkOS authorization URL bound to a PKCE verifier.
45
+ *
46
+ * Returns the URL, the sealed state blob (used as both the OAuth `state`
47
+ * query param AND the cookie value — identical string; the callback does a
48
+ * byte-compare before decrypting), and the cookie options the verifier
49
+ * cookie should be written with.
50
+ */
51
+ export async function generateAuthorizationUrl(params: {
52
+ client: WorkOS;
53
+ config: AuthKitConfig;
54
+ encryption: SessionEncryption;
55
+ options: GetAuthorizationUrlOptions;
56
+ }): Promise<GeneratedAuthorizationUrl> {
57
+ const { client, config, encryption, options } = params;
58
+ const redirectUri = options.redirectUri ?? config.redirectUri;
59
+
60
+ // Early bound on caller-supplied `state` so oversized input fails with a
61
+ // clear error before any crypto work. The authoritative guard on the
62
+ // serialized cookie runs below — this one just avoids confusing users.
63
+ if (options.state !== undefined) {
64
+ const stateBytes = new TextEncoder().encode(options.state).byteLength;
65
+ if (stateBytes > PKCE_MAX_STATE_BYTES) {
66
+ throw new PKCEPayloadTooLargeError(
67
+ `Custom OAuth state is ${stateBytes} bytes, exceeds supported limit of ${PKCE_MAX_STATE_BYTES} bytes. ` +
68
+ `The sealed state is stored as the wos-auth-verifier cookie; oversized values would be silently dropped by the browser.`,
69
+ );
70
+ }
71
+ }
72
+
73
+ const pkce = await client.pkce.generate();
74
+ const nonce = crypto.randomUUID();
75
+
76
+ const sealedState = await sealState(encryption, config.cookiePassword, {
77
+ nonce,
78
+ codeVerifier: pkce.codeVerifier,
79
+ returnPathname: options.returnPathname,
80
+ customState: options.state,
81
+ // Persisted so handleCallback's verifier-delete cookie uses the same
82
+ // computed attributes as the original setCookie — notably `secure`,
83
+ // which depends on the redirect URI's protocol.
84
+ redirectUri: options.redirectUri,
85
+ });
86
+
87
+ // Authoritative guard: measure the actual Set-Cookie header the adapter
88
+ // will emit. Catches cases the input-only check can't, like oversized
89
+ // returnPathname combined with near-max state, or an unusually long
90
+ // cookieDomain attribute.
91
+ const cookieOptions = getPKCECookieOptions(config, redirectUri);
92
+ const serialized = serializeCookie(
93
+ PKCE_COOKIE_NAME,
94
+ sealedState,
95
+ cookieOptions,
96
+ );
97
+ const cookieBytes = new TextEncoder().encode(serialized).byteLength;
98
+ if (cookieBytes > PKCE_MAX_COOKIE_BYTES) {
99
+ throw new PKCEPayloadTooLargeError(
100
+ `Sealed PKCE verifier cookie is ${cookieBytes} bytes, exceeds supported limit of ${PKCE_MAX_COOKIE_BYTES} bytes. ` +
101
+ `Reduce the size of options.state, options.returnPathname, or options.redirectUri.`,
102
+ );
103
+ }
104
+
105
+ const url = client.userManagement.getAuthorizationUrl({
106
+ provider: 'authkit',
107
+ clientId: config.clientId,
108
+ redirectUri,
109
+ screenHint: options.screenHint,
110
+ organizationId: options.organizationId,
111
+ loginHint: options.loginHint,
112
+ prompt: options.prompt,
113
+ state: sealedState,
114
+ codeChallenge: pkce.codeChallenge,
115
+ codeChallengeMethod: pkce.codeChallengeMethod,
116
+ });
117
+
118
+ return {
119
+ url,
120
+ sealedState,
121
+ cookieOptions,
122
+ };
123
+ }
@@ -0,0 +1,166 @@
1
+ import { AuthKitCore } from '../AuthKitCore.js';
2
+ import sessionEncryption from '../encryption/ironWebcryptoEncryption.js';
3
+ import {
4
+ OAuthStateMismatchError,
5
+ PKCECookieMissingError,
6
+ PKCEPayloadTooLargeError,
7
+ } from '../errors.js';
8
+ import {
9
+ generateAuthorizationUrl,
10
+ PKCE_MAX_COOKIE_BYTES,
11
+ PKCE_MAX_STATE_BYTES,
12
+ } from './generateAuthorizationUrl.js';
13
+
14
+ const config = {
15
+ clientId: 'test-client-id',
16
+ apiKey: 'test-api-key',
17
+ redirectUri: 'https://app.example.com/callback',
18
+ cookiePassword: 'this-is-a-test-password-that-is-32-characters-long!',
19
+ } as const;
20
+
21
+ const mockClient = {
22
+ pkce: {
23
+ generate: async () => ({
24
+ codeVerifier: 'verifier-' + crypto.randomUUID(),
25
+ codeChallenge: 'challenge-' + crypto.randomUUID(),
26
+ codeChallengeMethod: 'S256',
27
+ }),
28
+ },
29
+ userManagement: {
30
+ getAuthorizationUrl: (opts: any) => {
31
+ const params = new URLSearchParams({
32
+ client_id: opts.clientId,
33
+ redirect_uri: opts.redirectUri,
34
+ state: opts.state ?? '',
35
+ code_challenge: opts.codeChallenge ?? '',
36
+ code_challenge_method: opts.codeChallengeMethod ?? '',
37
+ });
38
+ return `https://api.workos.com/sso/authorize?${params.toString()}`;
39
+ },
40
+ getJwksUrl: () => 'https://api.workos.com/sso/jwks/test-client-id',
41
+ },
42
+ } as const;
43
+
44
+ function makeCore() {
45
+ return new AuthKitCore(config as any, mockClient as any, sessionEncryption);
46
+ }
47
+
48
+ function generate(
49
+ options: Parameters<typeof generateAuthorizationUrl>[0]['options'] = {},
50
+ ) {
51
+ return generateAuthorizationUrl({
52
+ client: mockClient as any,
53
+ config: config as any,
54
+ encryption: sessionEncryption,
55
+ options,
56
+ });
57
+ }
58
+
59
+ // Tamper, missing cookie, missing state, TTL, and single-byte custom-state
60
+ // round-trip are covered in state.spec.ts and AuthKitCore.spec.ts. These
61
+ // tests exercise the integration seam (generateAuthorizationUrl →
62
+ // verifyCallbackState) for behaviors that only emerge when both modules
63
+ // run together.
64
+ describe('PKCE end-to-end round-trip', () => {
65
+ it('verifyCallbackState recovers the sealed state after generateAuthorizationUrl', async () => {
66
+ const core = makeCore();
67
+ const { sealedState } = await generate({
68
+ returnPathname: '/dashboard',
69
+ state: 'user-opaque',
70
+ });
71
+
72
+ const result = await core.verifyCallbackState({
73
+ stateFromUrl: sealedState,
74
+ cookieValue: sealedState,
75
+ });
76
+
77
+ expect(result.returnPathname).toBe('/dashboard');
78
+ expect(result.customState).toBe('user-opaque');
79
+ expect(typeof result.codeVerifier).toBe('string');
80
+ expect(typeof result.nonce).toBe('string');
81
+ });
82
+
83
+ it('empty-string cookieValue is treated as missing (falsy check)', async () => {
84
+ const core = makeCore();
85
+ const { sealedState } = await generate();
86
+
87
+ await expect(
88
+ core.verifyCallbackState({ stateFromUrl: sealedState, cookieValue: '' }),
89
+ ).rejects.toThrow(PKCECookieMissingError);
90
+ });
91
+
92
+ it('concurrent sign-ins produce distinct sealedStates (cross-flow rejection)', async () => {
93
+ const core = makeCore();
94
+ const a = await generate();
95
+ const b = await generate();
96
+
97
+ expect(a.sealedState).not.toBe(b.sealedState);
98
+ await expect(
99
+ core.verifyCallbackState({
100
+ stateFromUrl: a.sealedState,
101
+ cookieValue: b.sealedState,
102
+ }),
103
+ ).rejects.toThrow(OAuthStateMismatchError);
104
+ });
105
+ });
106
+
107
+ describe('PKCE payload size guards', () => {
108
+ it(`accepts custom state at the ${PKCE_MAX_STATE_BYTES}-byte supported limit`, async () => {
109
+ const state = 'a'.repeat(PKCE_MAX_STATE_BYTES);
110
+ await expect(generate({ state })).resolves.toMatchObject({
111
+ sealedState: expect.any(String),
112
+ });
113
+ });
114
+
115
+ it(`rejects custom state ${PKCE_MAX_STATE_BYTES + 1} bytes or larger before sealing`, async () => {
116
+ const state = 'a'.repeat(PKCE_MAX_STATE_BYTES + 1);
117
+ await expect(generate({ state })).rejects.toThrow(PKCEPayloadTooLargeError);
118
+ });
119
+
120
+ it('counts state size in UTF-8 bytes, not JS characters (multibyte input)', async () => {
121
+ // 2-byte UTF-8 char; 1025 chars = 2050 bytes > 2048.
122
+ const state = '\u00e9'.repeat(1025);
123
+ await expect(generate({ state })).rejects.toThrow(PKCEPayloadTooLargeError);
124
+ });
125
+
126
+ it('rejects oversized serialized cookie from large returnPathname + near-limit state', async () => {
127
+ // Under the per-field state cap, but the sealed cookie still overflows
128
+ // once returnPathname is concatenated into the payload.
129
+ const state = 'a'.repeat(PKCE_MAX_STATE_BYTES);
130
+ const returnPathname = '/' + 'p'.repeat(2048);
131
+ await expect(generate({ state, returnPathname })).rejects.toThrow(
132
+ PKCEPayloadTooLargeError,
133
+ );
134
+ });
135
+
136
+ it('shrinks the effective budget when cookieDomain adds attribute bytes', async () => {
137
+ // cookieDomain=<long> is serialized into every Set-Cookie and counts
138
+ // against the browser's per-cookie budget. A state payload that fits
139
+ // without a Domain attribute can push the serialized header over the
140
+ // limit when Domain is present.
141
+ const longDomain = 'sub.' + 'd'.repeat(200) + '.example.com';
142
+ const configWithDomain = { ...config, cookieDomain: longDomain } as any;
143
+
144
+ const state = 'a'.repeat(PKCE_MAX_STATE_BYTES);
145
+ await expect(
146
+ generateAuthorizationUrl({
147
+ client: mockClient as any,
148
+ config: configWithDomain,
149
+ encryption: sessionEncryption,
150
+ options: { state, returnPathname: '/' + 'p'.repeat(700) },
151
+ }),
152
+ ).rejects.toThrow(PKCEPayloadTooLargeError);
153
+ });
154
+
155
+ it(`error message names PKCE_MAX_COOKIE_BYTES (${PKCE_MAX_COOKIE_BYTES})`, async () => {
156
+ const state = 'a'.repeat(PKCE_MAX_STATE_BYTES);
157
+ const returnPathname = '/' + 'p'.repeat(2048);
158
+ try {
159
+ await generate({ state, returnPathname });
160
+ throw new Error('expected throw');
161
+ } catch (err) {
162
+ expect(err).toBeInstanceOf(PKCEPayloadTooLargeError);
163
+ expect((err as Error).message).toContain(String(PKCE_MAX_COOKIE_BYTES));
164
+ }
165
+ });
166
+ });