@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
package/README.md CHANGED
@@ -3,633 +3,223 @@
3
3
  > [!WARNING]
4
4
  > This is prerelease software. APIs may change without notice.
5
5
 
6
- A framework-agnostic authentication library for WorkOS with a modular adapter system for server-side rendered applications.
6
+ **Toolkit for building WorkOS AuthKit framework integrations.**
7
7
 
8
- This library serves as the foundation for framework-specific WorkOS authentication packages like `@workos-inc/authkit-nextjs`, `@workos-inc/authkit-remix`, and `@workos-inc/authkit-sveltekit`. By implementing the `SessionStorage` interface for your framework, you can provide WorkOS authentication capabilities with minimal framework-specific code.
9
-
10
- ## Features
11
-
12
- - **Framework-agnostic core**: Common authentication logic that works across platforms
13
- - **Adapter pattern**: Simple interface for framework-specific implementations
14
- - **Session management**: Secure encrypted cookie-based authentication
15
- - **JWT handling**: Token validation, parsing, and refresh
16
- - **Organization switching**: Switch user context between organizations
17
- - **Type-safe API**: Full TypeScript support with custom claims
18
- - **Token claims parsing**: Extract and validate JWT claims
8
+ Handles JWT verification, session encryption, and token refresh orchestration. You build the framework-specific glue.
19
9
 
20
10
  ## Installation
21
11
 
22
12
  ```bash
23
- # Using npm
24
- npm install @workos/authkit-session
25
-
26
- # Using pnpm
27
13
  pnpm add @workos/authkit-session
28
-
29
- # Using yarn
30
- yarn add @workos/authkit-session
31
14
  ```
32
15
 
16
+ ## What This Library Provides
17
+
18
+ | Layer | Class | Purpose |
19
+ | ------------- | ---------------------- | --------------------------------------------------------------------------------------------------- |
20
+ | Core | `AuthKitCore` | JWT verification (JWKS with caching), session encryption (AES-256-CBC), token refresh orchestration |
21
+ | Operations | `AuthOperations` | WorkOS API calls: signOut, refreshSession, authorization URLs |
22
+ | Helpers | `CookieSessionStorage` | Base class with secure cookie defaults |
23
+ | Orchestration | `AuthService` | Reference implementation combining all layers |
24
+
33
25
  ## Quick Start
34
26
 
35
- 1. Configure AuthKit with your WorkOS credentials:
27
+ ### 1. Configure
28
+
29
+ ```bash
30
+ WORKOS_CLIENT_ID=your-client-id
31
+ WORKOS_API_KEY=your-api-key
32
+ WORKOS_REDIRECT_URI=https://yourdomain.com/auth/callback
33
+ WORKOS_COOKIE_PASSWORD=must-be-at-least-32-characters-long-secret
34
+ ```
35
+
36
+ Or programmatically:
36
37
 
37
38
  ```typescript
38
- import { configure, createAuthKitFactory } from '@workos/authkit-session';
39
+ import { configure } from '@workos/authkit-session';
39
40
 
40
41
  configure({
41
42
  clientId: 'your-client-id',
42
- apiKey: 'your-workos-api-key',
43
+ apiKey: 'your-api-key',
43
44
  redirectUri: 'https://yourdomain.com/auth/callback',
44
45
  cookiePassword: 'must-be-at-least-32-characters-long-secret',
45
46
  });
46
47
  ```
47
48
 
48
- 2. Create a storage adapter for your framework:
49
+ ### 2. Create Storage Adapter
49
50
 
