@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,100 +1,29 @@
1
1
  import {
2
2
  AuthKitError,
3
+ OAuthStateMismatchError,
4
+ PKCECookieMissingError,
5
+ PKCEPayloadTooLargeError,
3
6
  SessionEncryptionError,
4
7
  TokenValidationError,
5
8
  TokenRefreshError,
6
9
  } from './errors.js';
7
10
 
8
11
  describe('AuthKitError', () => {
9
- it('creates error with message', () => {
10
- const error = new AuthKitError('Test error');
11
-
12
- expect(error.message).toBe('Test error');
13
- expect(error.name).toBe('AuthKitError');
14
- expect(error).toBeInstanceOf(Error);
15
- });
16
-
17
- it('creates error with cause', () => {
18
- const originalError = new Error('Original error');
19
- const error = new AuthKitError('Test error', originalError);
20
-
21
- expect(error.cause).toBe(originalError);
22
- });
23
-
24
- it('creates error with data', () => {
25
- const data = { userId: '123', action: 'login' };
26
- const error = new AuthKitError('Test error', undefined, data);
27
-
28
- expect(error.data).toEqual(data);
29
- });
30
-
31
- it('creates error with cause and data', () => {
32
- const originalError = new Error('Original error');
12
+ it('carries message, cause, and arbitrary data', () => {
13
+ const cause = new Error('Original');
33
14
  const data = { userId: '123' };
34
- const error = new AuthKitError('Test error', originalError, data);
15
+ const error = new AuthKitError('Test', cause, data);
35
16
 
36
- expect(error.cause).toBe(originalError);
17
+ expect(error.message).toBe('Test');
18
+ expect(error.name).toBe('AuthKitError');
19
+ expect(error.cause).toBe(cause);
37
20
  expect(error.data).toEqual(data);
38
- });
39
- });
40
-
41
- describe('SessionEncryptionError', () => {
42
- it('creates error with correct name', () => {
43
- const error = new SessionEncryptionError('Encryption failed');
44
-
45
- expect(error.name).toBe('SessionEncryptionError');
46
- expect(error.message).toBe('Encryption failed');
47
- expect(error).toBeInstanceOf(AuthKitError);
48
21
  expect(error).toBeInstanceOf(Error);
49
22
  });
50
-
51
- it('creates error with cause', () => {
52
- const originalError = new Error('Crypto error');
53
- const error = new SessionEncryptionError(
54
- 'Encryption failed',
55
- originalError,
56
- );
57
-
58
- expect(error.cause).toBe(originalError);
59
- });
60
23
  });
61
24
 
62
- describe('TokenValidationError', () => {
63
- it('creates error with correct name', () => {
64
- const error = new TokenValidationError('Token invalid');
65
-
66
- expect(error.name).toBe('TokenValidationError');
67
- expect(error.message).toBe('Token invalid');
68
- expect(error).toBeInstanceOf(AuthKitError);
69
- expect(error).toBeInstanceOf(Error);
70
- });
71
-
72
- it('creates error with cause', () => {
73
- const originalError = new Error('JWT malformed');
74
- const error = new TokenValidationError('Token invalid', originalError);
75
-
76
- expect(error.cause).toBe(originalError);
77
- });
78
- });
79
-
80
- describe('TokenRefreshError', () => {
81
- it('creates error with correct name', () => {
82
- const error = new TokenRefreshError('Refresh failed');
83
-
84
- expect(error.name).toBe('TokenRefreshError');
85
- expect(error.message).toBe('Refresh failed');
86
- expect(error).toBeInstanceOf(AuthKitError);
87
- expect(error).toBeInstanceOf(Error);
88
- });
89
-
90
- it('creates error with cause', () => {
91
- const originalError = new Error('Network error');
92
- const error = new TokenRefreshError('Refresh failed', originalError);
93
-
94
- expect(error.cause).toBe(originalError);
95
- });
96
-
97
- it('creates error with userId and sessionId', () => {
25
+ describe('TokenRefreshError context', () => {
26
+ it('captures optional userId and sessionId', () => {
98
27
  const error = new TokenRefreshError('Refresh failed', undefined, {
99
28
  userId: 'user_123',
100
29
  sessionId: 'session_456',
@@ -104,37 +33,7 @@ describe('TokenRefreshError', () => {
104
33
  expect(error.sessionId).toBe('session_456');
105
34
  });
106
35
 
107
- it('creates error with cause and context', () => {
108
- const originalError = new Error('Network error');
109
- const error = new TokenRefreshError('Refresh failed', originalError, {
110
- userId: 'user_123',
111
- sessionId: 'session_456',
112
- });
113
-
114
- expect(error.cause).toBe(originalError);
115
- expect(error.userId).toBe('user_123');
116
- expect(error.sessionId).toBe('session_456');
117
- });
118
-
119
- it('creates error with partial context (userId only)', () => {
120
- const error = new TokenRefreshError('Refresh failed', undefined, {
121
- userId: 'user_123',
122
- });
123
-
124
- expect(error.userId).toBe('user_123');
125
- expect(error.sessionId).toBeUndefined();
126
- });
127
-
128
- it('creates error with partial context (sessionId only)', () => {
129
- const error = new TokenRefreshError('Refresh failed', undefined, {
130
- sessionId: 'session_456',
131
- });
132
-
133
- expect(error.userId).toBeUndefined();
134
- expect(error.sessionId).toBe('session_456');
135
- });
136
-
137
- it('has undefined properties when no context provided', () => {
36
+ it('leaves context fields undefined when omitted', () => {
138
37
  const error = new TokenRefreshError('Refresh failed');
139
38
 
140
39
  expect(error.userId).toBeUndefined();
@@ -142,36 +41,28 @@ describe('TokenRefreshError', () => {
142
41
  });
143
42
  });
144
43
 
145
- describe('error inheritance', () => {
146
- it('maintains proper inheritance chain', () => {
147
- const sessionError = new SessionEncryptionError('test');
148
- const tokenError = new TokenValidationError('test');
149
- const refreshError = new TokenRefreshError('test');
150
-
151
- expect(sessionError).toBeInstanceOf(SessionEncryptionError);
152
- expect(sessionError).toBeInstanceOf(AuthKitError);
153
- expect(sessionError).toBeInstanceOf(Error);
154
-
155
- expect(tokenError).toBeInstanceOf(TokenValidationError);
156
- expect(tokenError).toBeInstanceOf(AuthKitError);
157
- expect(tokenError).toBeInstanceOf(Error);
158
-
159
- expect(refreshError).toBeInstanceOf(TokenRefreshError);
160
- expect(refreshError).toBeInstanceOf(AuthKitError);
161
- expect(refreshError).toBeInstanceOf(Error);
162
- });
163
-
164
- it('can be caught as AuthKitError', () => {
165
- const errors = [
166
- new SessionEncryptionError('test'),
167
- new TokenValidationError('test'),
168
- new TokenRefreshError('test'),
169
- ];
170
-
171
- errors.forEach(error => {
44
+ describe('error subclasses', () => {
45
+ const cases: Array<[string, new (msg: string) => AuthKitError]> = [
46
+ ['SessionEncryptionError', SessionEncryptionError],
47
+ ['TokenValidationError', TokenValidationError],
48
+ ['TokenRefreshError', TokenRefreshError],
49
+ ['OAuthStateMismatchError', OAuthStateMismatchError],
50
+ ['PKCECookieMissingError', PKCECookieMissingError],
51
+ ['PKCEPayloadTooLargeError', PKCEPayloadTooLargeError],
52
+ ];
53
+
54
+ it.each(cases)(
55
+ '%s preserves name, message, and AuthKitError inheritance',
56
+ (name, Ctor) => {
57
+ const error = new Ctor('msg');
58
+
59
+ expect(error.name).toBe(name);
60
+ expect(error.message).toBe('msg');
61
+ expect(error).toBeInstanceOf(Ctor);
62
+ expect(error).toBeInstanceOf(AuthKitError);
172
63
  expect(() => {
173
64
  throw error;
174
65
  }).toThrow(AuthKitError);
175
- });
176
- });
66
+ },
67
+ );
177
68
  });
@@ -23,6 +23,27 @@ export class TokenValidationError extends AuthKitError {
23
23
  }
24
24
  }
25
25
 
26
+ export class OAuthStateMismatchError extends AuthKitError {
27
+ constructor(message: string, cause?: unknown) {
28
+ super(message, cause);
29
+ this.name = 'OAuthStateMismatchError';
30
+ }
31
+ }
32
+
33
+ export class PKCECookieMissingError extends AuthKitError {
34
+ constructor(message: string, cause?: unknown) {
35
+ super(message, cause);
36
+ this.name = 'PKCECookieMissingError';
37
+ }
38
+ }
39
+
40
+ export class PKCEPayloadTooLargeError extends AuthKitError {
41
+ constructor(message: string, cause?: unknown) {
42
+ super(message, cause);
43
+ this.name = 'PKCEPayloadTooLargeError';
44
+ }
45
+ }
46
+
26
47
  export class TokenRefreshError extends AuthKitError {
27
48
  readonly userId?: string;
28
49
  readonly sessionId?: string;
@@ -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
+ }