@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
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
import type { WorkOS } from '@workos-inc/node';
|
|
2
|
+
import { AuthKitCore } from '../core/AuthKitCore.js';
|
|
3
|
+
import type { ConfigurationProvider } from '../core/config/ConfigurationProvider.js';
|
|
4
|
+
import type { AuthKitConfig } from '../core/config/types.js';
|
|
5
|
+
import { AuthOperations } from '../operations/AuthOperations.js';
|
|
6
|
+
import type {
|
|
7
|
+
AuthResult,
|
|
8
|
+
CustomClaims,
|
|
9
|
+
GetAuthorizationUrlOptions,
|
|
10
|
+
HeadersBag,
|
|
11
|
+
Session,
|
|
12
|
+
SessionEncryption,
|
|
13
|
+
SessionStorage,
|
|
14
|
+
} from '../core/session/types.js';
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* AuthService is a REFERENCE IMPLEMENTATION for framework adapters.
|
|
18
|
+
*
|
|
19
|
+
* **IMPORTANT:** This class is optional. Framework adapters can use AuthKitCore,
|
|
20
|
+
* AuthOperations, and CookieSessionStorage directly to implement their own patterns.
|
|
21
|
+
*
|
|
22
|
+
* This class provides a pattern for coordinating between:
|
|
23
|
+
* - AuthKitCore (pure business logic: crypto, JWT, refresh)
|
|
24
|
+
* - AuthOperations (WorkOS API operations: signOut, refreshSession, URLs)
|
|
25
|
+
* - SessionStorage<TRequest, TResponse> (framework-specific storage)
|
|
26
|
+
*
|
|
27
|
+
* **Why this is optional:**
|
|
28
|
+
* - Frameworks have different middleware/route patterns (Next.js vs TanStack vs Remix)
|
|
29
|
+
* - Request context handling differs by framework (headers vs locals vs WeakMap)
|
|
30
|
+
* - Framework-specific features (callbacks, eagerAuth) don't fit generic patterns
|
|
31
|
+
*
|
|
32
|
+
* **Recommended usage:**
|
|
33
|
+
* - Use AuthKitCore directly for crypto, token validation, and refresh logic
|
|
34
|
+
* - Use AuthOperations for WorkOS API calls (refreshSession, signOut, URLs)
|
|
35
|
+
* - Use CookieSessionStorage.buildSetCookie() for cookie string generation
|
|
36
|
+
* - Implement your own updateSession/withAuth patterns that fit your framework
|
|
37
|
+
*
|
|
38
|
+
* **See also:**
|
|
39
|
+
* - authkit-nextjs: Uses Core + Operations directly, implements Next.js patterns
|
|
40
|
+
* - authkit-tanstack-start: Uses Core + Operations, implements TanStack patterns
|
|
41
|
+
*
|
|
42
|
+
* **Lazy initialization:**
|
|
43
|
+
* This class uses lazy initialization via private getters, which allows
|
|
44
|
+
* configuration to be set AFTER instantiation but BEFORE first use.
|
|
45
|
+
* This pattern may be useful for your framework adapter.
|
|
46
|
+
*/
|
|
47
|
+
export class AuthService<TRequest, TResponse> {
|
|
48
|
+
private _core?: AuthKitCore;
|
|
49
|
+
private _operations?: AuthOperations;
|
|
50
|
+
private readonly storage: SessionStorage<TRequest, TResponse>;
|
|
51
|
+
private readonly config: ConfigurationProvider;
|
|
52
|
+
private readonly clientFactory: (config: AuthKitConfig) => WorkOS;
|
|
53
|
+
private readonly encryptionFactory: (config: AuthKitConfig) => SessionEncryption;
|
|
54
|
+
|
|
55
|
+
constructor(
|
|
56
|
+
config: ConfigurationProvider,
|
|
57
|
+
storage: SessionStorage<TRequest, TResponse>,
|
|
58
|
+
clientFactory: (config: AuthKitConfig) => WorkOS,
|
|
59
|
+
encryptionFactory: (config: AuthKitConfig) => SessionEncryption,
|
|
60
|
+
) {
|
|
61
|
+
this.config = config;
|
|
62
|
+
this.storage = storage;
|
|
63
|
+
this.clientFactory = clientFactory;
|
|
64
|
+
this.encryptionFactory = encryptionFactory;
|
|
65
|
+
// NOTE: core and operations are NOT instantiated here
|
|
66
|
+
// They're created lazily on first access via getters below
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Lazy getter for AuthKitCore.
|
|
71
|
+
* Instantiates on first access, allowing config to be set beforehand.
|
|
72
|
+
*/
|
|
73
|
+
private get core(): AuthKitCore {
|
|
74
|
+
if (!this._core) {
|
|
75
|
+
this._core = new AuthKitCore(
|
|
76
|
+
this.config,
|
|
77
|
+
this.clientFactory(this.config.getConfig()),
|
|
78
|
+
this.encryptionFactory(this.config.getConfig()),
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
return this._core;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Lazy getter for AuthOperations.
|
|
86
|
+
* Instantiates on first access, allowing config to be set beforehand.
|
|
87
|
+
*/
|
|
88
|
+
private get operations(): AuthOperations {
|
|
89
|
+
if (!this._operations) {
|
|
90
|
+
this._operations = new AuthOperations(
|
|
91
|
+
this.core,
|
|
92
|
+
this.clientFactory(this.config.getConfig()),
|
|
93
|
+
this.config,
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
return this._operations;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Main authentication check method.
|
|
101
|
+
*
|
|
102
|
+
* This method:
|
|
103
|
+
* 1. Reads encrypted session from request (via storage)
|
|
104
|
+
* 2. Validates and potentially refreshes the session (via core)
|
|
105
|
+
* 3. Returns auth result + optionally refreshed session data
|
|
106
|
+
*
|
|
107
|
+
* @param request - Framework-specific request object
|
|
108
|
+
* @returns Auth result and optional refreshed session data
|
|
109
|
+
*/
|
|
110
|
+
async withAuth<TCustomClaims = CustomClaims>(
|
|
111
|
+
request: TRequest,
|
|
112
|
+
): Promise<{
|
|
113
|
+
auth: AuthResult<TCustomClaims>;
|
|
114
|
+
refreshedSessionData?: string;
|
|
115
|
+
}> {
|
|
116
|
+
try {
|
|
117
|
+
const encryptedSession = await this.storage.getSession(request);
|
|
118
|
+
if (!encryptedSession) {
|
|
119
|
+
return { auth: { user: null } };
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const { claims, session, refreshed } =
|
|
123
|
+
await this.core.validateAndRefresh<TCustomClaims>(
|
|
124
|
+
await this.core.decryptSession(encryptedSession),
|
|
125
|
+
);
|
|
126
|
+
|
|
127
|
+
const auth: AuthResult<TCustomClaims> = {
|
|
128
|
+
refreshToken: session.refreshToken,
|
|
129
|
+
user: session.user,
|
|
130
|
+
claims,
|
|
131
|
+
impersonator: session.impersonator,
|
|
132
|
+
accessToken: session.accessToken,
|
|
133
|
+
sessionId: claims.sid,
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
if (refreshed) {
|
|
137
|
+
const refreshedSessionData = await this.core.encryptSession(session);
|
|
138
|
+
return { auth, refreshedSessionData };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
return { auth };
|
|
142
|
+
} catch {
|
|
143
|
+
return { auth: { user: null } };
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Get a session from a request.
|
|
149
|
+
*
|
|
150
|
+
* @param request - Framework-specific request object
|
|
151
|
+
* @returns Decrypted session or null
|
|
152
|
+
*/
|
|
153
|
+
async getSession(request: TRequest): Promise<Session | null> {
|
|
154
|
+
const encryptedSession = await this.storage.getSession(request);
|
|
155
|
+
if (!encryptedSession) {
|
|
156
|
+
return null;
|
|
157
|
+
}
|
|
158
|
+
return this.core.decryptSession(encryptedSession);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Save a session to storage.
|
|
163
|
+
*
|
|
164
|
+
* @param response - Framework-specific response object (may be undefined)
|
|
165
|
+
* @param sessionData - Encrypted session string
|
|
166
|
+
* @returns Updated response and/or headers
|
|
167
|
+
*/
|
|
168
|
+
async saveSession(
|
|
169
|
+
response: TResponse | undefined,
|
|
170
|
+
sessionData: string,
|
|
171
|
+
): Promise<{ response?: TResponse; headers?: HeadersBag }> {
|
|
172
|
+
return this.storage.saveSession(response, sessionData);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Clear a session from storage.
|
|
177
|
+
*
|
|
178
|
+
* @param response - Framework-specific response object
|
|
179
|
+
* @returns Updated response and/or headers
|
|
180
|
+
*/
|
|
181
|
+
async clearSession(
|
|
182
|
+
response: TResponse,
|
|
183
|
+
): Promise<{ response?: TResponse; headers?: HeadersBag }> {
|
|
184
|
+
return this.storage.clearSession(response);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Sign out operation - delegates to AuthOperations.
|
|
189
|
+
*/
|
|
190
|
+
async signOut(sessionId: string, options?: { returnTo?: string }) {
|
|
191
|
+
return this.operations.signOut(sessionId, options);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Switch organization - delegates to AuthOperations.
|
|
196
|
+
*/
|
|
197
|
+
async switchOrganization(session: Session, organizationId: string) {
|
|
198
|
+
return this.operations.switchOrganization(session, organizationId);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Refresh session - delegates to AuthOperations.
|
|
203
|
+
*/
|
|
204
|
+
async refreshSession(session: Session, organizationId?: string) {
|
|
205
|
+
return this.operations.refreshSession(session, organizationId);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Get authorization URL - delegates to AuthOperations.
|
|
210
|
+
*/
|
|
211
|
+
async getAuthorizationUrl(options: GetAuthorizationUrlOptions = {}) {
|
|
212
|
+
return this.operations.getAuthorizationUrl(options);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* Convenience: Get sign-in URL.
|
|
217
|
+
*/
|
|
218
|
+
async getSignInUrl(
|
|
219
|
+
options: Omit<GetAuthorizationUrlOptions, 'screenHint'> = {},
|
|
220
|
+
) {
|
|
221
|
+
return this.operations.getSignInUrl(options);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Convenience: Get sign-up URL.
|
|
226
|
+
*/
|
|
227
|
+
async getSignUpUrl(
|
|
228
|
+
options: Omit<GetAuthorizationUrlOptions, 'screenHint'> = {},
|
|
229
|
+
) {
|
|
230
|
+
return this.operations.getSignUpUrl(options);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Get the WorkOS client instance.
|
|
235
|
+
* Useful for direct API calls not covered by AuthKit.
|
|
236
|
+
*/
|
|
237
|
+
getWorkOS(): WorkOS {
|
|
238
|
+
return this.clientFactory(this.config.getConfig());
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Handle OAuth callback.
|
|
243
|
+
* This creates a new session after successful authentication.
|
|
244
|
+
*
|
|
245
|
+
* @param request - Framework-specific request (not currently used)
|
|
246
|
+
* @param response - Framework-specific response
|
|
247
|
+
* @param options - OAuth callback options (code, state)
|
|
248
|
+
* @returns Updated response, return pathname, and auth response
|
|
249
|
+
*/
|
|
250
|
+
async handleCallback(
|
|
251
|
+
_request: TRequest,
|
|
252
|
+
response: TResponse,
|
|
253
|
+
options: { code: string; state?: string },
|
|
254
|
+
) {
|
|
255
|
+
const clientId = this.config.getValue('clientId');
|
|
256
|
+
const client = this.clientFactory(this.config.getConfig());
|
|
257
|
+
|
|
258
|
+
// Authenticate with WorkOS using the OAuth code
|
|
259
|
+
const authResponse = await client.userManagement.authenticateWithCode({
|
|
260
|
+
code: options.code,
|
|
261
|
+
clientId,
|
|
262
|
+
});
|
|
263
|
+
|
|
264
|
+
// Create and save the new session
|
|
265
|
+
const session: Session = {
|
|
266
|
+
accessToken: authResponse.accessToken,
|
|
267
|
+
refreshToken: authResponse.refreshToken,
|
|
268
|
+
user: authResponse.user,
|
|
269
|
+
impersonator: authResponse.impersonator,
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
const encryptedSession = await this.core.encryptSession(session);
|
|
273
|
+
const { response: updatedResponse, headers } = await this.saveSession(response, encryptedSession);
|
|
274
|
+
|
|
275
|
+
// Decode return pathname from state
|
|
276
|
+
let returnPathname = '/';
|
|
277
|
+
if (options.state) {
|
|
278
|
+
try {
|
|
279
|
+
const decoded = JSON.parse(atob(options.state));
|
|
280
|
+
returnPathname = decoded.returnPathname || '/';
|
|
281
|
+
} catch {
|
|
282
|
+
// Invalid state, use default
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
return {
|
|
287
|
+
response: updatedResponse,
|
|
288
|
+
headers,
|
|
289
|
+
returnPathname,
|
|
290
|
+
authResponse,
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { createAuthService } from './factory.js';
|
|
2
|
+
import { AuthService } from './AuthService.js';
|
|
3
|
+
|
|
4
|
+
const mockConfig = {
|
|
5
|
+
clientId: 'test-client-id',
|
|
6
|
+
apiKey: 'test-api-key',
|
|
7
|
+
redirectUri: 'http://localhost:3000/callback',
|
|
8
|
+
cookiePassword: 'test-password-that-is-32-chars-long!!',
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
const mockStorage = {
|
|
12
|
+
getSession: async () => null,
|
|
13
|
+
saveSession: async (response: any) => ({ response }),
|
|
14
|
+
clearSession: async (response: any) => ({ response }),
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
describe('createAuthService', () => {
|
|
18
|
+
beforeEach(() => {
|
|
19
|
+
process.env.WORKOS_CLIENT_ID = mockConfig.clientId;
|
|
20
|
+
process.env.WORKOS_API_KEY = mockConfig.apiKey;
|
|
21
|
+
process.env.WORKOS_REDIRECT_URI = mockConfig.redirectUri;
|
|
22
|
+
process.env.WORKOS_COOKIE_PASSWORD = mockConfig.cookiePassword;
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
afterEach(() => {
|
|
26
|
+
delete process.env.WORKOS_CLIENT_ID;
|
|
27
|
+
delete process.env.WORKOS_API_KEY;
|
|
28
|
+
delete process.env.WORKOS_REDIRECT_URI;
|
|
29
|
+
delete process.env.WORKOS_COOKIE_PASSWORD;
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
describe('factory creation', () => {
|
|
33
|
+
it('creates AuthService instance', () => {
|
|
34
|
+
const service = createAuthService({
|
|
35
|
+
sessionStorageFactory: () => mockStorage as any,
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
expect(service).toBeInstanceOf(AuthService);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it('accepts custom client factory', () => {
|
|
42
|
+
const customClient = {
|
|
43
|
+
userManagement: {
|
|
44
|
+
getJwksUrl: () => 'https://custom.example.com/jwks',
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
const service = createAuthService({
|
|
49
|
+
sessionStorageFactory: () => mockStorage as any,
|
|
50
|
+
clientFactory: () => customClient as any,
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
expect(service).toBeInstanceOf(AuthService);
|
|
54
|
+
expect(service.getWorkOS()).toBe(customClient);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it('accepts custom encryption factory', () => {
|
|
58
|
+
const customEncryption = {
|
|
59
|
+
sealData: async () => 'custom-encrypted',
|
|
60
|
+
unsealData: async () => ({}),
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
const service = createAuthService({
|
|
64
|
+
sessionStorageFactory: () => mockStorage as any,
|
|
65
|
+
encryptionFactory: () => customEncryption as any,
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
expect(service).toBeInstanceOf(AuthService);
|
|
69
|
+
});
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
describe('lazy storage initialization', () => {
|
|
73
|
+
it('defers storage creation until first use', async () => {
|
|
74
|
+
let storageCreated = false;
|
|
75
|
+
const storageFactory = () => {
|
|
76
|
+
storageCreated = true;
|
|
77
|
+
return mockStorage as any;
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
const service = createAuthService({
|
|
81
|
+
sessionStorageFactory: storageFactory,
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
expect(storageCreated).toBe(false);
|
|
85
|
+
|
|
86
|
+
await service.getSession('request');
|
|
87
|
+
|
|
88
|
+
expect(storageCreated).toBe(true);
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
it('creates storage only once', async () => {
|
|
92
|
+
let creationCount = 0;
|
|
93
|
+
const storageFactory = () => {
|
|
94
|
+
creationCount++;
|
|
95
|
+
return mockStorage as any;
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
const service = createAuthService({
|
|
99
|
+
sessionStorageFactory: storageFactory,
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
await service.getSession('request');
|
|
103
|
+
await service.getSession('request');
|
|
104
|
+
await service.getSession('request');
|
|
105
|
+
|
|
106
|
+
expect(creationCount).toBe(1);
|
|
107
|
+
});
|
|
108
|
+
});
|
|
109
|
+
});
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import type { WorkOS } from '@workos-inc/node';
|
|
2
|
+
import { once } from '../utils.js';
|
|
3
|
+
import { getConfigurationProvider, getFullConfig } from '../core/config.js';
|
|
4
|
+
import type { AuthKitConfig } from '../core/config/types.js';
|
|
5
|
+
import { getWorkOS } from '../core/client/workos.js';
|
|
6
|
+
import sessionEncryption from '../core/encryption/ironWebcryptoEncryption.js';
|
|
7
|
+
import type { SessionEncryption, SessionStorage } from '../core/session/types.js';
|
|
8
|
+
import { AuthService } from './AuthService.js';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Creates an AuthService instance with lazy initialization support.
|
|
12
|
+
*
|
|
13
|
+
* This factory function provides ergonomic AuthService creation with sensible defaults.
|
|
14
|
+
* The returned service uses lazy initialization, allowing configure() to be called
|
|
15
|
+
* after instantiation but before first use.
|
|
16
|
+
*
|
|
17
|
+
* @param options - Configuration options
|
|
18
|
+
* @param options.sessionStorageFactory - Factory function to create storage adapter
|
|
19
|
+
* @param options.clientFactory - Optional factory for WorkOS client (defaults to getWorkOS)
|
|
20
|
+
* @param options.encryptionFactory - Optional factory for encryption (defaults to iron-webcrypto)
|
|
21
|
+
* @returns AuthService instance with lazy initialization
|
|
22
|
+
*
|
|
23
|
+
* @example
|
|
24
|
+
* ```typescript
|
|
25
|
+
* // Create service (config not needed yet)
|
|
26
|
+
* export const authService = createAuthService({
|
|
27
|
+
* sessionStorageFactory: (config) => new MyFrameworkStorage(config),
|
|
28
|
+
* });
|
|
29
|
+
*
|
|
30
|
+
* // Configure later
|
|
31
|
+
* configure({ clientId: '...' });
|
|
32
|
+
*
|
|
33
|
+
* // Use (triggers lazy init)
|
|
34
|
+
* await authService.withAuth(request);
|
|
35
|
+
* ```
|
|
36
|
+
*/
|
|
37
|
+
export function createAuthService<TRequest, TResponse>(options: {
|
|
38
|
+
sessionStorageFactory: (
|
|
39
|
+
config: AuthKitConfig,
|
|
40
|
+
) => SessionStorage<TRequest, TResponse>;
|
|
41
|
+
clientFactory?: (config: AuthKitConfig) => WorkOS;
|
|
42
|
+
encryptionFactory?: (config: AuthKitConfig) => SessionEncryption;
|
|
43
|
+
}): AuthService<TRequest, TResponse> {
|
|
44
|
+
const {
|
|
45
|
+
sessionStorageFactory,
|
|
46
|
+
clientFactory = () => getWorkOS(),
|
|
47
|
+
encryptionFactory = () => sessionEncryption,
|
|
48
|
+
} = options;
|
|
49
|
+
|
|
50
|
+
// Storage needs to be created with lazy config evaluation
|
|
51
|
+
// We create a wrapper storage that delegates to the real storage lazily
|
|
52
|
+
const getStorage = once(() => sessionStorageFactory(getFullConfig()));
|
|
53
|
+
|
|
54
|
+
// Create a proxy storage that lazily instantiates the real storage
|
|
55
|
+
const lazyStorage: SessionStorage<TRequest, TResponse> = {
|
|
56
|
+
getSession: async (request: TRequest) => getStorage().getSession(request),
|
|
57
|
+
saveSession: async (response: TResponse | undefined, sessionData: string) =>
|
|
58
|
+
getStorage().saveSession(response, sessionData),
|
|
59
|
+
clearSession: async (response: TResponse) =>
|
|
60
|
+
getStorage().clearSession(response),
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
return new AuthService<TRequest, TResponse>(
|
|
64
|
+
getConfigurationProvider(),
|
|
65
|
+
lazyStorage,
|
|
66
|
+
clientFactory,
|
|
67
|
+
encryptionFactory,
|
|
68
|
+
);
|
|
69
|
+
}
|
|
@@ -1,64 +0,0 @@
|
|
|
1
|
-
import type { WorkOS } from '@workos-inc/node';
|
|
2
|
-
import type { AuthKitConfig } from './config/types.js';
|
|
3
|
-
import type { AuthUrlOptions, BaseTokenClaims, CustomClaims, SessionEncryption, SessionStorage } from './session/types.js';
|
|
4
|
-
export declare const createAuthKitFactory: <TRequest, TResponse>(options: {
|
|
5
|
-
sessionStorageFactory: (config: AuthKitConfig) => SessionStorage<TRequest, TResponse>;
|
|
6
|
-
sessionEncryptionFactory?: (confg: AuthKitConfig) => SessionEncryption;
|
|
7
|
-
clientFactory?: (config: AuthKitConfig) => WorkOS;
|
|
8
|
-
}) => {
|
|
9
|
-
withAuth: (request: any) => Promise<import("./session/types.js").AuthResult<CustomClaims>>;
|
|
10
|
-
getAuthorizationUrl: (args_0?: import("./session/types.js").GetAuthorizationUrlOptions | undefined) => Promise<string>;
|
|
11
|
-
refreshSession: (session: import("./session/types.js").Session, organizationId?: string | undefined) => Promise<{
|
|
12
|
-
user: import("@workos-inc/node").User;
|
|
13
|
-
sessionId: string;
|
|
14
|
-
organizationId: string | undefined;
|
|
15
|
-
role: string | undefined;
|
|
16
|
-
roles: string[] | undefined;
|
|
17
|
-
permissions: string[] | undefined;
|
|
18
|
-
entitlements: string[] | undefined;
|
|
19
|
-
impersonator: import("@workos-inc/node").Impersonator | undefined;
|
|
20
|
-
accessToken: string;
|
|
21
|
-
claims: BaseTokenClaims & CustomClaims;
|
|
22
|
-
sessionData: string;
|
|
23
|
-
session: import("./session/types.js").Session;
|
|
24
|
-
}>;
|
|
25
|
-
saveSession: (response: TResponse | undefined, sessionData: string, options?: unknown) => Promise<{
|
|
26
|
-
response?: TResponse | undefined;
|
|
27
|
-
headers?: import("./session/types.js").HeadersBag;
|
|
28
|
-
}>;
|
|
29
|
-
getSignInUrl: (options?: AuthUrlOptions) => Promise<string>;
|
|
30
|
-
getSignUpUrl: (options?: AuthUrlOptions) => Promise<string>;
|
|
31
|
-
getWorkOS: () => WorkOS;
|
|
32
|
-
getSession: (request: TRequest) => Promise<import("./session/types.js").Session | null>;
|
|
33
|
-
terminateSession: (session: import("./session/types.js").Session, response: any, options?: {
|
|
34
|
-
returnTo?: string;
|
|
35
|
-
} | undefined) => Promise<{
|
|
36
|
-
response?: TResponse | undefined;
|
|
37
|
-
headers?: import("./session/types.js").HeadersBag;
|
|
38
|
-
logoutUrl: string;
|
|
39
|
-
}>;
|
|
40
|
-
signOut: (request: TRequest, response: TResponse, options?: {
|
|
41
|
-
returnTo?: string;
|
|
42
|
-
}) => Promise<TResponse | {
|
|
43
|
-
response?: TResponse | undefined;
|
|
44
|
-
headers?: import("./session/types.js").HeadersBag;
|
|
45
|
-
} | undefined>;
|
|
46
|
-
switchToOrganization: (request: any, response: any, organizationId: string) => Promise<{
|
|
47
|
-
response?: TResponse | undefined;
|
|
48
|
-
headers?: import("./session/types.js").HeadersBag;
|
|
49
|
-
authResult: import("./session/types.js").AuthResult<CustomClaims>;
|
|
50
|
-
}>;
|
|
51
|
-
handleCallback: (_request: TRequest, response: TResponse, options: {
|
|
52
|
-
code: string;
|
|
53
|
-
state?: string;
|
|
54
|
-
}) => Promise<{
|
|
55
|
-
response: {
|
|
56
|
-
response?: TResponse | undefined;
|
|
57
|
-
headers?: import("./session/types.js").HeadersBag;
|
|
58
|
-
};
|
|
59
|
-
returnPathname: string;
|
|
60
|
-
authResponse: import("@workos-inc/node").AuthenticationResponse;
|
|
61
|
-
}>;
|
|
62
|
-
getTokenClaims: <TCustomClaims = CustomClaims>(request: TRequest, accessToken?: string) => Promise<Partial<BaseTokenClaims & TCustomClaims>>;
|
|
63
|
-
};
|
|
64
|
-
//# sourceMappingURL=createAuthKitFactory.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"createAuthKitFactory.d.ts","sourceRoot":"","sources":["../../src/core/createAuthKitFactory.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAQ/C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAIvD,OAAO,KAAK,EACV,cAAc,EACd,eAAe,EACf,YAAY,EACZ,iBAAiB,EACjB,cAAc,EACf,MAAM,oBAAoB,CAAC;AAE5B,eAAO,MAAM,oBAAoB,GAC/B,QAAQ,EACR,SAAS;2BAEc,CACrB,MAAM,EAAE,aAAa,KAClB,cAAc,CAAC,QAAQ,EAAE,SAAS,CAAC;+BACb,CAAC,KAAK,EAAE,aAAa,KAAK,iBAAiB;oBACtD,CAAC,MAAM,EAAE,aAAa,KAAK,MAAM;;;;;;;;;;;;;;;;;;;;;;6BA2CtB,cAAc;6BAMd,cAAc;;0BAUjB,QAAQ;;;;;;;;uBAQnB,QAAQ,YACP,SAAS,YACT;QAAE,QAAQ,CAAC,EAAE,MAAM,CAAA;KAAE;;;;;;;;;+BAuCrB,QAAQ,YACR,SAAS,WACV;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE;;;;;;;;qBAoCpB,aAAa,0BACzB,QAAQ,gBACH,MAAM,KACnB,OAAO,CAAC,OAAO,CAAC,eAAe,GAAG,aAAa,CAAC,CAAC;CAiBtD,CAAC"}
|
|
@@ -1,95 +0,0 @@
|
|
|
1
|
-
import { once } from '../utils.js';
|
|
2
|
-
import { getWorkOS } from './client/workos.js';
|
|
3
|
-
import { getConfig, getConfigurationProvider, getFullConfig, } from './config.js';
|
|
4
|
-
import sessionEncryption from './encryption/ironWebcryptoEncryption.js';
|
|
5
|
-
import { SessionManager } from './session/SessionManager.js';
|
|
6
|
-
import TokenManager from './session/TokenManager.js';
|
|
7
|
-
export const createAuthKitFactory = once(function createAuthKit(options) {
|
|
8
|
-
const { sessionStorageFactory, clientFactory = () => getWorkOS(), sessionEncryptionFactory = () => sessionEncryption, } = options;
|
|
9
|
-
const getTokenManager = once(() => new TokenManager(getConfig('clientId'), clientFactory(getFullConfig())));
|
|
10
|
-
const getSessionManager = once(() => new SessionManager(getConfigurationProvider(), sessionStorageFactory(getFullConfig()), getTokenManager(), clientFactory(getFullConfig()), sessionEncryptionFactory(getFullConfig())));
|
|
11
|
-
return {
|
|
12
|
-
withAuth: (...args) => getSessionManager().withAuth(...args),
|
|
13
|
-
getAuthorizationUrl: (...args) => getSessionManager().getAuthorizationUrl(...args),
|
|
14
|
-
refreshSession: (...args) => getSessionManager().refreshSession(...args),
|
|
15
|
-
saveSession: (...args) => sessionStorageFactory(getFullConfig()).saveSession(...args),
|
|
16
|
-
getSignInUrl: (options) => getSessionManager().getAuthorizationUrl({
|
|
17
|
-
...options,
|
|
18
|
-
screenHint: 'sign-in',
|
|
19
|
-
}),
|
|
20
|
-
getSignUpUrl: (options) => getSessionManager().getAuthorizationUrl({
|
|
21
|
-
...options,
|
|
22
|
-
screenHint: 'sign-up',
|
|
23
|
-
}),
|
|
24
|
-
// Expose getWorkOS for direct client access
|
|
25
|
-
getWorkOS: () => clientFactory(getFullConfig()),
|
|
26
|
-
// Expose SessionManager's getSession directly
|
|
27
|
-
getSession: (request) => getSessionManager().getSession(request),
|
|
28
|
-
// terminateSession uses the standard SessionManager signature
|
|
29
|
-
terminateSession: (...args) => getSessionManager().terminateSession(...args),
|
|
30
|
-
signOut: async (request, response, options) => {
|
|
31
|
-
// Get the current session
|
|
32
|
-
const authResult = await getSessionManager().withAuth(request);
|
|
33
|
-
if (!authResult.user ||
|
|
34
|
-
!authResult.accessToken ||
|
|
35
|
-
!authResult.refreshToken) {
|
|
36
|
-
// No session to terminate, just clear cookies
|
|
37
|
-
return sessionStorageFactory(getFullConfig()).clearSession(response);
|
|
38
|
-
}
|
|
39
|
-
// Create session object for termination
|
|
40
|
-
const session = {
|
|
41
|
-
accessToken: authResult.accessToken,
|
|
42
|
-
refreshToken: authResult.refreshToken,
|
|
43
|
-
user: authResult.user,
|
|
44
|
-
impersonator: authResult.impersonator,
|
|
45
|
-
};
|
|
46
|
-
// Terminate the session (this clears cookies and returns logout URL)
|
|
47
|
-
const result = await getSessionManager().terminateSession(session, response, options);
|
|
48
|
-
return result.response;
|
|
49
|
-
},
|
|
50
|
-
switchToOrganization: (...args) => getSessionManager().switchToOrganization(...args),
|
|
51
|
-
handleCallback: async (_request, response, options) => {
|
|
52
|
-
const config = getFullConfig();
|
|
53
|
-
const clientId = config.clientId;
|
|
54
|
-
const client = clientFactory(config);
|
|
55
|
-
// Authenticate with the OAuth code
|
|
56
|
-
const authResponse = await client.userManagement.authenticateWithCode({
|
|
57
|
-
code: options.code,
|
|
58
|
-
clientId,
|
|
59
|
-
});
|
|
60
|
-
// Create session using SessionManager
|
|
61
|
-
const updatedResponse = await getSessionManager().createSession(authResponse, response);
|
|
62
|
-
// Decode state if provided
|
|
63
|
-
let returnPathname = '/';
|
|
64
|
-
if (options.state) {
|
|
65
|
-
try {
|
|
66
|
-
const decoded = JSON.parse(atob(options.state));
|
|
67
|
-
returnPathname = decoded.returnPathname || '/';
|
|
68
|
-
}
|
|
69
|
-
catch {
|
|
70
|
-
// Invalid state, use default
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
return {
|
|
74
|
-
response: updatedResponse,
|
|
75
|
-
returnPathname,
|
|
76
|
-
authResponse,
|
|
77
|
-
};
|
|
78
|
-
},
|
|
79
|
-
getTokenClaims: async (request, accessToken) => {
|
|
80
|
-
const tokenToUse = accessToken ||
|
|
81
|
-
(await getSessionManager().withAuth(request))
|
|
82
|
-
.accessToken;
|
|
83
|
-
if (!tokenToUse) {
|
|
84
|
-
return {};
|
|
85
|
-
}
|
|
86
|
-
try {
|
|
87
|
-
return getTokenManager().parseTokenClaims(tokenToUse);
|
|
88
|
-
}
|
|
89
|
-
catch {
|
|
90
|
-
return {};
|
|
91
|
-
}
|
|
92
|
-
},
|
|
93
|
-
};
|
|
94
|
-
});
|
|
95
|
-
//# sourceMappingURL=createAuthKitFactory.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"createAuthKitFactory.js","sourceRoot":"","sources":["../../src/core/createAuthKitFactory.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAC;AACnC,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,EACL,SAAS,EACT,wBAAwB,EACxB,aAAa,GACd,MAAM,aAAa,CAAC;AAErB,OAAO,iBAAiB,MAAM,yCAAyC,CAAC;AACxE,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAC7D,OAAO,YAAY,MAAM,2BAA2B,CAAC;AASrD,MAAM,CAAC,MAAM,oBAAoB,GAAG,IAAI,CAAC,SAAS,aAAa,CAG7D,OAMD;IACC,MAAM,EACJ,qBAAqB,EACrB,aAAa,GAAG,GAAG,EAAE,CAAC,SAAS,EAAE,EACjC,wBAAwB,GAAG,GAAG,EAAE,CAAC,iBAAiB,GACnD,GAAG,OAAO,CAAC;IAEZ,MAAM,eAAe,GAAG,IAAI,CAC1B,GAAG,EAAE,CACH,IAAI,YAAY,CAAC,SAAS,CAAC,UAAU,CAAC,EAAE,aAAa,CAAC,aAAa,EAAE,CAAC,CAAC,CAC1E,CAAC;IAEF,MAAM,iBAAiB,GAAG,IAAI,CAC5B,GAAG,EAAE,CACH,IAAI,cAAc,CAChB,wBAAwB,EAAE,EAC1B,qBAAqB,CAAC,aAAa,EAAE,CAAC,EACtC,eAAe,EAAE,EACjB,aAAa,CAAC,aAAa,EAAE,CAAC,EAC9B,wBAAwB,CAAC,aAAa,EAAE,CAAC,CAC1C,CACJ,CAA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