@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
package/README.md CHANGED
@@ -3,119 +3,28 @@
3
3
  > [!WARNING]
4
4
  > This is prerelease software. APIs may change without notice.
5
5
 
6
- **A toolkit library for building WorkOS AuthKit integrations.**
6
+ **Toolkit for building WorkOS AuthKit framework integrations.**
7
7
 
8
- This library extracts the complex business logic (JWT verification, session encryption, token refresh orchestration) that WorkOS SDK authors need when building framework-specific authentication packages like `@workos-inc/authkit-nextjs`, `@workos-inc/authkit-tanstack-start`, and `@workos-inc/authkit-sveltekit`.
9
-
10
- ## Philosophy
11
-
12
- **We provide the hard stuff:**
13
- - Token verification with JWKS and caching
14
- - Session encryption/decryption (iron-webcrypto)
15
- - Token refresh orchestration (when to refresh, how to preserve org context)
16
- - WorkOS API integration helpers (signOut, refreshSession, authorization URLs)
17
- - Cookie building with secure defaults
18
- - Configuration management (environment variables, validation)
19
-
20
- **You own the integration:**
21
- - Implement `updateSession/withAuth` patterns that fit your framework
22
- - Handle request context (headers, locals, WeakMap) your way
23
- - Add framework-specific features (callbacks, debug logging, eager auth)
24
- - Control middleware and route handler patterns
25
-
26
- **Result:** Share 80% of the complexity, keep 100% control over framework integration.
27
-
28
- ## Features
29
-
30
- - **Business Logic Extraction**: JWT, crypto, and refresh logic in one place
31
- - **Framework-Agnostic Primitives**: Works in any JavaScript environment (Node.js, edge, Deno)
32
- - **Toolkit, Not Framework**: Use what you need, implement patterns your way
33
- - **Type-Safe**: Full TypeScript support with custom claims and generics
34
- - **Production-Ready**: 80%+ test coverage, comprehensive error handling
35
- - **Zero Framework Opinions**: No prescribed middleware/route patterns
36
-
37
- ## Architecture
38
-
39
- This library provides a **three-layer toolkit** for building authentication:
40
-
41
- ### Layer 1: Core Business Logic (`AuthKitCore`)
42
-
43
- Pure functions for the hard stuff - no framework dependencies:
44
-
45
- - **Token Operations**
46
- - `verifyToken()` - JWT verification against JWKS (with caching)
47
- - `isTokenExpiring()` - Check if token needs refresh soon
48
- - `parseTokenClaims()` - Extract and decode JWT claims
49
-
50
- - **Session Encryption**
51
- - `encryptSession()` - AES-256-CBC encryption for cookies
52
- - `decryptSession()` - Decrypt and validate session data
53
-
54
- - **Refresh Orchestration**
55
- - `refreshTokens()` - Call WorkOS API to refresh tokens
56
- - `validateAndRefresh()` - **Core orchestration**: validate token → refresh if expiring
57
-
58
- ```typescript
59
- import { AuthKitCore } from '@workos/authkit-session';
60
-
61
- const core = new AuthKitCore(config, client, encryption);
62
-
63
- // Validate and potentially refresh in one call
64
- const { valid, refreshed, session, claims } =
65
- await core.validateAndRefresh(session);
66
- ```
67
-
68
- ### Layer 2: WorkOS Operations (`AuthOperations`)
69
-
70
- High-level operations combining core logic with WorkOS API calls:
71
-
72
- - **Sign Out**: `signOut()` - Generate logout URL + cookie clear header
73
- - **Refresh Session**: `refreshSession()` - Refresh tokens with org context preservation
74
- - **Switch Organization**: `switchOrganization()` - Refresh with new org ID
75
- - **URL Generation**: `getAuthorizationUrl()`, `getSignInUrl()`, `getSignUpUrl()`
76
-
77
- ```typescript
78
- import { AuthOperations } from '@workos/authkit-session';
79
-
80
- const operations = new AuthOperations(core, client, config);
81
-
82
- // Sign out returns everything you need
83
- const { logoutUrl, clearCookieHeader } =
84
- await operations.signOut(sessionId, { returnTo: '/' });
85
- ```
86
-
87
- ### Layer 3: Integration Helpers
88
-
89
- - **`CookieSessionStorage`** - Base class with secure cookie defaults
90
- - **`ConfigurationProvider`** - Environment variable mapping and validation
91
- - **`AuthService`** - Optional reference implementation showing how to orchestrate Core + Operations + Storage
92
-
93
- **Key Design Decision:** We don't force context methods (`getSessionFromContext`) into interfaces. Each framework handles request context differently:
94
- - Next.js: Mutable headers (`request.headers.set()`)
95
- - TanStack Start: WeakMap (immutable requests)
96
- - SvelteKit: `event.locals`
97
- - Remix: Context objects
98
-
99
- Let frameworks implement context passing idiomatically.
8
+ Handles JWT verification, session encryption, and token refresh orchestration. You build the framework-specific glue.
100
9
 
