captcha-canvas-js
v1.0.5
Published
A simple captcha generator using canvas in JavaScript
Maintainers
Readme
📦 captcha-canvas-js
A lightweight, framework-independent image captcha generator for Node.js — supports base64 output, in-memory or custom storage, and easy integration with Express, NestJS, Koa, etc.
✨ Features
- ✅ Generate random text-based image captchas (PNG)
- ✅ Supports Base64 image output
- ✅ Pluggable storage (in-memory, Redis, etc.)
- ✅ Fully written in TypeScript
- ✅ Framework-agnostic: works with Express, NestJS, Koa, etc.
- ✅ Includes CAPTCHA verification method
📦 Installation
npm install or
pnpm add captcha-canvas-js🧱 Usage Example (Basic)
import { Captcha, MemoryStore } from "captcha-canvas-js";
const captcha = new Captcha(new MemoryStore());
const { id, imageBase64, text } = await captcha.generate();
console.log("Captcha ID:", id);
console.log("Captcha Text:", text); // You may skip logging this in production
console.log("Image (base64):", imageBase64);
// Later verify:
const isValid = await captcha.verify(id, "user-input");🧩 API
new Captcha(store: CaptchaStore, options?: CaptchaOptions)
store: storage object (e.g.,MemoryStore, or your own)options: optional customization:
{
width?: number; // default: 120
height?: number; // default: 40
length?: number; // number of characters (default: 4)
fontSize?: number; // default: 28
charset?: string; // default: A-Z + 2-9 (excluding O, I, 1)
background?: string; // e.g., "#f7f7f7"
noise?: number; // number of random lines (default: 3)
}await captcha.generate(): Promise<CaptchaResult>
Returns:
{
id: string;
text: string;
imageBase64: string; // starts with "data:image/png;base64,..."
}await captcha.verify(id: string, input: string): Promise<boolean>
Checks if the user input matches the stored captcha text.
🗃 Storage
✅ Built-in: MemoryStore
In-memory temporary store (auto-expire in 3 minutes by default).
✅ Custom Store Interface
You can implement your own CaptchaStore (e.g., Redis):
export interface CaptchaStore {
set(id: string, value: string): Promise<void>;
get(id: string): Promise<string | null>;
delete(id: string): Promise<void>;
}🔒 Security Notes
- Avoid exposing
textin production - Always expire stored captchas (e.g., 3–5 minutes)
- Rate limit captcha generation per IP/user if needed
🧪 Development
# build for ESM and CommonJS
npm run build📄 License
notice
- The published package may have errors
- We will continue to update
❤️ Author
Created by alias-- yiqishuyuan
