@workos/authkit-session 0.7.1 → 0.9.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 (44) hide show
  1. package/README.md +40 -14
  2. package/dist/core/AuthKitCore.d.ts +7 -0
  3. package/dist/core/AuthKitCore.d.ts.map +1 -1
  4. package/dist/core/AuthKitCore.js +26 -2
  5. package/dist/core/AuthKitCore.js.map +1 -1
  6. package/dist/core/client/workos.d.ts +16 -2
  7. package/dist/core/client/workos.d.ts.map +1 -1
  8. package/dist/core/client/workos.js +24 -16
  9. package/dist/core/client/workos.js.map +1 -1
  10. package/dist/core/config/ConfigurationProvider.d.ts +1 -0
  11. package/dist/core/config/ConfigurationProvider.d.ts.map +1 -1
  12. package/dist/core/config/ConfigurationProvider.js +20 -3
  13. package/dist/core/config/ConfigurationProvider.js.map +1 -1
  14. package/dist/core/config/types.d.ts +44 -7
  15. package/dist/core/config/types.d.ts.map +1 -1
  16. package/dist/core/encryption/ironWebcryptoEncryption.d.ts.map +1 -1
  17. package/dist/core/encryption/ironWebcryptoEncryption.js +3 -0
  18. package/dist/core/encryption/ironWebcryptoEncryption.js.map +1 -1
  19. package/dist/service/AuthService.d.ts +5 -0
  20. package/dist/service/AuthService.d.ts.map +1 -1
  21. package/dist/service/AuthService.js +5 -0
  22. package/dist/service/AuthService.js.map +1 -1
  23. package/dist/utils.d.ts +3 -3
  24. package/dist/utils.d.ts.map +1 -1
  25. package/dist/utils.js +10 -5
  26. package/dist/utils.js.map +1 -1
  27. package/package.json +3 -3
  28. package/src/core/AuthKitCore.issuer.spec.ts +97 -0
  29. package/src/core/AuthKitCore.spec.ts +48 -3
  30. package/src/core/AuthKitCore.ts +34 -2
  31. package/src/core/client/workos.spec.ts +99 -0
  32. package/src/core/client/workos.ts +24 -20
  33. package/src/core/config/ConfigurationProvider.spec.ts +236 -2
  34. package/src/core/config/ConfigurationProvider.ts +26 -2
  35. package/src/core/config/types.ts +47 -8
  36. package/src/core/config.spec.ts +1 -1
  37. package/src/core/encryption/ironWebcryptoEncryption.spec.ts +12 -0
  38. package/src/core/encryption/ironWebcryptoEncryption.ts +3 -0
  39. package/src/operations/AuthOperations.spec.ts +3 -3
  40. package/src/service/AuthService.spec.ts +30 -0
  41. package/src/service/AuthService.ts +5 -0
  42. package/src/service/publicClient.spec.ts +278 -0
  43. package/src/utils.spec.ts +25 -0
  44. package/src/utils.ts +10 -5
package/dist/utils.d.ts CHANGED
@@ -27,9 +27,9 @@ export declare function constantTimeEqual(a: Uint8Array, b: Uint8Array): boolean
27
27
  * state) to a same-origin relative URL. The returned value always begins
28
28
  * with exactly one `/`, safe to emit directly as a `Location` header.
29
29
  *
30
- * Parsing against a throwaway origin lets the WHATWG URL parser strip any
31
- * smuggled host, scheme, backslash, tab, or newline; the leading-slash
32
- * normalization defuses `//evil.com`-style protocol-relative redirects
30
+ * Parsing against a throwaway origin strips smuggled hosts and schemes.
31
+ * Re-resolving the normalized output also catches opaque paths whose raw
32
+ * backslashes become an authority when interpreted as a relative URL
33
33
  * (CWE-601). `fallback` is sanitized by the same pipeline so a hostile
34
34
  * fallback can't reopen the hole.