101
10
  ## Installation
102
11
 
103
12
  ```bash
104
- # Using npm
105
- npm install @workos/authkit-session
106
-
107
- # Using pnpm
108
13
  pnpm add @workos/authkit-session
109
-
110
- # Using yarn
111
- yarn add @workos/authkit-session
112
14
  ```
113
15
 
114
- ## Quick Start
16
+ ## What This Library Provides
115
17
 
116
- ### 1. Configure AuthKit
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
+
25
+ ## Quick Start
117
26
 
118
- Set up your WorkOS credentials using environment variables (recommended):
27
+ ### 1. Configure
119
28
 
120
29
  ```bash
121
30
  WORKOS_CLIENT_ID=your-client-id
@@ -124,7 +33,7 @@ WORKOS_REDIRECT_URI=https://yourdomain.com/auth/callback
124
33
  WORKOS_COOKIE_PASSWORD=must-be-at-least-32-characters-long-secret
125
34
  ```
126
35
 
127
- Or configure programmatically:
36
+ Or programmatically:
128
37
 
129
38
  ```typescript
130
39
  import { configure } from '@workos/authkit-session';
@@ -137,36 +46,29 @@ configure({
137
46
  });
138
47
  ```
139
48
 
140
- ### 2. Create a Storage Adapter
141
-
142
- Extend `CookieSessionStorage` for your framework's request/response objects:
49
+ ### 2. Create Storage Adapter
143
50
 
144
51
  ```typescript
145
- import { CookieSessionStorage, getConfigurationProvider } from '@workos/authkit-session';
52
+ import {
53
+ CookieSessionStorage,
54
+ parseCookieHeader,
55
+ } from '@workos/authkit-session';
146
56
 
147
- // Web-standard Request/Response example
148
- class MyFrameworkStorage extends CookieSessionStorage<Request, Response> {
57
+ export class MyFrameworkStorage extends CookieSessionStorage<
58
+ Request,
59
+ Response
60
+ > {
149
61
  async getSession(request: Request): Promise<string | null> {
150
62
  const cookieHeader = request.headers.get('cookie');
151
63
  if (!cookieHeader) return null;
152
-
153
- // Parse cookies
154
- const cookies = Object.fromEntries(
155
- cookieHeader.split(';').map((cookie) => {
156
- const [key, ...valueParts] = cookie.trim().split('=');
157
- return [key, valueParts.join('=')];
158
- }),
159
- );
160
-
161
- const value = cookies[this.cookieName];
162
- return value ? decodeURIComponent(value) : null;
64
+ return parseCookieHeader(cookieHeader)[this.cookieName] ?? null;
163
65
  }
164
66
 
67
+ // Optional: override if your framework can mutate responses
165
68
  protected async applyHeaders(
166
69
  response: Response | undefined,
167
70
  headers: Record<string, string>,
168
71
  ): Promise<{ response: Response }> {
169
- // Create or clone response to apply headers
170
72
  const newResponse = response
171
73
  ? new Response(response.body, {
172
74
  status: response.status,
@@ -175,7 +77,6 @@ class MyFrameworkStorage extends CookieSessionStorage<Request, Response> {
175
77
  })
176
78
  : new Response();
177
79
 
178
- // Apply headers
179
80
  Object.entries(headers).forEach(([key, value]) => {
180
81
  newResponse.headers.append(key, value);
181
82
  });
@@ -185,223 +86,44 @@ class MyFrameworkStorage extends CookieSessionStorage<Request, Response> {
185
86
  }
186
87
  ```
187
88
 
188
- **Note:** `CookieSessionStorage` provides:
189
- - `this.cookieName` - Cookie name from config
190
- - `this.cookieOptions` - Secure defaults (HttpOnly, Secure, SameSite)
191
- - `buildSetCookie(value, expired?)` - Helper for Set-Cookie header strings
192
- - `saveSession()` / `clearSession()` - Implemented using `applyHeaders()` + `buildSetCookie()`
193
-
194
- You only need to implement:
195
- - `getSession(request)` - Extract encrypted session from cookies
196
- - `applyHeaders(response, headers)` - Apply headers to framework's response (optional, defaults to returning headers)
89
+ `CookieSessionStorage` provides `this.cookieName`, `this.cookieOptions`, `buildSetCookie()`, and implements `saveSession()`/`clearSession()` using your `applyHeaders()`.
197
90
 
198
- ### 3. Create AuthService Instance
91
+ ### 3. Create Service
199
92
 
