@workos/authkit-session 0.1.2 → 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.
- package/README.md +507 -232
- package/dist/core/AuthKitCore.d.ts +107 -0
- package/dist/core/AuthKitCore.d.ts.map +1 -0
- package/dist/core/AuthKitCore.js +189 -0
- package/dist/core/AuthKitCore.js.map +1 -0
- package/dist/core/session/CookieSessionStorage.d.ts.map +1 -1
- package/dist/core/session/CookieSessionStorage.js +22 -3
- package/dist/core/session/CookieSessionStorage.js.map +1 -1
- package/dist/core/session/types.d.ts +27 -7
- package/dist/core/session/types.d.ts.map +1 -1
- package/dist/index.d.ts +27 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +48 -4
- package/dist/index.js.map +1 -1
- package/dist/operations/AuthOperations.d.ts +84 -0
- package/dist/operations/AuthOperations.d.ts.map +1 -0
- package/dist/operations/AuthOperations.js +147 -0
- package/dist/operations/AuthOperations.js.map +1 -0
- package/dist/service/AuthService.d.ts +156 -0
- package/dist/service/AuthService.d.ts.map +1 -0
- package/dist/service/AuthService.js +225 -0
- package/dist/service/AuthService.js.map +1 -0
- package/dist/service/factory.d.ts +37 -0
- package/dist/service/factory.d.ts.map +1 -0
- package/dist/service/factory.js +46 -0
- package/dist/service/factory.js.map +1 -0
- package/package.json +6 -6
- package/src/core/AuthKitCore.spec.ts +269 -0
- package/src/core/AuthKitCore.ts +239 -0
- package/src/core/session/CookieSessionStorage.spec.ts +17 -0
- package/src/core/session/CookieSessionStorage.ts +22 -2
- package/src/core/session/types.ts +30 -8
- package/src/index.ts +55 -4
- package/src/operations/AuthOperations.spec.ts +240 -0
- package/src/operations/AuthOperations.ts +192 -0
- package/src/service/AuthService.spec.ts +241 -0
- package/src/service/AuthService.ts +293 -0
- package/src/service/factory.spec.ts +109 -0
- package/src/service/factory.ts +69 -0
- package/dist/core/createAuthKitFactory.d.ts +0 -64
- package/dist/core/createAuthKitFactory.d.ts.map +0 -1
- package/dist/core/createAuthKitFactory.js +0 -95
- package/dist/core/createAuthKitFactory.js.map +0 -1
- package/dist/core/session/SessionManager.d.ts +0 -51
- package/dist/core/session/SessionManager.d.ts.map +0 -1
- package/dist/core/session/SessionManager.js +0 -238
- package/dist/core/session/SessionManager.js.map +0 -1
- package/src/core/createAuthKitFactory.spec.ts +0 -161
- package/src/core/createAuthKitFactory.ts +0 -195
- package/src/core/session/SessionManager.spec.ts +0 -357
- package/src/core/session/SessionManager.ts +0 -357
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
import { AuthKitCore } from './AuthKitCore.js';
|
|
2
|
+
import {
|
|
3
|
+
SessionEncryptionError,
|
|
4
|
+
TokenRefreshError,
|
|
5
|
+
} from './errors.js';
|
|
6
|
+
|
|
7
|
+
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
|
+
},
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
const mockUser = {
|
|
18
|
+
id: 'user_123',
|
|
19
|
+
email: 'test@example.com',
|
|
20
|
+
object: 'user',
|
|
21
|
+
firstName: 'Test',
|
|
22
|
+
lastName: 'User',
|
|
23
|
+
emailVerified: true,
|
|
24
|
+
profilePictureUrl: null,
|
|
25
|
+
createdAt: '2023-01-01T00:00:00Z',
|
|
26
|
+
updatedAt: '2023-01-01T00:00:00Z',
|
|
27
|
+
lastSignInAt: '2023-01-01T00:00:00Z',
|
|
28
|
+
externalId: null,
|
|
29
|
+
metadata: {},
|
|
30
|
+
} as const;
|
|
31
|
+
|
|
32
|
+
const mockClient = {
|
|
33
|
+
userManagement: {
|
|
34
|
+
getJwksUrl: () => 'https://api.workos.com/sso/jwks/test-client-id',
|
|
35
|
+
authenticateWithRefreshToken: async () => ({
|
|
36
|
+
accessToken: 'new-access-token',
|
|
37
|
+
refreshToken: 'new-refresh-token',
|
|
38
|
+
user: mockUser,
|
|
39
|
+
impersonator: undefined,
|
|
40
|
+
}),
|
|
41
|
+
},
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
const mockEncryption = {
|
|
45
|
+
sealData: async () => 'encrypted-session-data',
|
|
46
|
+
unsealData: async () => ({
|
|
47
|
+
accessToken: 'test-access-token',
|
|
48
|
+
refreshToken: 'test-refresh-token',
|
|
49
|
+
user: mockUser,
|
|
50
|
+
impersonator: undefined,
|
|
51
|
+
}),
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
describe('AuthKitCore', () => {
|
|
55
|
+
let core: AuthKitCore;
|
|
56
|
+
|
|
57
|
+
beforeEach(() => {
|
|
58
|
+
core = new AuthKitCore(
|
|
59
|
+
mockConfig as any,
|
|
60
|
+
mockClient as any,
|
|
61
|
+
mockEncryption as any,
|
|
62
|
+
);
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
describe('constructor', () => {
|
|
66
|
+
it('creates instance with required dependencies', () => {
|
|
67
|
+
expect(core).toBeInstanceOf(AuthKitCore);
|
|
68
|
+
});
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
describe('parseTokenClaims()', () => {
|
|
72
|
+
it('parses valid JWT payload', () => {
|
|
73
|
+
const validJwt =
|
|
74
|
+
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyXzEyMyIsInNpZCI6InNlc3Npb25fMTIzIiwiZXhwIjoxNzM2Mzc2MDAwfQ.fake-signature';
|
|
75
|
+
|
|
76
|
+
const result = core.parseTokenClaims(validJwt);
|
|
77
|
+
|
|
78
|
+
expect(result.sub).toBe('user_123');
|
|
79
|
+
expect(result.sid).toBe('session_123');
|
|
80
|
+
expect(result.exp).toBe(1736376000);
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
it('throws error for invalid JWT', () => {
|
|
84
|
+
expect(() => core.parseTokenClaims('invalid-jwt')).toThrow(
|
|
85
|
+
'Invalid token',
|
|
86
|
+
);
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
it('supports custom claims', () => {
|
|
90
|
+
const customJwt =
|
|
91
|
+
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyXzEyMyIsImN1c3RvbUZpZWxkIjoiY3VzdG9tLXZhbHVlIn0.fake-signature';
|
|
92
|
+
|
|
93
|
+
const result = core.parseTokenClaims<{ customField: string }>(customJwt);
|
|
94
|
+
|
|
95
|
+
expect(result.customField).toBe('custom-value');
|
|
96
|
+
});
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
describe('isTokenExpiring()', () => {
|
|
100
|
+
it('returns true when token expires soon', () => {
|
|
101
|
+
const soonExpiry = Math.floor(Date.now() / 1000) + 30;
|
|
102
|
+
const expiringJwt = `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.${btoa(JSON.stringify({ exp: soonExpiry }))}.fake-signature`;
|
|
103
|
+
|
|
104
|
+
const result = core.isTokenExpiring(expiringJwt);
|
|
105
|
+
|
|
106
|
+
expect(result).toBe(true);
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
it('returns false when token expires later', () => {
|
|
110
|
+
const laterExpiry = Math.floor(Date.now() / 1000) + 3600;
|
|
111
|
+
const validJwt = `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.${btoa(JSON.stringify({ exp: laterExpiry }))}.fake-signature`;
|
|
112
|
+
|
|
113
|
+
const result = core.isTokenExpiring(validJwt);
|
|
114
|
+
|
|
115
|
+
expect(result).toBe(false);
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
it('uses custom buffer time', () => {
|
|
119
|
+
const expiry = Math.floor(Date.now() / 1000) + 150;
|
|
120
|
+
const jwt = `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.${btoa(JSON.stringify({ exp: expiry }))}.fake-signature`;
|
|
121
|
+
|
|
122
|
+
const result = core.isTokenExpiring(jwt, 180);
|
|
123
|
+
|
|
124
|
+
expect(result).toBe(true);
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
it('returns false when token has no expiry', () => {
|
|
128
|
+
const noExpiryJwt =
|
|
129
|
+
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyXzEyMyJ9.fake-signature';
|
|
130
|
+
|
|
131
|
+
const result = core.isTokenExpiring(noExpiryJwt);
|
|
132
|
+
|
|
133
|
+
expect(result).toBe(false);
|
|
134
|
+
});
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
describe('verifyToken()', () => {
|
|
138
|
+
it('returns false for invalid tokens', async () => {
|
|
139
|
+
const result = await core.verifyToken('invalid-token');
|
|
140
|
+
|
|
141
|
+
expect(result).toBe(false);
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
it('returns false for malformed tokens', async () => {
|
|
145
|
+
const result = await core.verifyToken('not.a.jwt');
|
|
146
|
+
|
|
147
|
+
expect(result).toBe(false);
|
|
148
|
+
});
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
describe('encryptSession()', () => {
|
|
152
|
+
it('encrypts session data', async () => {
|
|
153
|
+
const session = {
|
|
154
|
+
accessToken: 'test-token',
|
|
155
|
+
refreshToken: 'test-refresh',
|
|
156
|
+
user: mockUser,
|
|
157
|
+
impersonator: undefined,
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
const result = await core.encryptSession(session);
|
|
161
|
+
|
|
162
|
+
expect(result).toBe('encrypted-session-data');
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
it('throws SessionEncryptionError on failure', async () => {
|
|
166
|
+
const failingEncryption = {
|
|
167
|
+
sealData: async () => {
|
|
168
|
+
throw new Error('Encryption failed');
|
|
169
|
+
},
|
|
170
|
+
unsealData: async () => ({}),
|
|
171
|
+
};
|
|
172
|
+
const failingCore = new AuthKitCore(
|
|
173
|
+
mockConfig as any,
|
|
174
|
+
mockClient as any,
|
|
175
|
+
failingEncryption as any,
|
|
176
|
+
);
|
|
177
|
+
|
|
178
|
+
await expect(
|
|
179
|
+
failingCore.encryptSession({
|
|
180
|
+
accessToken: 'test',
|
|
181
|
+
refreshToken: 'test',
|
|
182
|
+
user: mockUser,
|
|
183
|
+
impersonator: undefined,
|
|
184
|
+
}),
|
|
185
|
+
).rejects.toThrow(SessionEncryptionError);
|
|
186
|
+
});
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
describe('decryptSession()', () => {
|
|
190
|
+
it('decrypts session data', async () => {
|
|
191
|
+
const result = await core.decryptSession('encrypted-data');
|
|
192
|
+
|
|
193
|
+
expect(result.accessToken).toBe('test-access-token');
|
|
194
|
+
expect(result.user).toEqual(mockUser);
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
it('throws SessionEncryptionError on failure', async () => {
|
|
198
|
+
const failingEncryption = {
|
|
199
|
+
sealData: async () => 'encrypted',
|
|
200
|
+
unsealData: async () => {
|
|
201
|
+
throw new Error('Decryption failed');
|
|
202
|
+
},
|
|
203
|
+
};
|
|
204
|
+
const failingCore = new AuthKitCore(
|
|
205
|
+
mockConfig as any,
|
|
206
|
+
mockClient as any,
|
|
207
|
+
failingEncryption as any,
|
|
208
|
+
);
|
|
209
|
+
|
|
210
|
+
await expect(
|
|
211
|
+
failingCore.decryptSession('bad-data'),
|
|
212
|
+
).rejects.toThrow(SessionEncryptionError);
|
|
213
|
+
});
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
describe('refreshTokens()', () => {
|
|
217
|
+
it('refreshes tokens via WorkOS', async () => {
|
|
218
|
+
const result = await core.refreshTokens('refresh-token');
|
|
219
|
+
|
|
220
|
+
expect(result.accessToken).toBe('new-access-token');
|
|
221
|
+
expect(result.refreshToken).toBe('new-refresh-token');
|
|
222
|
+
expect(result.user).toEqual(mockUser);
|
|
223
|
+
});
|
|
224
|
+
|
|
225
|
+
it('includes organizationId when provided', async () => {
|
|
226
|
+
const clientWithSpy = {
|
|
227
|
+
userManagement: {
|
|
228
|
+
getJwksUrl: () => 'https://api.workos.com/sso/jwks/test-client-id',
|
|
229
|
+
authenticateWithRefreshToken: async ({ organizationId }: any) => ({
|
|
230
|
+
accessToken: organizationId ? 'org-token' : 'regular-token',
|
|
231
|
+
refreshToken: 'new-refresh-token',
|
|
232
|
+
user: mockUser,
|
|
233
|
+
impersonator: undefined,
|
|
234
|
+
}),
|
|
235
|
+
},
|
|
236
|
+
};
|
|
237
|
+
const testCore = new AuthKitCore(
|
|
238
|
+
mockConfig as any,
|
|
239
|
+
clientWithSpy as any,
|
|
240
|
+
mockEncryption as any,
|
|
241
|
+
);
|
|
242
|
+
|
|
243
|
+
const result = await testCore.refreshTokens('refresh-token', 'org_123');
|
|
244
|
+
|
|
245
|
+
expect(result.accessToken).toBe('org-token');
|
|
246
|
+
});
|
|
247
|
+
|
|
248
|
+
it('throws TokenRefreshError on failure', async () => {
|
|
249
|
+
const failingClient = {
|
|
250
|
+
userManagement: {
|
|
251
|
+
getJwksUrl: () => 'https://api.workos.com/sso/jwks/test-client-id',
|
|
252
|
+
authenticateWithRefreshToken: async () => {
|
|
253
|
+
throw new Error('Refresh failed');
|
|
254
|
+
},
|
|
255
|
+
},
|
|
256
|
+
};
|
|
257
|
+
const failingCore = new AuthKitCore(
|
|
258
|
+
mockConfig as any,
|
|
259
|
+
failingClient as any,
|
|
260
|
+
mockEncryption as any,
|
|
261
|
+
);
|
|
262
|
+
|
|
263
|
+
await expect(
|
|
264
|
+
failingCore.refreshTokens('bad-token'),
|
|
265
|
+
).rejects.toThrow(TokenRefreshError);
|
|
266
|
+
});
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
});
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
import type { Impersonator, User, WorkOS } from '@workos-inc/node';
|
|
2
|
+
import { createRemoteJWKSet, decodeJwt, jwtVerify } from 'jose';
|
|
3
|
+
import { once } from '../utils.js';
|
|
4
|
+
import type { ConfigurationProvider } from './config/ConfigurationProvider.js';
|
|
5
|
+
import { SessionEncryptionError, TokenRefreshError } from './errors.js';
|
|
6
|
+
import type {
|
|
7
|
+
BaseTokenClaims,
|
|
8
|
+
CustomClaims,
|
|
9
|
+
Session,
|
|
10
|
+
SessionEncryption,
|
|
11
|
+
} from './session/types.js';
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* AuthKitCore provides pure business logic for authentication operations.
|
|
15
|
+
*
|
|
16
|
+
* This class contains no framework-specific code - all methods are pure functions
|
|
17
|
+
* that take data in and return data out. No TRequest/TResponse generics here.
|
|
18
|
+
*
|
|
19
|
+
* Responsibilities:
|
|
20
|
+
* - Token validation (JWT verification against JWKS)
|
|
21
|
+
* - Token expiry detection
|
|
22
|
+
* - Token claims parsing
|
|
23
|
+
* - Session encryption/decryption
|
|
24
|
+
* - Token refresh (calling WorkOS API)
|
|
25
|
+
* - Session validation orchestration
|
|
26
|
+
*/
|
|
27
|
+
export class AuthKitCore {
|
|
28
|
+
private config: ConfigurationProvider;
|
|
29
|
+
private client: WorkOS;
|
|
30
|
+
private encryption: SessionEncryption;
|
|
31
|
+
private clientId: string;
|
|
32
|
+
|
|
33
|
+
constructor(
|
|
34
|
+
config: ConfigurationProvider,
|
|
35
|
+
client: WorkOS,
|
|
36
|
+
encryption: SessionEncryption,
|
|
37
|
+
) {
|
|
38
|
+
this.config = config;
|
|
39
|
+
this.client = client;
|
|
40
|
+
this.encryption = encryption;
|
|
41
|
+
this.clientId = config.getValue('clientId');
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* JWKS public key fetcher - cached for performance
|
|
46
|
+
*/
|
|
47
|
+
private readonly getPublicKey = once(() =>
|
|
48
|
+
createRemoteJWKSet(
|
|
49
|
+
new URL(this.client.userManagement.getJwksUrl(this.clientId)),
|
|
50
|
+
),
|
|
51
|
+
);
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Verify a JWT access token against WorkOS JWKS.
|
|
55
|
+
*
|
|
56
|
+
* @param token - The JWT access token to verify
|
|
57
|
+
* @returns true if valid, false otherwise
|
|
58
|
+
*/
|
|
59
|
+
async verifyToken(token: string): Promise<boolean> {
|
|
60
|
+
try {
|
|
61
|
+
await jwtVerify(token, this.getPublicKey());
|
|
62
|
+
return true;
|
|
63
|
+
} catch {
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Check if a token is expiring soon.
|
|
70
|
+
*
|
|
71
|
+
* @param token - The JWT access token
|
|
72
|
+
* @param bufferSeconds - How many seconds before expiry to consider "expiring" (default: 60)
|
|
73
|
+
* @returns true if token expires within buffer period
|
|
74
|
+
*/
|
|
75
|
+
isTokenExpiring(token: string, buffer: number = 60): boolean {
|
|
76
|
+
const expiryTime = this.getTokenExpiryTime(token);
|
|
77
|
+
if (!expiryTime) {
|
|
78
|
+
return false;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const currentTime = Math.floor(Date.now() / 1000);
|
|
82
|
+
return expiryTime - currentTime <= buffer;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Get the expiry time from a token's claims.
|
|
87
|
+
*
|
|
88
|
+
* @param token - The JWT access token
|
|
89
|
+
* @returns Unix timestamp of expiry, or null if not present
|
|
90
|
+
*/
|
|
91
|
+
private getTokenExpiryTime(token: string): number | null {
|
|
92
|
+
const claims = this.parseTokenClaims(token);
|
|
93
|
+
return claims.exp ?? null;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Parse JWT claims from an access token.
|
|
98
|
+
*
|
|
99
|
+
* @param token - The JWT access token
|
|
100
|
+
* @returns Decoded token claims
|
|
101
|
+
* @throws Error if token is invalid
|
|
102
|
+
*/
|
|
103
|
+
parseTokenClaims<TCustomClaims = CustomClaims>(
|
|
104
|
+
token: string,
|
|
105
|
+
): BaseTokenClaims & TCustomClaims {
|
|
106
|
+
try {
|
|
107
|
+
return decodeJwt<BaseTokenClaims & TCustomClaims>(token);
|
|
108
|
+
} catch (error) {
|
|
109
|
+
throw new Error('Invalid token');
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Encrypt a session object into a string suitable for cookie storage.
|
|
115
|
+
*
|
|
116
|
+
* @param session - The session to encrypt
|
|
117
|
+
* @returns Encrypted session string
|
|
118
|
+
* @throws SessionEncryptionError if encryption fails
|
|
119
|
+
*/
|
|
120
|
+
async encryptSession(session: Session): Promise<string> {
|
|
121
|
+
try {
|
|
122
|
+
const password = this.config.getValue('cookiePassword');
|
|
123
|
+
const encryptedSession = await this.encryption.sealData(session, {
|
|
124
|
+
password,
|
|
125
|
+
ttl: 0,
|
|
126
|
+
});
|
|
127
|
+
return encryptedSession;
|
|
128
|
+
} catch (error) {
|
|
129
|
+
throw new SessionEncryptionError('Failed to encrypt session', error);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Decrypt an encrypted session string back into a session object.
|
|
135
|
+
*
|
|
136
|
+
* @param encryptedSession - The encrypted session string
|
|
137
|
+
* @returns Decrypted session object
|
|
138
|
+
* @throws SessionEncryptionError if decryption fails
|
|
139
|
+
*/
|
|
140
|
+
async decryptSession(encryptedSession: string): Promise<Session> {
|
|
141
|
+
try {
|
|
142
|
+
const password = this.config.getValue('cookiePassword');
|
|
143
|
+
const session = await this.encryption.unsealData<Session>(
|
|
144
|
+
encryptedSession,
|
|
145
|
+
{ password },
|
|
146
|
+
);
|
|
147
|
+
return session;
|
|
148
|
+
} catch (error) {
|
|
149
|
+
throw new SessionEncryptionError('Failed to decrypt session', error);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Refresh tokens using WorkOS API.
|
|
155
|
+
*
|
|
156
|
+
* @param refreshToken - The refresh token
|
|
157
|
+
* @param organizationId - Optional organization ID to switch to
|
|
158
|
+
* @returns New access token, refresh token, user, and impersonator
|
|
159
|
+
* @throws TokenRefreshError if refresh fails
|
|
160
|
+
*/
|
|
161
|
+
async refreshTokens(
|
|
162
|
+
refreshToken: string,
|
|
163
|
+
organizationId?: string,
|
|
164
|
+
): Promise<{
|
|
165
|
+
accessToken: string;
|
|
166
|
+
refreshToken: string;
|
|
167
|
+
user: User;
|
|
168
|
+
impersonator: Impersonator | undefined;
|
|
169
|
+
}> {
|
|
170
|
+
try {
|
|
171
|
+
const result =
|
|
172
|
+
await this.client.userManagement.authenticateWithRefreshToken({
|
|
173
|
+
refreshToken,
|
|
174
|
+
clientId: this.clientId,
|
|
175
|
+
organizationId,
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
return {
|
|
179
|
+
accessToken: result.accessToken,
|
|
180
|
+
refreshToken: result.refreshToken,
|
|
181
|
+
user: result.user,
|
|
182
|
+
impersonator: result.impersonator,
|
|
183
|
+
};
|
|
184
|
+
} catch (error) {
|
|
185
|
+
throw new TokenRefreshError('Failed to refresh tokens', error);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Validate a session and refresh if needed.
|
|
191
|
+
*
|
|
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?
|
|
196
|
+
*
|
|
197
|
+
* @param session - The current session with access and refresh tokens
|
|
198
|
+
* @returns Validation result with refreshed session if needed
|
|
199
|
+
* @throws TokenRefreshError if refresh fails
|
|
200
|
+
*/
|
|
201
|
+
async validateAndRefresh<TCustomClaims = CustomClaims>(
|
|
202
|
+
session: Session,
|
|
203
|
+
): Promise<{
|
|
204
|
+
valid: boolean;
|
|
205
|
+
refreshed: boolean;
|
|
206
|
+
session: Session;
|
|
207
|
+
claims: BaseTokenClaims & TCustomClaims;
|
|
208
|
+
}> {
|
|
209
|
+
const { accessToken } = session;
|
|
210
|
+
const isValid = await this.verifyToken(accessToken);
|
|
211
|
+
const isExpiring = this.isTokenExpiring(accessToken);
|
|
212
|
+
if (isValid && !isExpiring) {
|
|
213
|
+
const claims = this.parseTokenClaims<TCustomClaims>(accessToken);
|
|
214
|
+
return { valid: true, refreshed: false, session, claims };
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
let organizationId: string | undefined;
|
|
218
|
+
if (isValid) {
|
|
219
|
+
try {
|
|
220
|
+
const oldClaims = this.parseTokenClaims(accessToken);
|
|
221
|
+
organizationId = oldClaims.org_id;
|
|
222
|
+
} catch {}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
const newSession = await this.refreshTokens(
|
|
226
|
+
session.refreshToken,
|
|
227
|
+
organizationId,
|
|
228
|
+
);
|
|
229
|
+
const newClaims = this.parseTokenClaims<TCustomClaims>(
|
|
230
|
+
newSession.accessToken,
|
|
231
|
+
);
|
|
232
|
+
return {
|
|
233
|
+
valid: true,
|
|
234
|
+
refreshed: true,
|
|
235
|
+
session: newSession,
|
|
236
|
+
claims: newClaims,
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
}
|
|
@@ -133,4 +133,21 @@ describe('CookieSessionStorage', () => {
|
|
|
133
133
|
expect(clearedResult.headers).toHaveProperty('Set-Cookie');
|
|
134
134
|
});
|
|
135
135
|
});
|
|
136
|
+
|
|
137
|
+
describe('buildSetCookie', () => {
|
|
138
|
+
it('capitalizes SameSite values for Safari compatibility', async () => {
|
|
139
|
+
const testCases = [
|
|
140
|
+
{ input: 'lax', expected: 'SameSite=Lax' },
|
|
141
|
+
{ input: 'strict', expected: 'SameSite=Strict' },
|
|
142
|
+
{ input: 'none', expected: 'SameSite=None' },
|
|
143
|
+
];
|
|
144
|
+
|
|
145
|
+
for (const { input, expected } of testCases) {
|
|
146
|
+
const config = createMockConfig({ cookieSameSite: input });
|
|
147
|
+
const storage = new TestCookieSessionStorage(config as any);
|
|
148
|
+
const result = await storage.saveSession(undefined, 'test-data');
|
|
149
|
+
expect(result.headers?.['Set-Cookie']).toContain(expected);
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
});
|
|
136
153
|
});
|
|
@@ -23,11 +23,28 @@ export abstract class CookieSessionStorage<TRequest, TResponse>
|
|
|
23
23
|
constructor(config: ConfigurationProvider) {
|
|
24
24
|
this.config = config;
|
|
25
25
|
this.cookieName = config.getValue('cookieName') || 'wos_session';
|
|
26
|
+
|
|
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
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
26
43
|
this.cookieOptions = {
|
|
27
44
|
path: '/',
|
|
28
45
|
httpOnly: true,
|
|
29
46
|
sameSite: config.getValue('cookieSameSite') ?? 'lax',
|
|
30
|
-
secure
|
|
47
|
+
secure,
|
|
31
48
|
maxAge: config.getValue('cookieMaxAge') || 60 * 60 * 24 * 400, // 400 days
|
|
32
49
|
domain: config.getValue('cookieDomain'),
|
|
33
50
|
};
|
|
@@ -48,7 +65,10 @@ export abstract class CookieSessionStorage<TRequest, TResponse>
|
|
|
48
65
|
if (o.maxAge || expired) a.push(`Max-Age=${expired ? 0 : o.maxAge}`);
|
|
49
66
|
if (o.httpOnly) a.push('HttpOnly');
|
|
50
67
|
if (o.secure) a.push('Secure');
|
|
51
|
-
if (o.sameSite)
|
|
68
|
+
if (o.sameSite) {
|
|
69
|
+
const capitalizedSameSite = o.sameSite.charAt(0).toUpperCase() + o.sameSite.slice(1).toLowerCase();
|
|
70
|
+
a.push(`SameSite=${capitalizedSameSite}`);
|
|
71
|
+
}
|
|
52
72
|
if (o.priority) a.push(`Priority=${o.priority}`);
|
|
53
73
|
if (o.partitioned) a.push('Partitioned');
|
|
54
74
|
return a.join('; ');
|
|
@@ -13,14 +13,36 @@ export interface BaseTokenClaims extends JWTPayload {
|
|
|
13
13
|
|
|
14
14
|
export type CustomClaims = Record<string, unknown>;
|
|
15
15
|
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
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
|
+
impersonator?: Impersonator;
|
|
45
|
+
};
|
|
24
46
|
|
|
25
47
|
/**
|
|
26
48
|
* AuthKit Session
|
package/src/index.ts
CHANGED
|
@@ -1,4 +1,43 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
* @workos/authkit-session
|
|
3
|
+
*
|
|
4
|
+
* A toolkit library for building WorkOS AuthKit integrations.
|
|
5
|
+
* Provides business logic primitives (crypto, JWT, refresh) that framework
|
|
6
|
+
* adapters use to implement authentication patterns.
|
|
7
|
+
*
|
|
8
|
+
* **Philosophy:**
|
|
9
|
+
* - Extract complex business logic → Shared across frameworks
|
|
10
|
+
* - Provide integration helpers → Cookie building, config management
|
|
11
|
+
* - Let frameworks own patterns → updateSession/withAuth are framework-specific
|
|
12
|
+
*
|
|
13
|
+
* **Core Toolkit (Recommended):**
|
|
14
|
+
* - AuthKitCore: Token verification, encryption, refresh orchestration
|
|
15
|
+
* - AuthOperations: WorkOS API operations (signOut, refreshSession, URLs)
|
|
16
|
+
* - CookieSessionStorage: Cookie building helpers
|
|
17
|
+
* - ConfigurationProvider: Environment variable and config management
|
|
18
|
+
*
|
|
19
|
+
* **Optional Reference:**
|
|
20
|
+
* - AuthService: Example orchestration pattern (frameworks can implement their own)
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
// ============================================
|
|
24
|
+
// TIER 1: Core Business Logic (Required)
|
|
25
|
+
// ============================================
|
|
26
|
+
export { AuthKitCore } from './core/AuthKitCore.js';
|
|
27
|
+
|
|
28
|
+
// ============================================
|
|
29
|
+
// TIER 2: WorkOS Operations (Recommended)
|
|
30
|
+
// ============================================
|
|
31
|
+
export { AuthOperations } from './operations/AuthOperations.js';
|
|
32
|
+
|
|
33
|
+
// ============================================
|
|
34
|
+
// TIER 3: Storage Helpers (Recommended)
|
|
35
|
+
// ============================================
|
|
36
|
+
export { CookieSessionStorage } from './core/session/CookieSessionStorage.js';
|
|
37
|
+
|
|
38
|
+
// ============================================
|
|
39
|
+
// TIER 4: Configuration (Utility)
|
|
40
|
+
// ============================================
|
|
2
41
|
export {
|
|
3
42
|
configure,
|
|
4
43
|
getConfig,
|
|
@@ -6,9 +45,15 @@ export {
|
|
|
6
45
|
validateConfig,
|
|
7
46
|
} from './core/config.js';
|
|
8
47
|
export { ConfigurationProvider } from './core/config/ConfigurationProvider.js';
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
48
|
+
|
|
49
|
+
// ============================================
|
|
50
|
+
// Client Factory
|
|
51
|
+
// ============================================
|
|
52
|
+
export { getWorkOS } from './core/client/workos.js';
|
|
53
|
+
|
|
54
|
+
// ============================================
|
|
55
|
+
// Type Exports
|
|
56
|
+
// ============================================
|
|
12
57
|
export * from './core/session/types.js';
|
|
13
58
|
export * from './core/config/types.js';
|
|
14
59
|
export type {
|
|
@@ -18,3 +63,9 @@ export type {
|
|
|
18
63
|
WorkOS,
|
|
19
64
|
AuthenticationResponse,
|
|
20
65
|
} from '@workos-inc/node';
|
|
66
|
+
|
|
67
|
+
// ============================================
|
|
68
|
+
// Optional Reference Implementation
|
|
69
|
+
// ============================================
|
|
70
|
+
export { AuthService } from './service/AuthService.js';
|
|
71
|
+
export { createAuthService } from './service/factory.js';
|