@workos/authkit-session 0.2.0-beta.0 → 0.3.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 (46) hide show
  1. package/README.md +96 -781
  2. package/dist/core/AuthKitCore.d.ts +16 -10
  3. package/dist/core/AuthKitCore.d.ts.map +1 -1
  4. package/dist/core/AuthKitCore.js +32 -22
  5. package/dist/core/AuthKitCore.js.map +1 -1
  6. package/dist/core/errors.d.ts +6 -1
  7. package/dist/core/errors.d.ts.map +1 -1
  8. package/dist/core/errors.js +5 -1
  9. package/dist/core/errors.js.map +1 -1
  10. package/dist/core/session/CookieSessionStorage.d.ts +2 -3
  11. package/dist/core/session/CookieSessionStorage.d.ts.map +1 -1
  12. package/dist/core/session/CookieSessionStorage.js +14 -20
  13. package/dist/core/session/CookieSessionStorage.js.map +1 -1
  14. package/dist/core/session/types.d.ts +8 -0
  15. package/dist/core/session/types.d.ts.map +1 -1
  16. package/dist/index.d.ts +18 -16
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +29 -24
  19. package/dist/index.js.map +1 -1
  20. package/dist/operations/AuthOperations.d.ts +13 -14
  21. package/dist/operations/AuthOperations.d.ts.map +1 -1
  22. package/dist/operations/AuthOperations.js +37 -47
  23. package/dist/operations/AuthOperations.js.map +1 -1
  24. package/dist/service/AuthService.d.ts +22 -41
  25. package/dist/service/AuthService.d.ts.map +1 -1
  26. package/dist/service/AuthService.js +64 -65
  27. package/dist/service/AuthService.js.map +1 -1
  28. package/dist/service/factory.d.ts.map +1 -1
  29. package/dist/service/factory.js +24 -10
  30. package/dist/service/factory.js.map +1 -1
  31. package/package.json +2 -2
  32. package/src/core/AuthKitCore.spec.ts +12 -19
  33. package/src/core/AuthKitCore.ts +38 -23
  34. package/src/core/config/ConfigurationProvider.spec.ts +1 -0
  35. package/src/core/errors.spec.ts +47 -0
  36. package/src/core/errors.ts +10 -1
  37. package/src/core/session/CookieSessionStorage.spec.ts +51 -62
  38. package/src/core/session/CookieSessionStorage.ts +19 -22
  39. package/src/core/session/types.ts +8 -0
  40. package/src/index.ts +36 -25
  41. package/src/operations/AuthOperations.spec.ts +128 -69
  42. package/src/operations/AuthOperations.ts +53 -66
  43. package/src/service/AuthService.spec.ts +66 -40
  44. package/src/service/AuthService.ts +77 -82
  45. package/src/service/factory.spec.ts +20 -9
  46. package/src/service/factory.ts +33 -20
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@workos/authkit-session",
3
- "version": "0.2.0-beta.0",
4
- "description": "",
3
+ "version": "0.3.0",
4
+ "description": "Framework-agnostic authentication library for WorkOS with pluggable storage adapters",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
7
7
  "types": "./dist/index.d.ts",
@@ -1,17 +1,9 @@
1
1
  import { AuthKitCore } from './AuthKitCore.js';
2
- import {
3
- SessionEncryptionError,
4
- TokenRefreshError,
5
- } from './errors.js';
2
+ import { SessionEncryptionError, TokenRefreshError } from './errors.js';
6
3
 
7
4
  const mockConfig = {
8
- getValue: (key: string) => {
9
- const values = {
10
- cookiePassword: 'test-password-that-is-32-chars-long!!',
11
- clientId: 'test-client-id',
12
- };
13
- return values[key as keyof typeof values];
14
- },
5
+ cookiePassword: 'test-password-that-is-32-chars-long!!',
6
+ clientId: 'test-client-id',
15
7
  };
16
8
 