200
93
  ```typescript
201
94
  import { createAuthService } from '@workos/authkit-session';
202
95
 
203
- const authService = createAuthService({
204
- sessionStorageFactory: (config) => new MyFrameworkStorage(config),
205
- });
206
- ```
207
-
208
- ### 4. Use in Your Application
209
-
210
- **Check authentication:**
211
-
212
- ```typescript
213
- const { auth, refreshedSessionData } = await authService.withAuth(request);
214
-
215
- if (!auth.user) {
216
- // User not authenticated - redirect to sign in
217
- return redirect('/sign-in');
218
- }
219
-
220
- // TypeScript knows: auth.user exists, so sessionId, accessToken, etc. exist too
221
- console.log(auth.sessionId); // string (no ! needed)
222
- console.log(auth.accessToken); // string
223
- console.log(auth.claims.org_id); // string | undefined
224
- ```
225
-
226
- **Apply refreshed session (if token was refreshed):**
227
-
228
- ```typescript
229
- if (refreshedSessionData) {
230
- const { headers } = await authService.saveSession(undefined, refreshedSessionData);
231
- // Apply headers['Set-Cookie'] to your framework's response
232
- response.headers.set('Set-Cookie', headers['Set-Cookie']);
233
- }
234
- ```
235
-
236
- **Generate authentication URLs:**
237
-
238
- ```typescript
239
- // Get sign-in URL
240
- const signInUrl = await authService.getSignInUrl({
241
- returnPathname: '/dashboard',
242
- });
243
-
244
- // Get sign-up URL
245
- const signUpUrl = await authService.getSignUpUrl({
246
- returnPathname: '/welcome',
247
- });
248
-
249
- // Get authorization URL (advanced)
250
- const authUrl = await authService.getAuthorizationUrl({
251
- returnPathname: '/dashboard',
252
- screenHint: 'sign-in', // or 'sign-up'
253
- organizationId: 'org_123', // Optional: pre-select organization
254
- loginHint: 'user@example.com', // Optional: pre-fill email
255
- });
256
- ```
257
-
258
- **Handle OAuth callback:**
259
-
260
- ```typescript
261
- const code = url.searchParams.get('code');
262
- const state = url.searchParams.get('state');
263
-
264
- const result = await authService.handleCallback(
265
- request,
266
- response,
267
- { code, state },
268
- );
269
-
270
- // result.returnPathname - Where to redirect after auth
271
- // result.authResponse - Full auth response with user, tokens, etc.
272
- // result.headers - Set-Cookie header to apply
273
- ```
274
-
275
- **Sign out:**
276
-
277
- ```typescript
278
- const { logoutUrl, clearCookieHeader } = await authService.signOut(
279
- auth.sessionId,
280
- { returnTo: '/' },
281
- );
282
-
283
- // Redirect to WorkOS logout URL with cookie clear header
284
- return redirect(logoutUrl, {
285
- headers: { 'Set-Cookie': clearCookieHeader },
96
+ export const authService = createAuthService({
97
+ sessionStorageFactory: config => new MyFrameworkStorage(config),
286
98
  });
287
99
  ```
288
100
 
289
- **Switch organization:**
101
+ ### 4. Implement Middleware
290
102
 
