"use strict"; // adpanel:siteverify-hardened-dial — pins + behavior for the shared hardened // siteverify dial (providerSiteverifyRequest in index.js). The three // verifyExternalCaptcha provider branches (Turnstile/hCaptcha/reCAPTCHA) must // dial through ONE helper carrying the repo's non-negotiable outbound-client // posture (mirroring services/node-http.js httpRequestJson): // 1. exactly one helper, all three branches migrated (no inline // https.request dials left in verifyExternalCaptcha); // 2. response 'error' AND 'aborted' listeners (attached at the TOP of the // response callback, BEFORE the Content-Length pre-check's early // return) + request 'error'/'timeout' listeners, under a single-settle // finish discipline; // 3. a hard TOTAL-duration deadline that strictly exceeds the 6s IDLE // timeout (idle only fires while no bytes move; the total deadline // bounds slow-drip providers that keep bytes flowing); // 4. a response body-size cap (providers return tiny JSON verdicts) with // settle-BEFORE-destroy ordering; // 5. rejections carry a "captcha-siteverify:" label and each branch maps // them to the exact { status: 0, json: null } shape the old req-error // path produced, so the route's 400 verification-failed mapping is // unchanged; // 6. request shape per branch is preserved (POST + branch headers + the // idle timeout as the request option). const test = require("node:test"); const assert = require("node:assert"); const fs = require("node:fs"); const path = require("node:path"); const vm = require("node:vm"); const EventEmitter = require("node:events"); const ROOT = path.join(__dirname, ".."); const INDEX_JS = path.join(ROOT, "index.js"); const indexSource = fs.readFileSync(INDEX_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; } // Same body extraction the captcha-hostname pins use: verifyExternalCaptcha // runs from its declaration to the next top-level function. 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"); return source.slice(start, end); } // The helper + its constants live immediately BEFORE verifyExternalCaptcha // (outside the body slice above, so the hostname pins' body stays dial-free). function extractHelperSource(source) { const start = source.indexOf("const SITEVERIFY_IDLE_TIMEOUT_MS = "); assert.ok(start >= 0, "SITEVERIFY_IDLE_TIMEOUT_MS must exist in index.js"); const end = source.indexOf("\n}", start); assert.ok(end > start, "the helper's top-level closing brace must follow the constants"); return source.slice(start, end + 2); } const HELPER_SOURCE = extractHelperSource(indexSource); const VERIFY_BODY = extractVerifyExternalCaptchaBody(indexSource); // --------------------------------------------------------------------------- // Source pins. // --------------------------------------------------------------------------- test("pins: exactly one hardened helper, all three branches migrated onto it", () => { assert.ok( indexSource.includes("// adpanel:siteverify-hardened-dial"), "the topic comment documenting the provider-bound posture exists" ); assert.strictEqual( countOccurrences(indexSource, "function providerSiteverifyRequest("), 1, "exactly ONE hardened siteverify dial helper (no forked copies)" ); assert.strictEqual( countOccurrences(indexSource, "await providerSiteverifyRequest({"), 3, "all three provider branches dial through the helper" ); assert.strictEqual( countOccurrences(VERIFY_BODY, "https.request("), 0, "no raw https.request dial remains inside verifyExternalCaptcha" ); const helperAt = indexSource.indexOf("function providerSiteverifyRequest("); const verifyAt = indexSource.indexOf("async function verifyExternalCaptcha(token, remoteIp) {"); assert.ok(helperAt >= 0 && helperAt < verifyAt, "the helper is defined before its callers"); }); test("pins: the helper carries the full hardened listener set, single-settle", () => { for (const listener of [ 'r.on("data"', 'r.on("end"', 'r.on("error"', 'r.on("aborted"', 'req.on("error"', 'req.on("timeout"', ]) { assert.strictEqual( countOccurrences(HELPER_SOURCE, listener), 1, `the helper registers ${listener} exactly once` ); } assert.strictEqual( countOccurrences(HELPER_SOURCE, "if (settled) return;"), 2, "single-settle: both the resolve and reject paths guard on the settled flag" ); // Settle-BEFORE-destroy: the labeled rejection is recorded before // destroy() so the destroy-induced 'aborted' can never win the race. const rejectAt = HELPER_SOURCE.indexOf("reject(new Error("); const destroyAt = HELPER_SOURCE.indexOf("req.destroy()"); assert.ok(rejectAt >= 0 && destroyAt > rejectAt, "fail() rejects before destroying the request"); // Attach-FIRST ordering: the response listeners are registered at the top // of the response callback — BEFORE the Content-Length pre-check whose // fail() → req.destroy() can induce late response events. The pre-fix // ordering (fail-then-return, attach-after) left the IncomingMessage // listener-free in that window; an unlistened 'error' event is the // worker-crash class, so this position is load-bearing. const errorAt = HELPER_SOURCE.indexOf('r.on("error"'); const abortedAt = HELPER_SOURCE.indexOf('r.on("aborted"'); const clFailAt = HELPER_SOURCE.indexOf('fail("response-exceeds-size-cap")'); const dataAt = HELPER_SOURCE.indexOf('r.on("data"'); assert.ok(errorAt >= 0 && abortedAt >= 0, "response error/aborted listeners exist"); assert.ok(errorAt < clFailAt && abortedAt < clFailAt, "response error/aborted listeners attach BEFORE the Content-Length pre-check"); assert.ok(errorAt < dataAt && abortedAt < dataAt, "response error/aborted listeners attach before the data listener"); }); test("pins: total deadline strictly exceeds the idle timeout; body cap is 256 KiB", () => { const idle = /const SITEVERIFY_IDLE_TIMEOUT_MS = (\d+);/.exec(HELPER_SOURCE); const total = /const SITEVERIFY_TOTAL_DEADLINE_MS = (\d+);/.exec(HELPER_SOURCE); assert.ok(idle && total, "both timeout constants are declared"); assert.strictEqual(Number(idle[1]), 6000, "the 6s idle timeout is preserved from the old inline dials"); assert.strictEqual(Number(total[1]), 8000, "the hard total deadline is 8s"); assert.ok(Number(total[1]) > Number(idle[1]), "total deadline MUST exceed the idle timeout"); assert.ok( /const SITEVERIFY_MAX_RESPONSE_BYTES = 256 \* 1024;/.test(HELPER_SOURCE), "the response body cap is 256 KiB" ); assert.ok( HELPER_SOURCE.includes("timeout: SITEVERIFY_IDLE_TIMEOUT_MS"), "the idle timeout stays on the request options (socket-inactivity 'timeout' event)" ); assert.ok( HELPER_SOURCE.includes('captcha-siteverify:'), "rejections carry the captcha-siteverify: label" ); }); test("pins: every branch maps a rejection to the exact legacy req-error failure shape", () => { const body = VERIFY_BODY; for (const url of [ "https://challenges.cloudflare.com/turnstile/v0/siteverify", "https://api.hcaptcha.com/siteverify", "https://www.google.com/recaptcha/api/siteverify", ]) { assert.strictEqual( countOccurrences(body, url), 1, `${url} stays at its call site exactly once` ); } const turnstileAt = body.indexOf("https://challenges.cloudflare.com/turnstile/v0/siteverify"); const hcaptchaAt = body.indexOf("https://api.hcaptcha.com/siteverify"); const recaptchaAt = body.indexOf("https://www.google.com/recaptcha/api/siteverify"); assert.ok(turnstileAt < hcaptchaAt && hcaptchaAt < recaptchaAt, "branch order preserved"); assert.strictEqual( countOccurrences(body, ".catch(() => ({ status: 0, json: null }))"), 3, "each branch maps helper rejection to the exact { status: 0, json: null } shape the old req-error path produced" ); // The success/guard/failure flow the hostname pins hold is untouched. assert.strictEqual( countOccurrences(body, 'return { ok: false, error: "captcha-validation-failed" }'), 3, "each branch keeps its own success check" ); }); // --------------------------------------------------------------------------- // Functional harness: the helper source is evaluated in a vm with a stubbed // https module so every failure class is drivable (slow-drip, over-cap, // connection error) without a real provider. // --------------------------------------------------------------------------- class FakeRequest extends EventEmitter { constructor() { super(); this.written = []; this.ended = false; this.destroyed = false; } write(chunk) { this.written.push(chunk); return true; } end() { this.ended = true; return this; } destroy() { this.destroyed = true; return this; } } class FakeResponse extends EventEmitter { constructor({ statusCode = 200, headers = {} } = {}) { super(); this.statusCode = statusCode; this.headers = headers; } } // Loads the real helper source in a vm sandbox. Constants may be shrunk for // timer tests (the real values are pinned separately above); a stubbed https // records every request so tests can drive its events. function loadHelper({ idleMs, totalMs, capBytes, stubTimers = false } = {}) { let src = HELPER_SOURCE; if (idleMs !== undefined) { const next = src.replace(/const SITEVERIFY_IDLE_TIMEOUT_MS = \d+;/, `const SITEVERIFY_IDLE_TIMEOUT_MS = ${idleMs};`); assert.notStrictEqual(next, src, "idle constant must exist to be overridden"); src = next; } if (totalMs !== undefined) { const next = src.replace(/const SITEVERIFY_TOTAL_DEADLINE_MS = \d+;/, `const SITEVERIFY_TOTAL_DEADLINE_MS = ${totalMs};`); assert.notStrictEqual(next, src, "total constant must exist to be overridden"); src = next; } if (capBytes !== undefined) { const next = src.replace(/const SITEVERIFY_MAX_RESPONSE_BYTES = [^;]+;/, `const SITEVERIFY_MAX_RESPONSE_BYTES = ${capBytes};`); assert.notStrictEqual(next, src, "cap constant must exist to be overridden"); src = next; } const captured = { requests: [] }; const timers = { created: [], cleared: [] }; const fakeHttps = { request(url, opts, cb) { const req = new FakeRequest(); captured.requests.push({ url, opts, cb, req }); return req; }, }; const sandbox = { https: fakeHttps, Buffer, console }; if (stubTimers) { sandbox.setTimeout = (fn, ms) => { const id = { fn, ms }; timers.created.push(id); return id; }; sandbox.clearTimeout = (id) => { timers.cleared.push(id); }; } else { sandbox.setTimeout = setTimeout; sandbox.clearTimeout = clearTimeout; } vm.createContext(sandbox); vm.runInContext(`${src}\n;providerSiteverifyRequest;`, sandbox, { filename: "providerSiteverifyRequest.extracted.js", }); return { helper: sandbox.providerSiteverifyRequest, captured, timers }; } function lastRequest(captured) { assert.ok(captured.requests.length > 0, "the helper must have issued a request"); return captured.requests[captured.requests.length - 1]; } test("functional: a normal small response parses exactly as before", async () => { const { helper, captured, timers } = loadHelper({ stubTimers: true }); const headers = { "Content-Type": "application/json", "Content-Length": 15 }; const p = helper({ url: "https://provider.test/siteverify", body: '{"x":1}', headers }); const { url, opts, cb, req } = lastRequest(captured); assert.strictEqual(url, "https://provider.test/siteverify"); assert.strictEqual(opts.method, "POST", "method shape preserved"); assert.deepStrictEqual(opts.headers, headers, "branch headers passed through verbatim"); assert.strictEqual(opts.timeout, 6000, "the idle timeout stays on the request options"); assert.deepStrictEqual(req.written, ['{"x":1}'], "the body is written"); assert.strictEqual(req.ended, true, "the request is ended"); const res = new FakeResponse({ statusCode: 200 }); cb(res); res.emit("data", Buffer.from('{"success":true,"hostname":"panel.example.com"}')); res.emit("end"); // JSON round-trip: the helper runs in a vm realm, so its result object // carries that realm's prototype; the round-trip also proves the resolved // shape is plain JSON data. assert.deepStrictEqual( JSON.parse(JSON.stringify(await p)), { status: 200, json: { success: true, hostname: "panel.example.com" } }, "parsed verdict shape identical to the old inline dial" ); // The deadline timer must be released on success (no leaked 8s timer). assert.strictEqual(timers.created.length, 1, "exactly one deadline timer was scheduled"); assert.strictEqual(timers.created[0].ms, 8000, "the deadline is the total-duration constant"); assert.ok(timers.cleared.includes(timers.created[0]), "the deadline timer is cleared on settle"); }); test("functional: a non-JSON 200 body still resolves { status, json: null }", async () => { const { helper, captured } = loadHelper(); const p = helper({ url: "https://provider.test/siteverify", body: "b", headers: {} }); const { cb } = lastRequest(captured); const res = new FakeResponse({ statusCode: 200 }); cb(res); res.emit("data", Buffer.from("not json")); res.emit("end"); assert.deepStrictEqual(JSON.parse(JSON.stringify(await p)), { status: 200, json: null }); }); test("functional: slow-drip beyond the total deadline is cut off with a labeled rejection", async () => { const { helper, captured } = loadHelper({ idleMs: 60, totalMs: 180, capBytes: 1024 }); const p = helper({ url: "https://provider.test/siteverify", body: "b", headers: {} }); const { cb, req } = lastRequest(captured); const res = new FakeResponse({ statusCode: 200 }); cb(res); // A byte every 20ms keeps socket inactivity (and thus a real idle timeout) // from ever firing — only the hard total deadline can bound this dial. const drip = setInterval(() => res.emit("data", Buffer.from("aaaaaaaa")), 20); const startedAt = Date.now(); try { await assert.rejects( p, (err) => err.message === "captcha-siteverify: total-deadline-exceeded", "the total deadline rejects with its label" ); } finally { clearInterval(drip); } const elapsed = Date.now() - startedAt; assert.ok(elapsed < 5000, `the deadline fired in bounded time (took ${elapsed}ms)`); assert.strictEqual(req.destroyed, true, "the deadline path destroys the request"); }); test("functional: an oversized accumulated body is rejected with the cap label, destroy-first-safe", async () => { const { helper, captured } = loadHelper({ capBytes: 64 }); const p = helper({ url: "https://provider.test/siteverify", body: "b", headers: {} }); const { cb, req } = lastRequest(captured); const res = new FakeResponse({ statusCode: 200 }); cb(res); res.emit("data", Buffer.alloc(100, "a")); await assert.rejects( p, (err) => err.message === "captcha-siteverify: response-exceeds-size-cap", "an over-cap body rejects with its label" ); assert.strictEqual(req.destroyed, true, "the cap path destroys the request"); // Settle-before-destroy discipline: late destroy-induced events are no-ops. res.emit("aborted"); res.emit("error", new Error("late after destroy")); req.emit("error", new Error("late after destroy")); }); test("functional: an over-cap Content-Length is rejected before any body byte", async () => { const { helper, captured } = loadHelper({ capBytes: 64 }); const p = helper({ url: "https://provider.test/siteverify", body: "b", headers: {} }); const { cb, req } = lastRequest(captured); const res = new FakeResponse({ statusCode: 200, headers: { "content-length": "1000" } }); cb(res); await assert.rejects( p, (err) => err.message === "captcha-siteverify: response-exceeds-size-cap", "the Content-Length pre-check rejects with the same cap label" ); assert.strictEqual(req.destroyed, true); }); test("functional: CL-over-cap keeps listeners attached — a post-destroy response error is a labeled no-op, not a crash", async () => { // The reviewer's empirical scenario: the Content-Length pre-check fails on // the response's FIRST byte and fail() → req.destroy() fires, yet the // destroyed response can still emit 'error' (RST) or 'aborted'. With the // pre-fix ordering (fail-then-return, attach-after) the IncomingMessage // sat listener-free in that window — and Node throws on an 'error' event // with no listener, so the res.emit("error") below IS the crash probe: it // must be swallowed by the guarded listener, not escape the emit call. const { helper, captured } = loadHelper({ capBytes: 64 }); const p = helper({ url: "https://provider.test/siteverify", body: "b", headers: {} }); const { cb, req } = lastRequest(captured); const res = new FakeResponse({ statusCode: 200, headers: { "content-length": "1000" } }); cb(res); await assert.rejects( p, (err) => err.message === "captcha-siteverify: response-exceeds-size-cap", "the over-cap dial rejects with its cap label first" ); assert.strictEqual(req.destroyed, true, "the cap path destroyed the request"); // Late destroy-induced events (RST / peer abort): single-settle no-ops. // This line throws synchronously if the listeners were not attached before // the pre-check's early return — i.e. the test fails on the pre-fix order. res.emit("error", new Error("ECONNRESET after destroy")); res.emit("aborted"); }); test("functional: a provider connection error rejects with its label and maps to the legacy failure shape", async () => { const { helper, captured } = loadHelper(); const p = helper({ url: "https://provider.test/siteverify", body: "b", headers: {} }); const { req } = lastRequest(captured); req.emit("error", new Error("ECONNREFUSED")); await assert.rejects( p, (err) => err.message === "captcha-siteverify: request-error", "a request-level error rejects with its label" ); assert.strictEqual(req.destroyed, true); // The branch mapping: rejection → the exact shape the old req-error path // resolved, which the route turns into 400 verification-failed. const p2 = helper({ url: "https://provider.test/siteverify", body: "b", headers: {} }); const { req: req2 } = lastRequest(captured); req2.emit("error", new Error("ECONNREFUSED")); const mapped = await p2.catch(() => ({ status: 0, json: null })); assert.deepStrictEqual(mapped, { status: 0, json: null }, "the branch catch shape is the legacy one"); }); test("functional: mid-response error/aborted and the idle timeout reject with their labels", async () => { for (const [eventName, label] of [ ["error", "response-error"], ["aborted", "response-aborted"], ]) { const { helper, captured } = loadHelper(); const p = helper({ url: "https://provider.test/siteverify", body: "b", headers: {} }); const { cb, req } = lastRequest(captured); const res = new FakeResponse({ statusCode: 200 }); cb(res); res.emit("data", Buffer.from('{"succ')); res.emit(eventName, new Error("reset")); await assert.rejects(p, (err) => err.message === `captcha-siteverify: ${label}`); assert.strictEqual(req.destroyed, true); } const { helper, captured } = loadHelper(); const p = helper({ url: "https://provider.test/siteverify", body: "b", headers: {} }); const { req } = lastRequest(captured); req.emit("timeout"); await assert.rejects( p, (err) => err.message === "captcha-siteverify: idle-timeout", "the socket-idle timeout rejects with its label" ); assert.strictEqual(req.destroyed, true, "the idle-timeout path destroys the request"); }); test("functional: single-settle — late events after a settled response are no-ops", async () => { const { helper, captured } = loadHelper(); const p = helper({ url: "https://provider.test/siteverify", body: "b", headers: {} }); const { cb, req } = lastRequest(captured); const res = new FakeResponse({ statusCode: 200 }); cb(res); res.emit("data", Buffer.from('{"success":true}')); res.emit("end"); assert.deepStrictEqual( JSON.parse(JSON.stringify(await p)), { status: 200, json: { success: true } } ); // Everything the real transport could still emit after completion: res.emit("error", new Error("late")); res.emit("aborted"); req.emit("error", new Error("late")); req.emit("timeout"); });