@workos/authkit-session 0.0.1-alpha.2 → 0.0.1-alpha.3
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
|
@@ -5,6 +5,8 @@
|
|
|
5
5
|
|
|
6
6
|
A framework-agnostic authentication library for WorkOS with a modular adapter system for server-side rendered applications.
|
|
7
7
|
|
|
8
|
+
This library serves as the foundation for framework-specific WorkOS authentication packages like `@workos-inc/authkit-nextjs`, `@workos-inc/authkit-remix`, and `@workos-inc/authkit-sveltekit`. By implementing the `SessionStorage` interface for your framework, you can provide WorkOS authentication capabilities with minimal framework-specific code.
|
|
9
|
+
|
|
8
10
|
## Features
|
|
9
11
|
|
|
10
12
|
- **Framework-agnostic core**: Common authentication logic that works across platforms
|
|
@@ -134,6 +136,9 @@ const authKit = createAuthKitFactory<MyRequest, MyResponse>({
|
|
|
134
136
|
const { user, claims, sessionId, impersonator, accessToken, refreshToken } =
|
|
135
137
|
await authKit.withAuth(request);
|
|
136
138
|
|
|
139
|
+
// Note: ensureSignedIn option not yet implemented
|
|
140
|
+
// Framework adapters should handle redirects when user is null
|
|
141
|
+
|
|
137
142
|
// Generate an authorization URL
|
|
138
143
|
const authUrl = await authKit.getAuthorizationUrl({
|
|
139
144
|
returnPathname: '/dashboard',
|
|
@@ -149,7 +154,7 @@ const signUpUrl = await authKit.getSignUpUrl({
|
|
|
149
154
|
redirectUri: 'https://yourdomain.com/auth/callback',
|
|
150
155
|
});
|
|
151
156
|
|
|
152
|
-
// Get token claims
|
|
157
|
+
// Get token claims from current session
|
|
153
158
|
const claims = await authKit.getTokenClaims(request);
|
|
154
159
|
// Or parse specific access token
|
|
155
160
|
const specificClaims = await authKit.getTokenClaims(request, accessToken);
|
|
@@ -158,14 +163,95 @@ const specificClaims = await authKit.getTokenClaims(request, accessToken);
|
|
|
158
163
|
const { response: updatedResponse, authResult: newAuth } =
|
|
159
164
|
await authKit.switchToOrganization(request, response, 'org_123');
|
|
160
165
|
|
|
161
|
-
//
|
|
162
|
-
const {
|
|
166
|
+
// Handle OAuth callback
|
|
167
|
+
const {
|
|
168
|
+
response: updatedResponse,
|
|
169
|
+
returnPathname,
|
|
170
|
+
authResponse,
|
|
171
|
+
} = await authKit.handleCallback(request, response, {
|
|
172
|
+
code: 'oauth_code_from_query',
|
|
173
|
+
state: 'optional_state_from_query',
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
// Sign out (simple session termination)
|
|
177
|
+
const clearedResponse = await authKit.signOut(request, response, {
|
|
178
|
+
returnTo: 'https://yourdomain.com',
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
// Terminate session and get logout URL (advanced)
|
|
182
|
+
const { response: clearedResponse, logoutUrl } = await authKit.terminateSession(
|
|
163
183
|
session,
|
|
164
184
|
response,
|
|
165
185
|
{ returnTo: 'https://yourdomain.com' },
|
|
166
186
|
);
|
|
187
|
+
|
|
188
|
+
// Manually save a session (for custom auth flows)
|
|
189
|
+
await authKit.saveSession(response, authResponse);
|
|
190
|
+
|
|
191
|
+
// Manually refresh session
|
|
192
|
+
const refreshedAuth = await authKit.refreshSession(session, organizationId);
|
|
167
193
|
```
|
|
168
194
|
|
|
195
|
+
## For Framework Implementers
|
|
196
|
+
|
|
197
|
+
If you're building a framework-specific package (like `@workos-inc/authkit-sveltekit`), this library provides everything needed for WorkOS authentication:
|
|
198
|
+
|
|
199
|
+
### Implementation Steps
|
|
200
|
+
|
|
201
|
+
1. **Install and configure** `@workos/authkit-session` as a dependency
|
|
202
|
+
2. **Create a SessionStorage adapter** for your framework's request/response objects
|
|
203
|
+
3. **Export framework-specific helpers** that wrap the core AuthKit functionality
|
|
204
|
+
4. **Handle routing** for sign-in, callback, and sign-out endpoints
|
|
205
|
+
|
|
206
|
+
### Example Framework Package Structure
|
|
207
|
+
|
|
208
|
+
```typescript
|
|
209
|
+
// src/storage.ts - Framework-specific storage adapter
|
|
210
|
+
import { CookieSessionStorage } from '@workos/authkit-session';
|
|
211
|
+
import type { ConfigurationProvider } from '@workos/authkit-session';
|
|
212
|
+
|
|
213
|
+
export class SvelteKitStorage extends CookieSessionStorage<RequestEvent, void> {
|
|
214
|
+
// Implement framework-specific cookie handling
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// src/index.ts - Main exports
|
|
218
|
+
import { configure, createAuthKitFactory } from '@workos/authkit-session';
|
|
219
|
+
import { SvelteKitStorage } from './storage';
|
|
220
|
+
|
|
221
|
+
export { configure };
|
|
222
|
+
|
|
223
|
+
export const authKit = createAuthKitFactory({
|
|
224
|
+
sessionStorageFactory: config => new SvelteKitStorage(config),
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
// Framework-specific helpers
|
|
228
|
+
export async function withAuth(event: RequestEvent) {
|
|
229
|
+
return authKit.withAuth(event);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
export async function handleCallback(event: RequestEvent) {
|
|
233
|
+
const url = new URL(event.request.url);
|
|
234
|
+
const code = url.searchParams.get('code');
|
|
235
|
+
const state = url.searchParams.get('state');
|
|
236
|
+
|
|
237
|
+
if (!code) throw new Error('Missing authorization code');
|
|
238
|
+
|
|
239
|
+
const result = await authKit.handleCallback(event, undefined, {
|
|
240
|
+
code,
|
|
241
|
+
state,
|
|
242
|
+
});
|
|
243
|
+
// Handle redirect to returnPathname
|
|
244
|
+
}
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
### Key Considerations
|
|
248
|
+
|
|
249
|
+
- **Request/Response Objects**: Adapt your framework's request/response objects to the `SessionStorage` interface
|
|
250
|
+
- **Cookie Handling**: Implement secure cookie setting/getting for your framework
|
|
251
|
+
- **Routing Integration**: Provide helpers for authentication routes (`/auth/signin`, `/auth/callback`, `/auth/signout`)
|
|
252
|
+
- **TypeScript Support**: Export proper types for your framework's patterns
|
|
253
|
+
- **Error Handling**: Wrap AuthKit errors in framework-appropriate error types
|
|
254
|
+
|
|
169
255
|
## Core Concepts
|
|
170
256
|
|
|
171
257
|
### Session Management
|
|
@@ -344,14 +430,26 @@ configure({
|
|
|
344
430
|
|
|
345
431
|
### AuthKit Instance API
|
|
346
432
|
|
|
347
|
-
|
|
433
|
+
#### Authentication & Session Management
|
|
434
|
+
|
|
435
|
+
- `withAuth<TCustomClaims>(request, options?)`: Validate the current session and return `AuthResult<TCustomClaims>`
|
|
436
|
+
- Note: `ensureSignedIn` option not yet implemented - framework adapters should handle redirects
|
|
437
|
+
- `handleCallback(request, response, { code, state? })`: Process OAuth callback and create session
|
|
438
|
+
- `signOut(request, response, options?)`: Simple session termination with cookie clearing
|
|
439
|
+
- `terminateSession(session, response, options?)`: Advanced session termination with logout URL
|
|
440
|
+
- `saveSession(response, authResponse)`: Manually save session from `AuthenticationResponse`
|
|
441
|
+
- `refreshSession(session, organizationId?)`: Manually refresh session tokens
|
|
442
|
+
|
|
443
|
+
#### URL Generation
|
|
444
|
+
|
|
348
445
|
- `getAuthorizationUrl(options)`: Generate a WorkOS authorization URL with `returnPathname`, `redirectUri`, and `screenHint`
|
|
349
446
|
- `getSignInUrl(options)`: Generate a sign-in URL with `organizationId`, `loginHint`, and `redirectUri`
|
|
350
447
|
- `getSignUpUrl(options)`: Generate a sign-up URL with `organizationId`, `loginHint`, and `redirectUri`
|
|
448
|
+
|
|
449
|
+
#### Token & Organization Management
|
|
450
|
+
|
|
351
451
|
- `getTokenClaims<TCustomClaims>(request, accessToken?)`: Parse JWT token claims from session or specific token
|
|
352
452
|
- `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
453
|
|
|
356
454
|
## Advanced Features
|
|
357
455
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@workos/authkit-session",
|
|
3
|
-
"version": "0.0.1-alpha.
|
|
3
|
+
"version": "0.0.1-alpha.3",
|
|
4
4
|
"description": "",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
},
|
|
14
14
|
"scripts": {
|
|
15
15
|
"build": "tsup",
|
|
16
|
+
"prettier": "prettier --check .",
|
|
16
17
|
"format": "prettier --write .",
|
|
17
18
|
"test": "echo \"Error: no test specified\" && exit 1"
|
|
18
19
|
},
|
|
@@ -32,7 +33,7 @@
|
|
|
32
33
|
"jose": "^6.0.12"
|
|
33
34
|
},
|
|
34
35
|
"engines": {
|
|
35
|
-
"node": ">=
|
|
36
|
+
"node": ">=20.0.0"
|
|
36
37
|
},
|
|
37
38
|
"files": [
|
|
38
39
|
"dist",
|
|
@@ -80,10 +80,10 @@ export class ConfigurationProvider {
|
|
|
80
80
|
getValue<K extends keyof AuthKitConfig>(key: K): AuthKitConfig[K] {
|
|
81
81
|
const envKey = this.getEnvironmentVariableName(key);
|
|
82
82
|
const envValue = this.getEnvironmentValue(envKey);
|
|
83
|
-
|
|
83
|
+
|
|
84
84
|
// Use environment value if available, otherwise fall back to config
|
|
85
85
|
const rawValue = envValue ?? this.config[key];
|
|
86
|
-
|
|
86
|
+
|
|
87
87
|
if (rawValue != null) {
|
|
88
88
|
return this.convertValueType(key, rawValue) as AuthKitConfig[K];
|
|
89
89
|
}
|
|
@@ -99,15 +99,15 @@ export class ConfigurationProvider {
|
|
|
99
99
|
|
|
100
100
|
private getEnvironmentValue(envKey: string): string | undefined {
|
|
101
101
|
const { valueSource } = this;
|
|
102
|
-
|
|
102
|
+
|
|
103
103
|
if (typeof valueSource === 'function') {
|
|
104
104
|
return valueSource(envKey);
|
|
105
105
|
}
|
|
106
|
-
|
|
106
|
+
|
|
107
107
|
if (valueSource && envKey in valueSource) {
|
|
108
108
|
return valueSource[envKey];
|
|
109
109
|
}
|
|
110
|
-
|
|
110
|
+
|
|
111
111
|
return undefined;
|
|
112
112
|
}
|
|
113
113
|
|
|
@@ -171,8 +171,11 @@ export const createAuthKitFactory = once(function createAuthKit<
|
|
|
171
171
|
request: TRequest,
|
|
172
172
|
accessToken?: string,
|
|
173
173
|
): Promise<Partial<BaseTokenClaims & TCustomClaims>> => {
|
|
174
|
-
const tokenToUse =
|
|
175
|
-
|
|
174
|
+
const tokenToUse =
|
|
175
|
+
accessToken ||
|
|
176
|
+
(await getSessionManager().withAuth<TCustomClaims>(request))
|
|
177
|
+
.accessToken;
|
|
178
|
+
|
|
176
179
|
if (!tokenToUse) {
|
|
177
180
|
return {};
|
|
178
181
|
}
|
|
@@ -288,14 +288,18 @@ export class SessionManager<TRequest, TResponse> {
|
|
|
288
288
|
}
|
|
289
289
|
}
|
|
290
290
|
|
|
291
|
-
private async handleSwitchOrganizationError(
|
|
291
|
+
private async handleSwitchOrganizationError(
|
|
292
|
+
error: any,
|
|
293
|
+
organizationId: string,
|
|
294
|
+
): Promise<AuthKitError> {
|
|
292
295
|
const errorCodeToMessage = {
|
|
293
296
|
sso_required: `SSO required for organization ${organizationId}`,
|
|
294
297
|
mfa_enrollment: `MFA enrollment required for organization ${organizationId}`,
|
|
295
298
|
};
|
|
296
299
|
|
|
297
|
-
const errorMessage =
|
|
298
|
-
|
|
300
|
+
const errorMessage =
|
|
301
|
+
errorCodeToMessage[error?.code as keyof typeof errorCodeToMessage];
|
|
302
|
+
|
|
299
303
|
if (errorMessage) {
|
|
300
304
|
const authUrl = await this.getAuthorizationUrl({
|
|
301
305
|
redirectUri: this.config.getValue('redirectUri'),
|