291
103
  ```typescript
292
- const session = await authService.getSession(request);
293
- const result = await authService.switchOrganization(session, 'org_123');
294
-
295
- // result.auth - New auth with org-specific claims
296
- // result.encryptedSession - New session to save
297
- ```
298
-
299
- ## For Framework Implementers
300
-
301
- If you're building a framework-specific package (like `@workos/authkit-tanstack-start`), this library provides all the business logic you need. You just add framework-specific glue.
302
-
303
- ### Recommended Approach: Use AuthService
304
-
305
- The simplest path is to use `createAuthService()` with your storage adapter:
306
-
307
- ```typescript
308
- // src/storage.ts - Your framework's storage adapter
309
- import { CookieSessionStorage } from '@workos/authkit-session';
310
-
311
- export class MyFrameworkStorage extends CookieSessionStorage<Request, Response> {
312
- async getSession(request: Request): Promise<string | null> {
313
- // Extract cookie from request
314
- const cookieHeader = request.headers.get('cookie');
315
- if (!cookieHeader) return null;
316
-
317
- const cookies = this.parseCookies(cookieHeader);
318
- return cookies[this.cookieName] ? decodeURIComponent(cookies[this.cookieName]) : null;
319
- }
320
-
321
- protected async applyHeaders(
322
- response: Response | undefined,
323
- headers: Record<string, string>,
324
- ): Promise<{ response: Response }> {
325
- // Clone response and apply headers (Response objects are immutable)
326
- const newResponse = response
327
- ? new Response(response.body, {
328
- status: response.status,
329
- statusText: response.statusText,
330
- headers: new Headers(response.headers),
331
- })
332
- : new Response();
333
-
334
- Object.entries(headers).forEach(([key, value]) => {
335
- newResponse.headers.append(key, value);
336
- });
337
-
338
- return { response: newResponse };
339
- }
340
-
341
- private parseCookies(header: string): Record<string, string> {
342
- return Object.fromEntries(
343
- header.split(';').map((c) => {
344
- const [key, ...parts] = c.trim().split('=');
345
- return [key, parts.join('=')];
346
- }),
347
- );
348
- }
349
- }
350
-
351
- // src/index.ts - Create auth instance
352
- import { createAuthService, getConfigurationProvider } from '@workos/authkit-session';
353
- import { MyFrameworkStorage } from './storage.js';
354
-
355
- const authService = createAuthService({
356
- sessionStorageFactory: (config) => new MyFrameworkStorage(getConfigurationProvider()),
357
- });
358
-
359
- // Export framework-specific wrappers
360
- export async function withAuth(request: Request) {
361
- return authService.withAuth(request);
362
- }
363
-
364
- export async function getSignInUrl(returnPathname?: string) {
365
- return authService.getSignInUrl({ returnPathname });
366
- }
367
-
368
- export async function signOut(sessionId: string, returnTo?: string) {
369
- return authService.signOut(sessionId, { returnTo });
370
- }
371
- ```
372
-
373
- ### Middleware Pattern (Critical for Token Refresh)
374
-
375
- Your middleware should:
376
- 1. Validate current session (auto-refreshes if expiring)
377
- 2. Store auth in framework context for downstream handlers
378
- 3. Apply `Set-Cookie` header if session was refreshed
379
-
380
- ```typescript
381
- // Example: TanStack Start-style middleware
382
104
  export const authMiddleware = () => {
383
- return createMiddleware().server(async (args) => {
384
- // Validate and potentially refresh session
385
- const { auth, refreshedSessionData } = await authService.withAuth(args.request);
105
+ return createMiddleware().server(async args => {
106
+ const { auth, refreshedSessionData } = await authService.withAuth(
107
+ args.request,
108
+ );
386
109
 
387
- // Pass auth to downstream via framework context
388
110
  const result = await args.next({
389
111
  context: { auth: () => auth },
390
112
  });
391
113
 
392
- // CRITICAL: Apply Set-Cookie if session was refreshed
114
+ // CRITICAL: Persist refreshed tokens to cookie
393
115
  if (refreshedSessionData) {
394
- const { headers } = await authService.saveSession(undefined, refreshedSessionData);
395
-
116
+ const { headers } = await authService.saveSession(
117
+ undefined,
118
+ refreshedSessionData,
119
+ );
396
120
  if (headers?.['Set-Cookie']) {
397
- // Clone immutable Response and add Set-Cookie header
398
121
  const newResponse = new Response(result.response.body, {
399
122
  status: result.response.status,
400
123
  statusText: result.response.statusText,
401
124
  headers: result.response.headers,
402
125
  });
403
126
  newResponse.headers.set('Set-Cookie', headers['Set-Cookie']);
404
-
405
127
  return { ...result, response: newResponse };
406
128
  }
407
129
  }
@@ -411,500 +133,93 @@ export const authMiddleware = () => {
411
133
  };
412
134
  ```
413
135
 
414
- **Why this matters:** If you don't apply the `Set-Cookie` header, refreshed tokens stay in memory but never persist to the cookie. This causes infinite refresh loops because the next request has the old (expired) token.
415
-
416
- ### Alternative: Use Core + Operations Directly
417
-
418
- For maximum flexibility, use the toolkit primitives directly:
419
-
420
- ```typescript
421
- import { AuthKitCore, AuthOperations, getWorkOS, getConfigurationProvider } from '@workos/authkit-session';
422
-
423
- const config = getConfigurationProvider();
424
- const client = getWorkOS(config.getConfig());
425
- const core = new AuthKitCore(config, client, encryption);
426
- const operations = new AuthOperations(core, client, config);
427
-
428
- // In your middleware
429
- async function middleware(request: Request) {
430
- const encrypted = await storage.getSession(request);
431
- if (!encrypted) {
432
- return { auth: { user: null } };
433
- }
434
-
435
- const session = await core.decryptSession(encrypted);
436
- const { valid, refreshed, session: validated, claims } =
437
- await core.validateAndRefresh(session);
438
-
439
- if (!valid) {
440
- return { auth: { user: null } };
441
- }
442
-
443
- // Handle refresh using your framework's patterns
444
- if (refreshed) {
445
- const encryptedSession = await core.encryptSession(validated);
446
- // Apply Set-Cookie using headers, locals, WeakMap, etc.
447
- }
448
-
449
- return {
450
- auth: {
451
- user: validated.user,
452
- sessionId: claims.sid,
453
- accessToken: validated.accessToken,
454
- refreshToken: validated.refreshToken,
455
- claims,
456
- impersonator: validated.impersonator,
457
- },
458
- };
459
- }
460
- ```
461
-
462
- ### Key Considerations
463
-
464
- - **Request Context**: Each framework handles context differently (headers, locals, WeakMap). Use your framework's idiomatic approach.
465
- - **Response Immutability**: Web-standard Response objects are immutable. Clone before modifying headers.
466
- - **Cookie Parsing**: Implement robust cookie parsing (handle edge cases like values with `=` signs).
467
- - **Set-Cookie Application**: Ensure refreshed sessions actually write to the HTTP response, not just memory.
468
- - **TypeScript**: Export proper types (`AuthResult`, `User`, etc.) for your framework's patterns.
469
- - **Configuration Validation**: Call `validateConfig()` early (first request) with helpful error messages.
136
+ **If you skip applying `Set-Cookie`, refreshed tokens never persist.** Next request sees the old expired token → infinite refresh loop.
470
137
 
