forked from Prompt-Hash-Stellar/prompt-hash
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreplayProtection.ts
More file actions
74 lines (63 loc) · 1.87 KB
/
Copy pathreplayProtection.ts
File metadata and controls
74 lines (63 loc) · 1.87 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
import { getRedisClient } from "./redisClient";
import { LRUCache } from "lru-cache";
interface ReplayCheckConfig {
ttlMs: number;
}
const defaultConfig: ReplayCheckConfig = {
ttlMs: 10 * 60 * 1000,
};
const fallbackCache = new LRUCache<string, boolean>({
max: 10000,
ttl: defaultConfig.ttlMs,
});
function computeSignatureHash(token: string, signedMessage: string): string {
return `${token}:${signedMessage}`;
}
async function redisCheckAndStore(
redis: Awaited<ReturnType<typeof getRedisClient>>,
signatureHash: string,
config: ReplayCheckConfig,
): Promise<boolean> {
const key = `replay:${signatureHash}`;
const ttlSec = Math.ceil(config.ttlMs / 1000);
const multi = redis!.multi();
multi.setNX(key, "1");
multi.expire(key, ttlSec, "NX");
const [wasSet] = (await multi.exec()) as [number, ...unknown[]];
return wasSet === 1;
}
function inMemoryCheckAndStore(
signatureHash: string,
_config: ReplayCheckConfig,
): boolean {
if (fallbackCache.has(signatureHash)) {
return false;
}
fallbackCache.set(signatureHash, true);
return true;
}
export async function checkReplayProtection(
token: string,
signedMessage: string,
config: Partial<ReplayCheckConfig> = {},
): Promise<{ valid: boolean; reason?: string }> {
const finalConfig = { ...defaultConfig, ...config };
const signatureHash = computeSignatureHash(token, signedMessage);
try {
const redis = await getRedisClient();
if (redis) {
const isValid = await redisCheckAndStore(redis, signatureHash, finalConfig);
if (!isValid) {
return { valid: false, reason: "replay_detected" };
}
return { valid: true };
}
} catch {
// Redis unavailable — fall back to in-memory.
}
const isValid = inMemoryCheckAndStore(signatureHash, finalConfig);
if (!isValid) {
return { valid: false, reason: "replay_detected" };
}
return { valid: true };
}