@workos/authkit-session 0.1.3 → 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 (53) hide show
  1. package/README.md +144 -554
  2. package/dist/core/AuthKitCore.d.ts +109 -0
  3. package/dist/core/AuthKitCore.d.ts.map +1 -0
  4. package/dist/core/AuthKitCore.js +190 -0
  5. package/dist/core/AuthKitCore.js.map +1 -0
  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 +22 -9
  9. package/dist/core/session/CookieSessionStorage.js.map +1 -1
  10. package/dist/core/session/types.d.ts +35 -7
  11. package/dist/core/session/types.d.ts.map +1 -1
  12. package/dist/index.d.ts +28 -4
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +49 -4
  15. package/dist/index.js.map +1 -1
  16. package/dist/operations/AuthOperations.d.ts +83 -0
  17. package/dist/operations/AuthOperations.d.ts.map +1 -0
  18. package/dist/operations/AuthOperations.js +137 -0
  19. package/dist/operations/AuthOperations.js.map +1 -0
  20. package/dist/service/AuthService.d.ts +137 -0
  21. package/dist/service/AuthService.d.ts.map +1 -0
  22. package/dist/service/AuthService.js +224 -0
  23. package/dist/service/AuthService.js.map +1 -0
  24. package/dist/service/factory.d.ts +37 -0
  25. package/dist/service/factory.d.ts.map +1 -0
  26. package/dist/service/factory.js +60 -0
  27. package/dist/service/factory.js.map +1 -0
  28. package/package.json +6 -6
  29. package/src/core/AuthKitCore.spec.ts +262 -0
  30. package/src/core/AuthKitCore.ts +243 -0
  31. package/src/core/config/ConfigurationProvider.spec.ts +1 -0
  32. package/src/core/session/CookieSessionStorage.spec.ts +64 -58
  33. package/src/core/session/CookieSessionStorage.ts +27 -10
  34. package/src/core/session/types.ts +38 -8
  35. package/src/index.ts +56 -4
  36. package/src/operations/AuthOperations.spec.ts +299 -0
  37. package/src/operations/AuthOperations.ts +179 -0
  38. package/src/service/AuthService.spec.ts +267 -0
  39. package/src/service/AuthService.ts +288 -0
  40. package/src/service/factory.spec.ts +120 -0
  41. package/src/service/factory.ts +82 -0
  42. package/dist/core/createAuthKitFactory.d.ts +0 -64
  43. package/dist/core/createAuthKitFactory.d.ts.map +0 -1
  44. package/dist/core/createAuthKitFactory.js +0 -95
  45. package/dist/core/createAuthKitFactory.js.map +0 -1
  46. package/dist/core/session/SessionManager.d.ts +0 -51
  47. package/dist/core/session/SessionManager.d.ts.map +0 -1
  48. package/dist/core/session/SessionManager.js +0 -238
  49. package/dist/core/session/SessionManager.js.map +0 -1
  50. package/src/core/createAuthKitFactory.spec.ts +0 -161
  51. package/src/core/createAuthKitFactory.ts +0 -195
  52. package/src/core/session/SessionManager.spec.ts +0 -357
  53. package/src/core/session/SessionManager.ts +0 -357
@@ -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();
@@ -133,4 +122,21 @@ describe('CookieSessionStorage', () => {
133
122
  expect(clearedResult.headers).toHaveProperty('Set-Cookie');
134
123
  });
135
124
  });
125
+
126
+ describe('buildSetCookie', () => {
127
+ it('capitalizes SameSite values for Safari compatibility', async () => {
128
+ const testCases = [
129
+ { input: 'lax' as const, expected: 'SameSite=Lax' },
130
+ { input: 'strict' as const, expected: 'SameSite=Strict' },
131
+ { input: 'none' as const, expected: 'SameSite=None' },
132
+ ];
133
+
134
+ for (const { input, expected } of testCases) {
135
+ const config = createMockConfig({ cookieSameSite: input });
136
+ const storage = new TestCookieSessionStorage(config);
137
+ const result = await storage.saveSession(undefined, 'test-data');
138
+ expect(result.headers?.['Set-Cookie']).toContain(expected);
139
+ }
140
+ });
141
+ });
136
142
  });
