@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,26 +1,21 @@
1
1
  import type { AuthKitConfig } from '../config/types.js';
2
- import type { HeadersBag, SessionStorage } from './types.js';
2
+ import { serializeCookie } from './serializeCookie.js';
3
+ import type { CookieOptions, HeadersBag, SessionStorage } from './types.js';
3
4
 
4
- export interface CookieOptions {
5
- path?: string;
6
- domain?: string;
7
- maxAge?: number;
8
- expires?: Date;
9
- httpOnly?: boolean;
10
- secure?: boolean;
11
- sameSite?: 'lax' | 'strict' | 'none';
12
- priority?: 'low' | 'medium' | 'high';
13
- partitioned?: boolean;
14
- }
5
+ export type { CookieOptions } from './types.js';
15
6
 
16
- export abstract class CookieSessionStorage<TRequest, TResponse>
17
- implements SessionStorage<TRequest, TResponse>
18
- {
7
+ export abstract class CookieSessionStorage<
8
+ TRequest,
9
+ TResponse,
10
+ > implements SessionStorage<TRequest, TResponse> {
19
11
  protected cookieName: string;
20
12
  protected readonly cookieOptions: CookieOptions;
21
13
 
22
14
  constructor(config: AuthKitConfig) {
23
- this.cookieName = config.cookieName ?? 'wos_session';
15
+ // Matches the canonical default in ConfigurationProvider. This fallback
16
+ // only fires when a caller instantiates the class with a config that
17
+ // hasn't been resolved through the provider.
18
+ this.cookieName = config.cookieName ?? 'wos-session';
24
19
 
25
20
  const sameSite = config.cookieSameSite ?? 'lax';
26
21
 
@@ -53,40 +48,66 @@ export abstract class CookieSessionStorage<TRequest, TResponse>
53
48
  /* default no-op. Adapters can override if they CAN mutate a native response */
54
49
  }
55
50
 
56
- protected buildSetCookie(value: string, expired?: boolean): string {
57
- const a = [`${this.cookieName}=${encodeURIComponent(value)}`];
58
- const o = this.cookieOptions;
59
- if (o.path) a.push(`Path=${o.path}`);
60
- if (o.domain) a.push(`Domain=${o.domain}`);
61
- if (o.maxAge || expired) a.push(`Max-Age=${expired ? 0 : o.maxAge}`);
62
- if (o.httpOnly) a.push('HttpOnly');
63
- if (o.secure) a.push('Secure');
64
- if (o.sameSite) {
65
- const capitalizedSameSite =
66
- o.sameSite.charAt(0).toUpperCase() + o.sameSite.slice(1).toLowerCase();
67
- a.push(`SameSite=${capitalizedSameSite}`);
68
- }
69
- if (o.priority) a.push(`Priority=${o.priority}`);
70
- if (o.partitioned) a.push('Partitioned');
71
- return a.join('; ');
51
+ protected serializeCookie(
52
+ name: string,
53
+ value: string,
54
+ options: CookieOptions,
55
+ flags: { expired?: boolean } = {},
56
+ ): string {
57
+ return serializeCookie(name, value, options, flags);
72
58
  }
73
59
 
74
- abstract getSession(request: TRequest): Promise<string | null>;
60
+ /**
61
+ * Read a named cookie from the framework-specific request.
62
+ *
63
+ * Implementations MUST return the URL-decoded value — the inverse of
64
+ * `serializeCookie`'s `encodeURIComponent` on write. Returning the raw
65
+ * on-wire bytes will silently break byte-comparison against the original
66
+ * value (e.g. PKCE state verification) for any seal containing characters
67
+ * that `encodeURIComponent` escapes.
68
+ */
69
+ abstract getCookie(request: TRequest, name: string): Promise<string | null>;
75
70
 
76
- async saveSession(
71
+ async setCookie(
77
72
  response: TResponse | undefined,
78
- sessionData: string,
73
+ name: string,
74
+ value: string,
75
+ options: CookieOptions,
79
76
  ): Promise<{ response?: TResponse; headers?: HeadersBag }> {
80
- const header = this.buildSetCookie(sessionData);
77
+ const header = this.serializeCookie(name, value, options);
81
78
  const mutated = await this.applyHeaders(response, { 'Set-Cookie': header });
82
79
  return mutated ?? { headers: { 'Set-Cookie': header } };
83
80
  }
84
81
 
85
- async clearSession(
86
- response: TResponse,
82
+ async clearCookie(
83
+ response: TResponse | undefined,
84
+ name: string,
85
+ options: CookieOptions,
87
86
  ): Promise<{ response?: TResponse; headers?: HeadersBag }> {
88
- const header = this.buildSetCookie('', true);
87
+ const header = this.serializeCookie(name, '', options, { expired: true });
89
88
  const mutated = await this.applyHeaders(response, { 'Set-Cookie': header });
90
89
  return mutated ?? { headers: { 'Set-Cookie': header } };
91
90
  }
91
+
92
+ getSession(request: TRequest): Promise<string | null> {
93
+ return this.getCookie(request, this.cookieName);
94
+ }
95
+
96
+ saveSession(
97
+ response: TResponse | undefined,
98
+ sessionData: string,
99
+ ): Promise<{ response?: TResponse; headers?: HeadersBag }> {
100
+ return this.setCookie(
101
+ response,
102
+ this.cookieName,
103
+ sessionData,
104
+ this.cookieOptions,
105
+ );
106
+ }
107
+
108
+ clearSession(
109
+ response: TResponse | undefined,
110
+ ): Promise<{ response?: TResponse; headers?: HeadersBag }> {
111
+ return this.clearCookie(response, this.cookieName, this.cookieOptions);
112
+ }
92
113
  }
@@ -32,8 +32,8 @@ export class TokenManager {
32
32
  ): BaseTokenClaims & TCustomClaims {
33
33
  try {
34
34
  return decodeJwt<BaseTokenClaims & TCustomClaims>(token);
35
- } catch (error) {
36
- throw new Error('Invalid token');
35
+ } catch (cause) {
36
+ throw new Error('Invalid token', { cause });
37
37
  }
38
38
  }
39
39
 
@@ -0,0 +1,33 @@
1
+ import type { CookieOptions } from './types.js';
2
+
3
+ /**
4
+ * Serialize a `Set-Cookie` header value from (name, value, options).
5
+ *
6
+ * Shared between `CookieSessionStorage` (writes the header on response) and
7
+ * the PKCE flow's pre-write size guard (must measure the exact bytes the
8
+ * browser will see, including attribute overhead, to detect oversized
9
+ * verifier cookies before they silently get dropped).
10
+ */
11
+ export function serializeCookie(
12
+ name: string,
13
+ value: string,
14
+ options: CookieOptions,
15
+ { expired }: { expired?: boolean } = {},
16
+ ): string {
17
+ const parts = [`${name}=${encodeURIComponent(value)}`];
18
+ if (options.path) parts.push(`Path=${options.path}`);
19
+ if (options.domain) parts.push(`Domain=${options.domain}`);
20
+ if (options.maxAge != null || expired)
21
+ parts.push(`Max-Age=${expired ? 0 : options.maxAge}`);
22
+ if (options.httpOnly) parts.push('HttpOnly');
23
+ if (options.secure) parts.push('Secure');
24
+ if (options.sameSite) {
25
+ const capitalized =
26
+ options.sameSite.charAt(0).toUpperCase() +
27
+ options.sameSite.slice(1).toLowerCase();
28
+ parts.push(`SameSite=${capitalized}`);
29
+ }
30
+ if (options.priority) parts.push(`Priority=${options.priority}`);
31
+ if (options.partitioned) parts.push('Partitioned');
32
+ return parts.join('; ');
33
+ }
@@ -72,9 +72,57 @@ export interface Session {
72
72
  impersonator?: Impersonator;
73
73
  }
74
74
 
75
+ /**
76
+ * Map of HTTP response headers.
77
+ *
78
+ * `Set-Cookie` MUST be represented as `string[]` when multiple values exist
79
+ * — adapters must append each entry as its own header, never comma-join.
80
+ * A comma-joined `Set-Cookie` string is not a valid single HTTP header.
81
+ */
75
82
  export type HeadersBag = Record<string, string | string[]>;
76
83
 
77
84
  export interface SessionStorage<TRequest, TResponse, TOptions = unknown> {
85
+ /**
86
+ * Read a named cookie from a request.
87
+ *
88
+ * MUST return the URL-decoded value (the inverse of `setCookie`'s
89
+ * `encodeURIComponent` on write). Returning raw on-wire bytes will break
90
+ * byte-comparison against the original value — notably PKCE state
91
+ * verification — for any seal format that contains characters
92
+ * `encodeURIComponent` escapes (`+`, `=`, etc.).
93
+ *
94
+ * @param request Framework-specific request object.
95
+ * @param name Cookie name.
96
+ * @returns The URL-decoded cookie value or null if absent.
97
+ */
98
+ getCookie(request: TRequest, name: string): Promise<string | null>;
99
+
100
+ /**
101
+ * Write a named cookie to a response.
102
+ * @param response Framework-specific response object (or undefined to emit headers only).
103
+ * @param name Cookie name.
104
+ * @param value Cookie value (will be URL-encoded).
105
+ * @param options Per-call cookie options.
106
+ */
107
+ setCookie(
108
+ response: TResponse | undefined,
109
+ name: string,
110
+ value: string,
111
+ options: CookieOptions,
112
+ ): Promise<{ response?: TResponse; headers?: HeadersBag }>;
113
+
114
+ /**
115
+ * Clear a named cookie by emitting a Set-Cookie with Max-Age=0.
116
+ * @param response Framework-specific response object (or undefined to emit headers only).
117
+ * @param name Cookie name.
118
+ * @param options Cookie options (must match those used at set time, especially `path`).
119
+ */
120
+ clearCookie(
121
+ response: TResponse | undefined,
122
+ name: string,
123
+ options: CookieOptions,
124
+ ): Promise<{ response?: TResponse; headers?: HeadersBag }>;
125
+
78
126
  /*
79
127
  * Extract session data from a request object
80
128
  * @param request the framework-specific request object.
@@ -117,10 +165,26 @@ export interface SessionEncryption {
117
165
  encryptedData: string,
118
166
  options: {
119
167
  password: string;
168
+ ttl?: number | undefined;
120
169
  },
121
170
  ) => Promise<T>;
122
171
  }
123
172
 
173
+ /**
174
+ * Result shape returned by `createAuthorization` / `createSignIn` / `createSignUp`.
175
+ *
176
+ * The verifier cookie is written internally via `SessionStorage.setCookie` — callers
177
+ * only need to redirect the browser to `url` and apply any returned `headers`/`response`.
178
+ */
179
+ export interface GetAuthorizationUrlResult {
180
+ url: string;
181
+ }
182
+
183
+ export type CreateAuthorizationResult<TResponse> = GetAuthorizationUrlResult & {
184
+ response?: TResponse;
185
+ headers?: HeadersBag;
186
+ };
187
+
124
188
  export interface CookieOptions {
125
189
  path?: string;
126
190
  domain?: string;
@@ -142,12 +206,25 @@ export interface AuthUrlOptions {
142
206
  organizationId?: string;
143
207
  loginHint?: string;
144
208
  prompt?: 'login' | 'none' | 'consent' | 'select_account';
145
- /** Custom state to pass through the OAuth flow. Returned in handleCallback. */
209
+ /**
210
+ * Custom state to pass through the OAuth flow. Returned in handleCallback.
211
+ *
212
+ * Bounded at 2048 UTF-8 bytes. The value is sealed alongside the PKCE
213
+ * verifier and stored in the `wos-auth-verifier` cookie; oversized values
214
+ * would push the cookie past the per-cookie browser limit (~4 KB) and
215
+ * would be silently dropped. Values over the supported limit throw
216
+ * `PKCEPayloadTooLargeError` at sign-in time.
217
+ *
218
+ * Note: total sealed payload size — not just `state` — drives the hard
219
+ * failure. Combining a large `returnPathname`, `redirectUri`, or
220
+ * `cookieDomain` with near-limit `state` can still overflow.
221
+ */
146
222
  state?: string;
147
223
  }
148
224
 
149
225
  /**
150
- * Options for getAuthorizationUrl, including screenHint
226
+ * Options for `createAuthorization` / `createSignIn` / `createSignUp`,
227
+ * including the `screenHint` selector used by the sign-in/sign-up variants.
151
228
  */
152
229
  export interface GetAuthorizationUrlOptions extends AuthUrlOptions {
153
230
  screenHint?: 'sign-up' | 'sign-in';
package/src/index.ts CHANGED
@@ -63,6 +63,9 @@ export { getWorkOS } from './core/client/workos.js';
63
63
  // ============================================
64
64
  export {
65
65
  AuthKitError,
66
+ OAuthStateMismatchError,
67
+ PKCECookieMissingError,
68
+ PKCEPayloadTooLargeError,
66
69
  SessionEncryptionError,
67
70
  TokenValidationError,
68
71
  TokenRefreshError,
@@ -1,10 +1,13 @@
1
+ import sessionEncryption from '../core/encryption/ironWebcryptoEncryption.js';
2
+ import { unsealState } from '../core/pkce/state.js';
1
3
  import { AuthOperations } from './AuthOperations.js';
2
4
 
3
5
  const mockConfig = {
4
6
  clientId: 'test-client-id',
5
7
  redirectUri: 'http://localhost:3000/callback',
6
8
  cookieName: 'wos-session',
7
- };
9
+ cookiePassword: 'this-is-a-test-password-that-is-32-characters-long!',
10
+ } as const;
8
11
 
9
12
  const mockUser = {
10
13
  id: 'user_123',
@@ -42,23 +45,45 @@ const mockCore = {
42
45
  encryptSession: async () => 'encrypted-session-data',
43
46
  };
44
47
 
45
- const mockClient = {
46
- userManagement: {
47
- getLogoutUrl: ({ sessionId, returnTo }: any) =>
48
- `https://api.workos.com/sso/logout?session_id=${sessionId}&return_to=${returnTo || ''}`,
49
- getAuthorizationUrl: ({ clientId, redirectUri, screenHint, state }: any) =>
50
- `https://api.workos.com/sso/authorize?client_id=${clientId}&redirect_uri=${encodeURIComponent(redirectUri)}&screen_hint=${screenHint || ''}&state=${state || ''}`,
51
- },
52
- };
48
+ function makeAuthUrlClient(capture?: { last?: Record<string, unknown> }) {
49
+ return {
50
+ pkce: {
51
+ generate: async () => ({
52
+ codeVerifier: 'generated-verifier-1234567890abcdef',
53
+ codeChallenge: 'generated-challenge',
54
+ codeChallengeMethod: 'S256',
55
+ }),
56
+ },
57
+ userManagement: {
58
+ getLogoutUrl: ({ sessionId, returnTo }: any) =>
59
+ `https://api.workos.com/sso/logout?session_id=${sessionId}&return_to=${returnTo || ''}`,
60
+ getAuthorizationUrl: (opts: any) => {
61
+ if (capture) capture.last = opts;
62
+ const params = new URLSearchParams({
63
+ client_id: opts.clientId,
64
+ redirect_uri: opts.redirectUri,
65
+ state: opts.state ?? '',
66
+ screen_hint: opts.screenHint ?? '',
67
+ code_challenge: opts.codeChallenge ?? '',
68
+ code_challenge_method: opts.codeChallengeMethod ?? '',
69
+ });
70
+ return `https://api.workos.com/sso/authorize?${params.toString()}`;
71
+ },
72
+ },
73
+ };
74
+ }
53
75
 
54
76
  describe('AuthOperations', () => {
55
77
  let operations: AuthOperations;
78
+ let capture: { last?: Record<string, unknown> };
56
79
 
57
80
  beforeEach(() => {
81
+ capture = {};
58
82
  operations = new AuthOperations(
59
83
  mockCore as any,
60
- mockClient as any,
84
+ makeAuthUrlClient(capture) as any,
61
85
  mockConfig as any,
86
+ sessionEncryption,
62
87
  );
63
88
  });
64
89
 
@@ -148,8 +173,9 @@ describe('AuthOperations', () => {
148
173
  };
149
174
  const testOps = new AuthOperations(
150
175
  coreWithSpy as any,
151
- mockClient as any,
176
+ makeAuthUrlClient() as any,
152
177
  mockConfig as any,
178
+ sessionEncryption,
153
179
  );
154
180
 
155
181
  const session = {
@@ -193,8 +219,9 @@ describe('AuthOperations', () => {
193
219
  };
194
220
  const testOps = new AuthOperations(
195
221
  coreWithSpy as any,
196
- mockClient as any,
222
+ makeAuthUrlClient() as any,
197
223
  mockConfig as any,
224
+ sessionEncryption,
198
225
  );
199
226
 
200
227
  const session = {
@@ -213,87 +240,105 @@ describe('AuthOperations', () => {
213
240
  });
214
241
  });
215
242
 
216
- describe('getAuthorizationUrl()', () => {
217
- it('returns WorkOS authorization URL', async () => {
218
- const result = await operations.getAuthorizationUrl();
243
+ describe('createAuthorization()', () => {
244
+ it('returns url + sealedState + cookieOptions for storage dispatch', async () => {
245
+ const result = await operations.createAuthorization();
219
246
 
220
- expect(result).toContain('client_id=test-client-id');
221
- expect(result).toContain('redirect_uri');
247
+ expect(typeof result.url).toBe('string');
248
+ expect(typeof result.sealedState).toBe('string');
249
+ expect(result.sealedState.length).toBeGreaterThan(0);
250
+ expect(result.cookieOptions.maxAge).toBe(600);
251
+ expect(result.cookieOptions.path).toBe('/');
252
+ expect(result.url).toContain('client_id=test-client-id');
222
253
  });
223
254
 
224
- it('encodes returnPathname in URL-safe base64 state', async () => {
225
- const result = await operations.getAuthorizationUrl({
226
- returnPathname: '/dashboard',
227
- });
255
+ it('passes the sealedState as the URL state param (identical string)', async () => {
256
+ const result = await operations.createAuthorization();
257
+ const urlState = decodeURIComponent(
258
+ new URL(result.url).searchParams.get('state') ?? '',
259
+ );
260
+
261
+ expect(urlState).toBe(result.sealedState);
262
+ });
228
263
 
229
- expect(result).toContain('state=');
230
- const stateMatch = result.match(/state=([^&]+)/);
231
- expect(stateMatch).toBeTruthy();
264
+ it('includes codeChallenge + codeChallengeMethod in WorkOS URL', async () => {
265
+ await operations.createAuthorization();
232
266
 
233
- // Decode URL-safe base64: reverse - to +, _ to /
234
- const urlSafeState = stateMatch![1]!;
235
- const standardBase64 = urlSafeState.replace(/-/g, '+').replace(/_/g, '/');
236
- const decoded = JSON.parse(atob(standardBase64));
237
- expect(decoded.returnPathname).toBe('/dashboard');
267
+ expect(capture.last?.codeChallenge).toBe('generated-challenge');
268
+ expect(capture.last?.codeChallengeMethod).toBe('S256');
238
269
  });
239
270
 
240
- it('combines internal state with custom user state', async () => {
241
- const result = await operations.getAuthorizationUrl({
242
- returnPathname: '/profile',
243
- state: 'my-custom-state',
271
+ it('seals returnPathname into the state blob', async () => {
272
+ const result = await operations.createAuthorization({
273
+ returnPathname: '/dashboard',
244
274
  });
275
+ const unsealed = await unsealState(
276
+ sessionEncryption,
277
+ mockConfig.cookiePassword,
278
+ result.sealedState,
279
+ );
245
280
 
246
- expect(result).toContain('state=');
247
- const stateMatch = result.match(/state=([^&]+)/);
248
- expect(stateMatch).toBeTruthy();
281
+ expect(unsealed.returnPathname).toBe('/dashboard');
282
+ expect(unsealed.codeVerifier).toBe('generated-verifier-1234567890abcdef');
283
+ });
249
284
 
250
- // State should be in format: internal.userState
251
- const fullState = stateMatch![1]!;
252
- expect(fullState).toContain('.');
253
- const [internal, userState] = fullState.split('.');
254
- expect(userState).toBe('my-custom-state');
285
+ it('seals customState into the state blob', async () => {
286
+ const result = await operations.createAuthorization({
287
+ state: 'my-custom-state',
288
+ });
289
+ const unsealed = await unsealState(
290
+ sessionEncryption,
291
+ mockConfig.cookiePassword,
292
+ result.sealedState,
293
+ );
255
294
 
256
- // Decode internal part
257
- const standardBase64 = internal!.replace(/-/g, '+').replace(/_/g, '/');
258
- const decoded = JSON.parse(atob(standardBase64));
259
- expect(decoded.returnPathname).toBe('/profile');
295
+ expect(unsealed.customState).toBe('my-custom-state');
260
296
  });
261
297
 
262
- it('passes custom state as-is when no returnPathname', async () => {
263
- const result = await operations.getAuthorizationUrl({
264
- state: 'only-user-state',
298
+ it('seals both returnPathname and customState together', async () => {
299
+ const result = await operations.createAuthorization({
300
+ returnPathname: '/profile',
301
+ state: 'custom',
265
302
  });
303
+ const unsealed = await unsealState(
304
+ sessionEncryption,
305
+ mockConfig.cookiePassword,
306
+ result.sealedState,
307
+ );
266
308
 
267
- expect(result).toContain('state=');
268
- const stateMatch = result.match(/state=([^&]+)/);
269
- expect(stateMatch).toBeTruthy();
270
-
271
- // State should be passed through directly without internal wrapper
272
- expect(stateMatch![1]).toBe('only-user-state');
309
+ expect(unsealed.returnPathname).toBe('/profile');
310
+ expect(unsealed.customState).toBe('custom');
273
311
  });
274
312
 
275
313
  it('includes screenHint when provided', async () => {
276
- const result = await operations.getAuthorizationUrl({
314
+ const result = await operations.createAuthorization({
277
315
  screenHint: 'sign-up',
278
316
  });
279
317
 
280
- expect(result).toContain('screen_hint=sign-up');
318
+ expect(result.url).toContain('screen_hint=sign-up');
319
+ });
320
+
321
+ it('generates a unique nonce per call (concurrent last-flow-wins)', async () => {
322
+ const a = await operations.createAuthorization();
323
+ const b = await operations.createAuthorization();
324
+
325
+ expect(a.sealedState).not.toBe(b.sealedState);
281
326
  });
282
327
  });
283
328
 
284
- describe('getSignInUrl()', () => {
329
+ describe('createSignIn()', () => {
285
330
  it('returns authorization URL with sign-in hint', async () => {
286
- const result = await operations.getSignInUrl();
331
+ const result = await operations.createSignIn();
287
332
 
288
- expect(result).toContain('screen_hint=sign-in');
333
+ expect(result.url).toContain('screen_hint=sign-in');
289
334
  });
290
335
  });
291
336
 
292
- describe('getSignUpUrl()', () => {
337
+ describe('createSignUp()', () => {
293
338
  it('returns authorization URL with sign-up hint', async () => {
294
- const result = await operations.getSignUpUrl();
339
+ const result = await operations.createSignUp();
295
340
 
296
- expect(result).toContain('screen_hint=sign-up');
341
+ expect(result.url).toContain('screen_hint=sign-up');
297
342
  });
298
343
  });
299
344
  });
@@ -1,10 +1,15 @@
1
1
  import type { WorkOS } from '@workos-inc/node';
2
2
  import type { AuthKitCore } from '../core/AuthKitCore.js';
3
3
  import type { AuthKitConfig } from '../core/config/types.js';
4
+ import {
5
+ type GeneratedAuthorizationUrl,
6
+ generateAuthorizationUrl,
7
+ } from '../core/pkce/generateAuthorizationUrl.js';
4
8
  import type {
5
9
  AuthResult,
6
10
  GetAuthorizationUrlOptions,
7
11
  Session,
12
+ SessionEncryption,
8
13
  } from '../core/session/types.js';
9
14
 
10
15
  /**
@@ -23,11 +28,18 @@ export class AuthOperations {
23
28
  private core: AuthKitCore;
24
29
  private client: WorkOS;
25
30
  private config: AuthKitConfig;
31
+ private encryption: SessionEncryption;
26
32
 
27
- constructor(core: AuthKitCore, client: WorkOS, config: AuthKitConfig) {
33
+ constructor(
34
+ core: AuthKitCore,
35
+ client: WorkOS,
36
+ config: AuthKitConfig,
37
+ encryption: SessionEncryption,
38
+ ) {
28
39
  this.core = core;
29
40
  this.client = client;
30
41
  this.config = config;
42
+ this.encryption = encryption;
31
43
  }
32
44
 
33
45
  /**
@@ -115,63 +127,45 @@ export class AuthOperations {
115
127
  }
116
128
 
117
129
  /**
118
- * Get authorization URL for WorkOS authentication.
130
+ * Create a PKCE-bound WorkOS authorization URL.
119
131
  *
120
- * State encoding format: `{internal}.{userState}` where internal is URL-safe
121
- * base64 encoded JSON containing returnPathname. This allows customers to
122
- * pass their own state through the OAuth flow.
132
+ * Returns the URL, the sealed state blob (to be used as both the cookie
133
+ * value and — already present in the URL — the OAuth `state` param), and
134
+ * the cookie options the verifier cookie should be written with.
135
+ * AuthService dispatches the write via `SessionStorage.setCookie`.
123
136
  *
124
- * @param options - Authorization URL options (returnPathname, screenHint, state, etc.)
125
- * @returns The authorization URL
137
+ * @param options - returnPathname, screenHint, custom state, redirectUri, etc.
126
138
  */
127
- async getAuthorizationUrl(
139
+ async createAuthorization(
128
140
  options: GetAuthorizationUrlOptions = {},
129
- ): Promise<string> {
130
- // Build the combined state parameter (matches authkit-nextjs format)
131
- const internalState = options.returnPathname
132
- ? btoa(JSON.stringify({ returnPathname: options.returnPathname }))
133
- .replace(/\+/g, '-')
134
- .replace(/\//g, '_')
135
- : null;
136
-
137
- // If both internal and custom state, combine as internal.custom
138
- // Otherwise use whichever is provided
139
- const state =
140
- internalState && options.state
141
- ? `${internalState}.${options.state}`
142
- : internalState || options.state || undefined;
143
-
144
- return this.client.userManagement.getAuthorizationUrl({
145
- provider: 'authkit',
146
- redirectUri: options.redirectUri ?? this.config.redirectUri,
147
- screenHint: options.screenHint,
148
- organizationId: options.organizationId,
149
- loginHint: options.loginHint,
150
- prompt: options.prompt,
151
- clientId: this.config.clientId,
152
- state,
141
+ ): Promise<GeneratedAuthorizationUrl> {
142
+ return generateAuthorizationUrl({
143
+ client: this.client,
144
+ config: this.config,
145
+ encryption: this.encryption,
146
+ options,
153
147
  });
154
148
  }
155
149
 
156
150
  /**
157
- * Convenience method: Get sign-in URL.
151
+ * Convenience method: Create sign-in authorization URL.
158
152
  */
159
- async getSignInUrl(
153
+ async createSignIn(
160
154
  options: Omit<GetAuthorizationUrlOptions, 'screenHint'> = {},
161
- ): Promise<string> {
162
- return this.getAuthorizationUrl({
155
+ ): Promise<GeneratedAuthorizationUrl> {
156
+ return this.createAuthorization({
163
157
  ...options,
164
158
  screenHint: 'sign-in',
165
159
  });
166
160
  }
167
161
 
168
162
  /**
169
- * Convenience method: Get sign-up URL.
163
+ * Convenience method: Create sign-up authorization URL.
170
164
  */
171
- async getSignUpUrl(
165
+ async createSignUp(
172
166
  options: Omit<GetAuthorizationUrlOptions, 'screenHint'> = {},
173
- ): Promise<string> {
174
- return this.getAuthorizationUrl({
167
+ ): Promise<GeneratedAuthorizationUrl> {
168
+ return this.createAuthorization({
175
169
  ...options,
176
170
  screenHint: 'sign-up',
177
171
  });