227 lines
11 KiB
JavaScript
227 lines
11 KiB
JavaScript
"use strict";
|
|
|
|
// adpanel:captcha-hostname-default — pins + behavior for the DERIVED default
|
|
// hostname pin. When CAPTCHA_EXPECTED_HOSTNAMES is entirely unset, the
|
|
// hCaptcha branch of verifyExternalCaptcha opts into a pin derived from
|
|
// PANEL_PUBLIC_URL (the deployment's canonical public origin). Guarantees
|
|
// held here:
|
|
// 1. the default is derived ONLY from PANEL_PUBLIC_URL via the canonical
|
|
// normalizeHostLower(parseOriginHost(...)) pair — the exact twin of the
|
|
// _CSRF_PANEL_PUBLIC_HOST derivation — never from a request header;
|
|
// 2. an explicit env value overrides the default byte-identically; an
|
|
// explicit BLANK env value keeps the historical off behavior and
|
|
// disables the default too (operator kill switch);
|
|
// 3. only the hCaptcha branch opts in ({ useDefault: true }) — the
|
|
// Turnstile/reCAPTCHA branches' guard calls stay byte-identical (their
|
|
// providers are domain-bound at token issuance);
|
|
// 4. under the default, a foreign or missing hostname fails closed with
|
|
// the existing shared failure shape { ok: false, error:
|
|
// "captcha-hostname-not-allowed" } and exact match semantics;
|
|
// 5. a one-time unpinned warning exists, wired once-per-process, fired at
|
|
// startup and lazily from verifyExternalCaptcha (covers Settings
|
|
// hot-enable).
|
|
|
|
const test = require("node:test");
|
|
const assert = require("node:assert");
|
|
const fs = require("node:fs");
|
|
const path = require("node:path");
|
|
|
|
const ROOT = path.join(__dirname, "..");
|
|
const INDEX_JS = path.join(ROOT, "index.js");
|
|
const GUARD_JS = path.join(ROOT, "utils", "captcha-expected-hostnames.js");
|
|
|
|
const {
|
|
CAPTCHA_EXPECTED_HOSTNAMES_ENV,
|
|
CAPTCHA_HOSTNAME_MISMATCH_ERROR,
|
|
normalizeCaptchaDefaultHostnames,
|
|
createCaptchaHostnameGuard,
|
|
} = require("../utils/captcha-expected-hostnames");
|
|
|
|
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
|
|
const guardSource = fs.readFileSync(GUARD_JS, "utf8");
|
|
|
|
function countOccurrences(haystack, needle) {
|
|
let count = 0;
|
|
let at = haystack.indexOf(needle);
|
|
while (at >= 0) {
|
|
count += 1;
|
|
at = haystack.indexOf(needle, at + 1);
|
|
}
|
|
return count;
|
|
}
|
|
|
|
function extractVerifyExternalCaptchaBody(source) {
|
|
const start = source.indexOf("async function verifyExternalCaptcha(token, remoteIp) {");
|
|
assert.ok(start >= 0, "verifyExternalCaptcha(token, remoteIp) must exist in index.js");
|
|
const end = source.indexOf("\nfunction cloneJsonPayload(", start);
|
|
assert.ok(end > start, "cloneJsonPayload must follow verifyExternalCaptcha (update this pin if the function moves)");
|
|
return source.slice(start, end);
|
|
}
|
|
|
|
function failure(result, message) {
|
|
assert.ok(result, `expected a failure object, got null (allowed)${message ? `: ${message}` : ""}`);
|
|
assert.strictEqual(result.ok, false, message);
|
|
assert.strictEqual(result.error, CAPTCHA_HOSTNAME_MISMATCH_ERROR, message);
|
|
assert.strictEqual(Object.keys(result).length, 2, "failure shape is exactly { ok, error }");
|
|
}
|
|
|
|
// Behavior: the default pin activates ONLY when the env var is absent.
|
|
const PANEL_HOST = "panel.example.com";
|
|
|
|
function guardWithEnv(envValue, defaults = [PANEL_HOST]) {
|
|
const env = envValue === undefined ? {} : { [CAPTCHA_EXPECTED_HOSTNAMES_ENV]: envValue };
|
|
return createCaptchaHostnameGuard({ env, defaultHostnames: defaults });
|
|
}
|
|
|
|
test("default pin activates only when the env var is entirely unset", () => {
|
|
const guard = guardWithEnv(undefined);
|
|
assert.strictEqual(guard.enabled, false, "env pin is off");
|
|
assert.strictEqual(guard.defaultEnabled, true, "derived default is on");
|
|
assert.strictEqual(guard.pinActive, true, "a pin is effective");
|
|
assert.deepStrictEqual(guard.defaultHostnames, [PANEL_HOST]);
|
|
assert.strictEqual(
|
|
guard.check({ success: true, hostname: PANEL_HOST }, { useDefault: true }),
|
|
null,
|
|
"the deployment's own hostname passes"
|
|
);
|
|
failure(guard.check({ success: true, hostname: "attacker.example" }, { useDefault: true }), "attacker-solved hostname rejected");
|
|
failure(guard.check({ success: true }, { useDefault: true }), "missing hostname fails closed under the default");
|
|
failure(guard.check(null, { useDefault: true }), "non-object response fails closed under the default");
|
|
});
|
|
|
|
test("an explicit non-empty env value overrides the default byte-identically", () => {
|
|
const guard = guardWithEnv("other.example");
|
|
assert.strictEqual(guard.enabled, true);
|
|
assert.strictEqual(guard.defaultEnabled, false, "default must not coexist with the env list");
|
|
assert.deepStrictEqual(guard.expectedHostnames, ["other.example"]);
|
|
assert.strictEqual(guard.check({ success: true, hostname: "other.example" }, { useDefault: true }), null);
|
|
failure(guard.check({ success: true, hostname: PANEL_HOST }, { useDefault: true }), "the derived default list is ignored when env is set");
|
|
failure(guard.check({ success: true, hostname: "attacker.example" }, { useDefault: true }));
|
|
});
|
|
|
|
test("an explicit blank env value keeps the historical off behavior and disables the default", () => {
|
|
for (const raw of ["", " ", ",", " , , "]) {
|
|
const guard = guardWithEnv(raw);
|
|
assert.strictEqual(guard.enabled, false, `raw=${JSON.stringify(raw)} must be off`);
|
|
assert.strictEqual(guard.defaultEnabled, false, `raw=${JSON.stringify(raw)} must disable the default`);
|
|
assert.strictEqual(guard.pinActive, false, `raw=${JSON.stringify(raw)} leaves no effective pin`);
|
|
assert.strictEqual(
|
|
guard.check({ success: true, hostname: "attacker.example" }, { useDefault: true }),
|
|
null,
|
|
`raw=${JSON.stringify(raw)} keeps the historical only-success behavior`
|
|
);
|
|
}
|
|
});
|
|
|
|
test("no default hostnames configured means unpinned even for opt-in callers", () => {
|
|
const guard = createCaptchaHostnameGuard({ env: {}, defaultHostnames: [] });
|
|
assert.strictEqual(guard.defaultEnabled, false);
|
|
assert.strictEqual(guard.pinActive, false);
|
|
assert.strictEqual(
|
|
guard.check({ success: true, hostname: "attacker.example" }, { useDefault: true }),
|
|
null,
|
|
"the deployment shape without PANEL_PUBLIC_URL behaves exactly as before"
|
|
);
|
|
});
|
|
|
|
test("default pin never applies to callers that do not opt in", () => {
|
|
const guard = guardWithEnv(undefined);
|
|
assert.strictEqual(guard.check({ success: true, hostname: "attacker.example" }), null, "no opts: off");
|
|
assert.strictEqual(guard.check({ success: true, hostname: "attacker.example" }, {}), null, "empty opts: off");
|
|
assert.strictEqual(guard.check({ success: true, hostname: "attacker.example" }, { useDefault: false }), null, "explicit false: off");
|
|
assert.strictEqual(guard.check({ success: true, hostname: "attacker.example" }, { useDefault: "yes" }), null, "non-boolean truthy is not an opt-in");
|
|
});
|
|
|
|
test("default matching is exact after trim + lowercase (no subdomain or suffix smuggling)", () => {
|
|
const guard = guardWithEnv(undefined, ["Panel.Example.COM"]);
|
|
assert.strictEqual(guard.check({ success: true, hostname: "panel.example.com" }, { useDefault: true }), null);
|
|
assert.strictEqual(guard.check({ success: true, hostname: "PANEL.EXAMPLE.COM" }, { useDefault: true }), null);
|
|
assert.strictEqual(guard.check({ success: true, hostname: " panel.example.com " }, { useDefault: true }), null);
|
|
failure(guard.check({ success: true, hostname: "sub.panel.example.com" }, { useDefault: true }), "subdomains are not implied");
|
|
failure(guard.check({ success: true, hostname: "evilpanel.example.com" }, { useDefault: true }));
|
|
failure(guard.check({ success: true, hostname: "panel.example.com.evil.test" }, { useDefault: true }));
|
|
});
|
|
|
|
test("default hostnames are normalized like the env list (trim, lowercase, dedupe)", () => {
|
|
assert.deepStrictEqual(
|
|
normalizeCaptchaDefaultHostnames([" Panel.Example.COM ", "", "b.example", "panel.example.com"]),
|
|
["panel.example.com", "b.example"]
|
|
);
|
|
assert.deepStrictEqual(normalizeCaptchaDefaultHostnames(undefined), []);
|
|
assert.deepStrictEqual(normalizeCaptchaDefaultHostnames(null), []);
|
|
assert.deepStrictEqual(normalizeCaptchaDefaultHostnames([123, null, {}]), []);
|
|
});
|
|
|
|
test("env-pin-only guard still reports a pin as active (warn stays silent)", () => {
|
|
const guard = guardWithEnv("env.example");
|
|
assert.strictEqual(guard.pinActive, true);
|
|
});
|
|
|
|
// Source pins on index.js wiring.
|
|
|
|
test("pins: the default hostname comes only from PANEL_PUBLIC_URL via the canonical derivation", () => {
|
|
const derivation = 'const _CAPTCHA_DEFAULT_HOSTNAME = normalizeHostLower(parseOriginHost(process.env.PANEL_PUBLIC_URL || ""));';
|
|
assert.ok(
|
|
indexSource.includes(derivation),
|
|
"index.js must derive the default pin from PANEL_PUBLIC_URL with the exact normalizeHostLower(parseOriginHost(...)) pair"
|
|
);
|
|
assert.ok(
|
|
indexSource.includes('_CSRF_PANEL_PUBLIC_HOST = normalizeHostLower(parseOriginHost(process.env.PANEL_PUBLIC_URL || ""))'),
|
|
"the _CSRF_PANEL_PUBLIC_HOST twin derivation exists — the two must stay in lockstep"
|
|
);
|
|
const derivationAt = indexSource.indexOf(derivation);
|
|
const constructionAt = indexSource.indexOf("createCaptchaHostnameGuard({");
|
|
assert.ok(
|
|
derivationAt >= 0 && constructionAt > derivationAt,
|
|
"the derivation is module-eval-time and precedes the guard construction"
|
|
);
|
|
});
|
|
|
|
test("pins: only the hCaptcha branch opts into the default pin", () => {
|
|
const body = extractVerifyExternalCaptchaBody(indexSource);
|
|
assert.strictEqual(
|
|
countOccurrences(body, "captchaHostnameGuard.check(res.json"),
|
|
3,
|
|
"all three provider branches still consult the shared guard exactly once (prefix form: the hCaptcha call carries the opt-in argument)"
|
|
);
|
|
assert.strictEqual(
|
|
countOccurrences(body, "captchaHostnameGuard.check(res.json);"),
|
|
2,
|
|
"the Turnstile and reCAPTCHA branches keep the byte-identical plain call (no default opt-in)"
|
|
);
|
|
assert.strictEqual(
|
|
countOccurrences(body, "captchaHostnameGuard.check(res.json, { useDefault: true })"),
|
|
1,
|
|
"exactly one branch opts into the derived default"
|
|
);
|
|
const hcaptchaAt = body.indexOf("EXTERNAL_CAPTCHA_IS_HCAPTCHA");
|
|
const optInAt = body.indexOf("captchaHostnameGuard.check(res.json, { useDefault: true })");
|
|
const recaptchaAt = body.indexOf("https://www.google.com/recaptcha/api/siteverify");
|
|
assert.ok(hcaptchaAt >= 0 && recaptchaAt > hcaptchaAt, "both branch markers found in order");
|
|
assert.ok(
|
|
optInAt > hcaptchaAt && optInAt < recaptchaAt,
|
|
"the { useDefault: true } opt-in lives inside the hCaptcha branch, before the reCAPTCHA branch"
|
|
);
|
|
});
|
|
|
|
test("pins: one-time unpinned warning is once-per-process and wired at both entry points", () => {
|
|
assert.ok(
|
|
countOccurrences(indexSource, "captchaHostnamePinWarningPrinted = true") === 1,
|
|
"exactly one flag flip — the warning prints at most once per process"
|
|
);
|
|
assert.ok(indexSource.includes("function warnIfCaptchaHostnamePinMissing()"), "the warn helper exists");
|
|
assert.ok(
|
|
countOccurrences(indexSource, "warnIfCaptchaHostnamePinMissing();") >= 2,
|
|
"fired at startup (module eval) and lazily from verifyExternalCaptcha"
|
|
);
|
|
const body = extractVerifyExternalCaptchaBody(indexSource);
|
|
assert.ok(
|
|
body.includes("warnIfCaptchaHostnamePinMissing();"),
|
|
"verifyExternalCaptcha carries the lazy call so Settings hot-enable is covered"
|
|
);
|
|
assert.ok(
|
|
!guardSource.includes("console."),
|
|
"the warning lives in index.js; the guard module stays pure"
|
|
);
|
|
});
|