feat: SVG image captcha with noise and color distortion

This commit is contained in:
2026-07-13 18:33:31 +08:00
parent befd51dbd5
commit bc16833a57
4 changed files with 70 additions and 22 deletions

View File

@@ -1,4 +1,5 @@
const express = require('express');
const svgCaptcha = require('svg-captcha');
const crypto = require('crypto');
const { query } = require('../db');
@@ -7,16 +8,19 @@ const router = express.Router();
router.get('/', async (req, res) => {
try {
await query("DELETE FROM captchas WHERE created_at < NOW() - INTERVAL 5 MINUTE");
const captcha = svgCaptcha.create({
size: 4,
noise: 3,
color: true,
background: '#f4f4f4',
width: 120,
height: 44,
fontSize: 40,
ignoreChars: '0oO1iIl',
});
const id = crypto.randomUUID();
const ops = ['+', '-', '\u00d7'];
const op = ops[Math.floor(Math.random() * ops.length)];
let a, b;
if (op === '\u00d7') { a = Math.floor(Math.random() * 9) + 1; b = Math.floor(Math.random() * 9) + 1; }
else { a = Math.floor(Math.random() * 20) + 1; b = Math.floor(Math.random() * 10) + 1; if (op === '-' && a < b) [a, b] = [b, a]; }
const answer = op === '+' ? a + b : op === '-' ? a - b : a * b;
const question = `${a} ${op} ${b} = ?`;
await query('INSERT INTO captchas(id, question, answer) VALUES (?,?,?)', [id, question, String(answer)]);
res.json({ id, question });
await query('INSERT INTO captchas(id, question, answer) VALUES (?,?,?)', [id, '', captcha.text.toLowerCase()]);
res.json({ id, svg: captcha.data });
} catch (e) { res.status(500).json({ error: e.message }); }
});
@@ -24,7 +28,7 @@ async function verify(id, answer) {
const rows = await query("SELECT * FROM captchas WHERE id = ? AND created_at > NOW() - INTERVAL 5 MINUTE", [id]);
if (!rows.length) return false;
await query('DELETE FROM captchas WHERE id = ?', [id]);
return String(answer).trim() === rows[0].answer;
return String(answer).trim().toLowerCase() === rows[0].answer;
}
module.exports = router;