const crypto = require('crypto'); const { getDb } = require('./db'); function generate() { const db = getDb(); db.prepare("DELETE FROM captchas WHERE datetime(created_at) < datetime('now','localtime','-5 minutes')").run(); const id = crypto.randomUUID(); const ops = ['+', '-', '\u00d7']; const op = ops[Math.floor(Math.random() * ops.length)]; let a, b, answer; 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]; } if (op === '+') answer = a + b; else if (op === '-') answer = a - b; else answer = a * b; const question = `${a} ${op} ${b} = ?`; db.prepare('INSERT INTO captchas(id, question, answer) VALUES (?,?,?)').run(id, question, String(answer)); return { id, question }; } function verify(id, answer) { const db = getDb(); const row = db.prepare("SELECT * FROM captchas WHERE id = ? AND datetime(created_at) > datetime('now','localtime','-5 minutes')").get(id); if (!row) return false; db.prepare('DELETE FROM captchas WHERE id = ?').run(id); return String(answer).trim() === row.answer; } module.exports = { generate, verify };