@workos/authkit-session 0.1.3 → 0.2.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 (53) hide show
  1. package/README.md +144 -554
  2. package/dist/core/AuthKitCore.d.ts +109 -0
  3. package/dist/core/AuthKitCore.d.ts.map +1 -0
  4. package/dist/core/AuthKitCore.js +190 -0
  5. package/dist/core/AuthKitCore.js.map +1 -0
  6. package/dist/core/session/CookieSessionStorage.d.ts +2 -3
  7. package/dist/core/session/CookieSessionStorage.d.ts.map +1 -1
  8. package/dist/core/session/CookieSessionStorage.js +22 -9
  9. package/dist/core/session/CookieSessionStorage.js.map +1 -1
  10. package/dist/core/session/types.d.ts +35 -7
  11. package/dist/core/session/types.d.ts.map +1 -1
  12. package/dist/index.d.ts +28 -4
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +49 -4
  15. package/dist/index.js.map +1 -1
  16. package/dist/operations/AuthOperations.d.ts +83 -0
  17. package/dist/operations/AuthOperations.d.ts.map +1 -0
  18. package/dist/operations/AuthOperations.js +137 -0
  19. package/dist/operations/AuthOperations.js.map +1 -0
  20. package/dist/service/AuthService.d.ts +137 -0
  21. package/dist/service/AuthService.d.ts.map +1 -0
  22. package/dist/service/AuthService.js +224 -0
  23. package/dist/service/AuthService.js.map +1 -0
  24. package/dist/service/factory.d.ts +37 -0
  25. package/dist/service/factory.d.ts.map +1 -0
  26. package/dist/service/factory.js +60 -0
  27. package/dist/service/factory.js.map +1 -0
  28. package/package.json +6 -6
  29. package/src/core/AuthKitCore.spec.ts +262 -0
  30. package/src/core/AuthKitCore.ts +243 -0
  31. package/src/core/config/ConfigurationProvider.spec.ts +1 -0
  32. package/src/core/session/CookieSessionStorage.spec.ts +64 -58
  33. package/src/core/session/CookieSessionStorage.ts +27 -10
  34. package/src/core/session/types.ts +38 -8
  35. package/src/index.ts +56 -4
  36. package/src/operations/AuthOperations.spec.ts +299 -0
  37. package/src/operations/AuthOperations.ts +179 -0
  38. package/src/service/AuthService.spec.ts +267 -0
  39. package/src/service/AuthService.ts +288 -0
  40. package/src/service/factory.spec.ts +120 -0
  41. package/src/service/factory.ts +82 -0
  42. package/dist/core/createAuthKitFactory.d.ts +0 -64
  43. package/dist/core/createAuthKitFactory.d.ts.map +0 -1
  44. package/dist/core/createAuthKitFactory.js +0 -95
  45. package/dist/core/createAuthKitFactory.js.map +0 -1
  46. package/dist/core/session/SessionManager.d.ts +0 -51
  47. package/dist/core/session/SessionManager.d.ts.map +0 -1
  48. package/dist/core/session/SessionManager.js +0 -238
  49. package/dist/core/session/SessionManager.js.map +0 -1
  50. package/src/core/createAuthKitFactory.spec.ts +0 -161
  51. package/src/core/createAuthKitFactory.ts +0 -195
  52. package/src/core/session/SessionManager.spec.ts +0 -357
  53. package/src/core/session/SessionManager.ts +0 -357
