captcha-canvas-js
Version:
A simple captcha generator using canvas in JavaScript
45 lines (44 loc) • 1.59 kB
JavaScript
import { createCanvas } from "canvas";
import { randomUUID } from "crypto";
export class Captcha {
store;
options;
constructor(store, options = {}) {
this.store = store;
this.options = options;
}
async generate() {
const { width = 120, height = 40, length = 4, fontSize = 28, charset = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789", background = "#f7f7f7", noise = 3, } = this.options;
const canvas = createCanvas(width, height);
const ctx = canvas.getContext("2d");
ctx.fillStyle = background;
ctx.fillRect(0, 0, width, height);
const text = Array.from({ length }, () => charset.charAt(Math.floor(Math.random() * charset.length))).join("");
ctx.font = `${fontSize}px Arial`;
ctx.fillStyle = "#333";
ctx.fillText(text, 15, fontSize);
ctx.strokeStyle = "#ccc";
for (let i = 0; i < noise; i++) {
ctx.beginPath();
ctx.moveTo(Math.random() * width, Math.random() * height);
ctx.lineTo(Math.random() * width, Math.random() * height);
ctx.stroke();
}
const id = randomUUID();
await this.store.set(id, text.toLowerCase());
return {
id,
text,
imageBase64: canvas.toDataURL("image/png"),
};
}
async verify(id, input) {
const expected = await this.store.get(id);
if (!expected)
return false;
const ok = input.toLowerCase() === expected;
if (ok)
await this.store.delete(id);
return ok;
}
}