17
9
  const mockUser = {
@@ -25,6 +17,7 @@ const mockUser = {
25
17
  createdAt: '2023-01-01T00:00:00Z',
26
18
  updatedAt: '2023-01-01T00:00:00Z',
27
19
  lastSignInAt: '2023-01-01T00:00:00Z',
20
+ locale: 'en-US',
28
21
  externalId: null,
29
22
  metadata: {},
30
23
  } as const;
@@ -98,7 +91,8 @@ describe('AuthKitCore', () => {
98
91
 
99
92
  describe('isTokenExpiring()', () => {
100
93
  it('returns true when token expires soon', () => {
101
- const soonExpiry = Math.floor(Date.now() / 1000) + 30;
94
+ // Token expires in 5 seconds, which is within the default 10-second buffer
95
+ const soonExpiry = Math.floor(Date.now() / 1000) + 5;
102
96
  const expiringJwt = `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.${btoa(JSON.stringify({ exp: soonExpiry }))}.fake-signature`;
103
97
 
104
98
  const result = core.isTokenExpiring(expiringJwt);
@@ -207,9 +201,9 @@ describe('AuthKitCore', () => {
207
201
  failingEncryption as any,
208
202
  );
209
203
 
210
- await expect(
211
- failingCore.decryptSession('bad-data'),
212
- ).rejects.toThrow(SessionEncryptionError);
204
+ await expect(failingCore.decryptSession('bad-data')).rejects.toThrow(
205
+ SessionEncryptionError,
206
+ );
213
207
  });
214
208
  });
215
209
 
@@ -260,10 +254,9 @@ describe('AuthKitCore', () => {
260
254
  mockEncryption as any,
261
255
  );
262
256
 
263
- await expect(
264
- failingCore.refreshTokens('bad-token'),
265
- ).rejects.toThrow(TokenRefreshError);
257
+ await expect(failingCore.refreshTokens('bad-token')).rejects.toThrow(
258
+ TokenRefreshError,
259
+ );
266
260
  });
267
261
  });
268
-
269
262
  });