@@ -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,18 +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';
24
+
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)
36
+ }
37
+ }
38
+
26
39
  this.cookieOptions = {
27
40
  path: '/',
28
41
  httpOnly: true,
29
- sameSite: config.getValue('cookieSameSite') ?? 'lax',
30
- secure: config.getValue('apiHttps') ?? true,
31
- maxAge: config.getValue('cookieMaxAge') || 60 * 60 * 24 * 400, // 400 days
32
- domain: config.getValue('cookieDomain'),
42
+ sameSite,
43
+ secure,
44
+ maxAge: config.cookieMaxAge ?? 60 * 60 * 24 * 400, // 400 days
45
+ domain: config.cookieDomain,
33
46
  };
34
47
  }
35
48
 
@@ -48,7 +61,11 @@ export abstract class CookieSessionStorage<TRequest, TResponse>
48
61
  if (o.maxAge || expired) a.push(`Max-Age=${expired ? 0 : o.maxAge}`);
49
62
  if (o.httpOnly) a.push('HttpOnly');
50
63
  if (o.secure) a.push('Secure');
51
- if (o.sameSite) a.push(`SameSite=${o.sameSite}`);
64
+ if (o.sameSite) {
65
+ const capitalizedSameSite =
66
+ o.sameSite.charAt(0).toUpperCase() + o.sameSite.slice(1).toLowerCase();
67
+ a.push(`SameSite=${capitalizedSameSite}`);
68
+ }
52
69
  if (o.priority) a.push(`Priority=${o.priority}`);
53
70
  if (o.partitioned) a.push('Partitioned');
54
71
  return a.join('; ');
@@ -13,14 +13,42 @@ export interface BaseTokenClaims extends JWTPayload {
13
13
 
14
14
  export type CustomClaims = Record<string, unknown>;
15
15
 
16
- export interface AuthResult<TCustomClaims = Record<string, unknown>> {
17
- refreshToken?: string;
18
- user?: User | null;
19
- claims?: BaseTokenClaims & TCustomClaims;
20
- impersonator?: Impersonator;
21
- accessToken?: string;
22
- sessionId?: string;
23
- }
16
+ /**
17
+ * Authentication result - discriminated union based on user presence.
18
+ *
19
+ * TypeScript can narrow this type by checking if user is null:
20
+ *
21
+ * @example
22
+ * ```typescript
23
+ * const { auth } = await authService.withAuth(request);
24
+ *
25
+ * if (!auth.user) {
26
+ * // auth is { user: null }
27
+ * return redirect('/login');
28
+ * }
29
+ *
30
+ * // TypeScript knows: auth.user exists, so sessionId, accessToken, etc. also exist
31
+ * console.log(auth.sessionId); // ← No ! needed, TypeScript knows it's string
32
+ * ```
33
+ */
34
+ export type AuthResult<TCustomClaims = Record<string, unknown>> =
35
+ | {
36
+ user: null;
37
+ }
38
+ | {
39
+ user: User;
40
+ sessionId: string;
41
+ accessToken: string;
42
+ refreshToken: string;
43
+ claims: BaseTokenClaims & TCustomClaims;
44
+ organizationId?: string;
45
+ role?: string;
46
+ roles?: string[];
47
+ permissions?: string[];
48
+ entitlements?: string[];
49
+ featureFlags?: string[];
50
+ impersonator?: Impersonator;
51
+ };
24
52
 
25
53
  /**
26
54
  * AuthKit Session
@@ -114,6 +142,8 @@ export interface AuthUrlOptions {
114
142
  organizationId?: string;
115
143
  loginHint?: string;
116
144
  prompt?: 'login' | 'none' | 'consent' | 'select_account';
145
+ /** Custom state to pass through the OAuth flow. Returned in handleCallback. */
146
+ state?: string;
117
147
  }
118
148
 
