@workos/authkit-session 0.0.1-alpha.1 → 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.
@@ -1,7 +1,7 @@
1
1
  import type { ConfigurationProvider } from '../config/ConfigurationProvider';
2
2
  import {
3
3
  AuthKitError,
4
- SessionEcnryptionError,
4
+ SessionEncryptionError,
5
5
  TokenRefreshError,
6
6
  } from '../errors';
7
7
  import type { AuthenticationResponse, WorkOSClient } from '../client/types';
@@ -45,7 +45,7 @@ export class SessionManager<TRequest, TResponse> {
45
45
  });
46
46
  return encryptedSession;
47
47
  } catch (error) {
48
- throw new SessionEcnryptionError('Failed to encrypt session', error);
48
+ throw new SessionEncryptionError('Failed to encrypt session', error);
49
49
  }
50
50
  }
51
51
 
@@ -59,7 +59,7 @@ export class SessionManager<TRequest, TResponse> {
59
59
  return session;
60
60
  } catch (error) {
61
61
  console.error('Detailed error:', error);
62
- throw new SessionEcnryptionError('Failed to decrypt session', error);
62
+ throw new SessionEncryptionError('Failed to decrypt session', error);
63
63
  }
64
64
  }
65
65
 
@@ -76,48 +76,7 @@ export class SessionManager<TRequest, TResponse> {
76
76
  ) {
77
77
  try {
78
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
- }
79
+ return await this.validateAndRefreshIfNeeded<TCustomClaims>(session);
121
80
  } catch (error) {
122
81
  return {
123
82
  valid: false,
@@ -129,6 +88,50 @@ export class SessionManager<TRequest, TResponse> {
129
88
  }
130
89
  }
131
90
 
91
+ private async validateAndRefreshIfNeeded<TCustomClaims = CustomClaims>(
92
+ session: Session,
93
+ ) {
94
+ const isValid = await this.tokenManager.verifyToken(session.accessToken);
95
+ const isExpiring = this.tokenManager.isTokenExpiring(session.accessToken);
96
+
97
+ // Refresh if token is invalid or expiring
98
+ if (!isValid || isExpiring) {
99
+ return await this.attemptTokenRefresh<TCustomClaims>(session);
100
+ }
101
+
102
+ // Token is valid and not expiring, parse claims
103
+ const claims = this.tokenManager.parseTokenClaims<TCustomClaims>(
104
+ session.accessToken,
105
+ );
106
+
107
+ return {
108
+ valid: true,
109
+ session,
110
+ claims,
111
+ };
112
+ }
113
+
114
+ private async attemptTokenRefresh<TCustomClaims = CustomClaims>(
115
+ session: Session,
116
+ ) {
117
+ try {
118
+ const refreshResult = await this.refreshSession<TCustomClaims>(session);
119
+ return {
120
+ valid: true,
121
+ session: refreshResult.session,
122
+ claims: refreshResult.claims,
123
+ };
124
+ } catch (error) {
125
+ return {
126
+ valid: false,
127
+ error:
128
+ error instanceof Error
129
+ ? error
130
+ : new TokenRefreshError('Failed to refresh session', error),
131
+ };
132
+ }
133
+ }
134
+
132
135
  async withAuth<TCustomClaims = CustomClaims>(
133
136
  request: TRequest,
134
137
  ): Promise<AuthResult<TCustomClaims>> {
@@ -281,46 +284,41 @@ export class SessionManager<TRequest, TResponse> {
281
284
  },
282
285
  };
283
286
  } 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}`,
287
+ throw await this.handleSwitchOrganizationError(error, organizationId);
288
+ }
289
+ }
290
+
291
+ private async handleSwitchOrganizationError(
292
+ error: any,
293
+ organizationId: string,
294
+ ): Promise<AuthKitError> {
295
+ const errorCodeToMessage = {
296
+ sso_required: `SSO required for organization ${organizationId}`,
297
+ mfa_enrollment: `MFA enrollment required for organization ${organizationId}`,
298
+ };
299
+
300
+ const errorMessage =
301
+ errorCodeToMessage[error?.code as keyof typeof errorCodeToMessage];
302
+
303
+ if (errorMessage) {
304
+ const authUrl = await this.getAuthorizationUrl({
305
+ redirectUri: this.config.getValue('redirectUri'),
306
+ });
307
+ return new AuthKitError(errorMessage, error, { authUrl });
308
+ }
309
+
310
+ if (error?.authkit_redirect_url) {
311
+ return new AuthKitError(
312
+ 'Organization switch requires authentication',
321
313
  error,
314
+ { authUrl: error.authkit_redirect_url },
322
315
  );
323
316
  }
317
+
318
+ return new AuthKitError(
319
+ `Failed to switch to organization ${organizationId}`,
320
+ error,
321
+ );
324
322
  }
325
323
 
326
324
  async terminateSession(
@@ -331,10 +329,22 @@ export class SessionManager<TRequest, TResponse> {
331
329
  response: TResponse;
332
330
  logoutUrl: string;
333
331
  }> {
334
- const clearedResponse = await this.storage.clearSession(response);
335
-
336
332
  const claims = this.tokenManager.parseTokenClaims(session.accessToken);
337
333
 
334
+ // Revoke the session on WorkOS side
335
+ try {
336
+ await this.client.userManagement.revokeSession({
337
+ sessionId: claims.sid,
338
+ });
339
+ } catch (error) {
340
+ console.error('Failed to revoke session on WorkOS:', error);
341
+ // Continue with local logout even if remote revocation fails
342
+ }
343
+
344
+ // Clear the session cookie locally
345
+ const clearedResponse = await this.storage.clearSession(response);
346
+
347
+ // Generate logout URL (for completeness, though session is already revoked)
338
348
  const logoutUrl = this.client.userManagement.getLogoutUrl({
339
349
  sessionId: claims.sid,
340
350
  returnTo: options?.returnTo,
@@ -48,7 +48,7 @@ export class TokenManager {
48
48
 
49
49
  getTokenExpiryTime(token: string): number | null {
50
50
  const claims = this.parseTokenClaims(token);
51
- return claims.exp ? claims.exp : null;
51
+ return claims.exp ?? null;
52
52
  }
53
53
  }
54
54
 
@@ -1,4 +1,4 @@
1
- import type { Impersonator, User } from '../client/types';
1
+ import type { Impersonator, User } from '@workos-inc/node';
2
2
  import type { JWTPayload } from 'jose';
3
3
 
4
4
  export interface BaseTokenClaims extends JWTPayload {
package/src/index.ts CHANGED
@@ -5,3 +5,4 @@ export { CookieSessionStorage } from './core/session/CookieSessionStorage';
5
5
  export { createAuthKitFactory } from './core/createAuthKitFactory';
6
6
  export * from './core/session/types';
7
7
  export * from './core/config/types';
8
+ export type { User, Impersonator, Organization } from '@workos-inc/node';