@workos/authkit-session 0.2.0-beta.0 → 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 (40) hide show
  1. package/README.md +96 -781
  2. package/dist/core/AuthKitCore.d.ts +11 -9
  3. package/dist/core/AuthKitCore.d.ts.map +1 -1
  4. package/dist/core/AuthKitCore.js +20 -19
  5. package/dist/core/AuthKitCore.js.map +1 -1
  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 +14 -20
  9. package/dist/core/session/CookieSessionStorage.js.map +1 -1
  10. package/dist/core/session/types.d.ts +8 -0
  11. package/dist/core/session/types.d.ts.map +1 -1
  12. package/dist/index.d.ts +17 -16
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +25 -24
  15. package/dist/index.js.map +1 -1
  16. package/dist/operations/AuthOperations.d.ts +13 -14
  17. package/dist/operations/AuthOperations.d.ts.map +1 -1
  18. package/dist/operations/AuthOperations.js +37 -47
  19. package/dist/operations/AuthOperations.js.map +1 -1
  20. package/dist/service/AuthService.d.ts +22 -41
  21. package/dist/service/AuthService.d.ts.map +1 -1
  22. package/dist/service/AuthService.js +64 -65
  23. package/dist/service/AuthService.js.map +1 -1
  24. package/dist/service/factory.d.ts.map +1 -1
  25. package/dist/service/factory.js +24 -10
  26. package/dist/service/factory.js.map +1 -1
  27. package/package.json +2 -2
  28. package/src/core/AuthKitCore.spec.ts +12 -19
  29. package/src/core/AuthKitCore.ts +26 -22
  30. package/src/core/config/ConfigurationProvider.spec.ts +1 -0
  31. package/src/core/session/CookieSessionStorage.spec.ts +51 -62
  32. package/src/core/session/CookieSessionStorage.ts +19 -22
  33. package/src/core/session/types.ts +8 -0
  34. package/src/index.ts +26 -25
  35. package/src/operations/AuthOperations.spec.ts +128 -69
  36. package/src/operations/AuthOperations.ts +53 -66
  37. package/src/service/AuthService.spec.ts +66 -40
  38. package/src/service/AuthService.ts +77 -82
  39. package/src/service/factory.spec.ts +20 -9
  40. package/src/service/factory.ts +33 -20
@@ -1,6 +1,5 @@
1
1
  import type { WorkOS } from '@workos-inc/node';
2
2
  import { AuthKitCore } from '../core/AuthKitCore.js';
3
- import type { ConfigurationProvider } from '../core/config/ConfigurationProvider.js';
4
3
  import type { AuthKitConfig } from '../core/config/types.js';
5
4
  import { AuthOperations } from '../operations/AuthOperations.js';
