@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.
- package/README.md +30 -5
- package/dist/core/client/workos.d.ts +16 -2
- package/dist/core/client/workos.d.ts.map +1 -1
- package/dist/core/client/workos.js +24 -16
- package/dist/core/client/workos.js.map +1 -1
- package/dist/core/config/ConfigurationProvider.d.ts +1 -0
- package/dist/core/config/ConfigurationProvider.d.ts.map +1 -1
- package/dist/core/config/ConfigurationProvider.js +9 -1
- package/dist/core/config/ConfigurationProvider.js.map +1 -1
- package/dist/core/config/types.d.ts +38 -7
- package/dist/core/config/types.d.ts.map +1 -1
- package/dist/service/AuthService.d.ts +5 -0
- package/dist/service/AuthService.d.ts.map +1 -1
- package/dist/service/AuthService.js +5 -0
- package/dist/service/AuthService.js.map +1 -1
- package/dist/service/factory.d.ts.map +1 -1
- package/dist/service/factory.js +1 -0
- package/dist/service/factory.js.map +1 -1
- package/dist/utils.d.ts +3 -3
- package/dist/utils.d.ts.map +1 -1
- package/dist/utils.js +10 -5
- package/dist/utils.js.map +1 -1
- package/package.json +1 -1
- package/src/core/client/workos.spec.ts +99 -0
- package/src/core/client/workos.ts +24 -20
- package/src/core/config/ConfigurationProvider.spec.ts +189 -2
- package/src/core/config/ConfigurationProvider.ts +10 -1
- package/src/core/config/types.ts +40 -8
- package/src/core/config.spec.ts +1 -1
- package/src/service/AuthService.spec.ts +30 -0
- package/src/service/AuthService.ts +5 -0
- package/src/service/factory.spec.ts +3 -0
- package/src/service/factory.ts +2 -0
- package/src/service/publicClient.spec.ts +271 -0
- package/src/utils.spec.ts +25 -0
- package/src/utils.ts +10 -5
|
@@ -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
|
+
});
|
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
|
|
51
|
-
*
|
|
52
|
-
*
|
|
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,
|
|
64
|
+
const parsed = new URL(candidate, base);
|
|
64
65
|
const path = '/' + parsed.pathname.replace(/^\/+/, '');
|
|
65
|
-
|
|
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
|
}
|