@workos/authkit-session 0.1.2 → 0.2.0-beta.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 +507 -232
- package/dist/core/AuthKitCore.d.ts +107 -0
- package/dist/core/AuthKitCore.d.ts.map +1 -0
- package/dist/core/AuthKitCore.js +189 -0
- package/dist/core/AuthKitCore.js.map +1 -0
- package/dist/core/session/CookieSessionStorage.d.ts.map +1 -1
- package/dist/core/session/CookieSessionStorage.js +22 -3
- package/dist/core/session/CookieSessionStorage.js.map +1 -1
- package/dist/core/session/types.d.ts +27 -7
- package/dist/core/session/types.d.ts.map +1 -1
- package/dist/index.d.ts +27 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +48 -4
- package/dist/index.js.map +1 -1
- package/dist/operations/AuthOperations.d.ts +84 -0
- package/dist/operations/AuthOperations.d.ts.map +1 -0
- package/dist/operations/AuthOperations.js +147 -0
- package/dist/operations/AuthOperations.js.map +1 -0
- package/dist/service/AuthService.d.ts +156 -0
- package/dist/service/AuthService.d.ts.map +1 -0
- package/dist/service/AuthService.js +225 -0
- package/dist/service/AuthService.js.map +1 -0
- package/dist/service/factory.d.ts +37 -0
- package/dist/service/factory.d.ts.map +1 -0
- package/dist/service/factory.js +46 -0
- package/dist/service/factory.js.map +1 -0
- package/package.json +6 -6
- package/src/core/AuthKitCore.spec.ts +269 -0
- package/src/core/AuthKitCore.ts +239 -0
- package/src/core/session/CookieSessionStorage.spec.ts +17 -0
- package/src/core/session/CookieSessionStorage.ts +22 -2
- package/src/core/session/types.ts +30 -8
- package/src/index.ts +55 -4
- package/src/operations/AuthOperations.spec.ts +240 -0
- package/src/operations/AuthOperations.ts +192 -0
- package/src/service/AuthService.spec.ts +241 -0
- package/src/service/AuthService.ts +293 -0
- package/src/service/factory.spec.ts +109 -0
- package/src/service/factory.ts +69 -0
- package/dist/core/createAuthKitFactory.d.ts +0 -64
- package/dist/core/createAuthKitFactory.d.ts.map +0 -1
- package/dist/core/createAuthKitFactory.js +0 -95
- package/dist/core/createAuthKitFactory.js.map +0 -1
- package/dist/core/session/SessionManager.d.ts +0 -51
- package/dist/core/session/SessionManager.d.ts.map +0 -1
- package/dist/core/session/SessionManager.js +0 -238
- package/dist/core/session/SessionManager.js.map +0 -1
- package/src/core/createAuthKitFactory.spec.ts +0 -161
- package/src/core/createAuthKitFactory.ts +0 -195
- package/src/core/session/SessionManager.spec.ts +0 -357
- package/src/core/session/SessionManager.ts +0 -357
|
@@ -1,357 +0,0 @@
|
|
|
1
|
-
import { SessionManager } from './SessionManager.js';
|
|
2
|
-
import {
|
|
3
|
-
SessionEncryptionError,
|
|
4
|
-
AuthKitError,
|
|
5
|
-
TokenRefreshError,
|
|
6
|
-
} from '../errors.js';
|
|
7
|
-
|
|
8
|
-
// Simple mocks for dependencies
|
|
9
|
-
const mockConfig = {
|
|
10
|
-
getValue: (key: string) => {
|
|
11
|
-
const values = {
|
|
12
|
-
cookiePassword: 'test-password-that-is-32-chars-long!!',
|
|
13
|
-
clientId: 'test-client-id',
|
|
14
|
-
redirectUri: 'http://localhost:3000/callback',
|
|
15
|
-
};
|
|
16
|
-
return values[key as keyof typeof values];
|
|
17
|
-
},
|
|
18
|
-
};
|
|
19
|
-
|
|
20
|
-
const mockUser = {
|
|
21
|
-
id: 'user_123',
|
|
22
|
-
email: 'test@example.com',
|
|
23
|
-
object: 'user',
|
|
24
|
-
firstName: 'Test',
|
|
25
|
-
lastName: 'User',
|
|
26
|
-
emailVerified: true,
|
|
27
|
-
profilePictureUrl: null,
|
|
28
|
-
createdAt: '2023-01-01T00:00:00Z',
|
|
29
|
-
updatedAt: '2023-01-01T00:00:00Z',
|
|
30
|
-
lastSignInAt: '2023-01-01T00:00:00Z',
|
|
31
|
-
externalId: null,
|
|
32
|
-
metadata: {},
|
|
33
|
-
} as const;
|
|
34
|
-
|
|
35
|
-
const mockStorage = {
|
|
36
|
-
getSession: async () => null,
|
|
37
|
-
saveSession: async (response: any) => ({ response }),
|
|
38
|
-
clearSession: async (response: any) => ({ response }),
|
|
39
|
-
};
|
|
40
|
-
|
|
41
|
-
const mockTokenManager = {
|
|
42
|
-
verifyToken: async () => true,
|
|
43
|
-
isTokenExpiring: () => false,
|
|
44
|
-
parseTokenClaims: () => ({
|
|
45
|
-
sub: 'user_123',
|
|
46
|
-
sid: 'session_123',
|
|
47
|
-
exp: Math.floor(Date.now() / 1000) + 3600,
|
|
48
|
-
org_id: 'org_123',
|
|
49
|
-
}),
|
|
50
|
-
};
|
|
51
|
-
|
|
52
|
-
const mockClient = {
|
|
53
|
-
userManagement: {
|
|
54
|
-
getAuthorizationUrl: ({ redirectUri, clientId, state }: any) =>
|
|
55
|
-
`https://api.workos.com/sso/authorize?client_id=${clientId}&redirect_uri=${encodeURIComponent(redirectUri)}&state=${state || ''}`,
|
|
56
|
-
authenticateWithRefreshToken: async () => ({
|
|
57
|
-
accessToken: 'new-access-token',
|
|
58
|
-
refreshToken: 'new-refresh-token',
|
|
59
|
-
user: mockUser,
|
|
60
|
-
impersonator: undefined,
|
|
61
|
-
}),
|
|
62
|
-
revokeSession: async () => {},
|
|
63
|
-
getLogoutUrl: ({ sessionId, returnTo }: any) =>
|
|
64
|
-
`https://api.workos.com/sso/logout?session_id=${sessionId}&return_to=${returnTo || ''}`,
|
|
65
|
-
},
|
|
66
|
-
};
|
|
67
|
-
|
|
68
|
-
const mockEncryption = {
|
|
69
|
-
sealData: async () => 'encrypted-session-data',
|
|
70
|
-
unsealData: async () => ({
|
|
71
|
-
accessToken: 'test-access-token',
|
|
72
|
-
refreshToken: 'test-refresh-token',
|
|
73
|
-
user: mockUser,
|
|
74
|
-
impersonator: undefined,
|
|
75
|
-
}),
|
|
76
|
-
};
|
|
77
|
-
|
|
78
|
-
describe('SessionManager', () => {
|
|
79
|
-
let sessionManager: SessionManager<any, any>;
|
|
80
|
-
|
|
81
|
-
beforeEach(() => {
|
|
82
|
-
sessionManager = new SessionManager(
|
|
83
|
-
mockConfig as any,
|
|
84
|
-
mockStorage as any,
|
|
85
|
-
mockTokenManager as any,
|
|
86
|
-
mockClient as any,
|
|
87
|
-
mockEncryption as any,
|
|
88
|
-
);
|
|
89
|
-
});
|
|
90
|
-
|
|
91
|
-
describe('constructor', () => {
|
|
92
|
-
it('creates instance with required dependencies', () => {
|
|
93
|
-
expect(sessionManager).toBeInstanceOf(SessionManager);
|
|
94
|
-
});
|
|
95
|
-
});
|
|
96
|
-
|
|
97
|
-
describe('withAuth()', () => {
|
|
98
|
-
it('returns null user when no session exists', async () => {
|
|
99
|
-
const result = await sessionManager.withAuth('request');
|
|
100
|
-
|
|
101
|
-
expect(result.user).toBeNull();
|
|
102
|
-
});
|
|
103
|
-
|
|
104
|
-
it('returns user data when valid session exists', async () => {
|
|
105
|
-
const storageWithSession = {
|
|
106
|
-
...mockStorage,
|
|
107
|
-
getSession: async () => 'encrypted-session',
|
|
108
|
-
};
|
|
109
|
-
|
|
110
|
-
const manager = new SessionManager(
|
|
111
|
-
mockConfig as any,
|
|
112
|
-
storageWithSession as any,
|
|
113
|
-
mockTokenManager as any,
|
|
114
|
-
mockClient as any,
|
|
115
|
-
mockEncryption as any,
|
|
116
|
-
);
|
|
117
|
-
|
|
118
|
-
const result = await manager.withAuth('request');
|
|
119
|
-
|
|
120
|
-
expect(result.user).toEqual(mockUser);
|
|
121
|
-
expect(result.sessionId).toBe('session_123');
|
|
122
|
-
expect(result.accessToken).toBe('test-access-token');
|
|
123
|
-
});
|
|
124
|
-
});
|
|
125
|
-
|
|
126
|
-
describe('getAuthorizationUrl()', () => {
|
|
127
|
-
it('generates authorization URL with default values', async () => {
|
|
128
|
-
const url = await sessionManager.getAuthorizationUrl({});
|
|
129
|
-
|
|
130
|
-
expect(url).toContain('client_id=test-client-id');
|
|
131
|
-
expect(url).toContain(
|
|
132
|
-
'redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fcallback',
|
|
133
|
-
);
|
|
134
|
-
});
|
|
135
|
-
|
|
136
|
-
it('includes return pathname in state', async () => {
|
|
137
|
-
const url = await sessionManager.getAuthorizationUrl({
|
|
138
|
-
returnPathname: '/dashboard',
|
|
139
|
-
});
|
|
140
|
-
|
|
141
|
-
const stateParam = new URLSearchParams(url.split('?')[1]).get('state');
|
|
142
|
-
const decodedState = JSON.parse(atob(stateParam!));
|
|
143
|
-
|
|
144
|
-
expect(decodedState.returnPathname).toBe('/dashboard');
|
|
145
|
-
});
|
|
146
|
-
|
|
147
|
-
it('uses custom redirect URI when provided', async () => {
|
|
148
|
-
const url = await sessionManager.getAuthorizationUrl({
|
|
149
|
-
redirectUri: 'https://example.com/auth/callback',
|
|
150
|
-
});
|
|
151
|
-
|
|
152
|
-
expect(url).toContain(
|
|
153
|
-
'redirect_uri=https%3A%2F%2Fexample.com%2Fauth%2Fcallback',
|
|
154
|
-
);
|
|
155
|
-
});
|
|
156
|
-
});
|
|
157
|
-
|
|
158
|
-
describe('createSession()', () => {
|
|
159
|
-
it('creates session from auth response', async () => {
|
|
160
|
-
const authResponse = {
|
|
161
|
-
accessToken: 'access-token',
|
|
162
|
-
refreshToken: 'refresh-token',
|
|
163
|
-
user: mockUser,
|
|
164
|
-
impersonator: undefined,
|
|
165
|
-
};
|
|
166
|
-
|
|
167
|
-
const result = await sessionManager.createSession(
|
|
168
|
-
authResponse,
|
|
169
|
-
'response',
|
|
170
|
-
);
|
|
171
|
-
|
|
172
|
-
expect(result.response).toBe('response');
|
|
173
|
-
});
|
|
174
|
-
|
|
175
|
-
it('throws error when tokens are missing', async () => {
|
|
176
|
-
const authResponse = {
|
|
177
|
-
accessToken: null,
|
|
178
|
-
refreshToken: 'refresh-token',
|
|
179
|
-
user: mockUser,
|
|
180
|
-
impersonator: undefined,
|
|
181
|
-
};
|
|
182
|
-
|
|
183
|
-
await expect(
|
|
184
|
-
sessionManager.createSession(authResponse as any, 'response'),
|
|
185
|
-
).rejects.toThrow(AuthKitError);
|
|
186
|
-
});
|
|
187
|
-
});
|
|
188
|
-
|
|
189
|
-
describe('refreshSession()', () => {
|
|
190
|
-
it('refreshes session with new tokens', async () => {
|
|
191
|
-
const session = {
|
|
192
|
-
accessToken: 'old-access-token',
|
|
193
|
-
refreshToken: 'old-refresh-token',
|
|
194
|
-
user: mockUser,
|
|
195
|
-
impersonator: undefined,
|
|
196
|
-
};
|
|
197
|
-
|
|
198
|
-
const result = await sessionManager.refreshSession(session);
|
|
199
|
-
|
|
200
|
-
expect(result.accessToken).toBe('new-access-token');
|
|
201
|
-
expect(result.session.refreshToken).toBe('new-refresh-token');
|
|
202
|
-
expect(result.sessionId).toBe('session_123');
|
|
203
|
-
});
|
|
204
|
-
|
|
205
|
-
it('throws TokenRefreshError on failure', async () => {
|
|
206
|
-
const failingClient = {
|
|
207
|
-
userManagement: {
|
|
208
|
-
authenticateWithRefreshToken: async () => {
|
|
209
|
-
throw new Error('Refresh failed');
|
|
210
|
-
},
|
|
211
|
-
},
|
|
212
|
-
};
|
|
213
|
-
|
|
214
|
-
const manager = new SessionManager(
|
|
215
|
-
mockConfig as any,
|
|
216
|
-
mockStorage as any,
|
|
217
|
-
mockTokenManager as any,
|
|
218
|
-
failingClient as any,
|
|
219
|
-
mockEncryption as any,
|
|
220
|
-
);
|
|
221
|
-
|
|
222
|
-
const session = {
|
|
223
|
-
accessToken: 'token',
|
|
224
|
-
refreshToken: 'refresh',
|
|
225
|
-
user: mockUser,
|
|
226
|
-
impersonator: undefined,
|
|
227
|
-
};
|
|
228
|
-
|
|
229
|
-
await expect(manager.refreshSession(session)).rejects.toThrow(
|
|
230
|
-
TokenRefreshError,
|
|
231
|
-
);
|
|
232
|
-
});
|
|
233
|
-
});
|
|
234
|
-
|
|
235
|
-
describe('terminateSession()', () => {
|
|
236
|
-
it('revokes session and returns logout URL', async () => {
|
|
237
|
-
const session = {
|
|
238
|
-
accessToken: 'access-token',
|
|
239
|
-
refreshToken: 'refresh-token',
|
|
240
|
-
user: mockUser,
|
|
241
|
-
impersonator: undefined,
|
|
242
|
-
};
|
|
243
|
-
|
|
244
|
-
const result = await sessionManager.terminateSession(session, 'response');
|
|
245
|
-
|
|
246
|
-
expect(result.response).toBe('response');
|
|
247
|
-
expect(result.logoutUrl).toContain('session_id=session_123');
|
|
248
|
-
});
|
|
249
|
-
|
|
250
|
-
it('includes return URL in logout URL when provided', async () => {
|
|
251
|
-
const session = {
|
|
252
|
-
accessToken: 'access-token',
|
|
253
|
-
refreshToken: 'refresh-token',
|
|
254
|
-
user: mockUser,
|
|
255
|
-
impersonator: undefined,
|
|
256
|
-
};
|
|
257
|
-
|
|
258
|
-
const result = await sessionManager.terminateSession(
|
|
259
|
-
session,
|
|
260
|
-
'response',
|
|
261
|
-
{
|
|
262
|
-
returnTo: 'https://example.com',
|
|
263
|
-
},
|
|
264
|
-
);
|
|
265
|
-
|
|
266
|
-
expect(result.logoutUrl).toContain('return_to=https://example.com');
|
|
267
|
-
});
|
|
268
|
-
});
|
|
269
|
-
|
|
270
|
-
describe('switchToOrganization()', () => {
|
|
271
|
-
it('switches organization and updates session', async () => {
|
|
272
|
-
const storageWithSession = {
|
|
273
|
-
...mockStorage,
|
|
274
|
-
getSession: async () => 'encrypted-session',
|
|
275
|
-
};
|
|
276
|
-
|
|
277
|
-
const manager = new SessionManager(
|
|
278
|
-
mockConfig as any,
|
|
279
|
-
storageWithSession as any,
|
|
280
|
-
mockTokenManager as any,
|
|
281
|
-
mockClient as any,
|
|
282
|
-
mockEncryption as any,
|
|
283
|
-
);
|
|
284
|
-
|
|
285
|
-
const result = await manager.switchToOrganization(
|
|
286
|
-
'request',
|
|
287
|
-
'response',
|
|
288
|
-
'org_456',
|
|
289
|
-
);
|
|
290
|
-
|
|
291
|
-
expect(result.response).toBe('response');
|
|
292
|
-
expect(result.authResult.user).toEqual(mockUser);
|
|
293
|
-
});
|
|
294
|
-
|
|
295
|
-
it('throws error when no session exists', async () => {
|
|
296
|
-
await expect(
|
|
297
|
-
sessionManager.switchToOrganization('request', 'response', 'org_456'),
|
|
298
|
-
).rejects.toThrow(AuthKitError);
|
|
299
|
-
});
|
|
300
|
-
});
|
|
301
|
-
|
|
302
|
-
describe('error handling', () => {
|
|
303
|
-
it('handles encryption failures', async () => {
|
|
304
|
-
const failingEncryption = {
|
|
305
|
-
sealData: async () => {
|
|
306
|
-
throw new Error('Encryption failed');
|
|
307
|
-
},
|
|
308
|
-
unsealData: async () => ({}),
|
|
309
|
-
};
|
|
310
|
-
|
|
311
|
-
const manager = new SessionManager(
|
|
312
|
-
mockConfig as any,
|
|
313
|
-
mockStorage as any,
|
|
314
|
-
mockTokenManager as any,
|
|
315
|
-
mockClient as any,
|
|
316
|
-
failingEncryption as any,
|
|
317
|
-
);
|
|
318
|
-
|
|
319
|
-
const session = {
|
|
320
|
-
accessToken: 'token',
|
|
321
|
-
refreshToken: 'refresh',
|
|
322
|
-
user: mockUser,
|
|
323
|
-
impersonator: undefined,
|
|
324
|
-
};
|
|
325
|
-
|
|
326
|
-
await expect(manager.createSession(session, 'response')).rejects.toThrow(
|
|
327
|
-
SessionEncryptionError,
|
|
328
|
-
);
|
|
329
|
-
});
|
|
330
|
-
|
|
331
|
-
it('handles decryption failures', async () => {
|
|
332
|
-
const storageWithSession = {
|
|
333
|
-
...mockStorage,
|
|
334
|
-
getSession: async () => 'invalid-encrypted-session',
|
|
335
|
-
};
|
|
336
|
-
|
|
337
|
-
const failingEncryption = {
|
|
338
|
-
sealData: async () => 'encrypted',
|
|
339
|
-
unsealData: async () => {
|
|
340
|
-
throw new Error('Decryption failed');
|
|
341
|
-
},
|
|
342
|
-
};
|
|
343
|
-
|
|
344
|
-
const manager = new SessionManager(
|
|
345
|
-
mockConfig as any,
|
|
346
|
-
storageWithSession as any,
|
|
347
|
-
mockTokenManager as any,
|
|
348
|
-
mockClient as any,
|
|
349
|
-
failingEncryption as any,
|
|
350
|
-
);
|
|
351
|
-
|
|
352
|
-
const result = await manager.withAuth('request');
|
|
353
|
-
|
|
354
|
-
expect(result.user).toBeNull();
|
|
355
|
-
});
|
|
356
|
-
});
|
|
357
|
-
});
|
|
@@ -1,357 +0,0 @@
|
|
|
1
|
-
import type { ConfigurationProvider } from '../config/ConfigurationProvider.js';
|
|
2
|
-
import {
|
|
3
|
-
AuthKitError,
|
|
4
|
-
SessionEncryptionError,
|
|
5
|
-
TokenRefreshError,
|
|
6
|
-
} from '../errors.js';
|
|
7
|
-
import type { AuthenticationResponse } from '../client/types.js';
|
|
8
|
-
import type { TokenManager } from './TokenManager.js';
|
|
9
|
-
import type {
|
|
10
|
-
AuthResult,
|
|
11
|
-
CustomClaims,
|
|
12
|
-
GetAuthorizationUrlOptions,
|
|
13
|
-
HeadersBag,
|
|
14
|
-
Session,
|
|
15
|
-
SessionStorage,
|
|
16
|
-
SessionEncryption,
|
|
17
|
-
} from './types.js';
|
|
18
|
-
import type { WorkOS } from '@workos-inc/node';
|
|
19
|
-
|
|
20
|
-
export class SessionManager<TRequest, TResponse> {
|
|
21
|
-
private readonly config: ConfigurationProvider;
|
|
22
|
-
private readonly storage: SessionStorage<TRequest, TResponse>;
|
|
23
|
-
private readonly tokenManager: TokenManager;
|
|
24
|
-
private readonly client: WorkOS;
|
|
25
|
-
private readonly encryption: SessionEncryption;
|
|
26
|
-
|
|
27
|
-
constructor(
|
|
28
|
-
config: ConfigurationProvider,
|
|
29
|
-
storage: SessionStorage<TRequest, TResponse>,
|
|
30
|
-
tokenManager: TokenManager,
|
|
31
|
-
client: WorkOS,
|
|
32
|
-
encryption: SessionEncryption,
|
|
33
|
-
) {
|
|
34
|
-
this.config = config;
|
|
35
|
-
this.storage = storage;
|
|
36
|
-
this.tokenManager = tokenManager;
|
|
37
|
-
this.client = client;
|
|
38
|
-
this.encryption = encryption;
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
private async encryptSession(session: Session): Promise<string> {
|
|
42
|
-
try {
|
|
43
|
-
const password = this.config.getValue('cookiePassword');
|
|
44
|
-
// const encryptedSession = await sealData(session, { password });
|
|
45
|
-
const encryptedSession = await this.encryption.sealData(session, {
|
|
46
|
-
password,
|
|
47
|
-
ttl: 0,
|
|
48
|
-
});
|
|
49
|
-
return encryptedSession;
|
|
50
|
-
} catch (error) {
|
|
51
|
-
throw new SessionEncryptionError('Failed to encrypt session', error);
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
private async decryptSession(encryptedSession: string): Promise<Session> {
|
|
56
|
-
try {
|
|
57
|
-
const password = this.config.getValue('cookiePassword');
|
|
58
|
-
const session = await this.encryption.unsealData<Session>(
|
|
59
|
-
encryptedSession,
|
|
60
|
-
{ password },
|
|
61
|
-
);
|
|
62
|
-
return session;
|
|
63
|
-
} catch (error) {
|
|
64
|
-
throw new SessionEncryptionError('Failed to decrypt session', error);
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
async getSession(request: TRequest): Promise<Session | null> {
|
|
69
|
-
const encryptedSession = await this.storage.getSession(request);
|
|
70
|
-
if (!encryptedSession) {
|
|
71
|
-
return null;
|
|
72
|
-
}
|
|
73
|
-
return this.decryptSession(encryptedSession);
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
private async validateSession<TCustomClaims = CustomClaims>(
|
|
77
|
-
encryptedSession: string,
|
|
78
|
-
) {
|
|
79
|
-
try {
|
|
80
|
-
const session = await this.decryptSession(encryptedSession);
|
|
81
|
-
const isValid = await this.tokenManager.verifyToken(session.accessToken);
|
|
82
|
-
const isExpiring = this.tokenManager.isTokenExpiring(session.accessToken);
|
|
83
|
-
|
|
84
|
-
// Token is valid and not expiring - return immediately
|
|
85
|
-
if (isValid && !isExpiring) {
|
|
86
|
-
const claims = this.tokenManager.parseTokenClaims<TCustomClaims>(
|
|
87
|
-
session.accessToken,
|
|
88
|
-
);
|
|
89
|
-
return {
|
|
90
|
-
valid: true,
|
|
91
|
-
session,
|
|
92
|
-
claims,
|
|
93
|
-
};
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
// Token needs refresh
|
|
97
|
-
try {
|
|
98
|
-
const refreshResult = await this.refreshSession<TCustomClaims>(session);
|
|
99
|
-
return {
|
|
100
|
-
valid: true,
|
|
101
|
-
session: refreshResult.session,
|
|
102
|
-
claims: refreshResult.claims,
|
|
103
|
-
};
|
|
104
|
-
} catch (refreshError) {
|
|
105
|
-
return {
|
|
106
|
-
valid: false,
|
|
107
|
-
error:
|
|
108
|
-
refreshError instanceof Error
|
|
109
|
-
? refreshError
|
|
110
|
-
: new TokenRefreshError(
|
|
111
|
-
'Failed to refresh session',
|
|
112
|
-
refreshError,
|
|
113
|
-
),
|
|
114
|
-
};
|
|
115
|
-
}
|
|
116
|
-
} catch (decryptError) {
|
|
117
|
-
return {
|
|
118
|
-
valid: false,
|
|
119
|
-
error:
|
|
120
|
-
decryptError instanceof Error
|
|
121
|
-
? decryptError
|
|
122
|
-
: new AuthKitError('Failed to decrypt session', decryptError),
|
|
123
|
-
};
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
async withAuth<TCustomClaims = CustomClaims>(
|
|
128
|
-
request: TRequest,
|
|
129
|
-
): Promise<AuthResult<TCustomClaims>> {
|
|
130
|
-
const encryptedSession = await this.storage.getSession(request);
|
|
131
|
-
|
|
132
|
-
if (!encryptedSession) {
|
|
133
|
-
return { user: null };
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
const { valid, session, claims } =
|
|
137
|
-
await this.validateSession<TCustomClaims>(encryptedSession);
|
|
138
|
-
|
|
139
|
-
if (!valid || !session || !claims) {
|
|
140
|
-
return { user: null };
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
return {
|
|
144
|
-
user: session.user,
|
|
145
|
-
sessionId: claims.sid,
|
|
146
|
-
impersonator: session.impersonator,
|
|
147
|
-
accessToken: session.accessToken,
|
|
148
|
-
refreshToken: session.refreshToken, // TODO should this be here?
|
|
149
|
-
claims,
|
|
150
|
-
};
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
async refreshSession<TCustomClaims = CustomClaims>(
|
|
154
|
-
session: Session,
|
|
155
|
-
organizationId?: string,
|
|
156
|
-
) {
|
|
157
|
-
try {
|
|
158
|
-
const currentClaims = this.tokenManager.parseTokenClaims(
|
|
159
|
-
session.accessToken,
|
|
160
|
-
);
|
|
161
|
-
const refreshResponse =
|
|
162
|
-
await this.client.userManagement.authenticateWithRefreshToken({
|
|
163
|
-
refreshToken: session.refreshToken,
|
|
164
|
-
clientId: this.config.getValue('clientId'),
|
|
165
|
-
organizationId: organizationId ?? currentClaims.org_id,
|
|
166
|
-
});
|
|
167
|
-
|
|
168
|
-
const newSession: Session = {
|
|
169
|
-
accessToken: refreshResponse.accessToken,
|
|
170
|
-
refreshToken: refreshResponse.refreshToken,
|
|
171
|
-
user: refreshResponse.user,
|
|
172
|
-
impersonator: refreshResponse.impersonator,
|
|
173
|
-
};
|
|
174
|
-
|
|
175
|
-
const sessionData = await this.encryptSession(newSession);
|
|
176
|
-
|
|
177
|
-
const claims = this.tokenManager.parseTokenClaims<TCustomClaims>(
|
|
178
|
-
newSession.accessToken,
|
|
179
|
-
);
|
|
180
|
-
|
|
181
|
-
return {
|
|
182
|
-
user: newSession.user,
|
|
183
|
-
sessionId: claims.sid,
|
|
184
|
-
organizationId: claims.org_id,
|
|
185
|
-
role: claims.role,
|
|
186
|
-
roles: claims.roles,
|
|
187
|
-
permissions: claims.permissions,
|
|
188
|
-
entitlements: claims.entitlements,
|
|
189
|
-
impersonator: newSession.impersonator,
|
|
190
|
-
accessToken: newSession.accessToken,
|
|
191
|
-
claims,
|
|
192
|
-
sessionData,
|
|
193
|
-
session: newSession,
|
|
194
|
-
};
|
|
195
|
-
} catch (error) {
|
|
196
|
-
throw new TokenRefreshError('Failed to refresh session', error);
|
|
197
|
-
}
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
async getAuthorizationUrl({
|
|
201
|
-
returnPathname,
|
|
202
|
-
redirectUri,
|
|
203
|
-
screenHint,
|
|
204
|
-
organizationId,
|
|
205
|
-
loginHint,
|
|
206
|
-
prompt,
|
|
207
|
-
}: GetAuthorizationUrlOptions = {}): Promise<string> {
|
|
208
|
-
return this.client.userManagement.getAuthorizationUrl({
|
|
209
|
-
provider: 'authkit',
|
|
210
|
-
redirectUri: redirectUri ?? this.config.getValue('redirectUri'),
|
|
211
|
-
screenHint,
|
|
212
|
-
organizationId,
|
|
213
|
-
loginHint,
|
|
214
|
-
prompt,
|
|
215
|
-
clientId: this.config.getValue('clientId'),
|
|
216
|
-
state: returnPathname
|
|
217
|
-
? btoa(JSON.stringify({ returnPathname }))
|
|
218
|
-
: undefined,
|
|
219
|
-
});
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
async createSession(
|
|
223
|
-
authResponse: AuthenticationResponse,
|
|
224
|
-
response: TResponse | undefined,
|
|
225
|
-
): Promise<{ response?: TResponse; headers?: HeadersBag }> {
|
|
226
|
-
const { accessToken, refreshToken, user, impersonator } = authResponse;
|
|
227
|
-
if (!accessToken || !refreshToken) {
|
|
228
|
-
throw new AuthKitError('Missing access or refresh token');
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
const session: Session = {
|
|
232
|
-
accessToken,
|
|
233
|
-
refreshToken,
|
|
234
|
-
user,
|
|
235
|
-
impersonator,
|
|
236
|
-
};
|
|
237
|
-
|
|
238
|
-
const encryptedSession = await this.encryptSession(session);
|
|
239
|
-
|
|
240
|
-
// Save to response
|
|
241
|
-
return this.storage.saveSession(response, encryptedSession);
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
async switchToOrganization<TCustomClaims = CustomClaims>(
|
|
245
|
-
request: TRequest,
|
|
246
|
-
response: TResponse,
|
|
247
|
-
organizationId: string,
|
|
248
|
-
): Promise<{
|
|
249
|
-
response?: TResponse;
|
|
250
|
-
headers?: HeadersBag;
|
|
251
|
-
authResult: AuthResult<TCustomClaims>;
|
|
252
|
-
}> {
|
|
253
|
-
const session = await this.getSession(request);
|
|
254
|
-
|
|
255
|
-
if (!session) {
|
|
256
|
-
throw new AuthKitError('No active session to switch organization');
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
try {
|
|
260
|
-
const refreshResult = await this.refreshSession<TCustomClaims>(
|
|
261
|
-
session,
|
|
262
|
-
organizationId,
|
|
263
|
-
);
|
|
264
|
-
|
|
265
|
-
// Save the new session
|
|
266
|
-
const updatedResponse = await this.storage.saveSession(
|
|
267
|
-
response,
|
|
268
|
-
refreshResult.sessionData,
|
|
269
|
-
);
|
|
270
|
-
|
|
271
|
-
return {
|
|
272
|
-
response: updatedResponse.response,
|
|
273
|
-
headers: updatedResponse.headers,
|
|
274
|
-
authResult: {
|
|
275
|
-
user: refreshResult.user,
|
|
276
|
-
sessionId: refreshResult.sessionId,
|
|
277
|
-
impersonator: refreshResult.impersonator,
|
|
278
|
-
accessToken: refreshResult.accessToken,
|
|
279
|
-
refreshToken: refreshResult.session.refreshToken,
|
|
280
|
-
claims: refreshResult.claims,
|
|
281
|
-
},
|
|
282
|
-
};
|
|
283
|
-
} catch (error: any) {
|
|
284
|
-
throw await this.handleSwitchOrganizationError(error, organizationId);
|
|
285
|
-
}
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
private async handleSwitchOrganizationError(
|
|
289
|
-
error: any,
|
|
290
|
-
organizationId: string,
|
|
291
|
-
): Promise<AuthKitError> {
|
|
292
|
-
const errorCodeToMessage = {
|
|
293
|
-
sso_required: `SSO required for organization ${organizationId}`,
|
|
294
|
-
mfa_enrollment: `MFA enrollment required for organization ${organizationId}`,
|
|
295
|
-
};
|
|
296
|
-
|
|
297
|
-
const errorMessage =
|
|
298
|
-
errorCodeToMessage[error?.code as keyof typeof errorCodeToMessage];
|
|
299
|
-
|
|
300
|
-
if (errorMessage) {
|
|
301
|
-
const authUrl = await this.getAuthorizationUrl({
|
|
302
|
-
redirectUri: this.config.getValue('redirectUri'),
|
|
303
|
-
});
|
|
304
|
-
return new AuthKitError(errorMessage, error, { authUrl });
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
if (error?.authkit_redirect_url) {
|
|
308
|
-
return new AuthKitError(
|
|
309
|
-
'Organization switch requires authentication',
|
|
310
|
-
error,
|
|
311
|
-
{ authUrl: error.authkit_redirect_url },
|
|
312
|
-
);
|
|
313
|
-
}
|
|
314
|
-
|
|
315
|
-
return new AuthKitError(
|
|
316
|
-
`Failed to switch to organization ${organizationId}`,
|
|
317
|
-
error,
|
|
318
|
-
);
|
|
319
|
-
}
|
|
320
|
-
|
|
321
|
-
async terminateSession(
|
|
322
|
-
session: Session,
|
|
323
|
-
response: TResponse,
|
|
324
|
-
options?: { returnTo?: string },
|
|
325
|
-
): Promise<{
|
|
326
|
-
response?: TResponse;
|
|
327
|
-
headers?: HeadersBag;
|
|
328
|
-
logoutUrl: string;
|
|
329
|
-
}> {
|
|
330
|
-
const claims = this.tokenManager.parseTokenClaims(session.accessToken);
|
|
331
|
-
|
|
332
|
-
// Revoke the session on WorkOS side
|
|
333
|
-
try {
|
|
334
|
-
await this.client.userManagement.revokeSession({
|
|
335
|
-
sessionId: claims.sid,
|
|
336
|
-
});
|
|
337
|
-
} catch (error) {
|
|
338
|
-
console.error('Failed to revoke session on WorkOS:', error);
|
|
339
|
-
// Continue with local logout even if remote revocation fails
|
|
340
|
-
}
|
|
341
|
-
|
|
342
|
-
// Clear the session cookie locally
|
|
343
|
-
const cleared = await this.storage.clearSession(response);
|
|
344
|
-
|
|
345
|
-
// Generate logout URL (for completeness, though session is already revoked)
|
|
346
|
-
const logoutUrl = this.client.userManagement.getLogoutUrl({
|
|
347
|
-
sessionId: claims.sid,
|
|
348
|
-
returnTo: options?.returnTo,
|
|
349
|
-
});
|
|
350
|
-
|
|
351
|
-
return {
|
|
352
|
-
response: cleared.response,
|
|
353
|
-
headers: cleared.headers,
|
|
354
|
-
logoutUrl,
|
|
355
|
-
};
|
|
356
|
-
}
|
|
357
|
-
}
|