@workos/authkit-session 0.0.1-alpha.1 → 0.0.1-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # @workos/authkit-session
2
2
 
3
3
  > [!WARNING]
4
- >This is prerelease software. APIs may change without notice.
4
+ > This is prerelease software. APIs may change without notice.
5
5
 
6
6
  A framework-agnostic authentication library for WorkOS with a modular adapter system for server-side rendered applications.
7
7
 
@@ -9,9 +9,11 @@ A framework-agnostic authentication library for WorkOS with a modular adapter sy
9
9
 
10
10
  - **Framework-agnostic core**: Common authentication logic that works across platforms
11
11
  - **Adapter pattern**: Simple interface for framework-specific implementations
12
- - **Session management**: Secure cookie-based authentication
12
+ - **Session management**: Secure encrypted cookie-based authentication
13
13
  - **JWT handling**: Token validation, parsing, and refresh
14
- - **Type-safe API**: Full TypeScript support
14
+ - **Organization switching**: Switch user context between organizations
15
+ - **Type-safe API**: Full TypeScript support with custom claims
16
+ - **Token claims parsing**: Extract and validate JWT claims
15
17
 
16
18
  ## Installation
17
19
 
@@ -44,36 +46,84 @@ configure({
44
46
  2. Create a storage adapter for your framework:
45
47
 
46
48
  ```typescript
47
- import { createAuthKitFactory } from '@workos/authkit-session';
48
- import type { SessionStorage } from '@workos/authkit-session';
49
-
50
- // Create your framework-specific storage adapter
51
- class MyFrameworkStorage implements SessionStorage<MyRequest, MyResponse> {
52
- cookieName: string;
53
-
54
- constructor(cookieName = 'wos-session') {
55
- this.cookieName = cookieName;
49
+ import {
50
+ createAuthKitFactory,
51
+ CookieSessionStorage,
52
+ } from '@workos/authkit-session';
53
+ import type {
54
+ SessionStorage,
55
+ ConfigurationProvider,
56
+ } from '@workos/authkit-session';
57
+
58
+ // Option 1: Extend CookieSessionStorage (recommended)
59
+ class MyFrameworkStorage extends CookieSessionStorage<MyRequest, MyResponse> {
60
+ constructor(config: ConfigurationProvider) {
61
+ super(config);
56
62
  }
57
63
 
58
64
  async getSession(request: MyRequest): Promise<string | null> {
59
- // Framework-specific implementation to get cookie
60
- return getCookieFromRequest(request, this.cookieName);
65
+ // Extract cookie from your framework's request object
66
+ const cookies = request.headers.cookie || '';
67
+ const match = cookies.match(new RegExp(`${this.cookieName}=([^;]+)`));
68
+ return match ? decodeURIComponent(match[1]) : null;
61
69
  }
62
70
 
63
- async saveSession(response: MyResponse, sessionData: string): Promise<MyResponse> {
64
- // Framework-specific implementation to set cookie
65
- return setCookieOnResponse(response, this.cookieName, sessionData);
71
+ async saveSession(
72
+ response: MyResponse,
73
+ sessionData: string,
74
+ ): Promise<MyResponse> {
75
+ // Set cookie on your framework's response object
76
+ const cookieValue = `${this.cookieName}=${encodeURIComponent(sessionData)}; ${this.getCookieAttributes()}`;
77
+ response.headers['Set-Cookie'] = cookieValue;
78
+ return response;
66
79
  }
67
80
 
68
81
  async clearSession(response: MyResponse): Promise<MyResponse> {
69
- // Framework-specific implementation to clear cookie
70
- return clearCookieOnResponse(response, this.cookieName);
82
+ // Clear cookie by setting expired date
83
+ const expiredCookie = `${this.cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`;
84
+ response.headers['Set-Cookie'] = expiredCookie;
85
+ return response;
86
+ }
87
+
88
+ private getCookieAttributes(): string {
89
+ const attrs = [];
90
+ if (this.cookieOptions.path) attrs.push(`path=${this.cookieOptions.path}`);
91
+ if (this.cookieOptions.domain)
92
+ attrs.push(`domain=${this.cookieOptions.domain}`);
93
+ if (this.cookieOptions.maxAge)
94
+ attrs.push(`max-age=${this.cookieOptions.maxAge}`);
95
+ if (this.cookieOptions.httpOnly) attrs.push('httponly');
96
+ if (this.cookieOptions.secure) attrs.push('secure');
97
+ if (this.cookieOptions.sameSite)
98
+ attrs.push(`samesite=${this.cookieOptions.sameSite}`);
99
+ return attrs.join('; ');
100
+ }
101
+ }
102
+
103
+ // Option 2: Implement SessionStorage interface directly
104
+ class CustomStorage implements SessionStorage<MyRequest, MyResponse> {
105
+ async getSession(request: MyRequest): Promise<string | null> {
106
+ // Your custom session retrieval logic
107
+ return getSessionFromRequest(request);
108
+ }
109
+
110
+ async saveSession(
111
+ response: MyResponse,
112
+ sessionData: string,
113
+ ): Promise<MyResponse> {
114
+ // Your custom session storage logic
115
+ return saveSessionToResponse(response, sessionData);
116
+ }
117
+
118
+ async clearSession(response: MyResponse): Promise<MyResponse> {
119
+ // Your custom session clearing logic
120
+ return clearSessionFromResponse(response);
71
121
  }
72
122
  }
73
123
 
74
124
  // Create your AuthKit instance
75
125
  const authKit = createAuthKitFactory<MyRequest, MyResponse>({
76
- sessionStorageFactory: (config) => new MyFrameworkStorage(),
126
+ sessionStorageFactory: config => new MyFrameworkStorage(config),
77
127
  });
78
128
  ```
79
129
 
@@ -81,8 +131,8 @@ const authKit = createAuthKitFactory<MyRequest, MyResponse>({
81
131
 
82
132
  ```typescript
83
133
  // Validate a session
84
- const authResult = await authKit.withAuth(request);
85
- const { user, claims, accessToken, refreshToken, sessionId, impersonator } = authResult;
134
+ const { user, claims, sessionId, impersonator, accessToken, refreshToken } =
135
+ await authKit.withAuth(request);
86
136
 
87
137
  // Generate an authorization URL
88
138
  const authUrl = await authKit.getAuthorizationUrl({
@@ -91,9 +141,29 @@ const authUrl = await authKit.getAuthorizationUrl({
91
141
  screenHint: 'sign-in', // or 'sign-up'
92
142
  });
93
143
 
94
- // Refresh a session
95
- const refreshResult = await authKit.refreshSession(session);
96
- const { user, sessionId, organizationId, role, permissions, entitlements, impersonator, accessToken, claims, sessionData, session: newSession } = refreshResult;
144
+ // Generate sign-in/sign-up URLs
145
+ const signInUrl = await authKit.getSignInUrl({
146
+ redirectUri: 'https://yourdomain.com/auth/callback',
147
+ });
148
+ const signUpUrl = await authKit.getSignUpUrl({
149
+ redirectUri: 'https://yourdomain.com/auth/callback',
150
+ });
151
+
152
+ // Get token claims
153
+ const claims = await authKit.getTokenClaims(request);
154
+ // Or parse specific access token
155
+ const specificClaims = await authKit.getTokenClaims(request, accessToken);
156
+
157
+ // Switch to different organization
158
+ const { response: updatedResponse, authResult: newAuth } =
159
+ await authKit.switchToOrganization(request, response, 'org_123');
160
+
161
+ // Terminate session and get logout URL
162
+ const { response: clearedResponse, logoutUrl } = await authKit.getLogoutUrl(
163
+ session,
164
+ response,
165
+ { returnTo: 'https://yourdomain.com' },
166
+ );
97
167
  ```
98
168
 
99
169
  ## Core Concepts
@@ -109,17 +179,122 @@ AuthKit SSR uses encrypted cookies to store session information. It handles:
109
179
 
110
180
  ### Adapter System
111
181
 
112
- The adapter pattern uses a storage interface to abstract framework-specific concepts:
182
+ 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.
183
+
184
+ #### SessionStorage Interface
113
185
 
114
186
  ```typescript
115
187
  interface SessionStorage<TRequest, TResponse, TOptions = unknown> {
116
188
  getSession(request: TRequest): Promise<string | null>;
117
- saveSession(response: TResponse, sessionData: string, options?: TOptions): Promise<TResponse>;
189
+ saveSession(
190
+ response: TResponse,
191
+ sessionData: string,
192
+ options?: TOptions,
193
+ ): Promise<TResponse>;
118
194
  clearSession(response: TResponse, options?: TOptions): Promise<TResponse>;
119
195
  }
120
196
  ```
121
197
 
122
- Each framework adapter implements this interface to handle its specific request/response objects.
198
+ #### CookieSessionStorage Base Class
199
+
200
+ For cookie-based session storage, extend the provided `CookieSessionStorage` class:
201
+
202
+ ```typescript
203
+ import { CookieSessionStorage } from '@workos/authkit-session';
204
+
205
+ abstract class CookieSessionStorage<TRequest, TResponse> {
206
+ protected cookieName: string; // From config: cookieName
207
+ protected cookieOptions: CookieOptions; // Derived from config
208
+
209
+ // Implement these methods for your framework
210
+ abstract getSession(request: TRequest): Promise<string | null>;
211
+ abstract saveSession(
212
+ response: TResponse,
213
+ sessionData: string,
214
+ ): Promise<TResponse>;
215
+ abstract clearSession(response: TResponse): Promise<TResponse>;
216
+ }
217
+
218
+ interface CookieOptions {
219
+ path?: string; // Default: '/'
220
+ domain?: string; // From config: cookieDomain
221
+ maxAge?: number; // From config: cookieMaxAge (400 days)
222
+ httpOnly?: boolean; // Default: true
223
+ secure?: boolean; // From config: apiHttps
224
+ sameSite?: 'lax' | 'strict' | 'none'; // From config: cookieSameSite
225
+ }
226
+ ```
227
+
228
+ #### Framework-Specific Examples
229
+
230
+ **Express/Node.js:**
231
+
232
+ ```typescript
233
+ class ExpressStorage extends CookieSessionStorage<Request, Response> {
234
+ async getSession(request: Request): Promise<string | null> {
235
+ return request.cookies[this.cookieName] || null;
236
+ }
237
+
238
+ async saveSession(
239
+ response: Response,
240
+ sessionData: string,
241
+ ): Promise<Response> {
242
+ response.cookie(this.cookieName, sessionData, this.cookieOptions);
243
+ return response;
244
+ }
245
+
246
+ async clearSession(response: Response): Promise<Response> {
247
+ response.clearCookie(this.cookieName, { path: this.cookieOptions.path });
248
+ return response;
249
+ }
250
+ }
251
+ ```
252
+
253
+ **Hono:**
254
+
255
+ ```typescript
256
+ class HonoStorage extends CookieSessionStorage<HonoRequest, HonoResponse> {
257
+ async getSession(request: HonoRequest): Promise<string | null> {
258
+ return getCookie(request, this.cookieName) || null;
259
+ }
260
+
261
+ async saveSession(
262
+ response: HonoResponse,
263
+ sessionData: string,
264
+ ): Promise<HonoResponse> {
265
+ setCookie(response, this.cookieName, sessionData, this.cookieOptions);
266
+ return response;
267
+ }
268
+
269
+ async clearSession(response: HonoResponse): Promise<HonoResponse> {
270
+ deleteCookie(response, this.cookieName);
271
+ return response;
272
+ }
273
+ }
274
+ ```
275
+
276
+ #### Creating Framework Adapters
277
+
278
+ When creating an adapter for a new framework:
279
+
280
+ 1. **Choose your approach**: Extend `CookieSessionStorage` for cookie-based storage, or implement `SessionStorage` directly for custom storage
281
+ 2. **Handle framework request/response objects**: Extract cookies from requests and set cookies on responses
282
+ 3. **Respect configuration**: Use `this.cookieName` and `this.cookieOptions` from the base class
283
+ 4. **Test thoroughly**: Ensure session persistence works across requests
284
+
285
+ #### Factory Configuration
286
+
287
+ ```typescript
288
+ const authKit = createAuthKitFactory<MyRequest, MyResponse>({
289
+ sessionStorageFactory: config => new MyFrameworkStorage(config),
290
+
291
+ // Optional: Custom session encryption
292
+ sessionEncryptionFactory: config => myCustomEncryption,
293
+
294
+ // Optional: Custom WorkOS client
295
+ clientFactory: config => myCustomWorkOSClient,
296
+ });
297
+ ```
123
298
 
124
299
  ## Configuration
125
300
 
@@ -132,6 +307,11 @@ WORKOS_CLIENT_ID=your-client-id
132
307
  WORKOS_API_KEY=your-api-key
133
308
  WORKOS_REDIRECT_URI=https://yourdomain.com/auth/callback
134
309
  WORKOS_COOKIE_PASSWORD=must-be-at-least-32-characters-long
310
+ WORKOS_COOKIE_NAME=wos-session
311
+ WORKOS_COOKIE_MAX_AGE=34560000
312
+ WORKOS_API_HOSTNAME=api.workos.com
313
+ WORKOS_API_HTTPS=true
314
+ WORKOS_API_PORT=443
135
315
  ```
136
316
 
137
317
  ### Programmatic Configuration
@@ -144,9 +324,13 @@ configure({
144
324
  apiKey: 'your-api-key',
145
325
  redirectUri: 'https://yourdomain.com/auth/callback',
146
326
  cookiePassword: 'must-be-at-least-32-characters-long',
147
- cookieName: 'your-custom-cookie-name', // Default: 'wos-session'
148
- cookieMaxAge: 60 * 60 * 24 * 30, // 30 days in seconds
327
+ cookieName: 'wos-session', // Default: 'wos-session'
328
+ cookieMaxAge: 60 * 60 * 24 * 400, // 400 days in seconds
149
329
  cookieSameSite: 'lax', // 'strict', 'lax', or 'none'
330
+ cookieDomain: '.yourdomain.com', // Optional: cookie domain
331
+ apiHostname: 'api.workos.com', // Optional: API hostname
332
+ apiHttps: true, // Default: true
333
+ apiPort: 443, // Optional: API port
150
334
  });
151
335
  ```
152
336
 
@@ -160,13 +344,110 @@ configure({
160
344
 
161
345
  ### AuthKit Instance API
162
346
 
163
- - `withAuth(request)`: Validate the current session and return `AuthResult` with user, claims, tokens, and session info
347
+ - `withAuth<TCustomClaims>(request)`: Validate the current session and return `AuthResult<TCustomClaims>`
164
348
  - `getAuthorizationUrl(options)`: Generate a WorkOS authorization URL with `returnPathname`, `redirectUri`, and `screenHint`
165
- - `getSignInUrl(options)`: Generate a sign-in URL (calls `getAuthorizationUrl` with `screenHint: 'sign-in'`)
166
- - `getSignUpUrl(options)`: Generate a sign-up URL (calls `getAuthorizationUrl` with `screenHint: 'sign-up'`)
167
- - `refreshSession(session)`: Refresh an existing session and return updated session data
168
- - `saveSession(response, sessionData)`: Save session data to a response
169
- - `getLogoutUrl(session, response, options)`: End a user session and return logout URL with updated response
349
+ - `getSignInUrl(options)`: Generate a sign-in URL with `organizationId`, `loginHint`, and `redirectUri`
350
+ - `getSignUpUrl(options)`: Generate a sign-up URL with `organizationId`, `loginHint`, and `redirectUri`
351
+ - `getTokenClaims<TCustomClaims>(request, accessToken?)`: Parse JWT token claims from session or specific token
352
+ - `switchToOrganization(request, response, organizationId)`: Switch user to different organization context
353
+ - `saveSession(response, sessionData)`: Save encrypted session data to response
354
+ - `getLogoutUrl(session, response, options?)`: Terminate session and return logout URL with cleared response
355
+
356
+ ## Advanced Features
357
+
358
+ ### Organization Switching
359
+
360
+ Switch users between organizations without requiring re-authentication:
361
+
362
+ ```typescript
363
+ try {
364
+ const { response: updatedResponse, authResult } =
365
+ await authKit.switchToOrganization(
366
+ request,
367
+ response,
368
+ 'org_new_organization_id',
369
+ );
370
+
371
+ // Use the updated response and new auth context
372
+ const { user, sessionId, claims } = authResult;
373
+ } catch (error) {
374
+ if (error.authUrl) {
375
+ // Handle cases requiring re-authentication (SSO, MFA)
376
+ redirect(error.authUrl);
377
+ }
378
+ }
379
+ ```
380
+
381
+ ### Token Claims Parsing
382
+
383
+ Extract and validate JWT claims from access tokens:
384
+
385
+ ```typescript
386
+ // Parse claims from current session
387
+ const claims = await authKit.getTokenClaims<MyCustomClaims>(request);
388
+
389
+ // Parse claims from specific token
390
+ const specificClaims = await authKit.getTokenClaims<MyCustomClaims>(
391
+ request,
392
+ accessToken,
393
+ );
394
+
395
+ // Custom claims interface
396
+ interface MyCustomClaims {
397
+ custom_field: string;
398
+ user_metadata: Record<string, unknown>;
399
+ }
400
+ ```
401
+
402
+ ### TypeScript Support
403
+
404
+ AuthKit provides full TypeScript support with generic type parameters:
405
+
406
+ ```typescript
407
+ interface CustomClaims {
408
+ department: string;
409
+ permissions: string[];
410
+ }
411
+
412
+ const { user, claims } = await authKit.withAuth<CustomClaims>(request);
413
+ // claims is typed as BaseTokenClaims & CustomClaims
414
+ ```
415
+
416
+ ### AuthResult Interface
417
+
418
+ The `withAuth` method returns an `AuthResult` object with the following structure:
419
+
420
+ ```typescript
421
+ interface AuthResult<TCustomClaims = Record<string, unknown>> {
422
+ user?: User | null; // WorkOS user object
423
+ claims?: BaseTokenClaims & TCustomClaims; // JWT token claims
424
+ impersonator?: Impersonator; // Impersonation context if any
425
+ accessToken?: string; // JWT access token
426
+ refreshToken?: string; // Refresh token
427
+ sessionId?: string; // Session identifier from claims
428
+ }
429
+
430
+ interface BaseTokenClaims {
431
+ sid: string; // Session ID
432
+ org_id?: string; // Organization ID
433
+ role?: string; // User role
434
+ permissions?: string[]; // User permissions
435
+ entitlements?: string[]; // User entitlements
436
+ feature_flags?: string[]; // Feature flags
437
+ }
438
+ ```
439
+
440
+ ### Additional Exports
441
+
442
+ The library also exports these components for advanced use cases:
443
+
444
+ ```typescript
445
+ import {
446
+ SessionManager, // Core session management class
447
+ CookieSessionStorage, // Abstract cookie storage base class
448
+ getWorkOS, // WorkOS client factory
449
+ } from '@workos/authkit-session';
450
+ ```
170
451
 
171
452
  ## Security
172
453