@tstdl/base 0.93.174 → 0.93.175
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/authentication/client/authentication.service.js +13 -0
- package/authentication/server/authentication.service.d.ts +1 -1
- package/authentication/server/authentication.service.js +2 -2
- package/authentication/tests/authentication.client-service-refresh.test.js +19 -0
- package/authentication/tests/authentication.refresh-busy-loop.test.d.ts +1 -0
- package/authentication/tests/authentication.refresh-busy-loop.test.js +84 -0
- package/package.json +1 -1
|
@@ -421,6 +421,7 @@ let AuthenticationClientService = class AuthenticationClientService {
|
|
|
421
421
|
// 2. Handle token refresh
|
|
422
422
|
if (needsRefresh) {
|
|
423
423
|
const lockResult = await this.lock.tryUse(undefined, async () => {
|
|
424
|
+
this.loadToken();
|
|
424
425
|
const currentToken = this.token();
|
|
425
426
|
if (isUndefined(currentToken)) {
|
|
426
427
|
return;
|
|
@@ -442,6 +443,18 @@ let AuthenticationClientService = class AuthenticationClientService {
|
|
|
442
443
|
this.forceRefreshRequested.set(false);
|
|
443
444
|
}
|
|
444
445
|
}
|
|
446
|
+
// Protection against tight loops (e.g. if server clock is ahead and sync failed)
|
|
447
|
+
const newToken = this.token();
|
|
448
|
+
if (isDefined(newToken)) {
|
|
449
|
+
const newNow = this.estimatedServerTimestampSeconds();
|
|
450
|
+
const newBuffer = calculateRefreshBufferSeconds(newToken);
|
|
451
|
+
const stillNeedsRefresh = this.forceRefreshRequested() || (newNow >= newToken.exp - newBuffer);
|
|
452
|
+
if (stillNeedsRefresh) {
|
|
453
|
+
this.logger.warn('Token still needs refresh after attempt. Waiting for minRefreshDelay to avoid tight loop.');
|
|
454
|
+
await waitForNextAction(minRefreshDelay, newToken.exp);
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
await waitForNextAction(100, newToken?.exp);
|
|
445
458
|
continue; // Re-evaluate the loop with the newly refreshed (or synced) token
|
|
446
459
|
}
|
|
447
460
|
// 3. Calculate delay and sleep until the next scheduled refresh window
|
|
@@ -55,7 +55,7 @@ export class AuthenticationServiceOptions {
|
|
|
55
55
|
/**
|
|
56
56
|
* How long a refresh token is valid in milliseconds. Implies session time to live.
|
|
57
57
|
*
|
|
58
|
-
* @default
|
|
58
|
+
* @default 6 hours
|
|
59
59
|
*/
|
|
60
60
|
refreshTokenTimeToLive;
|
|
61
61
|
/**
|
|
@@ -126,7 +126,7 @@ let AuthenticationService = AuthenticationService_1 = class AuthenticationServic
|
|
|
126
126
|
};
|
|
127
127
|
tokenVersion = this.#options.version ?? 1;
|
|
128
128
|
tokenTimeToLive = this.#options.tokenTimeToLive ?? (5 * millisecondsPerMinute);
|
|
129
|
-
refreshTokenTimeToLive = this.#options.refreshTokenTimeToLive ?? (
|
|
129
|
+
refreshTokenTimeToLive = this.#options.refreshTokenTimeToLive ?? (6 * millisecondsPerHour);
|
|
130
130
|
rememberRefreshTokenTimeToLive = this.#options.rememberRefreshTokenTimeToLive ?? (30 * millisecondsPerDay);
|
|
131
131
|
secretResetTokenTimeToLive = this.#options.secretResetTokenTimeToLive ?? (10 * millisecondsPerMinute);
|
|
132
132
|
derivedTokenSigningSecret;
|
|
@@ -130,4 +130,23 @@ describe('AuthenticationClientService Refresh Loop Reproduction', () => {
|
|
|
130
130
|
await service.refresh();
|
|
131
131
|
expect(mockApiClient.timestamp).toHaveBeenCalled();
|
|
132
132
|
});
|
|
133
|
+
test('Cross-tab Sync: should not refresh if another tab already did (simulated via localStorage update)', async () => {
|
|
134
|
+
const now = Math.floor(Date.now() / 1000);
|
|
135
|
+
const initialToken = { iat: now - 3600, exp: now + 5, jti: 'initial' }; // Expiring soon
|
|
136
|
+
globalThis.localStorage.setItem('AuthenticationService:token', JSON.stringify(initialToken));
|
|
137
|
+
// 1. Mock lock behavior to simulate another tab refreshing while we wait for the lock
|
|
138
|
+
mockLock.tryUse.mockImplementation(async (_timeout, callback) => {
|
|
139
|
+
// Simulate another tab refreshing and updating localStorage
|
|
140
|
+
const newToken = { iat: now, exp: now + 3600, jti: 'refreshed-by-other-tab' };
|
|
141
|
+
globalThis.localStorage.setItem('AuthenticationService:token', JSON.stringify(newToken));
|
|
142
|
+
const result = await callback({ lost: false });
|
|
143
|
+
return { success: true, result };
|
|
144
|
+
});
|
|
145
|
+
service = injector.resolve(AuthenticationClientService);
|
|
146
|
+
// Wait for loop to run
|
|
147
|
+
await timeout(100);
|
|
148
|
+
// Should NOT have called refresh because loadToken() inside the lock updated the token
|
|
149
|
+
expect(mockApiClient.refresh).not.toHaveBeenCalled();
|
|
150
|
+
expect(service.token()?.jti).toBe('refreshed-by-other-tab');
|
|
151
|
+
});
|
|
133
152
|
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
|
|
2
|
+
import { AuthenticationClientService } from '../../authentication/client/authentication.service.js';
|
|
3
|
+
import { AUTHENTICATION_API_CLIENT } from '../../authentication/client/tokens.js';
|
|
4
|
+
import { CancellationSignal, CancellationToken } from '../../cancellation/token.js';
|
|
5
|
+
import { Injector } from '../../injector/index.js';
|
|
6
|
+
import { Lock } from '../../lock/index.js';
|
|
7
|
+
import { Logger } from '../../logger/index.js';
|
|
8
|
+
import { MessageBus } from '../../message-bus/index.js';
|
|
9
|
+
import { configureDefaultSignalsImplementation } from '../../signals/implementation/configure.js';
|
|
10
|
+
import { timeout } from '../../utils/timing.js';
|
|
11
|
+
import { Subject } from 'rxjs';
|
|
12
|
+
describe('AuthenticationClientService Refresh Busy Loop Prevention', () => {
|
|
13
|
+
let injector;
|
|
14
|
+
let service;
|
|
15
|
+
let mockApiClient;
|
|
16
|
+
let mockLock;
|
|
17
|
+
let mockMessageBus;
|
|
18
|
+
let mockLogger;
|
|
19
|
+
let disposeToken;
|
|
20
|
+
beforeEach(() => {
|
|
21
|
+
const storage = new Map();
|
|
22
|
+
globalThis.localStorage = {
|
|
23
|
+
getItem: vi.fn((key) => storage.get(key) ?? null),
|
|
24
|
+
setItem: vi.fn((key, value) => storage.set(key, value)),
|
|
25
|
+
removeItem: vi.fn((key) => storage.delete(key)),
|
|
26
|
+
clear: vi.fn(() => storage.clear()),
|
|
27
|
+
};
|
|
28
|
+
configureDefaultSignalsImplementation();
|
|
29
|
+
injector = new Injector('Test');
|
|
30
|
+
mockApiClient = {
|
|
31
|
+
login: vi.fn(),
|
|
32
|
+
refresh: vi.fn(),
|
|
33
|
+
timestamp: vi.fn().mockResolvedValue(1000), // Fixed timestamp
|
|
34
|
+
endSession: vi.fn().mockResolvedValue(undefined),
|
|
35
|
+
};
|
|
36
|
+
mockLock = {
|
|
37
|
+
tryUse: vi.fn(async (_timeout, callback) => {
|
|
38
|
+
const result = await callback({ lost: false });
|
|
39
|
+
return { success: true, result };
|
|
40
|
+
}),
|
|
41
|
+
use: vi.fn(async (_timeout, callback) => {
|
|
42
|
+
return await callback({ lost: false });
|
|
43
|
+
}),
|
|
44
|
+
};
|
|
45
|
+
mockMessageBus = {
|
|
46
|
+
publishAndForget: vi.fn(),
|
|
47
|
+
messages$: new Subject(),
|
|
48
|
+
dispose: vi.fn(),
|
|
49
|
+
};
|
|
50
|
+
mockLogger = {
|
|
51
|
+
error: vi.fn(),
|
|
52
|
+
warn: vi.fn(),
|
|
53
|
+
info: vi.fn(),
|
|
54
|
+
debug: vi.fn(),
|
|
55
|
+
};
|
|
56
|
+
injector.register(AUTHENTICATION_API_CLIENT, { useValue: mockApiClient });
|
|
57
|
+
injector.register(Lock, { useValue: mockLock });
|
|
58
|
+
injector.register(MessageBus, { useValue: mockMessageBus });
|
|
59
|
+
injector.register(Logger, { useValue: mockLogger });
|
|
60
|
+
disposeToken = new CancellationToken();
|
|
61
|
+
injector.register(CancellationSignal, { useValue: disposeToken.signal });
|
|
62
|
+
});
|
|
63
|
+
afterEach(async () => {
|
|
64
|
+
disposeToken.set();
|
|
65
|
+
await injector.dispose();
|
|
66
|
+
});
|
|
67
|
+
test('should not busy loop when refresh fails to produce a valid token', async () => {
|
|
68
|
+
// 1. Mock a token that is ALWAYS expired
|
|
69
|
+
// Server time is 1000. Token expires at 500.
|
|
70
|
+
const expiredToken = { iat: 0, exp: 500, jti: 'expired', session: 's', tenant: 't', subject: 'sub' };
|
|
71
|
+
globalThis.localStorage.setItem('AuthenticationService:token', JSON.stringify(expiredToken));
|
|
72
|
+
// refresh() will return the SAME expired token
|
|
73
|
+
mockApiClient.refresh.mockResolvedValue(expiredToken);
|
|
74
|
+
// 2. Start service
|
|
75
|
+
service = injector.resolve(AuthenticationClientService);
|
|
76
|
+
// 3. Wait a bit
|
|
77
|
+
// With 100ms mandatory yield + minRefreshDelay (1 min) protection, it should only try once or twice in 500ms
|
|
78
|
+
// WITHOUT protection, it would try thousands of times.
|
|
79
|
+
await timeout(500);
|
|
80
|
+
// It should have tried to refresh
|
|
81
|
+
expect(mockApiClient.refresh.mock.calls.length).toBeLessThan(5);
|
|
82
|
+
expect(mockLogger.warn).toHaveBeenCalledWith(expect.stringContaining('Token still needs refresh after attempt'));
|
|
83
|
+
});
|
|
84
|
+
});
|