195 lines
6.0 KiB
TypeScript
195 lines
6.0 KiB
TypeScript
import type { CaptchaLogger, CaptchaProvider } from "./types.js";
|
|
|
|
const DEFAULT_TIMEOUT_MS = 3_000;
|
|
const MCAPTCHA_SITEVERIFY_PATH = "/api/v1/pow/siteverify";
|
|
const MAX_RESPONSE_BYTES = 64 * 1024;
|
|
const MAX_TOKEN_BYTES = 8 * 1024;
|
|
const MAX_SITEKEY_BYTES = 1024;
|
|
const MAX_SECRET_BYTES = 4 * 1024;
|
|
const MAX_INSTANCE_URL_BYTES = 2048;
|
|
|
|
export type VerifyCaptchaArgs = {
|
|
/** Challenge token produced by the captcha widget. */
|
|
token: string | null | undefined;
|
|
/** Public sitekey for the surface being protected. */
|
|
sitekey: string | undefined;
|
|
/** Server-side site/account secret. */
|
|
secret: string | undefined;
|
|
/** Base URL of the captcha instance. */
|
|
instanceUrl: string | undefined;
|
|
provider?: CaptchaProvider;
|
|
/** Outage/misconfig policy: false (default) blocks the request. */
|
|
failOpen?: boolean;
|
|
logger?: CaptchaLogger;
|
|
fetchImpl?: typeof fetch;
|
|
timeoutMs?: number;
|
|
};
|
|
|
|
/**
|
|
* Verifies a captcha token against a self-hosted provider.
|
|
*
|
|
* mCaptcha:
|
|
* POST {instanceUrl}/api/v1/pow/siteverify body: { token, key, secret }
|
|
* response: { valid: boolean }
|
|
*
|
|
* Cap:
|
|
* POST {instanceUrl}/{sitekey}/siteverify body: { response, secret }
|
|
* response: { success: boolean }
|
|
*
|
|
* Semantics:
|
|
* - missing token -> false (real client failure, never fail-open)
|
|
* - misconfigured / outage -> `failOpen` (default false), with a warn log
|
|
* - valid:true -> true, otherwise false
|
|
*/
|
|
export async function verifyCaptchaToken({
|
|
token,
|
|
sitekey,
|
|
secret,
|
|
instanceUrl,
|
|
provider = "mcaptcha",
|
|
failOpen = false,
|
|
logger,
|
|
fetchImpl = fetch,
|
|
timeoutMs = DEFAULT_TIMEOUT_MS,
|
|
}: VerifyCaptchaArgs): Promise<boolean> {
|
|
if (
|
|
!instanceUrl ||
|
|
!secret ||
|
|
!sitekey ||
|
|
byteLength(instanceUrl) > MAX_INSTANCE_URL_BYTES ||
|
|
byteLength(secret) > MAX_SECRET_BYTES ||
|
|
byteLength(sitekey) > MAX_SITEKEY_BYTES
|
|
) {
|
|
logger?.warn(
|
|
{
|
|
op: "captcha.misconfigured",
|
|
hasInstance: Boolean(instanceUrl),
|
|
hasSecret: Boolean(secret),
|
|
hasSitekey: Boolean(sitekey),
|
|
failOpen,
|
|
},
|
|
"captcha not configured — applying fail policy",
|
|
);
|
|
return failOpen;
|
|
}
|
|
|
|
if (!token || byteLength(token) > MAX_TOKEN_BYTES) return false;
|
|
|
|
const safeTimeoutMs = Number.isSafeInteger(timeoutMs) && timeoutMs >= 100 && timeoutMs <= 10_000 ? timeoutMs : DEFAULT_TIMEOUT_MS;
|
|
const controller = new AbortController();
|
|
const timeout = setTimeout(() => controller.abort(), safeTimeoutMs);
|
|
try {
|
|
const url = buildSiteverifyUrl({ provider, instanceUrl, sitekey });
|
|
const res = await fetchImpl(url, {
|
|
method: "POST",
|
|
headers: { "content-type": "application/json" },
|
|
body: JSON.stringify(buildSiteverifyBody({ provider, token, sitekey, secret })),
|
|
redirect: "manual",
|
|
signal: controller.signal,
|
|
});
|
|
if (!res.ok) {
|
|
logger?.warn(
|
|
{ op: "captcha.http_error", provider, status: res.status, failOpen },
|
|
"captcha siteverify returned non-OK — applying fail policy",
|
|
);
|
|
return failOpen;
|
|
}
|
|
const data = (await readBoundedJson(res)) as { valid?: boolean; success?: boolean };
|
|
return provider === "cap" ? data.success === true : data.valid === true;
|
|
} catch (err) {
|
|
logger?.warn(
|
|
{
|
|
op: "captcha.error",
|
|
provider,
|
|
errorName: err instanceof Error ? err.name : "UnknownError",
|
|
failOpen,
|
|
},
|
|
"captcha verification failed — applying fail policy",
|
|
);
|
|
return failOpen;
|
|
} finally {
|
|
clearTimeout(timeout);
|
|
}
|
|
}
|
|
|
|
function buildSiteverifyUrl({
|
|
provider,
|
|
instanceUrl,
|
|
sitekey,
|
|
}: {
|
|
provider: CaptchaProvider;
|
|
instanceUrl: string;
|
|
sitekey: string;
|
|
}): string {
|
|
const url = new URL(instanceUrl);
|
|
const isLoopback = url.hostname === "localhost" || url.hostname === "::1" || url.hostname === "[::1]" || url.hostname.startsWith("127.");
|
|
if ((url.protocol !== "https:" && !(url.protocol === "http:" && isLoopback)) || url.username || url.password || url.search || url.hash) {
|
|
throw new Error("Captcha instance URL is not allowed.");
|
|
}
|
|
const basePath = url.pathname.replace(/\/+$/u, "");
|
|
url.pathname = provider === "cap" ? `${basePath}/${encodeURIComponent(sitekey)}/siteverify` : `${basePath}${MCAPTCHA_SITEVERIFY_PATH}`;
|
|
return url.toString();
|
|
}
|
|
|
|
async function readBoundedJson(response: Response): Promise<unknown> {
|
|
const contentType = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
|
|
if (contentType !== "application/json") {
|
|
throw new Error("Captcha response is not JSON.");
|
|
}
|
|
const declaredLength = response.headers.get("content-length");
|
|
if (declaredLength) {
|
|
const parsedLength = Number(declaredLength);
|
|
if (!Number.isSafeInteger(parsedLength) || parsedLength < 0 || parsedLength > MAX_RESPONSE_BYTES) {
|
|
throw new Error("Captcha response is too large.");
|
|
}
|
|
}
|
|
if (!response.body) {
|
|
throw new Error("Captcha response body is missing.");
|
|
}
|
|
|
|
const reader = response.body.getReader();
|
|
const chunks: Uint8Array[] = [];
|
|
let totalBytes = 0;
|
|
try {
|
|
while (true) {
|
|
const { done, value } = await reader.read();
|
|
if (done) break;
|
|
totalBytes += value.byteLength;
|
|
if (totalBytes > MAX_RESPONSE_BYTES) {
|
|
await reader.cancel("captcha response too large");
|
|
throw new Error("Captcha response is too large.");
|
|
}
|
|
chunks.push(value);
|
|
}
|
|
} finally {
|
|
reader.releaseLock();
|
|
}
|
|
|
|
const body = new Uint8Array(totalBytes);
|
|
let offset = 0;
|
|
for (const chunk of chunks) {
|
|
body.set(chunk, offset);
|
|
offset += chunk.byteLength;
|
|
}
|
|
return JSON.parse(new TextDecoder().decode(body));
|
|
}
|
|
|
|
function byteLength(value: string): number {
|
|
return Buffer.byteLength(value, "utf8");
|
|
}
|
|
|
|
function buildSiteverifyBody({
|
|
provider,
|
|
token,
|
|
sitekey,
|
|
secret,
|
|
}: {
|
|
provider: CaptchaProvider;
|
|
token: string;
|
|
sitekey: string;
|
|
secret: string;
|
|
}): Record<string, string> {
|
|
if (provider === "cap") return { response: token, secret };
|
|
return { token, key: sitekey, secret };
|
|
}
|