games_app/backend/dist-test-faq/services/captchaService.js

163 lines
5.9 KiB
JavaScript

"use strict";
/**
* Login captcha: Cloudflare Turnstile when configured, otherwise built-in math challenge.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getCaptchaProvider = getCaptchaProvider;
exports.getCaptchaSiteKey = getCaptchaSiteKey;
exports.isCaptchaAvailable = isCaptchaAvailable;
exports.isCaptchaConfigured = isCaptchaConfigured;
exports.createMathChallenge = createMathChallenge;
exports.createLoginCaptchaChallenge = createLoginCaptchaChallenge;
exports.verifyCaptchaToken = verifyCaptchaToken;
exports.withCaptchaChallenge = withCaptchaChallenge;
const crypto_1 = __importDefault(require("crypto"));
const config_1 = require("../config");
function captchaHmacSecret() {
return config_1.config.turnstile.secretKey || config_1.config.jwt.secret || 'captcha-dev-secret';
}
function b64url(buf) {
const b = typeof buf === 'string' ? Buffer.from(buf, 'utf8') : buf;
return b.toString('base64url');
}
function signMathPayload(payload) {
const body = b64url(JSON.stringify(payload));
const sig = crypto_1.default.createHmac('sha256', captchaHmacSecret()).update(body).digest('base64url');
return `${body}.${sig}`;
}
function parseMathChallengeToken(token) {
const [body, sig] = token.split('.');
if (!body || !sig)
return null;
const expected = crypto_1.default.createHmac('sha256', captchaHmacSecret()).update(body).digest('base64url');
const a = Buffer.from(sig);
const b = Buffer.from(expected);
if (a.length !== b.length || !crypto_1.default.timingSafeEqual(a, b))
return null;
try {
const parsed = JSON.parse(Buffer.from(body, 'base64url').toString('utf8'));
if (typeof parsed?.a !== 'number' ||
typeof parsed?.b !== 'number' ||
typeof parsed?.exp !== 'number') {
return null;
}
return parsed;
}
catch {
return null;
}
}
/** Turnstile is preferred when secret key is present. */
function getCaptchaProvider() {
return config_1.config.turnstile.secretKey ? 'turnstile' : 'math';
}
function getCaptchaSiteKey() {
return config_1.config.turnstile.siteKey || null;
}
/** Captcha is available whenever the admin threshold is positive (math fallback always works). */
function isCaptchaAvailable(afterFailures) {
return afterFailures > 0;
}
/** @deprecated Prefer isCaptchaAvailable(afterFailures) — kept for call sites during transition. */
function isCaptchaConfigured() {
return true;
}
function createMathChallenge() {
const a = 2 + crypto_1.default.randomInt(8); // 2..9
const b = 2 + crypto_1.default.randomInt(8);
const exp = Date.now() + 5 * 60 * 1000;
const challengeToken = signMathPayload({ a, b, exp });
return {
provider: 'math',
challengeToken,
prompt: `${a} + ${b} = ?`,
};
}
function createLoginCaptchaChallenge() {
if (getCaptchaProvider() === 'turnstile') {
return {
provider: 'turnstile',
siteKey: getCaptchaSiteKey(),
};
}
return createMathChallenge();
}
function captchaError(message, code) {
const err = new Error(message);
err.code = code;
return err;
}
function verifyMathToken(token) {
if (!token?.trim()) {
throw captchaError('Captcha verification is required', 'CAPTCHA_REQUIRED');
}
const raw = token.trim();
// Expected: math:<challengeToken>:<answer>
if (!raw.startsWith('math:')) {
throw captchaError('Captcha verification failed', 'CAPTCHA_INVALID');
}
const rest = raw.slice('math:'.length);
const lastColon = rest.lastIndexOf(':');
if (lastColon <= 0) {
throw captchaError('Captcha verification failed', 'CAPTCHA_INVALID');
}
const challengeToken = rest.slice(0, lastColon);
const answerRaw = rest.slice(lastColon + 1).trim();
const payload = parseMathChallengeToken(challengeToken);
if (!payload) {
throw captchaError('Captcha verification failed', 'CAPTCHA_INVALID');
}
if (Date.now() > payload.exp) {
throw captchaError('Captcha verification failed', 'CAPTCHA_INVALID');
}
const answer = Number.parseInt(answerRaw, 10);
if (!Number.isFinite(answer) || answer !== payload.a + payload.b) {
throw captchaError('Captcha verification failed', 'CAPTCHA_INVALID');
}
}
async function verifyTurnstileToken(token, remoteIp) {
if (!token?.trim()) {
throw captchaError('Captcha verification is required', 'CAPTCHA_REQUIRED');
}
if (token.trim().startsWith('math:')) {
// Client sent math token while Turnstile is configured
throw captchaError('Captcha verification failed', 'CAPTCHA_INVALID');
}
const body = new URLSearchParams({
secret: config_1.config.turnstile.secretKey,
response: token.trim(),
});
if (remoteIp)
body.set('remoteip', remoteIp);
const res = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body,
});
if (!res.ok) {
throw new Error('Captcha verification service unavailable');
}
const data = (await res.json());
if (!data.success) {
throw captchaError('Captcha verification failed', 'CAPTCHA_INVALID');
}
}
/** Verifies login captcha using Turnstile or built-in math challenge. */
async function verifyCaptchaToken(token, remoteIp) {
if (getCaptchaProvider() === 'turnstile') {
await verifyTurnstileToken(token, remoteIp);
return;
}
verifyMathToken(token);
}
/** Attach a fresh challenge to captcha errors for the client. */
function withCaptchaChallenge(err) {
if (err.code === 'CAPTCHA_REQUIRED' || err.code === 'CAPTCHA_INVALID') {
err.captcha = createLoginCaptchaChallenge();
}
return err;
}
//# sourceMappingURL=captchaService.js.map