6
5
  import type {
@@ -14,86 +13,38 @@ import type {
14
13
  } from '../core/session/types.js';
15
14
 
16
15
  /**
17
- * AuthService is a REFERENCE IMPLEMENTATION for framework adapters.
16
+ * Framework-agnostic authentication service.
18
17
  *
19
- * **IMPORTANT:** This class is optional. Framework adapters can use AuthKitCore,
20
- * AuthOperations, and CookieSessionStorage directly to implement their own patterns.
21
- *
22
- * This class provides a pattern for coordinating between:
18
+ * Coordinates between:
23
19
  * - AuthKitCore (pure business logic: crypto, JWT, refresh)
24
20
  * - AuthOperations (WorkOS API operations: signOut, refreshSession, URLs)
25
21
  * - SessionStorage<TRequest, TResponse> (framework-specific storage)
26
22
  *
27
- * **Why this is optional:**
28
- * - Frameworks have different middleware/route patterns (Next.js vs TanStack vs Remix)
29
- * - Request context handling differs by framework (headers vs locals vs WeakMap)
30
- * - Framework-specific features (callbacks, eagerAuth) don't fit generic patterns
31
- *
32
- * **Recommended usage:**
33
- * - Use AuthKitCore directly for crypto, token validation, and refresh logic
34
- * - Use AuthOperations for WorkOS API calls (refreshSession, signOut, URLs)
35
- * - Use CookieSessionStorage.buildSetCookie() for cookie string generation
36
- * - Implement your own updateSession/withAuth patterns that fit your framework
37
- *
38
- * **See also:**
39
- * - authkit-nextjs: Uses Core + Operations directly, implements Next.js patterns
40
- * - authkit-tanstack-start: Uses Core + Operations, implements TanStack patterns
23
+ * Provides common patterns:
24
+ * - `withAuth()` - Validate session with auto-refresh
25
+ * - `handleCallback()` - Process OAuth callback
26
+ * - `signOut()`, `getSignInUrl()`, etc. - Delegate to AuthOperations
41
27
  *
42
- * **Lazy initialization:**
43
- * This class uses lazy initialization via private getters, which allows
44
- * configuration to be set AFTER instantiation but BEFORE first use.
45
- * This pattern may be useful for your framework adapter.
28
+ * **Used by:** @workos/authkit-tanstack-react-start
46
29
  */
47
30
  export class AuthService<TRequest, TResponse> {
48
- private _core?: AuthKitCore;
49
- private _operations?: AuthOperations;
31
+ private readonly core: AuthKitCore;
32
+ private readonly operations: AuthOperations;
50
33
  private readonly storage: SessionStorage<TRequest, TResponse>;
51
- private readonly config: ConfigurationProvider;
52
- private readonly clientFactory: (config: AuthKitConfig) => WorkOS;
53
- private readonly encryptionFactory: (config: AuthKitConfig) => SessionEncryption;
34
+ private readonly config: AuthKitConfig;
35
+ private readonly client: WorkOS;
54
36
 
55
37
  constructor(
56
- config: ConfigurationProvider,
38
+ config: AuthKitConfig,
57
39
  storage: SessionStorage<TRequest, TResponse>,
58
- clientFactory: (config: AuthKitConfig) => WorkOS,
59
- encryptionFactory: (config: AuthKitConfig) => SessionEncryption,
40
+ client: WorkOS,
41
+ encryption: SessionEncryption,
60
42
  ) {
61
43
  this.config = config;
62
44
  this.storage = storage;
63
- this.clientFactory = clientFactory;
64
- this.encryptionFactory = encryptionFactory;
65
- // NOTE: core and operations are NOT instantiated here
66
- // They're created lazily on first access via getters below
67
- }
68
-
69
- /**
70
- * Lazy getter for AuthKitCore.
71
- * Instantiates on first access, allowing config to be set beforehand.
72
- */
73
- private get core(): AuthKitCore {
74
- if (!this._core) {
75
- this._core = new AuthKitCore(
76
- this.config,
77
- this.clientFactory(this.config.getConfig()),
78
- this.encryptionFactory(this.config.getConfig()),
79
- );
80
- }
81
- return this._core;
82
- }
83
-
84
- /**
85
- * Lazy getter for AuthOperations.
86
- * Instantiates on first access, allowing config to be set beforehand.
87
- */
88
- private get operations(): AuthOperations {
89
- if (!this._operations) {
90
- this._operations = new AuthOperations(
91
- this.core,
92
- this.clientFactory(this.config.getConfig()),
93
- this.config,
94
- );
95
- }
96
- return this._operations;
45
+ this.client = client;
46
+ this.core = new AuthKitCore(config, client, encryption);
47
+ this.operations = new AuthOperations(this.core, client, config);
97
48
  }
98
49
 
99
50
  /**
@@ -131,6 +82,12 @@ export class AuthService<TRequest, TResponse> {
131
82
  impersonator: session.impersonator,
132
83
  accessToken: session.accessToken,
133
84
  sessionId: claims.sid,
85
+ organizationId: claims.org_id,
86
+ role: claims.role,
87
+ roles: claims.roles,
88
+ permissions: claims.permissions,
89
+ entitlements: claims.entitlements,
90
+ featureFlags: claims.feature_flags,
134
91
  };
135
92
 
136
93
  if (refreshed) {
@@ -185,10 +142,26 @@ export class AuthService<TRequest, TResponse> {
185
142
  }
186
143
 
187
144
  /**
188
- * Sign out operation - delegates to AuthOperations.
145
+ * Sign out operation.
146
+ *
147
+ * Gets the WorkOS logout URL and clears the session via storage.
148
+ * Returns the URL plus whatever the storage returns (headers and/or response).
149
+ *
150
+ * @param sessionId - The session ID to terminate
151
+ * @param options - Optional return URL
152
+ * @returns Logout URL and storage clear result (headers and/or response)
189
153
  */
190
- async signOut(sessionId: string, options?: { returnTo?: string }) {
191
- return this.operations.signOut(sessionId, options);
154
+ async signOut(
155
+ sessionId: string,
156
+ options?: { returnTo?: string },
157
+ ): Promise<{
158
+ logoutUrl: string;
159
+ response?: TResponse;
160
+ headers?: HeadersBag;
161
+ }> {
162
+ const logoutUrl = this.operations.getLogoutUrl(sessionId, options);
163
+ const clearResult = await this.storage.clearSession(undefined);
164
+ return { logoutUrl, ...clearResult };
192
165
  }
193
166
 
194
167
  /**
@@ -235,7 +208,7 @@ export class AuthService<TRequest, TResponse> {
235
208
  * Useful for direct API calls not covered by AuthKit.
236
209
  */
237
210
  getWorkOS(): WorkOS {
238
- return this.clientFactory(this.config.getConfig());
211
+ return this.client;
239
212
  }
240
213
 
241
214
  /**
@@ -252,13 +225,10 @@ export class AuthService<TRequest, TResponse> {
252
225
  response: TResponse,
253
226
  options: { code: string; state?: string },
254
227
  ) {
255
- const clientId = this.config.getValue('clientId');
256
- const client = this.clientFactory(this.config.getConfig());
257
-
258
228
  // Authenticate with WorkOS using the OAuth code
259
- const authResponse = await client.userManagement.authenticateWithCode({
229
+ const authResponse = await this.client.userManagement.authenticateWithCode({
260
230
  code: options.code,
261
- clientId,
231
+ clientId: this.config.clientId,
262
232
  });
263
233
 
264
234
  // Create and save the new session
@@ -270,16 +240,40 @@ export class AuthService<TRequest, TResponse> {
270
240
  };
271
241
 
272
242
  const encryptedSession = await this.core.encryptSession(session);
273
- const { response: updatedResponse, headers } = await this.saveSession(response, encryptedSession);
243
+ const { response: updatedResponse, headers } = await this.saveSession(
244
+ response,
245
+ encryptedSession,
246
+ );
274
247
 
275
- // Decode return pathname from state
248
+ // Parse state: format is `{internal}.{userState}` or legacy `{base64JSON}`
276
249
  let returnPathname = '/';
250
+ let customState: string | undefined;
251
+
277
252
  if (options.state) {
278
- try {
279
- const decoded = JSON.parse(atob(options.state));
280
- returnPathname = decoded.returnPathname || '/';
281
- } catch {
282
- // Invalid state, use default
253
+ if (options.state.includes('.')) {
254
+ const [internal, ...rest] = options.state.split('.');
255
+ customState = rest.join('.'); // Rejoin in case userState contains dots
256
+ try {
257
+ // Reverse URL-safe base64 encoding and decode
258
+ const decoded = (internal ?? '')
259
+ .replace(/-/g, '+')
260
+ .replace(/_/g, '/');
261
+ const parsed = JSON.parse(atob(decoded));
262
+ returnPathname = parsed.returnPathname || '/';
263
+ } catch {
264
+ // Malformed internal state, use default
265
+ }
266
+ } else {
267
+ try {
268
+ const parsed = JSON.parse(atob(options.state));
269
+ if (parsed.returnPathname) {
270
+ returnPathname = parsed.returnPathname;
271
+ } else {
272
+ customState = options.state;
273
+ }
274
+ } catch {
275
+ customState = options.state;
276
+ }
283
277
  }
284
278
  }
285
279
 
@@ -287,6 +281,7 @@ export class AuthService<TRequest, TResponse> {
287
281
  response: updatedResponse,
288
282
  headers,
289
283
  returnPathname,
284
+ state: customState,
290
285
  authResponse,
291
286
  };
292
287
  }
@@ -1,5 +1,4 @@
1
1
  import { createAuthService } from './factory.js';
2
- import { AuthService } from './AuthService.js';
3
2
 
4
3
  const mockConfig = {
5
4
  clientId: 'test-client-id',
@@ -30,15 +29,25 @@ describe('createAuthService', () => {
30
29
  });
31
30
 
32
31
  describe('factory creation', () => {
33
- it('creates AuthService instance', () => {
32
+ it('creates AuthService-compatible interface', () => {
34
33
  const service = createAuthService({
35
34
  sessionStorageFactory: () => mockStorage as any,
36
35
  });
37
36
 
38
- expect(service).toBeInstanceOf(AuthService);
37
+ // Verify the proxy has all expected methods
38
+ expect(typeof service.withAuth).toBe('function');
39
+ expect(typeof service.getSession).toBe('function');
40
+ expect(typeof service.saveSession).toBe('function');
41
+ expect(typeof service.clearSession).toBe('function');
42
+ expect(typeof service.signOut).toBe('function');
43
+ expect(typeof service.getAuthorizationUrl).toBe('function');
44
+ expect(typeof service.getSignInUrl).toBe('function');
45
+ expect(typeof service.getSignUpUrl).toBe('function');
46
+ expect(typeof service.getWorkOS).toBe('function');
47
+ expect(typeof service.handleCallback).toBe('function');
39
48
  });
40
49
 
41
- it('accepts custom client factory', () => {
50
+ it('accepts custom client factory', async () => {
42
51
  const customClient = {
43
52
  userManagement: {
44
53
  getJwksUrl: () => 'https://custom.example.com/jwks',
@@ -50,7 +59,6 @@ describe('createAuthService', () => {
50
59
  clientFactory: () => customClient as any,
51
60
  });
52
61
 
53
- expect(service).toBeInstanceOf(AuthService);
54
62
  expect(service.getWorkOS()).toBe(customClient);
55
63
  });
56
64
 
@@ -65,12 +73,13 @@ describe('createAuthService', () => {
65
73
  encryptionFactory: () => customEncryption as any,
66
74
  });
67
75
 
68
- expect(service).toBeInstanceOf(AuthService);
76
+ // Factory accepts the custom encryption - verify by checking the interface exists
77
+ expect(typeof service.withAuth).toBe('function');
69
78
  });
70
79
  });
71
80
 
72
- describe('lazy storage initialization', () => {
73
- it('defers storage creation until first use', async () => {
81
+ describe('lazy initialization', () => {
82
+ it('defers service creation until first use', async () => {
74
83
  let storageCreated = false;
75
84
  const storageFactory = () => {
76
85
  storageCreated = true;
@@ -81,14 +90,16 @@ describe('createAuthService', () => {
81
90
  sessionStorageFactory: storageFactory,
82
91
  });
83
92
 
93
+ // Service created, but underlying AuthService not yet instantiated
84
94
  expect(storageCreated).toBe(false);
85
95
 
96
+ // First use triggers lazy init
86
97
  await service.getSession('request');
87
98
 
88
99
  expect(storageCreated).toBe(true);
89
100
  });
90
101
 
91
- it('creates storage only once', async () => {
102
+ it('creates service only once', async () => {
92
103
  let creationCount = 0;
93
104
  const storageFactory = () => {
94
105
  creationCount++;
@@ -1,10 +1,13 @@
1
1
  import type { WorkOS } from '@workos-inc/node';
2
2
  import { once } from '../utils.js';
3
- import { getConfigurationProvider, getFullConfig } from '../core/config.js';
3
+ import { getFullConfig } from '../core/config.js';
4
4
  import type { AuthKitConfig } from '../core/config/types.js';
5
5
  import { getWorkOS } from '../core/client/workos.js';
6
6
  import sessionEncryption from '../core/encryption/ironWebcryptoEncryption.js';
7
- import type { SessionEncryption, SessionStorage } from '../core/session/types.js';
7
+ import type {
8
+ SessionEncryption,
9
+ SessionStorage,
10
+ } from '../core/session/types.js';
8
11
  import { AuthService } from './AuthService.js';
9
12
 
10
13
  /**
@@ -47,23 +50,33 @@ export function createAuthService<TRequest, TResponse>(options: {
47
50
  encryptionFactory = () => sessionEncryption,
48
51
  } = options;
49
52
 
50
- // Storage needs to be created with lazy config evaluation
51
- // We create a wrapper storage that delegates to the real storage lazily
52
- const getStorage = once(() => sessionStorageFactory(getFullConfig()));
53
+ // Lazily create the real AuthService with resolved config
54
+ const getService = once(() => {
55
+ const config = getFullConfig();
56
+ const storage = sessionStorageFactory(config);
57
+ const client = clientFactory(config);
58
+ const encryption = encryptionFactory(config);
59
+ return new AuthService(config, storage, client, encryption);
60
+ });
53
61
 
54
- // Create a proxy storage that lazily instantiates the real storage
55
- const lazyStorage: SessionStorage<TRequest, TResponse> = {
56
- getSession: async (request: TRequest) => getStorage().getSession(request),
57
- saveSession: async (response: TResponse | undefined, sessionData: string) =>
58
- getStorage().saveSession(response, sessionData),
59
- clearSession: async (response: TResponse) =>
60
- getStorage().clearSession(response),
61
- };
62
-
63
- return new AuthService<TRequest, TResponse>(
64
- getConfigurationProvider(),
65
- lazyStorage,
66
- clientFactory,
67
- encryptionFactory,
68
- );
62
+ // Return proxy that lazily delegates to the real service
63
+ // This allows configure() to be called after createAuthService() but before first use
64
+ return {
65
+ withAuth: request => getService().withAuth(request),
66
+ getSession: request => getService().getSession(request),
67
+ saveSession: (response, sessionData) =>
68
+ getService().saveSession(response, sessionData),
69
+ clearSession: response => getService().clearSession(response),
70
+ signOut: (sessionId, opts) => getService().signOut(sessionId, opts),
71
+ switchOrganization: (session, organizationId) =>
72
+ getService().switchOrganization(session, organizationId),
73
+ refreshSession: (session, organizationId) =>
74
+ getService().refreshSession(session, organizationId),
75
+ getAuthorizationUrl: opts => getService().getAuthorizationUrl(opts),
76
+ getSignInUrl: opts => getService().getSignInUrl(opts),
77
+ getSignUpUrl: opts => getService().getSignUpUrl(opts),
78
+ getWorkOS: () => getService().getWorkOS(),
79
+ handleCallback: (request, response, opts) =>
80
+ getService().handleCallback(request, response, opts),
81
+ } as AuthService<TRequest, TResponse>;
69
82
  }