35
35
  */
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,wBAAgB,IAAI,CAAC,KAAK,SAAS,OAAO,EAAE,EAAE,OAAO,EACnD,EAAE,EAAE,CAAC,GAAG,IAAI,EAAE,KAAK,KAAK,OAAO,GAC9B,CAAC,GAAG,IAAI,EAAE,KAAK,KAAK,OAAO,CAW7B;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,iBAAiB,CAAC,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE,UAAU,GAAG,OAAO,CAKvE;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,sBAAsB,CACpC,KAAK,EAAE,OAAO,EACd,QAAQ,GAAE,MAAY,GACrB,MAAM,CAYR"}
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,wBAAgB,IAAI,CAAC,KAAK,SAAS,OAAO,EAAE,EAAE,OAAO,EACnD,EAAE,EAAE,CAAC,GAAG,IAAI,EAAE,KAAK,KAAK,OAAO,GAC9B,CAAC,GAAG,IAAI,EAAE,KAAK,KAAK,OAAO,CAW7B;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,iBAAiB,CAAC,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE,UAAU,GAAG,OAAO,CAKvE;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,sBAAsB,CACpC,KAAK,EAAE,OAAO,EACd,QAAQ,GAAE,MAAY,GACrB,MAAM,CAiBR"}
package/dist/utils.js CHANGED
@@ -44,20 +44,25 @@ export function constantTimeEqual(a, b) {
44
44
  * state) to a same-origin relative URL. The returned value always begins
45
45
  * with exactly one `/`, safe to emit directly as a `Location` header.
46
46
  *
47
- * Parsing against a throwaway origin lets the WHATWG URL parser strip any
48
- * smuggled host, scheme, backslash, tab, or newline; the leading-slash
49
- * normalization defuses `//evil.com`-style protocol-relative redirects
47
+ * Parsing against a throwaway origin strips smuggled hosts and schemes.
48
+ * Re-resolving the normalized output also catches opaque paths whose raw
49
+ * backslashes become an authority when interpreted as a relative URL
50
50
  * (CWE-601). `fallback` is sanitized by the same pipeline so a hostile
51
51
  * fallback can't reopen the hole.
52
52
  */