471
- ### Reference Implementation
138
+ ## AuthResult Type
472
139
 
473
- See `@workos/authkit-tanstack-start` for a complete example:
474
- - Storage adapter with `applyHeaders()` override
475
- - Middleware with proper Set-Cookie handling
476
- - Server functions delegating to AuthOperations
477
- - Dynamic imports orchestrator (if your bundler needs it)
478
-
479
- ### Configuration Validation
480
-
481
- Framework adapters should validate configuration on startup to provide clear error messages:
140
+ `withAuth()` returns a discriminated union. If `auth.user` exists, all other properties exist:
482
141
 
483
142
  ```typescript
484
- import { validateConfig } from '@workos/authkit-session';
485
-
486
- // In your framework's initialization or middleware
487
- try {
488
- validateConfig();
489
- } catch (error) {
490
- // Framework will display helpful error message with all missing/invalid config
491
- throw error;
492
- }
493
- ```
494
-
495
- 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.
496
-
497
- ### Accessing Configuration
498
-
499
- Framework adapters can access configuration values directly:
500
-
501
- ```typescript
502
- import { getConfig, getConfigurationProvider } from '@workos/authkit-session';
503
-
504
- // Get a single config value
505
- const clientId = getConfig('clientId');
506
-
507
- // Get the ConfigurationProvider for more advanced use
508
- const provider = getConfigurationProvider();
509
- const config = provider.getConfig(); // Returns full AuthKitConfig object
510
- ```
511
-
512
- ## Core Concepts
513
-
514
- ### Session Management
515
-
516
- AuthKit SSR uses encrypted cookies to store session information. It handles:
517
-
518
- - Token encryption/decryption (using iron-webcrypto)
519
- - JWT validation and parsing
520
- - Session refresh logic
521
- - Session termination
522
-
523
- ### Adapter System
524
-
525
- 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.
526
-
527
- #### SessionStorage Interface
528
-
529
- ```typescript
530
- interface SessionStorage<TRequest, TResponse, TOptions = unknown> {
531
- getSession(request: TRequest): Promise<string | null>;
532
- saveSession(
533
- response: TResponse,
534
- sessionData: string,
535
- options?: TOptions,
536
- ): Promise<TResponse>;
537
- clearSession(response: TResponse, options?: TOptions): Promise<TResponse>;
538
- }
539
- ```
540
-
541
- #### CookieSessionStorage Base Class
542
-
543
- For cookie-based session storage, extend the provided `CookieSessionStorage` class:
544
-
545
- ```typescript
546
- import { CookieSessionStorage } from '@workos/authkit-session';
547
-
548
- abstract class CookieSessionStorage<TRequest, TResponse> {
549
- protected cookieName: string; // From config: cookieName
550
- protected cookieOptions: CookieOptions; // Derived from config
551
-
552
- // Implement these methods for your framework
553
- abstract getSession(request: TRequest): Promise<string | null>;
554
- abstract saveSession(
555
- response: TResponse,
556
- sessionData: string,
557
- ): Promise<TResponse>;
558
- abstract clearSession(response: TResponse): Promise<TResponse>;
559
- }
560
-
561
- interface CookieOptions {
562
- path?: string; // Default: '/'
563
- domain?: string; // From config: cookieDomain
564
- maxAge?: number; // From config: cookieMaxAge (400 days)
565
- httpOnly?: boolean; // Default: true
566
- secure?: boolean; // From config: apiHttps
567
- sameSite?: 'lax' | 'strict' | 'none'; // From config: cookieSameSite
568
- }
569
- ```
570
-
571
- #### Framework-Specific Examples
572
-
573
- **Express/Node.js:**
574
-
575
- ```typescript
576
- class ExpressStorage extends CookieSessionStorage<Request, Response> {
577
- async getSession(request: Request): Promise<string | null> {
578
- return request.cookies[this.cookieName] || null;
579
- }
580
-
581
- async saveSession(
582
- response: Response,
583
- sessionData: string,
584
- ): Promise<Response> {
585
- response.cookie(this.cookieName, sessionData, this.cookieOptions);
586
- return response;
587
- }
588
-
589
- async clearSession(response: Response): Promise<Response> {
590
- response.clearCookie(this.cookieName, { path: this.cookieOptions.path });
591
- return response;
592
- }
593
- }
594
- ```
595
-
596
- **Hono:**
597
-
598
- ```typescript
599
- class HonoStorage extends CookieSessionStorage<HonoRequest, HonoResponse> {
600
- async getSession(request: HonoRequest): Promise<string | null> {
601
- return getCookie(request, this.cookieName) || null;
602
- }
603
-
604
- async saveSession(
605
- response: HonoResponse,
606
- sessionData: string,
607
- ): Promise<HonoResponse> {
608
- setCookie(response, this.cookieName, sessionData, this.cookieOptions);
609
- return response;
610
- }
143
+ const { auth } = await authService.withAuth(request);
611
144
 
612
- async clearSession(response: HonoResponse): Promise<HonoResponse> {
613
- deleteCookie(response, this.cookieName);
614
- return response;
615
- }
145
+ if (!auth.user) {
146
+ return redirect('/login');
616
147
  }
617
- ```
618
-
619
- #### Creating Framework Adapters
620
-
621
- When creating a storage adapter:
622
-
623
- 1. **Extend `CookieSessionStorage`** for cookie-based storage (recommended)
624
- 2. **Implement `getSession()`** to extract encrypted session from cookies
625
- 3. **Optionally override `applyHeaders()`** to apply headers in framework-specific ways
626
- 4. **Use provided helpers**: `this.cookieName`, `this.cookieOptions`, `buildSetCookie()`
627
- 5. **Test thoroughly**: Ensure session persistence works across requests, especially after refresh
628
-
629
- ## Configuration
630
-
631
- AuthKit can be configured in multiple ways:
632
-
633
- ### Environment Variables
634
-
635
- ```bash
636
- WORKOS_CLIENT_ID=your-client-id
637
- WORKOS_API_KEY=your-api-key
638
- WORKOS_REDIRECT_URI=https://yourdomain.com/auth/callback
639
- WORKOS_COOKIE_PASSWORD=must-be-at-least-32-characters-long
640
- WORKOS_COOKIE_NAME=wos-session
641
- WORKOS_COOKIE_MAX_AGE=34560000
642
- WORKOS_API_HOSTNAME=api.workos.com
643
- WORKOS_API_HTTPS=true
644
- WORKOS_API_PORT=443
645
- ```
646
-
647
- **Environment Variable Naming Convention:**
648
- Environment variables follow the pattern: `WORKOS_{PROPERTY_NAME}` where the property name is converted from camelCase to UPPER_SNAKE_CASE.
649
-
650
- Examples:
651
148
 