50
51
  ```typescript
51
52
  import {
52
- createAuthKitFactory,
53
53
  CookieSessionStorage,
54
+ parseCookieHeader,
54
55
  } from '@workos/authkit-session';
55
- import type {
56
- SessionStorage,
57
- ConfigurationProvider,
58
- } from '@workos/authkit-session';
59
-
60
- // Option 1: Extend CookieSessionStorage (recommended)
61
- class MyFrameworkStorage extends CookieSessionStorage<MyRequest, MyResponse> {
62
- constructor(config: ConfigurationProvider) {
63
- super(config);
64
- }
65
56
 
66
- async getSession(request: MyRequest): Promise<string | null> {
67
- // Extract cookie from your framework's request object
68
- const cookies = request.headers.cookie || '';
69
- const match = cookies.match(new RegExp(`${this.cookieName}=([^;]+)`));
70
- return match ? decodeURIComponent(match[1]) : null;
71
- }
72
-
73
- async saveSession(
74
- response: MyResponse,
75
- sessionData: string,
76
- ): Promise<MyResponse> {
77
- // Set cookie on your framework's response object
78
- const cookieValue = `${this.cookieName}=${encodeURIComponent(sessionData)}; ${this.getCookieAttributes()}`;
79
- response.headers['Set-Cookie'] = cookieValue;
80
- return response;
81
- }
82
-
83
- async clearSession(response: MyResponse): Promise<MyResponse> {
84
- // Clear cookie by setting expired date
85
- const expiredCookie = `${this.cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`;
86
- response.headers['Set-Cookie'] = expiredCookie;
87
- return response;
88
- }
89
-
90
- private getCookieAttributes(): string {
91
- const attrs = [];
92
- if (this.cookieOptions.path) attrs.push(`path=${this.cookieOptions.path}`);
93
- if (this.cookieOptions.domain)
94
- attrs.push(`domain=${this.cookieOptions.domain}`);
95
- if (this.cookieOptions.maxAge)
96
- attrs.push(`max-age=${this.cookieOptions.maxAge}`);
97
- if (this.cookieOptions.httpOnly) attrs.push('httponly');
98
- if (this.cookieOptions.secure) attrs.push('secure');
99
- if (this.cookieOptions.sameSite)
100
- attrs.push(`samesite=${this.cookieOptions.sameSite}`);
101
- return attrs.join('; ');
102
- }
103
- }
104
-
105
- // Option 2: Implement SessionStorage interface directly
106
- class CustomStorage implements SessionStorage<MyRequest, MyResponse> {
107
- async getSession(request: MyRequest): Promise<string | null> {
108
- // Your custom session retrieval logic
109
- return getSessionFromRequest(request);
110
- }
111
-
112
- async saveSession(
113
- response: MyResponse,
114
- sessionData: string,
115
- ): Promise<MyResponse> {
116
- // Your custom session storage logic
117
- return saveSessionToResponse(response, sessionData);
57
+ export class MyFrameworkStorage extends CookieSessionStorage<
58
+ Request,
59
+ Response
60
+ > {
61
+ async getSession(request: Request): Promise<string | null> {
62
+ const cookieHeader = request.headers.get('cookie');
63
+ if (!cookieHeader) return null;
64
+ return parseCookieHeader(cookieHeader)[this.cookieName] ?? null;
118
65
  }
119
66
 
120
- async clearSession(response: MyResponse): Promise<MyResponse> {
121
- // Your custom session clearing logic
122
- return clearSessionFromResponse(response);
67
+ // Optional: override if your framework can mutate responses
68
+ protected async applyHeaders(
69
+ response: Response | undefined,
70
+ headers: Record<string, string>,
71
+ ): Promise<{ response: Response }> {
72
+ const newResponse = response
73
+ ? new Response(response.body, {
74
+ status: response.status,
75
+ statusText: response.statusText,
76
+ headers: new Headers(response.headers),
77
+ })
78
+ : new Response();
79
+
80
+ Object.entries(headers).forEach(([key, value]) => {
81
+ newResponse.headers.append(key, value);
82
+ });
83
+
84
+ return { response: newResponse };
123
85
  }
124
86
  }
125
-
126
- // Create your AuthKit instance
127
- const authKit = createAuthKitFactory<MyRequest, MyResponse>({
128
- sessionStorageFactory: config => new MyFrameworkStorage(config),
129
- });
130
- ```
131
-
132
- 3. Use AuthKit in your application:
133
-
134
- ```typescript
135
- // Validate a session
136
- const { user, claims, sessionId, impersonator, accessToken, refreshToken } =
137
- await authKit.withAuth(request);
138
-
139
- // Note: ensureSignedIn option not yet implemented
140
- // Framework adapters should handle redirects when user is null
141
-
142
- // Generate an authorization URL
143
- const authUrl = await authKit.getAuthorizationUrl({
144
- returnPathname: '/dashboard',
145
- redirectUri: 'https://yourdomain.com/auth/callback',
146
- screenHint: 'sign-in', // or 'sign-up'
147
- organizationId: 'org_123', // Optional: pre-select organization
148
- loginHint: 'user@example.com', // Optional: pre-fill email
149
- prompt: 'login', // Optional: force re-authentication
150
- });
151
-
152
- // Generate sign-in/sign-up URLs (convenience methods)
153
- const signInUrl = await authKit.getSignInUrl({
154
- returnPathname: '/dashboard',
155
- redirectUri: 'https://yourdomain.com/auth/callback',
156
- organizationId: 'org_123', // Optional
157
- });
158
- const signUpUrl = await authKit.getSignUpUrl({
159
- returnPathname: '/welcome',
160
- redirectUri: 'https://yourdomain.com/auth/callback',
161
- });
162
-
163
- // Get token claims from current session
164
- const claims = await authKit.getTokenClaims(request);
165
- // Or parse specific access token
166
- const specificClaims = await authKit.getTokenClaims(request, accessToken);
167
-
168
- // Switch to different organization
169
- const { response: updatedResponse, authResult: newAuth } =
170
- await authKit.switchToOrganization(request, response, 'org_123');
171
-
172
- // Handle OAuth callback
173
- const {
174
- response: updatedResponse,
175
- returnPathname,
176
- authResponse,
177
- } = await authKit.handleCallback(request, response, {
178
- code: 'oauth_code_from_query',
179
- state: 'optional_state_from_query',
180
- });
181
-
182
- // Sign out (simple session termination)
183
- const clearedResponse = await authKit.signOut(request, response, {
184
- returnTo: 'https://yourdomain.com',
185
- });
186
-
187
- // Terminate session and get logout URL (advanced)
188
- const { response: clearedResponse, logoutUrl } = await authKit.terminateSession(
189
- session,
190
- response,
191
- { returnTo: 'https://yourdomain.com' },
192
- );
193
-
194
- // Manually save a session (for custom auth flows)
195
- await authKit.saveSession(response, authResponse);
196
-
197
- // Manually refresh session
198
- const refreshedAuth = await authKit.refreshSession(session, organizationId);
199
87
  ```
200
88
 
201
- ## For Framework Implementers
202
-
203
- If you're building a framework-specific package (like `@workos-inc/authkit-sveltekit`), this library provides everything needed for WorkOS authentication:
89
+ `CookieSessionStorage` provides `this.cookieName`, `this.cookieOptions`, `buildSetCookie()`, and implements `saveSession()`/`clearSession()` using your `applyHeaders()`.
204
90
 
205
- ### Implementation Steps
206
-
207
- 1. **Install and configure** `@workos/authkit-session` as a dependency
208
- 2. **Create a SessionStorage adapter** for your framework's request/response objects
209
- 3. **Export framework-specific helpers** that wrap the core AuthKit functionality
210
- 4. **Handle routing** for sign-in, callback, and sign-out endpoints
211
-
212
- ### Example Framework Package Structure
91
+ ### 3. Create Service
213
92
 
214
93
  ```typescript
215
- // src/storage.ts - Framework-specific storage adapter
216
- import { CookieSessionStorage } from '@workos/authkit-session';
217
- import type { ConfigurationProvider } from '@workos/authkit-session';
94
+ import { createAuthService } from '@workos/authkit-session';
218
95
 
219
- export class SvelteKitStorage extends CookieSessionStorage<RequestEvent, void> {
220
- // Implement framework-specific cookie handling
221
- }
222
-
223
- // src/index.ts - Main exports
224
- import { configure, createAuthKitFactory } from '@workos/authkit-session';
225
- import { SvelteKitStorage } from './storage';
226
-
227
- export { configure };
228
-
229
- export const authKit = createAuthKitFactory({
230
- sessionStorageFactory: config => new SvelteKitStorage(config),
96
+ export const authService = createAuthService({
97
+ sessionStorageFactory: config => new MyFrameworkStorage(config),
231
98
  });
232
-
233
- // Framework-specific helpers
234
- export async function withAuth(event: RequestEvent) {
235
- return authKit.withAuth(event);
236
- }
237
-
238
- export async function handleCallback(event: RequestEvent) {
239
- const url = new URL(event.request.url);
240
- const code = url.searchParams.get('code');
241
- const state = url.searchParams.get('state');
242
-
243
- if (!code) throw new Error('Missing authorization code');
244
-
245
- const result = await authKit.handleCallback(event, undefined, {
246
- code,
247
- state,
248
- });
249
- // Handle redirect to returnPathname
250
- }
251
- ```
252
-
253
- ### Key Considerations
254
-
255
- - **Request/Response Objects**: Adapt your framework's request/response objects to the `SessionStorage` interface
256
- - **Cookie Handling**: Implement secure cookie setting/getting for your framework
257
- - **Routing Integration**: Provide helpers for authentication routes (`/auth/signin`, `/auth/callback`, `/auth/signout`)
258
- - **TypeScript Support**: Export proper types for your framework's patterns
259
- - **Error Handling**: Wrap AuthKit errors in framework-appropriate error types
260
-
261
- ### Configuration Validation
262
-
263
- Framework adapters should validate configuration on startup to provide clear error messages:
264
-
265
- ```typescript
266
- import { validateConfig } from '@workos/authkit-session';
267
-
268
- // In your framework's initialization or middleware
269
- try {
270
- validateConfig();
271
- } catch (error) {
272
- // Framework will display helpful error message with all missing/invalid config
273
- throw error;
274
- }
275
- ```
276
-
277
- The `validateConfig()` function performs batch validation, collecting all configuration errors before throwing. This provides developers with a complete picture of what needs to be fixed, rather than discovering issues one at a time.
278
-
279
- ### Accessing Configuration
280
-
281
- Framework adapters can access configuration values directly:
282
-
283
- ```typescript
284
- import { getConfig, getConfigurationProvider } from '@workos/authkit-session';
285
-
286
- // Get a single config value
287
- const clientId = getConfig('clientId');
288
-
289
- // Get the ConfigurationProvider for more advanced use
290
- const provider = getConfigurationProvider();
291
- const config = provider.getConfig(); // Returns full AuthKitConfig object
292
- ```
293
-
294
- ## Core Concepts
295
-
296
- ### Session Management
297
-
298
- AuthKit SSR uses encrypted cookies to store session information. It handles:
299
-
300
- - Token encryption/decryption (using iron-webcrypto)
301
- - JWT validation and parsing
302
- - Session refresh logic
303
- - Session termination
304
-
305
- ### Adapter System
306
-
307
- AuthKit uses an adapter pattern to abstract framework-specific request/response handling. This allows the core authentication logic to remain framework-agnostic while enabling support for any server-side framework.
308
-
309
- #### SessionStorage Interface
310
-
311
- ```typescript
312
- interface SessionStorage<TRequest, TResponse, TOptions = unknown> {
313
- getSession(request: TRequest): Promise<string | null>;
314
- saveSession(
315
- response: TResponse,
316
- sessionData: string,
317
- options?: TOptions,
318
- ): Promise<TResponse>;
319
- clearSession(response: TResponse, options?: TOptions): Promise<TResponse>;
320
- }
321
99
  ```
322
100
 
323
- #### CookieSessionStorage Base Class
324
-
325
- For cookie-based session storage, extend the provided `CookieSessionStorage` class:
101
+ ### 4. Implement Middleware
326
102
 
327
103
  ```typescript
328
- import { CookieSessionStorage } from '@workos/authkit-session';
329
-
330
- abstract class CookieSessionStorage<TRequest, TResponse> {
331
- protected cookieName: string; // From config: cookieName
332
- protected cookieOptions: CookieOptions; // Derived from config
333
-
334
- // Implement these methods for your framework
335
- abstract getSession(request: TRequest): Promise<string | null>;
336
- abstract saveSession(
337
- response: TResponse,
338
- sessionData: string,
339
- ): Promise<TResponse>;
340
- abstract clearSession(response: TResponse): Promise<TResponse>;
341
- }
104
+ export const authMiddleware = () => {
105
+ return createMiddleware().server(async args => {
106
+ const { auth, refreshedSessionData } = await authService.withAuth(
107
+ args.request,
108
+ );
342
109
 
343
- interface CookieOptions {
344
- path?: string; // Default: '/'
345
- domain?: string; // From config: cookieDomain
346
- maxAge?: number; // From config: cookieMaxAge (400 days)
347
- httpOnly?: boolean; // Default: true
348
- secure?: boolean; // From config: apiHttps
349
- sameSite?: 'lax' | 'strict' | 'none'; // From config: cookieSameSite
350
- }
110
+ const result = await args.next({
111
+ context: { auth: () => auth },
112
+ });
113
+
114
+ // CRITICAL: Persist refreshed tokens to cookie
115
+ if (refreshedSessionData) {
116
+ const { headers } = await authService.saveSession(
117
+ undefined,
118
+ refreshedSessionData,
119
+ );
120
+ if (headers?.['Set-Cookie']) {
121
+ const newResponse = new Response(result.response.body, {
122
+ status: result.response.status,
123
+ statusText: result.response.statusText,
124
+ headers: result.response.headers,
125
+ });
126
+ newResponse.headers.set('Set-Cookie', headers['Set-Cookie']);
127
+ return { ...result, response: newResponse };
128
+ }
129
+ }
130
+
131
+ return result;
132
+ });
133
+ };
351
134
  ```
352
135
 
353
- #### Framework-Specific Examples
136
+ **If you skip applying `Set-Cookie`, refreshed tokens never persist.** Next request sees the old expired token → infinite refresh loop.
354
137
 
355
- **Express/Node.js:**
138
+ ## AuthResult Type
356
139
 
357
- ```typescript
358
- class ExpressStorage extends CookieSessionStorage<Request, Response> {
359
- async getSession(request: Request): Promise<string | null> {
360
- return request.cookies[this.cookieName] || null;
361
- }
362
-
363
- async saveSession(
364
- response: Response,
365
- sessionData: string,
366
- ): Promise<Response> {
367
- response.cookie(this.cookieName, sessionData, this.cookieOptions);
368
- return response;
369
- }
370
-
371
- async clearSession(response: Response): Promise<Response> {
372
- response.clearCookie(this.cookieName, { path: this.cookieOptions.path });
373
- return response;
374
- }
375
- }
376
- ```
377
-
378
- **Hono:**
140
+ `withAuth()` returns a discriminated union. If `auth.user` exists, all other properties exist:
379
141
 
380
142
  ```typescript
381
- class HonoStorage extends CookieSessionStorage<HonoRequest, HonoResponse> {
382
- async getSession(request: HonoRequest): Promise<string | null> {
383
- return getCookie(request, this.cookieName) || null;
384
- }
385
-
386
- async saveSession(
387
- response: HonoResponse,
388
- sessionData: string,
389
- ): Promise<HonoResponse> {
390
- setCookie(response, this.cookieName, sessionData, this.cookieOptions);
391
- return response;
392
- }
143
+ const { auth } = await authService.withAuth(request);
393
144
 
394
- async clearSession(response: HonoResponse): Promise<HonoResponse> {
395
- deleteCookie(response, this.cookieName);
396
- return response;
397
- }
145
+ if (!auth.user) {
146
+ return redirect('/login');
398
147
  }
399
- ```
400
-
401
- #### Creating Framework Adapters
402
-
403
- When creating an adapter for a new framework:
404
-
405
- 1. **Choose your approach**: Extend `CookieSessionStorage` for cookie-based storage, or implement `SessionStorage` directly for custom storage
406
- 2. **Handle framework request/response objects**: Extract cookies from requests and set cookies on responses
407
- 3. **Respect configuration**: Use `this.cookieName` and `this.cookieOptions` from the base class
408
- 4. **Test thoroughly**: Ensure session persistence works across requests
409
-
410
- #### Factory Configuration
411
-
412
- ```typescript
413
- const authKit = createAuthKitFactory<MyRequest, MyResponse>({
414
- sessionStorageFactory: config => new MyFrameworkStorage(config),
415
-
416
- // Optional: Custom session encryption
417
- sessionEncryptionFactory: config => myCustomEncryption,
418
-
419
- // Optional: Custom WorkOS client
420
- clientFactory: config => myCustomWorkOSClient,
421
- });
422
- ```
423
-
424
- ## Configuration
425
-
426
- AuthKit can be configured in multiple ways:
427
-
428
- ### Environment Variables
429
-
430
- ```bash
431
- WORKOS_CLIENT_ID=your-client-id
432
- WORKOS_API_KEY=your-api-key
433
- WORKOS_REDIRECT_URI=https://yourdomain.com/auth/callback
434
- WORKOS_COOKIE_PASSWORD=must-be-at-least-32-characters-long
435
- WORKOS_COOKIE_NAME=wos-session
436
- WORKOS_COOKIE_MAX_AGE=34560000
437
- WORKOS_API_HOSTNAME=api.workos.com
438
- WORKOS_API_HTTPS=true
439
- WORKOS_API_PORT=443
440
- ```
441
148
 
442
- **Environment Variable Naming Convention:**
443
- Environment variables follow the pattern: `WORKOS_{PROPERTY_NAME}` where the property name is converted from camelCase to UPPER_SNAKE_CASE.
444
-
445
- Examples:
446
-
447
- - `clientId` → `WORKOS_CLIENT_ID`
448
- - `redirectUri` → `WORKOS_REDIRECT_URI`
449
- - `cookiePassword` → `WORKOS_COOKIE_PASSWORD`
450
- - `cookieMaxAge` → `WORKOS_COOKIE_MAX_AGE`
451
-
452
- Environment variables always take precedence over programmatic configuration.
453
-
454
- ### Programmatic Configuration
455
-
456
- ```typescript
457
- import { configure } from '@workos/authkit-session';
458
-
459
- configure({
460
- clientId: 'your-client-id',
461
- apiKey: 'your-api-key',
462
- redirectUri: 'https://yourdomain.com/auth/callback',
463
- cookiePassword: 'must-be-at-least-32-characters-long',
464
- cookieName: 'wos-session', // Default: 'wos-session'
465
- cookieMaxAge: 60 * 60 * 24 * 400, // 400 days in seconds
466
- cookieSameSite: 'lax', // 'strict', 'lax', or 'none'
467
- cookieDomain: '.yourdomain.com', // Optional: cookie domain
468
- apiHostname: 'api.workos.com', // Optional: API hostname
469
- apiHttps: true, // Default: true
470
- apiPort: 443, // Optional: API port
471
- });
149
+ // TypeScript knows these exist (no ! needed)
150
+ auth.sessionId; // string
151
+ auth.accessToken; // string
152
+ auth.claims.sid; // string
472
153
  ```
473
154
 
474
- ## API Reference
475
-
476
- ### Core API
477
-
478
- - `configure(config)`: Set up AuthKit with your WorkOS configuration
479
- - `validateConfig()`: Validate all required configuration values are present and valid (throws descriptive error if not)
480
- - `getConfig(key)`: Get a specific configuration value
481
- - `getConfigurationProvider()`: Get the ConfigurationProvider instance for advanced configuration access
482
- - `createAuthKitFactory(options)`: Create an instance of AuthKit for your framework
483
-
484
- ### AuthKit Instance API
485
-
486
- #### Authentication & Session Management
487
-
488
- - `withAuth<TCustomClaims>(request, options?)`: Validate the current session and return `AuthResult<TCustomClaims>`
489
- - Note: `ensureSignedIn` option not yet implemented - framework adapters should handle redirects
490
- - `handleCallback(request, response, { code, state? })`: Process OAuth callback and create session
491
- - `signOut(request, response, options?)`: Simple session termination with cookie clearing
492
- - `terminateSession(session, response, options?)`: Advanced session termination with logout URL
493
- - `saveSession(response, authResponse)`: Manually save session from `AuthenticationResponse`
494
- - `refreshSession(session, organizationId?)`: Manually refresh session tokens
155
+ ## Configuration Options
495
156
 
496
- #### URL Generation
157
+ | Environment Variable | Config Key | Description |
158
+ | ------------------------- | ---------------- | ------------------------------------ |
159
+ | `WORKOS_CLIENT_ID` | `clientId` | WorkOS client ID |
160
+ | `WORKOS_API_KEY` | `apiKey` | WorkOS API key |
161
+ | `WORKOS_REDIRECT_URI` | `redirectUri` | OAuth callback URL |
162
+ | `WORKOS_COOKIE_PASSWORD` | `cookiePassword` | 32+ char encryption key |
163
+ | `WORKOS_COOKIE_NAME` | `cookieName` | Cookie name (default: `wos_session`) |
164
+ | `WORKOS_COOKIE_MAX_AGE` | `cookieMaxAge` | Cookie lifetime in seconds |
165
+ | `WORKOS_COOKIE_DOMAIN` | `cookieDomain` | Cookie domain |
166
+ | `WORKOS_COOKIE_SAME_SITE` | `cookieSameSite` | `lax`, `strict`, or `none` |
497
167
 
498
- - `getAuthorizationUrl(options)`: Generate a WorkOS authorization URL
499
- - Options: `returnPathname`, `redirectUri`, `screenHint` ('sign-in' | 'sign-up'), `organizationId`, `loginHint`, `prompt` ('login' | 'none' | 'consent' | 'select_account')
500
- - `getSignInUrl(options)`: Generate a sign-in URL (convenience method with screenHint='sign-in')
501
- - Options: `returnPathname`, `redirectUri`, `organizationId`, `loginHint`, `prompt`
502
- - `getSignUpUrl(options)`: Generate a sign-up URL (convenience method with screenHint='sign-up')
503
- - Options: `returnPathname`, `redirectUri`, `organizationId`, `loginHint`, `prompt`
168
+ Environment variables override programmatic config.
504
169
 
505
- #### Token & Organization Management
170
+ ## API Overview
506
171
 
507
- - `getTokenClaims<TCustomClaims>(request, accessToken?)`: Parse JWT token claims from session or specific token
508
- - `switchToOrganization(request, response, organizationId)`: Switch user to different organization context
509
-
510
- ## Advanced Features
511
-
512
- ### Organization Switching
513
-
514
- Switch users between organizations without requiring re-authentication:
172
+ ### AuthService Methods
515
173
 
516
174
  ```typescript
517
- try {
518
- const { response: updatedResponse, authResult } =
519
- await authKit.switchToOrganization(
520
- request,
521
- response,
522
- 'org_new_organization_id',
523
- );
175
+ // Authentication
176
+ authService.withAuth(request) // → { auth, refreshedSessionData? }
177
+ authService.handleCallback(request, response, { code, state })
178
+ authService.getSession(request) // → Session | null
179
+ authService.saveSession(response, sessionData) // → { response?, headers? }
180
+ authService.clearSession(response)
524
181
 
525
- // Use the updated response and new auth context
526
- const { user, sessionId, claims } = authResult;
527
- } catch (error) {
528
- if (error.authUrl) {
529
- // Handle cases requiring re-authentication (SSO, MFA)
530
- redirect(error.authUrl);
531
- }
532
- }
533
- ```
534
-
535
- ### Token Claims Parsing
182
+ // WorkOS Operations
183
+ authService.signOut(sessionId, { returnTo }) // → { logoutUrl, clearCookieHeader }
184
+ authService.refreshSession(session, organizationId?)
185
+ authService.switchOrganization(session, organizationId)
536
186
 
537
- Extract and validate JWT claims from access tokens:
538
-
539
- ```typescript
540
- // Parse claims from current session
541
- const claims = await authKit.getTokenClaims<MyCustomClaims>(request);
542
-
543
- // Parse claims from specific token
544
- const specificClaims = await authKit.getTokenClaims<MyCustomClaims>(
545
- request,
546
- accessToken,
547
- );
548
-
549
- // Custom claims interface
550
- interface MyCustomClaims {
551
- custom_field: string;
552
- user_metadata: Record<string, unknown>;
553
- }
187
+ // URL Generation
188
+ authService.getAuthorizationUrl(options)
189
+ authService.getSignInUrl(options)
190
+ authService.getSignUpUrl(options)
554
191
  ```
555
192
 
556
- ### TypeScript Support
193
+ ### Direct Access (Advanced)
557
194
 
558
- AuthKit provides full TypeScript support with generic type parameters:
195
+ For maximum control, use the primitives directly:
559
196
 
560
197
  ```typescript
561
- interface CustomClaims {
562
- department: string;
563
- permissions: string[];
564
- }
565
-
566
- const { user, claims } = await authKit.withAuth<CustomClaims>(request);
567
- // claims is typed as BaseTokenClaims & CustomClaims
568
- ```
569
-
570
- ### AuthResult Interface
571
-
572
- The `withAuth` method returns an `AuthResult` object with the following structure:
198
+ import {
199
+ AuthKitCore,
200
+ AuthOperations,
201
+ getWorkOS,
202
+ getConfigurationProvider,
203
+ } from '@workos/authkit-session';
573
204
 
574
- ```typescript
575
- interface AuthResult<TCustomClaims = Record<string, unknown>> {
576
- user?: User | null; // WorkOS user object
577
- claims?: BaseTokenClaims & TCustomClaims; // JWT token claims
578
- impersonator?: Impersonator; // Impersonation context if any
579
- accessToken?: string; // JWT access token
580
- refreshToken?: string; // Refresh token
581
- sessionId?: string; // Session identifier from claims
582
- }
205
+ const config = getConfigurationProvider();
206
+ const client = getWorkOS(config.getConfig());
207
+ const core = new AuthKitCore(config, client, encryption);
208
+ const operations = new AuthOperations(core, client, config);
583
209
 
584
- interface BaseTokenClaims {
585
- sid: string; // Session ID
586
- org_id?: string; // Organization ID
587
- role?: string; // User role
588
- permissions?: string[]; // User permissions
589
- entitlements?: string[]; // User entitlements
590
- feature_flags?: string[]; // Feature flags
591
- }
210
+ // Use core.validateAndRefresh(), core.encryptSession(), etc.
592
211
  ```
593
212
 
594
- ### Additional Exports
595
-
596
- The library also exports these components for advanced use cases:
597
-
598
- ```typescript
599
- import {
600
- // Core configuration
601
- configure, // Set up configuration
602
- validateConfig, // Validate all required config values
603
- getConfig, // Get specific config value
604
- getConfigurationProvider, // Get ConfigurationProvider instance
605
- ConfigurationProvider, // ConfigurationProvider class
606
-
607
- // Session management
608
- SessionManager, // Core session management class
609
- CookieSessionStorage, // Abstract cookie storage base class
610
-
611
- // WorkOS client
612
- getWorkOS, // WorkOS client factory
613
-
614
- // Types
615
- type SessionStorage,
616
- type AuthKitConfig,
617
- type AuthResult,
618
- type Session,
619
- type User,
620
- type Impersonator,
621
- // ... and more
622
- } from '@workos/authkit-session';
623
- ```
213
+ ## Technical Details
624
214
 
625
- ## Security
215
+ - **JWKS Caching**: Keys fetched on-demand, cached for process lifetime. `jose` handles key rotation automatically.
216
+ - **Token Expiry Buffer**: 60 seconds default. Tokens refresh before actual expiry.
217
+ - **Session Encryption**: AES-256-CBC + SHA-256 HMAC via `iron-webcrypto`.
218
+ - **Lazy Initialization**: `createAuthService()` defers initialization until first use, allowing `configure()` to be called later.
626
219
 
627
- AuthKit uses iron-webcrypto for secure, encrypted cookies with the following security features:
220
+ ## Reference Implementation
628
221
 
629
- - Encrypted cookies (AES-256-CBC)
630
- - HMAC validation (SHA-256)
631
- - Customizable cookie settings (HttpOnly, SameSite, etc.)
632
- - Token refresh mechanism
222
+ See [`@workos/authkit-tanstack-start`](https://github.com/workos/authkit-tanstack-start) for a complete example.
633
223
 
634
224
  ## License
635
225