Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
@@ -2,6 +2,11 @@ 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. */
|
||||
@@ -13,7 +18,7 @@ export type VerifyCaptchaArgs = {
|
||||
/** Base URL of the captcha instance. */
|
||||
instanceUrl: string | undefined;
|
||||
provider?: CaptchaProvider;
|
||||
/** Outage/misconfig policy: true (default) lets the request through. */
|
||||
/** Outage/misconfig policy: false (default) blocks the request. */
|
||||
failOpen?: boolean;
|
||||
logger?: CaptchaLogger;
|
||||
fetchImpl?: typeof fetch;
|
||||
@@ -33,7 +38,7 @@ export type VerifyCaptchaArgs = {
|
||||
*
|
||||
* Semantics:
|
||||
* - missing token -> false (real client failure, never fail-open)
|
||||
* - misconfigured / outage -> `failOpen` (default true), with a warn log
|
||||
* - misconfigured / outage -> `failOpen` (default false), with a warn log
|
||||
* - valid:true -> true, otherwise false
|
||||
*/
|
||||
export async function verifyCaptchaToken({
|
||||
@@ -42,12 +47,19 @@ export async function verifyCaptchaToken({
|
||||
secret,
|
||||
instanceUrl,
|
||||
provider = "mcaptcha",
|
||||
failOpen = true,
|
||||
failOpen = false,
|
||||
logger,
|
||||
fetchImpl = fetch,
|
||||
timeoutMs = DEFAULT_TIMEOUT_MS,
|
||||
}: VerifyCaptchaArgs): Promise<boolean> {
|
||||
if (!instanceUrl || !secret || !sitekey) {
|
||||
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",
|
||||
@@ -61,16 +73,18 @@ export async function verifyCaptchaToken({
|
||||
return failOpen;
|
||||
}
|
||||
|
||||
if (!token) return false;
|
||||
if (!token || byteLength(token) > MAX_TOKEN_BYTES) return false;
|
||||
|
||||
const url = buildSiteverifyUrl({ provider, instanceUrl, sitekey });
|
||||
const safeTimeoutMs = Number.isSafeInteger(timeoutMs) && timeoutMs >= 100 && timeoutMs <= 10_000 ? timeoutMs : DEFAULT_TIMEOUT_MS;
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), timeoutMs);
|
||||
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) {
|
||||
@@ -80,14 +94,14 @@ export async function verifyCaptchaToken({
|
||||
);
|
||||
return failOpen;
|
||||
}
|
||||
const data = (await res.json()) as { valid?: boolean; success?: boolean };
|
||||
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,
|
||||
err: err instanceof Error ? err.message : String(err),
|
||||
errorName: err instanceof Error ? err.name : "UnknownError",
|
||||
failOpen,
|
||||
},
|
||||
"captcha verification failed — applying fail policy",
|
||||
@@ -107,9 +121,61 @@ function buildSiteverifyUrl({
|
||||
instanceUrl: string;
|
||||
sitekey: string;
|
||||
}): string {
|
||||
const base = instanceUrl.replace(/\/+$/, "");
|
||||
if (provider === "cap") return `${base}/${encodeURIComponent(sitekey)}/siteverify`;
|
||||
return base + MCAPTCHA_SITEVERIFY_PATH;
|
||||
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({
|
||||
|
||||
Reference in new issue
Block a user