@workos/authkit-session 0.2.0-beta.0 → 0.2.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.
Files changed (40) hide show
  1. package/README.md +96 -781
  2. package/dist/core/AuthKitCore.d.ts +11 -9
  3. package/dist/core/AuthKitCore.d.ts.map +1 -1
  4. package/dist/core/AuthKitCore.js +20 -19
  5. package/dist/core/AuthKitCore.js.map +1 -1
  6. package/dist/core/session/CookieSessionStorage.d.ts +2 -3
  7. package/dist/core/session/CookieSessionStorage.d.ts.map +1 -1
  8. package/dist/core/session/CookieSessionStorage.js +14 -20
  9. package/dist/core/session/CookieSessionStorage.js.map +1 -1
  10. package/dist/core/session/types.d.ts +8 -0
  11. package/dist/core/session/types.d.ts.map +1 -1
  12. package/dist/index.d.ts +17 -16
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +25 -24
  15. package/dist/index.js.map +1 -1
  16. package/dist/operations/AuthOperations.d.ts +13 -14
  17. package/dist/operations/AuthOperations.d.ts.map +1 -1
  18. package/dist/operations/AuthOperations.js +37 -47
  19. package/dist/operations/AuthOperations.js.map +1 -1
  20. package/dist/service/AuthService.d.ts +22 -41
  21. package/dist/service/AuthService.d.ts.map +1 -1
  22. package/dist/service/AuthService.js +64 -65
  23. package/dist/service/AuthService.js.map +1 -1
  24. package/dist/service/factory.d.ts.map +1 -1
  25. package/dist/service/factory.js +24 -10
  26. package/dist/service/factory.js.map +1 -1
  27. package/package.json +2 -2
  28. package/src/core/AuthKitCore.spec.ts +12 -19
  29. package/src/core/AuthKitCore.ts +26 -22
  30. package/src/core/config/ConfigurationProvider.spec.ts +1 -0
  31. package/src/core/session/CookieSessionStorage.spec.ts +51 -62
  32. package/src/core/session/CookieSessionStorage.ts +19 -22
  33. package/src/core/session/types.ts +8 -0
  34. package/src/index.ts +26 -25
  35. package/src/operations/AuthOperations.spec.ts +128 -69
  36. package/src/operations/AuthOperations.ts +53 -66
  37. package/src/service/AuthService.spec.ts +66 -40
  38. package/src/service/AuthService.ts +77 -82
  39. package/src/service/factory.spec.ts +20 -9
  40. package/src/service/factory.ts +33 -20
@@ -1,7 +1,7 @@
1
1
  import type { Impersonator, User, WorkOS } from '@workos-inc/node';
2
2
  import { createRemoteJWKSet, decodeJwt, jwtVerify } from 'jose';
3
3
  import { once } from '../utils.js';
4
- import type { ConfigurationProvider } from './config/ConfigurationProvider.js';
4
+ import type { AuthKitConfig } from './config/types.js';
5
5
  import { SessionEncryptionError, TokenRefreshError } from './errors.js';
