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 panel runtime — RPC broker, sandboxed iframe host, consent UI, namespaced storage (P3) (#19)
Ashiq Hussain Mirdbb266c5a32a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e91e878..4de598c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,63 @@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.2] — 2026-11-02++### Added++- **Plugin system, part 3 of 5 — the panel runtime (P3).**+ The host half of research §4.3/§4.8: an installed row can now+ become running code — inside the boundary P1/P2 pinned. 57 new+ unit tests, zero new npm dependencies.+ - **RPC broker** (`src/lib/plugins/broker.ts`): one instance per+ mounted iframe, and the ONLY path between plugin and host.+ Origin discipline by window identity (`ev.source === the frame+ we mounted` — an opaque-origin iframe cannot be named, so the+ object IS the origin check), one-time handshake token echoed+ on the first call (rides the iframe URL fragment, never the+ wire), 200 calls/min sliding-window budget (`E_THROTTLE`),+ default-deny dispatch against the install's consented+ permissions, typed `BrokerError`s that stay wire-legal, and+ `E_INTERNAL` + server-side-only logging for host failures.+ Full method surface: `info`/`ping` (no permission),+ `design.getSnapshot` (lossy read-only projection, RPC-capped),+ `subscribe('selection'|'document')` with ack-bounded pushes,+ `actions.apply` (the §4.3 whitelist — AI actions excluded,+ `addPluginElement` reserved for P4), `storage.*`, `ui.notify`+ (sanitized, 200-char cap), `ui.closePanel`. Read-only designs+ suspend `design:write` at the broker (E_PERMISSION).+ - **Design snapshot projection** (`src/lib/plugins/snapshot.ts`):+ what `design.getSnapshot` returns — geometry + small own data+ + background, groups projected recursively; heavy fields+ (image dataURLs) omitted-and-listed, internal bookkeeping+ (`_m` HLC stamps, `magicLayer`, `shadow`) never crossing the+ boundary.+ - **Namespaced plugin storage** (`src/lib/plugins/plugin-storage.ts`):+ `canvix:plugin:<pluginId>:*`, 256 KB per plugin, 64 KB per+ value, structured-clone-checked — the prefix is the isolation+ (one plugin can never see another's keys or the host's).+ - **Panel iframe host** (`PluginRuntime.tsx`):+ `<iframe sandbox="allow-scripts">` — nothing else in the+ attribute — loading the DB-served entry panel with the+ handshake token in the fragment; mounts the broker, wires+ store subscriptions to `pushEvent`, and unmount = deactivate+ (broker disposed, listeners removed, zero residue).+ - **"Installed" section in Apps** (`InstalledApps.tsx`, lazy+ dynamic import — flag-off instances never download a byte):+ install by manifest URL, **consent modal listing every+ requested permission verbatim** (grant keeps it / remove+ deletes the row), per-plugin enable/disable, uninstall that+ never touches the design. Silent degradation: flag off (503),+ signed out (401) or offline → the section never renders.+ - **`addImage` design action** (`design-actions.ts`): the §4.3+ whitelist's image entry — `/api/media` id or dataURL ≤ 4 MB+ (png/jpeg/gif/webp), natural-size clamped, same clamps the AI+ path applies.+ - **E2E regression spec** (`tests/e2e/plugins-panel.spec.ts`):+ with the flag off the built-in app grid is untouched, no+ plugin UI leaks, and `/api/plugins` answers 503+ `PLUGINS_DISABLED`.+## [0.13.0] — 2026-11-02### Addeddiff --git a/README.md b/README.mdindex bc5ec71..2d67300 100644--- a/README.md+++ b/README.md@@ -909,7 +909,14 @@ tool descriptions so agents pick the right format.(default off) gates `/api/plugins` install/list/uninstall +a DB-served asset route with the per-manifest CSP,sha256-pinned bundles fetched through the SSRF guard- *(v0.13.1)*+ *(v0.13.1)*; the **panel runtime** (P3) turned installs into+ running code — the RPC broker (origin discipline by window+ identity, one-time handshake token, 200 calls/min, default-deny+ dispatch), a lossy read-only design-snapshot projection,+ namespaced 256 KB plugin storage, the+ `<iframe sandbox="allow-scripts">` panel host, and the Apps+ grid's "Installed" section with a consent modal that lists+ every requested permission verbatim *(v0.13.2)*- [ ] 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.json b/package.jsonindex 7ce11f4..487880f 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "canvix",- "version": "0.13.1",+ "version": "0.13.2","private": false,"description": "Canvix — free & open-source graphic design tool. A community-built Canva alternative.","scripts": {diff --git a/src/components/editor/apps/InstalledApps.tsx b/src/components/editor/apps/InstalledApps.tsxnew file mode 100644index 0000000..6fb58a4--- /dev/null+++ b/src/components/editor/apps/InstalledApps.tsx@@ -0,0 +1,326 @@+'use client'++// ─────────────────────────────────────────────────────────────+// InstalledApps — the "Installed" section of the Apps grid (P3,+// research §4.4 extension points / §4.3 lifecycle).+//+// Flow: Install by URL → POST /api/plugins (server fetches,+// validates, sha256-pins the bundle) → CONSENT MODAL lists every+// requested permission verbatim → grant keeps it listed / remove+// deletes the install row.+//+// Degrades silently: flag off (503), signed out (401) or offline+// → the section never renders. The plugin runtime itself is a+// lazy dynamic import — self-hosters with the flag off never+// download a byte of it (§4.10 bundle accounting).+// ─────────────────────────────────────────────────────────────++import { useCallback, useEffect, useState } from 'react'+import dynamic from 'next/dynamic'+import { Puzzle, ShieldCheck, Trash2, Power, Loader2, X, ExternalLink } from 'lucide-react'+import { toast } from '@/hooks/use-toast'+import { cn } from '@/lib/utils'+import type { PluginInstallView } from './PluginRuntime'++const PluginRuntime = dynamic(() => import('./PluginRuntime').then((m) => m.PluginRuntime), {+ ssr: false,+ loading: () => (+ <div className="flex items-center justify-center h-64">+ <Loader2 size={18} className="text-[#02C0CC] animate-spin" />+ </div>+ ),+})++interface InstallSummaryRow {+ id: string+ pluginId: string+ name: string+ description: string | null+ author: string | null+ version: string+ enabled: boolean+ entry: { panel?: string }+ permissions: { permission: string; description: string }[]+ createdAt: string+}++export function InstalledApps() {+ const [installs, setInstalls] = useState<InstallSummaryRow[] | null>(null)+ const [openId, setOpenId] = useState<string | null>(null)+ const [url, setUrl] = useState('')+ const [installing, setInstalling] = useState(false)+ const [consent, setConsent] = useState<InstallSummaryRow | null>(null)++ const load = useCallback(async () => {+ try {+ const res = await fetch('/api/plugins', { cache: 'no-store' })+ if (!res.ok) return // 503 flag off / 401 signed out — silent+ const data = (await res.json()) as { installs: InstallSummaryRow[] }+ setInstalls(data.installs)+ } catch {+ // offline — leave the section hidden+ }+ }, [])++ useEffect(() => {+ // async state updates live in the .then — never synchronously+ // inside the effect body (react-hooks/set-state-in-effect)+ let cancelled = false+ void fetch('/api/plugins', { cache: 'no-store' })+ .then(async (res) => {+ if (!res.ok || cancelled) return // 503 flag off / 401 signed out — silent+ const data = (await res.json()) as { installs: InstallSummaryRow[] }+ if (!cancelled) setInstalls(data.installs)+ })+ .catch(() => {+ // offline — leave the section hidden+ })+ return () => {+ cancelled = true+ }+ }, [])++ const install = useCallback(async () => {+ const manifestUrl = url.trim()+ if (!manifestUrl) return+ setInstalling(true)+ try {+ const res = await fetch('/api/plugins', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ manifestUrl }),+ })+ const data = (await res.json().catch(() => ({}))) as { install?: InstallSummaryRow; error?: string }+ if (!res.ok || !data.install) {+ toast({ title: 'Could not install this plugin', description: data.error ?? `HTTP ${res.status}` })+ return+ }+ setConsent(data.install) // consent screen — permissions verbatim+ setUrl('')+ await load()+ } catch {+ toast({ title: 'Could not install this plugin', description: 'Network error — try again.' })+ } finally {+ setInstalling(false)+ }+ }, [url, load])++ const setEnabled = useCallback(async (row: InstallSummaryRow, enabled: boolean) => {+ setInstalls((prev) => (prev ? prev.map((r) => (r.id === row.id ? { ...r, enabled } : r)) : prev))+ try {+ const res = await fetch(`/api/plugins/${encodeURIComponent(row.id)}`, {+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ enabled }),+ })+ if (!res.ok) throw new Error(String(res.status))+ toast({ title: enabled ? `${row.name} enabled` : `${row.name} disabled`, description: enabled ? undefined : 'Its elements stay on the canvas as placeholders.' })+ } catch {+ toast({ title: 'Could not update the plugin' })+ await load()+ }+ }, [load])++ const uninstall = useCallback(async (row: InstallSummaryRow) => {+ setInstalls((prev) => (prev ? prev.filter((r) => r.id !== row.id) : prev))+ if (openId === row.id) setOpenId(null)+ try {+ const res = await fetch(`/api/plugins/${encodeURIComponent(row.id)}`, { method: 'DELETE' })+ if (!res.ok) throw new Error(String(res.status))+ toast({ title: `${row.name} removed`, description: 'Your design and its elements are untouched.' })+ } catch {+ toast({ title: 'Could not remove the plugin' })+ await load()+ }+ }, [openId, load])++ // flag off / signed out / offline → render nothing at all+ if (!installs) return null++ const open = installs.find((r) => r.id === openId && r.enabled) ?? null+ if (open) {+ const view: PluginInstallView = {+ id: open.id,+ pluginId: open.pluginId,+ name: open.name,+ version: open.version,+ author: open.author,+ grantedPermissions: open.permissions.map((p) => p.permission),+ entryPanel: open.entry.panel,+ }+ return <PluginRuntime install={view} onClose={() => setOpenId(null)} />+ }++ return (+ <section className="mt-4" aria-label="Installed plugin apps">+ <div className="flex items-center gap-1.5 mb-2">+ <Puzzle size={12} className="text-[#02C0CC]" />+ <span className="text-[11px] font-bold uppercase tracking-wider text-white/50">Installed</span>+ <span className="text-[10px] text-white/30">({installs.length})</span>+ </div>++ <div className="flex gap-1.5 mb-2.5">+ <input+ value={url}+ onChange={(e) => setUrl(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === 'Enter') void install()+ }}+ placeholder="https://example.com/plugin/manifest.json"+ aria-label="Plugin manifest URL"+ className="flex-1 min-w-0 h-8 rounded-lg bg-white/[0.05] border border-white/10 px-2.5 text-[11px] text-white placeholder:text-white/25 focus:outline-none focus:border-[#7630D7]"+ />+ <button+ onClick={() => void install()}+ disabled={installing || !url.trim()}+ className="h-8 px-3 rounded-lg bg-[#7630D7] hover:bg-[#8B5CF6] disabled:opacity-40 text-white text-[11px] font-semibold flex items-center gap-1 shrink-0 transition-colors"+ >+ {installing ? <Loader2 size={11} className="animate-spin" /> : null}+ Install+ </button>+ </div>++ {installs.length === 0 ? (+ <p className="text-[11px] text-white/35 leading-relaxed rounded-xl border border-dashed border-white/10 p-3">+ No apps installed yet. Paste a plugin manifest URL above — you'll see exactly what it may access+ before anything runs.+ </p>+ ) : (+ <ul className="space-y-1.5">+ {installs.map((row) => (+ <li+ key={row.id}+ className={cn(+ 'rounded-xl border p-2.5 transition-colors',+ row.enabled ? 'border-white/10 bg-white/[0.03]' : 'border-white/5 bg-transparent opacity-60',+ )}+ >+ <div className="flex items-center gap-2">+ <button+ onClick={() => (row.enabled ? setOpenId(row.id) : toast({ title: `${row.name} is disabled` }))}+ disabled={!row.enabled}+ className="flex-1 min-w-0 text-left cursor-pointer disabled:cursor-not-allowed group"+ aria-label={`Open ${row.name}`}+ >+ <div className="flex items-center gap-1.5">+ <span className="text-[12px] font-semibold text-white truncate group-hover:text-[#02C0CC] transition-colors">+ {row.name}+ </span>+ <span className="text-[9px] font-mono text-white/30 shrink-0">v{row.version}</span>+ </div>+ <div className="text-[10px] text-white/40 truncate">{row.description ?? row.pluginId}</div>+ </button>+ <button+ onClick={() => void setEnabled(row, !row.enabled)}+ title={row.enabled ? 'Disable' : 'Enable'}+ aria-label={row.enabled ? `Disable ${row.name}` : `Enable ${row.name}`}+ className={cn(+ 'w-6 h-6 rounded-md flex items-center justify-center transition-colors',+ row.enabled ? 'text-emerald-400 hover:bg-emerald-400/10' : 'text-white/30 hover:bg-white/10',+ )}+ >+ <Power size={12} />+ </button>+ <button+ onClick={() => void uninstall(row)}+ title="Remove (your design is never touched)"+ aria-label={`Remove ${row.name}`}+ className="w-6 h-6 rounded-md flex items-center justify-center text-white/30 hover:text-red-400 hover:bg-red-400/10 transition-colors"+ >+ <Trash2 size={12} />+ </button>+ </div>+ </li>+ ))}+ </ul>+ )}++ {consent && <ConsentModal row={consent} onClose={() => setConsent(null)} />}+ </section>+ )+}++// ── consent screen — the trust gate (§4.6) ───────────────────++function ConsentModal({ row, onClose }: { row: InstallSummaryRow; onClose: () => void }) {+ const [removing, setRemoving] = useState(false)+ const remove = async () => {+ setRemoving(true)+ try {+ await fetch(`/api/plugins/${encodeURIComponent(row.id)}`, { method: 'DELETE' })+ toast({ title: `${row.name} removed`, description: 'Nothing from this plugin was kept.' })+ } catch {+ toast({ title: 'Could not remove — delete it from the Installed list' })+ } finally {+ onClose()+ }+ }+ return (+ <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4" role="dialog" aria-modal="true" aria-label={`Permissions for ${row.name}`}>+ <div className="w-full max-w-md rounded-2xl border border-white/12 bg-[#14141A] shadow-2xl">+ <div className="flex items-start gap-3 p-4 border-b border-white/8">+ <div className="w-9 h-9 rounded-xl bg-[#7630D7]/20 flex items-center justify-center shrink-0">+ <ShieldCheck size={17} className="text-[#7630D7]" />+ </div>+ <div className="flex-1 min-w-0">+ <h2 className="text-[14px] font-bold text-white">+ {row.name} <span className="font-mono text-[10px] text-white/40">v{row.version}</span>+ </h2>+ <p className="text-[11px] text-white/50">+ by {row.author ?? 'unknown author'} · wants to join this Canvix+ </p>+ </div>+ <button onClick={onClose} aria-label="Close" className="text-white/40 hover:text-white">+ <X size={15} />+ </button>+ </div>++ <div className="p-4">+ <p className="text-[12px] text-white/70 leading-relaxed mb-3">+ This app is third-party code. It runs in a sandbox and can only do the things listed below —+ <span className="text-white/90 font-semibold"> nothing else, ever</span>. Review carefully.+ </p>+ <ul className="space-y-2">+ {row.permissions.map((p) => (+ <li key={p.permission} className="flex gap-2.5 rounded-xl bg-white/[0.04] border border-white/8 p-2.5">+ <span className="text-[10px] font-mono text-[#02C0CC] bg-[#02C0CC]/10 rounded px-1.5 py-0.5 h-fit shrink-0">+ {p.permission}+ </span>+ <span className="text-[11px] text-white/70 leading-relaxed">{p.description}</span>+ </li>+ ))}+ {row.permissions.length === 0 && (+ <li className="text-[11px] text-white/45 italic">No permissions requested — this plugin is read-only.</li>+ )}+ </ul>+ </div>++ <div className="flex items-center gap-2 p-4 pt-0">+ <a+ href="https://github.com/mir-ashiq/canvix/blob/main/docs/PLUGINS.md"+ target="_blank"+ rel="noreferrer"+ className="text-[10px] text-white/35 hover:text-white/60 flex items-center gap-1"+ >+ <ExternalLink size={10} /> How plugins work+ </a>+ <div className="flex-1" />+ <button+ onClick={() => void remove()}+ disabled={removing}+ className="h-9 px-3.5 rounded-lg border border-white/12 text-[12px] text-white/70 hover:text-white hover:border-white/25 transition-colors flex items-center gap-1.5 disabled:opacity-40"+ >+ {removing ? <Loader2 size={12} className="animate-spin" /> : <Trash2 size={12} />}+ Remove it+ </button>+ <button+ onClick={onClose}+ className="h-9 px-4 rounded-lg bg-[#7630D7] hover:bg-[#8B5CF6] text-white text-[12px] font-semibold transition-colors"+ >+ Keep installed+ </button>+ </div>+ </div>+ </div>+ )+}diff --git a/src/components/editor/apps/PluginRuntime.tsx b/src/components/editor/apps/PluginRuntime.tsxnew file mode 100644index 0000000..9a70bfd--- /dev/null+++ b/src/components/editor/apps/PluginRuntime.tsx@@ -0,0 +1,193 @@+'use client'++// ─────────────────────────────────────────────────────────────+// PluginRuntime — the host side of a plugin panel (P3, research+// PLUGIN-SYSTEM.md §4.3 "lifecycle").+//+// This component is the ONLY thing that turns an installed row+// into running code. Everything the research pinned as the+// boundary lives here, in one auditable place:+//+// · <iframe sandbox="allow-scripts"> — and NOTHING else in+// the attribute: no same-origin, no top-navigation, no+// forms, no popups. The frame is an opaque origin: it+// cannot read host cookies, host DOM or host localStorage.+// · The handshake token rides the URL fragment (#…) — the+// fragment is never sent over the wire, and the broker+// refuses the first RPC call that does not echo it.+// · The PluginBroker owns every message in/out (origin+// discipline, permissions, rate budget, payload caps).+// · Unmount = deactivate: broker disposed, listener removed.+// Plugins are ephemeral; only their namespaced storage+// survives.+// ─────────────────────────────────────────────────────────────++import { useCallback, useEffect, useMemo, useRef, useState } from 'react'+import { AlertTriangle, Loader2, ShieldCheck } from 'lucide-react'+import { AppHeader } from './registry'+import { PluginBroker, type BrokerInstall } from '@/lib/plugins/broker'+import { PluginStorage } from '@/lib/plugins/plugin-storage'+import { applyDesignAction } from '@/lib/design-actions'+import { useEditorStore } from '@/store/editor-store'+import { toast } from '@/hooks/use-toast'++export interface PluginInstallView {+ id: string+ pluginId: string+ name: string+ version: string+ author?: string | null+ /** granted permission strings (the consent record) */+ grantedPermissions: string[]+ /** manifest entry.panel — relative path inside the bundle */+ entryPanel?: string+}++/** Cryptographically random handshake token (URL-fragment safe). */+function newHandshakeToken(): string {+ const bytes = new Uint8Array(18)+ crypto.getRandomValues(bytes)+ return Array.from(bytes, (b) => b.toString(36).padStart(2, '0')).join('').slice(0, 24)+}++export function PluginRuntime({ install, onClose }: { install: PluginInstallView; onClose: () => void }) {+ const iframeRef = useRef<HTMLIFrameElement | null>(null)+ const brokerRef = useRef<PluginBroker | null>(null)+ const [ready, setReady] = useState(false)+ const [failed, setFailed] = useState(false)++ // one handshake token per mount — never reused across remounts+ const handshake = useMemo(() => newHandshakeToken(), [])+ const panelSrc = useMemo(() => {+ const entry = install.entryPanel && /^[\w][\w./-]*\.html$/.test(install.entryPanel) ? install.entryPanel : 'panel.html'+ return `/api/plugins/${encodeURIComponent(install.id)}/serve/${entry}#${encodeURIComponent(handshake)}`+ }, [install.id, install.entryPanel, handshake])++ const hostVersion = useMemo(() => {+ const el = document.querySelector('meta[name="canvix-version"]')+ return el?.getAttribute('content') ?? 'dev'+ }, [])++ const attachBroker = useCallback(() => {+ const frame = iframeRef.current?.contentWindow+ if (!frame || brokerRef.current || failed) return++ const record: BrokerInstall = {+ installId: install.id,+ pluginId: install.pluginId,+ version: install.version,+ permissions: install.grantedPermissions,+ }+ const broker = new PluginBroker({+ install: record,+ host: {+ getDesignState: () => {+ const s = useEditorStore.getState()+ return { pages: s.pages, currentPage: s.currentPage, readOnly: s.readOnly }+ },+ applyAction: (action) => applyDesignAction({ ...action, type: String(action.type) }),+ notify: (text) => toast({ title: install.name, description: text }),+ closePanel: () => onClose(),+ logError: (scope, error) => console.error(`[plugin:${install.pluginId}] ${scope}`, error),+ },+ storage: new PluginStorage(install.pluginId),+ hostVersion,+ context: 'panel',+ })+ const onMessage = (ev: MessageEvent) => broker.handleMessage(ev)+ broker.attach(frame, handshake, onMessage)+ brokerRef.current = broker+ setReady(true)++ // host→plugin subscription pushes: zustand's subscribe fires on+ // every set — diff against the last snapshot we pushed so a+ // plugin only hears about real selection/document changes+ let lastSelection = JSON.stringify(useEditorStore.getState().selectedIds)+ let lastDoc = JSON.stringify(docSignature())+ const unsub = useEditorStore.subscribe(() => {+ const broker = brokerRef.current+ if (!broker) return+ const s = useEditorStore.getState()+ const selection = JSON.stringify(s.selectedIds)+ if (selection !== lastSelection) {+ lastSelection = selection+ broker.pushEvent('selection', { ids: s.selectedIds })+ }+ const doc = JSON.stringify(docSignature())+ if (doc !== lastDoc) {+ lastDoc = doc+ broker.pushEvent('document', {+ pages: s.pages.map((p) => ({ id: p.id, elements: p.elements.length })),+ currentPage: s.currentPage,+ })+ }+ })++ // dispose on unmount: no listener leaks, no dangling iframes+ return () => {+ unsub()+ broker.dispose(onMessage)+ brokerRef.current = null+ }+ }, [install.id, install.pluginId, install.version, handshake, hostVersion, failed])++ useEffect(() => {+ const cleanup = attachBroker()+ return cleanup+ }, [attachBroker])++ return (+ <div className="flex flex-col h-full min-h-0">+ <AppHeader icon={ShieldCheck} title={install.name} onClose={onClose}>+ <span className="text-[10px] text-white/35 font-mono">+ v{install.version}+ {install.author ? ` · ${install.author}` : ''}+ </span>+ </AppHeader>++ <div className="relative flex-1 min-h-0 rounded-xl border border-white/10 bg-white/[0.02] overflow-hidden">+ {!ready && !failed && (+ <div className="absolute inset-0 z-10 flex flex-col items-center justify-center gap-2 bg-[#0F0F13]">+ <Loader2 size={18} className="text-[#02C0CC] animate-spin" />+ <p className="text-[11px] text-white/45">Starting {install.name} in its sandbox…</p>+ </div>+ )}+ {failed && (+ <div className="absolute inset-0 z-10 flex flex-col items-center justify-center gap-2 bg-[#0F0F13] px-6 text-center">+ <AlertTriangle size={18} className="text-amber-400" />+ <p className="text-[12px] text-white/70 font-semibold">This app could not start</p>+ <p className="text-[11px] text-white/45 leading-relaxed">+ The plugin's panel is unavailable — it may have been uninstalled or disabled. Removing the app+ never affects your design.+ </p>+ </div>+ )}+ <iframe+ ref={iframeRef}+ title={`${install.name} (sandboxed plugin)`}+ // THE SECURITY BOUNDARY — allow-scripts ONLY:+ // no allow-same-origin (opaque origin: no cookies/DOM/storage)+ // no allow-top-navigation, allow-forms, allow-popups, allow-modals+ sandbox="allow-scripts"+ src={panelSrc}+ className="w-full h-full border-0 bg-white"+ onError={() => setFailed(true)}+ />+ </div>++ <p className="mt-2 text-[10px] text-white/30 leading-relaxed flex items-center gap-1.5">+ <ShieldCheck size={11} className="shrink-0" />+ Sandboxed — this app runs isolated and can only act inside the permissions you granted.+ </p>+ </div>+ )+}++/** Cheap structural signature of the document for document-event diffing. */+function docSignature(): { pages: { id: string; n: number }[]; currentPage: number } {+ const s = useEditorStore.getState()+ return {+ pages: s.pages.map((p) => ({ id: p.id, n: p.elements.length })),+ currentPage: s.currentPage,+ }+}diff --git a/src/components/editor/panels/AppsPanel.tsx b/src/components/editor/panels/AppsPanel.tsxindex 18b5166..5a3df46 100644--- a/src/components/editor/panels/AppsPanel.tsx+++ b/src/components/editor/panels/AppsPanel.tsx@@ -1,12 +1,18 @@'use client'import { useState } from 'react'+import dynamic from 'next/dynamic'import { ArrowRight } from 'lucide-react'import { PanelShell } from './panel-shell'import { CANVIX_APPS, type CanvixApp } from '../apps/registry'import { toast } from '@/hooks/use-toast'import { cn } from '@/lib/utils'+// v0.13 (P3): the "Installed" section — installed plugin panels.+// Lazy + client-only: instances with CANVIX_PLUGINS off never+// download a byte of the plugin runtime (research §4.10).+const InstalledApps = dynamic(() => import('../apps/InstalledApps').then((m) => m.InstalledApps), { ssr: false })+/** Canva Apps panel — a registry-driven app ecosystem. Open an app to get its* full panel UI; new apps are added by registering in apps/registry.tsx. */export function AppsPanel() {@@ -17,25 +23,28 @@ export function AppsPanel() {{open ? (<open.content onClose={() => setOpen(null)} />) : (- <div className="grid grid-cols-2 gap-2.5">- {CANVIX_APPS.map((app) => (- <AppCard key={app.id} app={app} onOpen={() => setOpen(app)} />- ))}- <div className="col-span-2 mt-1 rounded-xl border border-dashed border-white/12 p-3 text-center">- <p className="text-[11px] text-white/40 leading-relaxed">- Canvix apps are open —{' '}- <a- href="https://github.com/mir-ashiq/canvix"- target="_blank"- rel="noreferrer"- className="text-[#02C0CC] hover:underline"- >- build your own- </a>{' '}- by registering a component in <code className="text-white/60">apps/registry.tsx</code>.- </p>+ <>+ <div className="grid grid-cols-2 gap-2.5">+ {CANVIX_APPS.map((app) => (+ <AppCard key={app.id} app={app} onOpen={() => setOpen(app)} />+ ))}+ <div className="col-span-2 mt-1 rounded-xl border border-dashed border-white/12 p-3 text-center">+ <p className="text-[11px] text-white/40 leading-relaxed">+ Canvix apps are open —{' '}+ <a+ href="https://github.com/mir-ashiq/canvix"+ target="_blank"+ rel="noreferrer"+ className="text-[#02C0CC] hover:underline"+ >+ build your own+ </a>{' '}+ by registering a component in <code className="text-white/60">apps/registry.tsx</code>.+ </p>+ </div></div>- </div>+ <InstalledApps />+ </>)}</PanelShell>)diff --git a/src/lib/design-actions.ts b/src/lib/design-actions.tsindex 77ea687..3c810cf 100644--- a/src/lib/design-actions.ts+++ b/src/lib/design-actions.ts@@ -90,6 +90,28 @@ export async function applyDesignAction(action: DesignAction): Promise<string> {return 'Text added — fully editable'}+ // v0.13 (P3): plugin panels may add images — the §4.3 whitelist+ // ("dataURL ≤ 4 MB or /api/media id"). Same clamps the AI image+ // path applies; nothing about the plugin is trusted raw.+ case 'addImage': {+ const src = String(action.src ?? '')+ const isMediaRef = /^\/api\/media\/[A-Za-z0-9_-]{1,64}$/.test(src)+ const isDataUrl = /^data:image\/(png|jpeg|jpg|gif|webp);base64,[A-Za-z0-9+/=]+$/.test(src)+ if (!isMediaRef && !isDataUrl) return 'src must be a /api/media id or a png/jpeg/gif/webp data URL'+ if (isDataUrl && src.length > 4 * 1024 * 1024) return 'Image is larger than 4 MB'+ const naturalWidth = Math.min(8000, Math.max(16, Number(action.naturalWidth) || 800))+ const naturalHeight = Math.min(8000, Math.max(16, Number(action.naturalHeight) || 600))+ const scale = Math.min(1, (width * 0.7) / naturalWidth)+ const el = createImageElement(src, naturalWidth, naturalHeight, {+ width: Math.max(8, Math.round(naturalWidth * scale)),+ height: Math.max(8, Math.round(naturalHeight * scale)),+ x: Math.round(width * 0.15),+ y: Math.round(height * 0.15),+ })+ useEditorStore.getState().addElement(el)+ return 'Image added'+ }+case 'updateElements': {const ids = resolveIds(action.ids)if (!ids.length) return 'No matching elements'@@ -370,6 +392,7 @@ function balanceLayout(): string {export function describeAction(action: DesignAction): string {switch (action.type) {case 'addText': return `Add text: “${String(action.text ?? '').slice(0, 40)}${String(action.text ?? '').length > 40 ? '…' : ''}”`+ case 'addImage': return `Add image (${String(action.src ?? '').startsWith('data:') ? 'embedded' : 'media library'})`case 'updateElements': return `Update ${action.ids?.length ?? 0} element${(action.ids?.length ?? 0) === 1 ? '' : 's'}`case 'deleteElements': return `Delete ${action.ids?.length ?? 0} element${(action.ids?.length ?? 0) === 1 ? '' : 's'}`case 'moveElements': return action.to ? `Move to ${action.to}` : 'Move elements'diff --git a/src/lib/plugins/broker.test.ts b/src/lib/plugins/broker.test.tsnew file mode 100644index 0000000..69f91ad--- /dev/null+++ b/src/lib/plugins/broker.test.ts@@ -0,0 +1,455 @@+import { describe, expect, it, vi } from 'vitest'+import { PluginBroker, PANEL_ACTION_TYPES, RPC_RATE_CALLS, NOTIFY_TEXT_MAX, type BrokerHost, type BrokerInstall, type PostableWindow } from './broker'+import { PluginStorage, type StorageLike } from './plugin-storage'+import { rpcOk } from './rpc'+import type { PageData } from '@/lib/types'++// The broker is where the security model becomes real: origin+// identity, one-time handshake, rate budget, default-deny+// permissions, whitelist actions, read-only suspension. Every+// property below is a §4.3/§4.6/§4.7 requirement, and each one+// fails CLOSED (an error envelope or silence — never a pass).++class FakeWindow {+ sent: unknown[] = []+ postMessage(message: unknown): void {+ this.sent.push(message)+ }+}++function memoryStorage(): StorageLike {+ const map = new Map<string, string>()+ return {+ getItem: (k) => (map.has(k) ? map.get(k)! : null),+ setItem: (k, v) => void map.set(k, v),+ removeItem: (k) => void map.delete(k),+ key: (i) => Array.from(map.keys())[i] ?? null,+ get length() {+ return map.size+ },+ }+}++const PAGES: PageData[] = [+ {+ id: 'page_1',+ background: { type: 'solid', color: '#FFFFFF' },+ elements: [+ {+ id: 'el_1',+ type: 'text',+ x: 0,+ y: 0,+ width: 100,+ height: 50,+ rotation: 0,+ opacity: 1,+ locked: false,+ visible: true,+ text: 'words',+ fontSize: 40,+ fontFamily: 'Inter',+ bold: false,+ italic: false,+ underline: false,+ strike: false,+ uppercase: false,+ fill: '#000000',+ align: 'center',+ lineHeight: 1.2,+ letterSpacing: 0,+ } as never,+ ],+ } as PageData,+]++interface TestOpts {+ permissions?: string[]+ readOnly?: boolean+}++function makeBroker(opts: TestOpts = {}) {+ const install: BrokerInstall = {+ installId: 'inst_1',+ pluginId: 'com.example.test',+ version: '1.0.0',+ permissions: opts.permissions ?? ['design:read', 'design:write', 'storage', 'ui:notify'],+ }+ const applyAction = vi.fn(async () => 'applied')+ const notify = vi.fn()+ const closePanel = vi.fn()+ const logError = vi.fn()+ const host: BrokerHost = {+ getDesignState: () => ({ pages: PAGES, currentPage: 0, readOnly: opts.readOnly ?? false }),+ applyAction,+ notify,+ closePanel,+ logError,+ }+ const clock = { t: 1_000_000 }+ const broker = new PluginBroker({+ install,+ host,+ storage: new PluginStorage(install.pluginId, memoryStorage()),+ hostVersion: '0.13.2',+ now: () => clock.t,+ })+ const frame = new FakeWindow()+ broker.attach(frame as unknown as PostableWindow, 'handshake-token-1', () => {})+ const ev = (data: unknown, source: unknown = frame) => ({ source, data }) as unknown as MessageEvent+ // dispatch() is async — flush enough microtask turns for send() to land+ const flush = async () => {+ for (let i = 0; i < 6; i++) await Promise.resolve()+ }+ const call = async (method: string, params?: unknown, extra: Record<string, unknown> = {}) => {+ broker.handleMessage(ev({ v: 1, id: `c${frame.sent.length}`, dir: 'call', method, params, ...extra }))+ await flush()+ }+ const last = () => frame.sent[frame.sent.length - 1] as { id?: string; ok?: boolean; error?: { code: string; message: string }; result?: unknown }+ const callOk = async (method: string, params?: unknown) => {+ await call(method, params, { handshake: 'handshake-token-1' })+ }+ return { broker, frame, ev, call, callOk, last, host: { applyAction, notify, closePanel, logError }, clock }+}++describe('origin discipline', () => {+ it('ignores messages from any window other than the mounted frame', () => {+ const { broker, frame } = makeBroker()+ const stranger = new FakeWindow()+ broker.handleMessage({ source: stranger, data: { v: 1, id: 'x', dir: 'call', method: 'ping', handshake: 'handshake-token-1' } } as unknown as MessageEvent)+ broker.handleMessage({ source: null, data: { v: 1, id: 'x', dir: 'call', method: 'ping', handshake: 'handshake-token-1' } } as MessageEvent)+ broker.handleMessage({ source: new FakeWindow() as unknown as PostableWindow, data: { v: 1, id: 'x', dir: 'call', method: 'ping', handshake: 'handshake-token-1' } } as unknown as MessageEvent)+ expect(frame.sent).toHaveLength(0)+ expect(broker.isVerified).toBe(false)+ })++ it('ignores non-object payloads', () => {+ const { broker, frame, ev } = makeBroker()+ broker.handleMessage(ev('ping'))+ broker.handleMessage(ev(null))+ broker.handleMessage(ev(42))+ expect(frame.sent).toHaveLength(0)+ })+})++describe('handshake (one-time token echo)', () => {+ it('rejects the first call lacking the handshake with E_PERMISSION and stays unverified', () => {+ const { broker, ev, last } = makeBroker()+ broker.handleMessage(ev({ v: 1, id: 'c1', dir: 'call', method: 'ping' }))+ expect(last().error?.code).toBe('E_PERMISSION')+ expect(last().error?.message).toContain('handshake')+ expect(broker.isVerified).toBe(false)+ })++ it('rejects a wrong token and stays unverified', async () => {+ const { broker, frame, ev, last } = makeBroker()+ broker.handleMessage(ev({ v: 1, id: 'c1', dir: 'call', method: 'ping', handshake: 'wrong-token-99' }))+ await Promise.resolve()+ expect(last().error?.code).toBe('E_PERMISSION')+ expect(broker.isVerified).toBe(false)+ // and the frame got exactly one rejection+ expect(frame.sent).toHaveLength(1)+ })++ it('accepts the right token once; later calls need not repeat it', async () => {+ const { broker, ev, last } = makeBroker()+ broker.handleMessage(ev({ v: 1, id: 'c1', dir: 'call', method: 'ping', handshake: 'handshake-token-1' }))+ await Promise.resolve()+ expect(last().ok).toBe(true)+ expect(broker.isVerified).toBe(true)+ broker.handleMessage(ev({ v: 1, id: 'c2', dir: 'call', method: 'ping' }))+ await Promise.resolve()+ expect((last() as { ok?: boolean }).ok).toBe(true)+ })++ it('a failed handshake does not consume rate budget', async () => {+ const { broker, ev, last } = makeBroker()+ for (let i = 0; i < RPC_RATE_CALLS + 20; i++) {+ broker.handleMessage(ev({ v: 1, id: `bad${i}`, dir: 'call', method: 'ping', handshake: 'nope-nope' }))+ }+ expect(last().error?.code).toBe('E_PERMISSION')+ broker.handleMessage(ev({ v: 1, id: 'good', dir: 'call', method: 'ping', handshake: 'handshake-token-1' }))+ await Promise.resolve()+ expect((last() as { ok?: boolean }).ok).toBe(true)+ })+})++describe('envelope validation', () => {+ it('answers protocol mismatch with E_VERSION', async () => {+ const { broker, ev, last } = makeBroker()+ broker.handleMessage(ev({ v: 2, id: 'c1', dir: 'call', method: 'ping', handshake: 'handshake-token-1' }))+ await Promise.resolve()+ expect(last().error?.code).toBe('E_VERSION')+ })++ it('answers malformed envelopes with E_MALFORMED; unknown dirs are ignored silently', async () => {+ const { broker, frame, ev, last } = makeBroker()+ // a dir that is neither call nor result is noise — no answer at all+ broker.handleMessage(ev({ v: 1, id: 'c0', dir: 'side', method: 'ping' }))+ expect(frame.sent).toHaveLength(0)+ broker.handleMessage(ev({ v: 1, id: '!!bad id!!', dir: 'call', method: 'ping', handshake: 'handshake-token-1' }))+ await Promise.resolve()+ expect(last().error?.code).toBe('E_MALFORMED')+ })++ it('answers unknown methods with E_METHOD', async () => {+ const { broker, ev, last } = makeBroker()+ broker.handleMessage(ev({ v: 1, id: 'c1', dir: 'call', method: 'host.readFile', handshake: 'handshake-token-1' }))+ await Promise.resolve()+ expect(last().error?.code).toBe('E_METHOD')+ // prototype-chain tricks must not "find" methods either+ broker.handleMessage(ev({ v: 1, id: 'c2', dir: 'call', method: 'constructor', handshake: 'handshake-token-1' }))+ await Promise.resolve()+ expect(last().error?.code).toBe('E_METHOD')+ })++ it('answers oversized params with E_PAYLOAD', async () => {+ const { broker, ev, last } = makeBroker()+ broker.handleMessage(ev({ v: 1, id: 'c1', dir: 'call', method: 'storage.set', params: { key: 'k', value: 'x'.repeat(300 * 1024) }, handshake: 'handshake-token-1' }))+ await Promise.resolve()+ expect(last().error?.code).toBe('E_PAYLOAD')+ })+})++describe('rate limit', () => {+ it('allows RPC_RATE_CALLS per minute then answers E_THROTTLE', async () => {+ const { broker, ev, last } = makeBroker()+ for (let i = 0; i < RPC_RATE_CALLS; i++) {+ broker.handleMessage(ev({ v: 1, id: `p${i}`, dir: 'call', method: 'ping', handshake: 'handshake-token-1' }))+ }+ await Promise.resolve()+ expect((last() as { ok?: boolean }).ok).toBe(true)+ broker.handleMessage(ev({ v: 1, id: 'over', dir: 'call', method: 'ping' }))+ await Promise.resolve()+ expect(last().error?.code).toBe('E_THROTTLE')+ })++ it('recovers when the window slides', async () => {+ const { broker, ev, last, clock } = makeBroker()+ for (let i = 0; i < RPC_RATE_CALLS; i++) {+ broker.handleMessage(ev({ v: 1, id: `p${i}`, dir: 'call', method: 'ping', handshake: 'handshake-token-1' }))+ }+ broker.handleMessage(ev({ v: 1, id: 'over', dir: 'call', method: 'ping' }))+ expect(last().error?.code).toBe('E_THROTTLE')+ clock.t += 61_000+ broker.handleMessage(ev({ v: 1, id: 'fresh', dir: 'call', method: 'ping' }))+ await Promise.resolve()+ expect((last() as { ok?: boolean }).ok).toBe(true)+ })+})++describe('permissions (default-deny)', () => {+ it('denies a granted-but-not-consented method with E_PERMISSION', async () => {+ const { callOk, last } = makeBroker({ permissions: ['design:read'] }) // no design:write+ await callOk('actions.apply', { action: { type: 'addText', text: 'x' } })+ expect(last().error?.code).toBe('E_PERMISSION')+ })++ it('denies storage when storage was not granted', async () => {+ const { callOk, last } = makeBroker({ permissions: [] })+ await callOk('storage.set', { key: 'k', value: 1 })+ expect(last().error?.code).toBe('E_PERMISSION')+ await callOk('storage.keys')+ expect(last().error?.code).toBe('E_PERMISSION')+ })++ it('ui.notify requires ui:notify', async () => {+ const { callOk, last } = makeBroker({ permissions: [] })+ await callOk('ui.notify', { text: 'hello' })+ expect(last().error?.code).toBe('E_PERMISSION')+ })++ it('info and ping need no permission', async () => {+ const { callOk, last } = makeBroker({ permissions: [] })+ await callOk('ping')+ expect((last() as { ok?: boolean }).ok).toBe(true)+ await callOk('info')+ const info = last().result as { api: { major: number; minor: number }; host: string; plugin: { id: string }; capabilities: { panel: boolean; renderer: boolean } }+ expect(info.api.major).toBe(1)+ expect(info.host).toBe('0.13.2')+ expect(info.plugin.id).toBe('com.example.test')+ expect(info.capabilities).toEqual({ panel: true, renderer: false })+ })+})++describe('design.getSnapshot', () => {+ it('returns the projected read-only snapshot', async () => {+ const { callOk, last } = makeBroker({ permissions: ['design:read'] })+ await callOk('design.getSnapshot')+ const r = last()+ expect(r.ok).toBe(true)+ const snap = r.result as { pages: { elements: { id: string; type: string; text: string }[] }[]; currentPage: number }+ expect(snap.pages[0]!.elements[0]!.id).toBe('el_1')+ expect(snap.pages[0]!.elements[0]!.text).toBe('words')+ })++ it('denies without design:read', async () => {+ const { callOk, last } = makeBroker({ permissions: [] })+ await callOk('design.getSnapshot')+ expect(last().error?.code).toBe('E_PERMISSION')+ })+})++describe('subscribe + pushEvent', () => {+ it('rejects unknown topics with E_PAYLOAD', async () => {+ const { callOk, last } = makeBroker({ permissions: ['design:read'] })+ await callOk('subscribe', { topic: 'cookies' })+ expect(last().error?.code).toBe('E_PAYLOAD')+ })++ it('pushes events only for subscribed topics', async () => {+ const { broker, frame, callOk } = makeBroker({ permissions: ['design:read'] })+ await callOk('subscribe', { topic: 'selection' })+ broker.pushEvent('selection', { ids: ['el_1'] })+ broker.pushEvent('document', { pages: 1 }) // not subscribed — dropped+ const pushes = frame.sent.filter((m) => (m as { method?: string }).method === 'event')+ expect(pushes).toHaveLength(1)+ expect((pushes[0] as { params: { topic: string; payload: unknown } }).params).toEqual({ topic: 'selection', payload: { ids: ['el_1'] } })+ })++ it('settles the ack when the plugin answers, and drops it after dispose', async () => {+ const { broker, frame, ev, callOk } = makeBroker({ permissions: ['design:read'] })+ await callOk('subscribe', { topic: 'selection' })+ broker.pushEvent('selection', { ids: [] })+ const push = frame.sent.find((m) => (m as { method?: string }).method === 'event') as { id: string }+ expect(push).toBeTruthy()+ broker.handleMessage(ev(rpcOk(push.id, { ok: true }))) // ack — no throw+ broker.pushEvent('selection', { ids: ['x'] })+ broker.dispose()+ const count = frame.sent.filter((m) => (m as { method?: string }).method === 'event').length+ expect(count).toBe(2) // post-dispose push produced nothing+ })++ it('ignores plugin results before the handshake completed', () => {+ const { broker, frame, ev } = makeBroker()+ broker.handleMessage(ev(rpcOk('whatever', { ok: true })))+ expect(frame.sent).toHaveLength(0)+ })+})++describe('actions.apply', () => {+ it('executes a whitelisted action through the host', async () => {+ const { callOk, host, last } = makeBroker()+ await callOk('actions.apply', { action: { type: 'addText', text: 'hi' } })+ expect(last().ok).toBe(true)+ expect(host.applyAction).toHaveBeenCalledWith({ type: 'addText', text: 'hi' })+ expect((last().result as { message: string }).message).toBe('applied')+ })++ it('rejects action types outside the panel whitelist with E_PAYLOAD', async () => {+ const { callOk, last } = makeBroker()+ for (const type of ['generateImage', 'translate', 'addPluginElement', 'updatePluginElementData', '__proto__', '']) {+ await callOk('actions.apply', { action: { type } })+ expect(last().error?.code).toBe('E_PAYLOAD')+ }+ expect(PANEL_ACTION_TYPES.has('addText')).toBe(true)+ })++ it('suspends writes on read-only designs with E_PERMISSION', async () => {+ const { callOk, last } = makeBroker({ readOnly: true })+ await callOk('actions.apply', { action: { type: 'addText', text: 'x' } })+ expect(last().error?.code).toBe('E_PERMISSION')+ })++ it('rejects non-object action params with E_PAYLOAD', async () => {+ const { callOk, last } = makeBroker()+ await callOk('actions.apply', { action: 'addText' })+ expect(last().error?.code).toBe('E_PAYLOAD')+ await callOk('actions.apply', {})+ expect(last().error?.code).toBe('E_PAYLOAD')+ })++ it('a host-side throw answers E_INTERNAL and logs privately', async () => {+ const { callOk, last, host } = makeBroker()+ host.applyAction.mockRejectedValueOnce(new Error('internal detail'))+ await callOk('actions.apply', { action: { type: 'addText', text: 'x' } })+ expect(last().error?.code).toBe('E_INTERNAL')+ expect(host.logError).toHaveBeenCalled()+ expect(JSON.stringify(last())).not.toContain('internal detail')+ })+})++describe('storage methods', () => {+ it('round-trips values inside the plugin namespace', async () => {+ const { callOk, last } = makeBroker({ permissions: ['storage'] })+ await callOk('storage.set', { key: 'palette', value: ['#fff', '#000'] })+ await callOk('storage.get', { key: 'palette' })+ expect((last().result as { value: unknown }).value).toEqual(['#fff', '#000'])+ await callOk('storage.keys')+ expect((last().result as { keys: string[] }).keys).toEqual(['palette'])+ await callOk('storage.remove', { key: 'palette' })+ await callOk('storage.get', { key: 'palette' })+ expect((last().result as { value: unknown }).value).toBeNull()+ })++ it('surfaces quota errors as E_PAYLOAD-coded errors', async () => {+ const { callOk, last } = makeBroker({ permissions: ['storage'] })+ await callOk('storage.set', { key: 'big', value: 'z'.repeat(70 * 1024) })+ expect(last().ok).toBe(false)+ expect(last().error?.code).toBe('E_PAYLOAD')+ expect(last().error?.message).toContain('storage')+ })++ it('rejects malformed keys with E_PAYLOAD', async () => {+ const { callOk, last } = makeBroker({ permissions: ['storage'] })+ await callOk('storage.set', { key: '../escape', value: 1 })+ expect(last().ok).toBe(false)+ expect(last().error?.code).toBe('E_PAYLOAD')+ })+})++describe('ui methods', () => {+ it('notifies with sanitized, capped text', async () => {+ const { callOk, host } = makeBroker({ permissions: ['ui:notify'] })+ await callOk('ui.notify', { text: `a${'b'.repeat(NOTIFY_TEXT_MAX)}c` })+ expect(host.notify).toHaveBeenCalledTimes(1)+ const text = host.notify.mock.calls[0]![0] as string+ expect(text.length).toBe(NOTIFY_TEXT_MAX)+ await callOk('ui.notify', { text: 'ok\x00\x07fine' })+ expect(host.notify.mock.calls[1]![0]).toBe('okfine')+ })++ it('rejects non-string or empty notify text', async () => {+ const { callOk, last } = makeBroker({ permissions: ['ui:notify'] })+ await callOk('ui.notify', { text: 42 })+ expect(last().error?.code).toBe('E_PAYLOAD')+ await callOk('ui.notify', { text: ' ' })+ expect(last().error?.code).toBe('E_PAYLOAD')+ })++ it('closePanel reaches the host', async () => {+ const { callOk, host } = makeBroker({ permissions: ['ui:notify'] })+ await callOk('ui.closePanel')+ expect(host.closePanel).toHaveBeenCalledTimes(1)+ })+})++describe('elements.registerRenderer (P4 preview semantics)', () => {+ it('answers E_METHOD in panel context even with the permission granted', async () => {+ const { callOk, last } = makeBroker({ permissions: ['element:plugin'] })+ await callOk('elements.registerRenderer', { kind: 'cloud', fn: 1 })+ expect(last().error?.code).toBe('E_METHOD')+ })+})++describe('lifecycle', () => {+ it('a disposed broker goes silent', async () => {+ const { broker, frame, ev } = makeBroker()+ broker.handleMessage(ev({ v: 1, id: 'c1', dir: 'call', method: 'ping', handshake: 'handshake-token-1' }))+ await Promise.resolve()+ expect(frame.sent).toHaveLength(1)+ broker.dispose()+ broker.handleMessage(ev({ v: 1, id: 'c2', dir: 'call', method: 'ping' }))+ await Promise.resolve()+ expect(frame.sent).toHaveLength(1)+ broker.pushEvent('selection', {}) // must not throw even with subscriptions+ })++ it('registerRenderer stays reserved for service context (catalog sanity)', async () => {+ // the method is in the wire catalog so P4 service iframes can use it;+ // panel brokers must keep refusing it (tested above)+ const { callOk, last } = makeBroker({ permissions: ['element:plugin'] })+ await callOk('elements.registerRenderer', { kind: 'k' })+ expect(last().error?.code).toBe('E_METHOD')+ })+})diff --git a/src/lib/plugins/broker.ts b/src/lib/plugins/broker.tsnew file mode 100644index 0000000..da499f2--- /dev/null+++ b/src/lib/plugins/broker.ts@@ -0,0 +1,426 @@+// ─────────────────────────────────────────────────────────────+// Plugin RPC broker — the host-side runtime half of the plugin+// system (research PLUGIN-SYSTEM.md §4.3, P3).+//+// One broker instance per mounted plugin iframe. It is the ONLY+// path between a plugin and the host:+//+// origin discipline ev.source === the iframe window we mounted+// (an opaque-origin frame cannot be named,+// so source identity IS the origin check)+// handshake a one-time token rides the iframe URL+// fragment; the first call must echo it+// rate limit 200 calls / minute, then E_THROTTLE+// permissions every method is checked against the+// install's granted list (default-deny)+// payload caps every envelope passes the RPC byte cap+//+// The broker is framework-free and fully dependency-injected:+// node unit tests drive it with fake windows and storages, the+// PluginRuntime component drives it with the real ones.+//+// postMessage targetOrigin: a sandboxed iframe has an OPAQUE+// origin, so '*' is the only addressable target. This is safe+// because every INBOUND message is gated on ev.source identity —+// we only ever speak to the frame we mounted, and it cannot be+// navigated away without dropping our reference.+// ─────────────────────────────────────────────────────────────++import { checkCloneSafe } from './data-caps'+import { PluginStorage } from './plugin-storage'+import { pluginSnapshot, type PluginDesignSnapshot } from './snapshot'+import { methodAllowed, requiredPermission } from './permissions'+import {+ MAX_RPC_BYTES,+ RPC_API_MAJOR,+ RPC_API_MINOR,+ newRpcId,+ parseRpcCall,+ parseRpcResult,+ rpcErr,+ rpcOk,+ type RpcCall,+ type RpcErrorCode,+} from './rpc'++/** The validated action set a PANEL may drive (§4.3). */+export const PANEL_ACTION_TYPES: ReadonlySet<string> = new Set([+ 'addText',+ 'addImage',+ 'updateElements',+ 'deleteElements',+ 'setBackground',+ 'addPage',+ 'duplicatePage',+ 'alignElements',+ 'distributeElements',+])++/** push-event topics a plugin may subscribe to (§4.3). */+export const SUBSCRIBE_TOPICS: ReadonlySet<string> = new Set(['selection', 'document'])++/** RPC rate budget (§4.7): 200 calls / minute, soft. */+export const RPC_RATE_CALLS = 200+export const RPC_RATE_WINDOW_MS = 60_000++/** How long a pushed event waits for the plugin's ack before dropping. */+export const EVENT_ACK_TIMEOUT_MS = 5_000++/** ui.notify text cap. */+export const NOTIFY_TEXT_MAX = 200++/** What the broker needs to know about an install. */+export interface BrokerInstall {+ installId: string+ pluginId: string+ version: string+ /** granted (normalized) permission strings — the consent record */+ permissions: string[]+}++/** Host capabilities the broker calls into (all injected, all mockable). */+export interface BrokerHost {+ /** current editor state for snapshots + read-only checks */+ getDesignState(): { pages: Parameters<typeof pluginSnapshot>[0]['pages']; currentPage: number; readOnly: boolean }+ /** execute a whitelisted design action (design-actions.ts) */+ applyAction(action: Record<string, unknown>): Promise<string>+ /** toast */+ notify(text: string): void+ /** close the plugin's panel */+ closePanel(): void+ /** structured error log — details never cross the RPC boundary */+ logError(scope: string, error: unknown): void+}++/** Minimal window surface (real iframes and test doubles both fit). */+export interface PostableWindow {+ postMessage(message: unknown, targetOrigin: string): void+}++export interface BrokerOptions {+ install: BrokerInstall+ host: BrokerHost+ storage: PluginStorage+ /** host app version for `info` (injected — no server imports here) */+ hostVersion: string+ /** 'panel' now; 'service' arrives with P4 renderers */+ context?: 'panel' | 'service'+ /** injectable clock for tests */+ now?: () => number+}++interface PendingAck {+ timer: ReturnType<typeof setTimeout>+ settled: boolean+}++export class PluginBroker {+ private readonly install: BrokerInstall+ private readonly host: BrokerHost+ private readonly storage: PluginStorage+ private readonly hostVersion: string+ private readonly context: 'panel' | 'service'+ private readonly now: () => number++ private iframeWindow: PostableWindow | null = null+ private handshakeToken: string | null = null+ private verified = false+ private disposed = false++ private readonly callTimestamps: number[] = []+ private readonly subscriptions = new Set<'selection' | 'document'>()+ private readonly pendingAcks = new Map<string, PendingAck>()++ constructor(opts: BrokerOptions) {+ this.install = opts.install+ this.host = opts.host+ this.storage = opts.storage+ this.hostVersion = opts.hostVersion+ this.context = opts.context ?? 'panel'+ this.now = opts.now ?? (() => Date.now())+ }++ /** Bind to the mounted iframe. `onMessage` must be wired to `window`. */+ attach(iframeWindow: PostableWindow, handshakeToken: string, onMessage: (ev: MessageEvent) => void): void {+ this.iframeWindow = iframeWindow+ this.handshakeToken = handshakeToken+ if (typeof window !== 'undefined') window.addEventListener('message', onMessage)+ }++ /** True after the plugin echoed the handshake token. */+ get isVerified(): boolean {+ return this.verified+ }++ get subscribedTopics(): ReadonlySet<'selection' | 'document'> {+ return this.subscriptions+ }++ /** Tear down: no listener leaks, no dangling ack timers. */+ dispose(onMessage?: (ev: MessageEvent) => void): void {+ this.disposed = true+ if (onMessage && typeof window !== 'undefined') window.removeEventListener('message', onMessage)+ for (const pending of this.pendingAcks.values()) clearTimeout(pending.timer)+ this.pendingAcks.clear()+ this.subscriptions.clear()+ this.iframeWindow = null+ }++ // ── inbound ─────────────────────────────────────────────────++ /** Handle one window MessageEvent. Safe to call for any event. */+ handleMessage(ev: MessageEvent): void {+ if (this.disposed || !this.iframeWindow) return+ // ORIGIN DISCIPLINE: the source must be exactly the frame we+ // mounted. An opaque-origin iframe cannot be named by origin,+ // so identity of the window object is the whole check.+ if ((ev as { source?: unknown }).source !== this.iframeWindow) return++ const data = (ev as { data?: unknown }).data+ if (typeof data !== 'object' || data === null) return+ const dir = (data as { dir?: unknown }).dir++ if (dir === 'call') {+ this.handleCall(data)+ } else if (dir === 'result') {+ this.handleResult(data)+ }+ // unknown dir — silently ignored (noise from a broken plugin)+ }++ private handleCall(data: unknown): void {+ const parsed = parseRpcCall(data, { methods: METHOD_CATALOG })+ if (!parsed.ok) {+ this.send(parsed.code === 'E_METHOD' ? rpcErr(this.safeId(data), parsed.code, parsed.message) : rpcErr(this.safeId(data), parsed.code, parsed.message))+ return+ }+ const call = parsed.value++ // HANDSHAKE: the first call must echo the token from its URL fragment.+ if (!this.verified) {+ if (call.handshake !== this.handshakeToken) {+ this.send(+ rpcErr(call.id, 'E_PERMISSION', 'handshake failed — remount the panel (the URL fragment token was not echoed)'),+ )+ return+ }+ this.verified = true+ }++ // RATE LIMIT (soft, per-iframe sliding window)+ if (!this.takeBudget()) {+ this.send(rpcErr(call.id, 'E_THROTTLE', `rate limit exceeded (${RPC_RATE_CALLS} calls/min) — back off and retry`))+ return+ }++ // PERMISSION (default-deny; unknown methods already answered E_METHOD)+ if (!methodAllowed(call.method, this.install.permissions)) {+ const need = requiredPermission(call.method)+ this.send(rpcErr(call.id, 'E_PERMISSION', `${need ?? call.method} was not granted to this plugin (consent screen)`))+ return+ }++ void this.dispatch(call).then(+ (result) => this.send(rpcOk(call.id, result)),+ (error: unknown) => {+ if (error instanceof BrokerError) {+ // typed broker rejection — its code is RPC-wire-legal+ this.send(rpcErr(call.id, error.code, error.message))+ return+ }+ this.host.logError(`plugin ${this.install.pluginId} ${call.method}`, error)+ this.send(rpcErr(call.id, 'E_INTERNAL', 'host-side failure (details are in the server logs)'))+ },+ )+ }++ private handleResult(data: unknown): void {+ if (!this.verified) return // acks only count post-handshake+ const parsed = parseRpcResult(data)+ if (!parsed.ok) return // malformed acks are dropped, not fatal+ const pending = this.pendingAcks.get(parsed.value.id)+ if (pending && !pending.settled) {+ pending.settled = true+ clearTimeout(pending.timer)+ this.pendingAcks.delete(parsed.value.id)+ }+ }++ private async dispatch(call: RpcCall): Promise<unknown> {+ switch (call.method) {+ case 'info':+ return {+ api: { major: RPC_API_MAJOR, minor: RPC_API_MINOR },+ host: this.hostVersion,+ plugin: { id: this.install.pluginId, version: this.install.version },+ capabilities: { panel: true, renderer: this.context === 'service' },+ }+ case 'ping':+ return { pong: true, t: this.now() }++ case 'design.getSnapshot': {+ const state = this.host.getDesignState()+ const snapshot: PluginDesignSnapshot = pluginSnapshot({ pages: state.pages, currentPage: state.currentPage })+ const err = checkCloneSafe(snapshot, { maxBytes: MAX_RPC_BYTES })+ if (err) {+ throw new BrokerError('E_PAYLOAD', `design snapshot exceeds the ${Math.round(MAX_RPC_BYTES / 1024)} KB plugin cap — split or simplify the design`)+ }+ return snapshot+ }++ case 'subscribe': {+ const topic = (call.params as { topic?: unknown } | undefined)?.topic+ if (typeof topic !== 'string' || !SUBSCRIBE_TOPICS.has(topic)) {+ throw new BrokerError('E_PAYLOAD', `topic must be one of ${Array.from(SUBSCRIBE_TOPICS).join(', ')}`)+ }+ this.subscriptions.add(topic as 'selection' | 'document')+ return { subscribed: Array.from(this.subscriptions) }+ }++ case 'actions.apply': {+ const state = this.host.getDesignState()+ if (state.readOnly) {+ throw new BrokerError('E_PERMISSION', 'this design is read-only — design:write is suspended')+ }+ const action = (call.params as { action?: unknown } | undefined)?.action+ if (typeof action !== 'object' || action === null || Array.isArray(action)) {+ throw new BrokerError('E_PAYLOAD', 'params.action must be an object')+ }+ const type = (action as { type?: unknown }).type+ if (typeof type !== 'string' || !PANEL_ACTION_TYPES.has(type)) {+ throw new BrokerError(+ 'E_PAYLOAD',+ `unknown action type — allowed: ${Array.from(PANEL_ACTION_TYPES).join(', ')} (addPluginElement arrives with element support)`,+ )+ }+ const message = await this.host.applyAction(action as Record<string, unknown>)+ return { message }+ }++ case 'elements.registerRenderer':+ // P4 wires this for service iframes; a panel cannot render.+ if (this.context !== 'service') {+ throw new BrokerError('E_METHOD', 'renderer registration is only available to element service iframes (P4)')+ }+ throw new BrokerError('E_METHOD', 'service renderer wiring is not enabled in this build')++ case 'storage.get': {+ const key = (call.params as { key?: unknown } | undefined)?.key+ const res = this.storage.get(asKey(key))+ if (!res.ok) throw storageError(res)+ return { value: res.value }+ }+ case 'storage.set': {+ const p = (call.params ?? {}) as { key?: unknown; value?: unknown }+ const res = this.storage.set(asKey(p.key), p.value)+ if (!res.ok) throw storageError(res)+ return { ok: true }+ }+ case 'storage.remove': {+ const key = (call.params as { key?: unknown } | undefined)?.key+ const res = this.storage.remove(asKey(key))+ if (!res.ok) throw storageError(res)+ return { ok: true }+ }+ case 'storage.keys':+ return { keys: this.storage.keys() }++ case 'ui.notify': {+ const text = (call.params as { text?: unknown } | undefined)?.text+ if (typeof text !== 'string' || !text.trim()) {+ throw new BrokerError('E_PAYLOAD', 'params.text must be a non-empty string')+ }+ this.host.notify(text.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g, '').slice(0, NOTIFY_TEXT_MAX))+ return { ok: true }+ }+ case 'ui.closePanel':+ this.host.closePanel()+ return { ok: true }++ default:+ // unreachable: parseRpcCall already filtered the catalog+ throw new BrokerError('E_METHOD', `unknown method "${call.method}"`)+ }+ }++ // ── outbound (host → plugin pushes) ─────────────────────────++ /**+ * Push a subscription event into the iframe (fire-and-forget+ * with a bounded ack wait). Call this from store listeners.+ */+ pushEvent(topic: 'selection' | 'document', payload: unknown): void {+ if (this.disposed || !this.iframeWindow || !this.subscriptions.has(topic)) return+ const err = checkCloneSafe(payload, { maxBytes: MAX_RPC_BYTES })+ if (err) return // never let a push blow the cap — drop silently+ const id = newRpcId()+ const pending: PendingAck = { settled: false, timer: setTimeout(() => this.pendingAcks.delete(id), EVENT_ACK_TIMEOUT_MS) }+ this.pendingAcks.set(id, pending)+ this.send({ v: RPC_API_MAJOR, id, dir: 'call', method: 'event', params: { topic, payload } })+ }++ // ── helpers ─────────────────────────────────────────────────++ private send(envelope: unknown): void {+ if (!this.iframeWindow || this.disposed) return+ try {+ this.iframeWindow.postMessage(envelope, '*')+ } catch {+ // frame went away mid-call — nothing to deliver to+ }+ }++ /** Sliding-window budget: true when the call is allowed. */+ private takeBudget(): boolean {+ const t = this.now()+ const cutoff = t - RPC_RATE_WINDOW_MS+ while (this.callTimestamps.length && this.callTimestamps[0] <= cutoff) this.callTimestamps.shift()+ if (this.callTimestamps.length >= RPC_RATE_CALLS) return false+ this.callTimestamps.push(t)+ return true+ }++ /** Best-effort id for parse failures (so even garbage gets an answer). */+ private safeId(data: unknown): string {+ const id = (data as { id?: unknown } | null)?.id+ return typeof id === 'string' && /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,63}$/.test(id) ? id : 'rpc_unparsed'+ }+}++/** Typed broker-side rejection — its code rides the RPC error wire. */+export class BrokerError extends Error {+ constructor(readonly code: RpcErrorCode, message: string) {+ super(message)+ this.name = 'BrokerError'+ }+}++/**+ * Map a storage-layer error onto the RPC error code space. The+ * storage codes (E_KEY/E_VALUE/E_QUOTA/E_STORAGE) are NOT wire+ * codes — a plugin-side parseRpcResult would reject them — so+ * they fold into E_PAYLOAD with the explanatory message intact.+ */+function storageError(res: { ok: false; code: string; message: string }): BrokerError {+ return new BrokerError('E_PAYLOAD', `storage: ${res.message}`)+}++function asKey(key: unknown): string {+ return typeof key === 'string' ? key : ''+}++/** The plugin→host method catalog as a plain record for parseRpcCall. */+const METHOD_CATALOG: Record<string, unknown> = {+ info: null,+ ping: null,+ 'design.getSnapshot': null,+ subscribe: null,+ 'actions.apply': null,+ 'elements.registerRenderer': null,+ 'storage.get': null,+ 'storage.set': null,+ 'storage.remove': null,+ 'storage.keys': null,+ 'ui.notify': null,+ 'ui.closePanel': null,+}diff --git a/src/lib/plugins/plugin-storage.test.ts b/src/lib/plugins/plugin-storage.test.tsnew file mode 100644index 0000000..3657c6c--- /dev/null+++ b/src/lib/plugins/plugin-storage.test.ts@@ -0,0 +1,152 @@+import { describe, expect, it } from 'vitest'+import {+ PLUGIN_STORAGE_QUOTA_BYTES,+ PluginStorage,+ type StorageLike,+} from './plugin-storage'++// The storage tier (§4.8) is a security boundary, not a+// convenience: the prefix IS the isolation. A plugin must never+// see keys outside `canvix:plugin:<its own id>:*`, and the quota+// must hold even against a plugin that writes in a loop.++function memoryStorage(): StorageLike & { dump(): Map<string, string> } {+ const map = new Map<string, string>()+ return {+ getItem: (k) => (map.has(k) ? map.get(k)! : null),+ setItem: (k, v) => void map.set(k, v),+ removeItem: (k) => void map.delete(k),+ key: (i) => Array.from(map.keys())[i] ?? null,+ get length() {+ return map.size+ },+ dump: () => map,+ }+}++const BIG = 'x'.repeat(1024) // 1 KB string++describe('PluginStorage isolation', () => {+ it('scopes every key under the plugin prefix', () => {+ const store = memoryStorage()+ const a = new PluginStorage('com.canvix.wordcloud', store)+ a.set('palette', ['red', 'blue'])+ expect(a.get('palette')).toEqual({ ok: true, value: ['red', 'blue'] })+ for (const key of store.dump().keys()) {+ expect(key.startsWith('canvix:plugin:com.canvix.wordcloud:')).toBe(true)+ }+ })++ it('two plugins cannot read or enumerate each other', () => {+ const store = memoryStorage()+ const a = new PluginStorage('com.canvix.a', store)+ const b = new PluginStorage('com.canvix.b', store)+ a.set('secret', 'a-value')+ expect(b.get('secret')).toEqual({ ok: true, value: null })+ expect(b.keys()).toEqual([])+ expect(a.keys()).toEqual(['secret'])+ // and neither can reach host keys written outside the namespace+ store.setItem('canvix:brandkit:colors', 'host-data')+ expect(a.get('canvix:brandkit:colors' as never)).toMatchObject({ ok: false })+ expect(a.keys()).toEqual(['secret'])+ })++ it('keys() lists only this plugin, sorted, without the prefix', () => {+ const store = memoryStorage()+ const p = new PluginStorage('com.canvix.p', store)+ p.set('zeta', 1)+ p.set('alpha', 2)+ p.set('mid.key-3', 3)+ expect(p.keys()).toEqual(['alpha', 'mid.key-3', 'zeta'])+ })+})++describe('PluginStorage validation', () => {+ it('rejects malformed keys with E_KEY', () => {+ const p = new PluginStorage('com.canvix.p', memoryStorage())+ for (const bad of ['', ' lead', 'sp ace', 'a'.repeat(65), '../escape', 'a:b', 'a/b']) {+ expect(p.set(bad, 1)).toMatchObject({ ok: false, code: 'E_KEY' })+ expect(p.get(bad)).toMatchObject({ ok: false, code: 'E_KEY' })+ expect(p.remove(bad)).toMatchObject({ ok: false, code: 'E_KEY' })+ }+ })++ it('rejects values that cannot ride structured clone / JSON', () => {+ const p = new PluginStorage('com.canvix.p', memoryStorage())+ expect(p.set('fn', (() => 1) as unknown as number)).toMatchObject({ ok: false, code: 'E_VALUE' })+ expect(p.set('sym', Symbol('x') as unknown as number)).toMatchObject({ ok: false, code: 'E_VALUE' })+ expect(p.set('deep', { a: { b: { c: { d: { e: { f: { g: { h: { i: { j: { k: { l: { m: 1 } } } } } } } } } } } } })).toMatchObject({+ ok: false,+ code: 'E_VALUE',+ })+ })++ it('rejects invalid plugin ids at construction', () => {+ expect(() => new PluginStorage('NOT A VALID ID', memoryStorage())).toThrow()+ expect(() => new PluginStorage('', memoryStorage())).toThrow()+ })++ it('get on a corrupted entry surfaces E_STORAGE instead of throwing', () => {+ const store = memoryStorage()+ const p = new PluginStorage('com.canvix.p', store)+ store.setItem('canvix:plugin:com.canvix.p:bad', '{not json')+ expect(p.get('bad')).toMatchObject({ ok: false, code: 'E_STORAGE' })+ })++ it('missing keys read as null (KV semantics), remove is idempotent', () => {+ const p = new PluginStorage('com.canvix.p', memoryStorage())+ expect(p.get('nothing')).toEqual({ ok: true, value: null })+ expect(p.remove('nothing')).toEqual({ ok: true, value: undefined })+ })+})++describe('PluginStorage quota', () => {+ it('enforces the 256 KB per-plugin quota', () => {+ const p = new PluginStorage('com.canvix.p', memoryStorage())+ // write 1 KB entries until the quota refuses — must land near the cap+ let written = 0+ let firstRefusal = -1+ for (let i = 0; i < 1000; i++) {+ const res = p.set(`k${String(i).padStart(4, '0')}`, BIG)+ if (res.ok) written+++ else {+ firstRefusal = i+ break+ }+ }+ expect(firstRefusal).toBeGreaterThan(230) // ≈ 250 KB / 1.05 KB per entry+ expect(firstRefusal).toBeLessThan(260)+ expect(p.usageBytes()).toBeLessThanOrEqual(PLUGIN_STORAGE_QUOTA_BYTES)+ // …and stay refused until space is freed+ expect(p.set('overflow2', BIG)).toMatchObject({ ok: false, code: 'E_QUOTA' })+ expect(p.remove('k0000')).toEqual({ ok: true, value: undefined })+ expect(p.set('overflow', BIG)).toEqual({ ok: true, value: undefined })+ })++ it('a single value past the 64 KB per-value cap is rejected outright', () => {+ const p = new PluginStorage('com.canvix.p', memoryStorage())+ const huge = 'y'.repeat(PLUGIN_STORAGE_QUOTA_BYTES + 1)+ expect(p.set('huge', huge)).toMatchObject({ ok: false, code: 'E_VALUE' })+ })++ it('overwriting a key reuses its own bytes (no phantom usage)', () => {+ const p = new PluginStorage('com.canvix.p', memoryStorage())+ p.set('k', BIG)+ const before = p.usageBytes()+ for (let i = 0; i < 50; i++) {+ expect(p.set('k', BIG)).toEqual({ ok: true, value: undefined })+ }+ expect(p.usageBytes()).toBe(before)+ })++ it('usageBytes counts keys and values of this plugin only', () => {+ const store = memoryStorage()+ const a = new PluginStorage('com.canvix.a', store)+ const b = new PluginStorage('com.canvix.b', store)+ store.setItem('unrelated-host-key', 'x'.repeat(5000))+ a.set('one', 'x'.repeat(100))+ b.set('one', 'x'.repeat(100))+ expect(a.usageBytes()).toBe(b.usageBytes())+ expect(a.usageBytes()).toBeLessThan(300)+ })+})diff --git a/src/lib/plugins/plugin-storage.ts b/src/lib/plugins/plugin-storage.tsnew file mode 100644index 0000000..b9786a8--- /dev/null+++ b/src/lib/plugins/plugin-storage.ts@@ -0,0 +1,172 @@+// ─────────────────────────────────────────────────────────────+// Plugin storage — tier 2 of the storage model (research+// PLUGIN-SYSTEM.md §4.8): per-plugin settings in localStorage,+// namespaced `canvix:plugin:<pluginId>:*`, 256 KB per plugin.+//+// The BROKER owns this module — plugins never touch localStorage+// directly (they cannot: sandbox="allow-scripts" gives them an+// opaque origin and a null localStorage). Every key the broker+// reads or writes is forced inside the plugin's own prefix, so+// one plugin can neither read another plugin's keys nor any host+// key (brand kit precedent: same browser-local approach).+//+// Cross-device sync is deliberately NOT here — that is phase 3's+// optional PluginStorage table. MVP settings follow the browser.+// ─────────────────────────────────────────────────────────────++import { checkCloneSafe } from './data-caps'++/** Full key prefix — `canvix:plugin:<pluginId>:`. */+export const PLUGIN_STORAGE_PREFIX = 'canvix:plugin:'++/** Total bytes (key + value, UTF-8) one plugin may occupy (§4.7). */+export const PLUGIN_STORAGE_QUOTA_BYTES = 256 * 1024++/** A single value may not eat the whole quota — keep headroom. */+export const MAX_VALUE_BYTES = 64 * 1024++/** Storage key charset — no traversal, no spaces, no colons. */+const KEY_RE = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/++/** pluginId shape — reverse-DNS, already enforced by the manifest validator. */+const PLUGIN_ID_RE = /^[a-z0-9][a-z0-9.-]{1,99}$/++/** The localStorage surface the broker needs (injectable for tests). */+export interface StorageLike {+ getItem(key: string): string | null+ setItem(key: string, value: string): void+ removeItem(key: string): void+ key(index: number): string | null+ readonly length: number+}++export type StorageErrorCode = 'E_KEY' | 'E_VALUE' | 'E_QUOTA' | 'E_STORAGE'++export type StorageResult<T = undefined> =+ | { ok: true; value: T }+ | { ok: false; code: StorageErrorCode; message: string }++function utf8Bytes(s: string): number {+ return new TextEncoder().encode(s).length+}++/** In-memory fallback for non-browser contexts (never happens in the panel flow). */+function memoryStorage(): StorageLike {+ const map = new Map<string, string>()+ return {+ getItem: (k) => (map.has(k) ? map.get(k)! : null),+ setItem: (k, v) => void map.set(k, v),+ removeItem: (k) => void map.delete(k),+ key: (i) => Array.from(map.keys())[i] ?? null,+ get length() {+ return map.size+ },+ }+}++function defaultStorage(): StorageLike {+ try {+ return globalThis.localStorage ?? memoryStorage()+ } catch {+ return memoryStorage()+ }+}++export class PluginStorage {+ readonly prefix: string++ constructor(+ readonly pluginId: string,+ private readonly storage: StorageLike = defaultStorage(),+ ) {+ if (!PLUGIN_ID_RE.test(pluginId)) {+ // pluginId comes from an install row the server validated —+ // this guard is belt-and-braces against a corrupted row.+ throw new Error('PluginStorage: invalid pluginId')+ }+ this.prefix = `${PLUGIN_STORAGE_PREFIX}${pluginId}:`+ }++ /** Read one key. Missing keys resolve to `null` (KV semantics, not an error). */+ get(key: string): StorageResult<unknown> {+ const keyErr = this.checkKey(key)+ if (keyErr) return keyErr+ const raw = this.storage.getItem(this.prefix + key)+ if (raw === null) return { ok: true, value: null }+ try {+ return { ok: true, value: JSON.parse(raw) as unknown }+ } catch {+ // corrupted entry — surface it rather than crash the panel+ return { ok: false, code: 'E_STORAGE', message: 'stored value is not valid JSON (was localStorage edited?)' }+ }+ }++ /** Write one JSON value inside the quota. */+ set(key: string, value: unknown): StorageResult {+ const keyErr = this.checkKey(key)+ if (keyErr) return keyErr+ // structured-clone-safe first: functions/DOM nodes/BigInt never+ // survive postMessage round-trips either, so reject them here.+ const cloneErr = checkCloneSafe(value, { maxBytes: MAX_VALUE_BYTES })+ if (cloneErr) return { ok: false, code: 'E_VALUE', message: cloneErr }+ const encoded = JSON.stringify(value) ?? 'null'+ const entryBytes = utf8Bytes(this.prefix + key) + utf8Bytes(encoded)+ if (entryBytes > PLUGIN_STORAGE_QUOTA_BYTES) {+ return { ok: false, code: 'E_QUOTA', message: `value is larger than the ${Math.round(PLUGIN_STORAGE_QUOTA_BYTES / 1024)} KB storage quota` }+ }+ // account current usage WITHOUT this key (a set may overwrite)+ let usage = this.usageBytes()+ const existing = this.storage.getItem(this.prefix + key)+ if (existing !== null) {+ usage -= utf8Bytes(this.prefix + key) + utf8Bytes(existing)+ }+ if (usage + entryBytes > PLUGIN_STORAGE_QUOTA_BYTES) {+ return {+ ok: false,+ code: 'E_QUOTA',+ message: `storage quota exceeded (${Math.round(PLUGIN_STORAGE_QUOTA_BYTES / 1024)} KB) — remove unused keys first`,+ }+ }+ try {+ this.storage.setItem(this.prefix + key, encoded)+ } catch {+ return { ok: false, code: 'E_STORAGE', message: 'localStorage is unavailable (private mode?)' }+ }+ return { ok: true, value: undefined }+ }++ /** Remove one key. Removing a missing key is a no-op. */+ remove(key: string): StorageResult {+ const keyErr = this.checkKey(key)+ if (keyErr) return keyErr+ this.storage.removeItem(this.prefix + key)+ return { ok: true, value: undefined }+ }++ /** This plugin's keys, relative (no prefix). */+ keys(): string[] {+ const out: string[] = []+ for (let i = 0; i < this.storage.length; i++) {+ const full = this.storage.key(i)+ if (full !== null && full.startsWith(this.prefix)) out.push(full.slice(this.prefix.length))+ }+ return out.sort()+ }++ /** Current UTF-8 usage of this plugin's namespace (keys + values). */+ usageBytes(): number {+ let total = 0+ for (const key of this.keys()) {+ const raw = this.storage.getItem(this.prefix + key)+ total += utf8Bytes(this.prefix + key) + (raw === null ? 0 : utf8Bytes(raw))+ }+ return total+ }++ private checkKey(key: string): { ok: false; code: StorageErrorCode; message: string } | null {+ if (typeof key !== 'string' || !KEY_RE.test(key)) {+ return { ok: false, code: 'E_KEY', message: 'storage keys are 1–64 chars of [A-Za-z0-9_.-]' }+ }+ return null+ }+}diff --git a/src/lib/plugins/snapshot.test.ts b/src/lib/plugins/snapshot.test.tsnew file mode 100644index 0000000..0bd8405--- /dev/null+++ b/src/lib/plugins/snapshot.test.ts@@ -0,0 +1,131 @@+import { describe, expect, it } from 'vitest'+import { pluginSnapshot, SNAPSHOT_FIELD_CHAR_CAP } from './snapshot'+import type { AnyElement, PageData } from '@/lib/types'++// The snapshot is what a consented plugin sees of the design+// (§4.3): geometry + own small data, never bytes, never internal+// bookkeeping. The tests pin that contract.++function page(elements: AnyElement[], background: unknown = { type: 'solid', color: '#FFFFFF' }): PageData {+ return { id: 'page_1', background, elements } as PageData+}++function textElement(overrides: Partial<Extract<AnyElement, { type: 'text' }>> = {}): AnyElement {+ return {+ id: 'el_1',+ type: 'text',+ x: 10,+ y: 20,+ width: 300,+ height: 80,+ rotation: 0,+ opacity: 1,+ locked: false,+ visible: true,+ shadow: { enabled: false, x: 0, y: 0, blur: 0, color: '#000000' },+ text: 'Hello design',+ fontSize: 48,+ fontFamily: 'Inter',+ bold: true,+ italic: false,+ underline: false,+ strike: false,+ uppercase: false,+ fill: '#123456',+ align: 'center',+ lineHeight: 1.2,+ letterSpacing: 0,+ ...overrides,+ } as AnyElement+}++describe('pluginSnapshot', () => {+ it('projects geometry and type verbatim', () => {+ const snap = pluginSnapshot({ pages: [page([textElement()])], currentPage: 0 })+ const el = snap.pages[0]!.elements[0]!+ expect(el.id).toBe('el_1')+ expect(el.type).toBe('text')+ expect(el.x).toBe(10)+ expect(el.y).toBe(20)+ expect(el.width).toBe(300)+ expect(el.height).toBe(80)+ })++ it('keeps small own data (text, fill, fontSize) and the background', () => {+ const snap = pluginSnapshot({ pages: [page([textElement()], { type: 'gradient', from: '#000000', to: '#FFFFFF', angle: 90 })], currentPage: 0 })+ expect(snap.pages[0]!.background).toEqual({ type: 'gradient', from: '#000000', to: '#FFFFFF', angle: 90 })+ const el = snap.pages[0]!.elements[0]!+ expect(el.text).toBe('Hello design')+ expect(el.fill).toBe('#123456')+ expect(el.fontSize).toBe(48)+ })++ it('drops internal bookkeeping fields (_m, magicLayer, shadow, animation, beatPulse)', () => {+ const el = textElement({ _m: 'w:5:actor', beatPulse: 0.5 } as never)+ const snap = pluginSnapshot({ pages: [page([el])], currentPage: 0 })+ const view = snap.pages[0]!.elements[0]!+ expect('_m' in view).toBe(false)+ expect('beatPulse' in view).toBe(false)+ expect('shadow' in view).toBe(false)+ expect('animation' in view).toBe(false)+ expect('magicLayer' in view).toBe(false)+ })++ it('omits heavy fields (image dataURLs) and lists them in `omitted`', () => {+ const el = {+ ...textElement(),+ type: 'image',+ src: `data:image/png;base64,${'z'.repeat(50_000)}`,+ } as AnyElement+ const snap = pluginSnapshot({ pages: [page([el])], currentPage: 0 })+ const view = snap.pages[0]!.elements[0]!+ expect(view.src).toBeUndefined()+ expect(view.omitted).toContain('src')+ })++ it('keeps short src refs (e.g. /api/media ids)', () => {+ const el = { ...textElement(), type: 'image', src: '/api/media/abc123' } as AnyElement+ const snap = pluginSnapshot({ pages: [page([el])], currentPage: 0 })+ expect(snap.pages[0]!.elements[0]!.src).toBe('/api/media/abc123')+ })++ it('omits any oversized string field, not just known-heavy ones', () => {+ const el = textElement({ text: 't'.repeat(SNAPSHOT_FIELD_CHAR_CAP + 1) })+ const snap = pluginSnapshot({ pages: [page([el])], currentPage: 0 })+ const view = snap.pages[0]!.elements[0]!+ expect(view.text).toBeUndefined()+ expect(view.omitted).toContain('text')+ })++ it('projects group children recursively', () => {+ const child = textElement({ id: 'child_1' } as never)+ const group = {+ ...textElement(),+ id: 'group_1',+ type: 'group',+ children: [child],+ } as unknown as AnyElement+ const snap = pluginSnapshot({ pages: [page([group])], currentPage: 0 })+ const view = snap.pages[0]!.elements[0]!+ expect(Array.isArray(view.children)).toBe(true)+ expect((view.children as { id: string }[])[0]!.id).toBe('child_1')+ })++ it('keeps small nested plain objects (gradients) but drops exotic ones', () => {+ const el = textElement({ fillGradient: { from: '#000000', to: '#FFFFFF', angle: 45 } } as never)+ const snap = pluginSnapshot({ pages: [page([el])], currentPage: 0 })+ expect(snap.pages[0]!.elements[0]!.fillGradient).toEqual({ from: '#000000', to: '#FFFFFF', angle: 45 })++ const el2 = textElement({ fillGradient: { from: '#000000', nested: { deep: { x: 1 } } } } as never)+ const snap2 = pluginSnapshot({ pages: [page([el2])], currentPage: 0 })+ expect(snap2.pages[0]!.elements[0]!.fillGradient).toBeUndefined()+ })++ it('carries multi-page structure and currentPage', () => {+ const pages = [page([textElement()]), page([textElement({ id: 'el_2' } as never)])]+ const snap = pluginSnapshot({ pages, currentPage: 1 })+ expect(snap.pages).toHaveLength(2)+ expect(snap.currentPage).toBe(1)+ expect(snap.pages[1]!.elements[0]!.id).toBe('el_2')+ })+})diff --git a/src/lib/plugins/snapshot.ts b/src/lib/plugins/snapshot.tsnew file mode 100644index 0000000..6989ba9--- /dev/null+++ b/src/lib/plugins/snapshot.ts@@ -0,0 +1,151 @@+// ─────────────────────────────────────────────────────────────+// Design snapshot projection — what `design.getSnapshot()` hands+// a plugin (research PLUGIN-SYSTEM.md §4.3): "current design:+// pages, elements (ids/types/geometry/own data), background —+// capped, read-only view".+//+// The projection is deliberately LOSSY, and that is the feature:+// · heavy fields (image dataURLs) are omitted, not truncated —+// a generator plugin needs geometry + text, never bytes+// · internal bookkeeping (`_m` HLC stamps, `magicLayer`+// provenance) never crosses the boundary+// · the result is checked against the RPC payload cap so an+// enormous design fails loudly (E_PAYLOAD) instead of+// silently stalling the iframe+// ─────────────────────────────────────────────────────────────++import type { AnyElement, PageData } from '@/lib/types'++/** Strings longer than this are dropped (image dataURLs etc.). */+export const SNAPSHOT_FIELD_CHAR_CAP = 1024++/** Fields every element view carries. */+export interface PluginElementView {+ id: string+ type: string+ x: number+ y: number+ width: number+ height: number+ rotation: number+ opacity: number+ visible: boolean+ name?: string+ /** element types with children (groups) keep the tree */+ children?: PluginElementView[]+ /** names of omitted oversized fields, e.g. ["src"] */+ omitted?: string[]+ /** type-specific own data survives verbatim when small */+ [key: string]: unknown+}++export interface PluginPageView {+ id: string+ background: unknown+ elements: PluginElementView[]+}++export interface PluginDesignSnapshot {+ pages: PluginPageView[]+ currentPage: number+}++/** Fields that are host-internal — never exposed to plugins. */+const INTERNAL_FIELDS = new Set(['_m', 'magicLayer', 'shadow', 'animation', 'beatPulse'])++/** Fields whose values are commonly megabyte dataURLs. */+const HEAVY_FIELDS = new Set(['src', 'poster', 'audio', 'thumb'])++function isPlainSmall(value: unknown): boolean {+ return (+ typeof value === 'string' ||+ typeof value === 'number' ||+ typeof value === 'boolean' ||+ value === null ||+ value === undefined+ )+}++function projectElement(el: AnyElement): PluginElementView {+ const view: PluginElementView = {+ id: el.id,+ type: el.type,+ x: el.x,+ y: el.y,+ width: el.width,+ height: el.height,+ rotation: el.rotation,+ opacity: el.opacity,+ visible: el.visible,+ }+ if (el.name !== undefined) view.name = el.name++ const omitted: string[] = []+ for (const [key, value] of Object.entries(el)) {+ if (INTERNAL_FIELDS.has(key)) continue+ if (key === 'id' || key === 'type' || key === 'x' || key === 'y' || key === 'width' || key === 'height') continue+ if (key === 'rotation' || key === 'opacity' || key === 'visible' || key === 'name') continue++ if (key === 'children') {+ // groups keep a projected tree+ if (Array.isArray(value)) {+ view.children = value.map((c) => projectElement(c as AnyElement))+ }+ continue+ }+ if (HEAVY_FIELDS.has(key)) {+ // short refs (e.g. "/api/media/abc") survive; dataURLs never do+ if (typeof value === 'string' && value.length <= SNAPSHOT_FIELD_CHAR_CAP) {+ view[key] = value+ } else {+ omitted.push(key)+ }+ continue+ }+ if (isPlainSmall(value)) {+ if (typeof value === 'string' && value.length > SNAPSHOT_FIELD_CHAR_CAP) {+ omitted.push(key)+ continue+ }+ if (value !== undefined) view[key] = value+ continue+ }+ // nested plain objects (fillGradient, effect…) — shallow-keep+ // only small scalar leaves; drop anything exotic+ if (value !== null && typeof value === 'object' && !Array.isArray(value)) {+ const nested: Record<string, unknown> = {}+ let small = true+ for (const [nk, nv] of Object.entries(value as Record<string, unknown>)) {+ if (!isPlainSmall(nv)) {+ small = false+ break+ }+ if (typeof nv === 'string' && nv.length > SNAPSHOT_FIELD_CHAR_CAP) {+ small = false+ break+ }+ nested[nk] = nv+ }+ if (small) view[key] = nested+ else omitted.push(key)+ }+ }+ if (omitted.length) view.omitted = omitted+ return view+}++/**+ * Build the read-only plugin view of a design.+ * `state` is the editor-store slice (or any compatible shape).+ */+export function pluginSnapshot(state: {+ pages: PageData[]+ currentPage: number+}): PluginDesignSnapshot {+ const pages: PluginPageView[] = state.pages.map((p) => ({+ id: p.id,+ background: p.background,+ elements: (p.elements ?? []).map(projectElement),+ }))+ return { pages, currentPage: state.currentPage }+}diff --git a/tests/e2e/plugins-panel.spec.ts b/tests/e2e/plugins-panel.spec.tsnew file mode 100644index 0000000..78881b0--- /dev/null+++ b/tests/e2e/plugins-panel.spec.ts@@ -0,0 +1,56 @@+import { expect, test } from '@playwright/test'++/**+ * v0.13 P3 regression check — the Apps panel now mounts the+ * lazy "Installed" plugin section (InstalledApps → dynamic+ * import → GET /api/plugins → flag off on this instance ⇒ 503+ * ⇒ section stays hidden, zero runtime bytes).+ *+ * What must NOT regress with the flag off:+ * 1. the built-in app grid renders exactly as before+ * 2. no console errors from the dynamic import path+ * 3. opening a built-in app still works (Charts)+ * 4. /api/plugins answers 503 PLUGINS_DISABLED+ */+test.describe('Apps panel with plugin runtime mounted (flag off)', () => {+ test('built-in app grid renders and opens an app; no plugin UI leaks', async ({ page }) => {+ const errors: string[] = []+ page.on('pageerror', (err) => errors.push(String(err)))++ await page.goto('/')+ await page.getByRole('button', { name: /start designing/i }).first().click()+ await expect(page.getByLabel('Create a design')).toBeVisible()++ // first blank-preset card in the "Start a new design" grid+ await page+ .locator('section:has(h2:text("Start a new design")) [aria-label^="Create "]')+ .first()+ .click()+ await expect(page.getByLabel('Design canvas')).toBeVisible({ timeout: 30_000 })++ // open the Apps panel+ await expect(page.getByRole('button', { name: 'Apps' })).toBeVisible({ timeout: 20_000 })+ await page.getByRole('button', { name: 'Apps' }).click()++ // built-in cards unchanged+ await expect(page.getByText('Charts', { exact: true })).toBeVisible()+ await expect(page.getByText('QR generator')).toBeVisible()++ // flag off ⇒ the install input must NOT appear+ await expect(page.getByPlaceholder('https://example.com/plugin/manifest.json')).toHaveCount(0)+ await expect(page.getByText('Installed', { exact: true })).toHaveCount(0)++ // opening a built-in app still routes to its panel+ await page.getByRole('button', { name: 'Open Charts app' }).click()+ await expect(page.getByText('Back to apps')).toBeVisible()++ expect(errors, `page errors: ${errors.join(' | ')}`).toEqual([])+ })++ test('GET /api/plugins answers 503 PLUGINS_DISABLED with the flag off', async ({ request }) => {+ const res = await request.get('/api/plugins')+ expect(res.status()).toBe(503)+ const body = (await res.json()) as { code?: string }+ expect(body.code).toBe('PLUGINS_DISABLED')+ })+})