119
149
  /**
package/src/index.ts CHANGED
@@ -1,4 +1,50 @@
1
- export { getWorkOS } from './core/client/workos.js';
1
+ /**
2
+ * @workos/authkit-session
3
+ *
4
+ * Framework-agnostic authentication library for WorkOS.
5
+ *
6
+ * Provides authentication business logic (JWT verification, token refresh)
7
+ * with a pluggable storage adapter pattern for framework integration.
8
+ *
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)
14
+ *
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
+ */
22
+
23
+ // ============================================
24
+ // Public API
25
+ // ============================================
26
+ export { AuthService } from './service/AuthService.js';
27
+ export { createAuthService } from './service/factory.js';
28
+
29
+ // ============================================
30
+ // Advanced (Internal Layers)
31
+ // ============================================
32
+ export { AuthKitCore } from './core/AuthKitCore.js';
33
+ export { AuthOperations } from './operations/AuthOperations.js';
34
+
35
+ // ============================================
36
+ // Storage Helpers
37
+ // ============================================
38
+ export { CookieSessionStorage } from './core/session/CookieSessionStorage.js';
39
+
40
+ // ============================================
41
+ // Encryption Fallback
42
+ // ============================================
43
+ export { default as sessionEncryption } from './core/encryption/ironWebcryptoEncryption.js';
44
+
45
+ // ============================================
46
+ // Configuration
47
+ // ============================================
2
48
  export {
3
49
  configure,
4
50
  getConfig,
@@ -6,9 +52,15 @@ export {
6
52
  validateConfig,
7
53
  } from './core/config.js';
8
54
  export { ConfigurationProvider } from './core/config/ConfigurationProvider.js';
9
- export { SessionManager } from './core/session/SessionManager.js';
10
- export { CookieSessionStorage } from './core/session/CookieSessionStorage.js';
11
- export { createAuthKitFactory } from './core/createAuthKitFactory.js';
55
+
56
+ // ============================================
57
+ // Client Factory
58
+ // ============================================
59
+ export { getWorkOS } from './core/client/workos.js';
60
+
61
+ // ============================================
62
+ // Type Exports
63
+ // ============================================
12
64
  export * from './core/session/types.js';
13
65
  export * from './core/config/types.js';
14
66
  export type {
@@ -0,0 +1,299 @@
1
+ import { AuthOperations } from './AuthOperations.js';
2
+
3
+ const mockConfig = {
4
+ clientId: 'test-client-id',
5
+ redirectUri: 'http://localhost:3000/callback',
6
+ cookieName: 'wos-session',
7
+ };
8
+
9
+ const mockUser = {
10
+ id: 'user_123',
11
+ email: 'test@example.com',
12
+ object: 'user',
13
+ firstName: 'Test',
14
+ lastName: 'User',
15
+ emailVerified: true,
16
+ profilePictureUrl: null,
17
+ createdAt: '2023-01-01T00:00:00Z',
18
+ updatedAt: '2023-01-01T00:00:00Z',
19
+ lastSignInAt: '2023-01-01T00:00:00Z',
20
+ locale: 'en-US',
21
+ externalId: null,
22
+ metadata: {},
23
+ } as const;
24
+
25
+ const mockCore = {
26
+ validateAndRefresh: async () => ({
27
+ valid: true,
28
+ refreshed: true,
29
+ session: {
30
+ accessToken: 'new-access-token',
31
+ refreshToken: 'new-refresh-token',
32
+ user: mockUser,
33
+ impersonator: undefined,
34
+ },
35
+ claims: {
36
+ sub: 'user_123',
37
+ sid: 'session_123',
38
+ exp: Math.floor(Date.now() / 1000) + 3600,
39
+ org_id: 'org_123',
40
+ },
41
+ }),
42
+ encryptSession: async () => 'encrypted-session-data',
43
+ };
44
+
45
+ const mockClient = {
46
+ userManagement: {
47
+ getLogoutUrl: ({ sessionId, returnTo }: any) =>
48
+ `https://api.workos.com/sso/logout?session_id=${sessionId}&return_to=${returnTo || ''}`,
49
+ getAuthorizationUrl: ({ clientId, redirectUri, screenHint, state }: any) =>
50
+ `https://api.workos.com/sso/authorize?client_id=${clientId}&redirect_uri=${encodeURIComponent(redirectUri)}&screen_hint=${screenHint || ''}&state=${state || ''}`,
51
+ },
52
+ };
53
+
54
+ describe('AuthOperations', () => {
55
+ let operations: AuthOperations;
56
+
57
+ beforeEach(() => {
58
+ operations = new AuthOperations(
59
+ mockCore as any,
60
+ mockClient as any,
61
+ mockConfig as any,
62
+ );
63
+ });
64
+
65
+ describe('constructor', () => {
66
+ it('creates instance with required dependencies', () => {
67
+ expect(operations).toBeInstanceOf(AuthOperations);
68
+ });
69
+ });
70
+
71
+ describe('getLogoutUrl()', () => {
72
+ it('returns logout URL with session ID', () => {
73
+ const result = operations.getLogoutUrl('session_123');
74
+
75
+ expect(result).toContain('session_id=session_123');
76
+ });
77
+
78
+ it('includes returnTo in logout URL', () => {
79
+ const result = operations.getLogoutUrl('session_123', {
80
+ returnTo: 'http://localhost:3000',
81
+ });
82
+
83
+ expect(result).toContain('return_to=');
84
+ });
85
+ });
86
+
87
+ describe('switchOrganization()', () => {
88
+ it('delegates to refreshSession with organizationId', async () => {
89
+ const session = {
90
+ accessToken: 'test-token',
91
+ refreshToken: 'test-refresh',
92
+ user: mockUser,
93
+ impersonator: undefined,
94
+ };
95
+
96
+ const result = await operations.switchOrganization(session, 'org_456');
97
+
98
+ expect(result.auth.user).toEqual(mockUser);
99
+ if (result.auth.user) {
100
+ expect(result.auth.accessToken).toBe('new-access-token');
101
+ }
102
+ expect(result.encryptedSession).toBe('encrypted-session-data');
103
+ });
104
+ });
105
+
106
+ describe('refreshSession()', () => {
107
+ it('refreshes session and returns auth result', async () => {
108
+ const session = {
109
+ accessToken: 'test-token',
110
+ refreshToken: 'test-refresh',
111
+ user: mockUser,
112
+ impersonator: undefined,
113
+ };
114
+
115
+ const result = await operations.refreshSession(session);
116
+ const auth = result.auth as Extract<typeof result.auth, { user: object }>;
117
+
118
+ expect(auth.user).toEqual(mockUser);
119
+ expect(auth.accessToken).toBe('new-access-token');
120
+ expect(auth.refreshToken).toBe('new-refresh-token');
121
+ expect(auth.sessionId).toBe('session_123');
122
+ expect(result.encryptedSession).toBe('encrypted-session-data');
123
+ });
124
+
125
+ it('passes organizationId to validateAndRefresh when provided', async () => {
126
+ let capturedOptions: any;
127
+ const coreWithSpy = {
128
+ validateAndRefresh: async (_session: any, options?: any) => {
129
+ capturedOptions = options;
130
+ return {
131
+ valid: true,
132
+ refreshed: true,
133
+ session: {
134
+ accessToken: 'new-access-token',
135
+ refreshToken: 'new-refresh-token',
136
+ user: mockUser,
137
+ impersonator: undefined,
138
+ },
139
+ claims: {
140
+ sub: 'user_123',
141
+ sid: 'session_123',
142
+ exp: Math.floor(Date.now() / 1000) + 3600,
143
+ org_id: 'org_456',
144
+ },
145
+ };
146
+ },
147
+ encryptSession: async () => 'encrypted-session-data',
148
+ };
149
+ const testOps = new AuthOperations(
150
+ coreWithSpy as any,
151
+ mockClient as any,
152
+ mockConfig as any,
153
+ );
154
+
155
+ const session = {
156
+ accessToken: 'test-token',
157
+ refreshToken: 'test-refresh',
158
+ user: mockUser,
159
+ impersonator: undefined,
160
+ };
161
+
162
+ await testOps.refreshSession(session, 'org_456');
163
+
164
+ expect(capturedOptions).toEqual({
165
+ force: true,
166
+ organizationId: 'org_456',
167
+ });
168
+ });
169
+
170
+ it('calls validateAndRefresh with force: true and no organizationId when not provided', async () => {
171
+ let capturedOptions: any;
172
+ const coreWithSpy = {
173
+ validateAndRefresh: async (_session: any, options?: any) => {
174
+ capturedOptions = options;
175
+ return {
176
+ valid: true,
177
+ refreshed: true,
178
+ session: {
179
+ accessToken: 'new-access-token',
180
+ refreshToken: 'new-refresh-token',
181
+ user: mockUser,
182
+ impersonator: undefined,
183
+ },
184
+ claims: {
185
+ sub: 'user_123',
186
+ sid: 'session_123',
187
+ exp: Math.floor(Date.now() / 1000) + 3600,
188
+ org_id: 'org_123',
189
+ },
190
+ };
191
+ },
192
+ encryptSession: async () => 'encrypted-session-data',
193
+ };
194
+ const testOps = new AuthOperations(
195
+ coreWithSpy as any,
196
+ mockClient as any,
197
+ mockConfig as any,
198
+ );
199
+
200
+ const session = {
201
+ accessToken: 'test-token',
202
+ refreshToken: 'test-refresh',
203
+ user: mockUser,
204
+ impersonator: undefined,
205
+ };
206
+
207
+ await testOps.refreshSession(session);
208
+
209
+ expect(capturedOptions).toEqual({
210
+ force: true,
211
+ organizationId: undefined,
212
+ });
213
+ });
214
+ });
215
+
216
+ describe('getAuthorizationUrl()', () => {
217
+ it('returns WorkOS authorization URL', async () => {
218
+ const result = await operations.getAuthorizationUrl();
219
+
220
+ expect(result).toContain('client_id=test-client-id');
221
+ expect(result).toContain('redirect_uri');
222
+ });
223
+
224
+ it('encodes returnPathname in URL-safe base64 state', async () => {
225
+ const result = await operations.getAuthorizationUrl({
226
+ returnPathname: '/dashboard',
227
+ });
228
+
229
+ expect(result).toContain('state=');
230
+ const stateMatch = result.match(/state=([^&]+)/);
231
+ expect(stateMatch).toBeTruthy();
232
+
233
+ // Decode URL-safe base64: reverse - to +, _ to /
234
+ const urlSafeState = stateMatch![1]!;
235
+ const standardBase64 = urlSafeState.replace(/-/g, '+').replace(/_/g, '/');
236
+ const decoded = JSON.parse(atob(standardBase64));
237
+ expect(decoded.returnPathname).toBe('/dashboard');
238
+ });
239
+
240
+ it('combines internal state with custom user state', async () => {
241
+ const result = await operations.getAuthorizationUrl({
242
+ returnPathname: '/profile',
243
+ state: 'my-custom-state',
244
+ });
245
+
246
+ expect(result).toContain('state=');
247
+ const stateMatch = result.match(/state=([^&]+)/);
248
+ expect(stateMatch).toBeTruthy();
249
+
250
+ // State should be in format: internal.userState
251
+ const fullState = stateMatch![1]!;
252
+ expect(fullState).toContain('.');
253
+ const [internal, userState] = fullState.split('.');
254
+ expect(userState).toBe('my-custom-state');
255
+
256
+ // Decode internal part
257
+ const standardBase64 = internal!.replace(/-/g, '+').replace(/_/g, '/');
258
+ const decoded = JSON.parse(atob(standardBase64));
259
+ expect(decoded.returnPathname).toBe('/profile');
260
+ });
261
+
262
+ it('passes custom state as-is when no returnPathname', async () => {
263
+ const result = await operations.getAuthorizationUrl({
264
+ state: 'only-user-state',
265
+ });
266
+
267
+ expect(result).toContain('state=');
268
+ const stateMatch = result.match(/state=([^&]+)/);
269
+ expect(stateMatch).toBeTruthy();
270
+
271
+ // State should be passed through directly without internal wrapper
272
+ expect(stateMatch![1]).toBe('only-user-state');
273
+ });
274
+
275
+ it('includes screenHint when provided', async () => {
276
+ const result = await operations.getAuthorizationUrl({
277
+ screenHint: 'sign-up',
278
+ });
279
+
280
+ expect(result).toContain('screen_hint=sign-up');
281
+ });
282
+ });
283
+
284
+ describe('getSignInUrl()', () => {
285
+ it('returns authorization URL with sign-in hint', async () => {
286
+ const result = await operations.getSignInUrl();
287
+
288
+ expect(result).toContain('screen_hint=sign-in');
289
+ });
290
+ });
291
+
292
+ describe('getSignUpUrl()', () => {
293
+ it('returns authorization URL with sign-up hint', async () => {
294
+ const result = await operations.getSignUpUrl();
295
+
296
+ expect(result).toContain('screen_hint=sign-up');
297
+ });
298
+ });
299
+ });