@@ -0,0 +1,179 @@
1
+ import type { WorkOS } from '@workos-inc/node';
2
+ import type { AuthKitCore } from '../core/AuthKitCore.js';
3
+ import type { AuthKitConfig } from '../core/config/types.js';
4
+ import type {
5
+ AuthResult,
6
+ GetAuthorizationUrlOptions,
7
+ Session,
8
+ } from '../core/session/types.js';
9
+
10
+ /**
11
+ * AuthOperations provides high-level authentication operations.
12
+ *
13
+ * This class orchestrates between AuthKitCore (pure logic) and WorkOS API.
14
+ * It doesn't know about requests, responses, or cookies - that's the framework's job.
15
+ *
16
+ * Responsibilities:
17
+ * - Sign out (generate logout URL + clear cookie header)
18
+ * - Switch organization (refresh with new org + return auth result)
19
+ * - Refresh session (refresh tokens + return auth result)
20
+ * - Get authorization URLs (for sign in/sign up flows)
21
+ */
22
+ export class AuthOperations {
23
+ private core: AuthKitCore;
24
+ private client: WorkOS;
25
+ private config: AuthKitConfig;
26
+
27
+ constructor(core: AuthKitCore, client: WorkOS, config: AuthKitConfig) {
28
+ this.core = core;
29
+ this.client = client;
30
+ this.config = config;
31
+ }
32
+
33
+ /**
34
+ * Get the WorkOS logout URL.
35
+ *
36
+ * This only handles the WorkOS API part. Session clearing is handled
37
+ * by the storage layer in AuthService.
38
+ *
39
+ * @param sessionId - The session ID to terminate
40
+ * @param options - Optional return URL
41
+ * @returns Logout URL
42
+ */
43
+ getLogoutUrl(sessionId: string, options?: { returnTo?: string }): string {
44
+ return this.client.userManagement.getLogoutUrl({
45
+ sessionId,
46
+ returnTo: options?.returnTo,
47
+ });
48
+ }
49
+
50
+ /**
51
+ * Switch to a different organization.
52
+ *
53
+ * This is a convenience wrapper around refreshSession() that enforces
54
+ * an organization ID must be provided.
55
+ *
56
+ * @param session - Current session
57
+ * @param organizationId - Organization ID to switch to (required)
58
+ * @returns Auth result and encrypted session data
59
+ */
60
+ async switchOrganization(
61
+ session: Session,
62
+ organizationId: string,
63
+ ): Promise<{
64
+ auth: AuthResult;
65
+ encryptedSession: string;
66
+ }> {
67
+ // Delegate to refreshSession with explicit organization
68
+ return this.refreshSession(session, organizationId);
69
+ }
70
+
71
+ /**
72
+ * Refresh session operation.
73
+ *
74
+ * Forces a token refresh (for org switching or manual refresh),
75
+ * encrypts the new session, and returns the auth result.
76
+ *
77
+ * @param session - Current session with refresh token
78
+ * @param organizationId - Optional organization ID to switch to during refresh
79
+ * @returns Auth result and encrypted session data
80
+ */
81
+ async refreshSession(
82
+ session: Session,
83
+ organizationId?: string,
84
+ ): Promise<{
85
+ auth: AuthResult;
86
+ encryptedSession: string;
87
+ }> {
88
+ // Force refresh via core, optionally switching organizations
89
+ const { session: newSession, claims } = await this.core.validateAndRefresh(
90
+ session,
91
+ { force: true, organizationId },
92
+ );
93
+
94
+ const encryptedSession = await this.core.encryptSession(newSession);
95
+
96
+ const auth: AuthResult = {
97
+ user: newSession.user,
98
+ sessionId: claims.sid,
99
+ impersonator: newSession.impersonator,
100
+ accessToken: newSession.accessToken,
101
+ refreshToken: newSession.refreshToken,
102
+ claims,
103
+ organizationId: claims.org_id,
104
+ role: claims.role,
105
+ roles: claims.roles,
106
+ permissions: claims.permissions,
107
+ entitlements: claims.entitlements,
108
+ featureFlags: claims.feature_flags,
109
+ };
110
+
111
+ return {
112
+ auth,
113
+ encryptedSession,
114
+ };
115
+ }
116
+
117
+ /**
118
+ * Get authorization URL for WorkOS authentication.
119
+ *
120
+ * State encoding format: `{internal}.{userState}` where internal is URL-safe
121
+ * base64 encoded JSON containing returnPathname. This allows customers to
122
+ * pass their own state through the OAuth flow.
123
+ *
124
+ * @param options - Authorization URL options (returnPathname, screenHint, state, etc.)
125
+ * @returns The authorization URL
126
+ */
127
+ async getAuthorizationUrl(
128
+ options: GetAuthorizationUrlOptions = {},
129
+ ): Promise<string> {
130
+ // Build the combined state parameter (matches authkit-nextjs format)
131
+ const internalState = options.returnPathname
132
+ ? btoa(JSON.stringify({ returnPathname: options.returnPathname }))
133
+ .replace(/\+/g, '-')
134
+ .replace(/\//g, '_')
135
+ : null;
136
+
137
+ // If both internal and custom state, combine as internal.custom
138
+ // Otherwise use whichever is provided
139
+ const state =
140
+ internalState && options.state
141
+ ? `${internalState}.${options.state}`
142
+ : internalState || options.state || undefined;
143
+
144
+ return this.client.userManagement.getAuthorizationUrl({
145
+ provider: 'authkit',
146
+ redirectUri: options.redirectUri ?? this.config.redirectUri,
147
+ screenHint: options.screenHint,
148
+ organizationId: options.organizationId,
149
+ loginHint: options.loginHint,
150
+ prompt: options.prompt,
151
+ clientId: this.config.clientId,
152
+ state,
153
+ });
154
+ }
155
+
156
+ /**
157
+ * Convenience method: Get sign-in URL.
158
+ */
159
+ async getSignInUrl(
160
+ options: Omit<GetAuthorizationUrlOptions, 'screenHint'> = {},
161
+ ): Promise<string> {
162
+ return this.getAuthorizationUrl({
163
+ ...options,
164
+ screenHint: 'sign-in',
165
+ });
166
+ }
167
+
168
+ /**
169
+ * Convenience method: Get sign-up URL.
170
+ */
171
+ async getSignUpUrl(
172
+ options: Omit<GetAuthorizationUrlOptions, 'screenHint'> = {},
173
+ ): Promise<string> {
174
+ return this.getAuthorizationUrl({
175
+ ...options,
176
+ screenHint: 'sign-up',
177
+ });
178
+ }
179
+ }
@@ -0,0 +1,267 @@
1
+ import { AuthService } from './AuthService.js';
2
+
3
+ const mockConfig = {
4
+ clientId: 'test-client-id',
5
+ apiKey: 'test-api-key',
6
+ redirectUri: 'http://localhost:3000/callback',
7
+ cookiePassword: 'test-password-that-is-32-chars-long!!',
8
+ cookieName: 'wos-session',
9
+ };
10
+
11
+ const mockUser = {
12
+ id: 'user_123',
13
+ email: 'test@example.com',
14
+ object: 'user',
15
+ firstName: 'Test',
16
+ lastName: 'User',
17
+ emailVerified: true,
18
+ profilePictureUrl: null,
19
+ createdAt: '2023-01-01T00:00:00Z',
20
+ updatedAt: '2023-01-01T00:00:00Z',
21
+ lastSignInAt: '2023-01-01T00:00:00Z',
22
+ externalId: null,
23
+ metadata: {},
24
+ } as const;
25
+
26
+ const mockStorage = {
27
+ getSession: async () => 'encrypted-session-data',
28
+ saveSession: async () => ({ response: 'updated-response' }),
29
+ clearSession: async () => ({
30
+ response: 'cleared-response',
31
+ headers: { 'Set-Cookie': 'wos-session=; Path=/; Max-Age=0' },
32
+ }),
33
+ };
34
+
35
+ const mockClient = {
36
+ userManagement: {
37
+ getJwksUrl: () => 'https://api.workos.com/sso/jwks/test-client-id',
38
+ getAuthorizationUrl: ({ screenHint }: any) =>
39
+ `https://api.workos.com/sso/authorize?screen_hint=${screenHint || ''}`,
40
+ authenticateWithCode: async ({ code }: any) => ({
41
+ accessToken: `access-${code}`,
42
+ refreshToken: `refresh-${code}`,
43
+ user: mockUser,
44
+ impersonator: undefined,
45
+ }),
46
+ getLogoutUrl: ({ sessionId }: any) =>
47
+ `https://api.workos.com/sso/logout?session_id=${sessionId}`,
48
+ },
49
+ };
50
+
51
+ const mockEncryption = {
52
+ sealData: async () => 'encrypted-session-data',
53
+ unsealData: async () => ({
54
+ accessToken: 'test-access-token',
55
+ refreshToken: 'test-refresh-token',
56
+ user: mockUser,
57
+ impersonator: undefined,
58
+ }),
59
+ };
60
+
61
+ describe('AuthService', () => {
62
+ let service: AuthService<any, any>;
63
+
64
+ beforeEach(() => {
65
+ service = new AuthService(
66
+ mockConfig as any,
67
+ mockStorage as any,
68
+ mockClient as any,
69
+ mockEncryption as any,
70
+ );
71
+ });
72
+
73
+ describe('constructor', () => {
74
+ it('creates instance with required dependencies', () => {
75
+ expect(service).toBeInstanceOf(AuthService);
76
+ });
77
+ });
78
+
79
+ describe('withAuth()', () => {
80
+ it('returns null user when no session exists', async () => {
81
+ const emptyStorage = {
82
+ ...mockStorage,
83
+ getSession: async () => null,
84
+ };
85
+ const testService = new AuthService(
86
+ mockConfig as any,
87
+ emptyStorage as any,
88
+ mockClient as any,
89
+ mockEncryption as any,
90
+ );
91
+
92
+ const result = await testService.withAuth('request');
93
+
94
+ expect(result.auth.user).toBeNull();
95
+ expect(result.refreshedSessionData).toBeUndefined();
96
+ });
97
+
98
+ it('returns null user on decryption error', async () => {
99
+ const failingEncryption = {
100
+ sealData: async () => 'encrypted',
101
+ unsealData: async () => {
102
+ throw new Error('Decryption failed');
103
+ },
104
+ };
105
+ const testService = new AuthService(
106
+ mockConfig as any,
107
+ mockStorage as any,
108
+ mockClient as any,
109
+ failingEncryption as any,
110
+ );
111
+
112
+ const result = await testService.withAuth('request');
113
+
114
+ expect(result.auth.user).toBeNull();
115
+ });
116
+ });
117
+
118
+ describe('getSession()', () => {
119
+ it('returns decrypted session', async () => {
120
+ const result = await service.getSession('request');
121
+
122
+ expect(result).toBeDefined();
123
+ expect(result?.user).toEqual(mockUser);
124
+ });
125
+
126
+ it('returns null when no session exists', async () => {
127
+ const emptyStorage = {
128
+ ...mockStorage,
129
+ getSession: async () => null,
130
+ };
131
+ const testService = new AuthService(
132
+ mockConfig as any,
133
+ emptyStorage as any,
134
+ mockClient as any,
135
+ mockEncryption as any,
136
+ );
137
+
138
+ const result = await testService.getSession('request');
139
+
140
+ expect(result).toBeNull();
141
+ });
142
+ });
143
+
144
+ describe('saveSession()', () => {
145
+ it('delegates to storage', async () => {
146
+ const result = await service.saveSession('response', 'session-data');
147
+
148
+ expect(result.response).toBe('updated-response');
149
+ });
150
+ });
151
+
152
+ describe('clearSession()', () => {
153
+ it('delegates to storage', async () => {
154
+ const result = await service.clearSession('response');
155
+
156
+ expect(result.response).toBe('cleared-response');
157
+ });
158
+ });
159
+
160
+ describe('signOut()', () => {
161
+ it('returns logout URL and headers from storage', async () => {
162
+ const result = await service.signOut('session_123');
163
+
164
+ expect(result.logoutUrl).toContain('session_id=session_123');
165
+ expect(result.headers).toBeDefined();
166
+ expect(result.headers?.['Set-Cookie']).toContain('wos-session=');
167
+ });
168
+ });
169
+
170
+ describe('getAuthorizationUrl()', () => {
171
+ it('delegates to operations', async () => {
172
+ const result = await service.getAuthorizationUrl();
173
+
174
+ expect(result).toContain('authorize');
175
+ });
176
+ });
177
+
178
+ describe('getSignInUrl()', () => {
179
+ it('returns sign-in URL', async () => {
180
+ const result = await service.getSignInUrl();
181
+
182
+ expect(result).toContain('screen_hint=sign-in');
183
+ });
184
+ });
185
+
186
+ describe('getSignUpUrl()', () => {
187
+ it('returns sign-up URL', async () => {
188
+ const result = await service.getSignUpUrl();
189
+
190
+ expect(result).toContain('screen_hint=sign-up');
191
+ });
192
+ });
193
+
194
+ describe('getWorkOS()', () => {
195
+ it('returns WorkOS client', () => {
196
+ const result = service.getWorkOS();
197
+
198
+ expect(result).toBe(mockClient);
199
+ });
200
+ });
201
+
202
+ describe('handleCallback()', () => {
203
+ it('authenticates and creates session', async () => {
204
+ const result = await service.handleCallback('request', 'response', {
205
+ code: 'auth-code-123',
206
+ });
207
+
208
+ expect(result.authResponse.accessToken).toBe('access-auth-code-123');
209
+ expect(result.returnPathname).toBe('/');
210
+ expect(result.response).toBe('updated-response');
211
+ });
212
+
213
+ it('decodes returnPathname from state', async () => {
214
+ const state = btoa(JSON.stringify({ returnPathname: '/dashboard' }));
215
+
216
+ const result = await service.handleCallback('request', 'response', {
217
+ code: 'auth-code-123',
218
+ state,
219
+ });
220
+
221
+ expect(result.returnPathname).toBe('/dashboard');
222
+ });
223
+
224
+ it('treats invalid state as custom state', async () => {
225
+ const result = await service.handleCallback('request', 'response', {
226
+ code: 'auth-code-123',
227
+ state: 'invalid-state',
228
+ });
229
+
230
+ expect(result.returnPathname).toBe('/');
231
+ expect(result.state).toBe('invalid-state');
232
+ });
233
+
234
+ it('parses new format with internal.userState', async () => {
235
+ // Create URL-safe base64 internal state
236
+ const internal = btoa(JSON.stringify({ returnPathname: '/profile' }))
237
+ .replace(/\+/g, '-')
238
+ .replace(/\//g, '_')
239
+ .replace(/=+$/, '');
240
+ const state = `${internal}.my-custom-state`;
241
+
242
+ const result = await service.handleCallback('request', 'response', {
243
+ code: 'auth-code-123',
244
+ state,
245
+ });
246
+
247
+ expect(result.returnPathname).toBe('/profile');
248
+ expect(result.state).toBe('my-custom-state');
249
+ });
250
+
251
+ it('handles user state with dots', async () => {
252
+ const internal = btoa(JSON.stringify({ returnPathname: '/dashboard' }))
253
+ .replace(/\+/g, '-')
254
+ .replace(/\//g, '_')
255
+ .replace(/=+$/, '');
256
+ const state = `${internal}.user.state.with.dots`;
257
+
258
+ const result = await service.handleCallback('request', 'response', {
259
+ code: 'auth-code-123',
260
+ state,
261
+ });
262
+
263
+ expect(result.returnPathname).toBe('/dashboard');
264
+ expect(result.state).toBe('user.state.with.dots');
265
+ });
266
+ });
267
+ });