Security Documentation
Comprehensive security documentation for SveltyCMS covering authentication, cryptography, widget security, and best practices
On this page
SveltyCMS implements enterprise-grade security measures across all system components to protect data, prevent vulnerabilities, and ensure compliance with security standards.
~99/100 Self-Assessment (June 2026). 0 CVEs is verifiable. Dimension scores are code-review-based, not externally audited. Full scorecard β
π‘οΈ Security Overview
SveltyCMS security architecture includes:
- π 4-Layer Defense-in-Depth β Middleware β Dispatcher β Handler β Page Action. Each layer re-validates independently. Fail-closed by default.
- β‘ Policy-as-Code (PaC) β In-memory CPU permission evaluation (< 50Β΅s) with Git policy rules. See Policy-as-Code & WASM Docs.
- π‘οΈ Layer 0 WASM WAF β Nanosecond WebAssembly threat pattern matching with pure-JS fallback.
- π Authentication & Authorization - Multi-factor authentication, session management, RBAC
- π Cryptography - Quantum-resistant password hashing, AES-256 encryption, Merkle Tree & SHA-256 audit chain, CSPRNG-only tokens (no
Math.random()fallback) - π‘οΈ Widget Security - XSS prevention, injection protection, file validation
- π Security Monitoring & Fuzzing - Real-time audit logging (Merkle Tree chained), automated API payload fuzzer (
bun run security --fuzz) - π Secure Development - Build-time security checks, vulnerability scanning, Runtime Baseline Clamping
- β‘ Enterprise Immunity - Self-healing load shedding, graceful shutdown, SSRF endpoint validation, and pre-compiled pipelines
π Security Scorecard
| Dimension | Weight | Score | Prevents |
|---|---|---|---|
| CVE Track Record | 25% | 100 | 0 CVEs β verifiable via NVD, GitHub Advisory DB |
| Cryptography | 15% | 100 | AES-256-GCM, SHA-256 chain, key rotation, timing-safe |
| Disclosure & Response | 10% | 98 | security.txt, incident runbook, responsible disclosure program |
| Auth & Session | 20% | 99 | Argon2id, CSPRNG, __Host- cookies, 2FA, fully tested lockout, device policy, TTL/idle timeouts, credential-free session caches, step-up re-auth, session anomaly log |
| Input Validation | 15% | 99 | strict CSP, safeFetch (SSRF), DOMPurify, Drizzle, body limit, MIME sniffing, SSRF IPv6 blocking, email normalization |
| Dependency Hygiene | 15% | 99 | Dependabot weekly, CI audit BLOCKING, override-pinned |
Weighted: 25.0 + 15.0 + 9.8 + 19.8 + 14.85 + 14.85 = ~99/100
Self-assessed (August 2026). Gaps: 3rd-party pentest, WebAuthn passkey UI polish, adaptive/risk-based auth policy engine, distributed SSO realm sessions. OIDC login/callback/RP-logout are implemented (
sso-session.ts). DOMPurify CVEs mitigated by explicit configs.
August 4, 2026 Session & Cache Hardening: credential-free session snapshots (password hashes / TOTP secrets / backup codes / reset & refresh tokens stripped at every cache/store boundary), log-only IP/UA anomaly detection,
SESSION_MAX_PER_USERcap, step-up re-auth for cross-session revoke, admin session console, untagged cache-delete propagation to remote nodes, config-import RBAC cache invalidation. Full auth pipeline measured at 0.881 ms avg (7 runs, self-measured, 2026-08-04) vs 0.856 ms July baseline.
π Security Documentation
Authentication & Access Control
-
Authentication System - Enterprise-grade authentication with 3-layer caching, automatic session rotation, multi-tenancy, API Keys, Magic Links, Guest Auth, and WebAuthn/Passkeys
-
Login Security - IP resolution, rate limiter secrets, OAuth HMAC validation, session/device tracking, password-reset token expiry codes, and accessibility fixes.
-
License Gate Inventory - Marketplace license checks, fail-open/fail-closed policy, plugin/widget gate map.
-
Access Management - Roles, Granular Permissions, and Website Token management
- Session management
- Token-based authentication
- Password policies
- Account lockout
-
Two-Factor Authentication API - 2FA setup, verification, recovery codes, and backup options
-
User Management API - User authentication, registration, profile management, and permissions
-
User Token Management API - API token generation, management, and revocation
Cryptography & Encryption
-
Cryptography Module - Enterprise-grade cryptography for password hashing and data encryption
- Argon2id password hashing (quantum-resistant)
- AES-256-GCM encryption
- Secure token generation
- Timing attack prevention
-
Quantum Security - Future-proof security measures against quantum computing threats
Widget & Content Security
- Widget Security β - Comprehensive security measures across all widgets
- XSS prevention
- Injection attack protection
- File upload validation (including SVG sanitization)
- SSRF prevention (including S3 endpoint validation)
- IDOR protection
- Input sanitization
- Tiptap link protocol hardening
Application Security
-
Security Plugin - Build-time plugin preventing accidental exposure of private settings
- Environment variable protection
- Secret detection
- Build-time validation
-
Login Error Handling - Secure error handling for authentication flows
- Rate limiting
- Timing attack prevention
- Information disclosure prevention
-
Middleware Security Hardening - Real-time security at the protocol layer
- Content Security Policy: Strictly-scoped CSP (
script-src 'self', zerounsafe-inlineorunsafe-eval) emitted globally on all pages and API routes β the highest-leverage single-line XSS mitigation in SvelteKit - Multi-Tenant Batch Isolation:
batch-module.tsrejects coalesced operations containing mixed tenant IDs, preventing cross-tenant data leaks in shared-DB deployments - Timing-Safe Auth Cache: Turbo auth cache uses absolute expiry (fixed at SET time, never extended on GET) β prevents attackers from inferring session liveness through TTL reset pattern analysis
- GraphQL Validation Hardening: Query depth is strictly limited to 8 levels (preventing resource exhaustion), and
NoSchemaIntrospectionCustomRuleis explicitly enforced in production to block unauthenticated schema enumeration.
- Content Security Policy: Strictly-scoped CSP (
Infrastructure Security
-
Cloud Storage Implementation - Secure cloud storage integration patterns
- Signed URLs
- Access control
- Encryption at rest
-
Database Resilience - Database security and reliability
- Connection pooling
- Query timeout protection
- Injection prevention
π Security Features by Category
1. Authentication Security
Features:
-
β Argon2id password hashing (125ms+ computational cost)
-
β Automatic session rotation every 15 minutes for active users (industry best practice)
-
β 3-layer session caching (memory, Redis, database)
-
β Two-factor authentication (TOTP)
-
β Account lockout after failed attempts
-
β Secure password reset with time-limited tokens
-
β API token generation with granular permissions
-
β Website Tokens with expiration policies and granular access control
-
β Internal System Authorization using shared secrets (JWT_SECRET_KEY) for system-to-system calls
-
β Cascading Password Change: All other active sessions across all devices immediately invalidated on password change (L0/L1/L2 purge)
-
β Session & Device Tracking: User-Agent and IP captured at session creation for auditing; Active Devices API for session management (
GET/DELETE /api/user/sessions) -
β Credential-Free Session Cache: password hashes, TOTP secrets, backup codes, and reset/refresh tokens never enter session caches or stores; password-verifying endpoints re-fetch from the DB
-
β Session Context Anomaly Detection (log-only): IP / user-agent drift flagged once per session per hour, no false-positive lockouts
-
β Max Sessions Per User (
SESSION_MAX_PER_USER): LRU eviction of the least recently active session when the cap is exceeded (Keycloak-style) -
β Step-Up Re-Authentication for session management: cross-session revoke requires a fresh password proof (stateless HMAC, 5-min, session-bound)
Implementation:
- Password validation with entropy requirements
- Session fixation prevention
- CSRF Protection: Multi-layer origin and referer validation for all mutation requests (POST, PUT, DELETE, PATCH)
- Secure cookie attributes (httpOnly, secure, sameSite: Strict)
Every request to SveltyCMS passes through an enterprise-grade pre-compiled pipeline in hooks.server.ts to ensure maximum security with minimal overhead. The entire chain is wrapped in a Global Security Guard for unified header enforcement.
- π‘οΈ Security Headers: CSP, HSTS, and X-Frame-Options applied first to all responses.
- ποΈ Compression: ESM-native streaming compression (Brotli/Gzip).
- π§ͺ Test Isolation: Worker-index based database isolation for CI.
- π₯ Dynamic Firewall: Scans for SQLi, XSS, and Command Injection threat patterns.
- π Load Shedding: Automatically rejects mutations when memory usage > 90%.
- π¦ Rate Limiting: Per-IP fixed-window token bucket with adaptive cost multipliers (0.8xβ2.0x based on system pressure). Returns 429 with
Retry-AfterandX-RateLimit-*headers. - π§ Setup Guard: Blocks initialization endpoints after the system is live.
- π Authentication: Resolves session and enforces tenant isolation.
- π Authorization: Granular RBAC and Fail-Closed API dispatching.
3. Data Protection
Features:
- β AES-256-GCM encryption for sensitive data
- β Field-level encryption support
- β SHA-256 checksums for data integrity
- β Encrypted database backups
- β Secure cloud storage with signed URLs
Implementation:
- Encryption at rest and in transit
- Key rotation support
- Secure key storage
- HTTPS enforcement
3. Input Validation & Sanitization
Features:
- β Schema-based validation (Valibot)
- β HTML sanitization (DOMPurify)
- β File upload validation (type, size, extension)
- β Binary MIME sniffing for large file uploads β server-side verifies file signatures against client-declared MIME types (prevents MIME type spoofing)
- β
SSRF IPv6 transition address blocking β blocks IPv4-mapped IPv6 (
::ffff:), 6to4 (2002:), and Teredo (2001:) patterns in egress guard - β
Email normalization β unified
normalizeEmail()utility with Unicode NFC normalization and trimming applied consistently across all auth adapters - β Path traversal prevention
- β Safe Query Mapping & Parameterization: All JSON/RichText queries are strictly mapped to whitelisted database columns and natively parameterized (via Drizzle ORM) protecting against SQL Injection and blind SQL attacks out-of-the-box.
- β ReDoS prevention (input length limits)
- β
NoSQL Injection Protection: MongoDB
$where,$function,$expr, and$accumulatoroperators blocked atmapQuerylevel insrc/utils/security/mongo-sanitize.ts;$regexpatterns validated for ReDoS
Implementation:
- Whitelist-based validation
- Multi-layer validation (client + server)
- Content Security Policy
- X-Content-Type-Options header
4. Widget-Specific Security
Features:
- β XSS prevention in RichText and MegaMenu widgets
- β SSRF prevention in RemoteVideo widget
- β IDOR prevention in Relation widget
- β CSS injection prevention in ColorPicker widget
- β Meta tag injection prevention in SEO widget
- β File validation in MediaUpload widget
- β Format validation in Email, PhoneNumber, Currency widgets
Implementation Details: See Widget Security Documentation
6. AI Defensive Layers
Features:
-
β AI Bot Detection & Blocking: Proactive User-Agent fingerprinting detects and blocks known AI crawlers (GPTBot, Claude, Perplexity, CommonCrawl, Bytespider, FacebookBot) and reconnaissance tools (Nmap, SQLMap, Nikto, Burp Suite, Zgrab, Masscan, Nessus) before they can map the system surface.
-
β Multi-Layer Honeypot Grid: 45+ decoy routes mimicking WordPress, Drupal, Joomla, AWS metadata endpoints, and common config/backup files. Any probe triggers immediate IP flagging/blacklisting.
-
β Honeypot IP Flagging (no socket tarpit): Honeypot routes return a decoy
200 OKimmediately (socket closes fast β the old 5β15s delay was a Slowloris/DDoS vector) whilesecurityResponseService.blockIp()flags the IP so the next request is rejected at the firewall layer. -
β Response Poisoning: Bots receive fake JSON payloads (phantom users, false config) designed to corrupt scraper datasets rather than revealing real system information.
-
β Cross-Origin Isolation Headers: All API responses include
Cross-Origin-Opener-Policy: same-origin,Cross-Origin-Embedder-Policy: require-corp, andCross-Origin-Resource-Policy: same-originpreventing Spectre-style side-channel attacks. -
β AI Crawler Honeypot (IP Flagging): Detects automated reconnaissance bots hitting shadow routes (e.g.,
/wp-admin,/.env) and immediately flags their IP for firewall rejection on the next request β without holding the socket open. -
β Draft-by-Default Airgap: A fundamental security boundary for AI agents. Any content created or modified via the Model Context Protocol (MCP) is forcefully saved as
draft, requiring a human administrator to manually approve/publish it. -
β Prompt Injection Shielding: Native
<user_data>delimiters and strictsystemPromptPrefixconfigurations prevent βIgnore previous instructionsβ payloads from hijacking AI enrichment workflows. -
β RAG Context Isolation (Ollama): Remote knowledge-base context is moved to the
usermessage role with<rag_context>XML delimiters and control-character stripping, preventing external context from overriding system-level instructions. RAG results are sanitized for hidden control characters before injection. -
β AI Reconnaissance Blinding: The full OpenAPI specification is strictly locked behind administrative authentication, preventing automated agents from mapping the systemβs API surface.
7. Access Control
Features:
-
β Architectural Immunity to Permission Bloat: SveltyCMS is immune to the βSQL Chokingβ that plagues platforms like Directus. By pre-calculating route-level RBAC in memory, we resolve permissions in sub-milliseconds without injecting massive, recursive SQL
WHEREclauses into every query. -
β Memory Stability (WeakRef Isolation): Unlike traditional architectures that can experience memory leaks and OOM crashes under high concurrency, SveltyCMS uses
WeakRefsession caching. -
β Self-Healing Load Shedding: Detects high memory pressure and gracefully rejects mutation traffic (503) with compressed error responses to prevent OOM.
-
β Graceful Shutdown Instrumentation: Tracks in-flight requests and ensures clean database/cache disconnection on
SIGTERM. -
β Batched Ghost Relation Hydration: Eliminates the N+1 query bottleneck. Relational data is hydrated in optimized batches only as it enters the viewport.
-
β Fail-Closed API Authorization: All REST API endpoints must be explicitly registered. Unmapped routes are denied by default.
-
β Tenant-Based Access Control (TBAC): User roles are dynamically resolved and isolated per
tenantIdduring the authentication handshake. -
β Informative 403 Feedback: The Admin Area natively detects authorization failures and provides granular feedback including the specific required permission.
-
β UUIDv4 Primary Keys Out-of-the-box: Protects against Cross-Collection IDOR (Insecure Direct Object Reference) vulnerability collision chains.
-
β Defense-in-Depth Handler Checks: System handlers (
handleSettingsRoutes,handleSystemMgmtRoutes,handleAutomationRoutes) enforce admin verification.Media handlers enforce
media:writeandmedia:deletepermissions. Page actions use centralized permission guards. -
β Cookie Prefix Hardening:
__Host-prefixed session cookies strictly enforced on secure connections; never leaked on insecure connections. -
β Setup Session Cookie Consistency: Setup handler now uses the same
__Host-cookie prefix logic as the authentication hook, eliminating the prefix inconsistency between setup and runtime session cookies. -
β Zero-Bias Token Generation:
generateRandomTokenuses rejection sampling to eliminate the ~3.125% modulo bias, guaranteeing uniform distribution across all characters for session tokens and API keys. -
β Setup Completion Gating: All
/api/setupendpoints blocked with 403 after initialization; bootstrap routes redirect to login. Hardened with a deep database check for existing admin users to prevent setup wizard hijacking if config files are deleted. -
β Stateless CSRF Exemption: Excludes Bearer-authenticated API key and Website token requests from CSRF validation, allowing external headless mutations while keeping admin sessions fully protected.
-
β Permission-based authorization
-
β Multi-tenant isolation
-
β Resource-level permissions
-
β Admin privilege separation
-
β Automated Setup Guard (blocks installation endpoints after initialization)
-
β GraphQL DoS Protection: Query depth limited to 7 levels and aliases capped at 15 via
securityValidationPluginenvelop plugin -
β Account Lockout: 5 consecutive failed logins lock the account for 15 minutes; enforced in both
Auth.authenticate()andAuthNamespace.login()
Implementation:
- Central Dispatcher: Permission checks enforced at the single entry point for all
/api/[...path]routes. - Namespace Fallback: Dynamic resource IDs (e.g.,
/api/collections/[id]) are authorized via parent namespace permissions (e.g.,api:collections). - Database query filtering by tenant
- Cache key prefixing for isolation
- Tamper-Evident Audit Logging: Immutable, database-backed audit trail for all sensitive operations
6. Monitoring & Auditing
Features:
- β Comprehensive database-backed audit logging with SHA-256 Merkle-tree hash chaining
- β
High Performance Non-Blocking Mutation Pipeline (
AUDIT_CHAIN_SYNC=falsedefault) - β Security event tracking (login failures, permission violations)
- β Real-time security dashboards and widgets
- β Audit statistics and anomaly detection
Mutation Write Pipeline Architecture:
[ CMS Write Operation (create/update) ]
β
βΌ
ββββββββββββββββββββββββββββββββ
β Direct Database Transaction β βββΊ Return 200 OK to client immediately (~4.2 ms) β‘
ββββββββββββββββββββββββββββββββ
β
βΌ (Asynchronous Background Microtask)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 1. Compute SHA-256 Tamper-Evident Hash Chain β
β 2. Save Content Revision Snapshot β
β 3. Dispatch Async L2 Cache Invalidation β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
- High Performance Core Mode (
AUDIT_CHAIN_SYNC=false, Default): Audit logging and revision snapshots run in detached microtask queues, eliminating all write-path CPU penalties and delivering sub-5ms write latencies. - Enterprise Compliance Mode (
AUDIT_CHAIN_SYNC=true, Opt-In): Audit hashing and revision snapshotting run synchronously inside the write transaction for strict ISO 27001, SOC2, and EU GDPR compliance.
Implementation:
- Structured logging with correlation IDs
- Security event aggregation
- Anomaly detection
- Alert thresholds
π‘οΈ No Backdoor Policy
SveltyCMS is designed with a zero-backdoor philosophy. Every testing and benchmarking path is explicitly gated, auditable, and production-impossible β even with full source code access.
π Physical Isolation (Triple-Lock)
To prevent accidental exposure or exploitation of testing features, we employ a βTriple-Lockβ system:
-
Environment Gating: Testing and benchmarking code paths are only active when explicit environment variables (
TEST_MODE=true,BENCHMARK=true) are set at the OS level β impossible to enable via HTTP requests. In production, these paths return 401 Unauthorized. -
Cryptographic Handshake: The
/api/testingendpoint usestimingSafeEqual()fromnode:cryptofor constant-time secret comparison, preventing timing side-channel attacks. The HyperTurbo hook uses standard comparison gated behind theBENCHMARK=trueenvironment check. -
Auth Path Exclusion: Authentication paths (
/api/auth/login,/api/auth/logout) always use real password verification with full account lockout enforcement. No test bypass exists for login β tests must seed a user via/api/testingand authenticate with real credentials. Audit trails are always populated.
π§ͺ Secure Testing Approach
Our integration tests authenticate like real users:
-
Setup Phase: Tests use the
/api/testingendpoint (strictly guarded by the Triple-Lock) to:- Reset the test database
- Seed default data (roles, themes, settings)
- Create a test admin user
-
Authentication Phase: Tests must login to get a valid session cookie:
// Tests login just like real users await postAction("login", { email: "admin@test.com", password: "Test123!" }); -
Test Phase: Authenticated requests proceed normally through the security middleware. Every request includes the
x-test-worker-indexfor database isolation and thex-test-secretfor the cryptographic handshake.
β Why This Matters
- Environment-Gated, Not Stripped: Testing code paths exist in all builds but are unconditionally gated behind OS-level environment variables. An attacker needs server filesystem access to enable them.
- Tests Real Security: Authentication and authorization are tested end-to-end exactly as users experience them.
- Compliance Ready: Audit logs show real user-like behavior, not bypasses.
- No Secrets in Code: Test secrets are generated at runtime and never persisted.
π Related Documentation {#related-documentation-compliance}
- Tested Security Features - Comprehensive list of tested security features
- Black-Box Testing - Test architecture and isolated test configurations
- Integration Tests - Running integration tests securely
π§ͺ Security Testing
Test Coverage
SveltyCMS includes comprehensive security testing:
# Encryption and cryptography tests
bun test tests/unit/utils/security.test.ts
# Account lockout and session security tests
bun x vitest run tests/unit/auth/auth-lockout.test.ts
# Middleware security (firewall, rate-limit, auth)
bun test tests/unit/hooks/
# API security tests
bun test tests/integration/api/security.test.ts
Security Test Categories:
- β Encryption & Cryptography (14 tests) - AES-256-GCM, Argon2id, key derivation
- β
Account Lockout & Session Security (25 tests) -
auth-lockout(lockout, device policy, TTL, max sessions) +session-user(credential-free snapshots, store hygiene, anomaly evaluation) - β
Authentication flows (100+ tests) - hooks (
authentication25), user API, 2FA API, API-keys, bearer, guest, magic links, re-auth proofs - β Authorization checks (40+ tests)
- β Input validation (80+ tests)
- β XSS prevention (30+ tests)
- β Injection prevention (40+ tests)
- β File upload security (20+ tests)
Security Vulnerabilities Fixed
| Issue | File | Fix Date |
|---|---|---|
| Rate limiting bypass (localhost) | src/hooks/handle-rate-limit.ts |
March 2026 (Protected) |
| Firewall bypass (TEST_MODE) | src/hooks/handle-firewall.ts |
March 2026 (Protected) |
| Stale RBAC/roles after config import (incorrect permission decisions up to 1h) | ConfigService.performImport + permission/roles caches |
August 2026 (Protected) |
| Credential material (password hash, TOTP secret, backup codes) in session caches/stores | session-user.ts (credential-free snapshots) |
August 2026 (Protected) |
| Untagged cache delete not propagated to remote nodes (multi-node stale data) | cache-service.ts (key-pattern invalidation publish) |
August 2026 (Protected) |
LIKE wildcard pattern injection in media search / JSON-path contains (% widened filters to all rows) |
escapeLikePattern + bound ESCAPE in relational-media.ts, media-json-path.ts |
August 2026 (Protected) |
| Share-link creation rode on read-only gate (anonymous download exposure) | handleMediaShareCreate now requires media:write |
August 2026 (Protected) |
See Tested Security Features for details.
Stack Risk Audit (Commit Gate)
Every commit runs a full risk audit (.githooks/pre-commit β bun run risk:audit). It covers the layers no single tool can:
| Layer | Check | What it catches |
|---|---|---|
| Our code (global, all src) | scripts/scan-security-risk.ts |
SQL value/concat interpolation (4 adapters), MongoDB $where/$function, dynamic code execution, shell interpolation, path traversal, SSRF, XSS sinks, regex injection, SvelteKit CSRF/cookie config |
| Our code (secrets) | scripts/scan-secret-misuse.ts |
Hardcoded credentials, comparison backdoors, weak randomness |
| Our code (quality) | scripts/slop-scanner.ts |
XSS, RTL, security architecture rules |
| Dependencies (npm) | bun audit |
GitHub Advisory DB for the npm tree (SvelteKit/Svelte/Vite advisories included) |
| Global database | scripts/scan-osv.ts β OSV.dev |
GHSA + NVD + 20+ feeds in one query, from SBOM purls (24h cache) |
| CI semantic analysis | GitHub CodeQL (security-extended) |
Complements the custom scanners β different engine, same classes; runs on push/PR/weekly |
Cross-CMS advisories (e.g. WordPress) are not monitored β only the vulnerability class matters, and those classes are checked directly against our own code in scan-security-risk.ts.
Audit commands (how they differ):
| Command | Type | What it runs | Server needed? |
|---|---|---|---|
bun run risk:audit |
Static | The 5 commit-gate checks above (code scan + secrets + slop + deps + OSV) | No (~5s) |
bun run security |
Dynamic | OWASP A01βA07 probes against a running server (default :4173) |
Yes |
bun run security:auth |
Dynamic | Same probes with an authenticated session (builds + seeds first) | Starts its own |
bun run security --full |
Both | Dynamic probes + secret scan + slop + bun audit |
Yes |
Penetration Testing
Recommended security testing tools:
- OWASP ZAP - Web application security scanner
- Burp Suite - Security testing platform
- SQLMap - SQL injection testing
- XSStrike - XSS vulnerability scanner
External NVD Pipeline (cms_security_data.py, ops-side)
Run 2026-08-04: 116 deps scanned, 0 CVEs (0 HIGH/CRITICAL). Two detector-noise classes worth fixing in the external script so future runs donβt cry wolf:
fetch_nvd_cves()crashes onTimeoutError(onlyHTTPError/URLError/JSONDecodeErrorare caught) β addTimeoutError+ a retry.raw_sql_injection_riskflags every bare${...}template literal (Tailwind classes, localStorage keys, URLs) β require SQL context (SQL verb near the interpolation).path_traversal_riskmatches../in relative imports β requirefs./path.resolveusage with dynamic input.
In-repo equivalent: slop-scanner.ts raw-SQL check is SQL-verb-gated and identifier-guard-aware (see scanRawSqlRisk) β no such false-positive class.
π¦ Is Your Setup Secure? (Hardening Checklist)
While the CMS provides built-in tools, a secure production deployment requires proper environmental configuration.
| Item | Requirement | Status | Verification |
|---|---|---|---|
| JWT_SECRET_KEY | 32+ characters of high entropy. | [ ] | Auth flow |
| ENCRYPTION_KEY | 32+ characters (AES-256-GCM baseline). | [ ] | Data decryption |
| HTTPS/SSL | CMS should only be served over TLS 1.3. | [ ] | security-headers.test |
| Database Access | DB must reside on a private VPC/Network. | [ ] | Infrastructure |
| Admin Password | Enterprise standard (16+ chars, mixed). | [ ] | Auth.validatePassword |
| Firewall | Enable internal firewall via FIREWALL_ENABLED. |
[ ] | firewall.test |
| Audit Logs | Retention policy matches compliance (Default 365). | [ ] | AuditLogService |
π Security Checklist
Application Deployment
- Environment variables secured (no secrets in code) - Tested via config validation
- Content Security Policy configured -
tests/unit/hooks/security-headers.test.ts - Security headers enabled (HSTS, X-Frame-Options, etc.) -
tests/unit/hooks/security-headers.test.ts - Rate limiting configured -
tests/unit/hooks/rate-limit.test.ts - CORS policies defined -
tests/unit/hooks/security-headers.test.ts - HTTPS enabled with valid SSL certificate (infrastructure)
- Database credentials rotated (operational)
- API tokens with minimal required permissions (operational)
User Management
- Adaptive Rate Limiting (Hardware-Aware): Automatically scales request costs based on real-time CPU load and Event Loop lag, preventing resource exhaustion during traffic spikes.
- Password complexity requirements enforced -
tests/integration/routes/login/signup.test.ts - User roles and permissions reviewed -
tests/unit/hooks/authorization.test.ts - 2FA enabled for admin accounts -
tests/integration/api/auth-2fa.test.ts - Default admin account password changed (setup wizard requires this)
- Account lockout policy configured -
tests/unit/auth/auth-lockout.test.ts(locks after 5 attempts, rejects while locked, expired-lockout recovery) +tests/integration/api/auth-lockout.test.ts(HTTP-level lockout) - Session timeout configured -
SESSION_TTL_HOURS(absolute) +SESSION_IDLE_HOURS(sliding idle) tested intests/unit/hooks/authentication.test.ts; device policy +SESSION_MAX_PER_USERintests/unit/auth/auth-lockout.test.ts - API access logs monitored -
/api/dashboard/logspagination/filter/search tested (tests/integration/api/dashboard.test.ts) + crypto-chained audit integrity (tests/unit/security/audit-chain-verification.test.ts); ops-side alerting remains a deployment concern
Data Protection
- Audit logging enabled -
tests/integration/api/* - Sensitive data encrypted at rest -
tests/unit/utils/security.test.ts - Backup encryption enabled (infrastructure)
- Key rotation schedule defined (operational)
- Data retention policies configured (not tested)
- PII handling compliant with regulations (not tested)
Widget Security {#checklist-widget-security}
- All widgets reviewed for security -
docs/architecture/security/widget-security.mdx - Custom widgets follow security guidelines -
docs/architecture/security/widget-security.mdx - File upload restrictions configured -
tests/unit/plugins/sandbox.test.ts - Input validation enabled -
tests/unit/hooks/firewall.test.ts - Output encoding verified -
docs/architecture/security/richtext-security.mdx - Widget permissions configured - RBAC tests
π¨ Security Incident Response
Incident Detection
Monitor for:
- Multiple failed login attempts
- Unusual API access patterns
- Permission violation attempts
- File upload anomalies
- SQL injection attempts
- XSS payload detection
Response Procedure
- Identify - Detect and confirm security incident
- Contain - Isolate affected systems
- Investigate - Analyze logs and determine scope
- Remediate - Fix vulnerabilities
- Recover - Restore normal operations
- Document - Record incident details and lessons learned
Reporting
Security issues should be reported to:
- Email: security@sveltycms.org
- GitHub: Private security advisory
- Severity Levels: Critical, High, Medium, Low
π Security Best Practices
Development
- Never commit secrets - Use environment variables
- Validate all input - Client and server side
- Sanitize all output - Prevent XSS
- Use parameterized queries - Prevent SQL injection
- Implement least privilege - Minimal permissions
- Log security events - Enable audit trail
- Keep dependencies updated - Regular security patches
Scaffolding Security Defaults
When a new SveltyCMS project is created via the setup wizard, the following bootstrap values are written to config/private.ts:
JWT_SECRET_KEYβ 32-character CSPRNG-generated signing keyENCRYPTION_KEYβ 32-character CSPRNG-generated encryption key
All other security settings (password policy, rate limiting, SAML/SSO keys) are seeded into the database and managed via the System Settings UI at /config/system-settings:
PASSWORD_MIN_LENGTHβ default 8, adjustable via Security settingsRATE_LIMIT_SECRETβ auto-generated on first use, managed via Security settings- SAML/SSO keys β RSA-2048 key pair generated during setup, managed via SAML / Enterprise SSO settings
Review and customize all values before deploying to production.
Deployment
- Use HTTPS everywhere - Encrypt all traffic
- Enable security headers - CSP, HSTS, etc.
- Configure CORS properly - Restrict origins
- Implement rate limiting - Prevent abuse at both app and edge
- Place behind a WAF β Cloudflare, AWS WAF, or similar for edge protection
- Monitor security logs - Real-time alerts
- Regular security audits - Quarterly reviews, annual pentests
- Backup encryption - Protect data at rest
Edge Protection Checklist
For production, layer these in front of SveltyCMS:
- Cloudflare / AWS WAF with managed OWASP + bot control rule sets
- DDoS Protection (Cloudflare Magic Transit / AWS Shield)
- IP allowlisting for admin panel access
- Edge rate limiting before origin
- Geo-IP filtering for high-risk regions
Operations
- Rotate credentials regularly - Passwords, tokens, keys
- Review permissions - Audit user access
- Monitor failed logins - Detect brute force
- Update security policies - Keep current with threats
- Train users - Security awareness
- Test disaster recovery - Backup restoration
- Maintain audit logs - Compliance requirements
π Compliance
SveltyCMS security features support compliance with:
GDPR (General Data Protection Regulation)
- β Data encryption
- β User consent management
- β Right to erasure
- β Data portability
- β Audit logging
- β Data breach notification
SOC 2 (Service Organization Control)
- β Access controls
- β Audit logging
- β Change management
- β Risk assessment
- β Incident response
- β Monitoring and alerting
OWASP Top 10
- β Injection prevention
- β Broken authentication protection
- β Sensitive data exposure prevention
- β XML external entities (XXE) prevention
- β Broken access control prevention
- β Security misconfiguration prevention
- β XSS prevention
- β Insecure deserialization prevention
- β Using components with known vulnerabilities (dependency scanning)
- β Insufficient logging and monitoring (comprehensive audit logs)
7. Supply Chain Security
Features:
- β Pinned GitHub Actions to specific commit SHAs
- β Enforced frozen lockfiles in CI/CD
- β Automated dependency updates with verification
- β
CycloneDX SBOM generation (
bun run audit:sbom)
Implementation:
- All GitHub workflows use immutable action references (e.g.,
actions/checkout@11bd7...) to prevent tag hijacking. bun install --frozen-lockfileis enforced in all CI jobs to prevent lockfile poisoning.- Secure update scripts ensure lockfile integrity during maintenance.
bun run updateregenerates the SBOM after dependency updates; the pre-commit hook also re-syncssbom.jsonwheneverbun.lock/package.jsonchange. The SBOM (CycloneDX 1.5, SHA-512 hashes) provides a verifiable inventory of every dependency for vulnerability scanners (e.g., Dependency-Track, Grype) and SOC 2 / GDPR Art. 32 compliance.
π Related Documentation {#related-documentation-links}
Architecture
API Security
Widget Security {#widget-security-2}
Testing
π Security Contact
For security-related questions or to report vulnerabilities:
- Security Email: security@sveltycms.com
- GitHub Security Advisories: Private Reporting
- security.txt (RFC 9116):
/.well-known/security.txtβ machine-readable policy + contacts - Bug Bounty: Coming soon
- Disclosure policy: SECURITY.md β staged timeline (critical 7d / high 30d / medium-low 90d)
Response Time:
- Critical vulnerabilities: 24 hours
- High severity: 48 hours
- Medium severity: 1 week
- Low severity: 2 weeks
Last Updated: August 4, 2026 Security Review Status: β A++ Grade (August 2026 Assessment β session/RBAC hardening: device policy, idle/TTL, credential-free caches, step-up re-auth, anomaly log) Next Review: Quarterly (October 2026)