@workos/authkit-session 0.7.0 → 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.
Files changed (36) hide show
  1. package/README.md +30 -5
  2. package/dist/core/client/workos.d.ts +16 -2
  3. package/dist/core/client/workos.d.ts.map +1 -1
  4. package/dist/core/client/workos.js +24 -16
  5. package/dist/core/client/workos.js.map +1 -1
  6. package/dist/core/config/ConfigurationProvider.d.ts +1 -0
  7. package/dist/core/config/ConfigurationProvider.d.ts.map +1 -1
  8. package/dist/core/config/ConfigurationProvider.js +9 -1
  9. package/dist/core/config/ConfigurationProvider.js.map +1 -1
  10. package/dist/core/config/types.d.ts +38 -7
  11. package/dist/core/config/types.d.ts.map +1 -1
  12. package/dist/service/AuthService.d.ts +5 -0
  13. package/dist/service/AuthService.d.ts.map +1 -1
  14. package/dist/service/AuthService.js +5 -0
  15. package/dist/service/AuthService.js.map +1 -1
  16. package/dist/service/factory.d.ts.map +1 -1
  17. package/dist/service/factory.js +1 -0
  18. package/dist/service/factory.js.map +1 -1
  19. package/dist/utils.d.ts +3 -3
  20. package/dist/utils.d.ts.map +1 -1
  21. package/dist/utils.js +10 -5
  22. package/dist/utils.js.map +1 -1
  23. package/package.json +1 -1
  24. package/src/core/client/workos.spec.ts +99 -0
  25. package/src/core/client/workos.ts +24 -20
  26. package/src/core/config/ConfigurationProvider.spec.ts +189 -2
  27. package/src/core/config/ConfigurationProvider.ts +10 -1
  28. package/src/core/config/types.ts +40 -8
  29. package/src/core/config.spec.ts +1 -1
  30. package/src/service/AuthService.spec.ts +30 -0
  31. package/src/service/AuthService.ts +5 -0
  32. package/src/service/factory.spec.ts +3 -0
  33. package/src/service/factory.ts +2 -0
  34. package/src/service/publicClient.spec.ts +271 -0
  35. package/src/utils.spec.ts +25 -0
  36. package/src/utils.ts +10 -5
@@ -4,35 +4,39 @@ import { once } from '../../utils.js';
4
4
  import pkg from '../../../package.json' with { type: 'json' };
5
5
 
6
6
  /**
7
- * Create a WorkOS instance with the provided API key and optional settings.
7
+ * Create a WorkOS instance from the AuthKit configuration.
8
+ *
9
+ * With an API key this is a confidential client. Without one it is a PKCE
10
+ * public client: sign-in, callback, refresh and sign-out work, but WorkOS
11
+ * management APIs throw an `ApiKeyRequiredException` before any request.
12
+ *
13
+ * Note: when no API key is configured, the WorkOS SDK itself falls back to
14
+ * `process.env.WORKOS_API_KEY`. So if that variable is set in the process
15
+ * environment, a key is always in play, even when a custom value source
16
+ * passed to `configure()` doesn't provide one.
8
17
  */
9
18
  export function createWorkOSInstance() {
10
- // Get required API key from config
11
- const apiKey = getConfig('apiKey');
12
-
13
- // Get optional settings
14
- const apiHostname = getConfig('apiHostname');
15
- const apiHttps = getConfig('apiHttps');
16
- const apiPort = getConfig('apiPort');
17
-
18
- const options = {
19
- apiHostname,
20
- https: apiHttps,
21
- port: apiPort,
19
+ return new WorkOS({
20
+ // Optional: absent means public-client (keyless) mode
21
+ apiKey: getConfig('apiKey'),
22
+ clientId: getConfig('clientId'),
23
+ apiHostname: getConfig('apiHostname'),
24
+ https: getConfig('apiHttps'),
25
+ port: getConfig('apiPort'),
22
26
  appInfo: {
23
27
  name: 'authkit-session',
24
28
  version: pkg.version,
25
29
  },
26
- };
27
-
28
- // Initialize the WorkOS client with config values
29
- const workos = new WorkOS(apiKey, options);
30
-
31
- return workos;
30
+ });
32
31
  }
33
32
 
34
33
  /**
35
- * Create a WorkOS instance with the provided API key and optional settings.
34
+ * Returns the shared WorkOS client used by AuthKit.
36
35
  * This function is lazy loaded to avoid loading the WorkOS SDK when it's not needed.
36
+ *
37
+ * Calling WorkOS management APIs directly (e.g. `getWorkOS().organizations`,
38
+ * `getWorkOS().userManagement.getUser`) requires an API key
39
+ * (`WORKOS_API_KEY` or `configure({ apiKey })`). In public-client (keyless)
40
+ * mode those calls throw an `ApiKeyRequiredException` before any request.
37
41
  */
38
42
  export const getWorkOS = once(createWorkOSInstance);
@@ -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;
@@ -44,6 +44,9 @@ describe('createAuthService', () => {
44
44
  expect(typeof service.createSignIn).toBe('function');
45
45
  expect(typeof service.createSignUp).toBe('function');
46
46
  expect(typeof service.clearPendingVerifier).toBe('function');
47
+ expect(typeof service.clearPendingVerifierByName).toBe('function');
48
+ expect(typeof service.switchOrganization).toBe('function');
49
+ expect(typeof service.refreshSession).toBe('function');
47
50
  expect(typeof service.getWorkOS).toBe('function');
48
51
  expect(typeof service.handleCallback).toBe('function');
49
52
  });
@@ -78,6 +78,8 @@ export function createAuthService<TRequest, TResponse>(options: {
78
78
  createSignUp: (response, opts) => getService().createSignUp(response, opts),
79
79
  clearPendingVerifier: (response, opts) =>
80
80
  getService().clearPendingVerifier(response, opts),
81
+ clearPendingVerifierByName: (response, opts) =>
82
+ getService().clearPendingVerifierByName(response, opts),
81
83
  getWorkOS: () => getService().getWorkOS(),
82
84
  handleCallback: (request, response, opts) =>
83
85
  getService().handleCallback(request, response, opts),