feat: harden application with CSP, security headers, input validation, CSRF protection, and env validation - #35
Merged
KarenZita01 merged 1 commit intoJul 29, 2026
Conversation
…, CSRF protection, and env validation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Implements comprehensive security hardening for the EquipChain frontend as described in issue #25. As a blockchain-connected application handling financial transactions on Stellar Soroban, security is paramount. This PR adds multiple layers of defense: HTTP security headers, CSRF protection, input validation with Zod, input sanitization, environment variable validation, transaction simulation, and dependency auditing in CI.
Closes #25
Changes
🔒 Security Headers (
src/middleware.ts)All HTTP responses now include industry-standard security headers:
Content-Security-Policydefault-src 'self', connect-src includes Stellar originsStrict-Transport-Securitymax-age=63072000; includeSubDomains; preloadX-Content-Type-OptionsnosniffX-Frame-OptionsDENYReferrer-Policystrict-origin-when-cross-originPermissions-Policycamera=(), microphone=(), geolocation=()Cache-Controlno-store, max-age=0(HTML documents only)The middleware config excludes
_next/static,_next/image,favicon.ico, PWA icons, andsw.jsfrom processing — preserving Next.js static asset caching.🛡️ CSRF Protection (
src/lib/security/csrf.ts)crypto.randomBytes()(32 bytes)timingSafeEqualto prevent timing attacksGET /api/csrf-token— returns a signed__Host-csrf-tokencookie/api/*routes require validx-csrf-tokenheaderHttpOnly,SameSite=Strict,Secure(production), and__Host-prefix✅ Input Validation (
src/lib/validation/schemas.ts)Zod v4 schemas for all critical input types:
stellarAddressSchemaG[A-Z2-7]{55}— Stellar public key with base32 checksumstellarSecretSchemaS[A-Z2-7]{55}— Stellar secret keystellarContractIdSchemaC[A-Z2-7]{55}— Stellar contract IDamountSchemarateSchemameterIdSchemameterRegistrationSchemameterReadingSchemabillingPeriodSchemabillingRecordSchematransactionEnvelopeSchematransactionSimulationSchemawalletOriginSchemasafeStringSchema<script>, event handlers)emailSchemaurlSchemaexportConfigSchema🧹 Input Sanitization (
src/lib/validation/sanitize.ts)Multi-layer sanitization to prevent XSS and injection attacks:
escapeHtml()— HTML entity escaping (<,>,",',&,/,`,=)sanitizeString()— Removes<script>,<style>, HTML comments, event handlers (on*=),javascript:,data:text/html,vbscript:protocolssanitizeObject()— Recursive object sanitization for entire request bodiessanitizeUrl()— Blocks dangerous URL protocols, allows onlyhttp:,https:, and relative URLssanitizeFileName()— Path traversal prevention (removes/,\,.., control chars, limits to 255 chars)sanitizeSqlInput()— Strips SQL-significant characters and keywords (defense in depth)🔐 Environment Variable Validation (
src/lib/security/env.ts)validatePublicEnv()— Validates allNEXT_PUBLIC_*variables at build time (called fromnext.config.ts)validateServerEnv()— Validates server-side variables at startup; throws in production if critical vars are missingdetectSecretLeaks()— Scans allNEXT_PUBLIC_*vars for secret patterns (keys, passwords, tokens, mnemonics, Stellar secret keys); throws in production if leaks detectedNEXT_PUBLIC_BASE_URL,NEXT_PUBLIC_STELLAR_NETWORK, RPC URLs, Horizon URLs,BACKEND_URL,CSRF_SECRET,NODE_ENV,DATABASE_URL,STELLAR_SECRET_KEY, rate limits🔄 Transaction Simulation (
src/lib/security/transaction-simulation.ts)Before a user signs a transaction, the app now previews:
simulateTransactionendpoint when configured📋 CI Pipeline (
ci.yml)security-auditjob:npm audit --audit-level=highon every push/PRlint-and-typecheckjob:npm run lint+npm run typecheckbefore build📄 Documentation
SECURITY.md: Comprehensive security policy covering supported versions, security model, all security features with configuration tables, vulnerability disclosure policy, security assumptions (trusted/untrusted boundaries), development guidelines, and a pre-deployment checklist🧹 ESLint Configuration
public/sw.jsto ignore list (minified service worker bundle)🐛 Fixed Pre-existing Issues
src/lib/hooks/usePwaInstall.ts,src/lib/hooks/useOnlineStatus.ts,src/components/common/OfflineBanner.tsx, andapp/offline/page.tsx(synchronous setState in effects)Files Changed
src/middleware.tssrc/lib/security/csrf.tssrc/lib/security/env.tssrc/lib/security/transaction-simulation.tssrc/lib/validation/schemas.tssrc/lib/validation/sanitize.tsSECURITY.mdnext.config.ts.github/workflows/ci.ymleslint.config.mjspublic/sw.jspackage.jsonzoddependencyVerification
npm run lint— 0 errors, 0 warningsnpm run typecheck— All types compilenpm run build— Production build succeedsTesting Instructions
curl -I http://localhost:3000— verify CSP, HSTS, X-Frame-Options, X-Content-Type-Options, Referrer-Policy, Permissions-Policy are presentcurl http://localhost:3000/api/csrf-token— returns JSON with token and sets cookiecurl -X POST http://localhost:3000/api/exportwithout token → 403<script>alert('xss')</script>→ blocked by CSPsimulateTransactionwith a valid XDR → preview costs and state changes