@workos/authkit-session 0.1.3 → 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.
Files changed (51) hide show
  1. package/README.md +507 -232
  2. package/dist/core/AuthKitCore.d.ts +107 -0
  3. package/dist/core/AuthKitCore.d.ts.map +1 -0
  4. package/dist/core/AuthKitCore.js +189 -0
  5. package/dist/core/AuthKitCore.js.map +1 -0
  6. package/dist/core/session/CookieSessionStorage.d.ts.map +1 -1
  7. package/dist/core/session/CookieSessionStorage.js +22 -3
  8. package/dist/core/session/CookieSessionStorage.js.map +1 -1
  9. package/dist/core/session/types.d.ts +27 -7
  10. package/dist/core/session/types.d.ts.map +1 -1
  11. package/dist/index.d.ts +27 -4
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +48 -4
  14. package/dist/index.js.map +1 -1
  15. package/dist/operations/AuthOperations.d.ts +84 -0
  16. package/dist/operations/AuthOperations.d.ts.map +1 -0
  17. package/dist/operations/AuthOperations.js +147 -0
  18. package/dist/operations/AuthOperations.js.map +1 -0
  19. package/dist/service/AuthService.d.ts +156 -0
  20. package/dist/service/AuthService.d.ts.map +1 -0
  21. package/dist/service/AuthService.js +225 -0
  22. package/dist/service/AuthService.js.map +1 -0
  23. package/dist/service/factory.d.ts +37 -0
  24. package/dist/service/factory.d.ts.map +1 -0
  25. package/dist/service/factory.js +46 -0
  26. package/dist/service/factory.js.map +1 -0
  27. package/package.json +5 -5
  28. package/src/core/AuthKitCore.spec.ts +269 -0
  29. package/src/core/AuthKitCore.ts +239 -0
  30. package/src/core/session/CookieSessionStorage.spec.ts +17 -0
  31. package/src/core/session/CookieSessionStorage.ts +22 -2
  32. package/src/core/session/types.ts +30 -8
  33. package/src/index.ts +55 -4
  34. package/src/operations/AuthOperations.spec.ts +240 -0
  35. package/src/operations/AuthOperations.ts +192 -0
  36. package/src/service/AuthService.spec.ts +241 -0
  37. package/src/service/AuthService.ts +293 -0
  38. package/src/service/factory.spec.ts +109 -0
  39. package/src/service/factory.ts +69 -0
  40. package/dist/core/createAuthKitFactory.d.ts +0 -64
  41. package/dist/core/createAuthKitFactory.d.ts.map +0 -1
  42. package/dist/core/createAuthKitFactory.js +0 -95
  43. package/dist/core/createAuthKitFactory.js.map +0 -1
  44. package/dist/core/session/SessionManager.d.ts +0 -51
  45. package/dist/core/session/SessionManager.d.ts.map +0 -1
  46. package/dist/core/session/SessionManager.js +0 -238
  47. package/dist/core/session/SessionManager.js.map +0 -1
  48. package/src/core/createAuthKitFactory.spec.ts +0 -161
  49. package/src/core/createAuthKitFactory.ts +0 -195
  50. package/src/core/session/SessionManager.spec.ts +0 -357
  51. package/src/core/session/SessionManager.ts +0 -357
