Canvix — Free & open-source graphic design tool. A community-built Canva alternative with a drag-and-drop editor, templates, shapes, text, images & one-click export. Works on desktop, tablet & mobile.
TypeScript canva-alternativecanvasdesigndesign-tooldrag-and-dropeditorgraphic-designkonvanextjsopen-sourcereactself-hostedtemplatestypescript
feat(v0.12): security headers + CSP baseline — nosniff/Referrer-Policy/XFO/HSTS/Permissions-Policy on every route class, report-only CSP, strict per-manifest plugin CSP drafted (H3) (#12)
Ashiq Hussain Mirc584717e8645
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex cc77132..b27344d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,44 @@All notable changes to Canvix will be documented in this file.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).+## [0.12.1] — 2026-11-02++### Added++- **Security headers + CSP baseline (H3).** Every response from every+ route class — landing/editor pages, read APIs, the health probe,+ even 404s and static assets — now carries the hardening baseline+ the roadmap research flagged as missing: `X-Content-Type-Options:+ nosniff`, `Referrer-Policy: strict-origin-when-cross-origin`,+ `X-Frame-Options: SAMEORIGIN` (with a matching `frame-ancestors+ 'self'` in the CSP), `Strict-Transport-Security` (180 days —+ documented that browsers ignore HSTS over plain HTTP, so+ `http://` self-hosters are unaffected by definition) and a+ `Permissions-Policy` turning off camera/mic/geo. The CSP itself+ ships as **Report-Only**: the policy the app needs today is+ written down directive by directive (Google Fonts css + files,+ `data:`/`blob:` images, blob workers for the background remover,+ TLS-only `frame-src` for embed cards, `object-src 'none'`,+ `base-uri`/`form-action 'self'`) and nothing breaks while the+ violation reports are reviewed — the enforcement flip is a+ one-line change in `next.config.ts`, documented in the README.+ The single source of truth is `next.config.ts → headers()`, so+ Vercel, Cloudflare Workers (OpenNext), Netlify and Node+ standalone all serve byte-identical values.+- **Drafted the strict per-manifest CSP for the v0.13 plugin serve+ route** (`src/lib/security/plugin-csp.ts`): `default-src 'none'`,+ `script-src 'self'` (no inline scripts — the packaging rule),+ `connect-src` collapsing to `'none'` unless the user consented to+ specific https origins, canonicalised and deduplicated, with+ loopback http allowed for development builds only. Unit tests pin+ the header byte-for-byte so the consent screen, the serve route+ and the P4 security suite all agree on what “strict” means.+- **Playwright spec `tests/e2e/security-headers.spec.ts`** — asserts+ the whole baseline on one representative URL per route class in+ CI (landing, design deep-link, templates/designs APIs, health,+ static asset), plus the CSP allowlist contents and the fact that+ no enforcing CSP header exists yet.+## [0.12.0] — 2026-11-02### Addeddiff --git a/README.md b/README.mdindex 9a8a87c..a2dbeac 100644--- a/README.md+++ b/README.md@@ -703,6 +703,23 @@ tool descriptions so agents pick the right format.## 🔐 Security notes+- **Security headers + CSP baseline (v0.12.1)** — every response from every+ route class (pages, APIs, SSE, static assets) now carries+ `X-Content-Type-Options: nosniff`,+ `Referrer-Policy: strict-origin-when-cross-origin`,+ `X-Frame-Options: SAMEORIGIN` (+ `frame-ancestors 'self'`),+ `Strict-Transport-Security` (180 days) and a `Permissions-Policy` that+ turns off camera/mic/geo. The CSP ships as **Report-Only** so nothing+ breaks while violations are reviewed: it allowlists Google Fonts,+ `data:`/`blob:` images, blob workers for the background remover and+ TLS-only frames for embed cards. After a review week, flip the+ `Content-Security-Policy-Report-Only` header in `next.config.ts` to+ `Content-Security-Policy` (and tighten `frame-src` to the embed+ allowlist). HSTS note for self-hosters: browsers only honour it over+ TLS, so an `http://` deployment is unaffected by definition — the+ header starts counting the moment you put the instance behind HTTPS.+ A Playwright spec (`tests/e2e/security-headers.spec.ts`) asserts the+ whole baseline on every route class in CI- **Secrets never reach the browser** — provider credentials are resolvedserver-side only; the public capabilities endpoint exposes booleans only- **Validated collaboration ops** — every realtime event is type-checked,@@ -771,6 +788,13 @@ tool descriptions so agents pick the right format.full vitest suite on GitHub Actions, and merges to `main` also run thePlaywright browser suite against a real Postgres service container —the deploy pipelines finally get tested code *(v0.12)*+- [x] Security headers + CSP baseline — `nosniff`, `Referrer-Policy`,+ `X-Frame-Options`/`frame-ancestors`, HSTS and `Permissions-Policy`+ on every route class from one source of truth in `next.config.ts`,+ a report-only CSP allowlisting Google Fonts + `data:`/`blob:` images+ + blob workers, and the strict per-manifest CSP the v0.13 plugin+ serve route will use, drafted and unit-tested in+ `src/lib/security/plugin-csp.ts` *(v0.12.1)*- [ ] Plugin system (external, installable apps) — sandboxed-iframe MVPper `research/PLUGIN-SYSTEM.md`: manifest + permission model, iframesandbox with postMessage bridge, an “Apps” panel store, and 2–3diff --git a/next.config.ts b/next.config.tsindex be832eb..d12a216 100644--- a/next.config.ts+++ b/next.config.ts@@ -1,7 +1,69 @@import type { NextConfig } from "next";+// ─────────────────────────────────────────────────────────────────+// Security headers + CSP baseline (v0.12.1, roadmap H3 — see+// research/V0118-ROADMAP-RESEARCH.md §5.1). One static source of+// truth in next.config: every deploy target (Vercel, Cloudflare+// Workers via OpenNext, Netlify, Node standalone) serves these on+// every route — pages and API handlers alike.+//+// CSP ships as Report-Only on purpose: it documents the policy the+// app needs today (Google Fonts, data:/blob: images, blob: workers)+// without risking a regression on a renderer we have not audited.+// Review the browser-console violation reports for ~a week, then+// flip to enforcement (README → “Security notes” has the path).+// The plugin serve route (v0.13, P1) will NOT use this baseline —+// it gets the strict per-manifest CSP drafted in+// src/lib/security/plugin-csp.ts.+// ─────────────────────────────────────────────────────────────────+const CSP_REPORT_ONLY = [+ "default-src 'self'",+ // dev needs eval for HMR; wasm+blob workers are the background+ // remover; inline is Next's hydration scripts (nonce-based CSP is+ // the enforcement-time upgrade, tracked with P1)+ "script-src 'self' 'unsafe-inline' 'unsafe-eval' 'wasm-unsafe-eval' blob:",+ "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com",+ "font-src 'self' data: blob: https://fonts.gstatic.com",+ // stock-photo providers may return remote URLs; data: covers AI+ // thumbnails, blob: covers canvas exports+ "img-src 'self' data: blob: https:",+ "media-src 'self' data: blob:",+ "connect-src 'self' blob: data:",+ "worker-src 'self' blob:",+ // embed cards (YouTube, Maps, …) frame out over TLS; enforcement+ // will tighten this to the embed allowlist+ "frame-src https:",+ "object-src 'none'",+ "base-uri 'self'",+ "form-action 'self'",+ "frame-ancestors 'self'",+].join("; ");++const securityHeaders = [+ { key: "X-Content-Type-Options", value: "nosniff" },+ { key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },+ { key: "X-Frame-Options", value: "SAMEORIGIN" },+ // Browsers ignore HSTS over plain HTTP, so self-hosters behind+ // http:// are unaffected by definition — the header only starts+ // counting once the host is served over TLS (reverse proxy,+ // platform, or tunnel).+ { key: "Strict-Transport-Security", value: "max-age=15552000; includeSubDomains" },+ // Canvix uses none of these; explicitly off.+ { key: "Permissions-Policy", value: "camera=(), microphone=(), geolocation=(), interest-cohort=()" },+ { key: "Content-Security-Policy-Report-Only", value: CSP_REPORT_ONLY },+];+const nextConfig: NextConfig = {output: "standalone",+ async headers() {+ return [+ {+ // every route class — landing/editor pages, API routes, SSE+ source: "/:path*",+ headers: securityHeaders,+ },+ ];+ },typescript: {// v0.6.1: strict again — the codebase typechecks clean; keep it that way.ignoreBuildErrors: false,diff --git a/package.json b/package.jsonindex ff65a7c..9494e4d 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "canvix",- "version": "0.12.0",+ "version": "0.12.1","private": false,"description": "Canvix — free & open-source graphic design tool. A community-built Canva alternative.","scripts": {diff --git a/src/lib/security/plugin-csp.test.ts b/src/lib/security/plugin-csp.test.tsnew file mode 100644index 0000000..12bf52f--- /dev/null+++ b/src/lib/security/plugin-csp.test.ts@@ -0,0 +1,64 @@+import { describe, expect, it } from 'vitest'+import { parseGrantedOrigin, pluginServeCsp } from './plugin-csp'++// H3: the draft CSP the v0.13 plugin serve route (P1) will attach.+// Pinned byte-for-byte so the consent screen, the route and the+// security suite (P4) all agree on what “strict” means.++describe('parseGrantedOrigin', () => {+ it('accepts plain https origins and canonicalises them', () => {+ expect(parseGrantedOrigin('https://api.example.com')).toBe('https://api.example.com')+ expect(parseGrantedOrigin(' https://api.example.com/very/long/path ')).toBe(+ 'https://api.example.com',+ )+ })++ it('accepts loopback http for development builds only', () => {+ expect(parseGrantedOrigin('http://127.0.0.1:8787/health')).toBe('http://127.0.0.1:8787')+ expect(parseGrantedOrigin('http://localhost:3000')).toBe('http://localhost:3000')+ expect(parseGrantedOrigin('http://example.com')).toBeNull()+ expect(parseGrantedOrigin('http://192.168.1.5:8787')).toBeNull()+ })++ it('rejects junk, credentials and fragments', () => {+ expect(parseGrantedOrigin('')).toBeNull()+ expect(parseGrantedOrigin('not a url')).toBeNull()+ expect(parseGrantedOrigin('ftp://example.com')).toBeNull()+ expect(parseGrantedOrigin('https://user:[email protected]')).toBeNull()+ expect(parseGrantedOrigin('https://example.com/#leak')).toBeNull()+ })+})++describe('pluginServeCsp', () => {+ it('zero grants collapse connect-src to none — a real exfiltration wall', () => {+ const csp = pluginServeCsp([])+ expect(csp).toBe(+ [+ "default-src 'none'",+ "script-src 'self'",+ "style-src 'unsafe-inline'",+ 'img-src data: blob:',+ "connect-src 'none'",+ 'font-src data:',+ "frame-ancestors 'self'",+ "form-action 'none'",+ "base-uri 'none'",+ ].join('; '),+ )+ })++ it('lists granted origins verbatim, deduplicated and canonical', () => {+ const csp = pluginServeCsp([+ 'https://api.example.com/v1',+ 'https://api.example.com',+ 'https://cdn.other.org',+ 'http://evil.example',+ ])+ expect(csp).toContain('connect-src https://api.example.com https://cdn.other.org')+ })++ it('never widens: invalid entries are dropped, not fatal', () => {+ const csp = pluginServeCsp(['garbage', 'http://127.0.0.1:9911/x'])+ expect(csp).toContain('connect-src http://127.0.0.1:9911')+ })+})diff --git a/src/lib/security/plugin-csp.ts b/src/lib/security/plugin-csp.tsnew file mode 100644index 0000000..c51473c--- /dev/null+++ b/src/lib/security/plugin-csp.ts@@ -0,0 +1,84 @@+// ─────────────────────────────────────────────────────────────+// Per-manifest CSP for the plugin serve route — the DRAFT the+// v0.13 runtime core (roadmap P1, research/PLUGIN-SYSTEM.md §4+// threat “data exfiltration”) will attach to every response of+// /api/plugins/<id>/serve.+//+// This is deliberately NOT the app-wide report-only baseline in+// next.config.ts. Plugin documents are served by the HOST (same+// origin as the app) but run inside <iframe sandbox>, so their CSP+// must assume the document itself is untrusted:+//+// default-src 'none' — nothing is allowed unless granted+// script-src 'self' — the manifest's entry script, served+// by the host route (packaging rule:+// no inline <script>, enforced by the+// validator)+// style-src 'unsafe-inline' — plugins style via DOM APIs; no+// external stylesheets, ever+// img-src data: blob: — generated art stays in the frame+// connect-src <grants|none> — ONLY origins the user consented to,+// verbatim from the install screen+// frame-ancestors 'self' — only the Canvix app may embed it+//+// CSP governs fetch()/XHR/beacons/images in every mode, including+// no-cors — so an empty connect-src is a real exfiltration wall.+// The documented residual (self-navigation of the iframe) is why+// the consent screen, not the sandbox alone, is the trust gate.+// ─────────────────────────────────────────────────────────────++/** Origin a plugin was explicitly granted network access to. */+export type GrantedOrigin = string++/**+ * Validate a consent-granted connect-src origin.+ * Rules: absolute https: URLs only (plugins on localhost may use+ * http://127.0.0.1 for development builds), no wildcards, no+ * credentials, no fragments. Returns null when invalid.+ */+export function parseGrantedOrigin(raw: string): GrantedOrigin | null {+ const value = raw.trim()+ if (!value) return null+ let url: URL+ try {+ url = new URL(value)+ } catch {+ return null+ }+ const isDevLocal =+ url.protocol === 'http:' &&+ (url.hostname === '127.0.0.1' || url.hostname === 'localhost')+ if (url.protocol !== 'https:' && !isDevLocal) return null+ if (url.username || url.password) return null+ if (url.hash) return null+ // canonical form so the header cannot be smuggled with padding+ return url.origin+}++/**+ * Build the strict serve-route CSP for one installed plugin.+ * `grantedConnectOrigins` comes verbatim from the consent screen —+ * an empty list means the plugin has zero network permissions and+ * connect-src collapses to 'none'.+ */+export function pluginServeCsp(+ grantedConnectOrigins: readonly string[],+): string {+ const origins: string[] = []+ for (const raw of grantedConnectOrigins) {+ const origin = parseGrantedOrigin(raw)+ if (origin && !origins.includes(origin)) origins.push(origin)+ }+ const connectSrc = origins.length ? origins.join(' ') : "'none'"+ return [+ "default-src 'none'",+ "script-src 'self'",+ "style-src 'unsafe-inline'",+ 'img-src data: blob:',+ `connect-src ${connectSrc}`,+ 'font-src data:',+ "frame-ancestors 'self'",+ "form-action 'none'",+ "base-uri 'none'",+ ].join('; ')+}diff --git a/tests/e2e/security-headers.spec.ts b/tests/e2e/security-headers.spec.tsnew file mode 100644index 0000000..dfe8270--- /dev/null+++ b/tests/e2e/security-headers.spec.ts@@ -0,0 +1,65 @@+import { test, expect } from '@playwright/test'++/**+ * H3 (v0.12.1): the security-header baseline is served on every+ * route class — landing/editor pages, read APIs, the health probe —+ * from the single source of truth in next.config.ts `headers()`.+ * These assertions are the “verified” in the epic's acceptance+ * criteria; they run against `next dev` (CI) but the header set is+ * static, so production builds serve byte-identical values.+ */++// One representative URL per route class.+const ROUTE_CLASSES = [+ { label: 'landing page', url: '/' },+ { label: 'design deep-link page', url: '/design/nonexistent-id' },+ { label: 'read API (templates)', url: '/api/templates' },+ { label: 'read API (designs list)', url: '/api/designs' },+ { label: 'health probe', url: '/api/health' },+] as const++for (const route of ROUTE_CLASSES) {+ test(`security headers on ${route.label}`, async ({ request }) => {+ const res = await request.get(route.url)+ // the header contract must hold whatever the body says — even a+ // 404/503 from the route itself carries the baseline+ const h = res.headers()++ expect(h['x-content-type-options']).toBe('nosniff')+ expect(h['referrer-policy']).toBe('strict-origin-when-cross-origin')+ expect(h['x-frame-options']).toBe('SAMEORIGIN')+ expect(h['strict-transport-security']).toBe('max-age=15552000; includeSubDomains')+ expect(h['permissions-policy']).toBe(+ 'camera=(), microphone=(), geolocation=(), interest-cohort=()',+ )+ })+}++test('CSP report-only baseline carries the documented policy', async ({ request }) => {+ const res = await request.get('/')+ const csp = res.headers()['content-security-policy-report-only']++ // report-only, never enforcing, until the review week is done+ expect(res.headers()['content-security-policy']).toBeUndefined()+ expect(csp).toBeDefined()++ // the app-need allowlist, directive by directive+ expect(csp).toContain("default-src 'self'")+ expect(csp).toContain('script-src')+ expect(csp).toContain('https://fonts.googleapis.com') // Google Fonts css+ expect(csp).toContain('https://fonts.gstatic.com') // Google Fonts files+ expect(csp).toContain('img-src')+ expect(csp).toContain('worker-src')+ expect(csp).toContain("frame-ancestors 'self'")+ expect(csp).toContain("object-src 'none'")+ expect(csp).toContain("base-uri 'self'")++ // the frame-src carve-out for embed cards is TLS-only+ expect(csp).toContain('frame-src https:')+})++test('static assets inherit the baseline too', async ({ request }) => {+ const res = await request.get('/logo.svg')+ expect(res.headers()['x-content-type-options']).toBe('nosniff')+ expect(res.headers()['x-frame-options']).toBe('SAMEORIGIN')+})