Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -36,10 +36,13 @@ describe("resolveCaptchaConfig", () => {
expect(isCaptchaConfigured(cfg)).toBe(true);
});
it("defaults failOpen to true and respects explicit false", () => {
expect(resolveCaptchaConfig({}).failOpen).toBe(true);
it("defaults failOpen to false and honors opt-in only in local runtimes", () => {
expect(resolveCaptchaConfig({}).failOpen).toBe(false);
expect(resolveCaptchaConfig({ CAPTCHA_FAIL_OPEN: "false" }).failOpen).toBe(false);
expect(resolveCaptchaConfig({ CAPTCHA_FAIL_OPEN: "true" }).failOpen).toBe(true);
expect(resolveCaptchaConfig({ CAPTCHA_FAIL_OPEN: "true" }).failOpen).toBe(false);
expect(resolveCaptchaConfig({ NODE_ENV: "development", CAPTCHA_FAIL_OPEN: "true" }).failOpen).toBe(true);
expect(resolveCaptchaConfig({ NODE_ENV: "test", CAPTCHA_FAIL_OPEN: "true" }).failOpen).toBe(true);
expect(resolveCaptchaConfig({ NODE_ENV: "production", CAPTCHA_FAIL_OPEN: "true" }).failOpen).toBe(false);
});
it("treats blank env values as undefined and reports unconfigured", () => {
@@ -21,7 +21,7 @@ function present(value: string | undefined): string | undefined {
* CAP_SITE_SECRET_LOGIN / _FORMS / _BOOKING=<per-surface site secrets>
* CAP_SITEKEY_LOGIN / _FORMS / _BOOKING=<public sitekeys>
*
* CAPTCHA_FAIL_OPEN=true|false (default true)
* CAPTCHA_FAIL_OPEN=true|false (development/test only; default false)
*/
export function resolveCaptchaConfig(env: EnvLike): CaptchaConfig {
const provider = resolveProvider(env);
@@ -41,7 +41,7 @@ export function resolveCaptchaConfig(env: EnvLike): CaptchaConfig {
forms: present(env.CAP_SITE_SECRET_FORMS) ?? sharedSecret,
booking: present(env.CAP_SITE_SECRET_BOOKING) ?? sharedSecret,
},
failOpen: present(env.CAPTCHA_FAIL_OPEN) !== "false",
failOpen: resolveFailOpen(env),
};
}
@@ -60,10 +60,15 @@ export function resolveCaptchaConfig(env: EnvLike): CaptchaConfig {
forms: accountSecret,
booking: accountSecret,
},
failOpen: present(env.CAPTCHA_FAIL_OPEN) !== "false",
failOpen: resolveFailOpen(env),
};
}
function resolveFailOpen(env: EnvLike): boolean {
const runtime = present(env.NODE_ENV)?.toLowerCase();
return (runtime === "development" || runtime === "test") && present(env.CAPTCHA_FAIL_OPEN)?.toLowerCase() === "true";
}
function resolveProvider(env: EnvLike): CaptchaProvider {
const explicit = present(env.CAPTCHA_PROVIDER)?.toLowerCase();
if (explicit === "cap") return "cap";
@@ -22,8 +22,8 @@ export type CaptchaConfig = {
secrets: Record<CaptchaSurface, string | undefined>;
/**
* When the instance is unreachable/misconfigured: true = let the request
* through (fail-open, default), false = block it (fail-closed). A missing
* token is always a hard failure regardless of this flag.
* through, false = block it (secure default). Fail-open is honored only in
* development/test; a missing token is always a hard failure.
*/
failOpen: boolean;
};
@@ -1,4 +1,4 @@
import { describe, it, expect } from "vitest";
import { describe, it, expect, vi } from "vitest";
import { verifyCaptchaToken } from "./verify.js";
const base = {
@@ -9,20 +9,21 @@ const base = {
};
function jsonResponse(body: unknown, ok = true, status = 200): Response {
return {
ok,
status,
json: async () => body,
} as unknown as Response;
return new Response(JSON.stringify(body), {
status: ok ? status : status || 500,
headers: { "content-type": "application/json" },
});
}
describe("verifyCaptchaToken", () => {
it("returns true when mCaptcha reports valid", async () => {
let calledUrl = "";
let calledBody: unknown = null;
let calledInit: RequestInit | undefined;
const fetchImpl = (async (url: string, init?: RequestInit) => {
calledUrl = url;
calledBody = JSON.parse(String(init?.body));
calledInit = init;
return jsonResponse({ valid: true });
}) as unknown as typeof fetch;
@@ -30,6 +31,7 @@ describe("verifyCaptchaToken", () => {
expect(ok).toBe(true);
expect(calledUrl).toBe("https://captcha.example.test/api/v1/pow/siteverify");
expect(calledBody).toEqual({ token: "pow-token", key: "site-key", secret: "account-secret" });
expect(calledInit?.redirect).toBe("manual");
});
it("returns true when Cap reports success", async () => {
@@ -62,11 +64,11 @@ describe("verifyCaptchaToken", () => {
expect(await verifyCaptchaToken({ ...base, token: "", fetchImpl })).toBe(false);
});
it("fails open (true) on network error by default", async () => {
it("fails closed (false) on network error by default", async () => {
const fetchImpl = (async () => {
throw new Error("ECONNREFUSED");
}) as unknown as typeof fetch;
expect(await verifyCaptchaToken({ ...base, fetchImpl })).toBe(true);
expect(await verifyCaptchaToken({ ...base, fetchImpl })).toBe(false);
});
it("fails closed (false) on network error when failOpen=false", async () => {
@@ -76,16 +78,40 @@ describe("verifyCaptchaToken", () => {
expect(await verifyCaptchaToken({ ...base, failOpen: false, fetchImpl })).toBe(false);
});
it("fails open on non-OK HTTP status", async () => {
it("fails closed on non-OK HTTP status by default", async () => {
const fetchImpl = (async () => jsonResponse({}, false, 502)) as unknown as typeof fetch;
expect(await verifyCaptchaToken({ ...base, fetchImpl })).toBe(true);
expect(await verifyCaptchaToken({ ...base, fetchImpl })).toBe(false);
});
it("applies fail policy when misconfigured (no secret)", async () => {
const fetchImpl = (async () => jsonResponse({ valid: true })) as unknown as typeof fetch;
expect(await verifyCaptchaToken({ ...base, secret: undefined, fetchImpl })).toBe(true);
expect(await verifyCaptchaToken({ ...base, secret: undefined, fetchImpl })).toBe(false);
expect(await verifyCaptchaToken({ ...base, secret: undefined, failOpen: true, fetchImpl })).toBe(true);
expect(
await verifyCaptchaToken({ ...base, secret: undefined, failOpen: false, fetchImpl }),
).toBe(false);
});
it("rejects non-HTTPS non-loopback instance URLs before fetch", async () => {
const fetchImpl = vi.fn() as unknown as typeof fetch;
expect(await verifyCaptchaToken({ ...base, instanceUrl: "http://captcha.example.test", fetchImpl })).toBe(false);
expect(fetchImpl).not.toHaveBeenCalled();
});
it("allows HTTP only for a loopback development instance", async () => {
const fetchImpl = vi.fn(async () => jsonResponse({ valid: true })) as unknown as typeof fetch;
expect(await verifyCaptchaToken({ ...base, instanceUrl: "http://127.0.0.1:7000", fetchImpl })).toBe(true);
expect(fetchImpl).toHaveBeenCalledWith("http://127.0.0.1:7000/api/v1/pow/siteverify", expect.objectContaining({ redirect: "manual" }));
});
it("fails closed when the provider response exceeds the hard limit", async () => {
const fetchImpl = (async () => jsonResponse({ valid: true, padding: "x".repeat(70 * 1024) })) as unknown as typeof fetch;
expect(await verifyCaptchaToken({ ...base, fetchImpl })).toBe(false);
});
it("rejects oversized challenge tokens before fetch", async () => {
const fetchImpl = vi.fn() as unknown as typeof fetch;
expect(await verifyCaptchaToken({ ...base, token: "x".repeat(9 * 1024), fetchImpl })).toBe(false);
expect(fetchImpl).not.toHaveBeenCalled();
});
});
@@ -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({