-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrate.ts
More file actions
55 lines (28 loc) · 1.1 KB
/
Copy pathrate.ts
File metadata and controls
55 lines (28 loc) · 1.1 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
import { printLogLine } from "./utils.ts";
export async function checkTimeRateLimit(hashedIp: string, limitSeconds: number): Promise<boolean> {
try {
const cache = (caches as any)?.default;
if (!cache) return true;
const cacheKey = `https://ratelimit.local/${hashedIp}`;
const hit = await cache.match(cacheKey);
if (hit) return false;
await cache.put(cacheKey, new Response("1", {
"headers": { "Cache-Control": `max-age=${limitSeconds}` }
}));
return true;
} catch (_err) {
printLogLine("ERROR", "Cache API failure.");
return true;
}
}
export async function hashIP(ip: string, salt: string): Promise<string> {
const msgBuffer = new TextEncoder().encode(ip + salt);
const hashBuffer = await crypto.subtle.digest("SHA-256", msgBuffer);
const hashArray = new Uint8Array(hashBuffer);
let hexString = "";
for (let i = 0; i < hashArray.length; i++) {
const b = hashArray[i];
hexString += ((b < 16) ? '0' : '') + b.toString(16);
}
return hexString;
}