652
- - `clientId` → `WORKOS_CLIENT_ID`
653
- - `redirectUri` → `WORKOS_REDIRECT_URI`
654
- - `cookiePassword` → `WORKOS_COOKIE_PASSWORD`
655
- - `cookieMaxAge` → `WORKOS_COOKIE_MAX_AGE`
656
-
657
- Environment variables always take precedence over programmatic configuration.
658
-
659
- ### Programmatic Configuration
660
-
661
- ```typescript
662
- import { configure } from '@workos/authkit-session';
663
-
664
- configure({
665
- clientId: 'your-client-id',
666
- apiKey: 'your-api-key',
667
- redirectUri: 'https://yourdomain.com/auth/callback',
668
- cookiePassword: 'must-be-at-least-32-characters-long',
669
- cookieName: 'wos-session', // Default: 'wos-session'
670
- cookieMaxAge: 60 * 60 * 24 * 400, // 400 days in seconds
671
- cookieSameSite: 'lax', // 'strict', 'lax', or 'none'
672
- cookieDomain: '.yourdomain.com', // Optional: cookie domain
673
- apiHostname: 'api.workos.com', // Optional: API hostname
674
- apiHttps: true, // Default: true
675
- apiPort: 443, // Optional: API port
676
- });
149
+ // TypeScript knows these exist (no ! needed)
150
+ auth.sessionId; // string
151
+ auth.accessToken; // string
152
+ auth.claims.sid; // string
677
153
  ```
678
154
 
