@workos/authkit-session 0.0.1-alpha.1

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.
@@ -0,0 +1,103 @@
1
+ import { seal as sealData, unseal as unsealData } from 'iron-webcrypto';
2
+ import type { SessionEncryption as SessionEncryptionInterface } from './session/types';
3
+
4
+ /**
5
+ * A compatible implementation that works with iron-session
6
+ */
7
+ export class SessionEncryption implements SessionEncryptionInterface {
8
+ private readonly versionDelimiter = '~';
9
+ private readonly currentMajorVersion = 2;
10
+
11
+ // Parse an iron-session seal to extract the version
12
+ private parseSeal(seal: string): {
13
+ sealWithoutVersion: string;
14
+ tokenVersion: number | null;
15
+ } {
16
+ const [sealWithoutVersion = '', tokenVersionAsString] = seal.split(
17
+ this.versionDelimiter,
18
+ );
19
+ const tokenVersion =
20
+ tokenVersionAsString == null ? null : parseInt(tokenVersionAsString, 10);
21
+ return { sealWithoutVersion, tokenVersion };
22
+ }
23
+
24
+ // Encrypt data in a way that's compatible with iron-session
25
+ async sealData(
26
+ data: unknown,
27
+ { password, ttl = 0 }: { password: string; ttl?: number | undefined },
28
+ ) {
29
+ // Format password as iron-session expects
30
+ const passwordObj = {
31
+ id: '1',
32
+ secret: password,
33
+ };
34
+
35
+ // Seal the data using iron-webcrypto with properly formatted password
36
+ const seal = await sealData(globalThis.crypto, data, passwordObj, {
37
+ encryption: {
38
+ saltBits: 256,
39
+ algorithm: 'aes-256-cbc',
40
+ iterations: 1,
41
+ minPasswordlength: 32,
42
+ },
43
+ integrity: {
44
+ saltBits: 256,
45
+ algorithm: 'sha256',
46
+ iterations: 1,
47
+ minPasswordlength: 32,
48
+ },
49
+ ttl: ttl * 1000, // Convert seconds to milliseconds
50
+ timestampSkewSec: 60,
51
+ localtimeOffsetMsec: 0,
52
+ });
53
+
54
+ // Add the version delimiter exactly like iron-session does
55
+ return `${seal}${this.versionDelimiter}${this.currentMajorVersion}`;
56
+ }
57
+
58
+ // Decrypt data from iron-session with HMAC verification
59
+ async unsealData<T = unknown>(
60
+ encryptedData: string,
61
+ { password }: { password: string },
62
+ ): Promise<T> {
63
+ // First, parse the seal to extract the version
64
+ const { sealWithoutVersion, tokenVersion } = this.parseSeal(encryptedData);
65
+
66
+ // Format password as a map like iron-session expects
67
+ const passwordMap = { 1: password };
68
+
69
+ // Use iron-webcrypto's unseal function
70
+ const data = await unsealData(
71
+ globalThis.crypto,
72
+ sealWithoutVersion,
73
+ passwordMap,
74
+ {
75
+ encryption: {
76
+ saltBits: 256,
77
+ algorithm: 'aes-256-cbc',
78
+ iterations: 1,
79
+ minPasswordlength: 32,
80
+ },
81
+ integrity: {
82
+ saltBits: 256,
83
+ algorithm: 'sha256',
84
+ iterations: 1,
85
+ minPasswordlength: 32,
86
+ },
87
+ ttl: 0,
88
+ timestampSkewSec: 60,
89
+ localtimeOffsetMsec: 0,
90
+ },
91
+ );
92
+
93
+ // Check the token version if needed
94
+ if (tokenVersion === 2) {
95
+ return data as T;
96
+ } else if (tokenVersion !== null) {
97
+ // For older token versions, extract the persistent property
98
+ return { ...(data as any).persistent } as T;
99
+ }
100
+
101
+ return data as T;
102
+ }
103
+ }
@@ -0,0 +1,42 @@
1
+ import type { ConfigurationProvider } from '../config/ConfigurationProvider';
2
+ import type { SessionStorage } from './types';
3
+
4
+ export interface CookieOptions {
5
+ path?: string;
6
+ domain?: string;
7
+ maxAge?: number;
8
+ expires?: Date;
9
+ httpOnly?: boolean;
10
+ secure?: boolean;
11
+ sameSite?: 'lax' | 'strict' | 'none';
12
+ priority?: 'low' | 'medium' | 'high';
13
+ partitioned?: boolean;
14
+ }
15
+
16
+ export abstract class CookieSessionStorage<TRequest, TResponse>
17
+ implements SessionStorage<TRequest, TResponse>
18
+ {
19
+ protected cookieName: string;
20
+ protected readonly cookieOptions: CookieOptions;
21
+
22
+ constructor(config: ConfigurationProvider) {
23
+ this.cookieName = config.getValue('cookieName') || 'workos_session';
24
+ this.cookieOptions = {
25
+ path: '/',
26
+ httpOnly: true,
27
+ sameSite: config.getValue('cookieSameSite') ?? 'lax',
28
+ secure: config.getValue('apiHttps') ?? true,
29
+ maxAge: config.getValue('cookieMaxAge') || 60 * 60 * 24 * 400, // 400 days
30
+ domain: config.getValue('cookieDomain'),
31
+ };
32
+ }
33
+
34
+ abstract getSession(request: TRequest): Promise<string | null>;
35
+
36
+ abstract saveSession(
37
+ response: TResponse,
38
+ sessionData: string,
39
+ ): Promise<TResponse>;
40
+
41
+ abstract clearSession(response: TResponse): Promise<TResponse>;
42
+ }
@@ -0,0 +1,348 @@
1
+ import type { ConfigurationProvider } from '../config/ConfigurationProvider';
2
+ import {
3
+ AuthKitError,
4
+ SessionEcnryptionError,
5
+ TokenRefreshError,
6
+ } from '../errors';
7
+ import type { AuthenticationResponse, WorkOSClient } from '../client/types';
8
+ import type { TokenManager } from './TokenManager';
9
+ import type {
10
+ AuthResult,
11
+ CustomClaims,
12
+ Session,
13
+ SessionStorage,
14
+ } from './types';
15
+ import type { SessionEncryption } from './types';
16
+
17
+ export class SessionManager<TRequest, TResponse> {
18
+ private readonly config: ConfigurationProvider;
19
+ private readonly storage: SessionStorage<TRequest, TResponse>;
20
+ private readonly tokenManager: TokenManager;
21
+ private readonly client: WorkOSClient;
22
+ private readonly encryption: SessionEncryption;
23
+
24
+ constructor(
25
+ config: ConfigurationProvider,
26
+ storage: SessionStorage<TRequest, TResponse>,
27
+ tokenManager: TokenManager,
28
+ client: WorkOSClient,
29
+ encryption: SessionEncryption,
30
+ ) {
31
+ this.config = config;
32
+ this.storage = storage;
33
+ this.tokenManager = tokenManager;
34
+ this.client = client;
35
+ this.encryption = encryption;
36
+ }
37
+
38
+ private async encryptSession(session: Session): Promise<string> {
39
+ try {
40
+ const password = this.config.getValue('cookiePassword');
41
+ // const encryptedSession = await sealData(session, { password });
42
+ const encryptedSession = await this.encryption.sealData(session, {
43
+ password,
44
+ ttl: 0,
45
+ });
46
+ return encryptedSession;
47
+ } catch (error) {
48
+ throw new SessionEcnryptionError('Failed to encrypt session', error);
49
+ }
50
+ }
51
+
52
+ private async decryptSession(encryptedSession: string): Promise<Session> {
53
+ try {
54
+ const password = this.config.getValue('cookiePassword');
55
+ const session = await this.encryption.unsealData<Session>(
56
+ encryptedSession,
57
+ { password },
58
+ );
59
+ return session;
60
+ } catch (error) {
61
+ console.error('Detailed error:', error);
62
+ throw new SessionEcnryptionError('Failed to decrypt session', error);
63
+ }
64
+ }
65
+
66
+ private async getSession(request: TRequest): Promise<Session | null> {
67
+ const encryptedSession = await this.storage.getSession(request);
68
+ if (!encryptedSession) {
69
+ return null;
70
+ }
71
+ return this.decryptSession(encryptedSession);
72
+ }
73
+
74
+ private async validateSession<TCustomClaims = CustomClaims>(
75
+ encryptedSession: string,
76
+ ) {
77
+ try {
78
+ const session = await this.decryptSession(encryptedSession);
79
+
80
+ const isValid = await this.tokenManager.verifyToken(session.accessToken);
81
+
82
+ if (isValid) {
83
+ if (this.tokenManager.isTokenExpiring(session.accessToken)) {
84
+ const refreshResult =
85
+ await this.refreshSession<TCustomClaims>(session);
86
+ return {
87
+ valid: true,
88
+ session: refreshResult.session,
89
+ claims: refreshResult.claims,
90
+ };
91
+ }
92
+
93
+ const claims = this.tokenManager.parseTokenClaims<TCustomClaims>(
94
+ session.accessToken,
95
+ );
96
+
97
+ return {
98
+ valid: true,
99
+ session,
100
+ claims,
101
+ };
102
+ } else {
103
+ try {
104
+ const refreshResult =
105
+ await this.refreshSession<TCustomClaims>(session);
106
+ return {
107
+ valid: true,
108
+ session: refreshResult.session,
109
+ claims: refreshResult.claims,
110
+ };
111
+ } catch (error) {
112
+ return {
113
+ valid: false,
114
+ error:
115
+ error instanceof Error
116
+ ? error
117
+ : new TokenRefreshError('Failed to refresh session', error),
118
+ };
119
+ }
120
+ }
121
+ } catch (error) {
122
+ return {
123
+ valid: false,
124
+ error:
125
+ error instanceof Error
126
+ ? error
127
+ : new AuthKitError('Failed to decrypt session', error),
128
+ };
129
+ }
130
+ }
131
+
132
+ async withAuth<TCustomClaims = CustomClaims>(
133
+ request: TRequest,
134
+ ): Promise<AuthResult<TCustomClaims>> {
135
+ const encryptedSession = await this.storage.getSession(request);
136
+
137
+ if (!encryptedSession) {
138
+ return { user: null };
139
+ }
140
+
141
+ const { valid, session, claims } =
142
+ await this.validateSession<TCustomClaims>(encryptedSession);
143
+
144
+ if (!valid || !session || !claims) {
145
+ return { user: null };
146
+ }
147
+
148
+ return {
149
+ user: session.user,
150
+ sessionId: claims.sid,
151
+ impersonator: session.impersonator,
152
+ accessToken: session.accessToken,
153
+ refreshToken: session.refreshToken, // TODO should this be here?
154
+ claims,
155
+ };
156
+ }
157
+
158
+ async refreshSession<TCustomClaims = CustomClaims>(
159
+ session: Session,
160
+ organizationId?: string,
161
+ ) {
162
+ try {
163
+ const currentClaims = this.tokenManager.parseTokenClaims(
164
+ session.accessToken,
165
+ );
166
+ const refreshResponse =
167
+ await this.client.userManagement.authenticateWithRefreshToken({
168
+ refreshToken: session.refreshToken,
169
+ clientId: this.config.getValue('clientId'),
170
+ organizationId: organizationId ?? currentClaims.org_id,
171
+ });
172
+
173
+ const newSession: Session = {
174
+ accessToken: refreshResponse.accessToken,
175
+ refreshToken: refreshResponse.refreshToken,
176
+ user: refreshResponse.user,
177
+ impersonator: refreshResponse.impersonator,
178
+ };
179
+
180
+ const sessionData = await this.encryptSession(newSession);
181
+
182
+ const claims = this.tokenManager.parseTokenClaims<TCustomClaims>(
183
+ newSession.accessToken,
184
+ );
185
+
186
+ return {
187
+ user: newSession.user,
188
+ sessionId: claims.sid,
189
+ organizationId: claims.org_id,
190
+ role: claims.role,
191
+ permissions: claims.permissions,
192
+ entitlements: claims.entitlements,
193
+ impersonator: newSession.impersonator,
194
+ accessToken: newSession.accessToken,
195
+ claims,
196
+ sessionData,
197
+ session: newSession,
198
+ };
199
+ } catch (error) {
200
+ throw new TokenRefreshError('Failed to refresh session', error);
201
+ }
202
+ }
203
+
204
+ async getAuthorizationUrl({
205
+ returnPathname = '/',
206
+ redirectUri,
207
+ screenHint,
208
+ }: {
209
+ returnPathname?: string;
210
+ redirectUri?: string;
211
+ screenHint?: 'sign-up' | 'sign-in';
212
+ }): Promise<string> {
213
+ return this.client.userManagement.getAuthorizationUrl({
214
+ provider: 'authkit',
215
+ redirectUri: redirectUri ?? this.config.getValue('redirectUri'),
216
+ screenHint,
217
+ clientId: this.config.getValue('clientId'),
218
+ state: returnPathname
219
+ ? btoa(JSON.stringify({ returnPathname }))
220
+ : undefined,
221
+ });
222
+ }
223
+
224
+ async createSession(
225
+ authResponse: AuthenticationResponse,
226
+ response: TResponse,
227
+ ): Promise<TResponse> {
228
+ const { accessToken, refreshToken, user, impersonator } = authResponse;
229
+ if (!accessToken || !refreshToken) {
230
+ throw new AuthKitError('Missing access or refresh token');
231
+ }
232
+
233
+ const session: Session = {
234
+ accessToken,
235
+ refreshToken,
236
+ user,
237
+ impersonator,
238
+ };
239
+
240
+ const encryptedSession = await this.encryptSession(session);
241
+
242
+ // Save to response
243
+ return this.storage.saveSession(response, encryptedSession);
244
+ }
245
+
246
+ async switchToOrganization<TCustomClaims = CustomClaims>(
247
+ request: TRequest,
248
+ response: TResponse,
249
+ organizationId: string,
250
+ ): Promise<{
251
+ response: TResponse;
252
+ authResult: AuthResult<TCustomClaims>;
253
+ }> {
254
+ const session = await this.getSession(request);
255
+
256
+ if (!session) {
257
+ throw new AuthKitError('No active session to switch organization');
258
+ }
259
+
260
+ try {
261
+ const refreshResult = await this.refreshSession<TCustomClaims>(
262
+ session,
263
+ organizationId,
264
+ );
265
+
266
+ // Save the new session
267
+ const updatedResponse = await this.storage.saveSession(
268
+ response,
269
+ refreshResult.sessionData,
270
+ );
271
+
272
+ return {
273
+ response: updatedResponse,
274
+ authResult: {
275
+ user: refreshResult.user,
276
+ sessionId: refreshResult.sessionId,
277
+ impersonator: refreshResult.impersonator,
278
+ accessToken: refreshResult.accessToken,
279
+ refreshToken: refreshResult.session.refreshToken,
280
+ claims: refreshResult.claims,
281
+ },
282
+ };
283
+ } catch (error: any) {
284
+ // Handle specific WorkOS error codes
285
+ if (error?.code === 'sso_required') {
286
+ // For SSO required, we need to redirect to the authorization URL
287
+ const authUrl = await this.getAuthorizationUrl({
288
+ redirectUri: this.config.getValue('redirectUri'),
289
+ });
290
+ throw new AuthKitError(
291
+ `SSO required for organization ${organizationId}`,
292
+ error,
293
+ { authUrl },
294
+ );
295
+ }
296
+
297
+ if (error?.code === 'mfa_enrollment') {
298
+ // For MFA enrollment, also redirect to authorization URL
299
+ const authUrl = await this.getAuthorizationUrl({
300
+ redirectUri: this.config.getValue('redirectUri'),
301
+ });
302
+ throw new AuthKitError(
303
+ `MFA enrollment required for organization ${organizationId}`,
304
+ error,
305
+ { authUrl },
306
+ );
307
+ }
308
+
309
+ if (error?.authkit_redirect_url) {
310
+ // Custom redirect URL from WorkOS
311
+ throw new AuthKitError(
312
+ 'Organization switch requires authentication',
313
+ error,
314
+ { authUrl: error.authkit_redirect_url },
315
+ );
316
+ }
317
+
318
+ // Re-throw other errors
319
+ throw new AuthKitError(
320
+ `Failed to switch to organization ${organizationId}`,
321
+ error,
322
+ );
323
+ }
324
+ }
325
+
326
+ async terminateSession(
327
+ session: Session,
328
+ response: TResponse,
329
+ options?: { returnTo?: string },
330
+ ): Promise<{
331
+ response: TResponse;
332
+ logoutUrl: string;
333
+ }> {
334
+ const clearedResponse = await this.storage.clearSession(response);
335
+
336
+ const claims = this.tokenManager.parseTokenClaims(session.accessToken);
337
+
338
+ const logoutUrl = this.client.userManagement.getLogoutUrl({
339
+ sessionId: claims.sid,
340
+ returnTo: options?.returnTo,
341
+ });
342
+
343
+ return {
344
+ response: clearedResponse,
345
+ logoutUrl,
346
+ };
347
+ }
348
+ }
@@ -0,0 +1,55 @@
1
+ import { createRemoteJWKSet, decodeJwt, jwtVerify } from 'jose';
2
+ import { once } from '../../utils';
3
+ import type { WorkOSClient } from '../client/types';
4
+ import type { BaseTokenClaims, CustomClaims } from './types';
5
+
6
+ export class TokenManager {
7
+ private clientId: string;
8
+ private client: WorkOSClient;
9
+
10
+ constructor(clientId: string, client: WorkOSClient) {
11
+ this.clientId = clientId;
12
+ this.client = client;
13
+ }
14
+
15
+ private readonly getPublicKey = once(() =>
16
+ createRemoteJWKSet(new URL(this.client.getJwksUrl(this.clientId))),
17
+ );
18
+
19
+ async verifyToken(token: string): Promise<boolean> {
20
+ try {
21
+ await jwtVerify(token, this.getPublicKey());
22
+ return true;
23
+ } catch {
24
+ return false;
25
+ }
26
+ }
27
+
28
+ parseTokenClaims<TCustomClaims = CustomClaims>(
29
+ token: string,
30
+ ): BaseTokenClaims & TCustomClaims {
31
+ try {
32
+ return decodeJwt<BaseTokenClaims & TCustomClaims>(token);
33
+ } catch (error) {
34
+ throw new Error('Invalid token');
35
+ }
36
+ }
37
+
38
+ isTokenExpiring(token: string, bufferSeconds?: number): boolean {
39
+ const expiryTime = this.getTokenExpiryTime(token);
40
+ if (!expiryTime) {
41
+ return false;
42
+ }
43
+
44
+ const buffer = bufferSeconds ?? 60; // Default to 1 minute
45
+ const currentTime = Math.floor(Date.now() / 1000); // Current time in seconds
46
+ return expiryTime - currentTime <= buffer;
47
+ }
48
+
49
+ getTokenExpiryTime(token: string): number | null {
50
+ const claims = this.parseTokenClaims(token);
51
+ return claims.exp ? claims.exp : null;
52
+ }
53
+ }
54
+
55
+ export default TokenManager;
@@ -0,0 +1,88 @@
1
+ import type { Impersonator, User } from '../client/types';
2
+ import type { JWTPayload } from 'jose';
3
+
4
+ export interface BaseTokenClaims extends JWTPayload {
5
+ sid: string;
6
+ org_id?: string;
7
+ role?: string;
8
+ permissions?: string[];
9
+ entitlements?: string[];
10
+ feature_flags?: string[];
11
+ }
12
+
13
+ export type CustomClaims = Record<string, unknown>;
14
+
15
+ export interface AuthResult<TCustomClaims = Record<string, unknown>> {
16
+ refreshToken?: string;
17
+ user?: User | null;
18
+ claims?: BaseTokenClaims & TCustomClaims;
19
+ impersonator?: Impersonator;
20
+ accessToken?: string;
21
+ sessionId?: string;
22
+ }
23
+
24
+ /**
25
+ * AuthKit Session
26
+ */
27
+ export interface Session {
28
+ /**
29
+ * The session access token
30
+ */
31
+ accessToken: string;
32
+ /**
33
+ * The session refresh token - used to refresh the access token
34
+ */
35
+ refreshToken: string;
36
+ /**
37
+ * The logged-in user
38
+ */
39
+ user: User;
40
+ /**
41
+ * The impersonator user, if any
42
+ */
43
+ impersonator?: Impersonator;
44
+ }
45
+
46
+ export interface SessionStorage<TRequest, TResponse, TOptions = unknown> {
47
+ /*
48
+ * Extract session data from a request object
49
+ * @param request the framework-specific request object.
50
+ * @returns The encrypted session string or null if no session exists.
51
+ */
52
+ getSession(request: TRequest): Promise<string | null>;
53
+
54
+ /**
55
+ * Save session data to a response object.
56
+ * @param response The framework-specific response object.
57
+ * @param sessionData The encrypted session string.
58
+ * @param options Optional cookie options.
59
+ * @returns The framework-specific response object with the session cookie set.
60
+ */
61
+ saveSession(
62
+ response: TResponse,
63
+ sessionData: string,
64
+ options?: TOptions,
65
+ ): Promise<TResponse>;
66
+
67
+ /**
68
+ * @param response The frmework-specific response object.
69
+ * @returns The framework-specific response object with the session cookie removed.
70
+ */
71
+ clearSession(response: TResponse, options?: TOptions): Promise<TResponse>;
72
+ }
73
+
74
+ export interface SessionEncryption {
75
+ sealData: (
76
+ data: unknown,
77
+ options: {
78
+ password: string;
79
+ ttl?: number | undefined;
80
+ },
81
+ ) => Promise<string>;
82
+ unsealData: <T>(
83
+ encryptedData: string,
84
+ options: {
85
+ password: string;
86
+ },
87
+ ) => Promise<T>;
88
+ }
package/src/index.ts ADDED
@@ -0,0 +1,7 @@
1
+ export { getWorkOS } from './core/client/WorkOSLite';
2
+ export { configure, getConfig } from './core/config';
3
+ export { SessionManager } from './core/session/SessionManager';
4
+ export { CookieSessionStorage } from './core/session/CookieSessionStorage';
5
+ export { createAuthKitFactory } from './core/createAuthKitFactory';
6
+ export * from './core/session/types';
7
+ export * from './core/config/types';
package/src/utils.ts ADDED
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Returns a function that can only be called once.
3
+ * Subsequent calls will return the result of the first call.
4
+ * This is useful for lazy initialization.
5
+ * @param fn - The function to be called once.
6
+ * @returns A function that can only be called once.
7
+ */
8
+ export function once<TArgs extends unknown[], TReturn>(
9
+ fn: (...args: TArgs) => TReturn,
10
+ ): (...args: TArgs) => TReturn {
11
+ let called = false;
12
+ let result: TReturn;
13
+
14
+ return (...args: TArgs): TReturn => {
15
+ if (!called) {
16
+ result = fn(...args);
17
+ called = true;
18
+ }
19
+ return result;
20
+ };
21
+ }