fix(captcha): cap Cloudflare checks in flight, and let a blocked widget be retried

- server: at most config.maxConcurrentCaptchaChecks (AJ_CAPTCHA_MAX_CONCURRENT,
  24 by default, 1 to 100) Turnstile checks wait on Cloudflare at once; past
  that the answer is captcha_unavailable at once, so a slow Cloudflare cannot
  hold thousands of sockets open. The page's policy lets it connect to
  challenges.cloudflare.com too.
- page: public/captcha.js gives up on a widget that has not loaded in 15 s,
  or that loaded without turnstile.render, instead of waiting for ever, and a
  render that throws counts as a failed answer. The game's captcha window says
  to check the connection or a content blocker, with a "Try again" button.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
SnipzilandClaude Opus 5.5 committed 2026-10-21 22:24:59 -04:00
1 parent 43f2717b44
commit 974f68490e
4 files changed
+62 -19

No files matched your search

+4
View File
@@ -101,6 +101,10 @@ module.exports = {
// tried or an account is made, with both set. off without them. // tried or an account is made, with both set. off without them.
turnstile: env.AJ_TURNSTILE_SITE_KEY && env.AJ_TURNSTILE_SECRET turnstile: env.AJ_TURNSTILE_SITE_KEY && env.AJ_TURNSTILE_SECRET
? {siteKey: env.AJ_TURNSTILE_SITE_KEY, secret: env.AJ_TURNSTILE_SECRET} : null, ? {siteKey: env.AJ_TURNSTILE_SITE_KEY, secret: env.AJ_TURNSTILE_SECRET} : null,
// A stalled CAPTCHA provider must not consume all of the VPS's outbound
// sockets. This only limits simultaneous verification requests; normal
// players use one, and a rejected request can safely be retried.
maxConcurrentCaptchaChecks: Math.max(1, Math.min(100, Number(env.AJ_CAPTCHA_MAX_CONCURRENT) || 24)),
// Account-recovery mail is delivered to this HTTPS webhook. It receives // Account-recovery mail is delivered to this HTTPS webhook. It receives
// {to, subject, text}; point it at the transactional-mail provider or // {to, subject, text}; point it at the transactional-mail provider or
+13 -1
View File
@@ -26,10 +26,12 @@ const MAX_ANSWER_LENGTH = 2048;
const PASS_MS = 600000; const PASS_MS = 600000;
const PASS_USES = 5; const PASS_USES = 5;
const MAX_PASSES = 10000; const MAX_PASSES = 10000;
const MAX_VERIFYING = config.maxConcurrentCaptchaChecks;
const on = Boolean(config.turnstile); const on = Boolean(config.turnstile);
const passes = new Map(); // SHA-256 of a pass -> {id: account id, key: address key, expiry, uses} const passes = new Map(); // SHA-256 of a pass -> {id: account id, key: address key, expiry, uses}
const sha256 = text => crypto.createHash("sha256").update(String(text)).digest("hex"); const sha256 = text => crypto.createHash("sha256").update(String(text)).digest("hex");
let verifying = 0;
// for the pages: what each answer means // for the pages: what each answer means
const MESSAGES = { const MESSAGES = {
@@ -70,6 +72,13 @@ const verify = async (answer, from, action) => {
if (typeof answer !== "string" || !answer || answer.length > MAX_ANSWER_LENGTH) { if (typeof answer !== "string" || !answer || answer.length > MAX_ANSWER_LENGTH) {
return "captcha_required"; return "captcha_required";
} }
// A burst of valid-looking tokens should not turn an upstream Turnstile
// slowdown into thousands of open fetches on this VPS. Refuse quickly;
// the browser can reset its widget and retry after the short outage.
if (verifying >= MAX_VERIFYING) {
return "captcha_unavailable";
}
verifying++;
const form = new URLSearchParams({secret: config.turnstile.secret, response: answer}); const form = new URLSearchParams({secret: config.turnstile.secret, response: answer});
if (!limits.isLoopback(from.address)) { if (!limits.isLoopback(from.address)) {
form.set("remoteip", from.address); form.set("remoteip", from.address);
@@ -83,6 +92,9 @@ const verify = async (answer, from, action) => {
console.log(`[captcha] cloudflare did not answer: ${logText(err.message)}`); console.log(`[captcha] cloudflare did not answer: ${logText(err.message)}`);
return "captcha_unavailable"; return "captcha_unavailable";
} }
finally {
verifying--;
}
// an answer made for another form is no answer for this one. cloudflare's // an answer made for another form is no answer for this one. cloudflare's
// test keys give none. // test keys give none.
if (!result || result.success !== true || (result.action && result.action !== action)) { if (!result || result.success !== true || (result.action && result.action !== action)) {
@@ -107,7 +119,7 @@ const check = async (body, from, action, account) => {
// a page's security policy: public/captcha.js always (the page calls it even // a page's security policy: public/captcha.js always (the page calls it even
// when off), and the widget too when it is on. // when off), and the widget too when it is on.
const policy = csp => (on const policy = csp => (on
? `${csp.replace("script-src ", `script-src 'self' ${ORIGIN} `)}; frame-src ${ORIGIN}` ? `${csp.replace("script-src ", `script-src 'self' ${ORIGIN} `).replace("connect-src ", `connect-src 'self' ${ORIGIN} `)}; frame-src ${ORIGIN}`
: csp.replace("script-src ", "script-src 'self' ")); : csp.replace("script-src ", "script-src 'self' "));
// a page with public/captcha.js asked for under a name that changes with the // a page with public/captcha.js asked for under a name that changes with the
+7 -1
View File
@@ -25,17 +25,21 @@
-webkit-font-smoothing: antialiased; -webkit-font-smoothing: antialiased;
} }
#status { margin: 0; text-align: center; } #status { margin: 0; text-align: center; }
button { display: none; border: 1px solid #8c8c8c; border-radius: 5px; padding: 6px 12px; background: transparent; color: #ddd; font: inherit; cursor: pointer; }
button.show { display: block; }
</style> </style>
</head> </head>
<body> <body>
<div id="widget"></div> <div id="widget"></div>
<p id="status" role="status">Checking…</p> <p id="status" role="status">Checking…</p>
<button id="retry" type="button">Try again</button>
<script src="/captcha.js"></script> <script src="/captcha.js"></script>
<script> <script>
"use strict"; "use strict";
const action = new URLSearchParams(location.search).get("action") === "signup" ? "signup" : "login"; const action = new URLSearchParams(location.search).get("action") === "signup" ? "signup" : "login";
const status = document.getElementById("status"); const status = document.getElementById("status");
const retry = document.getElementById("retry");
const done = token => { const done = token => {
if (window.burrowCaptcha) { if (window.burrowCaptcha) {
window.burrowCaptcha.done(token); window.burrowCaptcha.done(token);
@@ -53,10 +57,12 @@
}}); }});
check.answer().then(token => { check.answer().then(token => {
if (!token) { if (!token) {
status.textContent = "Captcha failed. Close this and try again."; status.textContent = "Captcha could not load. Check your connection or content blocker.";
retry.classList.add("show");
} }
}); });
} }
retry.addEventListener("click", () => location.reload());
</script> </script>
</body> </body>
</html> </html>
+38 -17
View File
@@ -10,14 +10,29 @@
// captcha.FAILED then), and check.reset() after it: an answer is good once. // captcha.FAILED then), and check.reset() after it: an answer is good once.
window.captcha = (() => { window.captcha = (() => {
const siteKey = "{{siteKey}}"; const siteKey = "{{siteKey}}";
const LOAD_TIMEOUT_MS = 15000;
let loading = null; let loading = null;
const load = () => { const load = () => {
loading = loading || new Promise((resolve, reject) => { loading = loading || new Promise((resolve, reject) => {
const script = document.createElement("script"); const script = document.createElement("script");
script.src = "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit"; script.src = "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit";
script.onload = () => resolve(window.turnstile); const timer = setTimeout(() => {
loading = null;
reject(new Error("the captcha took too long to load"));
}, LOAD_TIMEOUT_MS);
script.onload = () => {
clearTimeout(timer);
if (window.turnstile && typeof window.turnstile.render === "function") {
resolve(window.turnstile);
}
else {
loading = null;
reject(new Error("the captcha did not start"));
}
};
script.onerror = () => { script.onerror = () => {
clearTimeout(timer);
loading = null; loading = null;
reject(new Error("the captcha did not load")); reject(new Error("the captcha did not load"));
}; };
@@ -44,21 +59,27 @@ window.captcha = (() => {
}; };
if (siteKey) { if (siteKey) {
load().then(turnstile => { load().then(turnstile => {
widget = turnstile.render(element, { try {
sitekey: siteKey, widget = turnstile.render(element, {
action, sitekey: siteKey,
theme: "dark", action,
appearance: options.appearance || "interaction-only", theme: "dark",
callback: settle, appearance: options.appearance || "interaction-only",
"expired-callback": () => { callback: settle,
answer = null; "expired-callback": () => {
}, answer = null;
// its code is cloudflare's (110200: this site's name is not on the widget) },
"error-callback": code => { // its code is cloudflare's (110200: this site's name is not on the widget)
console.log(`captcha error ${code}`); "error-callback": code => {
settle(""); console.log(`captcha error ${code}`);
}, settle("");
}); },
});
}
catch (err) {
console.log(`captcha could not start: ${err.message}`);
settle("");
}
}, () => settle("")); }, () => settle(""));
} }
return { return {
@@ -79,5 +100,5 @@ window.captcha = (() => {
}; };
}; };
return {on: Boolean(siteKey), mount, FAILED: "Captcha could not load. Reload the page."}; return {on: Boolean(siteKey), mount, FAILED: "Captcha could not load. Check your connection or content blocker, then reload."};
})(); })();