@workos/authkit-session 0.7.1 → 0.8.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.
@@ -1,5 +1,10 @@
1
1
  import { vi } from 'vitest';
2
2
  import { ConfigurationProvider } from './ConfigurationProvider.js';
3
+ import type {
4
+ AuthKitConfidentialConfig,
5
+ AuthKitConfig,
6
+ AuthKitPublicConfig,
7
+ } from './types.js';
3
8
 
4
9
  describe('ConfigurationProvider', () => {
5
10
  let provider: ConfigurationProvider;
@@ -91,6 +96,12 @@ describe('ConfigurationProvider', () => {
91
96
  expect(provider['getEnvironmentVariableName']('cookieMaxAge')).toBe(
92
97
  'WORKOS_COOKIE_MAX_AGE',
93
98
  );
99
+ expect(provider['getEnvironmentVariableName']('cookieDomain')).toBe(
100
+ 'WORKOS_COOKIE_DOMAIN',
101
+ );
102
+ expect(provider['getEnvironmentVariableName']('cookieSameSite')).toBe(
103
+ 'WORKOS_COOKIE_SAME_SITE',
104
+ );
94
105
  });
95
106
  });
96
107
 
@@ -118,6 +129,28 @@ describe('ConfigurationProvider', () => {
118
129
  const config = provider.getConfig();
119
130
  expect(config.cookieName).toBe('test-cookie');
120
131
  });
132
+
133
+ it('reads optional env vars that have no defaults without configure()', () => {
134
+ const validPassword = 'a'.repeat(32);
135
+ const source = vi.fn((key: string) => {
136
+ if (key === 'WORKOS_CLIENT_ID') return 'env-client';
137
+ if (key === 'WORKOS_API_KEY') return 'env-api-key';
138
+ if (key === 'WORKOS_REDIRECT_URI')
139
+ return 'http://localhost:3000/callback';
140
+ if (key === 'WORKOS_COOKIE_PASSWORD') return validPassword;
141
+ if (key === 'WORKOS_COOKIE_DOMAIN') return '.example.com';
142
+ if (key === 'WORKOS_COOKIE_SAME_SITE') return 'strict';
143
+ if (key === 'WORKOS_API_PORT') return '8443';
144
+ return undefined;
145
+ });
146
+
147
+ provider.configure(source);
148
+
149
+ const config = provider.getConfig();
150
+ expect(config.cookieDomain).toBe('.example.com');
151
+ expect(config.cookieSameSite).toBe('strict');
152
+ expect(config.apiPort).toBe(8443);
153
+ });
121
154
  });
122
155
 
