-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAuthKitCore.ts
More file actions
254 lines (236 loc) · 7.41 KB
/
AuthKitCore.ts
File metadata and controls
254 lines (236 loc) · 7.41 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
import type { Impersonator, User, WorkOS } from '@workos-inc/node';
import { createRemoteJWKSet, decodeJwt, jwtVerify } from 'jose';
import { once } from '../utils.js';
import type { AuthKitConfig } from './config/types.js';
import { SessionEncryptionError, TokenRefreshError } from './errors.js';
import type {
BaseTokenClaims,
CustomClaims,
Session,
SessionEncryption,
} from './session/types.js';
/**
* AuthKitCore provides pure business logic for authentication operations.
*
* This class contains no framework-specific code - all methods are pure functions
* that take data in and return data out. No TRequest/TResponse generics here.
*
* Responsibilities:
* - Token validation (JWT verification against JWKS)
* - Token claims parsing
* - Session encryption/decryption
* - Token refresh (calling WorkOS API)
* - Session validation orchestration
*/
export class AuthKitCore {
private config: AuthKitConfig;
private client: WorkOS;
private encryption: SessionEncryption;
private clientId: string;
constructor(
config: AuthKitConfig,
client: WorkOS,
encryption: SessionEncryption,
) {
this.config = config;
this.client = client;
this.encryption = encryption;
this.clientId = config.clientId;
}
/**
* JWKS public key fetcher - cached for performance
*/
private readonly getPublicKey = once(() =>
createRemoteJWKSet(
new URL(this.client.userManagement.getJwksUrl(this.clientId)),
),
);
/**
* Verify a JWT access token against WorkOS JWKS.
*
* @param token - The JWT access token to verify
* @returns true if valid, false otherwise
*/
async verifyToken(token: string): Promise<boolean> {
try {
await jwtVerify(token, this.getPublicKey());
return true;
} catch {
return false;
}
}
/**
* Check if a token is expiring soon.
*
* @param token - The JWT access token
* @param buffer - How many seconds before expiry to consider "expiring" (default: 60)
* @returns true if token expires within buffer period
*/
isTokenExpiring(token: string, buffer: number = 10): boolean {
const expiryTime = this.getTokenExpiryTime(token);
if (!expiryTime) {
return false;
}
const currentTime = Math.floor(Date.now() / 1000);
return expiryTime - currentTime <= buffer;
}
/**
* Get the expiry time from a token's claims.
*
* @param token - The JWT access token
* @returns Unix timestamp of expiry, or null if not present
*/
private getTokenExpiryTime(token: string): number | undefined {
const claims = this.parseTokenClaims(token);
return claims.exp;
}
/**
* Parse JWT claims from an access token.
*
* @param token - The JWT access token
* @returns Decoded token claims
* @throws Error if token is invalid
*/
parseTokenClaims<TCustomClaims = CustomClaims>(
token: string,
): BaseTokenClaims & TCustomClaims {
try {
return decodeJwt<BaseTokenClaims & TCustomClaims>(token);
} catch (error) {
throw new Error('Invalid token');
}
}
/**
* Encrypt a session object into a string suitable for cookie storage.
*
* @param session - The session to encrypt
* @returns Encrypted session string
* @throws SessionEncryptionError if encryption fails
*/
async encryptSession(session: Session): Promise<string> {
try {
const encryptedSession = await this.encryption.sealData(session, {
password: this.config.cookiePassword,
ttl: 0,
});
return encryptedSession;
} catch (error) {
throw new SessionEncryptionError('Failed to encrypt session', error);
}
}
/**
* Decrypt an encrypted session string back into a session object.
*
* @param encryptedSession - The encrypted session string
* @returns Decrypted session object
* @throws SessionEncryptionError if decryption fails
*/
async decryptSession(encryptedSession: string): Promise<Session> {
try {
const session = await this.encryption.unsealData<Session>(
encryptedSession,
{ password: this.config.cookiePassword },
);
return session;
} catch (error) {
throw new SessionEncryptionError('Failed to decrypt session', error);
}
}
/**
* Refresh tokens using WorkOS API.
*
* @param refreshToken - The refresh token
* @param organizationId - Optional organization ID to switch to
* @param context - Optional context for error reporting (userId, sessionId)
* @returns New access token, refresh token, user, and impersonator
* @throws TokenRefreshError if refresh fails
*/
async refreshTokens(
refreshToken: string,
organizationId?: string,
context?: { userId?: string; sessionId?: string },
): Promise<{
accessToken: string;
refreshToken: string;
user: User;
impersonator: Impersonator | undefined;
}> {
try {
const result =
await this.client.userManagement.authenticateWithRefreshToken({
refreshToken,
clientId: this.clientId,
organizationId,
});
return {
accessToken: result.accessToken,
refreshToken: result.refreshToken,
user: result.user,
impersonator: result.impersonator,
};
} catch (error) {
throw new TokenRefreshError('Failed to refresh tokens', error, context);
}
}
/**
* Validate a session and refresh if needed.
*
* Only refreshes when token is invalid (expired) or force is true.
*
* @param session - The current session with access and refresh tokens
* @param options - Optional settings
* @param options.force - Force refresh even if token is valid (for org switching)
* @param options.organizationId - Organization ID to switch to during refresh
* @returns Validation result with refreshed session if needed
* @throws TokenRefreshError if refresh fails
*/
async validateAndRefresh<TCustomClaims = CustomClaims>(
session: Session,
options?: { force?: boolean; organizationId?: string },
): Promise<{
valid: boolean;
refreshed: boolean;
session: Session;
claims: BaseTokenClaims & TCustomClaims;
}> {
const { accessToken } = session;
const { force = false, organizationId: explicitOrgId } = options ?? {};
const isValid = await this.verifyToken(accessToken);
// Return early if token is valid and not forced
if (isValid && !force) {
const claims = this.parseTokenClaims<TCustomClaims>(accessToken);
return { valid: true, refreshed: false, session, claims };
}
// Determine organization ID: explicit > extracted from token
let organizationId = explicitOrgId;
if (!organizationId && isValid) {
try {
const oldClaims = this.parseTokenClaims(accessToken);
organizationId = oldClaims.org_id;
} catch {
// Token parsing failed - refresh without org context
}
}
// Extract session ID for error context (works on expired tokens too)
let sessionId: string | undefined;
try {
sessionId = this.parseTokenClaims(accessToken).sid;
} catch {
// Token parsing failed - continue without session context
}
const newSession = await this.refreshTokens(
session.refreshToken,
organizationId,
{ userId: session.user?.id, sessionId },
);
const newClaims = this.parseTokenClaims<TCustomClaims>(
newSession.accessToken,
);
return {
valid: true,
refreshed: true,
session: newSession,
claims: newClaims,
};
}
}