@workos/authkit-session 0.1.2 → 0.2.0-beta.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.
- package/README.md +507 -232
- package/dist/core/AuthKitCore.d.ts +107 -0
- package/dist/core/AuthKitCore.d.ts.map +1 -0
- package/dist/core/AuthKitCore.js +189 -0
- package/dist/core/AuthKitCore.js.map +1 -0
- package/dist/core/session/CookieSessionStorage.d.ts.map +1 -1
- package/dist/core/session/CookieSessionStorage.js +22 -3
- package/dist/core/session/CookieSessionStorage.js.map +1 -1
- package/dist/core/session/types.d.ts +27 -7
- package/dist/core/session/types.d.ts.map +1 -1
- package/dist/index.d.ts +27 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +48 -4
- package/dist/index.js.map +1 -1
- package/dist/operations/AuthOperations.d.ts +84 -0
- package/dist/operations/AuthOperations.d.ts.map +1 -0
- package/dist/operations/AuthOperations.js +147 -0
- package/dist/operations/AuthOperations.js.map +1 -0
- package/dist/service/AuthService.d.ts +156 -0
- package/dist/service/AuthService.d.ts.map +1 -0
- package/dist/service/AuthService.js +225 -0
- package/dist/service/AuthService.js.map +1 -0
- package/dist/service/factory.d.ts +37 -0
- package/dist/service/factory.d.ts.map +1 -0
- package/dist/service/factory.js +46 -0
- package/dist/service/factory.js.map +1 -0
- package/package.json +6 -6
- package/src/core/AuthKitCore.spec.ts +269 -0
- package/src/core/AuthKitCore.ts +239 -0
- package/src/core/session/CookieSessionStorage.spec.ts +17 -0
- package/src/core/session/CookieSessionStorage.ts +22 -2
- package/src/core/session/types.ts +30 -8
- package/src/index.ts +55 -4
- package/src/operations/AuthOperations.spec.ts +240 -0
- package/src/operations/AuthOperations.ts +192 -0
- package/src/service/AuthService.spec.ts +241 -0
- package/src/service/AuthService.ts +293 -0
- package/src/service/factory.spec.ts +109 -0
- package/src/service/factory.ts +69 -0
- package/dist/core/createAuthKitFactory.d.ts +0 -64
- package/dist/core/createAuthKitFactory.d.ts.map +0 -1
- package/dist/core/createAuthKitFactory.js +0 -95
- package/dist/core/createAuthKitFactory.js.map +0 -1
- package/dist/core/session/SessionManager.d.ts +0 -51
- package/dist/core/session/SessionManager.d.ts.map +0 -1
- package/dist/core/session/SessionManager.js +0 -238
- package/dist/core/session/SessionManager.js.map +0 -1
- package/src/core/createAuthKitFactory.spec.ts +0 -161
- package/src/core/createAuthKitFactory.ts +0 -195
- package/src/core/session/SessionManager.spec.ts +0 -357
- package/src/core/session/SessionManager.ts +0 -357
package/README.md
CHANGED
|
@@ -3,19 +3,100 @@
|
|
|
3
3
|
> [!WARNING]
|
|
4
4
|
> This is prerelease software. APIs may change without notice.
|
|
5
5
|
|
|
6
|
-
A
|
|
6
|
+
**A toolkit library for building WorkOS AuthKit integrations.**
|
|
7
7
|
|
|
8
|
-
This library
|
|
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.
|
|
9
27
|
|
|
10
28
|
## Features
|
|
11
29
|
|
|
12
|
-
- **
|
|
13
|
-
- **
|
|
14
|
-
- **
|
|
15
|
-
- **
|
|
16
|
-
- **
|
|
17
|
-
- **
|
|
18
|
-
|
|
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.
|
|
19
100
|
|
|
20
101
|
## Installation
|
|
21
102
|
|
|
@@ -32,231 +113,368 @@ yarn add @workos/authkit-session
|
|
|
32
113
|
|
|
33
114
|
## Quick Start
|
|
34
115
|
|
|
35
|
-
1. Configure AuthKit
|
|
116
|
+
### 1. Configure AuthKit
|
|
117
|
+
|
|
118
|
+
Set up your WorkOS credentials using environment variables (recommended):
|
|
119
|
+
|
|
120
|
+
```bash
|
|
121
|
+
WORKOS_CLIENT_ID=your-client-id
|
|
122
|
+
WORKOS_API_KEY=your-api-key
|
|
123
|
+
WORKOS_REDIRECT_URI=https://yourdomain.com/auth/callback
|
|
124
|
+
WORKOS_COOKIE_PASSWORD=must-be-at-least-32-characters-long-secret
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
Or configure programmatically:
|
|
36
128
|
|
|
37
129
|
```typescript
|
|
38
|
-
import { configure
|
|
130
|
+
import { configure } from '@workos/authkit-session';
|
|
39
131
|
|
|
40
132
|
configure({
|
|
41
133
|
clientId: 'your-client-id',
|
|
42
|
-
apiKey: 'your-
|
|
134
|
+
apiKey: 'your-api-key',
|
|
43
135
|
redirectUri: 'https://yourdomain.com/auth/callback',
|
|
44
136
|
cookiePassword: 'must-be-at-least-32-characters-long-secret',
|
|
45
137
|
});
|
|
46
138
|
```
|
|
47
139
|
|
|
48
|
-
2. Create a
|
|
140
|
+
### 2. Create a Storage Adapter
|
|
141
|
+
|
|
142
|
+
Extend `CookieSessionStorage` for your framework's request/response objects:
|
|
49
143
|
|
|
50
144
|
```typescript
|
|
51
|
-
import {
|
|
52
|
-
createAuthKitFactory,
|
|
53
|
-
CookieSessionStorage,
|
|
54
|
-
} from '@workos/authkit-session';
|
|
55
|
-
import type {
|
|
56
|
-
SessionStorage,
|
|
57
|
-
ConfigurationProvider,
|
|
58
|
-
} from '@workos/authkit-session';
|
|
145
|
+
import { CookieSessionStorage, getConfigurationProvider } from '@workos/authkit-session';
|
|
59
146
|
|
|
60
|
-
//
|
|
61
|
-
class MyFrameworkStorage extends CookieSessionStorage<
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
147
|
+
// Web-standard Request/Response example
|
|
148
|
+
class MyFrameworkStorage extends CookieSessionStorage<Request, Response> {
|
|
149
|
+
async getSession(request: Request): Promise<string | null> {
|
|
150
|
+
const cookieHeader = request.headers.get('cookie');
|
|
151
|
+
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
|
+
);
|
|
65
160
|
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
const cookies = request.headers.cookie || '';
|
|
69
|
-
const match = cookies.match(new RegExp(`${this.cookieName}=([^;]+)`));
|
|
70
|
-
return match ? decodeURIComponent(match[1]) : null;
|
|
161
|
+
const value = cookies[this.cookieName];
|
|
162
|
+
return value ? decodeURIComponent(value) : null;
|
|
71
163
|
}
|
|
72
164
|
|
|
73
|
-
async
|
|
74
|
-
response:
|
|
75
|
-
|
|
76
|
-
): Promise<
|
|
77
|
-
//
|
|
78
|
-
const
|
|
79
|
-
|
|
80
|
-
|
|
165
|
+
protected async applyHeaders(
|
|
166
|
+
response: Response | undefined,
|
|
167
|
+
headers: Record<string, string>,
|
|
168
|
+
): Promise<{ response: Response }> {
|
|
169
|
+
// Create or clone response to apply headers
|
|
170
|
+
const newResponse = response
|
|
171
|
+
? new Response(response.body, {
|
|
172
|
+
status: response.status,
|
|
173
|
+
statusText: response.statusText,
|
|
174
|
+
headers: new Headers(response.headers),
|
|
175
|
+
})
|
|
176
|
+
: new Response();
|
|
177
|
+
|
|
178
|
+
// Apply headers
|
|
179
|
+
Object.entries(headers).forEach(([key, value]) => {
|
|
180
|
+
newResponse.headers.append(key, value);
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
return { response: newResponse };
|
|
81
184
|
}
|
|
185
|
+
}
|
|
186
|
+
```
|
|
82
187
|
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
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()`
|
|
89
193
|
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
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
|
-
}
|
|
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)
|
|
104
197
|
|
|
105
|
-
|
|
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
|
-
}
|
|
198
|
+
### 3. Create AuthService Instance
|
|
111
199
|
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
sessionData: string,
|
|
115
|
-
): Promise<MyResponse> {
|
|
116
|
-
// Your custom session storage logic
|
|
117
|
-
return saveSessionToResponse(response, sessionData);
|
|
118
|
-
}
|
|
200
|
+
```typescript
|
|
201
|
+
import { createAuthService } from '@workos/authkit-session';
|
|
119
202
|
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
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');
|
|
124
218
|
}
|
|
125
219
|
|
|
126
|
-
//
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
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
|
|
130
224
|
```
|
|
131
225
|
|
|
132
|
-
|
|
226
|
+
**Apply refreshed session (if token was refreshed):**
|
|
133
227
|
|
|
134
228
|
```typescript
|
|
135
|
-
|
|
136
|
-
const {
|
|
137
|
-
|
|
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
|
+
```
|
|
138
235
|
|
|
139
|
-
|
|
140
|
-
// Framework adapters should handle redirects when user is null
|
|
236
|
+
**Generate authentication URLs:**
|
|
141
237
|
|
|
142
|
-
|
|
143
|
-
|
|
238
|
+
```typescript
|
|
239
|
+
// Get sign-in URL
|
|
240
|
+
const signInUrl = await authService.getSignInUrl({
|
|
144
241
|
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
242
|
});
|
|
151
243
|
|
|
152
|
-
//
|
|
153
|
-
const
|
|
154
|
-
returnPathname: '/dashboard',
|
|
155
|
-
redirectUri: 'https://yourdomain.com/auth/callback',
|
|
156
|
-
organizationId: 'org_123', // Optional
|
|
157
|
-
});
|
|
158
|
-
const signUpUrl = await authKit.getSignUpUrl({
|
|
244
|
+
// Get sign-up URL
|
|
245
|
+
const signUpUrl = await authService.getSignUpUrl({
|
|
159
246
|
returnPathname: '/welcome',
|
|
160
|
-
redirectUri: 'https://yourdomain.com/auth/callback',
|
|
161
247
|
});
|
|
162
248
|
|
|
163
|
-
// Get
|
|
164
|
-
const
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
//
|
|
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',
|
|
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
|
|
180
255
|
});
|
|
256
|
+
```
|
|
181
257
|
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
258
|
+
**Handle OAuth callback:**
|
|
259
|
+
|
|
260
|
+
```typescript
|
|
261
|
+
const code = url.searchParams.get('code');
|
|
262
|
+
const state = url.searchParams.get('state');
|
|
186
263
|
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
session,
|
|
264
|
+
const result = await authService.handleCallback(
|
|
265
|
+
request,
|
|
190
266
|
response,
|
|
191
|
-
{
|
|
267
|
+
{ code, state },
|
|
192
268
|
);
|
|
193
269
|
|
|
194
|
-
//
|
|
195
|
-
|
|
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:**
|
|
196
276
|
|
|
197
|
-
|
|
198
|
-
const
|
|
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 },
|
|
286
|
+
});
|
|
199
287
|
```
|
|
200
288
|
|
|
201
|
-
|
|
289
|
+
**Switch organization:**
|
|
202
290
|
|
|
203
|
-
|
|
291
|
+
```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
|
|
204
300
|
|
|
205
|
-
|
|
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.
|
|
206
302
|
|
|
207
|
-
|
|
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
|
|
303
|
+
### Recommended Approach: Use AuthService
|
|
211
304
|
|
|
212
|
-
|
|
305
|
+
The simplest path is to use `createAuthService()` with your storage adapter:
|
|
213
306
|
|
|
214
307
|
```typescript
|
|
215
|
-
// src/storage.ts -
|
|
308
|
+
// src/storage.ts - Your framework's storage adapter
|
|
216
309
|
import { CookieSessionStorage } from '@workos/authkit-session';
|
|
217
|
-
import type { ConfigurationProvider } from '@workos/authkit-session';
|
|
218
310
|
|
|
219
|
-
export class
|
|
220
|
-
|
|
221
|
-
|
|
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
|
+
}
|
|
222
340
|
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
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
|
+
}
|
|
226
350
|
|
|
227
|
-
|
|
351
|
+
// src/index.ts - Create auth instance
|
|
352
|
+
import { createAuthService, getConfigurationProvider } from '@workos/authkit-session';
|
|
353
|
+
import { MyFrameworkStorage } from './storage.js';
|
|
228
354
|
|
|
229
|
-
|
|
230
|
-
sessionStorageFactory: config => new
|
|
355
|
+
const authService = createAuthService({
|
|
356
|
+
sessionStorageFactory: (config) => new MyFrameworkStorage(getConfigurationProvider()),
|
|
231
357
|
});
|
|
232
358
|
|
|
233
|
-
//
|
|
234
|
-
export async function withAuth(
|
|
235
|
-
return
|
|
359
|
+
// Export framework-specific wrappers
|
|
360
|
+
export async function withAuth(request: Request) {
|
|
361
|
+
return authService.withAuth(request);
|
|
236
362
|
}
|
|
237
363
|
|
|
238
|
-
export async function
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
const state = url.searchParams.get('state');
|
|
364
|
+
export async function getSignInUrl(returnPathname?: string) {
|
|
365
|
+
return authService.getSignInUrl({ returnPathname });
|
|
366
|
+
}
|
|
242
367
|
|
|
243
|
-
|
|
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
|
|
244
379
|
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
380
|
+
```typescript
|
|
381
|
+
// Example: TanStack Start-style middleware
|
|
382
|
+
export const authMiddleware = () => {
|
|
383
|
+
return createMiddleware().server(async (args) => {
|
|
384
|
+
// Validate and potentially refresh session
|
|
385
|
+
const { auth, refreshedSessionData } = await authService.withAuth(args.request);
|
|
386
|
+
|
|
387
|
+
// Pass auth to downstream via framework context
|
|
388
|
+
const result = await args.next({
|
|
389
|
+
context: { auth: () => auth },
|
|
390
|
+
});
|
|
391
|
+
|
|
392
|
+
// CRITICAL: Apply Set-Cookie if session was refreshed
|
|
393
|
+
if (refreshedSessionData) {
|
|
394
|
+
const { headers } = await authService.saveSession(undefined, refreshedSessionData);
|
|
395
|
+
|
|
396
|
+
if (headers?.['Set-Cookie']) {
|
|
397
|
+
// Clone immutable Response and add Set-Cookie header
|
|
398
|
+
const newResponse = new Response(result.response.body, {
|
|
399
|
+
status: result.response.status,
|
|
400
|
+
statusText: result.response.statusText,
|
|
401
|
+
headers: result.response.headers,
|
|
402
|
+
});
|
|
403
|
+
newResponse.headers.set('Set-Cookie', headers['Set-Cookie']);
|
|
404
|
+
|
|
405
|
+
return { ...result, response: newResponse };
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
return result;
|
|
248
410
|
});
|
|
249
|
-
|
|
411
|
+
};
|
|
412
|
+
```
|
|
413
|
+
|
|
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
|
+
};
|
|
250
459
|
}
|
|
251
460
|
```
|
|
252
461
|
|
|
253
462
|
### Key Considerations
|
|
254
463
|
|
|
255
|
-
- **Request
|
|
256
|
-
- **
|
|
257
|
-
- **
|
|
258
|
-
- **
|
|
259
|
-
- **
|
|
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.
|
|
470
|
+
|
|
471
|
+
### Reference Implementation
|
|
472
|
+
|
|
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)
|
|
260
478
|
|
|
261
479
|
### Configuration Validation
|
|
262
480
|
|
|
@@ -400,26 +618,13 @@ class HonoStorage extends CookieSessionStorage<HonoRequest, HonoResponse> {
|
|
|
400
618
|
|
|
401
619
|
#### Creating Framework Adapters
|
|
402
620
|
|
|
403
|
-
When creating
|
|
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
|
|
621
|
+
When creating a storage adapter:
|
|
411
622
|
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
sessionEncryptionFactory: config => myCustomEncryption,
|
|
418
|
-
|
|
419
|
-
// Optional: Custom WorkOS client
|
|
420
|
-
clientFactory: config => myCustomWorkOSClient,
|
|
421
|
-
});
|
|
422
|
-
```
|
|
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
|
|
423
628
|
|
|
424
629
|
## Configuration
|
|
425
630
|
|
|
@@ -473,39 +678,69 @@ configure({
|
|
|
473
678
|
|
|
474
679
|
## API Reference
|
|
475
680
|
|
|
476
|
-
###
|
|
681
|
+
### Toolkit API (Recommended)
|
|
682
|
+
|
|
683
|
+
#### Core Configuration
|
|
477
684
|
|
|
478
685
|
- `configure(config)`: Set up AuthKit with your WorkOS configuration
|
|
479
|
-
- `validateConfig()`: Validate all required configuration values
|
|
686
|
+
- `validateConfig()`: Validate all required configuration values (throws descriptive error if invalid)
|
|
480
687
|
- `getConfig(key)`: Get a specific configuration value
|
|
481
|
-
- `getConfigurationProvider()`: Get the ConfigurationProvider instance
|
|
482
|
-
|
|
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
|
|
483
701
|
|
|
484
|
-
|
|
702
|
+
When using `createAuthService()`, you get these methods:
|
|
485
703
|
|
|
486
704
|
#### Authentication & Session Management
|
|
487
705
|
|
|
488
|
-
-
|
|
489
|
-
-
|
|
490
|
-
- `
|
|
491
|
-
- `
|
|
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
|
|
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()`)
|
|
495
710
|
|
|
496
|
-
|
|
711
|
+
- **`handleCallback(request, response, { code, state? })`** - Process OAuth callback
|
|
712
|
+
- Returns: `{ response, headers, returnPathname, authResponse }`
|
|
497
713
|
|
|
498
|
-
-
|
|
499
|
-
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
- `
|
|
503
|
-
|
|
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)
|
|
504
724
|
|
|
505
|
-
|
|
725
|
+
- **`signOut(sessionId, options?)`** - Generate logout URL + cookie clear header
|
|
726
|
+
- Returns: `{ logoutUrl: string; clearCookieHeader: string }`
|
|
506
727
|
|
|
507
|
-
-
|
|
508
|
-
- `
|
|
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`
|
|
509
744
|
|
|
510
745
|
## Advanced Features
|
|
511
746
|
|
|
@@ -567,49 +802,87 @@ const { user, claims } = await authKit.withAuth<CustomClaims>(request);
|
|
|
567
802
|
// claims is typed as BaseTokenClaims & CustomClaims
|
|
568
803
|
```
|
|
569
804
|
|
|
570
|
-
### AuthResult
|
|
805
|
+
### AuthResult Type (Discriminated Union)
|
|
571
806
|
|
|
572
|
-
The `withAuth` method returns
|
|
807
|
+
The `withAuth` method returns `{ auth: AuthResult; refreshedSessionData?: string }` where `AuthResult` is a **discriminated union** that TypeScript can narrow based on the `user` property:
|
|
573
808
|
|
|
574
809
|
```typescript
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
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
|
+
};
|
|
583
822
|
|
|
584
823
|
interface BaseTokenClaims {
|
|
585
|
-
sid: string;
|
|
586
|
-
org_id?: string;
|
|
587
|
-
role?: string;
|
|
588
|
-
|
|
589
|
-
|
|
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
|
|
590
830
|
feature_flags?: string[]; // Feature flags
|
|
591
831
|
}
|
|
592
832
|
```
|
|
593
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.
|
|
837
|
+
|
|
838
|
+
**Type narrowing in action:**
|
|
839
|
+
|
|
840
|
+
```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
|
+
}
|
|
848
|
+
|
|
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)
|
|
855
|
+
|
|
856
|
+
// This would be a TypeScript error in the !auth.user branch:
|
|
857
|
+
// console.log(auth.sessionId); // ❌ Property 'sessionId' does not exist
|
|
858
|
+
```
|
|
859
|
+
|
|
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
|
+
|
|
594
866
|
### Additional Exports
|
|
595
867
|
|
|
596
868
|
The library also exports these components for advanced use cases:
|
|
597
869
|
|
|
598
870
|
```typescript
|
|
599
871
|
import {
|
|
600
|
-
// Core
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
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
|
|
604
881
|
getConfigurationProvider, // Get ConfigurationProvider instance
|
|
605
|
-
ConfigurationProvider,
|
|
606
|
-
|
|
607
|
-
// Session management
|
|
608
|
-
SessionManager, // Core session management class
|
|
609
|
-
CookieSessionStorage, // Abstract cookie storage base class
|
|
882
|
+
ConfigurationProvider, // ConfigurationProvider class
|
|
610
883
|
|
|
611
884
|
// WorkOS client
|
|
612
|
-
getWorkOS,
|
|
885
|
+
getWorkOS, // WorkOS client factory
|
|
613
886
|
|
|
614
887
|
// Types
|
|
615
888
|
type SessionStorage,
|
|
@@ -618,6 +891,8 @@ import {
|
|
|
618
891
|
type Session,
|
|
619
892
|
type User,
|
|
620
893
|
type Impersonator,
|
|
894
|
+
type BaseTokenClaims,
|
|
895
|
+
type GetAuthorizationUrlOptions,
|
|
621
896
|
// ... and more
|
|
622
897
|
} from '@workos/authkit-session';
|
|
623
898
|
```
|