Add timeouts for Turnstile and Resend

This commit is contained in:
Calum Muir 2025-12-28 13:34:18 +00:00
parent 3cfebd6d51
commit bfe6469a46

View file

@ -11,6 +11,25 @@ const jsonResponse = (data: Record<string, unknown>, status = 200) =>
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
}); });
const fetchWithTimeout = async (
input: RequestInfo | URL,
init: RequestInit,
timeoutMs: number,
label: string,
) => {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), timeoutMs);
try {
return await fetch(input, { ...init, signal: controller.signal });
} catch (error) {
const message =
error instanceof Error ? error.message : "Unknown error";
throw new Error(`${label} request failed: ${message}`);
} finally {
clearTimeout(timeout);
}
};
const readFormField = (value: FormDataEntryValue | null) => const readFormField = (value: FormDataEntryValue | null) =>
typeof value === "string" ? value.trim() : ""; typeof value === "string" ? value.trim() : "";
const readTextField = (value: string | null) => (value ?? "").trim(); const readTextField = (value: string | null) => (value ?? "").trim();
@ -68,12 +87,15 @@ const handlePost: PagesFunction<Env> = async ({ request, env }) => {
remoteip: request.headers.get("CF-Connecting-IP") ?? "", remoteip: request.headers.get("CF-Connecting-IP") ?? "",
}); });
const verifyResponse = await fetch( const verifyResponse = await fetchWithTimeout(
"https://challenges.cloudflare.com/turnstile/v0/siteverify", "https://challenges.cloudflare.com/turnstile/v0/siteverify",
{ {
method: "POST", method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: verifyBody, body: verifyBody,
}, },
8000,
"Turnstile",
); );
const verifyResult = (await verifyResponse.json()) as { const verifyResult = (await verifyResponse.json()) as {
success?: boolean; success?: boolean;
@ -133,14 +155,19 @@ const handlePost: PagesFunction<Env> = async ({ request, env }) => {
text: `Name: ${name}\nEmail: ${email}\n\n${message}`, text: `Name: ${name}\nEmail: ${email}\n\n${message}`,
}; };
const response = await fetch("https://api.resend.com/emails", { const response = await fetchWithTimeout(
method: "POST", "https://api.resend.com/emails",
headers: { {
Authorization: `Bearer ${env.RESEND_API_KEY}`, method: "POST",
"Content-Type": "application/json", headers: {
Authorization: `Bearer ${env.RESEND_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify(emailPayload),
}, },
body: JSON.stringify(emailPayload), 8000,
}); "Resend",
);
if (!response.ok) { if (!response.ok) {
const contentType = response.headers.get("content-type") ?? ""; const contentType = response.headers.get("content-type") ?? "";
const errorText = contentType.includes("application/json") const errorText = contentType.includes("application/json")