@@ -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) {
@@ -155,12 +152,14 @@ export class AuthKitCore {
155
152
  *
156
153
  * @param refreshToken - The refresh token
157
154
  * @param organizationId - Optional organization ID to switch to
155
+ * @param context - Optional context for error reporting (userId, sessionId)
158
156
  * @returns New access token, refresh token, user, and impersonator
159
157
  * @throws TokenRefreshError if refresh fails
160
158
  */
161
159
  async refreshTokens(
162
160
  refreshToken: string,
163
161
  organizationId?: string,
162
+ context?: { userId?: string; sessionId?: string },
164
163
  ): Promise<{
165
164
  accessToken: string;
166
165
  refreshToken: string;
@@ -182,24 +181,25 @@ export class AuthKitCore {
182
181
  impersonator: result.impersonator,
183
182
  };
184
183
  } catch (error) {
185
- throw new TokenRefreshError('Failed to refresh tokens', error);
184
+ throw new TokenRefreshError('Failed to refresh tokens', error, context);
186
185
  }
187
186
  }
188
187
 
189
188
  /**
190
189
  * Validate a session and refresh if needed.
191
190
  *
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?
191
+ * Only refreshes when token is invalid (expired) or force is true.
196
192
  *
197
193
  * @param session - The current session with access and refresh tokens
194
+ * @param options - Optional settings
195
+ * @param options.force - Force refresh even if token is valid (for org switching)
196
+ * @param options.organizationId - Organization ID to switch to during refresh
198
197
  * @returns Validation result with refreshed session if needed
199
198
  * @throws TokenRefreshError if refresh fails
200
199
  */
201
200
  async validateAndRefresh<TCustomClaims = CustomClaims>(
202
201
  session: Session,
202
+ options?: { force?: boolean; organizationId?: string },
203
203
  ): Promise<{
204
204
  valid: boolean;
205
205
  refreshed: boolean;
@@ -207,24 +207,39 @@ export class AuthKitCore {
207
207
  claims: BaseTokenClaims & TCustomClaims;
208
208
  }> {
209
209
  const { accessToken } = session;
210
+ const { force = false, organizationId: explicitOrgId } = options ?? {};
211
+
210
212
  const isValid = await this.verifyToken(accessToken);
211
- const isExpiring = this.isTokenExpiring(accessToken);
212
- if (isValid && !isExpiring) {
213
+
214
+ // Return early if token is valid and not forced
215
+ if (isValid && !force) {
213
216
  const claims = this.parseTokenClaims<TCustomClaims>(accessToken);
214
217
  return { valid: true, refreshed: false, session, claims };
215
218
  }
216
219
 
217
- let organizationId: string | undefined;
218
- if (isValid) {
220
+ // Determine organization ID: explicit > extracted from token
221
+ let organizationId = explicitOrgId;
222
+ if (!organizationId && isValid) {
219
223
  try {
220
224
  const oldClaims = this.parseTokenClaims(accessToken);
221
225
  organizationId = oldClaims.org_id;
222
- } catch {}
226
+ } catch {
227
+ // Token parsing failed - refresh without org context
228
+ }
229
+ }
230
+
231
+ // Extract session ID for error context (works on expired tokens too)
232
+ let sessionId: string | undefined;
233
+ try {
234
+ sessionId = this.parseTokenClaims(accessToken).sid;
235
+ } catch {
236
+ // Token parsing failed - continue without session context
223
237
  }
224
238
 
225
239
  const newSession = await this.refreshTokens(
226
240
  session.refreshToken,
227
241
  organizationId,
242
+ { userId: session.user?.id, sessionId },
228
243
  );
229
244
  const newClaims = this.parseTokenClaims<TCustomClaims>(
230
245
  newSession.accessToken,
@@ -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()', () => {
@@ -93,6 +93,53 @@ describe('TokenRefreshError', () => {
93
93
 
94
94
  expect(error.cause).toBe(originalError);
95
95
  });
96
+
97
+ it('creates error with userId and sessionId', () => {
98
+ const error = new TokenRefreshError('Refresh failed', undefined, {
99
+ userId: 'user_123',
100
+ sessionId: 'session_456',
101
+ });
102
+
103
+ expect(error.userId).toBe('user_123');
104
+ expect(error.sessionId).toBe('session_456');
105
+ });
106
+
107
+ it('creates error with cause and context', () => {
108
+ const originalError = new Error('Network error');
109
+ const error = new TokenRefreshError('Refresh failed', originalError, {
110
+ userId: 'user_123',
111
+ sessionId: 'session_456',
112
+ });
113
+
114
+ expect(error.cause).toBe(originalError);
115
+ expect(error.userId).toBe('user_123');
116
+ expect(error.sessionId).toBe('session_456');
117
+ });
118
+
119
+ it('creates error with partial context (userId only)', () => {
120
+ const error = new TokenRefreshError('Refresh failed', undefined, {
121
+ userId: 'user_123',
122
+ });
123
+
124
+ expect(error.userId).toBe('user_123');
125
+ expect(error.sessionId).toBeUndefined();
126
+ });
127
+
128
+ it('creates error with partial context (sessionId only)', () => {
129
+ const error = new TokenRefreshError('Refresh failed', undefined, {
130
+ sessionId: 'session_456',
131
+ });
132
+
133
+ expect(error.userId).toBeUndefined();
134
+ expect(error.sessionId).toBe('session_456');
135
+ });
136
+
137
+ it('has undefined properties when no context provided', () => {
138
+ const error = new TokenRefreshError('Refresh failed');
139
+
140
+ expect(error.userId).toBeUndefined();
141
+ expect(error.sessionId).toBeUndefined();
142
+ });
96
143
  });
97
144
 
98
145
  describe('error inheritance', () => {
@@ -24,8 +24,17 @@ export class TokenValidationError extends AuthKitError {
24
24
  }
25
25
 
26
26
  export class TokenRefreshError extends AuthKitError {
27
- constructor(message: string, cause?: unknown) {
27
+ readonly userId?: string;
28
+ readonly sessionId?: string;
29
+
30
+ constructor(
31
+ message: string,
32
+ cause?: unknown,
33
+ context?: { userId?: string; sessionId?: string },
34
+ ) {
28
35
  super(message, cause);
29
36
  this.name = 'TokenRefreshError';
37
+ this.userId = context?.userId;
38
+ this.sessionId = context?.sessionId;
30
39
  }
31
40
  }
@@ -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
  /**