-
Notifications
You must be signed in to change notification settings - Fork 453
Expand file tree
/
Copy pathoauthNegativeCache.ts
More file actions
44 lines (38 loc) · 1.19 KB
/
oauthNegativeCache.ts
File metadata and controls
44 lines (38 loc) · 1.19 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
import { MachineTokenVerificationError, MachineTokenVerificationErrorCode } from '../errors';
const TTL_MS = 30_000;
const MAX_ENTRIES = 10_000;
type Entry = { expiresAt: number };
const cache = new Map<string, Entry>();
export function isOAuthTokenCachedAsInvalid(token: string): boolean {
const entry = cache.get(token);
if (!entry) {
return false;
}
if (Date.now() >= entry.expiresAt) {
cache.delete(token);
return false;
}
return true;
}
export function maybeCacheOAuthTokenAsInvalid(err: unknown, token: string): void {
if (!(err instanceof MachineTokenVerificationError) || err.code !== MachineTokenVerificationErrorCode.TokenInvalid) {
return;
}
if (cache.size >= MAX_ENTRIES) {
const oldest = cache.keys().next().value;
if (oldest !== undefined) {
cache.delete(oldest);
}
}
cache.set(token, { expiresAt: Date.now() + TTL_MS });
}
export function makeCachedInvalidOAuthTokenError(): MachineTokenVerificationError {
return new MachineTokenVerificationError({
message: 'OAuth token not found',
code: MachineTokenVerificationErrorCode.TokenInvalid,
status: 404,
});
}
export function resetOAuthNegativeCache(): void {
cache.clear();
}