679
- ## API Reference
680
-
681
- ### Toolkit API (Recommended)
682
-
683
- #### Core Configuration
684
-
685
- - `configure(config)`: Set up AuthKit with your WorkOS configuration
686
- - `validateConfig()`: Validate all required configuration values (throws descriptive error if invalid)
687
- - `getConfig(key)`: Get a specific configuration value
688
- - `getConfigurationProvider()`: Get the ConfigurationProvider instance
689
-
690
- #### Toolkit Classes
691
-
692
- - **`AuthKitCore`** - Pure business logic (JWT, crypto, refresh orchestration)
693
- - **`AuthOperations`** - WorkOS API operations (signOut, refreshSession, authorization URLs)
694
- - **`AuthService`** - Optional reference implementation orchestrating Core + Operations + Storage
695
- - **`CookieSessionStorage`** - Base class for cookie-based session storage
696
- - **`createAuthService(options)`** - Factory for creating AuthService instances
697
-
698
- See the [Architecture](#architecture) section for detailed usage of each class.
699
-
700
- ### AuthService Instance API
701
-
702
- When using `createAuthService()`, you get these methods:
155
+ ## Configuration Options
703
156
 
704
- #### Authentication & Session Management
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` |
705
167
 
706
- - **`withAuth<TCustomClaims>(request)`** - Validate session and auto-refresh if expiring
707
- - Returns: `{ auth: AuthResult<TCustomClaims>; refreshedSessionData?: string }`
708
- - `auth` is a discriminated union (see [AuthResult Type](#authresult-type-discriminated-union))
709
- - `refreshedSessionData` is present if token was refreshed (must be persisted via `saveSession()`)
168
+ Environment variables override programmatic config.
710
169
 
711
- - **`handleCallback(request, response, { code, state? })`** - Process OAuth callback
712
- - Returns: `{ response, headers, returnPathname, authResponse }`
170
+ ## API Overview
713
171
 
714
- - **`getSession(request)`** - Get decrypted session from request
715
- - Returns: `Session | null`
716
-
717
- - **`saveSession(response, sessionData)`** - Save encrypted session to storage
718
- - Returns: `{ response?: TResponse; headers?: HeadersBag }`
719
-
720
- - **`clearSession(response)`** - Clear session from storage
721
- - Returns: `{ response?: TResponse; headers?: HeadersBag }`
722
-
723
- #### WorkOS Operations (Delegated to AuthOperations)
724
-
725
- - **`signOut(sessionId, options?)`** - Generate logout URL + cookie clear header
726
- - Returns: `{ logoutUrl: string; clearCookieHeader: string }`
727
-
728
- - **`refreshSession(session, organizationId?)`** - Manually refresh session tokens
729
- - Returns: `{ auth: AuthResult; encryptedSession: string }`
730
-
731
- - **`switchOrganization(session, organizationId)`** - Switch to different organization
732
- - Returns: `{ auth: AuthResult; encryptedSession: string }`
733
-
734
- #### URL Generation (Delegated to AuthOperations)
735
-
736
- - **`getAuthorizationUrl(options)`** - Generate WorkOS authorization URL
737
- - Options: `returnPathname`, `redirectUri`, `screenHint`, `organizationId`, `loginHint`, `prompt`
738
-
739
- - **`getSignInUrl(options)`** - Generate sign-in URL (screenHint='sign-in')
740
- - Options: `returnPathname`, `redirectUri`, `organizationId`, `loginHint`, `prompt`
741
-
742
- - **`getSignUpUrl(options)`** - Generate sign-up URL (screenHint='sign-up')
743
- - Options: `returnPathname`, `redirectUri`, `organizationId`, `loginHint`, `prompt`
744
-
745
- ## Advanced Features
746
-
747
- ### Organization Switching
748
-
749
- Switch users between organizations without requiring re-authentication:
172
+ ### AuthService Methods
750
173
 
751
174
  ```typescript
752
- try {
753
- const { response: updatedResponse, authResult } =
754
- await authKit.switchToOrganization(
755
- request,
756
- response,
757
- 'org_new_organization_id',
758
- );
759
-
760
- // Use the updated response and new auth context
761
- const { user, sessionId, claims } = authResult;
762
- } catch (error) {
763
- if (error.authUrl) {
764
- // Handle cases requiring re-authentication (SSO, MFA)
765
- redirect(error.authUrl);
766
- }
767
- }
768
- ```
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)
769
181
 
770
- ### Token Claims Parsing
182
+ // WorkOS Operations
183
+ authService.signOut(sessionId, { returnTo }) // → { logoutUrl, clearCookieHeader }
184
+ authService.refreshSession(session, organizationId?)
185
+ authService.switchOrganization(session, organizationId)
771
186
 
772
- Extract and validate JWT claims from access tokens:
773
-
774
- ```typescript
775
- // Parse claims from current session
776
- const claims = await authKit.getTokenClaims<MyCustomClaims>(request);
777
-
778
- // Parse claims from specific token
779
- const specificClaims = await authKit.getTokenClaims<MyCustomClaims>(
780
- request,
781
- accessToken,
782
- );
783
-
784
- // Custom claims interface
785
- interface MyCustomClaims {
786
- custom_field: string;
787
- user_metadata: Record<string, unknown>;
788
- }
789
- ```
790
-
791
- ### TypeScript Support
792
-
793
- AuthKit provides full TypeScript support with generic type parameters:
794
-
795
- ```typescript
796
- interface CustomClaims {
797
- department: string;
798
- permissions: string[];
799
- }
800
-
801
- const { user, claims } = await authKit.withAuth<CustomClaims>(request);
802
- // claims is typed as BaseTokenClaims & CustomClaims
187
+ // URL Generation
188
+ authService.getAuthorizationUrl(options)
189
+ authService.getSignInUrl(options)
190
+ authService.getSignUpUrl(options)
803
191
  ```
804
192
 
805
- ### AuthResult Type (Discriminated Union)
806
-
807
- The `withAuth` method returns `{ auth: AuthResult; refreshedSessionData?: string }` where `AuthResult` is a **discriminated union** that TypeScript can narrow based on the `user` property:
808
-
809
- ```typescript
810
- type AuthResult<TCustomClaims = Record<string, unknown>> =
811
- | {
812
- user: null; // Not authenticated
813
- }
814
- | {
815
- user: User; // Authenticated user
816
- sessionId: string; // Session ID from JWT claims
817
- accessToken: string; // JWT access token
818
- refreshToken: string; // Refresh token
819
- claims: BaseTokenClaims & TCustomClaims; // Full JWT claims
820
- impersonator?: Impersonator; // Present if impersonating
821
- };
822
-
823
- interface BaseTokenClaims {
824
- sid: string; // Session ID
825
- org_id?: string; // Organization ID
826
- role?: string; // User role
827
- roles?: string[]; // User roles (array)
828
- permissions?: string[]; // User permissions
829
- entitlements?: string[]; // User entitlements
830
- feature_flags?: string[]; // Feature flags
831
- }
832
- ```
833
-
834
- **Why a discriminated union?**
835
-
836
- This pattern makes **impossible states unrepresentable**. You can't have a user without a sessionId, or a sessionId without a user. TypeScript enforces this at compile time.
193
+ ### Direct Access (Advanced)
837
194
 
838
- **Type narrowing in action:**
195
+ For maximum control, use the primitives directly:
839
196
 
840
197
  ```typescript
841
- const { auth } = await authService.withAuth(request);
842
-
843
- if (!auth.user) {
844
- // TypeScript knows: auth is { user: null }
845
- // No other properties exist in this branch
846
- return redirect('/login');
847
- }
198
+ import {
199
+ AuthKitCore,
200
+ AuthOperations,
201
+ getWorkOS,
202
+ getConfigurationProvider,
203
+ } from '@workos/authkit-session';
848
204
 
849
- // TypeScript knows: auth.user exists, so ALL required properties exist
850
- console.log(auth.sessionId); // ✅ string (no ! needed)
851
- console.log(auth.accessToken); // ✅ string
852
- console.log(auth.refreshToken); // ✅ string
853
- console.log(auth.claims.sid); // ✅ string
854
- console.log(auth.claims.org_id); // ✅ string | undefined (optional claim)
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);
855
209
 
