This repository was archived by the owner on Sep 17, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathguard.ts
54 lines (45 loc) · 1.5 KB
/
guard.ts
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
import { RuntimeError, ScriptContext } from "../module.gen.ts";
import { getPublicConfig } from "../utils/get_sitekey.ts";
// import { getPublicConfig } from "../utils/get_sitekey.ts";
import type { CaptchaProvider, ThrottleRequest, ThrottleResponse } from "../utils/types.ts";
export interface Request {
type: string;
key: string;
requests: number;
period: number;
captchaToken?: string | null,
captchaProvider: CaptchaProvider
}
export type Response = Record<string, never>;
export async function run(
ctx: ScriptContext,
req: Request,
): Promise<Response> {
const key = `${JSON.stringify(req.type)}.${JSON.stringify(req.key)}`;
if (req.captchaToken) {
try {
await ctx.modules.captcha.verifyCaptchaToken({
token: req.captchaToken,
provider: req.captchaProvider
});
await ctx.actors.throttle.getOrCreateAndCall<undefined, {}, {}>(key, undefined, "reset", {});
return {};
} catch {
// If we error, it means the captcha failed, we can continue with our normal ratelimitting
}
}
const res = await ctx.actors.throttle.getOrCreateAndCall<
undefined,
ThrottleRequest,
ThrottleResponse
>(key, undefined, "throttle", {
requests: req.requests,
period: req.period,
});
if (!res.success) {
throw new RuntimeError("captcha_needed", {
meta: getPublicConfig(req.captchaProvider)
});
}
return {};
}