bigly-chat/client/captcha.js
2024-11-25 14:12:44 -05:00

52 lines
No EOL
1.7 KiB
JavaScript

/* https://raw.githubusercontent.com/napa3um/node-captcha/refs/heads/master/captcha.js */
import Route from "../route.js";
import initDb from "../db.js";
import Canvas from "canvas";
import crypto from "node:crypto";
let db = await initDb();
let main = new Route([], async function (req, res, input) {
const canvas = new Canvas.Canvas(250, 100)
const ctx = canvas.getContext('2d')
ctx.antialias = 'gray'
ctx.fillStyle = 'black'
ctx.fillRect(0, 0, 250, 100)
ctx.fillStyle = 'red'
ctx.lineWidth = 3
ctx.strokeStyle = 'red'
ctx.font = `40px sans`
// draw two curve lines:
for (var i = 0; i < 2; i++) {
ctx.moveTo(Math.floor(0.08 * 250), Math.random() * 100)
ctx.bezierCurveTo(Math.floor(0.32 * 250), Math.random() * 100, Math.floor(1.07 * 100), Math.random() * 100, Math.floor(0.92 * 250), Math.random() * 100)
ctx.stroke()
}
// draw text:
const text = ('' + crypto.randomBytes(4).readUIntBE(0, 4)).substring(2, 10)
text.split('').forEach((char, i) => {
ctx.setTransform(Math.random() * 0.5 + 1, Math.random() * 0.4, Math.random() * 0.4, Math.random() * 0.5 + 1, Math.floor(0.375 * 50) * i + Math.floor(0.25 * 10), Math.floor(1.25 * 40))
ctx.fillText(char, 0, 0)
})
let ck = crypto.randomUUID();
res.cookie('captcha', ck);
await db.run('INSERT INTO captcha (key, solution) VALUES (?,?)', [
ck,
text
])
// send image:
res.type('jpg')
res.header('Cache-Control', 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0')
res.header('Expires', 'Sun, 19 May 1984 02:00:00 GMT')
canvas.jpegStream().pipe(res)
return true;
});
export default main;