UNPKG

captcha-canvas

Version:

A captcha generator by using skia-canvas module.

72 lines (71 loc) 2.36 kB
"use strict"; /** * Input validation utilities for CAPTCHA generation parameters */ Object.defineProperty(exports, "__esModule", { value: true }); exports.validateDimensions = validateDimensions; exports.validateText = validateText; exports.validateColor = validateColor; exports.validateNumericRange = validateNumericRange; /** * Validates and sanitizes dimension parameters */ function validateDimensions(width, height) { // Prevent extremely large images that could cause memory issues const MAX_DIMENSION = 2000; const MIN_DIMENSION = 50; if (!Number.isInteger(width) || !Number.isInteger(height)) { throw new Error('Dimensions must be integers'); } if (width < MIN_DIMENSION || width > MAX_DIMENSION) { throw new Error(`Width must be between ${MIN_DIMENSION} and ${MAX_DIMENSION} pixels`); } if (height < MIN_DIMENSION || height > MAX_DIMENSION) { throw new Error(`Height must be between ${MIN_DIMENSION} and ${MAX_DIMENSION} pixels`); } return { width, height }; } /** * Validates text content for security */ function validateText(text) { if (typeof text !== 'string') { throw new Error('Text must be a string'); } // Prevent excessively long text if (text.length > 50) { throw new Error('Text length cannot exceed 50 characters'); } // Remove potentially dangerous characters const sanitized = text.replace(/[<>'"&]/g, ''); if (sanitized.length === 0) { throw new Error('Text cannot be empty after sanitization'); } return sanitized; } /** * Validates color values */ function validateColor(color) { if (typeof color !== 'string') { throw new Error('Color must be a string'); } // Basic color validation (hex, rgb, named colors) const colorRegex = /^(#[0-9A-Fa-f]{3,8}|rgb\([^)]+\)|rgba\([^)]+\)|[a-zA-Z]+)$/; if (!colorRegex.test(color)) { throw new Error('Invalid color format'); } return color; } /** * Validates numeric parameters with bounds */ function validateNumericRange(value, min, max, name) { if (typeof value !== 'number' || !Number.isFinite(value)) { throw new Error(`${name} must be a finite number`); } if (value < min || value > max) { throw new Error(`${name} must be between ${min} and ${max}`); } return value; }