@arcis/node 1.4.2 → 1.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/core/constants.d.ts +1 -1
- package/dist/core/constants.d.ts.map +1 -1
- package/dist/core/index.js.map +1 -1
- package/dist/core/index.mjs.map +1 -1
- package/dist/core/types.d.ts +6 -0
- package/dist/core/types.d.ts.map +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +405 -20
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +402 -21
- package/dist/index.mjs.map +1 -1
- package/dist/logging/index.js.map +1 -1
- package/dist/logging/index.mjs.map +1 -1
- package/dist/middleware/bot-detection.d.ts.map +1 -1
- package/dist/middleware/cookies.d.ts.map +1 -1
- package/dist/middleware/csrf.d.ts +10 -0
- package/dist/middleware/csrf.d.ts.map +1 -1
- package/dist/middleware/hpp.d.ts.map +1 -1
- package/dist/middleware/index.d.ts +2 -0
- package/dist/middleware/index.d.ts.map +1 -1
- package/dist/middleware/index.js +609 -9
- package/dist/middleware/index.js.map +1 -1
- package/dist/middleware/index.mjs +608 -10
- package/dist/middleware/index.mjs.map +1 -1
- package/dist/middleware/main.d.ts.map +1 -1
- package/dist/middleware/rate-limit.d.ts.map +1 -1
- package/dist/middleware/signup-protection.d.ts +65 -0
- package/dist/middleware/signup-protection.d.ts.map +1 -0
- package/dist/middleware/telemetry.d.ts +36 -0
- package/dist/middleware/telemetry.d.ts.map +1 -0
- package/dist/sanitizers/index.js +26 -8
- package/dist/sanitizers/index.js.map +1 -1
- package/dist/sanitizers/index.mjs +26 -8
- package/dist/sanitizers/index.mjs.map +1 -1
- package/dist/sanitizers/pii.d.ts.map +1 -1
- package/dist/sanitizers/ssti.d.ts.map +1 -1
- package/dist/sanitizers/xxe.d.ts.map +1 -1
- package/dist/stores/index.js.map +1 -1
- package/dist/stores/index.mjs.map +1 -1
- package/dist/telemetry/client.d.ts +60 -0
- package/dist/telemetry/client.d.ts.map +1 -0
- package/dist/telemetry/index.d.ts +3 -0
- package/dist/telemetry/index.d.ts.map +1 -0
- package/dist/telemetry/types.d.ts +59 -0
- package/dist/telemetry/types.d.ts.map +1 -0
- package/dist/validation/index.js +3 -0
- package/dist/validation/index.js.map +1 -1
- package/dist/validation/index.mjs +3 -0
- package/dist/validation/index.mjs.map +1 -1
- package/package.json +7 -1
package/dist/stores/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/core/constants.ts","../../src/stores/memory.ts","../../src/stores/redis.ts"],"names":[],"mappings":";;;AAkBO,IAAM,UAAA,GAAa;AAAA;AAAA,EAExB,iBAAA,EAAmB,GAAA;AAAA,EAMF;AAAA,EAEjB,aAAA,EAAe,GAGjB,CAAA;;;ACbA,IAAM,gBAAA,GAAmB,GAAA;AAElB,IAAM,cAAN,MAA4C;AAAA,EAMjD,WAAA,CAAY,QAAA,GAAmB,UAAA,CAAW,iBAAA,EAAmB,UAAkB,gBAAA,EAAkB;AALjG,IAAA,IAAA,CAAQ,KAAA,uBAAyC,GAAA,EAAI;AACrD,IAAA,IAAA,CAAQ,eAAA,GAAyD,IAAA;AAK/D,IAAA,IAAI,CAAC,MAAA,CAAO,QAAA,CAAS,QAAQ,CAAA,IAAK,QAAA,GAAW,WAAW,aAAA,EAAe;AACrE,MAAA,MAAM,IAAI,UAAA;AAAA,QACR,CAAA,iDAAA,EAAoD,UAAA,CAAW,aAAa,CAAA,MAAA,EAAS,QAAQ,CAAA,CAAA;AAAA,OAC/F;AAAA,IACF;AACA,IAAA,IAAI,CAAC,MAAA,CAAO,QAAA,CAAS,OAAO,CAAA,IAAK,UAAU,CAAA,EAAG;AAC5C,MAAA,MAAM,IAAI,UAAA,CAAW,CAAA,uCAAA,EAA0C,OAAO,CAAA,CAAA,CAAG,CAAA;AAAA,IAC3E;AACA,IAAA,IAAA,CAAK,QAAA,GAAW,QAAA;AAChB,IAAA,IAAA,CAAK,O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GAAQ,MAAM,IAAA,CAAK,MAAA,CAAO,KAAK,QAAQ,CAAA;AAK7C,IAAA,IAAI,UAAU,CAAA,EAAG;AACf,MAAA,MAAM,IAAA,CAAK,MAAA,CAAO,MAAA,CAAO,QAAA,EAAU,KAAK,SAAS,CAAA;AAAA,IACnD;AAEA,IAAA,OAAO,KAAA;AAAA,EACT;AAAA,EAEA,MAAM,UAAU,GAAA,EAA4B;AAC1C,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,MAAA,CAAO,GAAG,CAAA;AAChC,IAAA,MAAM,IAAA,CAAK,MAAA,CAAO,IAAA,CAAK,QAAQ,CAAA;AAAA,EACjC;AAAA,EAEA,MAAM,MAAM,GAAA,EAA4B;AACtC,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,MAAA,CAAO,GAAG,CAAA;AAChC,IAAA,MAAM,IAAA,CAAK,MAAA,CAAO,GAAA,CAAI,QAAQ,CAAA;AAAA,EAChC;AAAA,EAEA,MAAM,KAAA,GAAuB;AAAA,EAG7B;AACF;AASO,SAAS,iBAAiB,OAAA,EAAwC;AACvE,EAAA,OAAO,IAAI,WAAW,OAAO,CAAA;AAC/B","file":"index.js","sourcesContent":["/**\n * @module @arcis/node/core/constants\n * Named constants for Arcis - no magic numbers\n */\n\n// =============================================================================\n// INPUT LIMITS\n// =============================================================================\nexport const INPUT = {\n /** Default maximum input size (1MB) */\n DEFAULT_MAX_SIZE: 1_000_000,\n /** Maximum recursion depth for nested objects */\n MAX_RECURSION_DEPTH: 10,\n} as const;\n\n// =============================================================================\n// RATE LIMITING\n// =============================================================================\nexport const RATE_LIMIT = {\n /** Default window size (1 minute) */\n DEFAULT_WINDOW_MS: 60_000,\n /** Default max requests per window */\n DEFAULT_MAX_REQUESTS: 100,\n /** Default HTTP status code for rate limited responses */\n DEFAULT_STATUS_CODE: 429,\n /** Default error message */\n DEFAULT_MESSAGE: 'Too many requests, please try again later.',\n /** Minimum window size (1 second) */\n MIN_WINDOW_MS: 1_000,\n /** Maximum window size (24 hours) */\n MAX_WINDOW_MS: 86_400_000,\n} as const;\n\n// =============================================================================\n// SECURITY HEADERS\n// =============================================================================\nexport const HEADERS = {\n /** Default Content Security Policy */\n DEFAULT_CSP: [\n \"default-src 'self'\",\n \"script-src 'self'\",\n \"style-src 'self' 'unsafe-inline'\",\n \"img-src 'self' data: https:\",\n \"font-src 'self'\",\n \"object-src 'none'\",\n \"frame-ancestors 'none'\",\n ].join('; '),\n /** Default HSTS max age (1 year in seconds) */\n HSTS_MAX_AGE: 31_536_000,\n /** Default X-Frame-Options value */\n FRAME_OPTIONS: 'DENY' as const,\n /** Default X-Content-Type-Options value */\n CONTENT_TYPE_OPTIONS: 'nosniff',\n /** Default Referrer-Policy value */\n REFERRER_POLICY: 'strict-origin-when-cross-origin',\n /** Default Permissions-Policy value */\n PERMISSIONS_POLICY: 'geolocation=(), microphone=(), camera=()',\n /** Default Cache-Control value for security */\n CACHE_CONTROL: 'no-store, no-cache, must-revalidate, proxy-revalidate',\n} as const;\n\n// =============================================================================\n// XSS PATTERNS (ReDoS-safe)\n// =============================================================================\n\n/**\n * Detection patterns — used to flag whether a string contains XSS payloads.\n * Must stay in sync with XSS_REMOVE_PATTERNS below.\n */\nexport const XSS_PATTERNS = [\n /** Script tags (ReDoS-safe version) */\n /<script[^>]*>[\\s\\S]*?<\\/script>/gi,\n /** javascript: protocol (allow optional spaces before colon) */\n /javascript\\s*:/gi,\n /** vbscript: protocol */\n /vbscript\\s*:/gi,\n /** Event handlers (onclick, onerror, etc.) — any separator before attribute */\n /(?:[\\s/])on\\w+\\s*=/gi,\n /** iframe tags */\n /<iframe/gi,\n /** object tags */\n /<object/gi,\n /** embed tags */\n /<embed/gi,\n /** data: URIs (only dangerous ones, avoid false positives) */\n /(?:^|[\\s\"'=])data:/gi,\n /** URL-encoded script tags */\n /%3Cscript/gi,\n /** SVG with onload */\n /<svg[^>]*onload/gi,\n /** form tags — phishing/credential harvesting via action= redirection */\n /<form[\\s>]/gi,\n /** meta tags — http-equiv refresh redirects or CSP bypass */\n /<meta[\\s>]/gi,\n /** base href hijacking — redirects all relative URLs to attacker domain */\n /<base[\\s>]/gi,\n /** link tag injection — stylesheet or preload CSRF attacks */\n /<link[\\s>]/gi,\n] as const;\n\n/**\n * Removal patterns — used by sanitizeXss() to strip dangerous content.\n * More targeted than XSS_PATTERNS: each pattern captures the full dangerous\n * substring (tag, attribute + value, protocol) so it can be replaced safely.\n * Must stay in sync with XSS_PATTERNS above.\n */\nexport const XSS_REMOVE_PATTERNS = [\n /** Full script blocks (content + tags) */\n /<script[^>]*>[\\s\\S]*?<\\/script>/gi,\n /** Standalone/unclosed script tags */\n /<script[^>]*>/gi,\n /** iframe — full block and partial/unclosed */\n /<iframe[^>]*>[\\s\\S]*?<\\/iframe>/gi,\n /<iframe[^>]*/gi,\n /** object — full block and partial/unclosed */\n /<object[^>]*>[\\s\\S]*?<\\/object>/gi,\n /<object[^>]*/gi,\n /** embed tags */\n /<embed[^>]*/gi,\n /** SVG with inline event handlers */\n /<svg[^>]*onload[^>]*>/gi,\n /** URL-encoded script tags */\n /%3Cscript/gi,\n /** Event handlers with quoted values: onclick=\"...\", onerror='...' */\n /(?:[\\s/])on\\w+\\s*=\\s*[\"'][^\"']*[\"']/gi,\n /** Event handlers with unquoted values: onload=value */\n /(?:[\\s/])on\\w+\\s*=\\s*[^\\s>]*/gi,\n /** javascript: and vbscript: protocols (allow optional spaces before colon) */\n /javascript\\s*:/gi,\n /vbscript\\s*:/gi,\n /** data: URIs with HTML/script content */\n /data\\s*:\\s*text\\/html[^>\\s]*/gi,\n /** form tag injection — phishing via action= redirection */\n /<form[\\s>][^>]*/gi,\n /** meta tag injection — http-equiv refresh or CSP bypass */\n /<meta[\\s>][^>]*/gi,\n /** base href hijacking */\n /<base[\\s>][^>]*/gi,\n /** link tag injection — stylesheet or preload attacks */\n /<link[\\s>][^>]*/gi,\n] as const;\n\n// =============================================================================\n// SQL INJECTION PATTERNS\n// =============================================================================\nexport const SQL_PATTERNS = [\n /** SQL keywords */\n /(\\b(SELECT|INSERT|UPDATE|DELETE|DROP|UNION|ALTER|CREATE|TRUNCATE|EXEC|EXECUTE)\\b)/gi,\n /** SQL comments: ANSI (--), C-style (slash-star ... star-slash), MySQL (#) */\n /(--|\\/\\*|\\*\\/|#)/g,\n /** SQL statement separators */\n /(;|\\|\\||&&)/g,\n /** Boolean injection: OR 1=1 */\n /\\bOR\\s+\\d+\\s*=\\s*\\d+/gi,\n /** Boolean injection: OR 'a'='a' or OR \"a\"=\"a\" (including mixed quotes) */\n /\\bOR\\s+(['\"])[^'\"]*\\1\\s*=\\s*(['\"])[^'\"]*\\2/gi,\n /\\bOR\\s+('[^']*'|\"[^\"]*\")\\s*=\\s*('[^']*'|\"[^\"]*\")/gi,\n /** Boolean injection: AND 1=1 */\n /\\bAND\\s+\\d+\\s*=\\s*\\d+/gi,\n /** Boolean injection: AND 'a'='a' or AND \"a\"=\"a\" (including mixed quotes) */\n /\\bAND\\s+(['\"])[^'\"]*\\1\\s*=\\s*(['\"])[^'\"]*\\2/gi,\n /\\bAND\\s+('[^']*'|\"[^\"]*\")\\s*=\\s*('[^']*'|\"[^\"]*\")/gi,\n /** Time-based blind: SLEEP() */\n /\\bSLEEP\\s*\\(\\s*\\d+\\s*\\)/gi,\n /** Time-based blind: BENCHMARK() */\n /\\bBENCHMARK\\s*\\(/gi,\n /** Time-based blind: PostgreSQL pg_sleep() */\n /\\bpg_sleep\\s*\\(/gi,\n /** Time-based blind: MSSQL WAITFOR DELAY */\n /\\bWAITFOR\\s+DELAY\\b/gi,\n] as const;\n\n// =============================================================================\n// PATH TRAVERSAL PATTERNS\n// =============================================================================\nexport const PATH_PATTERNS = [\n /** Unix path traversal */\n /\\.\\.\\//g,\n /** Windows path traversal */\n /\\.\\.\\\\/g,\n /** URL-encoded traversal (%2e%2e) */\n /%2e%2e/gi,\n /** Double URL-encoded traversal (%252e) */\n /%252e/gi,\n /** Mixed encoding: ..%2F */\n /\\.\\.%2F/gi,\n /** Mixed encoding: %2e./ and .%2e/ */\n /%2e\\.[\\\\/]/gi,\n /\\.%2e[\\\\/]/gi,\n /** Fully URL-encoded: %2e%2e%2f */\n /%2e%2e%2f/gi,\n /** Double URL-encoded forward slash: %252f */\n /%252f/gi,\n /** Dotdotslash bypass: ....// or ....\\\\ */\n /\\.{2,}[/\\\\]{2,}/g,\n /** Null byte injection in paths */\n /\\0/g,\n] as const;\n\n// =============================================================================\n// COMMAND INJECTION PATTERNS\n// =============================================================================\nexport const COMMAND_PATTERNS = [\n /**\n * Shell metacharacters that enable command chaining/substitution.\n * Bare ( and ) are excluded — they appear in common legitimate values\n * (function calls in code fields, math expressions, etc.).\n * Command substitution is caught by the $( combined pattern below.\n * NOTE: ';', '&', '|' may appear in legitimate URL query strings\n * and Markdown; consider disabling command checking (command: false)\n * for fields that intentionally allow those characters.\n */\n /[;&|`]/g,\n /** Command substitution: $( ... ) — matched as a pair to reduce false positives */\n /\\$\\(/g,\n /** URL-encoded control characters (%00-%0F): null, tab, vtab, formfeed, LF, CR */\n /%0[0-9a-f]/gi,\n] as const;\n\n// =============================================================================\n// DANGEROUS KEYS\n// =============================================================================\n\n/**\n * Prototype pollution keys to block.\n * Stored lowercase — always compare with key.toLowerCase().\n *\n * Includes:\n * - __proto__: direct prototype assignment\n * - constructor: access to constructor.prototype chain\n * - prototype: direct prototype property\n * - __defineGetter__/__defineSetter__: legacy property definition (can override getters/setters)\n * - __lookupGetter__/__lookupSetter__: legacy property introspection\n */\nexport const DANGEROUS_PROTO_KEYS = new Set([\n '__proto__',\n 'constructor',\n 'prototype',\n '__definegetter__',\n '__definesetter__',\n '__lookupgetter__',\n '__lookupsetter__',\n]);\n\n/** MongoDB operators to block */\nexport const NOSQL_DANGEROUS_KEYS = new Set([\n // Comparison\n '$gt', '$gte', '$lt', '$lte', '$ne', '$eq', '$in', '$nin',\n // Logical\n '$and', '$or', '$not', '$nor',\n // Element / evaluation\n '$exists', '$type', '$regex', '$where', '$expr', '$mod', '$text', '$jsonSchema',\n // Array\n '$elemMatch', '$all', '$size',\n // JavaScript execution (critical)\n '$function', '$accumulator',\n // Aggregation pipeline operators (injectable via $lookup etc.)\n '$lookup', '$match', '$project', '$group', '$sort', '$limit', '$skip',\n '$unwind', '$addFields', '$replaceRoot',\n]);\n\n// =============================================================================\n// REDACTION\n// =============================================================================\nexport const REDACTION = {\n /** Replacement text for redacted values */\n REPLACEMENT: '[REDACTED]',\n /** Truncation indicator */\n TRUNCATED: '[TRUNCATED]',\n /** Max depth indicator */\n MAX_DEPTH: '[MAX_DEPTH]',\n /** Default max message length */\n DEFAULT_MAX_LENGTH: 10_000,\n /** Default sensitive keys to redact */\n SENSITIVE_KEYS: new Set([\n 'password', 'passwd', 'pwd', 'secret', 'token', 'apikey',\n 'api_key', 'apiKey', 'auth', 'authorization', 'credit_card',\n 'creditcard', 'cc', 'ssn', 'social_security', 'private_key',\n 'privateKey', 'access_token', 'accessToken', 'refresh_token',\n 'refreshToken', 'bearer', 'jwt', 'session', 'cookie',\n 'credentials', 'x-api-key', 'x-auth-token',\n ]),\n} as const;\n\n// =============================================================================\n// VALIDATION PATTERNS\n// =============================================================================\nexport const VALIDATION = {\n /**\n * Email regex pattern.\n * Rejects consecutive dots in local part (e.g. test..foo@example.com),\n * leading/trailing dots, and other common invalid forms.\n */\n EMAIL: /^[^\\s@.][^\\s@]*(?:\\.[^\\s@.][^\\s@]*)*@[^\\s@]+\\.[^\\s@]+$/,\n /**\n * URL regex pattern.\n * Only allows http:// and https:// — explicitly rejects javascript:,\n * data:, vbscript:, and other dangerous URI schemes.\n */\n URL: /^https?:\\/\\/[^\\s/$.?#][^\\s]*$/,\n /** UUID regex pattern (v4) */\n UUID: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,\n} as const;\n\n// =============================================================================\n// ERROR MESSAGES\n// =============================================================================\nexport const ERRORS = {\n /** Generic error message (production) */\n INTERNAL_SERVER_ERROR: 'Internal Server Error',\n /** Input too large error */\n INPUT_TOO_LARGE: (maxSize: number) => `Input exceeds maximum size of ${maxSize} bytes`,\n /** Validation error messages */\n VALIDATION: {\n REQUIRED: (field: string) => `${field} is required`,\n INVALID_TYPE: (field: string, type: string) => `${field} must be a ${type}`,\n MIN_LENGTH: (field: string, min: number) => `${field} must be at least ${min} characters`,\n MAX_LENGTH: (field: string, max: number) => `${field} must be at most ${max} characters`,\n MIN_VALUE: (field: string, min: number) => `${field} must be at least ${min}`,\n MAX_VALUE: (field: string, max: number) => `${field} must be at most ${max}`,\n INVALID_FORMAT: (field: string) => `${field} format is invalid`,\n INVALID_EMAIL: (field: string) => `${field} must be a valid email`,\n INVALID_URL: (field: string) => `${field} must be a valid URL`,\n INVALID_UUID: (field: string) => `${field} must be a valid UUID`,\n INVALID_ENUM: (field: string, values: unknown[]) => `${field} must be one of: ${values.join(', ')}`,\n MIN_ITEMS: (field: string, min: number) => `${field} must have at least ${min} items`,\n MAX_ITEMS: (field: string, max: number) => `${field} must have at most ${max} items`,\n },\n} as const;\n\n// =============================================================================\n// BLOCKED TEXT (for sanitizer replacements)\n// =============================================================================\nexport const BLOCKED = '[BLOCKED]' as const;\n","/**\n * @module @arcis/node/stores/memory\n * In-memory rate limit store\n */\n\nimport type { RateLimitStore, RateLimitEntry } from '../core/types';\nimport { RATE_LIMIT } from '../core/constants';\n\n/**\n * In-memory rate limit store.\n * Suitable for single-instance deployments.\n * For distributed systems, use RedisStore or a custom store.\n * \n * @example\n * const store = new MemoryStore(60000); // 1 minute window\n * const limiter = createRateLimiter({ store });\n */\n/** Default maximum number of keys the in-memory store will hold. */\nconst DEFAULT_MAX_SIZE = 10_000;\n\nexport class MemoryStore implements RateLimitStore {\n private store: Map<string, RateLimitEntry> = new Map();\n private cleanupInterval: ReturnType<typeof setInterval> | null = null;\n private windowMs: number;\n private maxSize: number;\n\n constructor(windowMs: number = RATE_LIMIT.DEFAULT_WINDOW_MS, maxSize: number = DEFAULT_MAX_SIZE) {\n if (!Number.isFinite(windowMs) || windowMs < RATE_LIMIT.MIN_WINDOW_MS) {\n throw new RangeError(\n `MemoryStore: windowMs must be a finite number >= ${RATE_LIMIT.MIN_WINDOW_MS} (got ${windowMs})`\n );\n }\n if (!Number.isFinite(maxSize) || maxSize < 1) {\n throw new RangeError(`MemoryStore: maxSize must be >= 1 (got ${maxSize})`);\n }\n this.windowMs = windowMs;\n this.maxSize = maxSize;\n this.startCleanup();\n }\n\n /**\n * Start the cleanup interval to remove expired entries.\n */\n private startCleanup(): void {\n // Clamp the cleanup interval between 30 s and 5 min regardless of windowMs.\n // Running it every windowMs is fine for typical windows but would fire every\n // second for short windows (e.g. windowMs: 1000), causing O(n) GC pressure.\n const CLEANUP_MIN_MS = 30_000;\n const CLEANUP_MAX_MS = 300_000;\n const cleanupMs = Math.min(Math.max(this.windowMs, CLEANUP_MIN_MS), CLEANUP_MAX_MS);\n\n this.cleanupInterval = setInterval(() => {\n const now = Date.now();\n for (const [key, entry] of this.store.entries()) {\n if (entry.resetTime < now) {\n this.store.delete(key);\n }\n }\n }, cleanupMs);\n\n // Prevent interval from keeping the process alive\n if (typeof this.cleanupInterval.unref === 'function') {\n this.cleanupInterval.unref();\n }\n }\n\n async get(key: string): Promise<RateLimitEntry | null> {\n const entry = this.store.get(key);\n if (!entry) return null;\n \n // Check if expired\n if (entry.resetTime < Date.now()) {\n this.store.delete(key);\n return null;\n }\n \n return entry;\n }\n\n async set(key: string, entry: RateLimitEntry): Promise<void> {\n if (!this.store.has(key) && this.store.size >= this.maxSize) {\n this.evictExpired();\n // If still at capacity after eviction, fail open — don't crash the app\n if (this.store.size >= this.maxSize) return;\n }\n this.store.set(key, entry);\n }\n\n async increment(key: string): Promise<number> {\n const now = Date.now();\n const entry = this.store.get(key);\n\n if (!entry || entry.resetTime < now) {\n // Start new window — check capacity first\n if (this.store.size >= this.maxSize) {\n this.evictExpired();\n if (this.store.size >= this.maxSize) return 1; // fail open\n }\n this.store.set(key, { count: 1, resetTime: now + this.windowMs });\n return 1;\n }\n\n entry.count++;\n return entry.count;\n }\n\n /** Eagerly remove expired entries to reclaim capacity. */\n private evictExpired(): void {\n const now = Date.now();\n for (const [key, entry] of this.store.entries()) {\n if (entry.resetTime < now) this.store.delete(key);\n }\n }\n\n async decrement(key: string): Promise<void> {\n const entry = this.store.get(key);\n if (entry && entry.count > 0) {\n entry.count--;\n }\n }\n\n async reset(key: string): Promise<void> {\n this.store.delete(key);\n }\n\n async close(): Promise<void> {\n if (this.cleanupInterval) {\n clearInterval(this.cleanupInterval);\n this.cleanupInterval = null;\n }\n this.store.clear();\n }\n\n /**\n * Get current store size (for monitoring).\n */\n get size(): number {\n return this.store.size;\n }\n}\n","/**\n * @module @arcis/node/stores/redis\n * Redis rate limit store\n * \n * Note: This is a reference implementation. You'll need to install\n * the 'ioredis' or 'redis' package and pass your client instance.\n */\n\nimport type { RateLimitStore, RateLimitEntry } from '../core/types';\nimport { RATE_LIMIT } from '../core/constants';\n\n/** Generic Redis client interface (works with ioredis, redis, etc.) */\nexport interface RedisClientLike {\n get(key: string): Promise<string | null>;\n set(key: string, value: string, mode?: string, duration?: number): Promise<unknown>;\n setex(key: string, seconds: number, value: string): Promise<unknown>;\n expire(key: string, seconds: number): Promise<unknown>;\n incr(key: string): Promise<number>;\n decr(key: string): Promise<number>;\n del(key: string): Promise<number>;\n ttl(key: string): Promise<number>;\n quit?(): Promise<unknown>;\n disconnect?(): Promise<unknown>;\n}\n\nexport interface RedisStoreOptions {\n /** Redis client instance */\n client: RedisClientLike;\n /** Key prefix. Default: 'arcis:rl:' */\n prefix?: string;\n /** Window size in milliseconds. Default: 60000 */\n windowMs?: number;\n}\n\n/**\n * Redis rate limit store for distributed deployments.\n * \n * @example\n * import Redis from 'ioredis';\n * \n * const redis = new Redis();\n * const store = new RedisStore({ client: redis });\n * const limiter = createRateLimiter({ store });\n * \n * // Cleanup on shutdown\n * process.on('SIGTERM', async () => {\n * await store.close();\n * });\n */\nexport class RedisStore implements RateLimitStore {\n private client: RedisClientLike;\n private prefix: string;\n private windowMs: number;\n private windowSec: number;\n\n constructor(options: RedisStoreOptions) {\n this.client = options.client;\n this.prefix = options.prefix ?? 'arcis:rl:';\n this.windowMs = options.windowMs ?? RATE_LIMIT.DEFAULT_WINDOW_MS;\n this.windowSec = Math.ceil(this.windowMs / 1000);\n }\n\n private getKey(key: string): string {\n return `${this.prefix}${key}`;\n }\n\n async get(key: string): Promise<RateLimitEntry | null> {\n const redisKey = this.getKey(key);\n \n const [countStr, ttl] = await Promise.all([\n this.client.get(redisKey),\n this.client.ttl(redisKey),\n ]);\n \n if (!countStr || ttl < 0) {\n return null;\n }\n \n const count = parseInt(countStr, 10);\n if (isNaN(count)) {\n // Corrupt value in Redis — treat as if key doesn't exist\n return null;\n }\n\n return {\n count,\n resetTime: Date.now() + (ttl * 1000),\n };\n }\n\n async set(key: string, entry: RateLimitEntry): Promise<void> {\n const redisKey = this.getKey(key);\n // Clamp to at least 1 second — Math.ceil can produce 0 or negative values\n // when entry.resetTime is in the past due to Redis latency or clock skew.\n const ttlSec = Math.max(1, Math.ceil((entry.resetTime - Date.now()) / 1000));\n await this.client.setex(redisKey, ttlSec, entry.count.toString());\n }\n\n async increment(key: string): Promise<number> {\n const redisKey = this.getKey(key);\n \n // INCR creates key with value 1 if it doesn't exist\n const count = await this.client.incr(redisKey);\n\n // Set expiry only on first increment using EXPIRE, which sets the TTL\n // without overwriting the value (unlike SET ... EX which would reset the\n // counter if two requests increment concurrently before expiry is set).\n if (count === 1) {\n await this.client.expire(redisKey, this.windowSec);\n }\n\n return count;\n }\n\n async decrement(key: string): Promise<void> {\n const redisKey = this.getKey(key);\n await this.client.decr(redisKey);\n }\n\n async reset(key: string): Promise<void> {\n const redisKey = this.getKey(key);\n await this.client.del(redisKey);\n }\n\n async close(): Promise<void> {\n // Don't close the client - it may be shared\n // The caller should manage the client lifecycle\n }\n}\n\n/**\n * Create a Redis store with the given options.\n * Convenience function for functional programming style.\n * \n * @example\n * const store = createRedisStore({ client: redisClient });\n */\nexport function createRedisStore(options: RedisStoreOptions): RedisStore {\n return new RedisStore(options);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/core/constants.ts","../../src/stores/memory.ts","../../src/stores/redis.ts"],"names":[],"mappings":";;;AAkBO,IAAM,UAAA,GAAa;AAAA;AAAA,EAExB,iBAAA,EAAmB,GAAA;AAAA,EAMF;AAAA,EAEjB,aAAA,EAAe,GAGjB,CAAA;;;ACbA,IAAM,gBAAA,GAAmB,GAAA;AAElB,IAAM,cAAN,MAA4C;AAAA,EAMjD,WAAA,CAAY,QAAA,GAAmB,UAAA,CAAW,iBAAA,EAAmB,UAAkB,gBAAA,EAAkB;AALjG,IAAA,IAAA,CAAQ,KAAA,uBAAyC,GAAA,EAAI;AACrD,IAAA,IAAA,CAAQ,eAAA,GAAyD,IAAA;AAK/D,IAAA,IAAI,CAAC,MAAA,CAAO,QAAA,CAAS,QAAQ,CAAA,IAAK,QAAA,GAAW,WAAW,aAAA,EAAe;AACrE,MAAA,MAAM,IAAI,UAAA;AAAA,QACR,CAAA,iDAAA,EAAoD,UAAA,CAAW,aAAa,CAAA,MAAA,EAAS,QAAQ,CAAA,CAAA;AAAA,OAC/F;AAAA,IACF;AACA,IAAA,IAAI,CAAC,MAAA,CAAO,QAAA,CAAS,OAAO,CAAA,IAAK,UAAU,CAAA,EAAG;AAC5C,MAAA,MAAM,IAAI,UAAA,CAAW,CAAA,uCAAA,EAA0C,OAAO,CAAA,CAAA,CAAG,CAAA;AAAA,IAC3E;AACA,IAAA,IAAA,CAAK,QAAA,GAAW,QAAA;AAChB,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AACf,IAAA,IAAA,CAAK,YAAA,EAAa;AAAA,EACpB;AAAA;AAAA;AAAA;AAAA,EAKQ,YAAA,GAAqB;AAI3B,IAAA,MAAM,cAAA,GAAiB,GAAA;AACvB,IAAA,MAAM,cAAA,GAAiB,GAAA;AACvB,IAAA,MA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A,OAAO,KAAA;AAAA,EACT;AAAA,EAEA,MAAM,UAAU,GAAA,EAA4B;AAC1C,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,MAAA,CAAO,GAAG,CAAA;AAChC,IAAA,MAAM,IAAA,CAAK,MAAA,CAAO,IAAA,CAAK,QAAQ,CAAA;AAAA,EACjC;AAAA,EAEA,MAAM,MAAM,GAAA,EAA4B;AACtC,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,MAAA,CAAO,GAAG,CAAA;AAChC,IAAA,MAAM,IAAA,CAAK,MAAA,CAAO,GAAA,CAAI,QAAQ,CAAA;AAAA,EAChC;AAAA,EAEA,MAAM,KAAA,GAAuB;AAAA,EAG7B;AACF;AASO,SAAS,iBAAiB,OAAA,EAAwC;AACvE,EAAA,OAAO,IAAI,WAAW,OAAO,CAAA;AAC/B","file":"index.js","sourcesContent":["/**\n * @module @arcis/node/core/constants\n * Named constants for Arcis - no magic numbers\n */\n\n// =============================================================================\n// INPUT LIMITS\n// =============================================================================\nexport const INPUT = {\n /** Default maximum input size (1MB) */\n DEFAULT_MAX_SIZE: 1_000_000,\n /** Maximum recursion depth for nested objects */\n MAX_RECURSION_DEPTH: 10,\n} as const;\n\n// =============================================================================\n// RATE LIMITING\n// =============================================================================\nexport const RATE_LIMIT = {\n /** Default window size (1 minute) */\n DEFAULT_WINDOW_MS: 60_000,\n /** Default max requests per window */\n DEFAULT_MAX_REQUESTS: 100,\n /** Default HTTP status code for rate limited responses */\n DEFAULT_STATUS_CODE: 429,\n /** Default error message */\n DEFAULT_MESSAGE: 'Too many requests, please try again later.',\n /** Minimum window size (1 second) */\n MIN_WINDOW_MS: 1_000,\n /** Maximum window size (24 hours) */\n MAX_WINDOW_MS: 86_400_000,\n} as const;\n\n// =============================================================================\n// SECURITY HEADERS\n// =============================================================================\nexport const HEADERS = {\n /** Default Content Security Policy */\n DEFAULT_CSP: [\n \"default-src 'self'\",\n \"script-src 'self'\",\n \"style-src 'self' 'unsafe-inline'\",\n \"img-src 'self' data: https:\",\n \"font-src 'self'\",\n \"object-src 'none'\",\n \"frame-ancestors 'none'\",\n ].join('; '),\n /** Default HSTS max age (1 year in seconds) */\n HSTS_MAX_AGE: 31_536_000,\n /** Default X-Frame-Options value */\n FRAME_OPTIONS: 'DENY' as const,\n /** Default X-Content-Type-Options value */\n CONTENT_TYPE_OPTIONS: 'nosniff',\n /** Default Referrer-Policy value */\n REFERRER_POLICY: 'strict-origin-when-cross-origin',\n /** Default Permissions-Policy value */\n PERMISSIONS_POLICY: 'geolocation=(), microphone=(), camera=()',\n /** Default Cache-Control value for security */\n CACHE_CONTROL: 'no-store, no-cache, must-revalidate, proxy-revalidate',\n} as const;\n\n// =============================================================================\n// XSS PATTERNS (ReDoS-safe)\n// =============================================================================\n\n/**\n * Detection patterns — used to flag whether a string contains XSS payloads.\n * Must stay in sync with XSS_REMOVE_PATTERNS below.\n */\nexport const XSS_PATTERNS = [\n /** Script tags (ReDoS-safe version) */\n /<script[^>]*>[\\s\\S]*?<\\/script>/gi,\n /** javascript: protocol (allow optional spaces before colon) */\n /javascript\\s*:/gi,\n /** vbscript: protocol */\n /vbscript\\s*:/gi,\n /** Event handlers (onclick, onerror, etc.) — any separator before attribute */\n /(?:[\\s/])on\\w+\\s*=/gi,\n /** iframe tags */\n /<iframe/gi,\n /** object tags */\n /<object/gi,\n /** embed tags */\n /<embed/gi,\n /** data: URIs (only dangerous ones, avoid false positives) */\n /(?:^|[\\s\"'=])data:/gi,\n /** URL-encoded script tags */\n /%3Cscript/gi,\n /** SVG with onload */\n /<svg[^>]*onload/gi,\n /** form tags — phishing/credential harvesting via action= redirection */\n /<form[\\s>]/gi,\n /** meta tags — http-equiv refresh redirects or CSP bypass */\n /<meta[\\s>]/gi,\n /** base href hijacking — redirects all relative URLs to attacker domain */\n /<base[\\s>]/gi,\n /** link tag injection — stylesheet or preload CSRF attacks */\n /<link[\\s>]/gi,\n] as const;\n\n/**\n * Removal patterns — used by sanitizeXss() to strip dangerous content.\n * More targeted than XSS_PATTERNS: each pattern captures the full dangerous\n * substring (tag, attribute + value, protocol) so it can be replaced safely.\n * Must stay in sync with XSS_PATTERNS above.\n */\nexport const XSS_REMOVE_PATTERNS = [\n /** Full script blocks (content + tags) */\n /<script[^>]*>[\\s\\S]*?<\\/script>/gi,\n /** Standalone/unclosed script tags */\n /<script[^>]*>/gi,\n /** style — CSS expression() and behavior: attacks (IE-era but still relevant) */\n /<style[^>]*>[\\s\\S]*?<\\/style>/gi,\n /<style[^>]*/gi,\n /** iframe — full block and partial/unclosed */\n /<iframe[^>]*>[\\s\\S]*?<\\/iframe>/gi,\n /<iframe[^>]*/gi,\n /** object — full block and partial/unclosed */\n /<object[^>]*>[\\s\\S]*?<\\/object>/gi,\n /<object[^>]*/gi,\n /** embed tags */\n /<embed[^>]*/gi,\n /** SVG with inline event handlers */\n /<svg[^>]*onload[^>]*>/gi,\n /** URL-encoded script tags */\n /%3Cscript/gi,\n /** Event handlers with quoted values: onclick=\"...\", onerror='...' */\n /(?:[\\s/])on\\w+\\s*=\\s*[\"'][^\"']*[\"']/gi,\n /** Event handlers with unquoted values: onload=value */\n /(?:[\\s/])on\\w+\\s*=\\s*[^\\s>]*/gi,\n /** javascript: and vbscript: protocols (allow optional spaces before colon) */\n /javascript\\s*:/gi,\n /vbscript\\s*:/gi,\n /** data: URIs with HTML/script content */\n /data\\s*:\\s*text\\/html[^>\\s]*/gi,\n /** form tag injection — phishing via action= redirection */\n /<form[\\s>][^>]*/gi,\n /** meta tag injection — http-equiv refresh or CSP bypass */\n /<meta[\\s>][^>]*/gi,\n /** base href hijacking */\n /<base[\\s>][^>]*/gi,\n /** link tag injection — stylesheet or preload attacks */\n /<link[\\s>][^>]*/gi,\n] as const;\n\n// =============================================================================\n// SQL INJECTION PATTERNS\n// =============================================================================\nexport const SQL_PATTERNS = [\n /** SQL keywords */\n /(\\b(SELECT|INSERT|UPDATE|DELETE|DROP|UNION|ALTER|CREATE|TRUNCATE|EXEC|EXECUTE)\\b)/gi,\n /** SQL comments: ANSI (--), C-style (slash-star ... star-slash), MySQL (#) */\n /(--|\\/\\*|\\*\\/|#)/g,\n /** SQL statement separators */\n /(;|\\|\\||&&)/g,\n /** Boolean injection: OR 1=1 */\n /\\bOR\\s+\\d+\\s*=\\s*\\d+/gi,\n /** Boolean injection: OR 'a'='a' or OR \"a\"=\"a\" (including mixed quotes) */\n /\\bOR\\s+(['\"])[^'\"]*\\1\\s*=\\s*(['\"])[^'\"]*\\2/gi,\n /\\bOR\\s+('[^']*'|\"[^\"]*\")\\s*=\\s*('[^']*'|\"[^\"]*\")/gi,\n /** Boolean injection: AND 1=1 */\n /\\bAND\\s+\\d+\\s*=\\s*\\d+/gi,\n /** Boolean injection: AND 'a'='a' or AND \"a\"=\"a\" (including mixed quotes) */\n /\\bAND\\s+(['\"])[^'\"]*\\1\\s*=\\s*(['\"])[^'\"]*\\2/gi,\n /\\bAND\\s+('[^']*'|\"[^\"]*\")\\s*=\\s*('[^']*'|\"[^\"]*\")/gi,\n /** Time-based blind: SLEEP() */\n /\\bSLEEP\\s*\\(\\s*\\d+\\s*\\)/gi,\n /** Time-based blind: BENCHMARK() */\n /\\bBENCHMARK\\s*\\(/gi,\n /** Time-based blind: PostgreSQL pg_sleep() */\n /\\bpg_sleep\\s*\\(/gi,\n /** Time-based blind: MSSQL WAITFOR DELAY */\n /\\bWAITFOR\\s+DELAY\\b/gi,\n] as const;\n\n// =============================================================================\n// PATH TRAVERSAL PATTERNS\n// =============================================================================\nexport const PATH_PATTERNS = [\n /** Unix path traversal */\n /\\.\\.\\//g,\n /** Windows path traversal */\n /\\.\\.\\\\/g,\n /** URL-encoded traversal (%2e%2e) */\n /%2e%2e/gi,\n /** Double URL-encoded traversal (%252e) */\n /%252e/gi,\n /** Mixed encoding: ..%2F */\n /\\.\\.%2F/gi,\n /** Mixed encoding: %2e./ and .%2e/ */\n /%2e\\.[\\\\/]/gi,\n /\\.%2e[\\\\/]/gi,\n /** Fully URL-encoded: %2e%2e%2f */\n /%2e%2e%2f/gi,\n /** Double URL-encoded forward slash: %252f */\n /%252f/gi,\n /** Dotdotslash bypass: ....// or ....\\\\ */\n /\\.{2,}[/\\\\]{2,}/g,\n /** Null byte injection in paths */\n /\\0/g,\n] as const;\n\n// =============================================================================\n// COMMAND INJECTION PATTERNS\n// =============================================================================\nexport const COMMAND_PATTERNS = [\n /**\n * Shell metacharacters that enable command chaining/substitution.\n * Bare ( and ) are excluded — they appear in common legitimate values\n * (function calls in code fields, math expressions, etc.).\n * Command substitution is caught by the $( combined pattern below.\n * NOTE: ';', '&', '|' may appear in legitimate URL query strings\n * and Markdown; consider disabling command checking (command: false)\n * for fields that intentionally allow those characters.\n */\n /[;&|`]/g,\n /** Command substitution: $( ... ) — matched as a pair to reduce false positives */\n /\\$\\(/g,\n /** URL-encoded control characters (%00-%0F): null, tab, vtab, formfeed, LF, CR */\n /%0[0-9a-f]/gi,\n] as const;\n\n// =============================================================================\n// DANGEROUS KEYS\n// =============================================================================\n\n/**\n * Prototype pollution keys to block.\n * Stored lowercase — always compare with key.toLowerCase().\n *\n * Includes:\n * - __proto__: direct prototype assignment\n * - constructor: access to constructor.prototype chain\n * - prototype: direct prototype property\n * - __defineGetter__/__defineSetter__: legacy property definition (can override getters/setters)\n * - __lookupGetter__/__lookupSetter__: legacy property introspection\n */\nexport const DANGEROUS_PROTO_KEYS = new Set([\n '__proto__',\n 'constructor',\n 'prototype',\n '__definegetter__',\n '__definesetter__',\n '__lookupgetter__',\n '__lookupsetter__',\n]);\n\n/** MongoDB operators to block */\nexport const NOSQL_DANGEROUS_KEYS = new Set([\n // Comparison\n '$gt', '$gte', '$lt', '$lte', '$ne', '$eq', '$in', '$nin',\n // Logical\n '$and', '$or', '$not', '$nor',\n // Element / evaluation\n '$exists', '$type', '$regex', '$where', '$expr', '$mod', '$text', '$jsonSchema',\n // Array\n '$elemMatch', '$all', '$size',\n // JavaScript execution (critical)\n '$function', '$accumulator',\n // Aggregation pipeline operators (injectable via $lookup etc.)\n '$lookup', '$match', '$project', '$group', '$sort', '$limit', '$skip',\n '$unwind', '$addFields', '$replaceRoot',\n]);\n\n// =============================================================================\n// REDACTION\n// =============================================================================\nexport const REDACTION = {\n /** Replacement text for redacted values */\n REPLACEMENT: '[REDACTED]',\n /** Truncation indicator */\n TRUNCATED: '[TRUNCATED]',\n /** Max depth indicator */\n MAX_DEPTH: '[MAX_DEPTH]',\n /** Default max message length */\n DEFAULT_MAX_LENGTH: 10_000,\n /** Default sensitive keys to redact */\n SENSITIVE_KEYS: new Set([\n 'password', 'passwd', 'pwd', 'secret', 'token', 'apikey',\n 'api_key', 'apiKey', 'auth', 'authorization', 'credit_card',\n 'creditcard', 'cc', 'ssn', 'social_security', 'private_key',\n 'privateKey', 'access_token', 'accessToken', 'refresh_token',\n 'refreshToken', 'bearer', 'jwt', 'session', 'cookie',\n 'credentials', 'x-api-key', 'x-auth-token',\n ]),\n} as const;\n\n// =============================================================================\n// VALIDATION PATTERNS\n// =============================================================================\nexport const VALIDATION = {\n /**\n * Email regex pattern.\n * Rejects consecutive dots in local part (e.g. test..foo@example.com),\n * leading/trailing dots, and other common invalid forms.\n */\n EMAIL: /^[^\\s@.][^\\s@]*(?:\\.[^\\s@.][^\\s@]*)*@[^\\s@]+\\.[^\\s@]+$/,\n /**\n * URL regex pattern.\n * Only allows http:// and https:// — explicitly rejects javascript:,\n * data:, vbscript:, and other dangerous URI schemes.\n */\n URL: /^https?:\\/\\/[^\\s/$.?#][^\\s]*$/,\n /** UUID regex pattern (v4) */\n UUID: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,\n} as const;\n\n// =============================================================================\n// ERROR MESSAGES\n// =============================================================================\nexport const ERRORS = {\n /** Generic error message (production) */\n INTERNAL_SERVER_ERROR: 'Internal Server Error',\n /** Input too large error */\n INPUT_TOO_LARGE: (maxSize: number) => `Input exceeds maximum size of ${maxSize} bytes`,\n /** Validation error messages */\n VALIDATION: {\n REQUIRED: (field: string) => `${field} is required`,\n INVALID_TYPE: (field: string, type: string) => `${field} must be a ${type}`,\n MIN_LENGTH: (field: string, min: number) => `${field} must be at least ${min} characters`,\n MAX_LENGTH: (field: string, max: number) => `${field} must be at most ${max} characters`,\n MIN_VALUE: (field: string, min: number) => `${field} must be at least ${min}`,\n MAX_VALUE: (field: string, max: number) => `${field} must be at most ${max}`,\n INVALID_FORMAT: (field: string) => `${field} format is invalid`,\n INVALID_EMAIL: (field: string) => `${field} must be a valid email`,\n INVALID_URL: (field: string) => `${field} must be a valid URL`,\n INVALID_UUID: (field: string) => `${field} must be a valid UUID`,\n INVALID_ENUM: (field: string, values: unknown[]) => `${field} must be one of: ${values.join(', ')}`,\n MIN_ITEMS: (field: string, min: number) => `${field} must have at least ${min} items`,\n MAX_ITEMS: (field: string, max: number) => `${field} must have at most ${max} items`,\n },\n} as const;\n\n// =============================================================================\n// BLOCKED TEXT (for sanitizer replacements)\n// =============================================================================\nexport const BLOCKED = '[BLOCKED]' as const;\n","/**\n * @module @arcis/node/stores/memory\n * In-memory rate limit store\n */\n\nimport type { RateLimitStore, RateLimitEntry } from '../core/types';\nimport { RATE_LIMIT } from '../core/constants';\n\n/**\n * In-memory rate limit store.\n * Suitable for single-instance deployments.\n * For distributed systems, use RedisStore or a custom store.\n * \n * @example\n * const store = new MemoryStore(60000); // 1 minute window\n * const limiter = createRateLimiter({ store });\n */\n/** Default maximum number of keys the in-memory store will hold. */\nconst DEFAULT_MAX_SIZE = 10_000;\n\nexport class MemoryStore implements RateLimitStore {\n private store: Map<string, RateLimitEntry> = new Map();\n private cleanupInterval: ReturnType<typeof setInterval> | null = null;\n private windowMs: number;\n private maxSize: number;\n\n constructor(windowMs: number = RATE_LIMIT.DEFAULT_WINDOW_MS, maxSize: number = DEFAULT_MAX_SIZE) {\n if (!Number.isFinite(windowMs) || windowMs < RATE_LIMIT.MIN_WINDOW_MS) {\n throw new RangeError(\n `MemoryStore: windowMs must be a finite number >= ${RATE_LIMIT.MIN_WINDOW_MS} (got ${windowMs})`\n );\n }\n if (!Number.isFinite(maxSize) || maxSize < 1) {\n throw new RangeError(`MemoryStore: maxSize must be >= 1 (got ${maxSize})`);\n }\n this.windowMs = windowMs;\n this.maxSize = maxSize;\n this.startCleanup();\n }\n\n /**\n * Start the cleanup interval to remove expired entries.\n */\n private startCleanup(): void {\n // Clamp the cleanup interval between 30 s and 5 min regardless of windowMs.\n // Running it every windowMs is fine for typical windows but would fire every\n // second for short windows (e.g. windowMs: 1000), causing O(n) GC pressure.\n const CLEANUP_MIN_MS = 30_000;\n const CLEANUP_MAX_MS = 300_000;\n const cleanupMs = Math.min(Math.max(this.windowMs, CLEANUP_MIN_MS), CLEANUP_MAX_MS);\n\n this.cleanupInterval = setInterval(() => {\n const now = Date.now();\n for (const [key, entry] of this.store.entries()) {\n if (entry.resetTime < now) {\n this.store.delete(key);\n }\n }\n }, cleanupMs);\n\n // Prevent interval from keeping the process alive\n if (typeof this.cleanupInterval.unref === 'function') {\n this.cleanupInterval.unref();\n }\n }\n\n async get(key: string): Promise<RateLimitEntry | null> {\n const entry = this.store.get(key);\n if (!entry) return null;\n \n // Check if expired\n if (entry.resetTime < Date.now()) {\n this.store.delete(key);\n return null;\n }\n \n return entry;\n }\n\n async set(key: string, entry: RateLimitEntry): Promise<void> {\n if (!this.store.has(key) && this.store.size >= this.maxSize) {\n this.evictExpired();\n // If still at capacity after eviction, fail open — don't crash the app\n if (this.store.size >= this.maxSize) return;\n }\n this.store.set(key, entry);\n }\n\n async increment(key: string): Promise<number> {\n const now = Date.now();\n const entry = this.store.get(key);\n\n if (!entry || entry.resetTime < now) {\n // Start new window — check capacity first\n if (this.store.size >= this.maxSize) {\n this.evictExpired();\n if (this.store.size >= this.maxSize) return 1; // fail open\n }\n this.store.set(key, { count: 1, resetTime: now + this.windowMs });\n return 1;\n }\n\n entry.count++;\n return entry.count;\n }\n\n /** Eagerly remove expired entries to reclaim capacity. */\n private evictExpired(): void {\n const now = Date.now();\n for (const [key, entry] of this.store.entries()) {\n if (entry.resetTime < now) this.store.delete(key);\n }\n }\n\n async decrement(key: string): Promise<void> {\n const entry = this.store.get(key);\n if (entry && entry.count > 0) {\n entry.count--;\n }\n }\n\n async reset(key: string): Promise<void> {\n this.store.delete(key);\n }\n\n async close(): Promise<void> {\n if (this.cleanupInterval) {\n clearInterval(this.cleanupInterval);\n this.cleanupInterval = null;\n }\n this.store.clear();\n }\n\n /**\n * Get current store size (for monitoring).\n */\n get size(): number {\n return this.store.size;\n }\n}\n","/**\n * @module @arcis/node/stores/redis\n * Redis rate limit store\n * \n * Note: This is a reference implementation. You'll need to install\n * the 'ioredis' or 'redis' package and pass your client instance.\n */\n\nimport type { RateLimitStore, RateLimitEntry } from '../core/types';\nimport { RATE_LIMIT } from '../core/constants';\n\n/** Generic Redis client interface (works with ioredis, redis, etc.) */\nexport interface RedisClientLike {\n get(key: string): Promise<string | null>;\n set(key: string, value: string, mode?: string, duration?: number): Promise<unknown>;\n setex(key: string, seconds: number, value: string): Promise<unknown>;\n expire(key: string, seconds: number): Promise<unknown>;\n incr(key: string): Promise<number>;\n decr(key: string): Promise<number>;\n del(key: string): Promise<number>;\n ttl(key: string): Promise<number>;\n quit?(): Promise<unknown>;\n disconnect?(): Promise<unknown>;\n}\n\nexport interface RedisStoreOptions {\n /** Redis client instance */\n client: RedisClientLike;\n /** Key prefix. Default: 'arcis:rl:' */\n prefix?: string;\n /** Window size in milliseconds. Default: 60000 */\n windowMs?: number;\n}\n\n/**\n * Redis rate limit store for distributed deployments.\n * \n * @example\n * import Redis from 'ioredis';\n * \n * const redis = new Redis();\n * const store = new RedisStore({ client: redis });\n * const limiter = createRateLimiter({ store });\n * \n * // Cleanup on shutdown\n * process.on('SIGTERM', async () => {\n * await store.close();\n * });\n */\nexport class RedisStore implements RateLimitStore {\n private client: RedisClientLike;\n private prefix: string;\n private windowMs: number;\n private windowSec: number;\n\n constructor(options: RedisStoreOptions) {\n this.client = options.client;\n this.prefix = options.prefix ?? 'arcis:rl:';\n this.windowMs = options.windowMs ?? RATE_LIMIT.DEFAULT_WINDOW_MS;\n this.windowSec = Math.ceil(this.windowMs / 1000);\n }\n\n private getKey(key: string): string {\n return `${this.prefix}${key}`;\n }\n\n async get(key: string): Promise<RateLimitEntry | null> {\n const redisKey = this.getKey(key);\n \n const [countStr, ttl] = await Promise.all([\n this.client.get(redisKey),\n this.client.ttl(redisKey),\n ]);\n \n if (!countStr || ttl < 0) {\n return null;\n }\n \n const count = parseInt(countStr, 10);\n if (isNaN(count)) {\n // Corrupt value in Redis — treat as if key doesn't exist\n return null;\n }\n\n return {\n count,\n resetTime: Date.now() + (ttl * 1000),\n };\n }\n\n async set(key: string, entry: RateLimitEntry): Promise<void> {\n const redisKey = this.getKey(key);\n // Clamp to at least 1 second — Math.ceil can produce 0 or negative values\n // when entry.resetTime is in the past due to Redis latency or clock skew.\n const ttlSec = Math.max(1, Math.ceil((entry.resetTime - Date.now()) / 1000));\n await this.client.setex(redisKey, ttlSec, entry.count.toString());\n }\n\n async increment(key: string): Promise<number> {\n const redisKey = this.getKey(key);\n \n // INCR creates key with value 1 if it doesn't exist\n const count = await this.client.incr(redisKey);\n\n // Set expiry only on first increment using EXPIRE, which sets the TTL\n // without overwriting the value (unlike SET ... EX which would reset the\n // counter if two requests increment concurrently before expiry is set).\n if (count === 1) {\n await this.client.expire(redisKey, this.windowSec);\n }\n\n return count;\n }\n\n async decrement(key: string): Promise<void> {\n const redisKey = this.getKey(key);\n await this.client.decr(redisKey);\n }\n\n async reset(key: string): Promise<void> {\n const redisKey = this.getKey(key);\n await this.client.del(redisKey);\n }\n\n async close(): Promise<void> {\n // Don't close the client - it may be shared\n // The caller should manage the client lifecycle\n }\n}\n\n/**\n * Create a Redis store with the given options.\n * Convenience function for functional programming style.\n * \n * @example\n * const store = createRedisStore({ client: redisClient });\n */\nexport function createRedisStore(options: RedisStoreOptions): RedisStore {\n return new RedisStore(options);\n}\n"]}
|
|
@@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,GAAW,IAAA,CAAK,MAAA,CAAO,GAAG,CAAA;AAChC,IAAA,MAAM,IAAA,CAAK,MAAA,CAAO,IAAA,CAAK,QAAQ,CAAA;AAAA,EACjC;AAAA,EAEA,MAAM,MAAM,GAAA,EAA4B;AACtC,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,MAAA,CAAO,GAAG,CAAA;AAChC,IAAA,MAAM,IAAA,CAAK,MAAA,CAAO,GAAA,CAAI,QAAQ,CAAA;AAAA,EAChC;AAAA,EAEA,MAAM,KAAA,GAAuB;AAAA,EAG7B;AACF;AASO,SAAS,iBAAiB,OAAA,EAAwC;AACvE,EAAA,OAAO,IAAI,WAAW,OAAO,CAAA;AAC/B","file":"index.mjs","sourcesContent":["/**\n * @module @arcis/node/core/constants\n * Named constants for Arcis - no magic numbers\n */\n\n// =============================================================================\n// INPUT LIMITS\n// =============================================================================\nexport const INPUT = {\n /** Default maximum input size (1MB) */\n DEFAULT_MAX_SIZE: 1_000_000,\n /** Maximum recursion depth for nested objects */\n MAX_RECURSION_DEPTH: 10,\n} as const;\n\n// =============================================================================\n// RATE LIMITING\n// =============================================================================\nexport const RATE_LIMIT = {\n /** Default window size (1 minute) */\n DEFAULT_WINDOW_MS: 60_000,\n /** Default max requests per window */\n DEFAULT_MAX_REQUESTS: 100,\n /** Default HTTP status code for rate limited responses */\n DEFAULT_STATUS_CODE: 429,\n /** Default error message */\n DEFAULT_MESSAGE: 'Too many requests, please try again later.',\n /** Minimum window size (1 second) */\n MIN_WINDOW_MS: 1_000,\n /** Maximum window size (24 hours) */\n MAX_WINDOW_MS: 86_400_000,\n} as const;\n\n// =============================================================================\n// SECURITY HEADERS\n// =============================================================================\nexport const HEADERS = {\n /** Default Content Security Policy */\n DEFAULT_CSP: [\n \"default-src 'self'\",\n \"script-src 'self'\",\n \"style-src 'self' 'unsafe-inline'\",\n \"img-src 'self' data: https:\",\n \"font-src 'self'\",\n \"object-src 'none'\",\n \"frame-ancestors 'none'\",\n ].join('; '),\n /** Default HSTS max age (1 year in seconds) */\n HSTS_MAX_AGE: 31_536_000,\n /** Default X-Frame-Options value */\n FRAME_OPTIONS: 'DENY' as const,\n /** Default X-Content-Type-Options value */\n CONTENT_TYPE_OPTIONS: 'nosniff',\n /** Default Referrer-Policy value */\n REFERRER_POLICY: 'strict-origin-when-cross-origin',\n /** Default Permissions-Policy value */\n PERMISSIONS_POLICY: 'geolocation=(), microphone=(), camera=()',\n /** Default Cache-Control value for security */\n CACHE_CONTROL: 'no-store, no-cache, must-revalidate, proxy-revalidate',\n} as const;\n\n// =============================================================================\n// XSS PATTERNS (ReDoS-safe)\n// =============================================================================\n\n/**\n * Detection patterns — used to flag whether a string contains XSS payloads.\n * Must stay in sync with XSS_REMOVE_PATTERNS below.\n */\nexport const XSS_PATTERNS = [\n /** Script tags (ReDoS-safe version) */\n /<script[^>]*>[\\s\\S]*?<\\/script>/gi,\n /** javascript: protocol (allow optional spaces before colon) */\n /javascript\\s*:/gi,\n /** vbscript: protocol */\n /vbscript\\s*:/gi,\n /** Event handlers (onclick, onerror, etc.) — any separator before attribute */\n /(?:[\\s/])on\\w+\\s*=/gi,\n /** iframe tags */\n /<iframe/gi,\n /** object tags */\n /<object/gi,\n /** embed tags */\n /<embed/gi,\n /** data: URIs (only dangerous ones, avoid false positives) */\n /(?:^|[\\s\"'=])data:/gi,\n /** URL-encoded script tags */\n /%3Cscript/gi,\n /** SVG with onload */\n /<svg[^>]*onload/gi,\n /** form tags — phishing/credential harvesting via action= redirection */\n /<form[\\s>]/gi,\n /** meta tags — http-equiv refresh redirects or CSP bypass */\n /<meta[\\s>]/gi,\n /** base href hijacking — redirects all relative URLs to attacker domain */\n /<base[\\s>]/gi,\n /** link tag injection — stylesheet or preload CSRF attacks */\n /<link[\\s>]/gi,\n] as const;\n\n/**\n * Removal patterns — used by sanitizeXss() to strip dangerous content.\n * More targeted than XSS_PATTERNS: each pattern captures the full dangerous\n * substring (tag, attribute + value, protocol) so it can be replaced safely.\n * Must stay in sync with XSS_PATTERNS above.\n */\nexport const XSS_REMOVE_PATTERNS = [\n /** Full script blocks (content + tags) */\n /<script[^>]*>[\\s\\S]*?<\\/script>/gi,\n /** Standalone/unclosed script tags */\n /<script[^>]*>/gi,\n /** iframe — full block and partial/unclosed */\n /<iframe[^>]*>[\\s\\S]*?<\\/iframe>/gi,\n /<iframe[^>]*/gi,\n /** object — full block and partial/unclosed */\n /<object[^>]*>[\\s\\S]*?<\\/object>/gi,\n /<object[^>]*/gi,\n /** embed tags */\n /<embed[^>]*/gi,\n /** SVG with inline event handlers */\n /<svg[^>]*onload[^>]*>/gi,\n /** URL-encoded script tags */\n /%3Cscript/gi,\n /** Event handlers with quoted values: onclick=\"...\", onerror='...' */\n /(?:[\\s/])on\\w+\\s*=\\s*[\"'][^\"']*[\"']/gi,\n /** Event handlers with unquoted values: onload=value */\n /(?:[\\s/])on\\w+\\s*=\\s*[^\\s>]*/gi,\n /** javascript: and vbscript: protocols (allow optional spaces before colon) */\n /javascript\\s*:/gi,\n /vbscript\\s*:/gi,\n /** data: URIs with HTML/script content */\n /data\\s*:\\s*text\\/html[^>\\s]*/gi,\n /** form tag injection — phishing via action= redirection */\n /<form[\\s>][^>]*/gi,\n /** meta tag injection — http-equiv refresh or CSP bypass */\n /<meta[\\s>][^>]*/gi,\n /** base href hijacking */\n /<base[\\s>][^>]*/gi,\n /** link tag injection — stylesheet or preload attacks */\n /<link[\\s>][^>]*/gi,\n] as const;\n\n// =============================================================================\n// SQL INJECTION PATTERNS\n// =============================================================================\nexport const SQL_PATTERNS = [\n /** SQL keywords */\n /(\\b(SELECT|INSERT|UPDATE|DELETE|DROP|UNION|ALTER|CREATE|TRUNCATE|EXEC|EXECUTE)\\b)/gi,\n /** SQL comments: ANSI (--), C-style (slash-star ... star-slash), MySQL (#) */\n /(--|\\/\\*|\\*\\/|#)/g,\n /** SQL statement separators */\n /(;|\\|\\||&&)/g,\n /** Boolean injection: OR 1=1 */\n /\\bOR\\s+\\d+\\s*=\\s*\\d+/gi,\n /** Boolean injection: OR 'a'='a' or OR \"a\"=\"a\" (including mixed quotes) */\n /\\bOR\\s+(['\"])[^'\"]*\\1\\s*=\\s*(['\"])[^'\"]*\\2/gi,\n /\\bOR\\s+('[^']*'|\"[^\"]*\")\\s*=\\s*('[^']*'|\"[^\"]*\")/gi,\n /** Boolean injection: AND 1=1 */\n /\\bAND\\s+\\d+\\s*=\\s*\\d+/gi,\n /** Boolean injection: AND 'a'='a' or AND \"a\"=\"a\" (including mixed quotes) */\n /\\bAND\\s+(['\"])[^'\"]*\\1\\s*=\\s*(['\"])[^'\"]*\\2/gi,\n /\\bAND\\s+('[^']*'|\"[^\"]*\")\\s*=\\s*('[^']*'|\"[^\"]*\")/gi,\n /** Time-based blind: SLEEP() */\n /\\bSLEEP\\s*\\(\\s*\\d+\\s*\\)/gi,\n /** Time-based blind: BENCHMARK() */\n /\\bBENCHMARK\\s*\\(/gi,\n /** Time-based blind: PostgreSQL pg_sleep() */\n /\\bpg_sleep\\s*\\(/gi,\n /** Time-based blind: MSSQL WAITFOR DELAY */\n /\\bWAITFOR\\s+DELAY\\b/gi,\n] as const;\n\n// =============================================================================\n// PATH TRAVERSAL PATTERNS\n// =============================================================================\nexport const PATH_PATTERNS = [\n /** Unix path traversal */\n /\\.\\.\\//g,\n /** Windows path traversal */\n /\\.\\.\\\\/g,\n /** URL-encoded traversal (%2e%2e) */\n /%2e%2e/gi,\n /** Double URL-encoded traversal (%252e) */\n /%252e/gi,\n /** Mixed encoding: ..%2F */\n /\\.\\.%2F/gi,\n /** Mixed encoding: %2e./ and .%2e/ */\n /%2e\\.[\\\\/]/gi,\n /\\.%2e[\\\\/]/gi,\n /** Fully URL-encoded: %2e%2e%2f */\n /%2e%2e%2f/gi,\n /** Double URL-encoded forward slash: %252f */\n /%252f/gi,\n /** Dotdotslash bypass: ....// or ....\\\\ */\n /\\.{2,}[/\\\\]{2,}/g,\n /** Null byte injection in paths */\n /\\0/g,\n] as const;\n\n// =============================================================================\n// COMMAND INJECTION PATTERNS\n// =============================================================================\nexport const COMMAND_PATTERNS = [\n /**\n * Shell metacharacters that enable command chaining/substitution.\n * Bare ( and ) are excluded — they appear in common legitimate values\n * (function calls in code fields, math expressions, etc.).\n * Command substitution is caught by the $( combined pattern below.\n * NOTE: ';', '&', '|' may appear in legitimate URL query strings\n * and Markdown; consider disabling command checking (command: false)\n * for fields that intentionally allow those characters.\n */\n /[;&|`]/g,\n /** Command substitution: $( ... ) — matched as a pair to reduce false positives */\n /\\$\\(/g,\n /** URL-encoded control characters (%00-%0F): null, tab, vtab, formfeed, LF, CR */\n /%0[0-9a-f]/gi,\n] as const;\n\n// =============================================================================\n// DANGEROUS KEYS\n// =============================================================================\n\n/**\n * Prototype pollution keys to block.\n * Stored lowercase — always compare with key.toLowerCase().\n *\n * Includes:\n * - __proto__: direct prototype assignment\n * - constructor: access to constructor.prototype chain\n * - prototype: direct prototype property\n * - __defineGetter__/__defineSetter__: legacy property definition (can override getters/setters)\n * - __lookupGetter__/__lookupSetter__: legacy property introspection\n */\nexport const DANGEROUS_PROTO_KEYS = new Set([\n '__proto__',\n 'constructor',\n 'prototype',\n '__definegetter__',\n '__definesetter__',\n '__lookupgetter__',\n '__lookupsetter__',\n]);\n\n/** MongoDB operators to block */\nexport const NOSQL_DANGEROUS_KEYS = new Set([\n // Comparison\n '$gt', '$gte', '$lt', '$lte', '$ne', '$eq', '$in', '$nin',\n // Logical\n '$and', '$or', '$not', '$nor',\n // Element / evaluation\n '$exists', '$type', '$regex', '$where', '$expr', '$mod', '$text', '$jsonSchema',\n // Array\n '$elemMatch', '$all', '$size',\n // JavaScript execution (critical)\n '$function', '$accumulator',\n // Aggregation pipeline operators (injectable via $lookup etc.)\n '$lookup', '$match', '$project', '$group', '$sort', '$limit', '$skip',\n '$unwind', '$addFields', '$replaceRoot',\n]);\n\n// =============================================================================\n// REDACTION\n// =============================================================================\nexport const REDACTION = {\n /** Replacement text for redacted values */\n REPLACEMENT: '[REDACTED]',\n /** Truncation indicator */\n TRUNCATED: '[TRUNCATED]',\n /** Max depth indicator */\n MAX_DEPTH: '[MAX_DEPTH]',\n /** Default max message length */\n DEFAULT_MAX_LENGTH: 10_000,\n /** Default sensitive keys to redact */\n SENSITIVE_KEYS: new Set([\n 'password', 'passwd', 'pwd', 'secret', 'token', 'apikey',\n 'api_key', 'apiKey', 'auth', 'authorization', 'credit_card',\n 'creditcard', 'cc', 'ssn', 'social_security', 'private_key',\n 'privateKey', 'access_token', 'accessToken', 'refresh_token',\n 'refreshToken', 'bearer', 'jwt', 'session', 'cookie',\n 'credentials', 'x-api-key', 'x-auth-token',\n ]),\n} as const;\n\n// =============================================================================\n// VALIDATION PATTERNS\n// =============================================================================\nexport const VALIDATION = {\n /**\n * Email regex pattern.\n * Rejects consecutive dots in local part (e.g. test..foo@example.com),\n * leading/trailing dots, and other common invalid forms.\n */\n EMAIL: /^[^\\s@.][^\\s@]*(?:\\.[^\\s@.][^\\s@]*)*@[^\\s@]+\\.[^\\s@]+$/,\n /**\n * URL regex pattern.\n * Only allows http:// and https:// — explicitly rejects javascript:,\n * data:, vbscript:, and other dangerous URI schemes.\n */\n URL: /^https?:\\/\\/[^\\s/$.?#][^\\s]*$/,\n /** UUID regex pattern (v4) */\n UUID: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,\n} as const;\n\n// =============================================================================\n// ERROR MESSAGES\n// =============================================================================\nexport const ERRORS = {\n /** Generic error message (production) */\n INTERNAL_SERVER_ERROR: 'Internal Server Error',\n /** Input too large error */\n INPUT_TOO_LARGE: (maxSize: number) => `Input exceeds maximum size of ${maxSize} bytes`,\n /** Validation error messages */\n VALIDATION: {\n REQUIRED: (field: string) => `${field} is required`,\n INVALID_TYPE: (field: string, type: string) => `${field} must be a ${type}`,\n MIN_LENGTH: (field: string, min: number) => `${field} must be at least ${min} characters`,\n MAX_LENGTH: (field: string, max: number) => `${field} must be at most ${max} characters`,\n MIN_VALUE: (field: string, min: number) => `${field} must be at least ${min}`,\n MAX_VALUE: (field: string, max: number) => `${field} must be at most ${max}`,\n INVALID_FORMAT: (field: string) => `${field} format is invalid`,\n INVALID_EMAIL: (field: string) => `${field} must be a valid email`,\n INVALID_URL: (field: string) => `${field} must be a valid URL`,\n INVALID_UUID: (field: string) => `${field} must be a valid UUID`,\n INVALID_ENUM: (field: string, values: unknown[]) => `${field} must be one of: ${values.join(', ')}`,\n MIN_ITEMS: (field: string, min: number) => `${field} must have at least ${min} items`,\n MAX_ITEMS: (field: string, max: number) => `${field} must have at most ${max} items`,\n },\n} as const;\n\n// =============================================================================\n// BLOCKED TEXT (for sanitizer replacements)\n// =============================================================================\nexport const BLOCKED = '[BLOCKED]' as const;\n","/**\n * @module @arcis/node/stores/memory\n * In-memory rate limit store\n */\n\nimport type { RateLimitStore, RateLimitEntry } from '../core/types';\nimport { RATE_LIMIT } from '../core/constants';\n\n/**\n * In-memory rate limit store.\n * Suitable for single-instance deployments.\n * For distributed systems, use RedisStore or a custom store.\n * \n * @example\n * const store = new MemoryStore(60000); // 1 minute window\n * const limiter = createRateLimiter({ store });\n */\n/** Default maximum number of keys the in-memory store will hold. */\nconst DEFAULT_MAX_SIZE = 10_000;\n\nexport class MemoryStore implements RateLimitStore {\n private store: Map<string, RateLimitEntry> = new Map();\n private cleanupInterval: ReturnType<typeof setInterval> | null = null;\n private windowMs: number;\n private maxSize: number;\n\n constructor(windowMs: number = RATE_LIMIT.DEFAULT_WINDOW_MS, maxSize: number = DEFAULT_MAX_SIZE) {\n if (!Number.isFinite(windowMs) || windowMs < RATE_LIMIT.MIN_WINDOW_MS) {\n throw new RangeError(\n `MemoryStore: windowMs must be a finite number >= ${RATE_LIMIT.MIN_WINDOW_MS} (got ${windowMs})`\n );\n }\n if (!Number.isFinite(maxSize) || maxSize < 1) {\n throw new RangeError(`MemoryStore: maxSize must be >= 1 (got ${maxSize})`);\n }\n this.windowMs = windowMs;\n this.maxSize = maxSize;\n this.startCleanup();\n }\n\n /**\n * Start the cleanup interval to remove expired entries.\n */\n private startCleanup(): void {\n // Clamp the cleanup interval between 30 s and 5 min regardless of windowMs.\n // Running it every windowMs is fine for typical windows but would fire every\n // second for short windows (e.g. windowMs: 1000), causing O(n) GC pressure.\n const CLEANUP_MIN_MS = 30_000;\n const CLEANUP_MAX_MS = 300_000;\n const cleanupMs = Math.min(Math.max(this.windowMs, CLEANUP_MIN_MS), CLEANUP_MAX_MS);\n\n this.cleanupInterval = setInterval(() => {\n const now = Date.now();\n for (const [key, entry] of this.store.entries()) {\n if (entry.resetTime < now) {\n this.store.delete(key);\n }\n }\n }, cleanupMs);\n\n // Prevent interval from keeping the process alive\n if (typeof this.cleanupInterval.unref === 'function') {\n this.cleanupInterval.unref();\n }\n }\n\n async get(key: string): Promise<RateLimitEntry | null> {\n const entry = this.store.get(key);\n if (!entry) return null;\n \n // Check if expired\n if (entry.resetTime < Date.now()) {\n this.store.delete(key);\n return null;\n }\n \n return entry;\n }\n\n async set(key: string, entry: RateLimitEntry): Promise<void> {\n if (!this.store.has(key) && this.store.size >= this.maxSize) {\n this.evictExpired();\n // If still at capacity after eviction, fail open — don't crash the app\n if (this.store.size >= this.maxSize) return;\n }\n this.store.set(key, entry);\n }\n\n async increment(key: string): Promise<number> {\n const now = Date.now();\n const entry = this.store.get(key);\n\n if (!entry || entry.resetTime < now) {\n // Start new window — check capacity first\n if (this.store.size >= this.maxSize) {\n this.evictExpired();\n if (this.store.size >= this.maxSize) return 1; // fail open\n }\n this.store.set(key, { count: 1, resetTime: now + this.windowMs });\n return 1;\n }\n\n entry.count++;\n return entry.count;\n }\n\n /** Eagerly remove expired entries to reclaim capacity. */\n private evictExpired(): void {\n const now = Date.now();\n for (const [key, entry] of this.store.entries()) {\n if (entry.resetTime < now) this.store.delete(key);\n }\n }\n\n async decrement(key: string): Promise<void> {\n const entry = this.store.get(key);\n if (entry && entry.count > 0) {\n entry.count--;\n }\n }\n\n async reset(key: string): Promise<void> {\n this.store.delete(key);\n }\n\n async close(): Promise<void> {\n if (this.cleanupInterval) {\n clearInterval(this.cleanupInterval);\n this.cleanupInterval = null;\n }\n this.store.clear();\n }\n\n /**\n * Get current store size (for monitoring).\n */\n get size(): number {\n return this.store.size;\n }\n}\n","/**\n * @module @arcis/node/stores/redis\n * Redis rate limit store\n * \n * Note: This is a reference implementation. You'll need to install\n * the 'ioredis' or 'redis' package and pass your client instance.\n */\n\nimport type { RateLimitStore, RateLimitEntry } from '../core/types';\nimport { RATE_LIMIT } from '../core/constants';\n\n/** Generic Redis client interface (works with ioredis, redis, etc.) */\nexport interface RedisClientLike {\n get(key: string): Promise<string | null>;\n set(key: string, value: string, mode?: string, duration?: number): Promise<unknown>;\n setex(key: string, seconds: number, value: string): Promise<unknown>;\n expire(key: string, seconds: number): Promise<unknown>;\n incr(key: string): Promise<number>;\n decr(key: string): Promise<number>;\n del(key: string): Promise<number>;\n ttl(key: string): Promise<number>;\n quit?(): Promise<unknown>;\n disconnect?(): Promise<unknown>;\n}\n\nexport interface RedisStoreOptions {\n /** Redis client instance */\n client: RedisClientLike;\n /** Key prefix. Default: 'arcis:rl:' */\n prefix?: string;\n /** Window size in milliseconds. Default: 60000 */\n windowMs?: number;\n}\n\n/**\n * Redis rate limit store for distributed deployments.\n * \n * @example\n * import Redis from 'ioredis';\n * \n * const redis = new Redis();\n * const store = new RedisStore({ client: redis });\n * const limiter = createRateLimiter({ store });\n * \n * // Cleanup on shutdown\n * process.on('SIGTERM', async () => {\n * await store.close();\n * });\n */\nexport class RedisStore implements RateLimitStore {\n private client: RedisClientLike;\n private prefix: string;\n private windowMs: number;\n private windowSec: number;\n\n constructor(options: RedisStoreOptions) {\n this.client = options.client;\n this.prefix = options.prefix ?? 'arcis:rl:';\n this.windowMs = options.windowMs ?? RATE_LIMIT.DEFAULT_WINDOW_MS;\n this.windowSec = Math.ceil(this.windowMs / 1000);\n }\n\n private getKey(key: string): string {\n return `${this.prefix}${key}`;\n }\n\n async get(key: string): Promise<RateLimitEntry | null> {\n const redisKey = this.getKey(key);\n \n const [countStr, ttl] = await Promise.all([\n this.client.get(redisKey),\n this.client.ttl(redisKey),\n ]);\n \n if (!countStr || ttl < 0) {\n return null;\n }\n \n const count = parseInt(countStr, 10);\n if (isNaN(count)) {\n // Corrupt value in Redis — treat as if key doesn't exist\n return null;\n }\n\n return {\n count,\n resetTime: Date.now() + (ttl * 1000),\n };\n }\n\n async set(key: string, entry: RateLimitEntry): Promise<void> {\n const redisKey = this.getKey(key);\n // Clamp to at least 1 second — Math.ceil can produce 0 or negative values\n // when entry.resetTime is in the past due to Redis latency or clock skew.\n const ttlSec = Math.max(1, Math.ceil((entry.resetTime - Date.now()) / 1000));\n await this.client.setex(redisKey, ttlSec, entry.count.toString());\n }\n\n async increment(key: string): Promise<number> {\n const redisKey = this.getKey(key);\n \n // INCR creates key with value 1 if it doesn't exist\n const count = await this.client.incr(redisKey);\n\n // Set expiry only on first increment using EXPIRE, which sets the TTL\n // without overwriting the value (unlike SET ... EX which would reset the\n // counter if two requests increment concurrently before expiry is set).\n if (count === 1) {\n await this.client.expire(redisKey, this.windowSec);\n }\n\n return count;\n }\n\n async decrement(key: string): Promise<void> {\n const redisKey = this.getKey(key);\n await this.client.decr(redisKey);\n }\n\n async reset(key: string): Promise<void> {\n const redisKey = this.getKey(key);\n await this.client.del(redisKey);\n }\n\n async close(): Promise<void> {\n // Don't close the client - it may be shared\n // The caller should manage the client lifecycle\n }\n}\n\n/**\n * Create a Redis store with the given options.\n * Convenience function for functional programming style.\n * \n * @example\n * const store = createRedisStore({ client: redisClient });\n */\nexport function createRedisStore(options: RedisStoreOptions): RedisStore {\n return new RedisStore(options);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/core/constants.ts","../../src/stores/memory.ts","../../src/stores/redis.ts"],"names":[],"mappings":";AAkBO,IAAM,UAAA,GAAa;AAAA;AAAA,EAExB,iBAAA,EAAmB,GAAA;AAAA,EAMF;AAAA,EAEjB,aAAA,EAA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AK,MAAA,CAAO,GAAG,CAAA;AAChC,IAAA,MAAM,IAAA,CAAK,MAAA,CAAO,GAAA,CAAI,QAAQ,CAAA;AAAA,EAChC;AAAA,EAEA,MAAM,KAAA,GAAuB;AAAA,EAG7B;AACF;AASO,SAAS,iBAAiB,OAAA,EAAwC;AACvE,EAAA,OAAO,IAAI,WAAW,OAAO,CAAA;AAC/B","file":"index.mjs","sourcesContent":["/**\n * @module @arcis/node/core/constants\n * Named constants for Arcis - no magic numbers\n */\n\n// =============================================================================\n// INPUT LIMITS\n// =============================================================================\nexport const INPUT = {\n /** Default maximum input size (1MB) */\n DEFAULT_MAX_SIZE: 1_000_000,\n /** Maximum recursion depth for nested objects */\n MAX_RECURSION_DEPTH: 10,\n} as const;\n\n// =============================================================================\n// RATE LIMITING\n// =============================================================================\nexport const RATE_LIMIT = {\n /** Default window size (1 minute) */\n DEFAULT_WINDOW_MS: 60_000,\n /** Default max requests per window */\n DEFAULT_MAX_REQUESTS: 100,\n /** Default HTTP status code for rate limited responses */\n DEFAULT_STATUS_CODE: 429,\n /** Default error message */\n DEFAULT_MESSAGE: 'Too many requests, please try again later.',\n /** Minimum window size (1 second) */\n MIN_WINDOW_MS: 1_000,\n /** Maximum window size (24 hours) */\n MAX_WINDOW_MS: 86_400_000,\n} as const;\n\n// =============================================================================\n// SECURITY HEADERS\n// =============================================================================\nexport const HEADERS = {\n /** Default Content Security Policy */\n DEFAULT_CSP: [\n \"default-src 'self'\",\n \"script-src 'self'\",\n \"style-src 'self' 'unsafe-inline'\",\n \"img-src 'self' data: https:\",\n \"font-src 'self'\",\n \"object-src 'none'\",\n \"frame-ancestors 'none'\",\n ].join('; '),\n /** Default HSTS max age (1 year in seconds) */\n HSTS_MAX_AGE: 31_536_000,\n /** Default X-Frame-Options value */\n FRAME_OPTIONS: 'DENY' as const,\n /** Default X-Content-Type-Options value */\n CONTENT_TYPE_OPTIONS: 'nosniff',\n /** Default Referrer-Policy value */\n REFERRER_POLICY: 'strict-origin-when-cross-origin',\n /** Default Permissions-Policy value */\n PERMISSIONS_POLICY: 'geolocation=(), microphone=(), camera=()',\n /** Default Cache-Control value for security */\n CACHE_CONTROL: 'no-store, no-cache, must-revalidate, proxy-revalidate',\n} as const;\n\n// =============================================================================\n// XSS PATTERNS (ReDoS-safe)\n// =============================================================================\n\n/**\n * Detection patterns — used to flag whether a string contains XSS payloads.\n * Must stay in sync with XSS_REMOVE_PATTERNS below.\n */\nexport const XSS_PATTERNS = [\n /** Script tags (ReDoS-safe version) */\n /<script[^>]*>[\\s\\S]*?<\\/script>/gi,\n /** javascript: protocol (allow optional spaces before colon) */\n /javascript\\s*:/gi,\n /** vbscript: protocol */\n /vbscript\\s*:/gi,\n /** Event handlers (onclick, onerror, etc.) — any separator before attribute */\n /(?:[\\s/])on\\w+\\s*=/gi,\n /** iframe tags */\n /<iframe/gi,\n /** object tags */\n /<object/gi,\n /** embed tags */\n /<embed/gi,\n /** data: URIs (only dangerous ones, avoid false positives) */\n /(?:^|[\\s\"'=])data:/gi,\n /** URL-encoded script tags */\n /%3Cscript/gi,\n /** SVG with onload */\n /<svg[^>]*onload/gi,\n /** form tags — phishing/credential harvesting via action= redirection */\n /<form[\\s>]/gi,\n /** meta tags — http-equiv refresh redirects or CSP bypass */\n /<meta[\\s>]/gi,\n /** base href hijacking — redirects all relative URLs to attacker domain */\n /<base[\\s>]/gi,\n /** link tag injection — stylesheet or preload CSRF attacks */\n /<link[\\s>]/gi,\n] as const;\n\n/**\n * Removal patterns — used by sanitizeXss() to strip dangerous content.\n * More targeted than XSS_PATTERNS: each pattern captures the full dangerous\n * substring (tag, attribute + value, protocol) so it can be replaced safely.\n * Must stay in sync with XSS_PATTERNS above.\n */\nexport const XSS_REMOVE_PATTERNS = [\n /** Full script blocks (content + tags) */\n /<script[^>]*>[\\s\\S]*?<\\/script>/gi,\n /** Standalone/unclosed script tags */\n /<script[^>]*>/gi,\n /** style — CSS expression() and behavior: attacks (IE-era but still relevant) */\n /<style[^>]*>[\\s\\S]*?<\\/style>/gi,\n /<style[^>]*/gi,\n /** iframe — full block and partial/unclosed */\n /<iframe[^>]*>[\\s\\S]*?<\\/iframe>/gi,\n /<iframe[^>]*/gi,\n /** object — full block and partial/unclosed */\n /<object[^>]*>[\\s\\S]*?<\\/object>/gi,\n /<object[^>]*/gi,\n /** embed tags */\n /<embed[^>]*/gi,\n /** SVG with inline event handlers */\n /<svg[^>]*onload[^>]*>/gi,\n /** URL-encoded script tags */\n /%3Cscript/gi,\n /** Event handlers with quoted values: onclick=\"...\", onerror='...' */\n /(?:[\\s/])on\\w+\\s*=\\s*[\"'][^\"']*[\"']/gi,\n /** Event handlers with unquoted values: onload=value */\n /(?:[\\s/])on\\w+\\s*=\\s*[^\\s>]*/gi,\n /** javascript: and vbscript: protocols (allow optional spaces before colon) */\n /javascript\\s*:/gi,\n /vbscript\\s*:/gi,\n /** data: URIs with HTML/script content */\n /data\\s*:\\s*text\\/html[^>\\s]*/gi,\n /** form tag injection — phishing via action= redirection */\n /<form[\\s>][^>]*/gi,\n /** meta tag injection — http-equiv refresh or CSP bypass */\n /<meta[\\s>][^>]*/gi,\n /** base href hijacking */\n /<base[\\s>][^>]*/gi,\n /** link tag injection — stylesheet or preload attacks */\n /<link[\\s>][^>]*/gi,\n] as const;\n\n// =============================================================================\n// SQL INJECTION PATTERNS\n// =============================================================================\nexport const SQL_PATTERNS = [\n /** SQL keywords */\n /(\\b(SELECT|INSERT|UPDATE|DELETE|DROP|UNION|ALTER|CREATE|TRUNCATE|EXEC|EXECUTE)\\b)/gi,\n /** SQL comments: ANSI (--), C-style (slash-star ... star-slash), MySQL (#) */\n /(--|\\/\\*|\\*\\/|#)/g,\n /** SQL statement separators */\n /(;|\\|\\||&&)/g,\n /** Boolean injection: OR 1=1 */\n /\\bOR\\s+\\d+\\s*=\\s*\\d+/gi,\n /** Boolean injection: OR 'a'='a' or OR \"a\"=\"a\" (including mixed quotes) */\n /\\bOR\\s+(['\"])[^'\"]*\\1\\s*=\\s*(['\"])[^'\"]*\\2/gi,\n /\\bOR\\s+('[^']*'|\"[^\"]*\")\\s*=\\s*('[^']*'|\"[^\"]*\")/gi,\n /** Boolean injection: AND 1=1 */\n /\\bAND\\s+\\d+\\s*=\\s*\\d+/gi,\n /** Boolean injection: AND 'a'='a' or AND \"a\"=\"a\" (including mixed quotes) */\n /\\bAND\\s+(['\"])[^'\"]*\\1\\s*=\\s*(['\"])[^'\"]*\\2/gi,\n /\\bAND\\s+('[^']*'|\"[^\"]*\")\\s*=\\s*('[^']*'|\"[^\"]*\")/gi,\n /** Time-based blind: SLEEP() */\n /\\bSLEEP\\s*\\(\\s*\\d+\\s*\\)/gi,\n /** Time-based blind: BENCHMARK() */\n /\\bBENCHMARK\\s*\\(/gi,\n /** Time-based blind: PostgreSQL pg_sleep() */\n /\\bpg_sleep\\s*\\(/gi,\n /** Time-based blind: MSSQL WAITFOR DELAY */\n /\\bWAITFOR\\s+DELAY\\b/gi,\n] as const;\n\n// =============================================================================\n// PATH TRAVERSAL PATTERNS\n// =============================================================================\nexport const PATH_PATTERNS = [\n /** Unix path traversal */\n /\\.\\.\\//g,\n /** Windows path traversal */\n /\\.\\.\\\\/g,\n /** URL-encoded traversal (%2e%2e) */\n /%2e%2e/gi,\n /** Double URL-encoded traversal (%252e) */\n /%252e/gi,\n /** Mixed encoding: ..%2F */\n /\\.\\.%2F/gi,\n /** Mixed encoding: %2e./ and .%2e/ */\n /%2e\\.[\\\\/]/gi,\n /\\.%2e[\\\\/]/gi,\n /** Fully URL-encoded: %2e%2e%2f */\n /%2e%2e%2f/gi,\n /** Double URL-encoded forward slash: %252f */\n /%252f/gi,\n /** Dotdotslash bypass: ....// or ....\\\\ */\n /\\.{2,}[/\\\\]{2,}/g,\n /** Null byte injection in paths */\n /\\0/g,\n] as const;\n\n// =============================================================================\n// COMMAND INJECTION PATTERNS\n// =============================================================================\nexport const COMMAND_PATTERNS = [\n /**\n * Shell metacharacters that enable command chaining/substitution.\n * Bare ( and ) are excluded — they appear in common legitimate values\n * (function calls in code fields, math expressions, etc.).\n * Command substitution is caught by the $( combined pattern below.\n * NOTE: ';', '&', '|' may appear in legitimate URL query strings\n * and Markdown; consider disabling command checking (command: false)\n * for fields that intentionally allow those characters.\n */\n /[;&|`]/g,\n /** Command substitution: $( ... ) — matched as a pair to reduce false positives */\n /\\$\\(/g,\n /** URL-encoded control characters (%00-%0F): null, tab, vtab, formfeed, LF, CR */\n /%0[0-9a-f]/gi,\n] as const;\n\n// =============================================================================\n// DANGEROUS KEYS\n// =============================================================================\n\n/**\n * Prototype pollution keys to block.\n * Stored lowercase — always compare with key.toLowerCase().\n *\n * Includes:\n * - __proto__: direct prototype assignment\n * - constructor: access to constructor.prototype chain\n * - prototype: direct prototype property\n * - __defineGetter__/__defineSetter__: legacy property definition (can override getters/setters)\n * - __lookupGetter__/__lookupSetter__: legacy property introspection\n */\nexport const DANGEROUS_PROTO_KEYS = new Set([\n '__proto__',\n 'constructor',\n 'prototype',\n '__definegetter__',\n '__definesetter__',\n '__lookupgetter__',\n '__lookupsetter__',\n]);\n\n/** MongoDB operators to block */\nexport const NOSQL_DANGEROUS_KEYS = new Set([\n // Comparison\n '$gt', '$gte', '$lt', '$lte', '$ne', '$eq', '$in', '$nin',\n // Logical\n '$and', '$or', '$not', '$nor',\n // Element / evaluation\n '$exists', '$type', '$regex', '$where', '$expr', '$mod', '$text', '$jsonSchema',\n // Array\n '$elemMatch', '$all', '$size',\n // JavaScript execution (critical)\n '$function', '$accumulator',\n // Aggregation pipeline operators (injectable via $lookup etc.)\n '$lookup', '$match', '$project', '$group', '$sort', '$limit', '$skip',\n '$unwind', '$addFields', '$replaceRoot',\n]);\n\n// =============================================================================\n// REDACTION\n// =============================================================================\nexport const REDACTION = {\n /** Replacement text for redacted values */\n REPLACEMENT: '[REDACTED]',\n /** Truncation indicator */\n TRUNCATED: '[TRUNCATED]',\n /** Max depth indicator */\n MAX_DEPTH: '[MAX_DEPTH]',\n /** Default max message length */\n DEFAULT_MAX_LENGTH: 10_000,\n /** Default sensitive keys to redact */\n SENSITIVE_KEYS: new Set([\n 'password', 'passwd', 'pwd', 'secret', 'token', 'apikey',\n 'api_key', 'apiKey', 'auth', 'authorization', 'credit_card',\n 'creditcard', 'cc', 'ssn', 'social_security', 'private_key',\n 'privateKey', 'access_token', 'accessToken', 'refresh_token',\n 'refreshToken', 'bearer', 'jwt', 'session', 'cookie',\n 'credentials', 'x-api-key', 'x-auth-token',\n ]),\n} as const;\n\n// =============================================================================\n// VALIDATION PATTERNS\n// =============================================================================\nexport const VALIDATION = {\n /**\n * Email regex pattern.\n * Rejects consecutive dots in local part (e.g. test..foo@example.com),\n * leading/trailing dots, and other common invalid forms.\n */\n EMAIL: /^[^\\s@.][^\\s@]*(?:\\.[^\\s@.][^\\s@]*)*@[^\\s@]+\\.[^\\s@]+$/,\n /**\n * URL regex pattern.\n * Only allows http:// and https:// — explicitly rejects javascript:,\n * data:, vbscript:, and other dangerous URI schemes.\n */\n URL: /^https?:\\/\\/[^\\s/$.?#][^\\s]*$/,\n /** UUID regex pattern (v4) */\n UUID: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,\n} as const;\n\n// =============================================================================\n// ERROR MESSAGES\n// =============================================================================\nexport const ERRORS = {\n /** Generic error message (production) */\n INTERNAL_SERVER_ERROR: 'Internal Server Error',\n /** Input too large error */\n INPUT_TOO_LARGE: (maxSize: number) => `Input exceeds maximum size of ${maxSize} bytes`,\n /** Validation error messages */\n VALIDATION: {\n REQUIRED: (field: string) => `${field} is required`,\n INVALID_TYPE: (field: string, type: string) => `${field} must be a ${type}`,\n MIN_LENGTH: (field: string, min: number) => `${field} must be at least ${min} characters`,\n MAX_LENGTH: (field: string, max: number) => `${field} must be at most ${max} characters`,\n MIN_VALUE: (field: string, min: number) => `${field} must be at least ${min}`,\n MAX_VALUE: (field: string, max: number) => `${field} must be at most ${max}`,\n INVALID_FORMAT: (field: string) => `${field} format is invalid`,\n INVALID_EMAIL: (field: string) => `${field} must be a valid email`,\n INVALID_URL: (field: string) => `${field} must be a valid URL`,\n INVALID_UUID: (field: string) => `${field} must be a valid UUID`,\n INVALID_ENUM: (field: string, values: unknown[]) => `${field} must be one of: ${values.join(', ')}`,\n MIN_ITEMS: (field: string, min: number) => `${field} must have at least ${min} items`,\n MAX_ITEMS: (field: string, max: number) => `${field} must have at most ${max} items`,\n },\n} as const;\n\n// =============================================================================\n// BLOCKED TEXT (for sanitizer replacements)\n// =============================================================================\nexport const BLOCKED = '[BLOCKED]' as const;\n","/**\n * @module @arcis/node/stores/memory\n * In-memory rate limit store\n */\n\nimport type { RateLimitStore, RateLimitEntry } from '../core/types';\nimport { RATE_LIMIT } from '../core/constants';\n\n/**\n * In-memory rate limit store.\n * Suitable for single-instance deployments.\n * For distributed systems, use RedisStore or a custom store.\n * \n * @example\n * const store = new MemoryStore(60000); // 1 minute window\n * const limiter = createRateLimiter({ store });\n */\n/** Default maximum number of keys the in-memory store will hold. */\nconst DEFAULT_MAX_SIZE = 10_000;\n\nexport class MemoryStore implements RateLimitStore {\n private store: Map<string, RateLimitEntry> = new Map();\n private cleanupInterval: ReturnType<typeof setInterval> | null = null;\n private windowMs: number;\n private maxSize: number;\n\n constructor(windowMs: number = RATE_LIMIT.DEFAULT_WINDOW_MS, maxSize: number = DEFAULT_MAX_SIZE) {\n if (!Number.isFinite(windowMs) || windowMs < RATE_LIMIT.MIN_WINDOW_MS) {\n throw new RangeError(\n `MemoryStore: windowMs must be a finite number >= ${RATE_LIMIT.MIN_WINDOW_MS} (got ${windowMs})`\n );\n }\n if (!Number.isFinite(maxSize) || maxSize < 1) {\n throw new RangeError(`MemoryStore: maxSize must be >= 1 (got ${maxSize})`);\n }\n this.windowMs = windowMs;\n this.maxSize = maxSize;\n this.startCleanup();\n }\n\n /**\n * Start the cleanup interval to remove expired entries.\n */\n private startCleanup(): void {\n // Clamp the cleanup interval between 30 s and 5 min regardless of windowMs.\n // Running it every windowMs is fine for typical windows but would fire every\n // second for short windows (e.g. windowMs: 1000), causing O(n) GC pressure.\n const CLEANUP_MIN_MS = 30_000;\n const CLEANUP_MAX_MS = 300_000;\n const cleanupMs = Math.min(Math.max(this.windowMs, CLEANUP_MIN_MS), CLEANUP_MAX_MS);\n\n this.cleanupInterval = setInterval(() => {\n const now = Date.now();\n for (const [key, entry] of this.store.entries()) {\n if (entry.resetTime < now) {\n this.store.delete(key);\n }\n }\n }, cleanupMs);\n\n // Prevent interval from keeping the process alive\n if (typeof this.cleanupInterval.unref === 'function') {\n this.cleanupInterval.unref();\n }\n }\n\n async get(key: string): Promise<RateLimitEntry | null> {\n const entry = this.store.get(key);\n if (!entry) return null;\n \n // Check if expired\n if (entry.resetTime < Date.now()) {\n this.store.delete(key);\n return null;\n }\n \n return entry;\n }\n\n async set(key: string, entry: RateLimitEntry): Promise<void> {\n if (!this.store.has(key) && this.store.size >= this.maxSize) {\n this.evictExpired();\n // If still at capacity after eviction, fail open — don't crash the app\n if (this.store.size >= this.maxSize) return;\n }\n this.store.set(key, entry);\n }\n\n async increment(key: string): Promise<number> {\n const now = Date.now();\n const entry = this.store.get(key);\n\n if (!entry || entry.resetTime < now) {\n // Start new window — check capacity first\n if (this.store.size >= this.maxSize) {\n this.evictExpired();\n if (this.store.size >= this.maxSize) return 1; // fail open\n }\n this.store.set(key, { count: 1, resetTime: now + this.windowMs });\n return 1;\n }\n\n entry.count++;\n return entry.count;\n }\n\n /** Eagerly remove expired entries to reclaim capacity. */\n private evictExpired(): void {\n const now = Date.now();\n for (const [key, entry] of this.store.entries()) {\n if (entry.resetTime < now) this.store.delete(key);\n }\n }\n\n async decrement(key: string): Promise<void> {\n const entry = this.store.get(key);\n if (entry && entry.count > 0) {\n entry.count--;\n }\n }\n\n async reset(key: string): Promise<void> {\n this.store.delete(key);\n }\n\n async close(): Promise<void> {\n if (this.cleanupInterval) {\n clearInterval(this.cleanupInterval);\n this.cleanupInterval = null;\n }\n this.store.clear();\n }\n\n /**\n * Get current store size (for monitoring).\n */\n get size(): number {\n return this.store.size;\n }\n}\n","/**\n * @module @arcis/node/stores/redis\n * Redis rate limit store\n * \n * Note: This is a reference implementation. You'll need to install\n * the 'ioredis' or 'redis' package and pass your client instance.\n */\n\nimport type { RateLimitStore, RateLimitEntry } from '../core/types';\nimport { RATE_LIMIT } from '../core/constants';\n\n/** Generic Redis client interface (works with ioredis, redis, etc.) */\nexport interface RedisClientLike {\n get(key: string): Promise<string | null>;\n set(key: string, value: string, mode?: string, duration?: number): Promise<unknown>;\n setex(key: string, seconds: number, value: string): Promise<unknown>;\n expire(key: string, seconds: number): Promise<unknown>;\n incr(key: string): Promise<number>;\n decr(key: string): Promise<number>;\n del(key: string): Promise<number>;\n ttl(key: string): Promise<number>;\n quit?(): Promise<unknown>;\n disconnect?(): Promise<unknown>;\n}\n\nexport interface RedisStoreOptions {\n /** Redis client instance */\n client: RedisClientLike;\n /** Key prefix. Default: 'arcis:rl:' */\n prefix?: string;\n /** Window size in milliseconds. Default: 60000 */\n windowMs?: number;\n}\n\n/**\n * Redis rate limit store for distributed deployments.\n * \n * @example\n * import Redis from 'ioredis';\n * \n * const redis = new Redis();\n * const store = new RedisStore({ client: redis });\n * const limiter = createRateLimiter({ store });\n * \n * // Cleanup on shutdown\n * process.on('SIGTERM', async () => {\n * await store.close();\n * });\n */\nexport class RedisStore implements RateLimitStore {\n private client: RedisClientLike;\n private prefix: string;\n private windowMs: number;\n private windowSec: number;\n\n constructor(options: RedisStoreOptions) {\n this.client = options.client;\n this.prefix = options.prefix ?? 'arcis:rl:';\n this.windowMs = options.windowMs ?? RATE_LIMIT.DEFAULT_WINDOW_MS;\n this.windowSec = Math.ceil(this.windowMs / 1000);\n }\n\n private getKey(key: string): string {\n return `${this.prefix}${key}`;\n }\n\n async get(key: string): Promise<RateLimitEntry | null> {\n const redisKey = this.getKey(key);\n \n const [countStr, ttl] = await Promise.all([\n this.client.get(redisKey),\n this.client.ttl(redisKey),\n ]);\n \n if (!countStr || ttl < 0) {\n return null;\n }\n \n const count = parseInt(countStr, 10);\n if (isNaN(count)) {\n // Corrupt value in Redis — treat as if key doesn't exist\n return null;\n }\n\n return {\n count,\n resetTime: Date.now() + (ttl * 1000),\n };\n }\n\n async set(key: string, entry: RateLimitEntry): Promise<void> {\n const redisKey = this.getKey(key);\n // Clamp to at least 1 second — Math.ceil can produce 0 or negative values\n // when entry.resetTime is in the past due to Redis latency or clock skew.\n const ttlSec = Math.max(1, Math.ceil((entry.resetTime - Date.now()) / 1000));\n await this.client.setex(redisKey, ttlSec, entry.count.toString());\n }\n\n async increment(key: string): Promise<number> {\n const redisKey = this.getKey(key);\n \n // INCR creates key with value 1 if it doesn't exist\n const count = await this.client.incr(redisKey);\n\n // Set expiry only on first increment using EXPIRE, which sets the TTL\n // without overwriting the value (unlike SET ... EX which would reset the\n // counter if two requests increment concurrently before expiry is set).\n if (count === 1) {\n await this.client.expire(redisKey, this.windowSec);\n }\n\n return count;\n }\n\n async decrement(key: string): Promise<void> {\n const redisKey = this.getKey(key);\n await this.client.decr(redisKey);\n }\n\n async reset(key: string): Promise<void> {\n const redisKey = this.getKey(key);\n await this.client.del(redisKey);\n }\n\n async close(): Promise<void> {\n // Don't close the client - it may be shared\n // The caller should manage the client lifecycle\n }\n}\n\n/**\n * Create a Redis store with the given options.\n * Convenience function for functional programming style.\n * \n * @example\n * const store = createRedisStore({ client: redisClient });\n */\nexport function createRedisStore(options: RedisStoreOptions): RedisStore {\n return new RedisStore(options);\n}\n"]}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import type { TelemetryEvent, TelemetryOptions } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* In-memory batching client that ships `TelemetryEvent` objects to an
|
|
4
|
+
* Arcis dashboard server.
|
|
5
|
+
*
|
|
6
|
+
* Design rules (spec/API_SPEC.md §9):
|
|
7
|
+
* 1. `record()` is synchronous and never throws — safe to call from hot paths.
|
|
8
|
+
* 2. Flushes trigger on batchSize OR flushIntervalMs, whichever comes first.
|
|
9
|
+
* 3. Network errors are fail-open: they call `onError` (if provided) and
|
|
10
|
+
* drop the batch. No retry, no disk persistence, no backpressure.
|
|
11
|
+
* 4. `close()` attempts one final flush; safe to call multiple times.
|
|
12
|
+
* 5. Interval timer uses `unref()` so it never holds the process open.
|
|
13
|
+
*/
|
|
14
|
+
export declare class TelemetryClient {
|
|
15
|
+
private queue;
|
|
16
|
+
private readonly endpoint;
|
|
17
|
+
private readonly apiKey;
|
|
18
|
+
private readonly workspaceId;
|
|
19
|
+
private readonly batchSize;
|
|
20
|
+
private readonly flushIntervalMs;
|
|
21
|
+
private readonly onError;
|
|
22
|
+
private timer;
|
|
23
|
+
private flushing;
|
|
24
|
+
private closed;
|
|
25
|
+
private signalHandler;
|
|
26
|
+
constructor(options: TelemetryOptions);
|
|
27
|
+
/**
|
|
28
|
+
* Enqueue an event. Fast, synchronous, cannot throw.
|
|
29
|
+
* Triggers a flush if the queue has reached `batchSize`.
|
|
30
|
+
*/
|
|
31
|
+
record(event: TelemetryEvent): void;
|
|
32
|
+
/**
|
|
33
|
+
* Manually flush the queue. Pulls up to `batchSize` events into a batch and
|
|
34
|
+
* POSTs them. Returns a resolved promise on success OR on handled failure.
|
|
35
|
+
* Never throws.
|
|
36
|
+
*/
|
|
37
|
+
flush(): Promise<void>;
|
|
38
|
+
/**
|
|
39
|
+
* Shut down: stop the interval timer and attempt one final flush.
|
|
40
|
+
* Safe to call multiple times.
|
|
41
|
+
*/
|
|
42
|
+
close(): Promise<void>;
|
|
43
|
+
/**
|
|
44
|
+
* Register `SIGTERM` / `SIGINT` handlers that call `close()` to drain
|
|
45
|
+
* the queue on graceful shutdown. Opt-in — libraries should not silently
|
|
46
|
+
* attach global signal handlers. Safe to call multiple times.
|
|
47
|
+
*/
|
|
48
|
+
installShutdownHooks(): void;
|
|
49
|
+
/** Count of events currently waiting to be sent. Useful for tests. */
|
|
50
|
+
get pendingCount(): number;
|
|
51
|
+
private send;
|
|
52
|
+
private startTimer;
|
|
53
|
+
private safeNotify;
|
|
54
|
+
}
|
|
55
|
+
export declare class TelemetryHttpError extends Error {
|
|
56
|
+
readonly status: number;
|
|
57
|
+
readonly responseBody: string;
|
|
58
|
+
constructor(status: number, responseBody: string);
|
|
59
|
+
}
|
|
60
|
+
//# sourceMappingURL=client.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/telemetry/client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAUhE;;;;;;;;;;;GAWG;AACH,qBAAa,eAAe;IAC1B,OAAO,CAAC,KAAK,CAAwB;IACrC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAqB;IAC5C,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAqB;IACjD,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAS;IACnC,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAS;IACzC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAW;IACnC,OAAO,CAAC,KAAK,CAA6C;IAC1D,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,aAAa,CAA2B;gBAEpC,OAAO,EAAE,gBAAgB;IAwBrC;;;OAGG;IACH,MAAM,CAAC,KAAK,EAAE,cAAc,GAAG,IAAI;IASnC;;;;OAIG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAoB5B;;;OAGG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAuB5B;;;;OAIG;IACH,oBAAoB,IAAI,IAAI;IAU5B,sEAAsE;IACtE,IAAI,YAAY,IAAI,MAAM,CAEzB;YAIa,IAAI;IA2BlB,OAAO,CAAC,UAAU;IASlB,OAAO,CAAC,UAAU;CAOnB;AAED,qBAAa,kBAAmB,SAAQ,KAAK;aAEzB,MAAM,EAAE,MAAM;aACd,YAAY,EAAE,MAAM;gBADpB,MAAM,EAAE,MAAM,EACd,YAAY,EAAE,MAAM;CAKvC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/telemetry/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,kBAAkB,EAAE,MAAM,UAAU,CAAC;AAC/D,YAAY,EACV,cAAc,EACd,gBAAgB,EAChB,iBAAiB,EACjB,iBAAiB,GAClB,MAAM,SAAS,CAAC"}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Telemetry contract — mirrors spec/API_SPEC.md §9 exactly.
|
|
3
|
+
* Shape accepted by the Arcis dashboard server's POST /v1/events endpoint.
|
|
4
|
+
*/
|
|
5
|
+
export type TelemetryDecision = 'allow' | 'deny' | 'challenge';
|
|
6
|
+
export type TelemetrySeverity = 'critical' | 'high' | 'medium' | 'low';
|
|
7
|
+
/**
|
|
8
|
+
* A single decision event emitted by the Arcis middleware.
|
|
9
|
+
* All optional fields are filled server-side with defaults when omitted.
|
|
10
|
+
*/
|
|
11
|
+
export interface TelemetryEvent {
|
|
12
|
+
/** ISO-8601 timestamp. SDK populates; server falls back to now() if missing. */
|
|
13
|
+
ts?: string;
|
|
14
|
+
/** Client IP extracted from the request. */
|
|
15
|
+
ip: string;
|
|
16
|
+
/** HTTP method (e.g., "GET", "POST"). */
|
|
17
|
+
method: string;
|
|
18
|
+
/** Request path without query string. */
|
|
19
|
+
path: string;
|
|
20
|
+
/** Final middleware decision. */
|
|
21
|
+
decision: TelemetryDecision;
|
|
22
|
+
/** Attack family (e.g., "xss", "sql", "ssrf"). Null for allowed traffic. */
|
|
23
|
+
vector?: string;
|
|
24
|
+
/** Specific rule fired (e.g., "sql/union-select"). */
|
|
25
|
+
rule?: string;
|
|
26
|
+
/** Finding severity. */
|
|
27
|
+
severity?: TelemetrySeverity;
|
|
28
|
+
/** ISO-3166 alpha-2 country code. */
|
|
29
|
+
country?: string;
|
|
30
|
+
/** Request User-Agent header. Server defaults to "" if missing. */
|
|
31
|
+
userAgent?: string;
|
|
32
|
+
/** Human-readable explanation for the dashboard. */
|
|
33
|
+
reason?: string;
|
|
34
|
+
/** HTTP status code returned by the middleware. Server defaults to 200. */
|
|
35
|
+
status: number;
|
|
36
|
+
/** Exact token that triggered the rule (e.g., "UNION SELECT"). */
|
|
37
|
+
matchedPattern?: string;
|
|
38
|
+
/** Middleware processing time in milliseconds, fractional. */
|
|
39
|
+
latencyMs?: number;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* User-provided configuration for the telemetry client.
|
|
43
|
+
* Passed via `telemetry` on the main `ArcisOptions`.
|
|
44
|
+
*/
|
|
45
|
+
export interface TelemetryOptions {
|
|
46
|
+
/** Full URL of the ingest endpoint, e.g., "https://arcis.mycorp.com/v1/events". */
|
|
47
|
+
endpoint: string;
|
|
48
|
+
/** Optional bearer token. Sent as `Authorization: Bearer <apiKey>`. */
|
|
49
|
+
apiKey?: string;
|
|
50
|
+
/** Optional workspace id. Sent as `x-workspace-id`. Defaults server-side to "default". */
|
|
51
|
+
workspaceId?: string;
|
|
52
|
+
/** Flush when queue reaches this size. Default: 50. Range: 1-500. */
|
|
53
|
+
batchSize?: number;
|
|
54
|
+
/** Periodic flush interval in milliseconds. Default: 5000. Minimum: 500. */
|
|
55
|
+
flushIntervalMs?: number;
|
|
56
|
+
/** Error hook for network/HTTP failures. If omitted, errors are swallowed silently. */
|
|
57
|
+
onError?: (err: Error) => void;
|
|
58
|
+
}
|
|
59
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/telemetry/types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,MAAM,MAAM,iBAAiB,GAAG,OAAO,GAAG,MAAM,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GED
|
@@ -11,6 +11,9 @@ var XSS_REMOVE_PATTERNS = [
|
|
|
11
11
|
/<script[^>]*>[\s\S]*?<\/script>/gi,
|
|
12
12
|
/** Standalone/unclosed script tags */
|
|
13
13
|
/<script[^>]*>/gi,
|
|
14
|
+
/** style — CSS expression() and behavior: attacks (IE-era but still relevant) */
|
|
15
|
+
/<style[^>]*>[\s\S]*?<\/style>/gi,
|
|
16
|
+
/<style[^>]*/gi,
|
|
14
17
|
/** iframe — full block and partial/unclosed */
|
|
15
18
|
/<iframe[^>]*>[\s\S]*?<\/iframe>/gi,
|
|
16
19
|
/<iframe[^>]*/gi,
|