-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBearerTokenHttpClient.ts
More file actions
336 lines (283 loc) · 10 KB
/
BearerTokenHttpClient.ts
File metadata and controls
336 lines (283 loc) · 10 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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
import fetch from 'node-fetch';
import { HttpClient } from './HttpClient';
import { AuthenticationError, MaintenanceError } from './errors';
import { LocalLoginRequest, LocalLoginResponse, LocalTokenRefreshRequest, LocalTokenRefreshResponse } from '../types/generated/auth';
/** Endpoints that bypass the maintenance mode block. */
const MAINTENANCE_EXEMPT_PREFIXES = ['/auth/', '/system/maintenance'];
export class BearerTokenHttpClient extends HttpClient {
private accessToken: string | null = null;
private refreshToken: string | null = null;
private tokenExpiry: Date | null = null;
private tokenIssuedAt: Date | null = null;
private userId: string | null = null;
private refreshPromise: Promise<void> | null = null;
private _maintenanceMode = false;
private _maintenanceMessage: string | null = null;
private readonly REFRESH_THRESHOLD_PERCENTAGE = 0.1; // Refresh when <10% lifetime remains
constructor(
baseUrl: string,
timeout?: number,
cacheConfig?: {
enabled?: boolean;
ttl?: number;
respectCacheHeaders?: boolean;
maxSize?: number;
}
) {
super(baseUrl, timeout, 3, 1000, cacheConfig);
}
async authenticateWithCredentials(username: string, password: string): Promise<void> {
try {
const request: LocalLoginRequest = {
username,
password
};
const response = await fetch(`${this.baseUrl}/auth/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(request),
});
if (!response.ok) {
const errorText = await response.text();
throw new AuthenticationError(`Login failed: ${response.status} ${errorText}`);
}
const loginResponse = await response.json() as LocalLoginResponse;
this.setTokensFromResponse(loginResponse);
} catch (error) {
if (error instanceof AuthenticationError) {
throw error;
}
if (error instanceof Error) {
throw new AuthenticationError(`Authentication failed: ${error.message}`);
}
throw new AuthenticationError('Authentication failed with unknown error');
}
}
async authenticate(): Promise<void> {
if (!this.accessToken) {
throw new AuthenticationError('No access token available. Please login first.');
}
}
isAuthenticated(): boolean {
return !!this.accessToken && !this.isTokenExpired();
}
getAuthHeaders(): Record<string, string> {
if (!this.accessToken) {
return {};
}
return {
'Authorization': `Bearer ${this.accessToken}`,
};
}
public async refreshAuth(): Promise<void> {
// Prevent duplicate concurrent refresh calls
if (this.refreshPromise) {
console.log('[BearerTokenHttpClient] Refresh already in progress, waiting...');
return this.refreshPromise;
}
if (!this.refreshToken) {
throw new AuthenticationError('No refresh token available');
}
this.refreshPromise = this.performRefresh();
try {
await this.refreshPromise;
} finally {
this.refreshPromise = null;
}
}
private async performRefresh(): Promise<void> {
try {
const request: LocalTokenRefreshRequest = {
refresh_token: this.refreshToken!
};
const response = await fetch(`${this.baseUrl}/auth/refresh/local`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(request),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Token refresh failed: ${response.status} ${errorText}`);
}
const refreshResponse = await response.json() as LocalTokenRefreshResponse;
this.updateTokensFromRefresh(refreshResponse);
console.log('[BearerTokenHttpClient] Token refreshed successfully');
} catch (error) {
this.clearTokens();
if (error instanceof Error) {
throw new AuthenticationError(`Token refresh failed: ${error.message}`);
}
throw new AuthenticationError('Token refresh failed with unknown error');
}
}
protected async request<T>(
method: import('../types/HttpTypes').HttpMethod,
endpoint: string,
data?: any,
params?: Record<string, any>
): Promise<import('../types/HttpTypes').HttpResponse<T>> {
// Block requests during maintenance mode (except auth and maintenance status endpoints)
if (this._maintenanceMode && !MAINTENANCE_EXEMPT_PREFIXES.some(p => endpoint.startsWith(p))) {
throw new MaintenanceError(this._maintenanceMessage || undefined);
}
// Proactive refresh: check if token needs refresh before making request
if (this.shouldRefreshToken() && this.refreshToken) {
console.log('[BearerTokenHttpClient] Token close to expiry, proactively refreshing');
await this.refreshAuth();
}
try {
// Make the request
const response = await super.request<T>(method, endpoint, data, params);
return response;
} catch (error: any) {
// Reactive refresh: handle 401 Unauthorized by refreshing and retrying
if (error?.status === 401 && this.refreshToken) {
console.log('[BearerTokenHttpClient] Received 401, attempting token refresh and retry');
try {
// Refresh the token
await this.refreshAuth();
// Retry the original request with new token
console.log('[BearerTokenHttpClient] Token refreshed, retrying request');
return await super.request<T>(method, endpoint, data, params);
} catch (refreshError: any) {
console.error('[BearerTokenHttpClient] Token refresh failed:', refreshError);
throw error; // Throw original 401 error
}
}
// For all other errors, just rethrow
throw error;
}
}
private setTokensFromResponse(loginResponse: LocalLoginResponse): void {
this.accessToken = loginResponse.access_token;
this.refreshToken = loginResponse.refresh_token;
this.userId = loginResponse.user_id;
const now = Date.now();
this.tokenIssuedAt = new Date(now);
if (loginResponse.expires_in) {
this.tokenExpiry = new Date(now + loginResponse.expires_in * 1000);
}
}
private updateTokensFromRefresh(refreshResponse: LocalTokenRefreshResponse): void {
this.accessToken = refreshResponse.access_token;
if (refreshResponse.refresh_token) {
this.refreshToken = refreshResponse.refresh_token;
}
const now = Date.now();
this.tokenIssuedAt = new Date(now);
if (refreshResponse.expires_in) {
this.tokenExpiry = new Date(now + refreshResponse.expires_in * 1000);
}
}
private clearTokens(): void {
this.accessToken = null;
this.refreshToken = null;
this.tokenExpiry = null;
this.tokenIssuedAt = null;
this.userId = null;
}
/**
* Check if token should be refreshed based on remaining lifetime.
* Returns true when less than 10% of token lifetime remains.
* This prevents excessive refreshing while ensuring tokens stay valid.
*
* Examples:
* - 30s token: refreshes when <3s remain
* - 15min token: refreshes when <90s remain
*/
private shouldRefreshToken(): boolean {
if (!this.tokenExpiry || !this.tokenIssuedAt || !this.accessToken) {
return false;
}
const now = Date.now();
const expiryTime = this.tokenExpiry.getTime();
const issuedTime = this.tokenIssuedAt.getTime();
// Already expired
if (now >= expiryTime) {
return true;
}
// Calculate the total token lifetime and remaining time
const totalLifetimeMs = expiryTime - issuedTime;
const remainingMs = expiryTime - now;
// Refresh when less than 10% of the TOTAL lifetime remains
const thresholdMs = totalLifetimeMs * this.REFRESH_THRESHOLD_PERCENTAGE;
return remainingMs <= thresholdMs;
}
/**
* Check if token is actually expired (for backward compatibility)
*/
private isTokenExpired(): boolean {
if (!this.tokenExpiry) {
return false;
}
return Date.now() >= this.tokenExpiry.getTime();
}
public setTokens(accessToken: string, refreshToken?: string, expiresAt?: Date, userId?: string): void {
this.accessToken = accessToken;
this.refreshToken = refreshToken || null;
this.tokenExpiry = expiresAt || null;
this.userId = userId || null;
// When restoring tokens, we don't know the exact issue time
// Estimate it based on expiry time (assume it was just issued if we don't know better)
if (expiresAt && !this.tokenIssuedAt) {
// Assume a default lifetime for estimation purposes
// This is imperfect but better than nothing
this.tokenIssuedAt = new Date();
}
}
public getAccessToken(): string | null {
return this.accessToken;
}
public getRefreshToken(): string | null {
return this.refreshToken;
}
public getTokenExpiry(): Date | null {
return this.tokenExpiry;
}
public getUserId(): string | null {
return this.userId;
}
public logout(): void {
this.clearTokens();
}
public getTokenData(): {
accessToken: string | null;
refreshToken: string | null;
expiresAt: Date | null;
issuedAt: Date | null;
userId: string | null;
} {
return {
accessToken: this.accessToken,
refreshToken: this.refreshToken,
expiresAt: this.tokenExpiry,
issuedAt: this.tokenIssuedAt,
userId: this.userId
};
}
public setTokenData(data: {
accessToken: string;
refreshToken?: string;
expiresAt?: Date;
issuedAt?: Date;
userId?: string;
}): void {
this.accessToken = data.accessToken;
this.refreshToken = data.refreshToken || null;
this.tokenExpiry = data.expiresAt || null;
this.tokenIssuedAt = data.issuedAt || null;
this.userId = data.userId || null;
}
public setMaintenanceMode(active: boolean, message?: string): void {
this._maintenanceMode = active;
this._maintenanceMessage = message || null;
console.log(`[BearerTokenHttpClient] Maintenance mode ${active ? 'ENABLED' : 'DISABLED'}${message ? ': ' + message : ''}`);
}
public isMaintenanceMode(): boolean {
return this._maintenanceMode;
}
}