UNPKG

captcha-canvas-js

Version:

A simple captcha generator using canvas in JavaScript

49 lines (48 loc) 1.74 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Captcha = void 0; const canvas_1 = require("canvas"); const crypto_1 = require("crypto"); 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 = (0, canvas_1.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 = (0, crypto_1.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; } } exports.Captcha = Captcha;