123
156
  describe('validate()', () => {
@@ -135,7 +168,7 @@ describe('ConfigurationProvider', () => {
135
168
 
136
169
  it('throws with all missing required fields at once', () => {
137
170
  expect(() => provider.validate()).toThrow(
138
- /AuthKit configuration error\. Missing or invalid environment variables:\n\n • WORKOS_CLIENT_ID is required\n • WORKOS_API_KEY is required\n • WORKOS_REDIRECT_URI is required\n • WORKOS_COOKIE_PASSWORD is required/,
171
+ /AuthKit configuration error\. Missing or invalid environment variables:\n\n • WORKOS_CLIENT_ID is required\n • WORKOS_REDIRECT_URI is required\n • WORKOS_COOKIE_PASSWORD is required/,
139
172
  );
140
173
  });
141
174
 
@@ -178,7 +211,7 @@ describe('ConfigurationProvider', () => {
178
211
  });
179
212
 
180
213
  const error = () => provider.validate();
181
- expect(error).toThrow(/WORKOS_API_KEY is required/);
214
+ expect(error).not.toThrow(/WORKOS_API_KEY/);
182
215
  expect(error).toThrow(/WORKOS_REDIRECT_URI is required/);
183
216
  expect(error).toThrow(
184
217
  /WORKOS_COOKIE_PASSWORD must be at least 32 characters/,
@@ -199,4 +232,158 @@ describe('ConfigurationProvider', () => {
199
232
  expect(() => provider.validate()).not.toThrow();
200
233
  });
201
234
  });
235
+
236
+ describe('public client (no API key)', () => {
237
+ const publicEnv: Record<string, string> = {
238
+ WORKOS_CLIENT_ID: 'client_public',
239
+ WORKOS_REDIRECT_URI: 'http://localhost:3000/callback',
240
+ WORKOS_COOKIE_PASSWORD: 'a'.repeat(32),
241
+ };
242
+ let savedApiKey: string | undefined;
243
+
244
+ beforeEach(() => {
245
+ // Make sure a key in the test runner's environment can't leak in.
246
+ savedApiKey = process.env.WORKOS_API_KEY;
247
+ delete process.env.WORKOS_API_KEY;
248
+ });
249
+
250
+ afterEach(() => {
251
+ if (savedApiKey !== undefined) process.env.WORKOS_API_KEY = savedApiKey;
252
+ });
253
+
254
+ it('resolves apiKey to undefined instead of throwing', () => {
255
+ expect(provider.getValue('apiKey')).toBeUndefined();
256
+ });
257
+
258
+ it('validates without an apiKey', () => {
259
+ provider.setValueSource(publicEnv);
260
+
261
+ expect(() => provider.validate()).not.toThrow();
262
+ });
263
+
264
+ it('builds a full config from an env-only value source', () => {
265
+ provider.setValueSource(publicEnv);
266
+
267
+ const config = provider.getConfig();
268
+ expect(config).not.toHaveProperty('apiKey');
269
+ expect(config).toMatchObject({
270
+ clientId: 'client_public',
271
+ redirectUri: 'http://localhost:3000/callback',
272
+ cookiePassword: publicEnv.WORKOS_COOKIE_PASSWORD,
273
+ });
274
+ });
275
+
276
+ it('builds a full config from process.env with no WORKOS_API_KEY', () => {
277
+ const fresh = new ConfigurationProvider(); // default process.env source
278
+ const saved = { ...process.env };
279
+ Object.assign(process.env, publicEnv);
280
+ try {
281
+ expect(() => fresh.validate()).not.toThrow();
282
+ const config = fresh.getConfig();
283
+ expect(config.apiKey).toBeUndefined();
284
+ expect(config.clientId).toBe('client_public');
285
+ } finally {
286
+ for (const key of Object.keys(publicEnv)) {
287
+ if (saved[key] === undefined) delete process.env[key];
288
+ else process.env[key] = saved[key];
289
+ }
290
+ }
291
+ });
292
+
293
+ it('accepts a programmatic config without apiKey', () => {
294
+ provider.configure({
295
+ clientId: 'client_public',
296
+ redirectUri: 'http://localhost:3000/callback',
297
+ cookiePassword: 'a'.repeat(32),
298
+ });
299
+
300
+ expect(() => provider.validate()).not.toThrow();
301
+ expect(provider.getConfig().apiKey).toBeUndefined();
302
+ });
303
+
304
+ it('still reads apiKey from an env-only source (confidential mode)', () => {
305
+ provider.setValueSource({ ...publicEnv, WORKOS_API_KEY: 'sk_test_env' });
306
+
307
+ expect(provider.getConfig().apiKey).toBe('sk_test_env');
308
+ });
309
+
310
+ it.each([
311
+ ['clientId', 'WORKOS_CLIENT_ID'],
312
+ ['redirectUri', 'WORKOS_REDIRECT_URI'],
313
+ ['cookiePassword', 'WORKOS_COOKIE_PASSWORD'],
314
+ ] as const)('still requires %s', (key, envKey) => {
315
+ const rest = { ...publicEnv };
316
+ delete rest[envKey];
317
+ provider.setValueSource(rest);
318
+
319
+ expect(() => provider.getValue(key)).toThrow(
320
+ `Missing required configuration value for ${key} (${envKey}).`,
321
+ );
322
+ expect(() => provider.getConfig()).toThrow(envKey);
323
+ expect(() => provider.validate()).toThrow(`${envKey} is required`);
324
+ });
325
+
326
+ it('still validates the cookie password length', () => {
327
+ provider.setValueSource({
328
+ ...publicEnv,
329
+ WORKOS_COOKIE_PASSWORD: 'short',
330
+ });
331
+
332
+ expect(() => provider.validate()).toThrow(
333
+ /WORKOS_COOKIE_PASSWORD must be at least 32 characters/,
334
+ );
335
+ });
336
+ });
337
+
338
+ describe('AuthKitConfig types', () => {
339
+ const base = {
340
+ clientId: 'client_123',
341
+ redirectUri: 'http://localhost:3000/callback',
342
+ cookiePassword: 'a'.repeat(32),
343
+ apiHttps: true,
344
+ cookieMaxAge: 60,
345
+ cookieName: 'wos-session',
346
+ };
347
+
348
+ it('narrows on the presence of apiKey', () => {
349
+ const narrow = (config: AuthKitConfig) => {
350
+ if (config.apiKey !== undefined) {
351
+ expectTypeOf(config).toEqualTypeOf<AuthKitConfidentialConfig>();
352
+ expectTypeOf(config.apiKey).toEqualTypeOf<string>();
353
+ } else {
354
+ expectTypeOf(config).toEqualTypeOf<AuthKitPublicConfig>();
355
+ }
356
+ if ('apiKey' in config) {
357
+ expectTypeOf(config.apiKey).toEqualTypeOf<string | undefined>();
358
+ }
359
+ };
360
+ narrow({ ...base, apiKey: 'sk_test' });
361
+ narrow(base);
362
+ });
363
+
364
+ it('types a runtime-resolved apiKey as optional', () => {
365
+ expectTypeOf<AuthKitConfig['apiKey']>().toEqualTypeOf<
366
+ string | undefined
367
+ >();
368
+ });
369
+
370
+ it('accepts both client shapes and rejects invalid ones', () => {
371
+ const confidential: AuthKitConfig = { ...base, apiKey: 'sk_test' };
372
+ const publicConfig: AuthKitConfig = base;
373
+ // @ts-expect-error a confidential config must carry a key
374
+ const missingKey: AuthKitConfidentialConfig = base;
375
+ // @ts-expect-error a public config cannot carry a key
376
+ const keyedPublic: AuthKitPublicConfig = { ...base, apiKey: 'sk_test' };
377
+ const { clientId: _clientId, ...noClientId } = base;
378
+ // @ts-expect-error clientId is required in both modes
379
+ const missingClientId: AuthKitPublicConfig = noClientId;
380
+ expect([
381
+ confidential,
382
+ publicConfig,
383
+ missingKey,
384
+ keyedPublic,
385
+ missingClientId,
386
+ ]).toHaveLength(5);
387
+ });
388
+ });
202
389
  });
@@ -33,13 +33,21 @@ export class ConfigurationProvider {
33
33
 
34
34
  private valueSource: ValueSource = defaultSource;
35
35
 
36
+ // `apiKey` is intentionally optional: without it AuthKit runs as a PKCE
37
+ // public client (sign-in only). See `AuthKitPublicConfig`.
36
38
  private readonly requiredKeys: (keyof AuthKitConfig)[] = [
37
39
  'clientId',
38
- 'apiKey',
39
40
  'redirectUri',
40
41
  'cookiePassword',
41
42
  ];
42
43
 
44
+ private readonly optionalKeys: (keyof AuthKitConfig)[] = [
45
+ 'apiKey',
46
+ 'apiPort',
47
+ 'cookieSameSite',
48
+ 'cookieDomain',
49
+ ];
50
+
43
51
  /**
44
52
  * Convert a camelCase string to an uppercase, underscore-separated environment variable name.
45
53
  * @param str The string to convert
@@ -184,6 +192,7 @@ export class ConfigurationProvider {
184
192
  const allKeys = new Set<keyof AuthKitConfig>([
185
193
  ...(Object.keys(this.config) as (keyof AuthKitConfig)[]),
186
194
  ...this.requiredKeys,
195
+ ...this.optionalKeys,
187
196
  ]);
188
197
 
189
198
  // Merge each key, with environment variables taking precedence
@@ -1,19 +1,13 @@
1
1
  /**
2
- * AuthKit Configuration Options
2
+ * Configuration shared by both client modes.
3
3
  */
4
- export interface AuthKitConfig {
4
+ interface AuthKitBaseConfig {
5
5
  /**
6
6
  * The WorkOS Client ID
7
7
  * Equivalent to the WORKOS_CLIENT_ID environment variable
8
8
  */
9
9
  clientId: string;
10
10
 
11
- /**
12
- * The WorkOS API Key
13
- * Equivalent to the WORKOS_API_KEY environment variable
14
- */
15
- apiKey: string;
16
-
17
11
  /**
18
12
  * The redirect URI for the authentication callback
19
13
  * Equivalent to the WORKOS_REDIRECT_URI environment variable
@@ -53,6 +47,7 @@ export interface AuthKitConfig {
53
47
 
54
48
  /**
55
49
  * The sameSite attribute for the session cookie
50
+ * Equivalent to the WORKOS_COOKIE_SAME_SITE environment variable
56
51
  */
57
52
  cookieSameSite?: 'strict' | 'lax' | 'none';
58
53
 
@@ -65,9 +60,46 @@ export interface AuthKitConfig {
65
60
 
66
61
  /**
67
62
  * The domain for the session cookie
63
+ * Equivalent to the WORKOS_COOKIE_DOMAIN environment variable
68
64
  */
69
65
  cookieDomain?: string;
70
66
  }
71
67
 
68
+ /**
69
+ * Confidential client: the server holds a WorkOS API key.
70
+ *
71
+ * The key is sent as the client secret on code exchange and refresh
72
+ * (alongside PKCE) and is required for WorkOS management APIs called through
73
+ * `getWorkOS()`, such as `organizations.*` or `userManagement.getUser`.
74
+ */
75
+ export interface AuthKitConfidentialConfig extends AuthKitBaseConfig {
76
+ /**
77
+ * The WorkOS API Key
78
+ * Equivalent to the WORKOS_API_KEY environment variable
79
+ */
80
+ apiKey: string;
81
+ }
82
+
83
+ /**
84
+ * Public client (keyless): the server holds no WorkOS API key.
85
+ *
86
+ * Sign-in, callback, session refresh, organization switching and sign-out all
87
+ * work; PKCE protects the code exchange and the refresh token is bound to the
88
+ * client ID. WorkOS management APIs are unavailable.
89
+ */
90
+ export interface AuthKitPublicConfig extends AuthKitBaseConfig {
91
+ apiKey?: never;
92
+ }
93
+
94
+ /**
95
+ * AuthKit Configuration Options
96
+ *
97
+ * Discriminated on the presence of `apiKey`: {@link AuthKitConfidentialConfig}
98
+ * when set, {@link AuthKitPublicConfig} when not. Configuration is resolved at
99
+ * runtime from environment variables and `configure()`, so
100
+ * `getConfig('apiKey')` is typed `string | undefined`.
101
+ */
102
+ export type AuthKitConfig = AuthKitConfidentialConfig | AuthKitPublicConfig;
103
+
72
104
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
73
105
  export type ValueSource = Record<string, any> | ((key: string) => any);
@@ -131,7 +131,7 @@ describe('config', () => {
131
131
 
132
132
  it('shows all missing fields at once', () => {
133
133
  expect(() => validateConfig()).toThrow(/WORKOS_CLIENT_ID is required/);
134
- expect(() => validateConfig()).toThrow(/WORKOS_API_KEY is required/);
134
+ expect(() => validateConfig()).not.toThrow(/WORKOS_API_KEY/);
135
135
  expect(() => validateConfig()).toThrow(/WORKOS_REDIRECT_URI is required/);
136
136
  expect(() => validateConfig()).toThrow(
137
137
  /WORKOS_COOKIE_PASSWORD is required/,
@@ -464,6 +464,36 @@ describe('AuthService', () => {
464
464
  });
465
465
 
466
466
  describe('handleCallback()', () => {
467
+ it.each([
468
+ 'x:\\evil.com',
469
+ 'x:/\\evil.com',
470
+ 'x:\\\\evil.com',
471
+ 'x:\\/evil.com',
472
+ ])(
473
+ 'keeps the callback return path same-origin for %s',
474
+ async returnPathname => {
475
+ const realStorage = makeStorage();
476
+ const realService = new AuthService(
477
+ mockConfig as any,
478
+ realStorage as any,
479
+ makeClient() as any,
480
+ sessionEncryption,
481
+ );
482
+ const { cookieName } = await realService.createAuthorization('res', {
483
+ returnPathname,
484
+ });
485
+ const result = await realService.handleCallback('req', 'res', {
486
+ code: 'auth-code',
487
+ state: realStorage.cookies.get(cookieName)!,
488
+ });
489
+
490
+ expect(
491
+ new URL(result.returnPathname, mockConfig.redirectUri).origin,
492
+ ).toBe(new URL(mockConfig.redirectUri).origin);
493
+ expect(result.returnPathname).toBe('/');
494
+ },
495
+ );
496
+
467
497
  it('round-trips through createSignIn → handleCallback', async () => {
468
498
  const capture: { authCall?: Record<string, unknown> } = {};
469
499
  const realStorage = makeStorage();
@@ -325,6 +325,11 @@ export class AuthService<TRequest, TResponse> {
325
325
  /**
326
326
  * Get the WorkOS client instance.
327
327
  * Useful for direct API calls not covered by AuthKit.
328
+ *
329
+ * WorkOS management APIs (e.g. `organizations.*`,
330
+ * `userManagement.getUser`) require an API key (`WORKOS_API_KEY` or
331
+ * `configure({ apiKey })`). In public-client (keyless) mode they throw an
332
+ * `ApiKeyRequiredException` before any request.
328
333
  */
329
334
  getWorkOS(): WorkOS {
330
335
  return this.client;
@@ -0,0 +1,271 @@
1
+ /**
2
+ * Wire-level tests for public-client (keyless) mode.
3
+ *
4
+ * These drive the real sign-in, callback and refresh paths through
5
+ * `createAuthService` and the real WorkOS SDK, with only `fetch` mocked, and
6
+ * assert on the request the SDK actually sends to
7
+ * `/user_management/authenticate`.
8
+ */
9
+ import { createHash } from 'node:crypto';
10
+ import { vi } from 'vitest';
11
+ import { exportJWK, generateKeyPair, SignJWT } from 'jose';
12
+ import sessionEncryption from '../core/encryption/ironWebcryptoEncryption.js';
13
+ import { CookieSessionStorage } from '../core/session/CookieSessionStorage.js';
14
+ import type { AuthKitConfig } from '../core/config/types.js';
15
+
16
+ const API_KEY = 'sk_test_confidential';
17
+ const CLIENT_ID = 'client_123';
18
+ const env: Record<string, string> = {
19
+ WORKOS_CLIENT_ID: CLIENT_ID,
20
+ WORKOS_REDIRECT_URI: 'http://localhost:3000/callback',
21
+ WORKOS_COOKIE_PASSWORD: 'a'.repeat(32),
22
+ };
23
+
24
+ class RequestStorage extends CookieSessionStorage<Request, undefined> {
25
+ async getCookie(request: Request, name: string): Promise<string | null> {
26
+ for (const part of (request.headers.get('cookie') ?? '').split(';')) {
27
+ const [k, ...rest] = part.trim().split('=');
28
+ if (k === name) return decodeURIComponent(rest.join('='));
29
+ }
30
+ return null;
31
+ }
32
+ }
33
+
34
+ function cookiePair(setCookie: string | string[] | undefined) {
35
+ const first = Array.isArray(setCookie) ? setCookie[0] : setCookie;
36
+ return first!.split(';')[0]!;
37
+ }
38
+
39
+ // One signing key per run; the mocked JWKS endpoint serves its public half so
40
+ // `withAuth` verifies tokens exactly as it does in production.
41
+ const signingKey = generateKeyPair('RS256');
42
+ async function signAccessToken(expiresAt: number) {
43
+ const { privateKey } = await signingKey;
44
+ return new SignJWT({ sid: 'session_123' })
45
+ .setProtectedHeader({ alg: 'RS256', kid: 'key_1' })
46
+ .setIssuedAt(expiresAt - 300)
47
+ .setExpirationTime(expiresAt)
48
+ .sign(privateKey);
49
+ }
50
+
51
+ function authenticateResponse(accessToken: string, refreshToken: string) {
52
+ return Response.json({
53
+ user: {
54
+ object: 'user',
55
+ id: 'user_123',
56
+ email: 'test@example.com',
57
+ email_verified: true,
58
+ first_name: 'Test',
59
+ last_name: 'User',
60
+ profile_picture_url: null,
61
+ last_sign_in_at: null,
62
+ locale: null,
63
+ external_id: null,
64
+ metadata: {},
65
+ created_at: '2024-01-01T00:00:00Z',
66
+ updated_at: '2024-01-01T00:00:00Z',
67
+ },
68
+ access_token: accessToken,
69
+ refresh_token: refreshToken,
70
+ });
71
+ }
72
+
73
+ describe.each([
74
+ ['public client (no API key)', undefined],
75
+ ['confidential client (API key)', API_KEY],
76
+ ] as const)('%s', (_label, apiKey) => {
77
+ let savedApiKey: string | undefined;
78
+ let fetchMock: ReturnType<typeof vi.fn>;
79
+ let authenticateCalls: { body: any; authorization: string | null }[];
80
+ let nextAuthenticate: () => Promise<Response>;
81
+
82
+ beforeEach(async () => {
83
+ vi.resetModules();
84
+ // The SDK falls back to process.env.WORKOS_API_KEY, so a key in the test
85
+ // runner's environment would silently turn the public case confidential.
86
+ savedApiKey = process.env.WORKOS_API_KEY;
87
+ delete process.env.WORKOS_API_KEY;
88
+
89
+ const jwk = await exportJWK((await signingKey).publicKey);
90
+ authenticateCalls = [];
91
+ fetchMock = vi.fn(async (input: string | URL | Request, init?: any) => {
92
+ const url = String(input instanceof Request ? input.url : input);
93
+ if (url === `https://api.workos.com/sso/jwks/${CLIENT_ID}`) {
94
+ return Response.json({
95
+ keys: [{ ...jwk, kid: 'key_1', alg: 'RS256' }],
96
+ });
97
+ }
98
+ if (url === 'https://api.workos.com/user_management/authenticate') {
99
+ authenticateCalls.push({
100
+ body: JSON.parse(init.body),
101
+ authorization: new Headers(init.headers).get('Authorization'),
102
+ });
103
+ return nextAuthenticate();
104
+ }
105
+ throw new Error(`Unexpected fetch: ${url}`);
106
+ });
107
+ // The SDK binds fetch when the client is constructed (lazily, below).
108
+ vi.stubGlobal('fetch', fetchMock);
109
+ });
110
+
111
+ afterEach(() => {
112
+ vi.unstubAllGlobals();
113
+ if (savedApiKey !== undefined) process.env.WORKOS_API_KEY = savedApiKey;
114
+ });
115
+
116
+ async function createService() {
117
+ const { configure } = await import('../core/config.js');
118
+ const { createAuthService } = await import('./factory.js');
119
+ const source = apiKey ? { ...env, WORKOS_API_KEY: apiKey } : env;
120
+ configure(key => source[key]);
121
+ return createAuthService({
122
+ sessionStorageFactory: (config: AuthKitConfig) =>
123
+ new RequestStorage(config),
124
+ });
125
+ }
126
+
127
+ function expectClientCredentials(call: {
128
+ body: any;
129
+ authorization: string | null;
130
+ }) {
131
+ if (apiKey) {
132
+ expect(call.body.client_secret).toBe(apiKey);
133
+ expect(call.authorization).toBe(`Bearer ${apiKey}`);
134
+ } else {
135
+ expect(call.body).not.toHaveProperty('client_secret');
136
+ expect(call.authorization).toBeNull();
137
+ }
138
+ }
139
+
140
+ it('builds the client in the expected mode', async () => {
141
+ const service = await createService();
142
+ expect(service.getWorkOS().key).toBe(apiKey);
143
+ });
144
+
145
+ it('signs in with PKCE, exchanges the code and refreshes the session', async () => {
146
+ const service = await createService();
147
+ const now = Math.floor(Date.now() / 1000);
148
+
149
+ // 1. Sign in: PKCE challenge in the URL, verifier sealed into a cookie.
150
+ const signIn = await service.createSignIn(undefined);
151
+ const authorizationUrl = new URL(signIn.url);
152
+ expect(authorizationUrl.searchParams.get('client_id')).toBe(CLIENT_ID);
153
+ expect(authorizationUrl.searchParams.get('code_challenge')).toBeTruthy();
154
+ expect(authorizationUrl.searchParams.get('code_challenge_method')).toBe(
155
+ 'S256',
156
+ );
157
+ const state = authorizationUrl.searchParams.get('state')!;
158
+
159
+ // 2. Callback: exchange the code with the verifier.
160
+ nextAuthenticate = async () =>
161
+ authenticateResponse(await signAccessToken(now + 300), 'refresh_1');
162
+ const callback = await service.handleCallback(
163
+ new Request(`${env.WORKOS_REDIRECT_URI}?code=code_123&state=${state}`, {
164
+ headers: { cookie: cookiePair(signIn.headers?.['Set-Cookie']) },
165
+ }),
166
+ undefined,
167
+ { code: 'code_123', state },
168
+ );
169
+ expect(callback.authResponse.user.id).toBe('user_123');
170
+
171
+ expect(authenticateCalls).toHaveLength(1);
172
+ const exchange = authenticateCalls[0]!;
173
+ expect(exchange.body).toMatchObject({
174
+ grant_type: 'authorization_code',
175
+ client_id: CLIENT_ID,
176
+ code: 'code_123',
177
+ code_verifier: expect.any(String),
178
+ });
179
+ // The verifier sent must be the one behind the URL's S256 challenge.
180
+ expect(
181
+ createHash('sha256')
182
+ .update(exchange.body.code_verifier)
183
+ .digest('base64url'),
184
+ ).toBe(authorizationUrl.searchParams.get('code_challenge'));
185
+ expectClientCredentials(exchange);
186
+
187
+ // 3. Explicit refresh of the saved session.
188
+ const sessionCookie = cookiePair(callback.headers?.['Set-Cookie']);
189
+ expect(sessionCookie).toMatch(/^wos-session=/);
190
+ const session = await service.getSession(
191
+ new Request('http://localhost:3000/', {
192
+ headers: { cookie: sessionCookie },
193
+ }),
194
+ );
195
+ nextAuthenticate = async () =>
196
+ authenticateResponse(await signAccessToken(now + 600), 'refresh_2');
197
+ const refreshed = await service.refreshSession(session!);
198
+ if (!refreshed.auth.user) throw new Error('expected a signed-in user');
199
+ expect(refreshed.auth.user.id).toBe('user_123');
200
+ expect(refreshed.auth.refreshToken).toBe('refresh_2');
201
+
202
+ expect(authenticateCalls).toHaveLength(2);
203
+ const refresh = authenticateCalls[1]!;
204
+ expect(refresh.body).toMatchObject({
205
+ grant_type: 'refresh_token',
206
+ client_id: CLIENT_ID,
207
+ refresh_token: 'refresh_1',
208
+ });
209
+ expectClientCredentials(refresh);
210
+ });
211
+
212
+ it('refreshes an expired session automatically in withAuth', async () => {
213
+ const service = await createService();
214
+ const now = Math.floor(Date.now() / 1000);
215
+ const sealed = await sessionEncryption.sealData(
216
+ {
217
+ accessToken: await signAccessToken(now - 60), // expired
218
+ refreshToken: 'refresh_1',
219
+ user: { id: 'user_123' },
220
+ },
221
+ { password: env.WORKOS_COOKIE_PASSWORD!, ttl: 0 },
222
+ );
223
+ const { headers } = await service.saveSession(undefined, sealed);
224
+
225
+ nextAuthenticate = async () =>
226
+ authenticateResponse(await signAccessToken(now + 300), 'refresh_2');
227
+ const { auth, refreshedSessionData } = await service.withAuth(
228
+ new Request('http://localhost:3000/', {
229
+ headers: { cookie: cookiePair(headers?.['Set-Cookie']) },
230
+ }),
231
+ );
232
+
233
+ expect(auth.user?.id).toBe('user_123');
234
+ expect(refreshedSessionData).toEqual(expect.any(String));
235
+ expect(authenticateCalls).toHaveLength(1);
236
+ expect(authenticateCalls[0]!.body).toMatchObject({
237
+ grant_type: 'refresh_token',
238
+ client_id: CLIENT_ID,
239
+ refresh_token: 'refresh_1',
240
+ });
241
+ expectClientCredentials(authenticateCalls[0]!);
242
+ });
243
+
244
+ it.runIf(!apiKey)(
245
+ 'rejects WorkOS management calls before any network request',
246
+ async () => {
247
+ const { ApiKeyRequiredException } = await import('@workos-inc/node');
248
+ const service = await createService();
249
+ const workos = service.getWorkOS();
250
+
251
+ // The SDK owns this error (AuthKit doesn't wrap the client); pin that it
252
+ // is the actionable API-key error for the called path, not a 401.
253
+ for (const [call, path] of [
254
+ [
255
+ () => workos.userManagement.getUser('user_123'),
256
+ '/user_management/users/user_123',
257
+ ],
258
+ [() => workos.organizations.listOrganizations(), '/organizations'],
259
+ ] as const) {
260
+ const error = await call().catch((e: unknown) => e);
261
+ expect(error).toBeInstanceOf(ApiKeyRequiredException);
262
+ expect(error).toMatchObject({ status: 403, path });
263
+ expect((error as Error).message).toContain(
264
+ `API key required for "${path}"`,
265
+ );
266
+ expect((error as Error).message).toContain('new WorkOS("sk_...")');
267
+ }
268
+ expect(fetchMock).not.toHaveBeenCalled();
269
+ },
270
+ );
271
+ });