856
- // This would be a TypeScript error in the !auth.user branch:
857
- // console.log(auth.sessionId); // ❌ Property 'sessionId' does not exist
210
+ // Use core.validateAndRefresh(), core.encryptSession(), etc.
858
211
  ```
859
212
 
860
- **Benefits:**
861
- - No more optional chaining (`auth.user?.id`)
862
- - No more null assertions (`auth.sessionId!`)
863
- - Impossible to access properties that don't exist
864
- - Compiler catches bugs before runtime
865
-
866
- ### Additional Exports
867
-
868
- The library also exports these components for advanced use cases:
869
-
870
- ```typescript
871
- import {
872
- // Core toolkit
873
- AuthKitCore, // Pure business logic (JWT, crypto, refresh)
874
- AuthOperations, // WorkOS API operations
875
- CookieSessionStorage, // Base class for cookie storage
876
-
877
- // Configuration
878
- configure, // Set up configuration
879
- validateConfig, // Validate required config values
880
- getConfig, // Get specific config value
881
- getConfigurationProvider, // Get ConfigurationProvider instance
882
- ConfigurationProvider, // ConfigurationProvider class
883
-
884
- // WorkOS client
885
- getWorkOS, // WorkOS client factory
886
-
887
- // Types
888
- type SessionStorage,
889
- type AuthKitConfig,
890
- type AuthResult,
891
- type Session,
892
- type User,
893
- type Impersonator,
894
- type BaseTokenClaims,
895
- type GetAuthorizationUrlOptions,
896
- // ... and more
897
- } from '@workos/authkit-session';
898
- ```
213
+ ## Technical Details
899
214
 
900
- ## 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.
901
219
 
902
- AuthKit uses iron-webcrypto for secure, encrypted cookies with the following security features:
220
+ ## Reference Implementation
903
221
 
904
- - Encrypted cookies (AES-256-CBC)
905
- - HMAC validation (SHA-256)
906
- - Customizable cookie settings (HttpOnly, SameSite, etc.)
907
- - Token refresh mechanism
222
+ See [`@workos/authkit-tanstack-start`](https://github.com/workos/authkit-tanstack-start) for a complete example.
908
223
 
909
224
  ## License
910
225