53
53
  export function sanitizeReturnPathname(input, fallback = '/') {
54
+ const base = 'https://placeholder.invalid';
54
55
  for (const candidate of [input, fallback]) {
55
56
  if (typeof candidate !== 'string' || candidate.length === 0)
56
57
  continue;
57
58
  try {
58
- const parsed = new URL(candidate, 'https://placeholder.invalid');
59
+ const parsed = new URL(candidate, base);
59
60
  const path = '/' + parsed.pathname.replace(/^\/+/, '');
60
- return `${path}${parsed.search}${parsed.hash}`;
61
+ const result = `${path}${parsed.search}${parsed.hash}`;
62
+ // Reject authority syntax even when it names the throwaway host itself.
63
+ if (!result.startsWith('/\\') && new URL(result, base).origin === base) {
64
+ return result;
65
+ }
61
66
  }
62
67
  catch {
63
68
  // Unparseable; try the next candidate.
package/dist/utils.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,MAAM,UAAU,IAAI,CAClB,EAA+B;IAE/B,IAAI,MAAM,GAAG,KAAK,CAAC;IACnB,IAAI,MAAe,CAAC;IAEpB,OAAO,CAAC,GAAG,IAAW,EAAW,EAAE;QACjC,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,MAAM,GAAG,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC;YACrB,MAAM,GAAG,IAAI,CAAC;QAChB,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;AACJ,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,iBAAiB,CAAC,CAAa,EAAE,CAAa;IAC5D,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,MAAM;QAAE,OAAO,KAAK,CAAC;IACxC,IAAI,IAAI,GAAG,CAAC,CAAC;IACb,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,EAAE;QAAE,IAAI,IAAI,CAAC,CAAC,CAAC,CAAE,GAAG,CAAC,CAAC,CAAC,CAAE,CAAC;IACzD,OAAO,IAAI,KAAK,CAAC,CAAC;AACpB,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,sBAAsB,CACpC,KAAc,EACd,WAAmB,GAAG;IAEtB,KAAK,MAAM,SAAS,IAAI,CAAC,KAAK,EAAE,QAAQ,CAAC,EAAE,CAAC;QAC1C,IAAI,OAAO,SAAS,KAAK,QAAQ,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC;YAAE,SAAS;QACtE,IAAI,CAAC;YACH,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,SAAS,EAAE,6BAA6B,CAAC,CAAC;YACjE,MAAM,IAAI,GAAG,GAAG,GAAG,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;YACvD,OAAO,GAAG,IAAI,GAAG,MAAM,CAAC,MAAM,GAAG,MAAM,CAAC,IAAI,EAAE,CAAC;QACjD,CAAC;QAAC,MAAM,CAAC;YACP,uCAAuC;QACzC,CAAC;IACH,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC"}
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,MAAM,UAAU,IAAI,CAClB,EAA+B;IAE/B,IAAI,MAAM,GAAG,KAAK,CAAC;IACnB,IAAI,MAAe,CAAC;IAEpB,OAAO,CAAC,GAAG,IAAW,EAAW,EAAE;QACjC,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,MAAM,GAAG,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC;YACrB,MAAM,GAAG,IAAI,CAAC;QAChB,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;AACJ,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,iBAAiB,CAAC,CAAa,EAAE,CAAa;IAC5D,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,MAAM;QAAE,OAAO,KAAK,CAAC;IACxC,IAAI,IAAI,GAAG,CAAC,CAAC;IACb,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,EAAE;QAAE,IAAI,IAAI,CAAC,CAAC,CAAC,CAAE,GAAG,CAAC,CAAC,CAAC,CAAE,CAAC;IACzD,OAAO,IAAI,KAAK,CAAC,CAAC;AACpB,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,sBAAsB,CACpC,KAAc,EACd,WAAmB,GAAG;IAEtB,MAAM,IAAI,GAAG,6BAA6B,CAAC;IAC3C,KAAK,MAAM,SAAS,IAAI,CAAC,KAAK,EAAE,QAAQ,CAAC,EAAE,CAAC;QAC1C,IAAI,OAAO,SAAS,KAAK,QAAQ,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC;YAAE,SAAS;QACtE,IAAI,CAAC;YACH,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;YACxC,MAAM,IAAI,GAAG,GAAG,GAAG,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;YACvD,MAAM,MAAM,GAAG,GAAG,IAAI,GAAG,MAAM,CAAC,MAAM,GAAG,MAAM,CAAC,IAAI,EAAE,CAAC;YACvD,wEAAwE;YACxE,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,IAAI,IAAI,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC,MAAM,KAAK,IAAI,EAAE,CAAC;gBACvE,OAAO,MAAM,CAAC;YAChB,CAAC;QACH,CAAC;QAAC,MAAM,CAAC;YACP,uCAAuC;QACzC,CAAC;IACH,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@workos/authkit-session",
3
- "version": "0.7.1",
3
+ "version": "0.9.0",
4
4
  "description": "Framework-agnostic authentication library for WorkOS with pluggable storage adapters",
5
5
  "keywords": [],
6
6
  "license": "MIT",
@@ -31,14 +31,14 @@
31
31
  "devDependencies": {
32
32
  "@types/node": "^20.17.0",
33
33
  "@vitest/coverage-v8": "^4.0.17",
34
- "@workos-inc/node": "^10.6.0",
34
+ "@workos-inc/node": "^12.1.0",
35
35
  "oxfmt": "^0.42.0",
36
36
  "oxlint": "^1.57.0",
37
37
  "typescript": "^5.9.3",
38
38
  "vitest": "^4.0.17"
39
39
  },
40
40
  "peerDependencies": {
41
- "@workos-inc/node": "^8.0.0 || ^9.0.0 || ^10.0.0"
41
+ "@workos-inc/node": "^8.0.0 || ^9.0.0 || ^10.0.0 || ^11.0.0 || ^12.0.0"
42
42
  },
43
43
  "engines": {
44
44
  "node": ">=20.0.0"
@@ -0,0 +1,97 @@
1
+ import { jwtVerify } from 'jose';
2
+ import { AuthKitCore } from './AuthKitCore.js';
3
+
4
+ vi.mock('jose', async importOriginal => {
5
+ const actual = await importOriginal<typeof import('jose')>();
6
+ return {
7
+ ...actual,
8
+ jwtVerify: vi.fn().mockResolvedValue({ payload: {}, protectedHeader: {} }),
9
+ };
10
+ });
11
+
12
+ const mockClient = {
13
+ userManagement: {
14
+ getJwksUrl: () => 'https://api.workos.com/sso/jwks/test-client-id',
15
+ },
16
+ };
17
+
18
+ const mockEncryption = {
19
+ sealData: async () => 'encrypted-session-data',
20
+ unsealData: async () => ({}),
21
+ };
22
+
23
+ const baseConfig = {
24
+ cookiePassword: 'test-password-that-is-32-chars-long!!',
25
+ clientId: 'test-client-id',
26
+ };
27
+
28
+ function createCore(config: Record<string, unknown>) {
29
+ return new AuthKitCore(
30
+ config as any,
31
+ mockClient as any,
32
+ mockEncryption as any,
33
+ );
34
+ }
35
+
36
+ describe('AuthKitCore.verifyToken() issuer validation', () => {
37
+ beforeEach(() => {
38
+ vi.mocked(jwtVerify).mockClear();
39
+ });
40
+
41
+ it('does not validate the issuer claim by default', async () => {
42
+ const core = createCore(baseConfig);
43
+
44
+ await expect(core.verifyToken('some.jwt.token')).resolves.toBe(true);
45
+
46
+ expect(jwtVerify).toHaveBeenCalledTimes(1);
47
+ expect(jwtVerify).toHaveBeenCalledWith(
48
+ 'some.jwt.token',
49
+ expect.any(Function),
50
+ undefined,
51
+ );
52
+ });
53
+
54
+ it('validates the issuer claim when issuer is configured', async () => {
55
+ const core = createCore({
56
+ ...baseConfig,
57
+ issuer: 'https://auth.example.com',
58
+ });
59
+
60
+ await expect(core.verifyToken('some.jwt.token')).resolves.toBe(true);
61
+
62
+ expect(jwtVerify).toHaveBeenCalledTimes(1);
63
+ expect(jwtVerify).toHaveBeenCalledWith(
64
+ 'some.jwt.token',
65
+ expect.any(Function),
66
+ { issuer: 'https://auth.example.com' },
67
+ );
68
+ });
69
+
70
+ it('passes a list of issuers through to jwtVerify', async () => {
71
+ const issuer = [
72
+ 'https://auth.example.com',
73
+ 'https://api.workos.com/user_management/test-client-id',
74
+ ];
75
+ const core = createCore({ ...baseConfig, issuer });
76
+
77
+ await expect(core.verifyToken('some.jwt.token')).resolves.toBe(true);
78
+
79
+ expect(jwtVerify).toHaveBeenCalledWith(
80
+ 'some.jwt.token',
81
+ expect.any(Function),
82
+ { issuer },
83
+ );
84
+ });
85
+
86
+ it('returns false when jwtVerify rejects the issuer', async () => {
87
+ vi.mocked(jwtVerify).mockRejectedValueOnce(
88
+ new Error('unexpected "iss" claim value'),
89
+ );
90
+ const core = createCore({
91
+ ...baseConfig,
92
+ issuer: 'https://auth.example.com',
93
+ });
94
+
95
+ await expect(core.verifyToken('some.jwt.token')).resolves.toBe(false);
96
+ });
97
+ });
@@ -1,6 +1,7 @@
1
1
  import { RateLimitExceededException } from '@workos-inc/node';
2
2
  import { AuthKitCore } from './AuthKitCore.js';
3
3
  import { SessionEncryptionError, TokenRefreshError } from './errors.js';
4
+ import sessionEncryption from './encryption/ironWebcryptoEncryption.js';
4
5
 
5
6
  const mockConfig = {
6
7
  cookiePassword: 'test-password-that-is-32-chars-long!!',
@@ -16,9 +17,9 @@ const mockUser = {
16
17
  name: 'Test User',
17
18
  emailVerified: true,
18
19
  profilePictureUrl: null,
19
- createdAt: '2023-01-01T00:00:00Z',
20
- updatedAt: '2023-01-01T00:00:00Z',
21
- lastSignInAt: '2023-01-01T00:00:00Z',
20
+ createdAt: new Date('2023-01-01T00:00:00Z'),
21
+ updatedAt: new Date('2023-01-01T00:00:00Z'),
22
+ lastSignInAt: new Date('2023-01-01T00:00:00Z'),
22
23
  locale: 'en-US',
23
24
  externalId: null,
24
25
  metadata: {},
@@ -280,6 +281,50 @@ describe('AuthKitCore', () => {
280
281
  SessionEncryptionError,
281
282
  );
282
283
  });
284
+
285
+ describe('user timestamps', () => {
286
+ const iso = '2023-01-01T00:00:00.000Z';
287
+
288
+ // Seal for real so timestamps go through JSON exactly as in a cookie.
289
+ async function roundTrip(
290
+ version: string | undefined,
291
+ lastSignInAt: Date | null = new Date(iso),
292
+ ) {
293
+ const sdkCore = new AuthKitCore(
294
+ mockConfig as any,
295
+ { ...mockClient, version } as any,
296
+ sessionEncryption,
297
+ );
298
+ const sealed = await sdkCore.encryptSession({
299
+ ...makeExpiredSession(),
300
+ user: { ...mockUser, lastSignInAt },
301
+ } as any);
302
+ return (await sdkCore.decryptSession(sealed)).user as any;
303
+ }
304
+
305
+ it('revives them as Dates with @workos-inc/node >= 12', async () => {
306
+ const user = await roundTrip('12.1.0');
307
+ expect(user.createdAt).toEqual(new Date(iso));
308
+ expect(user.updatedAt).toEqual(new Date(iso));
309
+ expect(user.lastSignInAt).toEqual(new Date(iso));
310
+ });
311
+
312
+ it('keeps a null lastSignInAt null', async () => {
313
+ const user = await roundTrip('12.0.0', null);
314
+ expect(user.lastSignInAt).toBeNull();
315
+ expect(user.createdAt).toEqual(new Date(iso));
316
+ });
317
+
318
+ it.each(['8.0.0', '10.14.0', '11.0.0', undefined])(
319
+ 'leaves them as strings with SDK version %s',
320
+ async version => {
321
+ const user = await roundTrip(version);
322
+ expect(user.createdAt).toBe(iso);
323
+ expect(user.updatedAt).toBe(iso);
324
+ expect(user.lastSignInAt).toBe(iso);
325
+ },
326
+ );
327
+ });
283
328
  });
284
329
 
285
330
  describe('refreshTokens()', () => {
@@ -21,6 +21,9 @@ import type {
21
21
  SessionEncryption,
22
22
  } from './session/types.js';
23
23
 
24
+ const toDate = (value: unknown) =>
25
+ value == null ? value : new Date(value as string | Date);
26
+
24
27
  type RefreshResult = {
25
28
  accessToken: string;
26
29
  refreshToken: string;
@@ -70,13 +73,19 @@ export class AuthKitCore {
70
73
 
71
74
  /**
72
75
  * Verify a JWT access token against WorkOS JWKS.
76
+ * The `iss` claim is only validated when `config.issuer` is set.
73
77
  *
74
78
  * @param token - The JWT access token to verify
75
79
  * @returns true if valid, false otherwise
76
80
  */
77
81
  async verifyToken(token: string): Promise<boolean> {
82
+ const issuer = this.config.issuer;
78
83
  try {
79
- await jwtVerify(token, this.getPublicKey());
84
+ await jwtVerify(
85
+ token,
86
+ this.getPublicKey(),
87
+ issuer ? { issuer } : undefined,
88
+ );
80
89
  return true;
81
90
  } catch {
82
91
  return false;
@@ -160,12 +169,35 @@ export class AuthKitCore {
160
169
  encryptedSession,
161
170
  { password: this.config.cookiePassword },
162
171
  );
163
- return session;
172
+ return this.reviveUserTimestamps(session);
164
173
  } catch (error) {
165
174
  throw new SessionEncryptionError('Failed to decrypt session', error);
166
175
  }
167
176
  }
168
177
 
178
+ /**
179
+ * `@workos-inc/node` >= 12 types `User` timestamps as `Date`, but a sealed
180
+ * session stores them as ISO strings. With that SDK installed, turn them back
181
+ * into `Date`s. Earlier SDKs type them as strings, so leave those as is.
182
+ */
183
+ private reviveUserTimestamps(session: Session): Session {
184
+ const sdkMajorVersion = Number.parseInt(this.client.version, 10);
185
+ if (!(sdkMajorVersion >= 12) || !session?.user) {
186
+ return session;
187
+ }
188
+
189
+ const user = session.user as unknown as Record<string, unknown>;
190
+ return {
191
+ ...session,
192
+ user: {
193
+ ...user,
194
+ createdAt: toDate(user.createdAt),
195
+ updatedAt: toDate(user.updatedAt),
196
+ lastSignInAt: toDate(user.lastSignInAt),
197
+ } as unknown as User,
198
+ };
199
+ }
200
+
169
201
  /**
170
202
  * Verify the OAuth callback state against the PKCE verifier cookie and
171
203
  * return the unsealed state blob.
@@ -0,0 +1,99 @@
1
+ import { vi } from 'vitest';
2
+
3
+ const env = {
4
+ WORKOS_CLIENT_ID: 'client_123',
5
+ WORKOS_REDIRECT_URI: 'http://localhost:3000/callback',
6
+ WORKOS_COOKIE_PASSWORD: 'a'.repeat(32),
7
+ };
8
+
9
+ // Fresh module graph per test: the config provider and getWorkOS() are
10
+ // process-wide singletons.
11
+ async function load(source: Record<string, string>) {
12
+ const { configure } = await import('../config.js');
13
+ configure(key => source[key]);
14
+ return import('./workos.js');
15
+ }
16
+
17
+ describe('WorkOS client', () => {
18
+ let savedApiKey: string | undefined;
19
+
20
+ beforeEach(() => {
21
+ vi.resetModules();
22
+ savedApiKey = process.env.WORKOS_API_KEY;
23
+ // The SDK falls back to process.env.WORKOS_API_KEY; keep it out unless a
24
+ // test sets it on purpose.
25
+ delete process.env.WORKOS_API_KEY;
26
+ });
27
+
28
+ afterEach(() => {
29
+ vi.doUnmock('@workos-inc/node');
30
+ if (savedApiKey !== undefined) process.env.WORKOS_API_KEY = savedApiKey;
31
+ else delete process.env.WORKOS_API_KEY;
32
+ });
33
+
34
+ describe('constructor arguments', () => {
35
+ let WorkOSMock: ReturnType<typeof vi.fn>;
36
+
37
+ beforeEach(() => {
38
+ WorkOSMock = vi.fn();
39
+ vi.doMock('@workos-inc/node', () => ({ WorkOS: WorkOSMock }));
40
+ });
41
+
42
+ it('passes apiKey and clientId in confidential mode', async () => {
43
+ const { createWorkOSInstance } = await load({
44
+ ...env,
45
+ WORKOS_API_KEY: 'sk_test_confidential',
46
+ });
47
+ createWorkOSInstance();
48
+
49
+ expect(WorkOSMock).toHaveBeenCalledTimes(1);
50
+ expect(WorkOSMock.mock.calls[0]).toEqual([
51
+ {
52
+ apiKey: 'sk_test_confidential',
53
+ clientId: 'client_123',
54
+ apiHostname: 'api.workos.com',
55
+ https: true,
56
+ port: undefined,
57
+ appInfo: { name: 'authkit-session', version: expect.any(String) },
58
+ },
59
+ ]);
60
+ });
61
+
62
+ it('passes clientId and no apiKey in public mode', async () => {
63
+ const { createWorkOSInstance } = await load(env);
64
+ createWorkOSInstance();
65
+
66
+ expect(WorkOSMock).toHaveBeenCalledTimes(1);
67
+ expect(WorkOSMock.mock.calls[0]).toHaveLength(1);
68
+ const [options] = WorkOSMock.mock.calls[0]!;
69
+ expect(options.apiKey).toBeUndefined();
70
+ expect(options.clientId).toBe('client_123');
71
+ });
72
+ });
73
+
74
+ it('builds a real keyless client in public mode', async () => {
75
+ const { getWorkOS } = await load(env);
76
+ const workos = getWorkOS();
77
+
78
+ expect(workos.key).toBeUndefined();
79
+ expect(workos.clientId).toBe('client_123');
80
+ });
81
+
82
+ it('builds a real confidential client with a key', async () => {
83
+ const { getWorkOS } = await load({
84
+ ...env,
85
+ WORKOS_API_KEY: 'sk_test_confidential',
86
+ });
87
+
88
+ expect(getWorkOS().key).toBe('sk_test_confidential');
89
+ });
90
+
91
+ it('picks up WORKOS_API_KEY from process.env even when a custom value source omits it', async () => {
92
+ // Documented behavior: the WorkOS SDK falls back to process.env, so a key
93
+ // in the process environment always ends up on the client.
94
+ process.env.WORKOS_API_KEY = 'sk_test_from_process_env';
95
+ const { getWorkOS } = await load(env);
96
+
97
+ expect(getWorkOS().key).toBe('sk_test_from_process_env');
98
+ });
99
+ });
@@ -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);