@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
@@ -0,0 +1,278 @@
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
+ // Read back from the cookie, timestamps match the installed SDK's `User`.
196
+ const sdkMajor = Number.parseInt(service.getWorkOS().version, 10);
197
+ expect(session!.user.createdAt).toEqual(
198
+ sdkMajor >= 12
199
+ ? new Date('2024-01-01T00:00:00Z')
200
+ : '2024-01-01T00:00:00Z',
201
+ );
202
+ nextAuthenticate = async () =>
203
+ authenticateResponse(await signAccessToken(now + 600), 'refresh_2');
204
+ const refreshed = await service.refreshSession(session!);
205
+ if (!refreshed.auth.user) throw new Error('expected a signed-in user');
206
+ expect(refreshed.auth.user.id).toBe('user_123');
207
+ expect(refreshed.auth.refreshToken).toBe('refresh_2');
208
+
209
+ expect(authenticateCalls).toHaveLength(2);
210
+ const refresh = authenticateCalls[1]!;
211
+ expect(refresh.body).toMatchObject({
212
+ grant_type: 'refresh_token',
213
+ client_id: CLIENT_ID,
214
+ refresh_token: 'refresh_1',
215
+ });
216
+ expectClientCredentials(refresh);
217
+ });
218
+
219
+ it('refreshes an expired session automatically in withAuth', async () => {
220
+ const service = await createService();
221
+ const now = Math.floor(Date.now() / 1000);
222
+ const sealed = await sessionEncryption.sealData(
223
+ {
224
+ accessToken: await signAccessToken(now - 60), // expired
225
+ refreshToken: 'refresh_1',
226
+ user: { id: 'user_123' },
227
+ },
228
+ { password: env.WORKOS_COOKIE_PASSWORD!, ttl: 0 },
229
+ );
230
+ const { headers } = await service.saveSession(undefined, sealed);
231
+
232
+ nextAuthenticate = async () =>
233
+ authenticateResponse(await signAccessToken(now + 300), 'refresh_2');
234
+ const { auth, refreshedSessionData } = await service.withAuth(
235
+ new Request('http://localhost:3000/', {
236
+ headers: { cookie: cookiePair(headers?.['Set-Cookie']) },
237
+ }),
238
+ );
239
+
240
+ expect(auth.user?.id).toBe('user_123');
241
+ expect(refreshedSessionData).toEqual(expect.any(String));
242
+ expect(authenticateCalls).toHaveLength(1);
243
+ expect(authenticateCalls[0]!.body).toMatchObject({
244
+ grant_type: 'refresh_token',
245
+ client_id: CLIENT_ID,
246
+ refresh_token: 'refresh_1',
247
+ });
248
+ expectClientCredentials(authenticateCalls[0]!);
249
+ });
250
+
251
+ it.runIf(!apiKey)(
252
+ 'rejects WorkOS management calls before any network request',
253
+ async () => {
254
+ const { ApiKeyRequiredException } = await import('@workos-inc/node');
255
+ const service = await createService();
256
+ const workos = service.getWorkOS();
257
+
258
+ // The SDK owns this error (AuthKit doesn't wrap the client); pin that it
259
+ // is the actionable API-key error for the called path, not a 401.
260
+ for (const [call, path] of [
261
+ [
262
+ () => workos.userManagement.getUser('user_123'),
263
+ '/user_management/users/user_123',
264
+ ],
265
+ [() => workos.organizations.listOrganizations(), '/organizations'],
266
+ ] as const) {
267
+ const error = await call().catch((e: unknown) => e);
268
+ expect(error).toBeInstanceOf(ApiKeyRequiredException);
269
+ expect(error).toMatchObject({ status: 403, path });
270
+ expect((error as Error).message).toContain(
271
+ `API key required for "${path}"`,
272
+ );
273
+ expect((error as Error).message).toContain('new WorkOS("sk_...")');
274
+ }
275
+ expect(fetchMock).not.toHaveBeenCalled();
276
+ },
277
+ );
278
+ });
package/src/utils.spec.ts CHANGED
@@ -17,6 +17,15 @@ describe('utils', () => {
17
17
  ['protocol-relative URL', '//evil.com/steal'],
18
18
  ['backslash smuggle', '/\\evil.com/path'],
19
19
  ['double-backslash', '\\\\evil.com/path'],
20
+ ['opaque path with backslash', 'x:\\evil.com'],
21
+ ['non-special scheme with slash-backslash', 'x:/\\evil.com'],
22
+ ['opaque path with double-backslash', 'x:\\\\evil.com'],
23
+ ['opaque path with backslash-slash', 'x:\\/evil.com'],
24
+ ['opaque path targeting the throwaway host', 'x:\\placeholder.invalid'],
25
+ [
26
+ 'opaque path with query and fragment',
27
+ 'x:\\evil.com/path?next=/home#login',
28
+ ],
20
29
  ['javascript: scheme', 'javascript:alert(1)'],
21
30
  ['data: scheme', 'data:text/html,<script>alert(1)</script>'],
22
31
  ['tab smuggling', '/\tevil.com'],
@@ -61,6 +70,22 @@ describe('utils', () => {
61
70
  );
62
71
  });
63
72
 
73
+ it('uses the safe fallback when the normalized input would leave the origin', () => {
74
+ expect(
75
+ sanitizeReturnPathname('x:\\evil.com', '/login?retry=1#form'),
76
+ ).toBe('/login?retry=1#form');
77
+ });
78
+
79
+ it('rejects opaque-path bypasses in the fallback too', () => {
80
+ expect(sanitizeReturnPathname(undefined, 'x:\\evil.com')).toBe('/');
81
+ expect(sanitizeReturnPathname(undefined, 'x:\\placeholder.invalid')).toBe(
82
+ '/',
83
+ );
84
+ expect(sanitizeReturnPathname('x:/\\evil.com', 'x:\\/evil.com')).toBe(
85
+ '/',
86
+ );
87
+ });
88
+
64
89
  it('backstops to `/` when both input and fallback are unusable', () => {
65
90
  expect(sanitizeReturnPathname(undefined, '')).toBe('/');
66
91
  expect(sanitizeReturnPathname(null, null as unknown as string)).toBe('/');
package/src/utils.ts CHANGED
@@ -47,9 +47,9 @@ export function constantTimeEqual(a: Uint8Array, b: Uint8Array): boolean {
47
47
  * state) to a same-origin relative URL. The returned value always begins
48
48
  * with exactly one `/`, safe to emit directly as a `Location` header.
49
49
  *
50
- * Parsing against a throwaway origin lets the WHATWG URL parser strip any
51
- * smuggled host, scheme, backslash, tab, or newline; the leading-slash
52
- * normalization defuses `//evil.com`-style protocol-relative redirects
50
+ * Parsing against a throwaway origin strips smuggled hosts and schemes.
51
+ * Re-resolving the normalized output also catches opaque paths whose raw
52
+ * backslashes become an authority when interpreted as a relative URL
53
53
  * (CWE-601). `fallback` is sanitized by the same pipeline so a hostile
54
54
  * fallback can't reopen the hole.
55
55
  */
@@ -57,12 +57,17 @@ export function sanitizeReturnPathname(
57
57
  input: unknown,
58
58
  fallback: string = '/',
59
59
  ): string {
60
+ const base = 'https://placeholder.invalid';
60
61
  for (const candidate of [input, fallback]) {
61
62
  if (typeof candidate !== 'string' || candidate.length === 0) continue;
62
63
  try {
63
- const parsed = new URL(candidate, 'https://placeholder.invalid');
64
+ const parsed = new URL(candidate, base);
64
65
  const path = '/' + parsed.pathname.replace(/^\/+/, '');
65
- return `${path}${parsed.search}${parsed.hash}`;
66
+ const result = `${path}${parsed.search}${parsed.hash}`;
67
+ // Reject authority syntax even when it names the throwaway host itself.
68
+ if (!result.startsWith('/\\') && new URL(result, base).origin === base) {
69
+ return result;
70
+ }
66
71
  } catch {
67
72
  // Unparseable; try the next candidate.
68
73
  }