@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,14 +1,9 @@
1
1
  import { AuthOperations } from './AuthOperations.js';
2
2
 
3
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
- },
4
+ clientId: 'test-client-id',
5
+ redirectUri: 'http://localhost:3000/callback',
6
+ cookieName: 'wos-session',
12
7
  };
13
8
 
14
9
  const mockUser = {
@@ -22,24 +17,29 @@ const mockUser = {
22
17
  createdAt: '2023-01-01T00:00:00Z',
23
18
  updatedAt: '2023-01-01T00:00:00Z',
24
19
  lastSignInAt: '2023-01-01T00:00:00Z',
20
+ locale: 'en-US',
25
21
  externalId: null,
26
22
  metadata: {},
27
23
  } as const;
28
24
 
29
25
  const mockCore = {
30
- refreshTokens: async () => ({
31
- accessToken: 'new-access-token',
32
- refreshToken: 'new-refresh-token',
33
- user: mockUser,
34
- impersonator: undefined,
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
+ },
35
41
  }),
36
42
  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
43
  };
44
44
 
45
45
  const mockClient = {
@@ -68,21 +68,19 @@ describe('AuthOperations', () => {
68
68
  });
69
69
  });
70
70
 
71
- describe('signOut()', () => {
72
- it('returns logout URL and clear cookie header', async () => {
73
- const result = await operations.signOut('session_123');
71
+ describe('getLogoutUrl()', () => {
72
+ it('returns logout URL with session ID', () => {
73
+ const result = operations.getLogoutUrl('session_123');
74
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');
75
+ expect(result).toContain('session_id=session_123');
78
76
  });
79
77
 
80
- it('includes returnTo in logout URL', async () => {
81
- const result = await operations.signOut('session_123', {
78
+ it('includes returnTo in logout URL', () => {
79
+ const result = operations.getLogoutUrl('session_123', {
82
80
  returnTo: 'http://localhost:3000',
83
81
  });
84
82
 
85
- expect(result.logoutUrl).toContain('return_to=');
83
+ expect(result).toContain('return_to=');
86
84
  });
87
85
  });
88
86
 
@@ -98,7 +96,9 @@ describe('AuthOperations', () => {
98
96
  const result = await operations.switchOrganization(session, 'org_456');
99
97
 
100
98
  expect(result.auth.user).toEqual(mockUser);
101
- expect(result.auth.accessToken).toBe('new-access-token');
99
+ if (result.auth.user) {
100
+ expect(result.auth.accessToken).toBe('new-access-token');
101
+ }
102
102
  expect(result.encryptedSession).toBe('encrypted-session-data');
103
103
  });
104
104
  });
@@ -113,29 +113,38 @@ describe('AuthOperations', () => {
113
113
  };
114
114
 
115
115
  const result = await operations.refreshSession(session);
116
+ const auth = result.auth as Extract<typeof result.auth, { user: object }>;
116
117
 
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');
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');
121
122
  expect(result.encryptedSession).toBe('encrypted-session-data');
122
123
  });
123
124
 
124
- it('includes organizationId when provided', async () => {
125
+ it('passes organizationId to validateAndRefresh when provided', async () => {
126
+ let capturedOptions: any;
125
127
  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
- }),
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
+ },
132
147
  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
148
  };
140
149
  const testOps = new AuthOperations(
141
150
  coreWithSpy as any,
@@ -150,29 +159,37 @@ describe('AuthOperations', () => {
150
159
  impersonator: undefined,
151
160
  };
152
161
 
153
- const result = await testOps.refreshSession(session, 'org_456');
162
+ await testOps.refreshSession(session, 'org_456');
154
163
 
155
- expect(result.auth.accessToken).toBe('org-token');
164
+ expect(capturedOptions).toEqual({
165
+ force: true,
166
+ organizationId: 'org_456',
167
+ });
156
168
  });
157
169
 
158
- it('extracts org from current token when not provided', async () => {
159
- const validJwt =
160
- 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyXzEyMyIsInNpZCI6InNlc3Npb25fMTIzIiwiZXhwIjoxNzM2Mzc2MDAwLCJvcmdfaWQiOiJvcmdfZnJvbV90b2tlbiJ9.fake-signature';
161
-
170
+ it('calls validateAndRefresh with force: true and no organizationId when not provided', async () => {
171
+ let capturedOptions: any;
162
172
  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
- }),
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
+ },
169
192
  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
193
  };
177
194
  const testOps = new AuthOperations(
178
195
  coreWithSpy as any,
@@ -181,15 +198,18 @@ describe('AuthOperations', () => {
181
198
  );
182
199
 
183
200
  const session = {
184
- accessToken: validJwt,
201
+ accessToken: 'test-token',
185
202
  refreshToken: 'test-refresh',
186
203
  user: mockUser,
187
204
  impersonator: undefined,
188
205
  };
189
206
 
190
- const result = await testOps.refreshSession(session);
207
+ await testOps.refreshSession(session);
191
208
 
192
- expect(result.auth.accessToken).toBe('extracted-org-token');
209
+ expect(capturedOptions).toEqual({
210
+ force: true,
211
+ organizationId: undefined,
212
+ });
193
213
  });
194
214
  });
195
215
 
@@ -201,7 +221,7 @@ describe('AuthOperations', () => {
201
221
  expect(result).toContain('redirect_uri');
202
222
  });
203
223
 
204
- it('encodes returnPathname in state', async () => {
224
+ it('encodes returnPathname in URL-safe base64 state', async () => {
205
225
  const result = await operations.getAuthorizationUrl({
206
226
  returnPathname: '/dashboard',
207
227
  });
@@ -209,10 +229,49 @@ describe('AuthOperations', () => {
209
229
  expect(result).toContain('state=');
210
230
  const stateMatch = result.match(/state=([^&]+)/);
211
231
  expect(stateMatch).toBeTruthy();
212
- const decoded = JSON.parse(atob(stateMatch![1]));
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));
213
237
  expect(decoded.returnPathname).toBe('/dashboard');
214
238
  });
215
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
+
216
275
  it('includes screenHint when provided', async () => {
217
276
  const result = await operations.getAuthorizationUrl({
218
277
  screenHint: 'sign-up',
@@ -1,9 +1,8 @@
1
1
  import type { WorkOS } from '@workos-inc/node';
2
2
  import type { AuthKitCore } from '../core/AuthKitCore.js';
3
- import type { ConfigurationProvider } from '../core/config/ConfigurationProvider.js';
3
+ import type { AuthKitConfig } from '../core/config/types.js';
4
4
  import type {
5
5
  AuthResult,
6
- BaseTokenClaims,
7
6
  GetAuthorizationUrlOptions,
8
7
  Session,
9
8
  } from '../core/session/types.js';
@@ -21,43 +20,31 @@ import type {
21
20
  * - Get authorization URLs (for sign in/sign up flows)
22
21
  */
23
22
  export class AuthOperations {
24
- constructor(
25
- private core: AuthKitCore,
26
- private client: WorkOS,
27
- private config: ConfigurationProvider,
28
- ) {}
23
+ private core: AuthKitCore;
24
+ private client: WorkOS;
25
+ private config: AuthKitConfig;
26
+
27
+ constructor(core: AuthKitCore, client: WorkOS, config: AuthKitConfig) {
28
+ this.core = core;
29
+ this.client = client;
30
+ this.config = config;
31
+ }
29
32
 
30
33
  /**
31
- * Sign out operation.
34
+ * Get the WorkOS logout URL.
32
35
  *
33
- * Returns the WorkOS logout URL and a cookie clear header string.
34
- * The framework is responsible for applying the header and redirecting.
36
+ * This only handles the WorkOS API part. Session clearing is handled
37
+ * by the storage layer in AuthService.
35
38
  *
36
39
  * @param sessionId - The session ID to terminate
37
40
  * @param options - Optional return URL
38
- * @returns Logout URL and clear cookie header
41
+ * @returns Logout URL
39
42
  */
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({
43
+ getLogoutUrl(sessionId: string, options?: { returnTo?: string }): string {
44
+ return this.client.userManagement.getLogoutUrl({
49
45
  sessionId,
50
46
  returnTo: options?.returnTo,
51
47
  });
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
48
  }
62
49
 
63
50
  /**
@@ -84,7 +71,7 @@ export class AuthOperations {
84
71
  /**
85
72
  * Refresh session operation.
86
73
  *
87
- * Calls WorkOS to refresh tokens (optionally switching organizations),
74
+ * Forces a token refresh (for org switching or manual refresh),
88
75
  * encrypts the new session, and returns the auth result.
89
76
  *
90
77
  * @param session - Current session with refresh token
@@ -98,41 +85,27 @@ export class AuthOperations {
98
85
  auth: AuthResult;
99
86
  encryptedSession: string;
100
87
  }> {
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
- };
88
+ // Force refresh via core, optionally switching organizations
89
+ const { session: newSession, claims } = await this.core.validateAndRefresh(
90
+ session,
91
+ { force: true, organizationId },
92
+ );
124
93
 
125
94
  const encryptedSession = await this.core.encryptSession(newSession);
126
95
 
127
- const claims = this.core.parseTokenClaims(result.accessToken);
128
-
129
96
  const auth: AuthResult = {
130
- user: result.user,
97
+ user: newSession.user,
131
98
  sessionId: claims.sid,
132
- impersonator: result.impersonator,
133
- accessToken: result.accessToken,
134
- refreshToken: result.refreshToken,
99
+ impersonator: newSession.impersonator,
100
+ accessToken: newSession.accessToken,
101
+ refreshToken: newSession.refreshToken,
135
102
  claims,
103
+ organizationId: claims.org_id,
104
+ role: claims.role,
105
+ roles: claims.roles,
106
+ permissions: claims.permissions,
107
+ entitlements: claims.entitlements,
108
+ featureFlags: claims.feature_flags,
136
109
  };
137
110
 
138
111
  return {
@@ -144,25 +117,39 @@ export class AuthOperations {
144
117
  /**
145
118
  * Get authorization URL for WorkOS authentication.
146
119
  *
147
- * Builds the WorkOS authorization URL with proper state encoding.
120
+ * State encoding format: `{internal}.{userState}` where internal is URL-safe
121
+ * base64 encoded JSON containing returnPathname. This allows customers to
122
+ * pass their own state through the OAuth flow.
148
123
  *
149
- * @param options - Authorization URL options (returnPathname, screenHint, etc.)
124
+ * @param options - Authorization URL options (returnPathname, screenHint, state, etc.)
150
125
  * @returns The authorization URL
151
126
  */
152
127
  async getAuthorizationUrl(
153
128
  options: GetAuthorizationUrlOptions = {},
154
129
  ): Promise<string> {
130
+ // Build the combined state parameter (matches authkit-nextjs format)
131
+ const internalState = options.returnPathname
132
+ ? btoa(JSON.stringify({ returnPathname: options.returnPathname }))
133
+ .replace(/\+/g, '-')
134
+ .replace(/\//g, '_')
135
+ : null;
136
+
137
+ // If both internal and custom state, combine as internal.custom
138
+ // Otherwise use whichever is provided
139
+ const state =
140
+ internalState && options.state
141
+ ? `${internalState}.${options.state}`
142
+ : internalState || options.state || undefined;
143
+
155
144
  return this.client.userManagement.getAuthorizationUrl({
156
145
  provider: 'authkit',
157
- redirectUri: options.redirectUri ?? this.config.getValue('redirectUri'),
146
+ redirectUri: options.redirectUri ?? this.config.redirectUri,
158
147
  screenHint: options.screenHint,
159
148
  organizationId: options.organizationId,
160
149
  loginHint: options.loginHint,
161
150
  prompt: options.prompt,
162
- clientId: this.config.getValue('clientId'),
163
- state: options.returnPathname
164
- ? btoa(JSON.stringify({ returnPathname: options.returnPathname }))
165
- : undefined,
151
+ clientId: this.config.clientId,
152
+ state,
166
153
  });
167
154
  }
168
155
 
@@ -1,19 +1,11 @@
1
1
  import { AuthService } from './AuthService.js';
2
2
 
3
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
- }),
4
+ clientId: 'test-client-id',
5
+ apiKey: 'test-api-key',
6
+ redirectUri: 'http://localhost:3000/callback',
7
+ cookiePassword: 'test-password-that-is-32-chars-long!!',
8
+ cookieName: 'wos-session',
17
9
  };
18
10
 
19
11
  const mockUser = {
@@ -34,7 +26,10 @@ const mockUser = {
34
26
  const mockStorage = {
35
27
  getSession: async () => 'encrypted-session-data',
36
28
  saveSession: async () => ({ response: 'updated-response' }),
37
- clearSession: async () => ({ response: 'cleared-response' }),
29
+ clearSession: async () => ({
30
+ response: 'cleared-response',
31
+ headers: { 'Set-Cookie': 'wos-session=; Path=/; Max-Age=0' },
32
+ }),
38
33
  };
39
34
 
40
35
  const mockClient = {
@@ -70,8 +65,8 @@ describe('AuthService', () => {
70
65
  service = new AuthService(
71
66
  mockConfig as any,
72
67
  mockStorage as any,
73
- () => mockClient as any,
74
- () => mockEncryption as any,
68
+ mockClient as any,
69
+ mockEncryption as any,
75
70
  );
76
71
  });
77
72
 
@@ -90,8 +85,8 @@ describe('AuthService', () => {
90
85
  const testService = new AuthService(
91
86
  mockConfig as any,
92
87
  emptyStorage as any,
93
- () => mockClient as any,
94
- () => mockEncryption as any,
88
+ mockClient as any,
89
+ mockEncryption as any,
95
90
  );
96
91
 
97
92
  const result = await testService.withAuth('request');
@@ -110,8 +105,8 @@ describe('AuthService', () => {
110
105
  const testService = new AuthService(
111
106
  mockConfig as any,
112
107
  mockStorage as any,
113
- () => mockClient as any,
114
- () => failingEncryption as any,
108
+ mockClient as any,
109
+ failingEncryption as any,
115
110
  );
116
111
 
117
112
  const result = await testService.withAuth('request');
@@ -136,8 +131,8 @@ describe('AuthService', () => {
136
131
  const testService = new AuthService(
137
132
  mockConfig as any,
138
133
  emptyStorage as any,
139
- () => mockClient as any,
140
- () => mockEncryption as any,
134
+ mockClient as any,
135
+ mockEncryption as any,
141
136
  );
142
137
 
143
138
  const result = await testService.getSession('request');
@@ -163,11 +158,12 @@ describe('AuthService', () => {
163
158
  });
164
159
 
165
160
  describe('signOut()', () => {
166
- it('delegates to operations', async () => {
161
+ it('returns logout URL and headers from storage', async () => {
167
162
  const result = await service.signOut('session_123');
168
163
 
169
164
  expect(result.logoutUrl).toContain('session_id=session_123');
170
- expect(result.clearCookieHeader).toBeDefined();
165
+ expect(result.headers).toBeDefined();
166
+ expect(result.headers?.['Set-Cookie']).toContain('wos-session=');
171
167
  });
172
168
  });
173
169
 
@@ -205,11 +201,9 @@ describe('AuthService', () => {
205
201
 
206
202
  describe('handleCallback()', () => {
207
203
  it('authenticates and creates session', async () => {
208
- const result = await service.handleCallback(
209
- 'request',
210
- 'response',
211
- { code: 'auth-code-123' },
212
- );
204
+ const result = await service.handleCallback('request', 'response', {
205
+ code: 'auth-code-123',
206
+ });
213
207
 
214
208
  expect(result.authResponse.accessToken).toBe('access-auth-code-123');
215
209
  expect(result.returnPathname).toBe('/');
@@ -219,23 +213,55 @@ describe('AuthService', () => {
219
213
  it('decodes returnPathname from state', async () => {
220
214
  const state = btoa(JSON.stringify({ returnPathname: '/dashboard' }));
221
215
 
222
- const result = await service.handleCallback(
223
- 'request',
224
- 'response',
225
- { code: 'auth-code-123', state },
226
- );
216
+ const result = await service.handleCallback('request', 'response', {
217
+ code: 'auth-code-123',
218
+ state,
219
+ });
227
220
 
228
221
  expect(result.returnPathname).toBe('/dashboard');
229
222
  });
230
223
 
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
- );
224
+ it('treats invalid state as custom state', async () => {
225
+ const result = await service.handleCallback('request', 'response', {
226
+ code: 'auth-code-123',
227
+ state: 'invalid-state',
228
+ });
237
229
 
238
230
  expect(result.returnPathname).toBe('/');
231
+ expect(result.state).toBe('invalid-state');
232
+ });
233
+
234
+ it('parses new format with internal.userState', async () => {
235
+ // Create URL-safe base64 internal state
236
+ const internal = btoa(JSON.stringify({ returnPathname: '/profile' }))
237
+ .replace(/\+/g, '-')
238
+ .replace(/\//g, '_')
239
+ .replace(/=+$/, '');
240
+ const state = `${internal}.my-custom-state`;
241
+
242
+ const result = await service.handleCallback('request', 'response', {
243
+ code: 'auth-code-123',
244
+ state,
245
+ });
246
+
247
+ expect(result.returnPathname).toBe('/profile');
248
+ expect(result.state).toBe('my-custom-state');
249
+ });
250
+
251
+ it('handles user state with dots', async () => {
252
+ const internal = btoa(JSON.stringify({ returnPathname: '/dashboard' }))
253
+ .replace(/\+/g, '-')
254
+ .replace(/\//g, '_')
255
+ .replace(/=+$/, '');
256
+ const state = `${internal}.user.state.with.dots`;
257
+
258
+ const result = await service.handleCallback('request', 'response', {
259
+ code: 'auth-code-123',
260
+ state,
261
+ });
262
+
263
+ expect(result.returnPathname).toBe('/dashboard');
264
+ expect(result.state).toBe('user.state.with.dots');
239
265
  });
240
266
  });
241
267
  });