@@ -0,0 +1,240 @@
1
+ import { AuthOperations } from './AuthOperations.js';
2
+
3
+ const mockConfig = {
4
+ getValue: (key: string) => {
5
+ const values = {
6
+ clientId: 'test-client-id',
7
+ redirectUri: 'http://localhost:3000/callback',
8
+ cookieName: 'wos-session',
9
+ };
10
+ return values[key as keyof typeof values];
11
+ },
12
+ };
13
+
14
+ const mockUser = {
15
+ id: 'user_123',
16
+ email: 'test@example.com',
17
+ object: 'user',
18
+ firstName: 'Test',
19
+ lastName: 'User',
20
+ emailVerified: true,
21
+ profilePictureUrl: null,
22
+ createdAt: '2023-01-01T00:00:00Z',
23
+ updatedAt: '2023-01-01T00:00:00Z',
24
+ lastSignInAt: '2023-01-01T00:00:00Z',
25
+ externalId: null,
26
+ metadata: {},
27
+ } as const;
28
+
29
+ const mockCore = {
30
+ refreshTokens: async () => ({
31
+ accessToken: 'new-access-token',
32
+ refreshToken: 'new-refresh-token',
33
+ user: mockUser,
34
+ impersonator: undefined,
35
+ }),
36
+ encryptSession: async () => 'encrypted-session-data',
37
+ parseTokenClaims: () => ({
38
+ sub: 'user_123',
39
+ sid: 'session_123',
40
+ exp: Math.floor(Date.now() / 1000) + 3600,
41
+ org_id: 'org_123',
42
+ }),
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('signOut()', () => {
72
+ it('returns logout URL and clear cookie header', async () => {
73
+ const result = await operations.signOut('session_123');
74
+
75
+ expect(result.logoutUrl).toContain('session_id=session_123');
76
+ expect(result.clearCookieHeader).toContain('wos-session=');
77
+ expect(result.clearCookieHeader).toContain('Max-Age=0');
78
+ });
79
+
80
+ it('includes returnTo in logout URL', async () => {
81
+ const result = await operations.signOut('session_123', {
82
+ returnTo: 'http://localhost:3000',
83
+ });
84
+
85
+ expect(result.logoutUrl).toContain('return_to=');
86
+ });
87
+ });
88
+
89
+ describe('switchOrganization()', () => {
90
+ it('delegates to refreshSession with organizationId', async () => {
91
+ const session = {
92
+ accessToken: 'test-token',
93
+ refreshToken: 'test-refresh',
94
+ user: mockUser,
95
+ impersonator: undefined,
96
+ };
97
+
98
+ const result = await operations.switchOrganization(session, 'org_456');
99
+
100
+ expect(result.auth.user).toEqual(mockUser);
101
+ expect(result.auth.accessToken).toBe('new-access-token');
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
+
117
+ expect(result.auth.user).toEqual(mockUser);
118
+ expect(result.auth.accessToken).toBe('new-access-token');
119
+ expect(result.auth.refreshToken).toBe('new-refresh-token');
120
+ expect(result.auth.sessionId).toBe('session_123');
121
+ expect(result.encryptedSession).toBe('encrypted-session-data');
122
+ });
123
+
124
+ it('includes organizationId when provided', async () => {
125
+ const coreWithSpy = {
126
+ refreshTokens: async (_token: string, orgId?: string) => ({
127
+ accessToken: orgId ? 'org-token' : 'regular-token',
128
+ refreshToken: 'new-refresh-token',
129
+ user: mockUser,
130
+ impersonator: undefined,
131
+ }),
132
+ encryptSession: async () => 'encrypted-session-data',
133
+ parseTokenClaims: () => ({
134
+ sub: 'user_123',
135
+ sid: 'session_123',
136
+ exp: Math.floor(Date.now() / 1000) + 3600,
137
+ org_id: 'org_123',
138
+ }),
139
+ };
140
+ const testOps = new AuthOperations(
141
+ coreWithSpy as any,
142
+ mockClient as any,
143
+ mockConfig as any,
144
+ );
145
+
146
+ const session = {
147
+ accessToken: 'test-token',
148
+ refreshToken: 'test-refresh',
149
+ user: mockUser,
150
+ impersonator: undefined,
151
+ };
152
+
153
+ const result = await testOps.refreshSession(session, 'org_456');
154
+
155
+ expect(result.auth.accessToken).toBe('org-token');
156
+ });
157
+
158
+ it('extracts org from current token when not provided', async () => {
159
+ const validJwt =
160
+ 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyXzEyMyIsInNpZCI6InNlc3Npb25fMTIzIiwiZXhwIjoxNzM2Mzc2MDAwLCJvcmdfaWQiOiJvcmdfZnJvbV90b2tlbiJ9.fake-signature';
161
+
162
+ const coreWithSpy = {
163
+ refreshTokens: async (_token: string, orgId?: string) => ({
164
+ accessToken: orgId === 'org_from_token' ? 'extracted-org-token' : 'no-org-token',
165
+ refreshToken: 'new-refresh-token',
166
+ user: mockUser,
167
+ impersonator: undefined,
168
+ }),
169
+ encryptSession: async () => 'encrypted-session-data',
170
+ parseTokenClaims: () => ({
171
+ sub: 'user_123',
172
+ sid: 'session_123',
173
+ exp: 1736376000,
174
+ org_id: 'org_from_token',
175
+ }),
176
+ };
177
+ const testOps = new AuthOperations(
178
+ coreWithSpy as any,
179
+ mockClient as any,
180
+ mockConfig as any,
181
+ );
182
+
183
+ const session = {
184
+ accessToken: validJwt,
185
+ refreshToken: 'test-refresh',
186
+ user: mockUser,
187
+ impersonator: undefined,
188
+ };
189
+
190
+ const result = await testOps.refreshSession(session);
191
+
192
+ expect(result.auth.accessToken).toBe('extracted-org-token');
193
+ });
194
+ });
195
+
196
+ describe('getAuthorizationUrl()', () => {
197
+ it('returns WorkOS authorization URL', async () => {
198
+ const result = await operations.getAuthorizationUrl();
199
+
200
+ expect(result).toContain('client_id=test-client-id');
201
+ expect(result).toContain('redirect_uri');
202
+ });
203
+
204
+ it('encodes returnPathname in state', async () => {
205
+ const result = await operations.getAuthorizationUrl({
206
+ returnPathname: '/dashboard',
207
+ });
208
+
209
+ expect(result).toContain('state=');
210
+ const stateMatch = result.match(/state=([^&]+)/);
211
+ expect(stateMatch).toBeTruthy();
212
+ const decoded = JSON.parse(atob(stateMatch![1]));
213
+ expect(decoded.returnPathname).toBe('/dashboard');
214
+ });
215
+
216
+ it('includes screenHint when provided', async () => {
217
+ const result = await operations.getAuthorizationUrl({
218
+ screenHint: 'sign-up',
219
+ });
220
+
221
+ expect(result).toContain('screen_hint=sign-up');
222
+ });
223
+ });
224
+
225
+ describe('getSignInUrl()', () => {
226
+ it('returns authorization URL with sign-in hint', async () => {
227
+ const result = await operations.getSignInUrl();
228
+
229
+ expect(result).toContain('screen_hint=sign-in');
230
+ });
231
+ });
232
+
233
+ describe('getSignUpUrl()', () => {
234
+ it('returns authorization URL with sign-up hint', async () => {
235
+ const result = await operations.getSignUpUrl();
236
+
237
+ expect(result).toContain('screen_hint=sign-up');
238
+ });
239
+ });
240
+ });
@@ -0,0 +1,192 @@
1
+ import type { WorkOS } from '@workos-inc/node';
2
+ import type { AuthKitCore } from '../core/AuthKitCore.js';
3
+ import type { ConfigurationProvider } from '../core/config/ConfigurationProvider.js';
4
+ import type {
5
+ AuthResult,
6
+ BaseTokenClaims,
7
+ GetAuthorizationUrlOptions,
8
+ Session,
9
+ } from '../core/session/types.js';
10
+
11
+ /**
12
+ * AuthOperations provides high-level authentication operations.
13
+ *
14
+ * This class orchestrates between AuthKitCore (pure logic) and WorkOS API.
15
+ * It doesn't know about requests, responses, or cookies - that's the framework's job.
16
+ *
17
+ * Responsibilities:
18
+ * - Sign out (generate logout URL + clear cookie header)
19
+ * - Switch organization (refresh with new org + return auth result)
20
+ * - Refresh session (refresh tokens + return auth result)
21
+ * - Get authorization URLs (for sign in/sign up flows)
22
+ */
23
+ export class AuthOperations {
24
+ constructor(
25
+ private core: AuthKitCore,
26
+ private client: WorkOS,
27
+ private config: ConfigurationProvider,
28
+ ) {}
29
+
30
+ /**
31
+ * Sign out operation.
32
+ *
33
+ * Returns the WorkOS logout URL and a cookie clear header string.
34
+ * The framework is responsible for applying the header and redirecting.
35
+ *
36
+ * @param sessionId - The session ID to terminate
37
+ * @param options - Optional return URL
38
+ * @returns Logout URL and clear cookie header
39
+ */
40
+ async signOut(
41
+ sessionId: string,
42
+ options?: { returnTo?: string },
43
+ ): Promise<{
44
+ logoutUrl: string;
45
+ clearCookieHeader: string;
46
+ }> {
47
+ // Generate WorkOS logout URL
48
+ const logoutUrl = this.client.userManagement.getLogoutUrl({
49
+ sessionId,
50
+ returnTo: options?.returnTo,
51
+ });
52
+
53
+ // Build cookie clear header
54
+ const cookieName = this.config.getValue('cookieName');
55
+ const clearCookieHeader = `${cookieName}=; Path=/; Max-Age=0; HttpOnly; Secure; SameSite=lax`;
56
+
57
+ return {
58
+ logoutUrl,
59
+ clearCookieHeader,
60
+ };
61
+ }
62
+
63
+ /**
64
+ * Switch to a different organization.
65
+ *
66
+ * This is a convenience wrapper around refreshSession() that enforces
67
+ * an organization ID must be provided.
68
+ *
69
+ * @param session - Current session
70
+ * @param organizationId - Organization ID to switch to (required)
71
+ * @returns Auth result and encrypted session data
72
+ */
73
+ async switchOrganization(
74
+ session: Session,
75
+ organizationId: string,
76
+ ): Promise<{
77
+ auth: AuthResult;
78
+ encryptedSession: string;
79
+ }> {
80
+ // Delegate to refreshSession with explicit organization
81
+ return this.refreshSession(session, organizationId);
82
+ }
83
+
84
+ /**
85
+ * Refresh session operation.
86
+ *
87
+ * Calls WorkOS to refresh tokens (optionally switching organizations),
88
+ * encrypts the new session, and returns the auth result.
89
+ *
90
+ * @param session - Current session with refresh token
91
+ * @param organizationId - Optional organization ID to switch to during refresh
92
+ * @returns Auth result and encrypted session data
93
+ */
94
+ async refreshSession(
95
+ session: Session,
96
+ organizationId?: string,
97
+ ): Promise<{
98
+ auth: AuthResult;
99
+ encryptedSession: string;
100
+ }> {
101
+ // Determine which organization to use
102
+ let orgId = organizationId;
103
+ if (!orgId) {
104
+ // Extract org from current token (decodeJwt works even on expired tokens)
105
+ try {
106
+ const claims = this.core.parseTokenClaims<BaseTokenClaims>(
107
+ session.accessToken,
108
+ );
109
+ orgId = claims.org_id;
110
+ } catch {
111
+ // Token too malformed to parse - refresh without org context
112
+ // WorkOS will use whatever org is embedded in the refresh token
113
+ }
114
+ }
115
+
116
+ const result = await this.core.refreshTokens(session.refreshToken, orgId);
117
+
118
+ const newSession: Session = {
119
+ accessToken: result.accessToken,
120
+ refreshToken: result.refreshToken,
121
+ user: result.user,
122
+ impersonator: result.impersonator,
123
+ };
124
+
125
+ const encryptedSession = await this.core.encryptSession(newSession);
126
+
127
+ const claims = this.core.parseTokenClaims(result.accessToken);
128
+
129
+ const auth: AuthResult = {
130
+ user: result.user,
131
+ sessionId: claims.sid,
132
+ impersonator: result.impersonator,
133
+ accessToken: result.accessToken,
134
+ refreshToken: result.refreshToken,
135
+ claims,
136
+ };
137
+
138
+ return {
139
+ auth,
140
+ encryptedSession,
141
+ };
142
+ }
143
+
144
+ /**
145
+ * Get authorization URL for WorkOS authentication.
146
+ *
147
+ * Builds the WorkOS authorization URL with proper state encoding.
148
+ *
149
+ * @param options - Authorization URL options (returnPathname, screenHint, etc.)
150
+ * @returns The authorization URL
151
+ */
152
+ async getAuthorizationUrl(
153
+ options: GetAuthorizationUrlOptions = {},
154
+ ): Promise<string> {
155
+ return this.client.userManagement.getAuthorizationUrl({
156
+ provider: 'authkit',
157
+ redirectUri: options.redirectUri ?? this.config.getValue('redirectUri'),
158
+ screenHint: options.screenHint,
159
+ organizationId: options.organizationId,
160
+ loginHint: options.loginHint,
161
+ prompt: options.prompt,
162
+ clientId: this.config.getValue('clientId'),
163
+ state: options.returnPathname
164
+ ? btoa(JSON.stringify({ returnPathname: options.returnPathname }))
165
+ : undefined,
166
+ });
167
+ }
168
+
169
+ /**
170
+ * Convenience method: Get sign-in URL.
171
+ */
172
+ async getSignInUrl(
173
+ options: Omit<GetAuthorizationUrlOptions, 'screenHint'> = {},
174
+ ): Promise<string> {
175
+ return this.getAuthorizationUrl({
176
+ ...options,
177
+ screenHint: 'sign-in',
178
+ });
179
+ }
180
+
181
+ /**
182
+ * Convenience method: Get sign-up URL.
183
+ */
184
+ async getSignUpUrl(
185
+ options: Omit<GetAuthorizationUrlOptions, 'screenHint'> = {},
186
+ ): Promise<string> {
187
+ return this.getAuthorizationUrl({
188
+ ...options,
189
+ screenHint: 'sign-up',
190
+ });
191
+ }
192
+ }
@@ -0,0 +1,241 @@
1
+ import { AuthService } from './AuthService.js';
2
+
3
+ const mockConfig = {
4
+ getValue: (key: string) => {
5
+ const values = {
6
+ clientId: 'test-client-id',
7
+ cookiePassword: 'test-password-that-is-32-chars-long!!',
8
+ };
9
+ return values[key as keyof typeof values];
10
+ },
11
+ getConfig: () => ({
12
+ clientId: 'test-client-id',
13
+ apiKey: 'test-api-key',
14
+ redirectUri: 'http://localhost:3000/callback',
15
+ cookiePassword: 'test-password-that-is-32-chars-long!!',
16
+ }),
17
+ };
18
+
19
+ const mockUser = {
20
+ id: 'user_123',
21
+ email: 'test@example.com',
22
+ object: 'user',
23
+ firstName: 'Test',
24
+ lastName: 'User',
25
+ emailVerified: true,
26
+ profilePictureUrl: null,
27
+ createdAt: '2023-01-01T00:00:00Z',
28
+ updatedAt: '2023-01-01T00:00:00Z',
29
+ lastSignInAt: '2023-01-01T00:00:00Z',
30
+ externalId: null,
31
+ metadata: {},
32
+ } as const;
33
+
34
+ const mockStorage = {
35
+ getSession: async () => 'encrypted-session-data',
36
+ saveSession: async () => ({ response: 'updated-response' }),
37
+ clearSession: async () => ({ response: 'cleared-response' }),
38
+ };
39
+
40
+ const mockClient = {
41
+ userManagement: {
42
+ getJwksUrl: () => 'https://api.workos.com/sso/jwks/test-client-id',
43
+ getAuthorizationUrl: ({ screenHint }: any) =>
44
+ `https://api.workos.com/sso/authorize?screen_hint=${screenHint || ''}`,
45
+ authenticateWithCode: async ({ code }: any) => ({
46
+ accessToken: `access-${code}`,
47
+ refreshToken: `refresh-${code}`,
48
+ user: mockUser,
49
+ impersonator: undefined,
50
+ }),
51
+ getLogoutUrl: ({ sessionId }: any) =>
52
+ `https://api.workos.com/sso/logout?session_id=${sessionId}`,
53
+ },
54
+ };
55
+
56
+ const mockEncryption = {
57
+ sealData: async () => 'encrypted-session-data',
58
+ unsealData: async () => ({
59
+ accessToken: 'test-access-token',
60
+ refreshToken: 'test-refresh-token',
61
+ user: mockUser,
62
+ impersonator: undefined,
63
+ }),
64
+ };
65
+
66
+ describe('AuthService', () => {
67
+ let service: AuthService<any, any>;
68
+
69
+ beforeEach(() => {
70
+ service = new AuthService(
71
+ mockConfig as any,
72
+ mockStorage as any,
73
+ () => mockClient as any,
74
+ () => mockEncryption as any,
75
+ );
76
+ });
77
+
78
+ describe('constructor', () => {
79
+ it('creates instance with required dependencies', () => {
80
+ expect(service).toBeInstanceOf(AuthService);
81
+ });
82
+ });
83
+
84
+ describe('withAuth()', () => {
85
+ it('returns null user when no session exists', async () => {
86
+ const emptyStorage = {
87
+ ...mockStorage,
88
+ getSession: async () => null,
89
+ };
90
+ const testService = new AuthService(
91
+ mockConfig as any,
92
+ emptyStorage as any,
93
+ () => mockClient as any,
94
+ () => mockEncryption as any,
95
+ );
96
+
97
+ const result = await testService.withAuth('request');
98
+
99
+ expect(result.auth.user).toBeNull();
100
+ expect(result.refreshedSessionData).toBeUndefined();
101
+ });
102
+
103
+ it('returns null user on decryption error', async () => {
104
+ const failingEncryption = {
105
+ sealData: async () => 'encrypted',
106
+ unsealData: async () => {
107
+ throw new Error('Decryption failed');
108
+ },
109
+ };
110
+ const testService = new AuthService(
111
+ mockConfig as any,
112
+ mockStorage as any,
113
+ () => mockClient as any,
114
+ () => failingEncryption as any,
115
+ );
116
+
117
+ const result = await testService.withAuth('request');
118
+
119
+ expect(result.auth.user).toBeNull();
120
+ });
121
+ });
122
+
123
+ describe('getSession()', () => {
124
+ it('returns decrypted session', async () => {
125
+ const result = await service.getSession('request');
126
+
127
+ expect(result).toBeDefined();
128
+ expect(result?.user).toEqual(mockUser);
129
+ });
130
+
131
+ it('returns null when no session exists', async () => {
132
+ const emptyStorage = {
133
+ ...mockStorage,
134
+ getSession: async () => null,
135
+ };
136
+ const testService = new AuthService(
137
+ mockConfig as any,
138
+ emptyStorage as any,
139
+ () => mockClient as any,
140
+ () => mockEncryption as any,
141
+ );
142
+
143
+ const result = await testService.getSession('request');
144
+
145
+ expect(result).toBeNull();
146
+ });
147
+ });
148
+
149
+ describe('saveSession()', () => {
150
+ it('delegates to storage', async () => {
151
+ const result = await service.saveSession('response', 'session-data');
152
+
153
+ expect(result.response).toBe('updated-response');
154
+ });
155
+ });
156
+
157
+ describe('clearSession()', () => {
158
+ it('delegates to storage', async () => {
159
+ const result = await service.clearSession('response');
160
+
161
+ expect(result.response).toBe('cleared-response');
162
+ });
163
+ });
164
+
165
+ describe('signOut()', () => {
166
+ it('delegates to operations', async () => {
167
+ const result = await service.signOut('session_123');
168
+
169
+ expect(result.logoutUrl).toContain('session_id=session_123');
170
+ expect(result.clearCookieHeader).toBeDefined();
171
+ });
172
+ });
173
+
174
+ describe('getAuthorizationUrl()', () => {
175
+ it('delegates to operations', async () => {
176
+ const result = await service.getAuthorizationUrl();
177
+
178
+ expect(result).toContain('authorize');
179
+ });
180
+ });
181
+
182
+ describe('getSignInUrl()', () => {
183
+ it('returns sign-in URL', async () => {
184
+ const result = await service.getSignInUrl();
185
+
186
+ expect(result).toContain('screen_hint=sign-in');
187
+ });
188
+ });
189
+
190
+ describe('getSignUpUrl()', () => {
191
+ it('returns sign-up URL', async () => {
192
+ const result = await service.getSignUpUrl();
193
+
194
+ expect(result).toContain('screen_hint=sign-up');
195
+ });
196
+ });
197
+
198
+ describe('getWorkOS()', () => {
199
+ it('returns WorkOS client', () => {
200
+ const result = service.getWorkOS();
201
+
202
+ expect(result).toBe(mockClient);
203
+ });
204
+ });
205
+
206
+ describe('handleCallback()', () => {
207
+ it('authenticates and creates session', async () => {
208
+ const result = await service.handleCallback(
209
+ 'request',
210
+ 'response',
211
+ { code: 'auth-code-123' },
212
+ );
213
+
214
+ expect(result.authResponse.accessToken).toBe('access-auth-code-123');
215
+ expect(result.returnPathname).toBe('/');
216
+ expect(result.response).toBe('updated-response');
217
+ });
218
+
219
+ it('decodes returnPathname from state', async () => {
220
+ const state = btoa(JSON.stringify({ returnPathname: '/dashboard' }));
221
+
222
+ const result = await service.handleCallback(
223
+ 'request',
224
+ 'response',
225
+ { code: 'auth-code-123', state },
226
+ );
227
+
228
+ expect(result.returnPathname).toBe('/dashboard');
229
+ });
230
+
231
+ it('uses default returnPathname for invalid state', async () => {
232
+ const result = await service.handleCallback(
233
+ 'request',
234
+ 'response',
235
+ { code: 'auth-code-123', state: 'invalid-state' },
236
+ );
237
+
238
+ expect(result.returnPathname).toBe('/');
239
+ });
240
+ });
241
+ });