security: add CSRF token protection (signed double-submit cookie)#668
Open
mmcintosh wants to merge 1 commit intoSonicJs-Org:mainfrom
Open
security: add CSRF token protection (signed double-submit cookie)#668mmcintosh wants to merge 1 commit intoSonicJs-Org:mainfrom
mmcintosh wants to merge 1 commit intoSonicJs-Org:mainfrom
Conversation
Add stateless CSRF protection using the Signed Double-Submit Cookie pattern with HMAC-SHA256 signatures keyed on JWT_SECRET. - New csrf.ts middleware: generates/validates signed tokens - Token format: <nonce>.<hmac_signature>, base64url-encoded - Header validation (X-CSRF-Token) with form body fallback (_csrf) - Exempt: safe methods, auth routes, public forms, bearer-only requests - Admin layout auto-attaches tokens to HTMX and fetch requests - 40 unit tests + E2E test updates for CSRF compatibility Fixes VULN-006
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.
security: CSRF Token Protection
Target:
SonicJs-Org/sonicjsmainBranch:
security/csrf-protectionDescription
Add stateless CSRF token protection using the Signed Double-Submit Cookie pattern, providing defense-in-depth against cross-site request forgery beyond
SameSite=Strictcookies alone.This protects against same-site attacks (e.g., subdomain cookie tossing, browser bugs that bypass SameSite) with zero infrastructure overhead — no D1 tables, no KV, no session store. The token is a self-validating
nonce.hmac_signatureusing HMAC-SHA256 keyed with the existingJWT_SECRET.Fixes VULN-006 from the security audit.
Changes
Core Middleware
csrf.tsmiddleware (281 lines) — generates and validates CSRF tokens using HMAC-SHA256 signed double-submit cookies<32-byte-nonce>.<hmac_signature>, base64url-encoded, no paddingX-CSRF-Token) with form body fallback (_csrfhidden field) for regular HTML form POSTsapp.tsbefore route handlersExempt Paths
/auth/login*,/auth/register*,/auth/seed-admin,/auth/accept-invitation,/auth/reset-password/api/search*/forms/*,/api/forms/*(NOT/admin/forms/*)auth_tokencookie present)Auth Integration
auth.ts: Setcsrf_tokencookie on login/register (all 7 handlers), clear on logoutHttpOnly,SameSite=Strict,Secure(production),Path=/Admin Layout
admin-layout-catalyst.template.ts:getCsrfToken()reads csrf_token from cookie (handles=in base64 values)htmx:configRequestlistener auto-attachesX-CSRF-Tokenheader to all HTMX requestsfetch()wrapper auto-attaches header to all non-GET fetch callssubmitevent listener injects hidden_csrffield into regular (non-HTMX) form submissionsForm Templates
_csrfinput field added toform.template.tsandcomponents/form.template.tsas defense-in-depthError Responses
Accept: text/html): HTML 403 page with "CSRF token missing or invalid"{ error: "CSRF token missing", status: 403 }JWT_SECRETis not setTechnical Details
New Files:
packages/core/src/middleware/csrf.tspackages/core/src/__tests__/middleware/csrf.test.tsModified Files:
packages/core/src/middleware/index.tspackages/core/src/app.tspackages/core/src/routes/auth.tspackages/core/src/templates/layouts/admin-layout-catalyst.template.tspackages/core/src/templates/form.template.ts_csrffieldpackages/core/src/templates/components/form.template.ts_csrffieldtests/e2e/utils/test-helpers.tstests/e2e/02b-authentication-api.spec.tstests/e2e/08b-admin-collections-api.spec.tstests/e2e/13-migrations.spec.tstests/e2e/14-database-tools.spec.tstests/e2e/23-content-api-crud.spec.tsTesting
Unit Tests
csrf.test.ts)Unit test coverage:
E2E Tests
Performance Impact
csrf_token)Breaking Changes
Potentially breaking for custom integrations:
auth_tokencookie) must now include theX-CSRF-Tokenheader matching thecsrf_tokencookie value/forms/*,/api/forms/*) are NOT affectedMigration for API consumers using cookie auth:
Migration Notes
JWT_SECRETbindingX-CSRF-TokenheaderKnown Issues
None.
Screenshots/Videos
N/A (middleware-only change, no UI changes)
Checklist