6
6
  import type {
7
7
  BaseTokenClaims,
@@ -18,27 +18,26 @@ import type {
18
18
  *
19
19
  * Responsibilities:
20
20
  * - Token validation (JWT verification against JWKS)
21
- * - Token expiry detection
22
21
  * - Token claims parsing
23
22
  * - Session encryption/decryption
24
23
  * - Token refresh (calling WorkOS API)
25
24
  * - Session validation orchestration
26
25
  */
27
26
  export class AuthKitCore {
28
- private config: ConfigurationProvider;
27
+ private config: AuthKitConfig;
29
28
  private client: WorkOS;
30
29
  private encryption: SessionEncryption;
31
30
  private clientId: string;
32
31
 
33
32
  constructor(
34
- config: ConfigurationProvider,
33
+ config: AuthKitConfig,
35
34
  client: WorkOS,
36
35
  encryption: SessionEncryption,
37
36
  ) {
38
37
  this.config = config;
39
38
  this.client = client;
40
39
  this.encryption = encryption;
41
- this.clientId = config.getValue('clientId');
40
+ this.clientId = config.clientId;
42
41
  }
43
42
 
44
43
  /**
@@ -69,10 +68,10 @@ export class AuthKitCore {
69
68
  * Check if a token is expiring soon.
70
69
  *
71
70
  * @param token - The JWT access token
72
- * @param bufferSeconds - How many seconds before expiry to consider "expiring" (default: 60)
71
+ * @param buffer - How many seconds before expiry to consider "expiring" (default: 60)
73
72
  * @returns true if token expires within buffer period
74
73
  */
75
- isTokenExpiring(token: string, buffer: number = 60): boolean {
74
+ isTokenExpiring(token: string, buffer: number = 10): boolean {
76
75
  const expiryTime = this.getTokenExpiryTime(token);
77
76
  if (!expiryTime) {
78
77
  return false;
@@ -88,9 +87,9 @@ export class AuthKitCore {
88
87
  * @param token - The JWT access token
89
88
  * @returns Unix timestamp of expiry, or null if not present
90
89
  */
91
- private getTokenExpiryTime(token: string): number | null {
90
+ private getTokenExpiryTime(token: string): number | undefined {
92
91
  const claims = this.parseTokenClaims(token);
93
- return claims.exp ?? null;
92
+ return claims.exp;
94
93
  }
95
94
 
96
95
  /**
@@ -119,9 +118,8 @@ export class AuthKitCore {
119
118
  */
120
119
  async encryptSession(session: Session): Promise<string> {
121
120
  try {
122
- const password = this.config.getValue('cookiePassword');
123
121
  const encryptedSession = await this.encryption.sealData(session, {
124
- password,
122
+ password: this.config.cookiePassword,
125
123
  ttl: 0,
126
124
  });
127
125
  return encryptedSession;
@@ -139,10 +137,9 @@ export class AuthKitCore {
139
137
  */
140
138
  async decryptSession(encryptedSession: string): Promise<Session> {
141
139
  try {
142
- const password = this.config.getValue('cookiePassword');
143
140
  const session = await this.encryption.unsealData<Session>(
144
141
  encryptedSession,
145
- { password },
142
+ { password: this.config.cookiePassword },
146
143
  );
147
144
  return session;
148
145
  } catch (error) {
@@ -189,17 +186,18 @@ export class AuthKitCore {
189
186
  /**
190
187
  * Validate a session and refresh if needed.
191
188
  *
192
- * This is the core orchestration method that decides:
193
- * 1. Is the token valid?
194
- * 2. Is it expiring soon?
195
- * 3. Should we refresh it?
189
+ * Only refreshes when token is invalid (expired) or force is true.
196
190
  *
197
191
  * @param session - The current session with access and refresh tokens
192
+ * @param options - Optional settings
193
+ * @param options.force - Force refresh even if token is valid (for org switching)
194
+ * @param options.organizationId - Organization ID to switch to during refresh
198
195
  * @returns Validation result with refreshed session if needed
199
196
  * @throws TokenRefreshError if refresh fails
200
197
  */
201
198
  async validateAndRefresh<TCustomClaims = CustomClaims>(
202
199
  session: Session,
200
+ options?: { force?: boolean; organizationId?: string },
203
201
  ): Promise<{
204
202
  valid: boolean;
205
203
  refreshed: boolean;
@@ -207,19 +205,25 @@ export class AuthKitCore {
207
205
  claims: BaseTokenClaims & TCustomClaims;
208
206
  }> {
209
207
  const { accessToken } = session;
208
+ const { force = false, organizationId: explicitOrgId } = options ?? {};
209
+
210
210
  const isValid = await this.verifyToken(accessToken);
211
- const isExpiring = this.isTokenExpiring(accessToken);
212
- if (isValid && !isExpiring) {
211
+
212
+ // Return early if token is valid and not forced
213
+ if (isValid && !force) {
213
214
  const claims = this.parseTokenClaims<TCustomClaims>(accessToken);
214
215
  return { valid: true, refreshed: false, session, claims };
215
216
  }
216
217
 
217
- let organizationId: string | undefined;
218
- if (isValid) {
218
+ // Determine organization ID: explicit > extracted from token
219
+ let organizationId = explicitOrgId;
220
+ if (!organizationId && isValid) {
219
221
  try {
220
222
  const oldClaims = this.parseTokenClaims(accessToken);
221
223
  organizationId = oldClaims.org_id;
222
- } catch {}
224
+ } catch {
225
+ // Token parsing failed - refresh without org context
226
+ }
223
227
  }
224
228
 
225
229
  const newSession = await this.refreshTokens(
@@ -6,6 +6,7 @@ describe('ConfigurationProvider', () => {
6
6
 
7
7
  beforeEach(() => {
8
8
  provider = new ConfigurationProvider();
9
+ provider.setValueSource(() => undefined); // Default to no env vars
9
10
  });
10
11
 
11
12
  describe('configure()', () => {
@@ -1,17 +1,20 @@
1
1
  import { CookieSessionStorage } from './CookieSessionStorage.js';
2
-
3
- // Mock config provider
4
- const createMockConfig = (overrides: Record<string, any> = {}) => ({
5
- getValue: (key: string) => {
6
- const defaults = {
7
- cookieName: 'wos-session',
8
- cookieSameSite: 'lax',
9
- apiHttps: true,
10
- cookieMaxAge: 60 * 60 * 24 * 400,
11
- cookieDomain: undefined,
12
- };
13
- return overrides[key] ?? defaults[key as keyof typeof defaults];
14
- },
2
+ import type { AuthKitConfig } from '../config/types.js';
3
+
4
+ // Mock config
5
+ const createMockConfig = (
6
+ overrides: Partial<AuthKitConfig> = {},
7
+ ): AuthKitConfig => ({
8
+ clientId: 'test-client-id',
9
+ apiKey: 'test-api-key',
10
+ redirectUri: 'https://example.com/callback',
11
+ cookiePassword: 'test-password-that-is-32-chars-long!!',
12
+ cookieName: 'wos-session',
13
+ cookieSameSite: 'lax',
14
+ apiHttps: true,
15
+ cookieMaxAge: 60 * 60 * 24 * 400,
16
+ cookieDomain: undefined,
17
+ ...overrides,
15
18
  });
16
19
 
17
20
  // Concrete implementation for testing the abstract class
@@ -24,7 +27,7 @@ class TestCookieSessionStorage extends CookieSessionStorage<string, string> {
24
27
  describe('CookieSessionStorage', () => {
25
28
  describe('constructor', () => {
26
29
  it('sets default cookie configuration', () => {
27
- const storage = new TestCookieSessionStorage(createMockConfig() as any);
30
+ const storage = new TestCookieSessionStorage(createMockConfig());
28
31
 
29
32
  expect(storage['cookieName']).toBe('wos-session');
30
33
  expect(storage['cookieOptions']).toEqual({
@@ -39,79 +42,65 @@ describe('CookieSessionStorage', () => {
39
42
 
40
43
  it('uses custom cookie name from config', () => {
41
44
  const config = createMockConfig({ cookieName: 'custom-session' });
42
- const storage = new TestCookieSessionStorage(config as any);
45
+ const storage = new TestCookieSessionStorage(config);
43
46
 
44
47
  expect(storage['cookieName']).toBe('custom-session');
45
48
  });
46
49
 
47
- it('falls back to default cookie name when config returns falsy', () => {
48
- const config = createMockConfig({ cookieName: '' });
49
- const storage = new TestCookieSessionStorage(config as any);
50
-
51
- expect(storage['cookieName']).toBe('wos_session');
52
- });
53
-
54
50
  it('uses custom sameSite setting', () => {
55
51
  const config = createMockConfig({ cookieSameSite: 'strict' });
56
- const storage = new TestCookieSessionStorage(config as any);
52
+ const storage = new TestCookieSessionStorage(config);
57
53
 
58
54
  expect(storage['cookieOptions'].sameSite).toBe('strict');
59
55
  });
60
56
 
61
- it('uses custom security settings', () => {
62
- const config = createMockConfig({ apiHttps: false });
63
- const storage = new TestCookieSessionStorage(config as any);
57
+ it('infers secure=false from http redirectUri', () => {
58
+ const config = createMockConfig({
59
+ redirectUri: 'http://localhost:3000/callback',
60
+ });
61
+ const storage = new TestCookieSessionStorage(config);
64
62
 
65
63
  expect(storage['cookieOptions'].secure).toBe(false);
66
64
  });
67
65
 
66
+ it('infers secure=true from https redirectUri', () => {
67
+ const config = createMockConfig({
68
+ redirectUri: 'https://example.com/callback',
69
+ });
70
+ const storage = new TestCookieSessionStorage(config);
71
+
72
+ expect(storage['cookieOptions'].secure).toBe(true);
73
+ });
74
+
75
+ it('forces secure=true when sameSite is none', () => {
76
+ const config = createMockConfig({
77
+ cookieSameSite: 'none',
78
+ redirectUri: 'http://localhost:3000/callback',
79
+ });
80
+ const storage = new TestCookieSessionStorage(config);
81
+
82
+ expect(storage['cookieOptions'].secure).toBe(true);
83
+ });
84
+
68
85
  it('uses custom max age', () => {
69
86
  const customMaxAge = 60 * 60 * 24; // 1 day
70
87
  const config = createMockConfig({ cookieMaxAge: customMaxAge });
71
- const storage = new TestCookieSessionStorage(config as any);
88
+ const storage = new TestCookieSessionStorage(config);
72
89
 
73
90
  expect(storage['cookieOptions'].maxAge).toBe(customMaxAge);
74
91
  });
75
92
 
76
- it('uses default max age when config returns null', () => {
77
- const config = createMockConfig({ cookieMaxAge: null });
78
- const storage = new TestCookieSessionStorage(config as any);
79
-
80
- expect(storage['cookieOptions'].maxAge).toBe(60 * 60 * 24 * 400);
81
- });
82
-
83
93
  it('sets custom cookie domain', () => {
84
94
  const config = createMockConfig({ cookieDomain: '.example.com' });
85
- const storage = new TestCookieSessionStorage(config as any);
95
+ const storage = new TestCookieSessionStorage(config);
86
96
 
87
97
  expect(storage['cookieOptions'].domain).toBe('.example.com');
88
98
  });
89
-
90
- it('uses all default fallbacks', () => {
91
- const config = createMockConfig({
92
- cookieName: '',
93
- cookieSameSite: null,
94
- apiHttps: null,
95
- cookieMaxAge: null,
96
- cookieDomain: null,
97
- });
98
- const storage = new TestCookieSessionStorage(config as any);
99
-
100
- expect(storage['cookieName']).toBe('wos_session');
101
- expect(storage['cookieOptions']).toEqual({
102
- path: '/',
103
- httpOnly: true,
104
- sameSite: 'lax',
105
- secure: true,
106
- maxAge: 60 * 60 * 24 * 400,
107
- domain: undefined,
108
- });
109
- });
110
99
  });
111
100
 
112
101
  describe('abstract methods', () => {
113
102
  it('implements SessionStorage interface', () => {
114
- const storage = new TestCookieSessionStorage(createMockConfig() as any);
103
+ const storage = new TestCookieSessionStorage(createMockConfig());
115
104
 
116
105
  expect(typeof storage.getSession).toBe('function');
117
106
  expect(typeof storage.saveSession).toBe('function');
@@ -119,7 +108,7 @@ describe('CookieSessionStorage', () => {
119
108
  });
120
109
 
121
110
  it('concrete implementation works', async () => {
122
- const storage = new TestCookieSessionStorage(createMockConfig() as any);
111
+ const storage = new TestCookieSessionStorage(createMockConfig());
123
112
 
124
113
  const session = await storage.getSession();
125
114
  expect(session).toBeNull();
@@ -137,14 +126,14 @@ describe('CookieSessionStorage', () => {
137
126
  describe('buildSetCookie', () => {
138
127
  it('capitalizes SameSite values for Safari compatibility', async () => {
139
128
  const testCases = [
140
- { input: 'lax', expected: 'SameSite=Lax' },
141
- { input: 'strict', expected: 'SameSite=Strict' },
142
- { input: 'none', expected: 'SameSite=None' },
129
+ { input: 'lax' as const, expected: 'SameSite=Lax' },
130
+ { input: 'strict' as const, expected: 'SameSite=Strict' },
131
+ { input: 'none' as const, expected: 'SameSite=None' },
143
132
  ];
144
133
 
145
134
  for (const { input, expected } of testCases) {
146
135
  const config = createMockConfig({ cookieSameSite: input });
147
- const storage = new TestCookieSessionStorage(config as any);
136
+ const storage = new TestCookieSessionStorage(config);
148
137
  const result = await storage.saveSession(undefined, 'test-data');
149
138
  expect(result.headers?.['Set-Cookie']).toContain(expected);
150
139
  }
@@ -1,4 +1,4 @@
1
- import type { ConfigurationProvider } from '../config/ConfigurationProvider.js';
1
+ import type { AuthKitConfig } from '../config/types.js';
2
2
  import type { HeadersBag, SessionStorage } from './types.js';
3
3
 
4
4
  export interface CookieOptions {
@@ -18,35 +18,31 @@ export abstract class CookieSessionStorage<TRequest, TResponse>
18
18
  {
19
19
  protected cookieName: string;
20
20
  protected readonly cookieOptions: CookieOptions;
21
- protected config: ConfigurationProvider;
22
21
 
23
- constructor(config: ConfigurationProvider) {
24
- this.config = config;
25
- this.cookieName = config.getValue('cookieName') || 'wos_session';
22
+ constructor(config: AuthKitConfig) {
23
+ this.cookieName = config.cookieName ?? 'wos_session';
26
24
 
27
- // Infer secure flag from redirectUri if not explicitly set
28
- let secure = config.getValue('apiHttps');
29
- if (secure === undefined) {
30
- const redirectUri = config.getValue('redirectUri');
31
- if (redirectUri) {
32
- try {
33
- const url = new URL(redirectUri);
34
- secure = url.protocol === 'https:';
35
- } catch {
36
- secure = true; // Default to secure if URL parsing fails
37
- }
38
- } else {
39
- secure = true; // Default to secure if no redirectUri
25
+ const sameSite = config.cookieSameSite ?? 'lax';
26
+
27
+ // Infer secure flag from redirectUri protocol
28
+ // sameSite='none' requires secure=true (browser requirement)
29
+ let secure = true;
30
+ if (sameSite.toLowerCase() !== 'none') {
31
+ try {
32
+ const url = new URL(config.redirectUri);
33
+ secure = url.protocol === 'https:';
34
+ } catch {
35
+ // Invalid URL - keep secure=true (safer default)
40
36
  }
41
37
  }
42
38
 
43
39
  this.cookieOptions = {
44
40
  path: '/',
45
41
  httpOnly: true,
46
- sameSite: config.getValue('cookieSameSite') ?? 'lax',
42
+ sameSite,
47
43
  secure,
48
- maxAge: config.getValue('cookieMaxAge') || 60 * 60 * 24 * 400, // 400 days
49
- domain: config.getValue('cookieDomain'),
44
+ maxAge: config.cookieMaxAge ?? 60 * 60 * 24 * 400, // 400 days
45
+ domain: config.cookieDomain,
50
46
  };
51
47
  }
52
48
 
@@ -66,7 +62,8 @@ export abstract class CookieSessionStorage<TRequest, TResponse>
66
62
  if (o.httpOnly) a.push('HttpOnly');
67
63
  if (o.secure) a.push('Secure');
68
64
  if (o.sameSite) {
69
- const capitalizedSameSite = o.sameSite.charAt(0).toUpperCase() + o.sameSite.slice(1).toLowerCase();
65
+ const capitalizedSameSite =
66
+ o.sameSite.charAt(0).toUpperCase() + o.sameSite.slice(1).toLowerCase();
70
67
  a.push(`SameSite=${capitalizedSameSite}`);
71
68
  }
72
69
  if (o.priority) a.push(`Priority=${o.priority}`);
@@ -41,6 +41,12 @@ export type AuthResult<TCustomClaims = Record<string, unknown>> =
41
41
  accessToken: string;
42
42
  refreshToken: string;
43
43
  claims: BaseTokenClaims & TCustomClaims;
44
+ organizationId?: string;
45
+ role?: string;
46
+ roles?: string[];
47
+ permissions?: string[];
48
+ entitlements?: string[];
49
+ featureFlags?: string[];
44
50
  impersonator?: Impersonator;
45
51
  };
46
52
 
@@ -136,6 +142,8 @@ export interface AuthUrlOptions {
136
142
  organizationId?: string;
137
143
  loginHint?: string;
138
144
  prompt?: 'login' | 'none' | 'consent' | 'select_account';
145
+ /** Custom state to pass through the OAuth flow. Returned in handleCallback. */
146
+ state?: string;
139
147
  }
140
148
 
141
149
  /**
package/src/index.ts CHANGED
@@ -1,42 +1,49 @@
1
1
  /**
2
2
  * @workos/authkit-session
3
3
  *
4
- * A toolkit library for building WorkOS AuthKit integrations.
5
- * Provides business logic primitives (crypto, JWT, refresh) that framework
6
- * adapters use to implement authentication patterns.
4
+ * Framework-agnostic authentication library for WorkOS.
7
5
  *
8
- * **Philosophy:**
9
- * - Extract complex business logic → Shared across frameworks
10
- * - Provide integration helpers → Cookie building, config management
11
- * - Let frameworks own patterns → updateSession/withAuth are framework-specific
6
+ * Provides authentication business logic (JWT verification, token refresh)
7
+ * with a pluggable storage adapter pattern for framework integration.
12
8
  *
13
- * **Core Toolkit (Recommended):**
14
- * - AuthKitCore: Token verification, encryption, refresh orchestration
15
- * - AuthOperations: WorkOS API operations (signOut, refreshSession, URLs)
16
- * - CookieSessionStorage: Cookie building helpers
17
- * - ConfigurationProvider: Environment variable and config management
9
+ * **What frameworks do:**
10
+ * - Implement storage adapter (SessionStorage<TRequest, TResponse>)
11
+ * - Add middleware for auth validation and refresh
12
+ * - Export framework-specific helpers
13
+ * - Handle session encryption (or use our fallback)
18
14
  *
19
- * **Optional Reference:**
20
- * - AuthService: Example orchestration pattern (frameworks can implement their own)
15
+ * **What this library does:**
16
+ * - All authentication logic (AuthService)
17
+ * - JWT verification (JWKS with caching)
18
+ * - Token refresh orchestration
19
+ * - WorkOS API operations
20
+ * - Session encryption fallback (iron-webcrypto, AES-256-CBC)
21
21
  */
22
22
 
23
23
  // ============================================
24
- // TIER 1: Core Business Logic (Required)
24
+ // Public API
25
25
  // ============================================
26
- export { AuthKitCore } from './core/AuthKitCore.js';
26
+ export { AuthService } from './service/AuthService.js';
27
+ export { createAuthService } from './service/factory.js';
27
28
 
28
29
  // ============================================
29
- // TIER 2: WorkOS Operations (Recommended)
30
+ // Advanced (Internal Layers)
30
31
  // ============================================
32
+ export { AuthKitCore } from './core/AuthKitCore.js';
31
33
  export { AuthOperations } from './operations/AuthOperations.js';
32
34
 
33
35
  // ============================================
34
- // TIER 3: Storage Helpers (Recommended)
36
+ // Storage Helpers
35
37
  // ============================================
36
38
  export { CookieSessionStorage } from './core/session/CookieSessionStorage.js';
37
39
 
38
40
  // ============================================
39
- // TIER 4: Configuration (Utility)
41
+ // Encryption Fallback
42
+ // ============================================
43
+ export { default as sessionEncryption } from './core/encryption/ironWebcryptoEncryption.js';
44
+
45
+ // ============================================
46
+ // Configuration
40
47
  // ============================================
41
48
  export {
42
49
  configure,
@@ -63,9 +70,3 @@ export type {
63
70
  WorkOS,
64
71
  AuthenticationResponse,
65
72
  } from '@workos-inc/node';
66
-
67
- // ============================================
68
- // Optional Reference Implementation
69
- // ============================================
70
- export { AuthService } from './service/AuthService.js';
71
- export { createAuthService } from './service/factory.js';