-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAuthKitCore.spec.ts
More file actions
265 lines (219 loc) · 7.53 KB
/
AuthKitCore.spec.ts
File metadata and controls
265 lines (219 loc) · 7.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
import { AuthKitCore } from './AuthKitCore.js';
import { SessionEncryptionError, TokenRefreshError } from './errors.js';
const mockConfig = {
getValue: (key: string) => {
const values = {
cookiePassword: 'test-password-that-is-32-chars-long!!',
clientId: 'test-client-id',
};
return values[key as keyof typeof values];
},
};
const mockUser = {
id: 'user_123',
email: 'test@example.com',
object: 'user',
firstName: 'Test',
lastName: 'User',
emailVerified: true,
profilePictureUrl: null,
createdAt: '2023-01-01T00:00:00Z',
updatedAt: '2023-01-01T00:00:00Z',
lastSignInAt: '2023-01-01T00:00:00Z',
externalId: null,
metadata: {},
} as const;
const mockClient = {
userManagement: {
getJwksUrl: () => 'https://api.workos.com/sso/jwks/test-client-id',
authenticateWithRefreshToken: async () => ({
accessToken: 'new-access-token',
refreshToken: 'new-refresh-token',
user: mockUser,
impersonator: undefined,
}),
},
};
const mockEncryption = {
sealData: async () => 'encrypted-session-data',
unsealData: async () => ({
accessToken: 'test-access-token',
refreshToken: 'test-refresh-token',
user: mockUser,
impersonator: undefined,
}),
};
describe('AuthKitCore', () => {
let core: AuthKitCore;
beforeEach(() => {
core = new AuthKitCore(
mockConfig as any,
mockClient as any,
mockEncryption as any,
);
});
describe('constructor', () => {
it('creates instance with required dependencies', () => {
expect(core).toBeInstanceOf(AuthKitCore);
});
});
describe('parseTokenClaims()', () => {
it('parses valid JWT payload', () => {
const validJwt =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyXzEyMyIsInNpZCI6InNlc3Npb25fMTIzIiwiZXhwIjoxNzM2Mzc2MDAwfQ.fake-signature';
const result = core.parseTokenClaims(validJwt);
expect(result.sub).toBe('user_123');
expect(result.sid).toBe('session_123');
expect(result.exp).toBe(1736376000);
});
it('throws error for invalid JWT', () => {
expect(() => core.parseTokenClaims('invalid-jwt')).toThrow(
'Invalid token',
);
});
it('supports custom claims', () => {
const customJwt =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyXzEyMyIsImN1c3RvbUZpZWxkIjoiY3VzdG9tLXZhbHVlIn0.fake-signature';
const result = core.parseTokenClaims<{ customField: string }>(customJwt);
expect(result.customField).toBe('custom-value');
});
});
describe('isTokenExpiring()', () => {
it('returns true when token expires soon', () => {
const soonExpiry = Math.floor(Date.now() / 1000) + 30;
const expiringJwt = `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.${btoa(JSON.stringify({ exp: soonExpiry }))}.fake-signature`;
const result = core.isTokenExpiring(expiringJwt);
expect(result).toBe(true);
});
it('returns false when token expires later', () => {
const laterExpiry = Math.floor(Date.now() / 1000) + 3600;
const validJwt = `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.${btoa(JSON.stringify({ exp: laterExpiry }))}.fake-signature`;
const result = core.isTokenExpiring(validJwt);
expect(result).toBe(false);
});
it('uses custom buffer time', () => {
const expiry = Math.floor(Date.now() / 1000) + 150;
const jwt = `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.${btoa(JSON.stringify({ exp: expiry }))}.fake-signature`;
const result = core.isTokenExpiring(jwt, 180);
expect(result).toBe(true);
});
it('returns false when token has no expiry', () => {
const noExpiryJwt =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyXzEyMyJ9.fake-signature';
const result = core.isTokenExpiring(noExpiryJwt);
expect(result).toBe(false);
});
});
describe('verifyToken()', () => {
it('returns false for invalid tokens', async () => {
const result = await core.verifyToken('invalid-token');
expect(result).toBe(false);
});
it('returns false for malformed tokens', async () => {
const result = await core.verifyToken('not.a.jwt');
expect(result).toBe(false);
});
});
describe('encryptSession()', () => {
it('encrypts session data', async () => {
const session = {
accessToken: 'test-token',
refreshToken: 'test-refresh',
user: mockUser,
impersonator: undefined,
};
const result = await core.encryptSession(session);
expect(result).toBe('encrypted-session-data');
});
it('throws SessionEncryptionError on failure', async () => {
const failingEncryption = {
sealData: async () => {
throw new Error('Encryption failed');
},
unsealData: async () => ({}),
};
const failingCore = new AuthKitCore(
mockConfig as any,
mockClient as any,
failingEncryption as any,
);
await expect(
failingCore.encryptSession({
accessToken: 'test',
refreshToken: 'test',
user: mockUser,
impersonator: undefined,
}),
).rejects.toThrow(SessionEncryptionError);
});
});
describe('decryptSession()', () => {
it('decrypts session data', async () => {
const result = await core.decryptSession('encrypted-data');
expect(result.accessToken).toBe('test-access-token');
expect(result.user).toEqual(mockUser);
});
it('throws SessionEncryptionError on failure', async () => {
const failingEncryption = {
sealData: async () => 'encrypted',
unsealData: async () => {
throw new Error('Decryption failed');
},
};
const failingCore = new AuthKitCore(
mockConfig as any,
mockClient as any,
failingEncryption as any,
);
await expect(failingCore.decryptSession('bad-data')).rejects.toThrow(
SessionEncryptionError,
);
});
});
describe('refreshTokens()', () => {
it('refreshes tokens via WorkOS', async () => {
const result = await core.refreshTokens('refresh-token');
expect(result.accessToken).toBe('new-access-token');
expect(result.refreshToken).toBe('new-refresh-token');
expect(result.user).toEqual(mockUser);
});
it('includes organizationId when provided', async () => {
const clientWithSpy = {
userManagement: {
getJwksUrl: () => 'https://api.workos.com/sso/jwks/test-client-id',
authenticateWithRefreshToken: async ({ organizationId }: any) => ({
accessToken: organizationId ? 'org-token' : 'regular-token',
refreshToken: 'new-refresh-token',
user: mockUser,
impersonator: undefined,
}),
},
};
const testCore = new AuthKitCore(
mockConfig as any,
clientWithSpy as any,
mockEncryption as any,
);
const result = await testCore.refreshTokens('refresh-token', 'org_123');
expect(result.accessToken).toBe('org-token');
});
it('throws TokenRefreshError on failure', async () => {
const failingClient = {
userManagement: {
getJwksUrl: () => 'https://api.workos.com/sso/jwks/test-client-id',
authenticateWithRefreshToken: async () => {
throw new Error('Refresh failed');
},
},
};
const failingCore = new AuthKitCore(
mockConfig as any,
failingClient as any,
mockEncryption as any,
);
await expect(failingCore.refreshTokens('bad-token')).rejects.toThrow(
TokenRefreshError,
);
});
});
});