Skip to content

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.

feat(v0.13): Word Cloud reference plugin + author docs — first-party rail, five integration fixes (P5) (#22)

Ashiq Hussain Mirbda46a877139
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index d523422..decc402 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -120,6 +120,13 @@ jobs:
- name: Run Playwright e2e suite
run: npx playwright test
+ # v0.13.4 (P5): the plugin-system acceptance suite — same dev
+ # server, CANVIX_PLUGINS=1, port 3100, tests/e2e-plugins only.
+ # The default suite above keeps the flag OFF (its specs assert
+ # 503s and hidden UI); this one proves the flag-on world.
+ - name: Run Playwright plugins suite (CANVIX_PLUGINS=1)
+ run: npx playwright test -c playwright.plugins.config.ts
+
- name: Upload Playwright traces (on failure)
if: failure()
uses: actions/upload-artifact@v4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fcd0356..4347702 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,94 @@
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.4] — 2026-11-03
+
+### Added
+
+- **Plugin system, part 5 of 5 — the first-party validation plugin
+ (P5): `com.canvix.wordcloud`.** The plugin whose end-to-end use *is*
+ the v0.13 MVP acceptance test (research §5): install → consent →
+ generate → render → export → restyle → disable → uninstall, all on
+ the public API, zero per-plugin host code. **This closes the v0.13
+ plugin-system MVP.**
+ - **The bundle** (`public/plugins/wordcloud/`): manifest v1.1 with
+ one `cloud` element kind (seed/density/mask/palette schema for the
+ host-rendered properties card), panel + service entries, and
+ exactly four permissions — `design:read`, `design:write`,
+ `element:plugin`, `storage`. **No network**, proving the
+ default-deny path. `wordcloud.js` is one shared zero-dependency
+ UMD script for both frames: the plugin half of the v1 RPC envelope
+ (handshake echo, call/result correlation, host→plugin call
+ answering) plus a mulberry32-seeded spiral layout whose SVG passes
+ the P1 sanitizer by construction (asserted in the unit suite on
+ hostile inputs). Widths are estimated from character classes, so
+ output is machine-independent and determinism — the render-cache
+ contract — holds exactly. The panel pulls page text via
+ `design.getSnapshot`, previews with the same code the service
+ renders with, remembers settings via namespaced storage, and
+ generates through `addPluginElement` / `updatePluginElementData`.
+ - **First-party distribution** (`firstparty.ts` +
+ `firstparty-fetch.ts`): bundled plugins ship in
+ `public/plugins/<slug>/` and install through the SAME rail
+ (validate → sha256-pin → consent → per-user rows) from the strict
+ relative form `/plugins/<slug>/manifest.json`. The server reads
+ the files from disk behind a synthetic origin — no network hop,
+ so the SSRF guard's correct loopback denial never applies, and
+ `allowFirstParty` is true on that branch ONLY: `com.canvix.*`
+ remains reserved to what the instance itself serves. The Apps
+ grid gains a one-click "+ Word Cloud (bundled)" chip. On
+ runtimes without a filesystem (Cloudflare Workers) a bundled
+ install answers an honest error; every other plugin route is
+ unaffected (lazy import).
+ - **The acceptance e2e** (`tests/e2e-plugins/wordcloud.spec.ts`,
+ 5 specs, run flag-on via the new `playwright.plugins.config.ts`,
+ port 3100): UI install with all four consent lines asserted
+ verbatim; mid-session install → panel handshake → page-text
+ collection → generate → the service frame's render observed →
+ element persisted (API truth); exported SVG embeds the real
+ cloud; restyle through the host schema card; disable → the
+ export degrades to the honest placeholder; signed-out viewer
+ inert; uninstall leaves design data byte-identical. CI's e2e job
+ runs the flag-on suite after the default one.
+ - **Plugin author docs** (`docs/PLUGINS.md`, ~350 lines): the trust
+ model, a hello-world quickstart, the manifest spec, the
+ permissions table with consent lines, the full RPC reference
+ (both directions, error codes, caps), the element/renderer
+ contract, packaging rules, hosting guide (incl. the bundled-plugin
+ path for forks), the Word Cloud walkthrough, and the FAQ
+ ("no marketplace, ever").
+
+### Fixed
+
+- **Four integration gaps the validation plugin exposed** — all
+ shipped silently in P3/P4 because every earlier e2e ran flag-off,
+ so no service frame or panel-driven element had ever really
+ mounted:
+ 1. `manifest.ts` spoke a stale plugin API version — its private
+ `PLUGIN_API_MINOR = 0` copy was never bumped with the P4
+ renderer minor, so the install rail rejected every real
+ `"canvixPluginApi": "1.1"` manifest. The constants now alias
+ the RPC envelope's single source of truth.
+ 2. Service frames pointed at `/api/plugins/undefined/serve/…` —
+ the install route's projection names the key `id`, the service
+ layer read `installId`; every service iframe 404'd and every
+ plugin element rendered as a "not responding" placeholder. The
+ projection now carries both names.
+ 3. Panels could not generate elements — the panel host dropped the
+ broker's `caller` identity (`addPluginElement` always refused)
+ and its record carried no `elementKinds` (the declared kind was
+ refused too). Both now ride the panel record, mirroring the
+ service frame.
+ 4. Mid-session installs never mounted a service frame — the
+ service layer fetched the install list once on editor mount.
+ InstalledApps now dispatches `canvix:plugins-changed` after
+ install/uninstall/enable/disable and the layer re-fetches.
+
+### Changed
+
+- Version 0.13.4; README plugin-system roadmap item updated with the
+ P5 paragraph; zero new npm dependencies.
+
## [0.13.3] — 2026-11-03
### Added
diff --git a/README.md b/README.md
index 9568f74..03fb35d 100644
--- a/README.md
+++ b/README.md
@@ -892,12 +892,12 @@ tool descriptions so agents pick the right format.
(`CANVIX_ERROR_WEBHOOK_URL`, POSTed from Next's `onRequestError`
hook for every unhandled error) — all off by default for
self-hoster privacy *(v0.12.5)*
-- [ ] Plugin system (external, installable apps) — sandboxed-iframe MVP
+- [x] Plugin system (external, installable apps) — sandboxed-iframe MVP
per `research/PLUGIN-SYSTEM.md`: manifest + permission model, iframe
- sandbox with postMessage bridge, an “Apps” panel store, and 2–3
- reference plugins (stock icons, charts, QR codes) to prove the
- surface — then a community plugin registry.
- In progress: the **security-boundary core** (P1) landed in
+ sandbox with postMessage bridge, an “Apps” panel store, and a
+ reference plugin to prove the surface. **No community registry —
+ by design** (see `docs/PLUGINS.md`'s FAQ).
+ Shipped across five slices: 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
@@ -930,7 +930,17 @@ tool descriptions so agents pick the right format.
`addPluginElement`/`updatePluginElementData` actions whose
caller identity comes from the install row — verified
end-to-end that uninstall/crash/flag-off never loses document
- data *(v0.13.3)*
+ data *(v0.13.3)*; and the **reference plugin** (P5) closed the
+ MVP — `com.canvix.wordcloud`, bundled in
+ `public/plugins/wordcloud/` and installable one-click from the
+ Apps grid: a seeded, fully deterministic word-cloud generator
+ (panel + service renderer, zero network permissions) whose
+ install → consent → generate → render → export → restyle →
+ disable → uninstall journey is the acceptance e2e
+ (`tests/e2e-plugins/`, flag-on). Author docs live in
+ [`docs/PLUGINS.md`](docs/PLUGINS.md) — quickstart, manifest
+ spec, RPC reference, renderer contract, hosting guide
+ *(v0.13.4)*
- [ ] Mobile editor polish — touch-first selection handles, gesture
zoom/pan without modifier keys, bottom-sheet property panels
(the responsive groundwork from v0.11.3 makes this tractable)
diff --git a/docs/PLUGINS.md b/docs/PLUGINS.md
new file mode 100644
index 0000000..51459e1
--- /dev/null
+++ b/docs/PLUGINS.md
@@ -0,0 +1,437 @@
+# Canvix plugins — author guide
+
+Canvix plugins are **plain static files** that run inside a sandbox and talk to
+the editor over a versioned postMessage RPC. No build step, no SDK npm
+package, no marketplace — you host the files anywhere that serves bytes over
+https, and a Canvix user installs them by URL.
+
+> **There is no plugin marketplace, and there will never be one.** A
+> marketplace makes the host the curator of what runs on your instance; in
+> Canvix the person who installs the plugin is the trust decision, and the
+> consent screen shows exactly what is being granted before anything runs.
+> See [the FAQ](#faq).
+
+This document is the complete author reference: [quickstart](#quickstart—hello-world-in-10-minutes),
+[the manifest](#the-manifest), [permissions](#permissions), [the RPC
+API](#the-rpc-api), [element renderers](#element-types--the-renderer-contract),
+[packaging rules](#packaging-rules), [hosting](#hosting-your-plugin), and the
+[Word Cloud walkthrough](#walkthrough--the-word-cloud-reference-plugin).
+The normative source for every rule cited here is `research/PLUGIN-SYSTEM.md`
+in this repository, and the enforcement code lives in `src/lib/plugins/`.
+
+---
+
+## The trust model in one paragraph
+
+A plugin is untrusted code. It runs in an `<iframe sandbox="allow-scripts">`
+— an opaque origin with no access to the host's cookies, DOM, or storage —
+and every message it exchanges with the host passes a broker that enforces,
+in order: **frame identity** (only the iframe we mounted is heard), a
+**one-time handshake token** (rides the iframe URL fragment, never the
+network), a **rate budget** (200 calls/minute), a **default-deny permission
+check** (every method maps to a consented permission), and **payload caps**
+(the same clone-safe caps collaboration ops obey). Files are fetched once at
+install, validated, and sha256-pinned into the database; after install the
+instance never contacts your server again. Install is per-user, and removing
+the plugin never touches the designs that used it.
+
+## Quickstart — hello world in 10 minutes
+
+A plugin is a directory with a `manifest.json` and whatever files the
+manifest lists. Three files total for a hello-world panel:
+
+```
+hello/
+ manifest.json
+ panel.html
+ panel.js
+```
+
+**manifest.json**
+
+```json
+{
+ "canvixPluginApi": "1.1",
+ "id": "net.yourname.hello",
+ "name": "Hello",
+ "description": "Adds a greeting text box",
+ "version": "1.0.0",
+ "author": { "name": "Your Name" },
+ "engines": { "canvix": ">=0.13.4 <0.14.0" },
+ "entry": { "panel": "panel.html" },
+ "permissions": ["design:write"],
+ "files": ["manifest.json", "panel.html", "panel.js"],
+ "elements": []
+}
+```
+
+**panel.html**
+
+```html
+<!DOCTYPE html>
+<html lang="en">
+<head><meta charset="utf-8"><title>Hello</title>
+<style>
+ body { font: 13px system-ui, sans-serif; color: #E7E8EE; background: #0F0F13; padding: 12px; }
+ button { font: inherit; border: 0; border-radius: 8px; padding: 8px 12px; background: #7630D7; color: #fff; cursor: pointer; }
+</style>
+</head>
+<body>
+ <button id="go" type="button">Say hello on the canvas</button>
+ <script src="panel.js"></script>
+</body>
+</html>
+```
+
+**panel.js** — the whole RPC client is ~30 lines; copy it from the
+[Word Cloud plugin](../../public/plugins/wordcloud/wordcloud.js)
+(`createRpc` / `handshakeFromLocation`) or inline this minimal version:
+
+```js
+;(function () {
+ 'use strict'
+ var seq = 0, verified = false
+ function call(method, params) {
+ return new Promise(function (resolve, reject) {
+ seq += 1
+ var id = 'p_' + seq + '_' + Math.random().toString(36).slice(2, 10)
+ var env = { v: 1, id: id, dir: 'call', method: method }
+ if (params !== undefined) env.params = params
+ if (!verified) { verified = true; env.handshake = decodeURIComponent(location.hash.slice(1)) }
+ var timer = setTimeout(function () { reject(new Error(method + ' timed out')) }, 15000)
+ window.addEventListener('message', function onMsg(ev) {
+ if (ev.source !== parent || !ev.data || ev.data.id !== id) return
+ window.removeEventListener('message', onMsg)
+ clearTimeout(timer)
+ ev.data.ok ? resolve(ev.data.result) : reject(new Error(ev.data.error.message))
+ })
+ parent.postMessage(env, '*')
+ })
+ }
+
+ document.getElementById('go').addEventListener('click', function () {
+ call('actions.apply', {
+ action: { type: 'addText', text: 'Hello from a plugin! 👋', fontSize: 48 }
+ }).catch(function (e) { console.error(e.message) })
+ })
+})()
+```
+
+Serve the `hello/` directory over https (or `http://127.0.0.1` for local
+testing), then in Canvix: open a design → **Apps** → paste the manifest URL →
+**Install** → review the consent screen → **Keep installed**. Click **Hello**
+in the Installed list, press the button, and the text lands on the canvas —
+undoable, collaborative, saved like any element.
+
+> The instance you install on must have `CANVIX_PLUGINS=1` set — self-hosters
+> opt into third-party code explicitly. On your own machine:
+> `CANVIX_PLUGINS=1 npm run dev`.
+
+---
+
+## The manifest
+
+`manifest.json` is the first gate of the trust chain: everything the consent
+screen shows and the broker enforces originates here. The validator
+(`src/lib/plugins/manifest.ts`) **collects every error** so authors fix
+everything in one round-trip, and rejects anything not explicitly allowed.
+
+| Field | Rules |
+|---|---|
+| `canvixPluginApi` | `"1"` or `"major.minor"` like `"1.1"`. The host speaks one major and every minor below its own. `1.1` = the renderer contract (service entries, `elements.render`). A mismatch blocks install with a plain-language message. |
+| `id` | `^[a-z0-9][a-z0-9-]{1,62}(\.[a-z0-9-]+){0,3}$`, 2–80 chars. `com.canvix.*` is reserved — only bundles shipped in Canvix's own `public/plugins/` may carry it (see [bundled plugins](#bundled-plugins)). |
+| `name` | 1–80 chars. Shown in the Apps panel and consent screen. |
+| `description` | Optional, ≤ 280 chars. |
+| `version` | Strict semver `"1.0.0"` — recorded on every element the plugin creates (`pluginVersion`) so a later version can migrate its own data. |
+| `author` | `{ name: 1–80 chars, url?: https-only }`. |
+| `engines.canvix` | A semver **range** over the host app, e.g. `">=0.13.4 <0.14.0"`. Supported: exact, comparators, `^`, `~`, hyphen ranges, partial versions, `\|\|`. Prerelease tags and loose forms are deliberately rejected (fail-closed). |
+| `entry` | `{ panel?: "panel.html", service?: "service.html" }` — safe relative `.html` paths. You need `panel` and/or `elements`; a plugin with `elements` **must** declare `service` (its renderers' host). |
+| `permissions` | Array — see [permissions](#permissions). Unknown entries block install. |
+| `files` | Every file the bundle ships (≤ 50, ≤ 2 MB total) — the install route fetches **exactly** this list. Relative paths, safe extensions only (html/js/mjs/css/png/jpg/jpeg/gif/svg/json/txt/woff2/map/ico), no traversal. Must include both entry files. |
+| `elements` | ≤ 20 element types — see [renderers](#element-types--the-renderer-contract). |
+
+Unknown top-level keys are ignored on purpose — a future-minor manifest keeps
+its v1 contract on this host.
+
+## Permissions
+
+Five static permissions plus repeatable `network:<origin>` grants. Declared
+in the manifest, shown **verbatim on the consent screen**, enforced per-call
+by the broker (default-deny):
+
+| Permission | Plain-language consent line | Gates |
+|---|---|---|
+| `design:read` | "Read the design you have open — pages, elements and their properties" | `design.getSnapshot`, `subscribe` |
+| `design:write` | "Add, edit and delete elements in this design (via Canvix's undoable actions)" | `actions.apply` — suspended in read-only designs |
+| `element:plugin` | "Add its own element types to the canvas and draw them" | `addPluginElement` / `updatePluginElementData` / `elements.registerRenderer` |
+| `storage` | "Remember its settings in this browser (namespaced, 256 KB cap)" | `storage.*` |
+| `ui:notify` | "Show toast notifications and close its own panel" | `ui.notify`, `ui.closePanel` |
+| `network:https://api.example.com` | "Send and receive data with https://api.example.com — the only server it may contact" | The iframe's CSP `connect-src` — nothing else is fetchable |
+
+Rules worth knowing: at most 8 static permissions and 5 network origins;
+origins are absolute **https** only (loopback http allowed for development);
+no wildcards, credentials, or fragments; a permission added in a new version
+requires fresh consent (the upgrade rule — an install is for exactly what
+was shown, never more).
+
+**Ask for nothing you don't need.** The reference Word Cloud plugin ships
+with zero network permissions on purpose — the default-deny path is the
+well-lit one.
+
+## The RPC API
+
+One JSON envelope, both directions:
+
+```jsonc
+// plugin → host (and host → plugin) call
+{ "v": 1, "id": "p_1_x8f2", "dir": "call", "method": "actions.apply", "params": { },
+ "handshake": "…first call only…" }
+
+// the answer, same id
+{ "v": 1, "id": "p_1_x8f2", "dir": "result", "ok": true, "result": { } }
+{ "v": 1, "id": "p_1_x8f2", "dir": "result", "ok": false,
+ "error": { "code": "E_PERMISSION", "message": "…" } }
+```
+
+- `v` is the protocol **major** (1 today). Additive changes bump the minor.
+- The **first** call from a frame must echo the handshake token from its URL
+ fragment (`location.hash`) or every later call fails `E_PERMISSION`.
+- `id` is your correlation key — 1–64 chars of `[A-Za-z0-9_.:-]`.
+- Error codes: `E_VERSION` `E_MALFORMED` `E_PAYLOAD` `E_PERMISSION` `E_METHOD`
+ `E_THROTTLE` `E_NOT_FOUND` `E_TIMEOUT` `E_INTERNAL`.
+- Every envelope passes the payload caps: 256 KB total, 500-item arrays,
+ 64-key objects, 13-deep nesting, 70 000-char strings (the collaboration
+ caps, applied identically). The ONE exception: the **result** of an
+ `elements.render` call may reach ~2 MB (a full SVG document).
+
+### Methods a plugin may call
+
+| Method | Permission | Returns |
+|---|---|---|
+| `info` | — | `{ api: { major, minor }, host, plugin: { id, version }, capabilities: { panel, renderer } }` |
+| `ping` | — | `{ pong: true, t }` |
+| `design.getSnapshot` | `design:read` | A **lossy, capped projection** of the current design: pages, element views (id/type/geometry/own small fields), background. Megabyte fields (image dataURLs) are omitted and named in `omitted`, internal bookkeeping never crosses. |
+| `subscribe` | `design:read` | `{ subscribed: ["selection", "document"] }` — pushes arrive as host→plugin `event` calls (see below). |
+| `actions.apply` | `design:write` | `{ message }` — applies one whitelisted design action (below). Refused in read-only designs. |
+| `elements.registerRenderer` | `element:plugin` | `{ registered: ["cloud"] }` — service frames only. |
+| `storage.get` / `set` / `remove` / `keys` | `storage` | 256 KB namespace per plugin id, JSON values, key grammar `[A-Za-z0-9_.:-]{1,64}`. |
+| `ui.notify` | `ui:notify` | Toast (≤ 200 chars, control chars stripped). |
+| `ui.closePanel` | `ui:notify` | Closes your panel. |
+
+**Whitelisted actions for `actions.apply`** (all of them the ordinary
+undoable, collaboration-safe store paths — a plugin can never mutate the
+document model directly):
+
+`addText` · `addImage` · `updateElements` · `deleteElements` ·
+`setBackground` · `addPage` · `duplicatePage` · `alignElements` ·
+`distributeElements` · `addPluginElement` · `updatePluginElementData`
+
+The two plugin-element actions run with the **calling install's identity** —
+you can only create elements for kinds your manifest declares, and only
+patch elements your own plugin id owns. A plugin cannot forge another
+plugin's namespace.
+
+Example — add one of your own element types:
+
+```js
+rpc.call('actions.apply', {
+ action: {
+ type: 'addPluginElement',
+ kind: 'cloud', // a kind your manifest declares
+ data: { words: [...], seed: 42, /* ≤ 64 KB, clone-safe */ },
+ width: 480, height: 300,
+ name: 'Word cloud',
+ },
+})
+```
+
+### Calls the host makes INTO your plugin
+
+Handle these in the **service** frame (and ack `event` pushes anywhere):
+
+| Method | Params | You answer |
+|---|---|---|
+| `elements.render` | `{ kind, data, width, height, mode }` | `{ svg: "<svg…>…</svg>" }` or `{ raster: "data:image/png;base64,…" }` — see the renderer contract |
+| `event` | `{ topic: 'selection' \| 'document', payload }` | Ack with an ok result (a client library does this for you) |
+
+## Element types — the renderer contract
+
+A plugin element is a first-class canvas element whose **pixels are
+delegated**. The manifest declares the types:
+
+```json
+"elements": [
+ {
+ "kind": "cloud",
+ "label": "Word cloud",
+ "initialData": { "words": [], "seed": 42, "density": 0.7, "mask": "rect", "palette": "canvix" },
+ "schema": [
+ { "key": "seed", "type": "number", "label": "Seed", "min": 1, "max": 9999 },
+ { "key": "density", "type": "range", "label": "Density", "min": 0.1, "max": 1, "step": 0.05 },
+ { "key": "mask", "type": "select", "label": "Shape",
+ "options": [ { "value": "rect", "label": "Rectangle" }, { "value": "circle", "label": "Circle" } ] },
+ { "key": "palette", "type": "select", "label": "Palette", "options": [ … ] }
+ ]
+ }
+]
+```
+
+- `kind` — a lowercase slug, unique per plugin. On the canvas the element is
+ `(pluginId, kind, pluginVersion, data)`; selection, drag, transform, undo,
+ layering, animations and Beat Sync apply through the ordinary paths.
+- `schema` — the **host** renders these fields in the properties bar when
+ the element is selected (`text` / `number` / `range` / `color` / `select`
+ with min/max/step/maxLength/options). No plugin code runs in the
+ properties bar — changes flow back as `updatePluginElementData` with the
+ install's identity. Keep the panel for anything richer ("Open in app"
+ is always one click away).
+- `initialData` must satisfy the schema and the data caps, and becomes the
+ element's `data` when created.
+
+### The service frame and `elements.render`
+
+When the open design contains your elements, the host mounts your
+`entry.service` in a hidden sandboxed iframe (same boundary as panels) and
+expects it to:
+
+1. echo the handshake (first call — registering is a natural first call),
+2. call `elements.registerRenderer` once per declared kind,
+3. answer `elements.render` calls — `{ kind, data, width, height, mode }`
+ where `mode` is `'canvas'` (editor/thumbnails) or `'export'`
+ (SVG/PNG/PDF/video serialization) — within **10 seconds**,
+4. return `{ svg }` or `{ raster }`.
+
+The rules that make this contract safe and cacheable:
+
+- **Deterministic.** Same `data` in, byte-identical output out — the host
+ caches renders by `(pluginId, elementId, hash(data), size, mode)` and
+ never re-asks for the same input. Put every random choice behind a seed
+ that lives in `data` (Word Cloud uses mulberry32 seeded by `data.seed`).
+ Never read `Date`, `Math.random`, the DOM, or the network in a render.
+- **Bounded.** The svg must stay under 2 MB and 20 000 elements; a raster
+ under 2 MB as a base64 png/jpeg/gif/webp data URL.
+- **Accept-or-reject sanitized.** Output passes the host sanitizer or the
+ element degrades to a placeholder — the host never rewrites your SVG, it
+ only accepts it. Allowed: `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 fe*
+ marker style switch a`. Forbidden, among others: `<script>`,
+ `foreignObject`, doctype/entity/CDATA/processing instructions, `on*`
+ event attributes, `javascript:` URIs, external `href`/`src` (only `data:`
+ and internal `#ref`), `@import` and non-`data:` `url()` in CSS.
+ **Emit from an allowlist, escape all text content, and test your output
+ against the sanitizer in the repo's unit suite** — that is exactly what
+ Word Cloud's `src/lib/plugins/wordcloud.test.ts` does.
+- **Never throw on hostile data.** Your render will meet elements written by
+ older/newer versions of yourself and by other clients. Clamp, default,
+ skip — degrade, don't crash (the 10-second deadline and the error path
+ both land on the placeholder, but a renderer that survives is a plugin
+ that keeps working).
+- Text width: if you measure text against local fonts your output differs
+ per machine — Word Cloud estimates widths from character classes so the
+ SVG is identical everywhere. Prefer estimation over measurement.
+
+### Durability — the promise your users feel
+
+Plugin elements are ordinary document data (`jsonb`). Uninstall, disable,
+crash, flag-off: the element never disappears — it degrades to a neutral
+placeholder card that names the element and tells the viewer why
+("Install "com.canvix.wordcloud" to view this element"). Reinstall and it
+renders again. A collaborator without your plugin edits the design freely
+and loses nothing. Exports embed the rendered cloud when available and the
+honest placeholder when not — never a silent omission.
+
+## Packaging rules
+
+- No inline `<script>` blocks, no `on*=` handlers, no `javascript:` URIs in
+ any served HTML — enforced **at install**, so the serve route's strict CSP
+ (`script-src 'self'`, no `unsafe-inline` for scripts) can never break a
+ valid plugin silently. Use `<script src="your.js">`.
+- Inline `<style>` and `style=` attributes are fine (`style-src
+ 'unsafe-inline'`); external stylesheets are not.
+- Images/fonts your frames need must be `data:` URLs or bundled files; the
+ CSP allows `img-src data: blob:` and `font-src data:` only.
+- The bundle is plain files — **no zip** (that would be a new dependency for
+ every self-hoster). The manifest lists its files; the installer fetches
+ each through the SSRF guard (2 MB total, 50 files, 10 s per file) and
+ sha256-pins every one.
+
+## Hosting your plugin
+
+Anywhere that serves static bytes over https: GitHub Pages, Netlify, S3, a
+directory on your own server. The manifest URL is what users paste —
+`https://example.com/hello/manifest.json` — and every `files[]` entry is
+resolved relative to it. Version bumps: update `version`, keep the URL
+stable; users reinstall to upgrade (the install row is replaced atomically,
+and a permission set that grew requires fresh consent).
+
+For local development, `http://127.0.0.1:8000/hello/manifest.json` is
+accepted (loopback http is the one dev carve-out) — serve with any static
+file server, e.g. `python3 -m http.server`.
+
+**Bundled plugins.** Canvix itself ships reference plugins in
+`public/plugins/` (currently: Word Cloud). They install through the same
+rail from the strict relative URL `/plugins/<slug>/manifest.json` — the
+server reads the files from its own disk, which is the only path that may
+carry a `com.canvix.*` id. On runtimes without a filesystem (Cloudflare
+Workers) bundled installs answer a clear error; third-party plugins by
+absolute URL are unaffected. If you fork Canvix, drop your own first-party
+plugins into `public/plugins/<slug>/` and add them to
+`src/lib/plugins/firstparty.ts`.
+
+## Walkthrough — the Word Cloud reference plugin
+
+[`public/plugins/wordcloud/`](../../public/plugins/wordcloud) is the
+canonical example, small enough to read in one sitting:
+
+- **`wordcloud.js`** — one shared UMD script both frames load: the RPC
+ client (`createRpc`), `tokenize`, and the seeded layout/SVG emitter. The
+ panel's preview and the service's renders are the same code, so the
+ preview never lies.
+- **`panel.html` / `panel.js`** — the UX: pull this page's text
+ (`design.getSnapshot`) or paste your own, stop-words, palettes, shape,
+ density, seed; a live preview; settings persisted via `storage`;
+ `addPluginElement` on Generate; `updatePluginElementData` when one of its
+ clouds is selected.
+- **`service.html` / `service.js`** — registers the `cloud` renderer and
+ answers `elements.render` with `{ svg }`.
+- **The tests that pin it**: `src/lib/plugins/wordcloud.test.ts`
+ (determinism, sanitizer acceptance on hostile words, mask containment,
+ caps) and `tests/e2e-plugins/wordcloud.spec.ts` (the full install →
+ consent → generate → render → export → restyle → disable → uninstall
+ acceptance, run flag-on via `playwright.plugins.config.ts`).
+
+## FAQ
+
+**Will there be a marketplace?** No — see the top of this document. Plugins
+install by URL; discovery is word-of-mouth, your README, your site. This is
+a deliberate product decision, not a missing feature.
+
+**Can a plugin phone home?** Only to origins the user explicitly granted at
+install (`network:https://…`), listed verbatim on the consent screen and
+enforced by the iframe's CSP `connect-src`. Zero network permissions means
+an exfiltration wall, not a speed bump.
+
+**What happens when I uninstall a plugin that made elements?** The elements
+stay — they are design data, not plugin data. They render as placeholder
+cards until the plugin is reinstalled. Uninstalling deletes the install row
+and its pinned files; nothing in any design is touched.
+
+**How do I test my plugin?** The repo's own pyramid: run the layout/pure
+parts under vitest (import your UMD file like `wordcloud.test.ts` does —
+including sanitizer-acceptance assertions against
+`sanitizePluginSvg`), then exercise the golden path in a browser with
+`CANVIX_PLUGINS=1 npm run dev` and the Apps panel.
+
+**Why is my element a placeholder?** One of, in order: the plugin system is
+flagged off on the instance; you are signed out; the plugin is not
+installed (or was uninstalled); it is disabled; its service frame has not
+finished booting; it has not registered a renderer for that kind; a render
+failed, timed out (10 s), or was rejected by the sanitizer. The card says
+which — that honesty is the contract.
+
+**How does versioning work?** `canvixPluginApi` major must match the host;
+minor ≤ the host's. `engines.canvix` constrains the host app version.
+`version` is yours, stamped on every element you create. Additive host
+changes bump the minor; breaking changes bump the major and old plugins
+fail at INSTALL with a plain message, never silently at runtime.
diff --git a/package.json b/package.json
index 4d43e31..c907158 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "canvix",
- "version": "0.13.3",
+ "version": "0.13.4",
"private": false,
"description": "Canvix — free & open-source graphic design tool. A community-built Canva alternative.",
"scripts": {
diff --git a/playwright.plugins.config.ts b/playwright.plugins.config.ts
new file mode 100644
index 0000000..175011e
--- /dev/null
+++ b/playwright.plugins.config.ts
@@ -0,0 +1,41 @@
+import { defineConfig, devices } from '@playwright/test'
+
+/**
+ * The PLUGINS-FLAG-ON browser suite (P5).
+ *
+ * The default playwright.config.ts keeps CANVIX_PLUGINS unset (its
+ * specs assert the flag-off behavior: 503s, hidden UI, zero runtime
+ * bytes). This config boots a SECOND dev server with the flag on,
+ * on a separate port, and runs tests/e2e-plugins — the Word Cloud
+ * acceptance suite for the v0.13 plugin system MVP.
+ *
+ * npx playwright test -c playwright.plugins.config.ts
+ *
+ * Requires a reachable DATABASE_URL (same as the default suite).
+ */
+export default defineConfig({
+ testDir: './tests/e2e-plugins',
+ timeout: 120_000,
+ expect: { timeout: 15_000 },
+ fullyParallel: false,
+ workers: 1,
+ retries: process.env.CI ? 1 : 0,
+ reporter: 'list',
+ use: {
+ baseURL: process.env.BASE_URL ?? 'http://localhost:3100',
+ trace: 'retain-on-failure',
+ },
+ projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],
+ webServer: process.env.BASE_URL
+ ? undefined
+ : {
+ // NOT `npm run dev` — that script pipes through tee and pins
+ // the port; invoke next directly with the plugins flag set
+ command: 'npx next dev -p 3100',
+ url: 'http://localhost:3100',
+ timeout: 180_000,
+ reuseExistingServer: true,
+ stdout: 'ignore',
+ env: { CANVIX_PLUGINS: '1' },
+ },
+})
diff --git a/public/plugins/wordcloud/manifest.json b/public/plugins/wordcloud/manifest.json
new file mode 100644
index 0000000..6b9b3f7
--- /dev/null
+++ b/public/plugins/wordcloud/manifest.json
@@ -0,0 +1,43 @@
+{
+ "canvixPluginApi": "1.1",
+ "id": "com.canvix.wordcloud",
+ "name": "Word Cloud",
+ "description": "Turn any text into a seeded word-cloud graphic. Deterministic, offline, zero network.",
+ "version": "1.0.0",
+ "author": { "name": "Canvix team", "url": "https://github.com/mir-ashiq/canvix" },
+ "engines": { "canvix": ">=0.13.4 <0.14.0" },
+ "entry": { "panel": "panel.html", "service": "service.html" },
+ "permissions": ["design:read", "design:write", "element:plugin", "storage"],
+ "files": ["manifest.json", "panel.html", "panel.js", "service.html", "service.js", "wordcloud.js"],
+ "elements": [
+ {
+ "kind": "cloud",
+ "label": "Word cloud",
+ "initialData": { "words": [], "seed": 42, "density": 0.7, "mask": "rect", "palette": "canvix" },
+ "schema": [
+ { "key": "seed", "type": "number", "label": "Seed", "min": 1, "max": 9999 },
+ { "key": "density", "type": "range", "label": "Density", "min": 0.1, "max": 1, "step": 0.05 },
+ {
+ "key": "mask",
+ "type": "select",
+ "label": "Shape",
+ "options": [
+ { "value": "rect", "label": "Rectangle" },
+ { "value": "circle", "label": "Circle" }
+ ]
+ },
+ {
+ "key": "palette",
+ "type": "select",
+ "label": "Palette",
+ "options": [
+ { "value": "canvix", "label": "Canvix" },
+ { "value": "sunset", "label": "Sunset" },
+ { "value": "ocean", "label": "Ocean" },
+ { "value": "mono", "label": "Mono" }
+ ]
+ }
+ ]
+ }
+ ]
+}
diff --git a/public/plugins/wordcloud/panel.html b/public/plugins/wordcloud/panel.html
new file mode 100644
index 0000000..637ea80
--- /dev/null
+++ b/public/plugins/wordcloud/panel.html
@@ -0,0 +1,126 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Word Cloud — panel</title>
+<style>
+ :root { color-scheme: dark; }
+ * { box-sizing: border-box; }
+ body {
+ margin: 0;
+ font-family: Inter, system-ui, -apple-system, "Segoe UI", sans-serif;
+ font-size: 12px;
+ color: #E7E8EE;
+ background: #0F0F13;
+ padding: 12px;
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ min-height: 100vh;
+ }
+ h1 { font-size: 13px; margin: 0; font-weight: 700; }
+ h1 small { font-weight: 400; color: #878E9C; font-size: 10px; }
+ .row { display: flex; align-items: center; gap: 6px; }
+ .grow { flex: 1; min-width: 0; }
+ label.field { display: flex; flex-direction: column; gap: 3px; flex: 1; min-width: 0; }
+ label.field > span { font-size: 10px; color: #878E9C; }
+ textarea, input[type="text"], select {
+ width: 100%;
+ background: rgba(255,255,255,0.05);
+ border: 1px solid rgba(255,255,255,0.12);
+ border-radius: 8px;
+ color: #E7E8EE;
+ padding: 6px 8px;
+ font: inherit;
+ outline: none;
+ }
+ textarea { resize: vertical; min-height: 88px; line-height: 1.45; }
+ textarea:focus, input:focus, select:focus { border-color: #7630D7; }
+ input[type="range"] { width: 100%; accent-color: #7630D7; }
+ button {
+ font: inherit;
+ font-weight: 600;
+ border: 0;
+ border-radius: 8px;
+ padding: 8px 12px;
+ cursor: pointer;
+ color: #fff;
+ background: #7630D7;
+ }
+ button:hover { background: #8B5CF6; }
+ button:disabled { opacity: 0.4; cursor: not-allowed; }
+ button.ghost { background: rgba(255,255,255,0.07); color: #C9CDD6; font-weight: 500; }
+ button.ghost:hover { background: rgba(255,255,255,0.12); }
+ .preview {
+ border: 1px solid rgba(255,255,255,0.1);
+ border-radius: 10px;
+ background: #fff;
+ overflow: hidden;
+ min-height: 120px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ }
+ .preview svg { display: block; max-width: 100%; height: auto; }
+ .hint { font-size: 10px; color: #878E9C; line-height: 1.5; margin: 0; }
+ .status { font-size: 11px; min-height: 16px; color: #878E9C; }
+ .status.ok { color: #34D399; }
+ .status.err { color: #F87171; }
+ .badge { font-size: 9px; color: #02C0CC; background: rgba(2,192,204,0.1); border-radius: 5px; padding: 2px 6px; }
+</style>
+</head>
+<body>
+ <h1>Word Cloud <small>· com.canvix.wordcloud</small> <span class="badge" id="wc-api">connecting…</span></h1>
+
+ <label class="field">
+ <span>Text — paste anything, or pull it from this page</span>
+ <textarea id="wc-text" placeholder="Paste or type the text for your cloud…" spellcheck="false"></textarea>
+ </label>
+ <div class="row">
+ <button class="ghost grow" id="wc-use-page" type="button">Use this page&rsquo;s text</button>
+ <button class="ghost" id="wc-reroll" type="button" title="New random seed">Reroll</button>
+ </div>
+
+ <div class="row">
+ <label class="field">
+ <span>Palette</span>
+ <select id="wc-palette">
+ <option value="canvix">Canvix</option>
+ <option value="sunset">Sunset</option>
+ <option value="ocean">Ocean</option>
+ <option value="mono">Mono</option>
+ </select>
+ </label>
+ <label class="field">
+ <span>Shape</span>
+ <select id="wc-mask">
+ <option value="rect">Rectangle</option>
+ <option value="circle">Circle</option>
+ </select>
+ </label>
+ </div>
+
+ <label class="field">
+ <span>Density — <b id="wc-density-val">0.70</b></span>
+ <input type="range" id="wc-density" min="0.1" max="1" step="0.05" value="0.7">
+ </label>
+
+ <label class="field">
+ <span>Stop words (comma separated — remembered)</span>
+ <input type="text" id="wc-stops" placeholder="e.g. lorem, ipsum">
+ </label>
+
+ <div class="preview" id="wc-preview" aria-label="Word cloud preview"></div>
+ <p class="hint" id="wc-count">No words yet.</p>
+
+ <button id="wc-add" type="button" disabled>Add to canvas</button>
+ <button id="wc-update" type="button" disabled hidden>Update selected cloud</button>
+ <div class="status" id="wc-status" role="status"></div>
+
+ <p class="hint">Deterministic: the same text, seed and options always render the same cloud. No network — everything happens in this sandbox.</p>
+
+<script src="wordcloud.js"></script>
+<script src="panel.js"></script>
+</body>
+</html>
diff --git a/public/plugins/wordcloud/panel.js b/public/plugins/wordcloud/panel.js
new file mode 100644
index 0000000..3902ebb
--- /dev/null
+++ b/public/plugins/wordcloud/panel.js
@@ -0,0 +1,300 @@
+/*
+ * Word Cloud — panel logic (runs inside the sandboxed panel iframe).
+ * The shared wordcloud.js provides the RPC client and the exact
+ * layout the service iframe uses, so the preview here is the truth
+ * the canvas will show.
+ */
+;(function () {
+ 'use strict'
+
+ var WC = window.CanvixWordCloud
+ var PLUGIN_ID = 'com.canvix.wordcloud'
+ var KIND = 'cloud'
+
+ // ── element handles ─────────────────────────────────────────
+ var $ = function (id) { return document.getElementById(id) }
+ var apiBadge = $('wc-api')
+ var textEl = $('wc-text')
+ var usePageBtn = $('wc-use-page')
+ var rerollBtn = $('wc-reroll')
+ var paletteEl = $('wc-palette')
+ var maskEl = $('wc-mask')
+ var densityEl = $('wc-density')
+ var densityVal = $('wc-density-val')
+ var stopsEl = $('wc-stops')
+ var previewEl = $('wc-preview')
+ var countEl = $('wc-count')
+ var addBtn = $('wc-add')
+ var updateBtn = $('wc-update')
+ var statusEl = $('wc-status')
+
+ // ── state ───────────────────────────────────────────────────
+ var settings = { palette: 'canvix', mask: 'rect', density: 0.7, seed: 42, stopwords: '' }
+ var selectedCloud = null // { id, data } of the selected own element
+ var previewTimer = null
+
+ function setStatus(text, kind) {
+ statusEl.textContent = text || ''
+ statusEl.className = 'status' + (kind ? ' ' + kind : '')
+ }
+
+ function currentWords() {
+ return WC.tokenize(textEl.value, settings.stopwords)
+ }
+
+ function currentData() {
+ return {
+ words: currentWords(),
+ seed: settings.seed,
+ density: settings.density,
+ mask: settings.mask,
+ palette: settings.palette,
+ }
+ }
+
+ // ── preview (same code path the service renderer uses) ──────
+ function renderPreview() {
+ var data = currentData()
+ var box = previewEl.getBoundingClientRect()
+ var w = Math.max(160, Math.round(box.width || 280))
+ var h = Math.round(w * 0.62)
+ previewEl.innerHTML = WC.toSvg(data, w, h, 'canvas')
+ countEl.textContent = data.words.length
+ ? data.words.length + ' words · seed ' + data.seed + (selectedCloud ? '' : ' · top: ' + data.words[0].text)
+ : 'No words yet.'
+ addBtn.disabled = data.words.length === 0
+ }
+
+ function schedulePreview() {
+ if (previewTimer) clearTimeout(previewTimer)
+ previewTimer = setTimeout(renderPreview, 120)
+ }
+
+ // ── settings persistence (namespaced by the host) ───────────
+ var saveTimer = null
+ function persistSettings() {
+ if (saveTimer) clearTimeout(saveTimer)
+ saveTimer = setTimeout(function () {
+ rpc.call('storage.set', { key: 'settings', value: settings }).catch(function () {
+ /* quota or permission — non-fatal, the panel still works */
+ })
+ }, 400)
+ }
+
+ function reflectSettings() {
+ paletteEl.value = settings.palette
+ maskEl.value = settings.mask
+ densityEl.value = String(settings.density)
+ densityVal.textContent = Number(settings.density).toFixed(2)
+ stopsEl.value = settings.stopwords
+ }
+
+ // ── RPC wiring ──────────────────────────────────────────────
+ var rpc = WC.createRpc({ handshake: WC.handshakeFromLocation() })
+
+ function collectPageText(pages, currentPage) {
+ var texts = []
+ function walk(elements) {
+ for (var i = 0; i < elements.length; i++) {
+ var el = elements[i]
+ if (!el || typeof el !== 'object') continue
+ if (typeof el.text === 'string' && el.text.trim()) texts.push(el.text)
+ if (Array.isArray(el.children)) walk(el.children)
+ }
+ }
+ var page = pages && pages[currentPage]
+ if (page && Array.isArray(page.elements)) walk(page.elements)
+ return texts
+ }
+
+ function findSelectedCloud(pages, currentPage, ids) {
+ var found = null
+ function walk(elements) {
+ for (var i = 0; i < elements.length && !found; i++) {
+ var el = elements[i]
+ if (!el || typeof el !== 'object') continue
+ if (
+ ids.indexOf(el.id) >= 0 &&
+ el.type === 'plugin' &&
+ el.pluginId === PLUGIN_ID &&
+ el.kind === KIND
+ ) {
+ found = el
+ } else if (Array.isArray(el.children) && !found) {
+ walk(el.children)
+ }
+ }
+ }
+ var page = pages && pages[currentPage]
+ if (page && Array.isArray(page.elements)) walk(page.elements)
+ return found
+ }
+
+ rpc.handle('event', function (params) {
+ // selection pushes — refresh the "update selected" affordance
+ if (!params || params.topic !== 'selection') return
+ var ids = (params.payload && params.payload.ids) || []
+ if (!ids.length) {
+ selectedCloud = null
+ updateBtn.hidden = true
+ return
+ }
+ rpc
+ .call('design.getSnapshot')
+ .then(function (snap) {
+ var el = findSelectedCloud(snap.pages, snap.currentPage, ids)
+ selectedCloud = el ? { id: el.id, data: el.data || {} } : null
+ if (selectedCloud) {
+ // load the element's words back for restyling
+ var words = selectedCloud.data.words
+ if (Array.isArray(words) && words.length) {
+ textEl.value = words
+ .map(function (w) {
+ return Array(Math.max(1, Math.min(30, Math.round(w.weight))))
+ .fill(w.text)
+ .join(' ')
+ })
+ .join(' ')
+ }
+ if (typeof selectedCloud.data.seed === 'number') settings.seed = selectedCloud.data.seed
+ reflectSettings()
+ updateBtn.hidden = false
+ setStatus('Selected a cloud — edit and update it in place.', 'ok')
+ } else {
+ updateBtn.hidden = true
+ }
+ schedulePreview()
+ })
+ .catch(function () {
+ /* read-only snapshot failure — non-fatal */
+ })
+ })
+
+ // ── actions ─────────────────────────────────────────────────
+ usePageBtn.addEventListener('click', function () {
+ setStatus('Reading this page…')
+ rpc
+ .call('design.getSnapshot')
+ .then(function (snap) {
+ var texts = collectPageText(snap.pages, snap.currentPage)
+ if (!texts.length) {
+ setStatus('No text elements on this page — paste some text instead.', 'err')
+ return
+ }
+ textEl.value = texts.join(' ')
+ setStatus('Collected ' + texts.length + ' text element' + (texts.length > 1 ? 's' : '') + '.', 'ok')
+ schedulePreview()
+ })
+ .catch(function (err) {
+ setStatus(String(err.message || err), 'err')
+ })
+ })
+
+ rerollBtn.addEventListener('click', function () {
+ settings.seed = 1 + Math.floor(Math.random() * 9999) // UI affordance only —
+ // the seed is then DATA: renders stay deterministic
+ reflectSettings()
+ persistSettings()
+ schedulePreview()
+ })
+
+ addBtn.addEventListener('click', function () {
+ var data = currentData()
+ if (!data.words.length) return
+ addBtn.disabled = true
+ setStatus('Adding…')
+ rpc
+ .call('actions.apply', {
+ action: {
+ type: 'addPluginElement',
+ kind: KIND,
+ data: data,
+ width: 480,
+ height: 300,
+ name: 'Word cloud',
+ },
+ })
+ .then(function (res) {
+ setStatus((res && res.message) || 'Added to the canvas.', 'ok')
+ })
+ .catch(function (err) {
+ setStatus(String(err.message || err), 'err')
+ })
+ .then(function () {
+ addBtn.disabled = false
+ })
+ })
+
+ updateBtn.addEventListener('click', function () {
+ if (!selectedCloud) return
+ var data = currentData()
+ setStatus('Updating…')
+ rpc
+ .call('actions.apply', {
+ action: {
+ type: 'updatePluginElementData',
+ ids: [selectedCloud.id],
+ patch: data,
+ },
+ })
+ .then(function (res) {
+ setStatus((res && res.message) || 'Updated.', 'ok')
+ })
+ .catch(function (err) {
+ setStatus(String(err.message || err), 'err')
+ })
+ })
+
+ // ── settings inputs ─────────────────────────────────────────
+ paletteEl.addEventListener('change', function () {
+ settings.palette = paletteEl.value
+ persistSettings()
+ schedulePreview()
+ })
+ maskEl.addEventListener('change', function () {
+ settings.mask = maskEl.value
+ persistSettings()
+ schedulePreview()
+ })
+ densityEl.addEventListener('input', function () {
+ settings.density = Number(densityEl.value)
+ densityVal.textContent = settings.density.toFixed(2)
+ persistSettings()
+ schedulePreview()
+ })
+ stopsEl.addEventListener('change', function () {
+ settings.stopwords = stopsEl.value.slice(0, 200)
+ persistSettings()
+ schedulePreview()
+ })
+ textEl.addEventListener('input', schedulePreview)
+
+ // ── boot ────────────────────────────────────────────────────
+ rpc
+ .call('info')
+ .then(function (info) {
+ var api = info && info.api
+ apiBadge.textContent = 'plugin API v' + (api ? api.major + '.' + api.minor : '1')
+ return rpc.call('storage.get', { key: 'settings' })
+ })
+ .then(function (res) {
+ var saved = res && res.value
+ if (saved && typeof saved === 'object') {
+ if (typeof saved.palette === 'string') settings.palette = saved.palette
+ if (typeof saved.mask === 'string') settings.mask = saved.mask
+ if (typeof saved.density === 'number') settings.density = saved.density
+ if (typeof saved.seed === 'number') settings.seed = saved.seed
+ if (typeof saved.stopwords === 'string') settings.stopwords = saved.stopwords
+ }
+ reflectSettings()
+ renderPreview()
+ return rpc.call('subscribe', { topic: 'selection' })
+ })
+ .then(function () {
+ setStatus('Ready — sandboxed, no network.', 'ok')
+ })
+ .catch(function (err) {
+ apiBadge.textContent = 'offline'
+ setStatus('Could not reach the host: ' + String(err.message || err), 'err')
+ })
+})()
diff --git a/public/plugins/wordcloud/service.html b/public/plugins/wordcloud/service.html
new file mode 100644
index 0000000..c9ac164
--- /dev/null
+++ b/public/plugins/wordcloud/service.html
@@ -0,0 +1,17 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<title>Word Cloud — renderer service</title>
+</head>
+<body>
+<!--
+ The hidden service frame the host mounts for every design that
+ contains Word Cloud elements. It registers the 'cloud' renderer
+ and answers host→plugin elements.render calls. No UI, no styles —
+ just the contract.
+-->
+<script src="wordcloud.js"></script>
+<script src="service.js"></script>
+</body>
+</html>
diff --git a/public/plugins/wordcloud/service.js b/public/plugins/wordcloud/service.js
new file mode 100644
index 0000000..e781fb1
--- /dev/null
+++ b/public/plugins/wordcloud/service.js
@@ -0,0 +1,41 @@
+/*
+ * Word Cloud — the service-frame half of the renderer contract
+ * (research/PLUGIN-SYSTEM.md §4.5). This frame is mounted hidden by
+ * the host whenever the open design contains Word Cloud elements.
+ *
+ * host → plugin elements.render { kind, data, width, height, mode }
+ * plugin → host result { svg } (sanitized host-side)
+ *
+ * Renders are deterministic by contract: every random decision is
+ * mulberry32 seeded from data.seed, so the host's render cache
+ * (keyed on a hash of the data) is sound — same data, same SVG.
+ */
+;(function () {
+ 'use strict'
+
+ var WC = window.CanvixWordCloud
+ var KIND = 'cloud'
+
+ var rpc = WC.createRpc({ handshake: WC.handshakeFromLocation() })
+
+ rpc.handle('elements.render', function (params) {
+ var p = params || {}
+ var svg = WC.toSvg(p.data, p.width, p.height, p.mode)
+ // one honest log line per render — the e2e suite and curious
+ // self-hosters watch the console; everything else stays quiet
+ console.log('[wordcloud] rendered ' + (p.width || '?') + 'x' + (p.height || '?') + (p.mode ? ' (' + p.mode + ')' : ''))
+ return { svg: svg }
+ })
+
+ // host→plugin pushes (event) are acked by the rpc client; this
+ // service subscribes to nothing.
+
+ rpc
+ .call('elements.registerRenderer', { kind: KIND })
+ .then(function () {
+ console.log('[wordcloud] renderer registered for "' + KIND + '"')
+ })
+ .catch(function (err) {
+ console.error('[wordcloud] renderer registration failed: ' + String(err.message || err))
+ })
+})()
diff --git a/public/plugins/wordcloud/wordcloud.js b/public/plugins/wordcloud/wordcloud.js
new file mode 100644
index 0000000..f8eab4d
--- /dev/null
+++ b/public/plugins/wordcloud/wordcloud.js
@@ -0,0 +1,385 @@
+/*
+ * Canvix Word Cloud — the one shared script both plugin frames load
+ * (P5, research/PLUGIN-SYSTEM.md §5). Zero dependencies, no build
+ * step, classic <script src> in a sandboxed iframe AND a CommonJS
+ * export for the host repo's vitest suite.
+ *
+ * Three concerns live here, on purpose:
+ *
+ * 1. RPC — the plugin half of the v1 postMessage envelope
+ * (handshake echo, call/result correlation, and
+ * answering host→plugin calls such as
+ * elements.render / event pushes).
+ * 2. tokenize — text → weighted word list (shared by the panel
+ * preview and the service renderer, so preview and
+ * canvas always agree).
+ * 3. layout/svg — the deterministic renderer. The seed lives in the
+ * element data; the ONLY randomness is mulberry32
+ * seeded by it. Same data in → same SVG out, which
+ * is what makes the host's render cache sound.
+ * Text width is estimated from character classes,
+ * not measured, so output is identical on every
+ * machine (documented in docs/PLUGINS.md).
+ *
+ * Output discipline: the emitted SVG passes Canvix's accept-or-reject
+ * sanitizer BY CONSTRUCTION — only <svg>/<g>/<text> elements, only
+ * geometry/typography attributes, XML-escaped text content, no
+ * comments, no doctype, no external references of any kind.
+ */
+(function (root, factory) {
+ var api = factory()
+ if (typeof module === 'object' && module.exports) module.exports = api
+ root.CanvixWordCloud = api
+})(typeof self !== 'undefined' ? self : this, function () {
+ 'use strict'
+
+ // ── 1. RPC client (plugin half of the v1 envelope) ──────────
+
+ /**
+ * Wire up the broker conversation. The handshake token rides the
+ * iframe URL fragment (never sent over the wire); the FIRST call
+ * must echo it or the broker answers E_PERMISSION forever.
+ */
+ function createRpc(opts) {
+ opts = opts || {}
+ var timeoutMs = opts.timeoutMs || 15000
+ var pending = new Map()
+ var handlers = new Map()
+ var seq = 0
+ var handshakeSent = false
+
+ function newId() {
+ seq += 1
+ // correlation ids only — uniqueness is all that matters.
+ // (Math.random is NEVER used in the layout itself.)
+ return 'wc_' + seq.toString(36) + '_' + Math.random().toString(36).slice(2, 10)
+ }
+
+ window.addEventListener('message', function (ev) {
+ if (ev.source !== parent) return // only the host may talk to us
+ var data = ev.data
+ if (!data || typeof data !== 'object' || data.v !== 1) return
+ if (data.dir === 'result') {
+ var p = pending.get(data.id)
+ if (!p) return
+ pending.delete(data.id)
+ clearTimeout(p.timer)
+ if (data.ok) p.resolve(data.result)
+ else p.reject(new Error((data.error && data.error.message) || 'rpc error'))
+ return
+ }
+ if (data.dir === 'call') {
+ // host→plugin: elements.render or an event push.
+ // Every call gets a result envelope — pushes are acked, and
+ // a missing handler is an honest E_METHOD, not silence.
+ var fn = handlers.get(data.method)
+ Promise.resolve()
+ .then(function () {
+ if (!fn) throw new Error('this plugin does not handle "' + data.method + '"')
+ return fn(data.params)
+ })
+ .then(
+ function (result) {
+ parent.postMessage({ v: 1, id: data.id, dir: 'result', ok: true, result: result }, '*')
+ },
+ function (err) {
+ parent.postMessage(
+ {
+ v: 1,
+ id: data.id,
+ dir: 'result',
+ ok: false,
+ error: { code: 'E_INTERNAL', message: String((err && err.message) || err).slice(0, 200) },
+ },
+ '*',
+ )
+ },
+ )
+ }
+ })
+
+ function call(method, params) {
+ return new Promise(function (resolve, reject) {
+ var id = newId()
+ var envelope = { v: 1, id: id, dir: 'call', method: method }
+ if (params !== undefined) envelope.params = params
+ if (!handshakeSent) {
+ handshakeSent = true
+ envelope.handshake = opts.handshake
+ }
+ var timer = setTimeout(function () {
+ pending.delete(id)
+ reject(new Error('"' + method + '" timed out'))
+ }, timeoutMs)
+ pending.set(id, { resolve: resolve, reject: reject, timer: timer })
+ parent.postMessage(envelope, '*')
+ })
+ }
+
+ return {
+ call: call,
+ handle: function (method, fn) {
+ handlers.set(method, fn)
+ },
+ }
+ }
+
+ /** The handshake token from this frame's URL fragment, decoded. */
+ function handshakeFromLocation() {
+ var raw = location.hash.replace(/^#/, '')
+ try {
+ return decodeURIComponent(raw)
+ } catch (e) {
+ return raw
+ }
+ }
+
+ // ── 2. tokenization ─────────────────────────────────────────
+
+ var STOPWORDS = {
+ the: 1, a: 1, an: 1, and: 1, or: 1, but: 1, if: 1, of: 1, at: 1, by: 1,
+ for: 1, with: 1, about: 1, to: 1, from: 1, in: 1, on: 1, into: 1, over: 1,
+ is: 1, are: 1, was: 1, were: 1, be: 1, been: 1, being: 1, am: 1,
+ it: 1, its: 1, this: 1, that: 1, these: 1, those: 1, as: 1, not: 1, no: 1,
+ so: 1, than: 1, too: 1, very: 1, can: 1, will: 1, just: 1, should: 1,
+ we: 1, you: 1, your: 1, i: 1, my: 1, me: 1, our: 1, their: 1,
+ he: 1, she: 1, they: 1, them: 1, his: 1, her: 1, him: 1,
+ do: 1, does: 1, did: 1, doing: 1, have: 1, has: 1, had: 1, having: 1,
+ what: 1, which: 1, who: 1, when: 1, where: 1, why: 1, how: 1, all: 1,
+ any: 1, each: 1, few: 1, more: 1, most: 1, other: 1, some: 1, such: 1,
+ then: 1, once: 1, here: 1, there: 1, also: 1,
+ }
+
+ /** text → [{text, weight}] — weight-desc, then alphabetical. */
+ function tokenize(text, extraStops) {
+ var stops = {}
+ var k
+ for (k in STOPWORDS) stops[k] = 1
+ String(extraStops || '')
+ .split(/[\s,;]+/)
+ .forEach(function (w) {
+ w = w.trim().toLowerCase()
+ if (w.length >= 2 && w.length <= 40) stops[w] = 1
+ })
+ var counts = Object.create(null)
+ var re = /[\p{L}\p{N}][\p{L}\p{N}'\u2019-]*/gu
+ var m
+ while ((m = re.exec(String(text || ''))) !== null) {
+ var w = m[0]
+ if (w.length < 2 || w.length > 40) continue
+ var lower = w.toLowerCase()
+ if (stops[lower]) continue
+ if (counts[lower] === undefined) counts[lower] = { text: w, n: 0 }
+ counts[lower].n += 1
+ }
+ var out = []
+ for (var key in counts) out.push({ text: counts[key].text, weight: counts[key].n })
+ out.sort(function (a, b) {
+ return b.weight - a.weight || (a.text < b.text ? -1 : a.text > b.text ? 1 : 0)
+ })
+ return out.slice(0, 150)
+ }
+
+ // ── 3. deterministic layout + SVG ───────────────────────────
+
+ var PALETTES = {
+ canvix: ['#7630D7', '#02C0CC', '#F59E0B', '#EF4444', '#10B981', '#3B82F6', '#EC4899'],
+ sunset: ['#F97316', '#EF4444', '#EC4899', '#A855F7', '#FBBF24', '#DC2626'],
+ ocean: ['#0EA5E9', '#06B6D4', '#3B82F6', '#6366F1', '#14B8A6', '#0284C7'],
+ mono: ['#111827', '#374151', '#4B5563', '#6B7280', '#1F2937', '#9CA3AF'],
+ }
+ var MASKS = ['rect', 'circle']
+ var FONT = 'Inter, system-ui, -apple-system, Segoe UI, sans-serif'
+
+ /** mulberry32 — tiny, well-understood, deterministic PRNG. */
+ function mulberry32(seed) {
+ var a = (seed >>> 0) || 1
+ return function () {
+ a |= 0
+ a = (a + 0x6d2b79f5) | 0
+ var t = Math.imul(a ^ (a >>> 15), 1 | a)
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296
+ }
+ }
+
+ /** Character-class width estimate (documented approximation — no
+ * text measurement anywhere, so output is machine-independent). */
+ function textWidth(s, fontSize) {
+ var NARROW = 'iljtIfI.,;:\'!\u2019|()[]{}1'
+ var WIDE = 'mwMW@%&USDQGO0'
+ var units = 0
+ for (var i = 0; i < s.length; i++) {
+ var c = s.charAt(i)
+ if (NARROW.indexOf(c) >= 0) units += 0.3
+ else if (WIDE.indexOf(c) >= 0) units += 0.92
+ else if (c >= 'A' && c <= 'Z') units += 0.68
+ else if (c >= '0' && c <= '9') units += 0.56
+ else units += 0.53
+ }
+ return units * fontSize
+ }
+
+ function clampDim(n) {
+ var v = Math.round(Number(n))
+ if (!Number.isFinite(v)) v = 480
+ return Math.min(8000, Math.max(8, v))
+ }
+
+ /** Defensive data normalization — a renderer must never throw on
+ * hostile or stale element data (a future pluginVersion may have
+ * written fields this version does not understand). */
+ function clampData(data) {
+ var d = data && typeof data === 'object' && !Array.isArray(data) ? data : {}
+ var wordsIn = Array.isArray(d.words) ? d.words : []
+ var words = []
+ for (var i = 0; i < wordsIn.length && words.length < 150; i++) {
+ var w = wordsIn[i]
+ if (!w || typeof w !== 'object') continue
+ var text = String(w.text || '').trim().slice(0, 40)
+ var weight = Number(w.weight)
+ if (!text || !Number.isFinite(weight) || weight < 1) continue
+ words.push({ text: text, weight: Math.min(999, Math.round(weight)) })
+ }
+ var seed = Math.round(Number(d.seed))
+ if (!Number.isFinite(seed)) seed = 42
+ seed = Math.min(9999, Math.max(1, seed))
+ var density = Number(d.density)
+ if (!Number.isFinite(density)) density = 0.7
+ density = Math.min(1, Math.max(0.1, density))
+ var mask = MASKS.indexOf(d.mask) >= 0 ? d.mask : 'rect'
+ var palette = Object.prototype.hasOwnProperty.call(PALETTES, d.palette) ? d.palette : 'canvix'
+ return { words: words, seed: seed, density: density, mask: mask, palette: palette }
+ }
+
+ /** Does a box centered at (cx,cy) fit — inside the canvas bounds,
+ * inside the mask, clear of every placed box? */
+ function fits(cx, cy, hw, hh, W, H, mask, placed) {
+ if (cx - hw < 2 || cx + hw > W - 2 || cy - hh < 2 || cy + hh > H - 2) return false
+ if (mask === 'circle') {
+ var rx = (W / 2) * 0.94
+ var ry = (H / 2) * 0.94
+ var dx = hw / rx
+ var dy = hh / ry
+ if (dx * dx + dy * dy > 1) return false
+ }
+ for (var i = 0; i < placed.length; i++) {
+ var b = placed[i]
+ if (cx - hw < b.x + b.w && cx + hw > b.x && cy - hh < b.y + b.h && cy + hh > b.y) return false
+ }
+ return true
+ }
+
+ /**
+ * The spiral layout. Deterministic: every random decision comes
+ * from mulberry32(seed). Words that cannot be placed at any of
+ * three shrinking sizes are skipped — honest omission, no overlap.
+ */
+ function layout(data, width, height) {
+ var W = clampDim(width)
+ var H = clampDim(height)
+ var minDim = Math.min(W, H)
+ var rng = mulberry32(data.seed)
+ var palette = PALETTES[data.palette]
+ var words = data.words
+ var maxW = words.length ? words[0].weight : 1
+ var placed = []
+ var out = []
+ for (var i = 0; i < words.length; i++) {
+ var word = words[i]
+ var rotate = rng() < 0.12 ? 90 : 0
+ var phase = rng() * Math.PI * 2
+ var done = false
+ var shrink = 1
+ for (var attempt = 0; attempt < 3 && !done; attempt++, shrink *= 0.82) {
+ var size = Math.max(
+ 8,
+ minDim * 0.16 * (0.25 + 0.75 * Math.sqrt(word.weight / maxW)) * (0.4 + 0.6 * data.density) * shrink,
+ )
+ var bw = textWidth(word.text, size) + size * 0.35
+ var bh = size * 1.12 + size * 0.22
+ var step = 0
+ while (step < 900) {
+ var r = 2 + step * (minDim / 240)
+ var ang = phase + step * 0.37
+ var cx = W / 2 + r * Math.cos(ang)
+ var cy = H / 2 + r * Math.sin(ang)
+ var hw = (rotate === 90 ? bh : bw) / 2
+ var hh = (rotate === 90 ? bw : bh) / 2
+ if (fits(cx, cy, hw, hh, W, H, data.mask, placed)) {
+ placed.push({ x: cx - hw, y: cy - hh, w: hw * 2, h: hh * 2 })
+ out.push({
+ text: word.text,
+ cx: Math.round(cx * 10) / 10,
+ cy: Math.round(cy * 10) / 10,
+ fontSize: Math.round(size * 10) / 10,
+ rotate: rotate,
+ fill: palette[Math.floor(rng() * palette.length)],
+ })
+ done = true
+ break
+ }
+ step++
+ }
+ }
+ }
+ return out
+ }
+
+ function escapeXml(s) {
+ return String(s).replace(/[&<>"']/g, function (c) {
+ return c === '&' ? '&amp;' : c === '<' ? '&lt;' : c === '>' ? '&gt;' : c === '"' ? '&quot;' : '&#39;'
+ })
+ }
+
+ /**
+ * Render element data to a self-contained SVG string. The output
+ * intentionally uses only <svg>/<text> elements with geometry and
+ * typography attributes — the exact shape Canvix's sanitizer
+ * accepts, so it can never be rejected for structure.
+ */
+ function toSvg(data, width, height, mode) {
+ var d = clampData(data)
+ var W = clampDim(width)
+ var H = clampDim(height)
+ var items = layout(d, W, H)
+ var parts = []
+ parts.push(
+ '<svg xmlns="http://www.w3.org/2000/svg" width="' + W + '" height="' + H + '" viewBox="0 0 ' + W + ' ' + H + '">',
+ )
+ if (!items.length) {
+ var hintSize = Math.max(10, Math.round(Math.min(W, H) / 16))
+ parts.push(
+ '<text x="' + W / 2 + '" y="' + H / 2 + '" text-anchor="middle" font-size="' + hintSize +
+ '" fill="#C9CDD6" font-family="' + FONT + '">Word cloud (open the app to add words)</text>',
+ )
+ } else {
+ for (var i = 0; i < items.length; i++) {
+ var it = items[i]
+ var x = it.cx
+ var y = Math.round((it.cy + it.fontSize * 0.34) * 10) / 10 // manual baseline — portable across rasterizers
+ var rot = it.rotate ? ' transform="rotate(90 ' + it.cx + ' ' + it.cy + ')"' : ''
+ parts.push(
+ '<text x="' + x + '" y="' + y + '"' + rot + ' font-size="' + it.fontSize +
+ '" fill="' + it.fill + '" font-family="' + FONT + '" text-anchor="middle">' +
+ escapeXml(it.text) + '</text>',
+ )
+ }
+ }
+ parts.push('</svg>')
+ return parts.join('')
+ }
+
+ return {
+ createRpc: createRpc,
+ handshakeFromLocation: handshakeFromLocation,
+ tokenize: tokenize,
+ toSvg: toSvg,
+ clampData: clampData,
+ layout: layout,
+ PALETTES: PALETTES,
+ MASKS: MASKS,
+ STOPWORDS: STOPWORDS,
+ FONT: FONT,
+ }
+})
diff --git a/src/app/api/plugins/plugins.test.ts b/src/app/api/plugins/plugins.test.ts
index 216fb82..4d7eaed 100644
--- a/src/app/api/plugins/plugins.test.ts
+++ b/src/app/api/plugins/plugins.test.ts
@@ -224,6 +224,65 @@ describe('POST /api/plugins — install', () => {
where: { install: { userId: USER.id, pluginId: 'net.example.wordcloud' } },
})
})
+
+ // ── P5: first-party bundled installs ─────────────────────────
+
+ it('the projection carries installId === id (the service layer keys on it)', async () => {
+ dbMock.pluginInstall.findMany.mockResolvedValue([
+ {
+ id: 'install-9',
+ pluginId: 'com.canvix.wordcloud',
+ version: '1.0.0',
+ enabled: true,
+ createdAt: new Date(),
+ manifest: GOOD_BUNDLE.manifest,
+ },
+ ])
+ const res = await listInstalls(req('http://canvix.test/api/plugins'))
+ expect(res.status).toBe(200)
+ const body = await res.json()
+ expect(body.installs[0].installId).toBe('install-9')
+ expect(body.installs[0].id).toBe('install-9')
+ })
+
+ it('a bundled relative URL installs with allowFirstParty + the synthetic origin', async () => {
+ const calls: unknown[][] = []
+ collectBundleMock.mockImplementation(async (...args: unknown[]) => {
+ calls.push(args)
+ return { ok: true, bundle: GOOD_BUNDLE }
+ })
+ const res = await installPlugin(
+ req('http://canvix.test/api/plugins', {
+ method: 'POST',
+ body: '{"manifestUrl":"/plugins/wordcloud/manifest.json"}',
+ }),
+ )
+ expect(res.status).toBe(201)
+ expect(calls.length).toBe(1)
+ const [url, opts] = calls[0] as [string, { allowFirstParty?: boolean }]
+ expect(url).toBe('http://canvix.bundled.internal/plugins/wordcloud/manifest.json')
+ expect(opts.allowFirstParty).toBe(true)
+ })
+
+ it('an ordinary absolute URL NEVER gets the first-party grant', async () => {
+ const calls: unknown[][] = []
+ collectBundleMock.mockImplementation(async (...args: unknown[]) => {
+ calls.push(args)
+ return { ok: true, bundle: GOOD_BUNDLE }
+ })
+ const res = await installPlugin(
+ req('http://canvix.test/api/plugins', {
+ method: 'POST',
+ // same-origin-looking but absolute, and not a bundled slug:
+ // must go through safeFetch with allowFirstParty unset
+ body: '{"manifestUrl":"http://canvix.test/plugins/someone-else/manifest.json"}',
+ }),
+ )
+ expect(res.status).toBe(201)
+ const [url, opts] = calls[0] as [string, { allowFirstParty?: boolean }]
+ expect(url).toBe('http://canvix.test/plugins/someone-else/manifest.json')
+ expect(opts.allowFirstParty).toBeUndefined()
+ })
})
describe('GET /api/plugins/[id]/serve/[...path]', () => {
diff --git a/src/app/api/plugins/route.ts b/src/app/api/plugins/route.ts
index 897d49d..14994f9 100644
--- a/src/app/api/plugins/route.ts
+++ b/src/app/api/plugins/route.ts
@@ -7,8 +7,9 @@ import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'
import { checkRateLimit, rateLimitResponse } from '@/lib/rate-limit'
import { withLogging, APP_VERSION } from '@/lib/observability'
import { PLUGINS_DISABLED, pluginsEnabled } from '@/lib/plugins/flag'
-import { collectBundle } from '@/lib/plugins/install'
+import { collectBundle, type CollectOptions } from '@/lib/plugins/install'
import { describePermission, parsePermission } from '@/lib/plugins/permissions'
+import { bundledSyntheticUrl, isBundledManifestUrl } from '@/lib/plugins/firstparty'
// ─────────────────────────────────────────────────────────────
// /api/plugins — list + install (research §4.2).
@@ -65,6 +66,11 @@ function installSummary(row: {
})
return {
id: row.id,
+ // P5: the service layer keys its iframes on installId — the
+ // projection used to expose only `id`, so every service frame
+ // pointed at /api/plugins/undefined/serve/... and 404'd. Both
+ // names now carry the same value (panels read `id`).
+ installId: row.id,
pluginId: row.pluginId,
name: m.name ?? row.pluginId,
description: m.description ?? null,
@@ -126,9 +132,38 @@ async function __canvix_post(req: NextRequest) {
}
const hostVersion = APP_VERSION.includes('.') ? APP_VERSION : '0.13.0'
- const collected = await collectBundle(manifestUrl, {
- hostAppVersion: hostVersion,
- })
+
+ // P5: first-party bundled plugins install through the same rail,
+ // from the strict relative form /plugins/<slug>/manifest.json.
+ // A relative URL is same-origin by construction, and the files are
+ // read from this instance's own public/ directory — no network
+ // hop at all, so the SSRF guard's (correct) loopback denial never
+ // applies, and ONLY this branch may carry a com.canvix.* id.
+ const opts: CollectOptions = { hostAppVersion: hostVersion }
+ let fetchUrl = manifestUrl
+ if (isBundledManifestUrl(manifestUrl)) {
+ const slug = manifestUrl.split('/')[2]
+ opts.allowFirstParty = true
+ try {
+ // lazy import: runtimes without a filesystem (Cloudflare
+ // Workers) keep every other plugin route working — a bundled
+ // install there fails with this honest error instead
+ const { createBundledFetcher } = await import('@/lib/plugins/firstparty-fetch')
+ opts.fetcher = createBundledFetcher()
+ fetchUrl = bundledSyntheticUrl(slug)
+ } catch {
+ return NextResponse.json(
+ {
+ error:
+ 'This Canvix runtime has no filesystem access, so bundled plugins cannot be installed from disk. Serve the plugin from any static host and install it by absolute URL instead.',
+ code: 'E_BUNDLED_UNAVAILABLE',
+ },
+ { status: 422 },
+ )
+ }
+ }
+
+ const collected = await collectBundle(fetchUrl, opts)
if (!collected.ok) {
const status =
collected.error.code === 'E_MANIFEST' || collected.error.code === 'E_URL' ? 422 : 502
diff --git a/src/components/editor/apps/InstalledApps.tsx b/src/components/editor/apps/InstalledApps.tsx
index 6fb58a4..3af6156 100644
--- a/src/components/editor/apps/InstalledApps.tsx
+++ b/src/components/editor/apps/InstalledApps.tsx
@@ -17,9 +17,10 @@
import { useCallback, useEffect, useState } from 'react'
import dynamic from 'next/dynamic'
-import { Puzzle, ShieldCheck, Trash2, Power, Loader2, X, ExternalLink } from 'lucide-react'
+import { Puzzle, ShieldCheck, Trash2, Power, Loader2, X, ExternalLink, Plus } from 'lucide-react'
import { toast } from '@/hooks/use-toast'
import { cn } from '@/lib/utils'
+import { BUNDLED_PLUGINS, bundledManifestUrl } from '@/lib/plugins/firstparty'
import type { PluginInstallView } from './PluginRuntime'
const PluginRuntime = dynamic(() => import('./PluginRuntime').then((m) => m.PluginRuntime), {
@@ -40,10 +41,19 @@ interface InstallSummaryRow {
version: string
enabled: boolean
entry: { panel?: string }
+ /** P5: element kinds + schema — flows into the panel's broker
+ * record so its addPluginElement calls pass the declared-kind check */
+ elements?: { kind: string; label: string; schema?: unknown[] }[]
permissions: { permission: string; description: string }[]
createdAt: string
}
+/** Tell the rest of the editor (the service layer) that the install
+ * list changed mid-session — P5. */
+function broadcastPluginsChanged() {
+ window.dispatchEvent(new CustomEvent('canvix:plugins-changed'))
+}
+
export function InstalledApps() {
const [installs, setInstalls] = useState<InstallSummaryRow[] | null>(null)
const [openId, setOpenId] = useState<string | null>(null)
@@ -80,15 +90,15 @@ export function InstalledApps() {
}
}, [])
- const install = useCallback(async () => {
- const manifestUrl = url.trim()
- if (!manifestUrl) return
+ const install = useCallback(async (manifestUrl: string) => {
+ const target = manifestUrl.trim()
+ if (!target) return
setInstalling(true)
try {
const res = await fetch('/api/plugins', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ manifestUrl }),
+ body: JSON.stringify({ manifestUrl: target }),
})
const data = (await res.json().catch(() => ({}))) as { install?: InstallSummaryRow; error?: string }
if (!res.ok || !data.install) {
@@ -98,12 +108,13 @@ export function InstalledApps() {
setConsent(data.install) // consent screen — permissions verbatim
setUrl('')
await load()
+ broadcastPluginsChanged()
} catch {
toast({ title: 'Could not install this plugin', description: 'Network error — try again.' })
} finally {
setInstalling(false)
}
- }, [url, load])
+ }, [load])
const setEnabled = useCallback(async (row: InstallSummaryRow, enabled: boolean) => {
setInstalls((prev) => (prev ? prev.map((r) => (r.id === row.id ? { ...r, enabled } : r)) : prev))
@@ -115,6 +126,7 @@ export function InstalledApps() {
})
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.' })
+ broadcastPluginsChanged()
} catch {
toast({ title: 'Could not update the plugin' })
await load()
@@ -128,6 +140,7 @@ export function InstalledApps() {
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.' })
+ broadcastPluginsChanged()
} catch {
toast({ title: 'Could not remove the plugin' })
await load()
@@ -147,10 +160,16 @@ export function InstalledApps() {
author: open.author,
grantedPermissions: open.permissions.map((p) => p.permission),
entryPanel: open.entry.panel,
+ elements: open.elements ?? [],
}
return <PluginRuntime install={view} onClose={() => setOpenId(null)} />
}
+ // bundled plugins this instance ships but the user has not installed
+ const bundledAvailable = BUNDLED_PLUGINS.filter(
+ (b) => !installs.some((r) => r.pluginId === b.pluginId),
+ )
+
return (
<section className="mt-4" aria-label="Installed plugin apps">
<div className="flex items-center gap-1.5 mb-2">
@@ -164,14 +183,14 @@ export function InstalledApps() {
value={url}
onChange={(e) => setUrl(e.target.value)}
onKeyDown={(e) => {
- if (e.key === 'Enter') void install()
+ if (e.key === 'Enter') void install(url)
}}
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()}
+ onClick={() => void install(url)}
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"
>
@@ -180,6 +199,29 @@ export function InstalledApps() {
</button>
</div>
+ {bundledAvailable.length > 0 && (
+ <div className="mb-2.5 space-y-1.5" aria-label="Bundled plugin apps">
+ {bundledAvailable.map((b) => (
+ <button
+ key={b.slug}
+ onClick={() => void install(bundledManifestUrl(b.slug))}
+ disabled={installing}
+ className="w-full text-left rounded-xl border border-[#7630D7]/30 bg-[#7630D7]/[0.08] hover:bg-[#7630D7]/[0.16] disabled:opacity-40 p-2.5 transition-colors group"
+ aria-label={`Install ${b.name} (bundled)`}
+ >
+ <div className="flex items-center gap-1.5">
+ <Plus size={11} className="text-[#02C0CC] shrink-0" />
+ <span className="text-[12px] font-semibold text-white group-hover:text-[#02C0CC] transition-colors">
+ {b.name}
+ </span>
+ <span className="text-[9px] font-mono text-white/30 shrink-0">bundled</span>
+ </div>
+ <div className="text-[10px] text-white/40 leading-relaxed">{b.description}</div>
+ </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&apos;ll see exactly what it may access
diff --git a/src/components/editor/apps/PluginRuntime.tsx b/src/components/editor/apps/PluginRuntime.tsx
index 9a70bfd..f77130e 100644
--- a/src/components/editor/apps/PluginRuntime.tsx
+++ b/src/components/editor/apps/PluginRuntime.tsx
@@ -41,6 +41,10 @@ export interface PluginInstallView {
grantedPermissions: string[]
/** manifest entry.panel — relative path inside the bundle */
entryPanel?: string
+ /** P5: element kinds the manifest declares — the panel record must
+ * carry them or the broker refuses its own addPluginElement
+ * calls ("this app does not declare an element kind …") */
+ elements?: { kind: string }[]
}
/** Cryptographically random handshake token (URL-fragment safe). */
@@ -77,6 +81,10 @@ export function PluginRuntime({ install, onClose }: { install: PluginInstallView
pluginId: install.pluginId,
version: install.version,
permissions: install.grantedPermissions,
+ // P5: panels may own element kinds too (the Word Cloud panel
+ // generates 'cloud' elements) — without this the broker's
+ // declared-kind check on addPluginElement always failed
+ elementKinds: (install.elements ?? []).map((e) => e.kind),
}
const broker = new PluginBroker({
install: record,
@@ -85,7 +93,12 @@ export function PluginRuntime({ install, onClose }: { install: PluginInstallView
const s = useEditorStore.getState()
return { pages: s.pages, currentPage: s.currentPage, readOnly: s.readOnly }
},
- applyAction: (action) => applyDesignAction({ ...action, type: String(action.type) }),
+ // P5: forward the broker's caller identity — the two plugin
+ // element actions are scoped to the CALLING install, and the
+ // broker derives that identity from the install row. Dropping
+ // it here made every panel-driven addPluginElement refuse.
+ applyAction: (action, caller) =>
+ applyDesignAction({ ...action, type: String(action.type) }, caller),
notify: (text) => toast({ title: install.name, description: text }),
closePanel: () => onClose(),
logError: (scope, error) => console.error(`[plugin:${install.pluginId}] ${scope}`, error),
diff --git a/src/components/editor/apps/PluginServiceFrame.tsx b/src/components/editor/apps/PluginServiceFrame.tsx
index 575b64e..619e6d9 100644
--- a/src/components/editor/apps/PluginServiceFrame.tsx
+++ b/src/components/editor/apps/PluginServiceFrame.tsx
@@ -19,7 +19,11 @@
import { useCallback, useEffect, useMemo, useRef } from 'react'
import { PluginBroker, type BrokerInstall } from '@/lib/plugins/broker'
import { PluginStorage } from '@/lib/plugins/plugin-storage'
-import { setRenderTransport, type PluginInstallInfo } from '@/lib/plugins/renderer-cache'
+import {
+ notifyRendererKindsChanged,
+ setRenderTransport,
+ type PluginInstallInfo,
+} from '@/lib/plugins/renderer-cache'
import { applyDesignAction } from '@/lib/design-actions'
import { useEditorStore } from '@/store/editor-store'
import { toast } from '@/hooks/use-toast'
@@ -84,6 +88,10 @@ export function PluginServiceFrame({ install }: ServiceFrameProps) {
storage: new PluginStorage(install.pluginId),
hostVersion,
context: 'service',
+ // P5: the moment this frame's renderer registers, renders that
+ // degraded while it was booting get re-attempted (dev cold
+ // compiles of the serve route can outrun the 12 s boot grace)
+ onKindsChanged: () => notifyRendererKindsChanged(install.pluginId),
})
const onMessage = (ev: MessageEvent) => broker.handleMessage(ev)
broker.attach(frame, handshake, onMessage)
diff --git a/src/components/editor/apps/PluginServiceLayer.tsx b/src/components/editor/apps/PluginServiceLayer.tsx
index d9722a2..9c92c14 100644
--- a/src/components/editor/apps/PluginServiceLayer.tsx
+++ b/src/components/editor/apps/PluginServiceLayer.tsx
@@ -58,9 +58,22 @@ export function PluginServiceLayer() {
const pages = useEditorStore((s) => s.pages)
const [installs, setInstalls] = useState<PluginInstallInfo[] | null>(null)
const [off, setOff] = useState(false)
+ const [reloadEpoch, setReloadEpoch] = useState(0)
- // fetch the install list once per editor mount; 503 (flag off) and
- // 401 (signed out) both mean "no plugin system" — state 'off'
+ // P5: InstalledApps broadcasts this after install/uninstall/enable/
+ // disable — without it, a plugin installed mid-session never got a
+ // service frame until the next editor remount (the list used to be
+ // fetched exactly once), so freshly-generated elements sat as
+ // "not responding" placeholders.
+ useEffect(() => {
+ const onPluginsChanged = () => setReloadEpoch((n) => n + 1)
+ window.addEventListener('canvix:plugins-changed', onPluginsChanged)
+ return () => window.removeEventListener('canvix:plugins-changed', onPluginsChanged)
+ }, [])
+
+ // fetch the install list on mount and after every install-list
+ // change; 503 (flag off) and 401 (signed out) both mean "no plugin
+ // system" — state 'off'
useEffect(() => {
let cancelled = false
void fetch('/api/plugins', { cache: 'no-store' })
@@ -89,7 +102,7 @@ export function PluginServiceLayer() {
return () => {
cancelled = true
}
- }, [])
+ }, [reloadEpoch])
// push install state into the renderer cache (placeholder reasons)
useEffect(() => {
diff --git a/src/lib/plugins/broker.ts b/src/lib/plugins/broker.ts
index df1abc5..aa7ecb6 100644
--- a/src/lib/plugins/broker.ts
+++ b/src/lib/plugins/broker.ts
@@ -123,6 +123,11 @@ export interface BrokerOptions {
hostVersion: string
/** 'panel' now; 'service' arrives with P4 renderers */
context?: 'panel' | 'service'
+ /** P5: called when a service broker registers a renderer kind —
+ * the render cache uses it to re-attempt renders that degraded
+ * to "not responding" while this iframe was still booting (dev
+ * cold-compiles of the serve route can outrun the 12 s grace) */
+ onKindsChanged?: () => void
/** injectable clock for tests */
now?: () => number
}
@@ -147,6 +152,7 @@ export class PluginBroker {
private readonly storage: PluginStorage
private readonly hostVersion: string
private readonly context: 'panel' | 'service'
+ private readonly onKindsChanged?: () => void
private readonly now: () => number
private iframeWindow: PostableWindow | null = null
@@ -167,6 +173,7 @@ export class PluginBroker {
this.storage = opts.storage
this.hostVersion = opts.hostVersion
this.context = opts.context ?? 'panel'
+ this.onKindsChanged = opts.onKindsChanged
this.now = opts.now ?? (() => Date.now())
}
@@ -403,6 +410,15 @@ export class PluginBroker {
throw new BrokerError('E_PAYLOAD', `at most ${MAX_REGISTERED_KINDS} kinds may be registered`)
}
this.registeredKinds.add(kind)
+ // P5: the landscape changed — renders that degraded to
+ // "not responding" while this frame booted get re-attempted
+ if (this.onKindsChanged) {
+ try {
+ this.onKindsChanged()
+ } catch {
+ // a listener bug must never break registration
+ }
+ }
}
return { registered: Array.from(this.registeredKinds) }
}
diff --git a/src/lib/plugins/firstparty-fetch.ts b/src/lib/plugins/firstparty-fetch.ts
new file mode 100644
index 0000000..2b513a4
--- /dev/null
+++ b/src/lib/plugins/firstparty-fetch.ts
@@ -0,0 +1,80 @@
+// ─────────────────────────────────────────────────────────────
+// Disk fetcher for bundled plugins (P5) — the server half of
+// firstparty.ts. Imported ONLY by the install route (and its
+// tests): it touches node:fs, so it must never enter a client
+// bundle. It is loaded lazily (dynamic import at the call site),
+// keeping runtimes without a filesystem (Cloudflare Workers)
+// able to serve every other plugin route unaffected — a bundled
+// install there fails with the honest error instead.
+//
+// Security posture: the fetcher answers exactly the FetchLike
+// surface collectBundle needs, and it reads only from
+// `public/plugins/**` — the same bytes the static file server
+// already publishes to the world. Path containment is enforced
+// segment-by-segment (no '..', '.', empty, backslash or NUL
+// segments), and the URL constructor has already percent-decoded,
+// so encoded traversal cannot smuggle through.
+// ─────────────────────────────────────────────────────────────
+
+import { readFile } from 'node:fs/promises'
+import path from 'node:path'
+import type { FetchLike } from './install'
+
+function notFound(url: string): { ok: false; status: number; arrayBuffer(): Promise<ArrayBuffer> } {
+ return {
+ ok: false,
+ status: 404,
+ arrayBuffer: async () => {
+ throw new Error(`bundled file not found: ${url}`)
+ },
+ }
+}
+
+/**
+ * Build the filesystem-backed fetcher for the bundled-plugin
+ * install branch. `cwd` is injectable for tests; production reads
+ * against process.cwd() (Next serves public/ from the repo root —
+ * standalone output copies it alongside the server).
+ */
+export function createBundledFetcher(cwd: string = process.cwd()): FetchLike {
+ return async (url) => {
+ let u: URL
+ try {
+ u = new URL(url)
+ } catch {
+ return notFound(url)
+ }
+ const pathname = u.pathname
+ if (!pathname.startsWith('/plugins/')) return notFound(url)
+
+ // segment-wise containment: the URL constructor decoded %XX,
+ // so checking the decoded segments closes encoded traversal
+ const segments = pathname.slice(1).split('/')
+ if (
+ segments.length < 3 ||
+ segments.some(
+ (s) =>
+ s === '' ||
+ s === '.' ||
+ s === '..' ||
+ s.includes('\\') ||
+ s.includes('\0') ||
+ !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(s),
+ )
+ ) {
+ return notFound(url)
+ }
+
+ const fsPath = path.join(cwd, 'public', ...segments)
+ try {
+ const bytes = await readFile(fsPath)
+ const ab = bytes.buffer.slice(
+ bytes.byteOffset,
+ bytes.byteOffset + bytes.byteLength,
+ ) as ArrayBuffer
+ return { ok: true, status: 200, arrayBuffer: async () => ab }
+ } catch {
+ return notFound(url)
+ }
+ }
+}
diff --git a/src/lib/plugins/firstparty.test.ts b/src/lib/plugins/firstparty.test.ts
new file mode 100644
index 0000000..0f6d787
--- /dev/null
+++ b/src/lib/plugins/firstparty.test.ts
@@ -0,0 +1,173 @@
+// ─────────────────────────────────────────────────────────────
+// First-party rail tests (P5). Two layers:
+//
+// A. the SHIPPED bundle is internally consistent — its manifest
+// validates against this very host build (api version, id
+// grammar incl. the reserved com.canvix.* grant, engines
+// range vs the current package.json version), its HTML
+// passes the packaging checks, every file it declares exists
+// on disk, and the whole thing installs through the REAL
+// collectBundle pipeline with the disk fetcher.
+//
+// B. the URL predicate + fetcher boundary — only the strict
+// relative /plugins/<bundled-slug>/manifest.json form counts
+// as first-party; traversal and foreign slugs are refused.
+// ─────────────────────────────────────────────────────────────
+
+import { describe, expect, it } from 'vitest'
+import { existsSync, readFileSync } from 'node:fs'
+import path from 'node:path'
+import { validateManifest, checkEntryHtml, PLUGIN_API_MAJOR, PLUGIN_API_MINOR } from './manifest'
+import { collectBundle } from './install'
+import { isBundledManifestUrl, bundledManifestUrl, bundledSyntheticUrl, BUNDLED_PLUGINS } from './firstparty'
+import { createBundledFetcher } from './firstparty-fetch'
+
+const BUNDLE_DIR = path.join(process.cwd(), 'public/plugins/wordcloud')
+const MANIFEST_PATH = path.join(BUNDLE_DIR, 'manifest.json')
+const RAW = JSON.parse(readFileSync(MANIFEST_PATH, 'utf8')) as {
+ canvixPluginApi: string
+ id: string
+ files: string[]
+ elements: { kind: string; schema: unknown[] }[]
+}
+
+/** The host's own version — what the install route passes. */
+function hostVersion(): string {
+ const pkg = JSON.parse(readFileSync(path.join(process.cwd(), 'package.json'), 'utf8')) as {
+ version: string
+ }
+ return pkg.version
+}
+
+describe('the shipped Word Cloud bundle (A — internal consistency)', () => {
+ it('declares plugin API 1.1 — exactly what this host speaks', () => {
+ // the P5 bug this suite pins: manifest constants must never drift
+ // from the RPC envelope again
+ expect(PLUGIN_API_MAJOR).toBe(1)
+ expect(PLUGIN_API_MINOR).toBeGreaterThanOrEqual(1)
+ expect(RAW.canvixPluginApi).toBe(`${PLUGIN_API_MAJOR}.${PLUGIN_API_MINOR}`)
+ })
+
+ it('validates as a first-party manifest against this exact build', () => {
+ const result = validateManifest(RAW, {
+ hostAppVersion: hostVersion(),
+ allowFirstParty: true,
+ })
+ expect(result.ok, result.ok ? '' : result.errors.join('; ')).toBe(true)
+ if (result.ok) {
+ expect(result.manifest.id).toBe('com.canvix.wordcloud')
+ expect(result.manifest.entry.panel).toBe('panel.html')
+ expect(result.manifest.entry.service).toBe('service.html')
+ expect(result.networkOrigins).toEqual([]) // zero network — the default-deny proof
+ expect(result.manifest.elements[0]?.kind).toBe('cloud')
+ expect(result.manifest.elements[0]?.schema.length).toBe(4)
+ }
+ })
+
+ it('is REFUSED without the first-party grant — com.canvix.* is reserved', () => {
+ const result = validateManifest(RAW, { hostAppVersion: hostVersion() })
+ expect(result.ok).toBe(false)
+ if (!result.ok) {
+ expect(result.errors.join(' ')).toContain('com.canvix')
+ }
+ })
+
+ it('both entry HTML files pass the packaging rules (no inline scripts/handlers)', () => {
+ for (const file of ['panel.html', 'service.html']) {
+ const err = checkEntryHtml(readFileSync(path.join(BUNDLE_DIR, file), 'utf8'))
+ expect(err, `${file}: ${err ?? ''}`).toBeNull()
+ }
+ })
+
+ it('every declared file exists on disk', () => {
+ for (const file of RAW.files) {
+ expect(existsSync(path.join(BUNDLE_DIR, file)), file).toBe(true)
+ }
+ })
+})
+
+describe('the first-party install rail (A — the real pipeline)', () => {
+ it('collects the shipped bundle from disk: manifest + files, sha256-pinned', async () => {
+ const result = await collectBundle(bundledSyntheticUrl('wordcloud'), {
+ hostAppVersion: hostVersion(),
+ allowFirstParty: true,
+ fetcher: createBundledFetcher(),
+ })
+ expect(result.ok, result.ok ? '' : result.error?.message).toBe(true)
+ if (result.ok) {
+ expect(result.bundle.manifest.id).toBe('com.canvix.wordcloud')
+ expect(result.bundle.networkOrigins).toEqual([])
+ expect(result.bundle.assets.length).toBe(RAW.files.length)
+ // byte-pinning is real: the sha matches a fresh digest of the file
+ const panel = result.bundle.assets.find((a) => a.path === 'panel.html')
+ expect(panel).toBeTruthy()
+ expect(panel!.bytes.byteLength).toBeGreaterThan(100)
+ expect(result.bundle.totalBytes).toBeLessThan(100 * 1024)
+ }
+ })
+
+ it('a declared-but-missing file fails honestly (404-shaped, no crash)', async () => {
+ const result = await collectBundle('http://canvix.bundled.internal/plugins/wordcloud/manifest.json', {
+ hostAppVersion: hostVersion(),
+ allowFirstParty: true,
+ // a fetcher that finds nothing — simulates a diskless/partial runtime
+ fetcher: async () => ({
+ ok: false,
+ status: 404,
+ arrayBuffer: async () => {
+ throw new Error('gone')
+ },
+ }),
+ })
+ expect(result.ok).toBe(false)
+ })
+})
+
+describe('the bundled URL predicate (B — the boundary)', () => {
+ it('accepts exactly the strict relative form for bundled slugs', () => {
+ expect(isBundledManifestUrl('/plugins/wordcloud/manifest.json')).toBe(true)
+ expect(isBundledManifestUrl(bundledManifestUrl('wordcloud'))).toBe(true)
+ })
+
+ it('refuses absolute URLs, foreign slugs, traversal and look-alikes', () => {
+ expect(isBundledManifestUrl('https://evil.example/plugins/wordcloud/manifest.json')).toBe(false)
+ expect(isBundledManifestUrl('/plugins/totally-other/manifest.json')).toBe(false)
+ expect(isBundledManifestUrl('/plugins/wordcloud/../wordcloud/manifest.json')).toBe(false)
+ expect(isBundledManifestUrl('/plugins/wordcloud/manifest.canvix.json')).toBe(false)
+ expect(isBundledManifestUrl('/plugins/WordCloud/manifest.json')).toBe(false)
+ expect(isBundledManifestUrl('/plugins/wordcloud/panel.html')).toBe(false)
+ expect(isBundledManifestUrl('')).toBe(false)
+ })
+
+ it('the BUNDLED_PLUGINS list stays in sync with what ships on disk', () => {
+ for (const b of BUNDLED_PLUGINS) {
+ expect(existsSync(path.join(process.cwd(), 'public/plugins', b.slug, 'manifest.json')), b.slug).toBe(true)
+ }
+ })
+})
+
+describe('the disk fetcher (B — containment)', () => {
+ const fetcher = createBundledFetcher()
+
+ it('serves a real file with its bytes', async () => {
+ const res = await fetcher('http://canvix.bundled.internal/plugins/wordcloud/service.js')
+ expect(res.ok).toBe(true)
+ const text = new TextDecoder().decode(await res.arrayBuffer())
+ expect(text).toContain("elements.registerRenderer")
+ })
+
+ it('refuses anything outside /plugins/ and any traversal shape', async () => {
+ for (const url of [
+ 'http://canvix.bundled.internal/package.json',
+ 'http://canvix.bundled.internal/prisma/schema.prisma',
+ 'http://canvix.bundled.internal/plugins/../package.json',
+ 'http://canvix.bundled.internal/plugins/%2e%2e/package.json',
+ 'http://canvix.bundled.internal/plugins/wordcloud/../../src/lib/plugins/manifest.ts',
+ 'http://canvix.bundled.internal/plugins/wordcloud/nope.js',
+ ]) {
+ const res = await fetcher(url)
+ expect(res.ok, url).toBe(false)
+ expect(res.status).toBe(404)
+ }
+ })
+})
diff --git a/src/lib/plugins/firstparty.ts b/src/lib/plugins/firstparty.ts
new file mode 100644
index 0000000..ca027c6
--- /dev/null
+++ b/src/lib/plugins/firstparty.ts
@@ -0,0 +1,79 @@
+// ─────────────────────────────────────────────────────────────
+// First-party bundled plugins (P5, research/PLUGIN-SYSTEM.md §5).
+//
+// Canvix ships a small set of reference plugins in
+// `public/plugins/<slug>/` — plain static files, versioned with the
+// repo, installable through the SAME rail as any third-party
+// plugin (validate → sha256-pin → consent → per-user rows). No
+// separate code path, no extra trust: the only specialness is the
+// reserved `com.canvix.*` id namespace, which the manifest
+// validator grants exactly when the bundle comes from this
+// instance's own `public/` directory.
+//
+// The install URL form is deliberately strict and RELATIVE:
+//
+// /plugins/<slug>/manifest.json
+//
+// A relative URL is same-origin by construction (the browser can
+// only resolve it against the app's own origin), so no Host-header
+// comparison is needed to decide "first-party" — and the files are
+// read from disk by the server, never fetched over the network,
+// so the SSRF guard's (correct) loopback denial never bites. This
+// module is CLIENT-SAFE (no node imports); the disk fetcher lives
+// in firstparty-fetch.ts, imported only by the install route.
+// ─────────────────────────────────────────────────────────────
+
+/** One plugin bundled with this Canvix build. */
+export interface BundledPlugin {
+ /** directory under public/plugins/ — lowercase slug */
+ slug: string
+ /** the manifest's plugin id (reserved com.canvix.* namespace) */
+ pluginId: string
+ name: string
+ description: string
+}
+
+/** The plugins shipped in this repository's public/plugins/. */
+export const BUNDLED_PLUGINS: readonly BundledPlugin[] = [
+ {
+ slug: 'wordcloud',
+ pluginId: 'com.canvix.wordcloud',
+ name: 'Word Cloud',
+ description: 'Turn any text into a seeded word-cloud graphic — bundled, zero network.',
+ },
+]
+
+/** Install URL for a bundled plugin (the strict relative form). */
+export function bundledManifestUrl(slug: string): string {
+ return `/plugins/${slug}/manifest.json`
+}
+
+/** The strict shape a bundled install URL must have. */
+const BUNDLED_URL_RE = /^\/plugins\/([a-z0-9][a-z0-9-]{0,40})\/manifest\.json$/
+
+/**
+ * True when `url` is the relative, same-origin-by-construction
+ * install form of a plugin this build actually bundles.
+ * Anything else — absolute URLs, other paths, traversal — is false.
+ */
+export function isBundledManifestUrl(url: string): boolean {
+ if (typeof url !== 'string') return false
+ const m = BUNDLED_URL_RE.exec(url)
+ if (!m) return false
+ return BUNDLED_PLUGINS.some((b) => b.slug === m[1])
+}
+
+/**
+ * The synthetic absolute origin the disk fetcher serves bundled
+ * files under. `collectBundle` requires an absolute http(s) URL and
+ * resolves every declared file against it; the bundled branch
+ * replaces the network hop entirely, so the host name is inert —
+ * it just needs to be a syntactically valid, obviously-internal
+ * origin that can never collide with a real one.
+ */
+export const BUNDLED_SYNTHETIC_ORIGIN = 'http://canvix.bundled.internal'
+
+/** Absolute (synthetic) manifest URL for the bundled branch. */
+export function bundledSyntheticUrl(slug: string): string {
+ return `${BUNDLED_SYNTHETIC_ORIGIN}${bundledManifestUrl(slug)}`
+}
diff --git a/src/lib/plugins/manifest.ts b/src/lib/plugins/manifest.ts
index ea99e92..1045a56 100644
--- a/src/lib/plugins/manifest.ts
+++ b/src/lib/plugins/manifest.ts
@@ -17,11 +17,17 @@
import { checkCloneSafe } from './data-caps'
import { normalizePermissions } from './permissions'
+import { RPC_API_MAJOR, RPC_API_MINOR } from './rpc'
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
+/** Plugin API version THIS host build speaks (envelope major + additive
+ * minor). Aliased from the RPC envelope's single source of truth —
+ * P5: the constants had drifted (manifest said 1.0 while the broker
+ * already spoke 1.1), so every real `"canvixPluginApi": "1.1"`
+ * manifest was rejected by the install rail even though the host
+ * supported everything it asked for. */
+export const PLUGIN_API_MAJOR = RPC_API_MAJOR
+export const PLUGIN_API_MINOR = RPC_API_MINOR
/** Hard size cap for the manifest JSON itself. */
export const MAX_MANIFEST_BYTES = 64 * 1024
diff --git a/src/lib/plugins/renderer-cache.test.ts b/src/lib/plugins/renderer-cache.test.ts
index d0ab06c..8a33988 100644
--- a/src/lib/plugins/renderer-cache.test.ts
+++ b/src/lib/plugins/renderer-cache.test.ts
@@ -8,6 +8,7 @@ import {
requestRender,
setPluginSystemState,
setRenderTransport,
+ notifyRendererKindsChanged,
getRenderEntry,
type PluginInstallInfo,
type RenderTransport,
@@ -288,3 +289,57 @@ describe('install state store', () => {
expect(getPluginSystemState().installs.size).toBe(0)
})
})
+
+describe('P5 — registration recovers renders that outran the boot grace', () => {
+ it('a settled "not responding" error is re-attempted when kinds register late', async () => {
+ setPluginSystemState('ready', [install()])
+ // the frame is mounted but NOT ready yet (booting — dev cold compile)
+ const booting = fakeTransport({ isHandshaked: false, kinds: new Set() })
+ setRenderTransport('com.example.test', booting)
+
+ const key = renderKey(el(), 'canvas')
+ requestRender(el(), 'canvas')
+ // boot grace expires before the handshake — honest degradation…
+ await vi.advanceTimersByTimeAsync(13_000)
+ expect(getRenderEntry(key)).toMatchObject({ status: 'error' })
+
+ // …and the moment the broker registers its kind, the settled error
+ // is dropped and a re-request goes through the now-ready transport
+ const ready = fakeTransport()
+ setRenderTransport('com.example.test', ready)
+ notifyRendererKindsChanged('com.example.test')
+ expect(getRenderEntry(key)).toBeUndefined() // stale error dropped
+
+ requestRender(el(), 'canvas')
+ const entry = await awaitRender(el(), 'canvas')
+ expect(entry.status).toBe('ok')
+ expect(ready.callPlugin).toHaveBeenCalled()
+ })
+
+ it('OK renders are never dropped by a kinds change (determinism)', async () => {
+ setPluginSystemState('ready', [install()])
+ const t = fakeTransport()
+ setRenderTransport('com.example.test', t)
+ const key = renderKey(el(), 'canvas')
+ requestRender(el(), 'canvas')
+ await vi.advanceTimersByTimeAsync(1_000)
+ expect(getRenderEntry(key)).toMatchObject({ status: 'ok' })
+
+ notifyRendererKindsChanged('com.example.test')
+ expect(getRenderEntry(key)).toMatchObject({ status: 'ok' }) // untouched
+ })
+
+ it('a kinds change never drops ANOTHER plugin\u2019s cells', async () => {
+ setPluginSystemState('ready', [install()])
+ setRenderTransport('com.example.test', fakeTransport())
+ const key = renderKey(el(), 'canvas')
+ requestRender(el(), 'canvas')
+ await vi.advanceTimersByTimeAsync(13_000)
+ // com.example.test rendered fine; simulate a late registration by a
+ // DIFFERENT plugin — our cell must survive untouched
+ const key2 = renderKey(el({ pluginId: 'net.other.plugin', id: 'el_other' }), 'canvas')
+ void key2
+ notifyRendererKindsChanged('net.other.plugin')
+ expect(getRenderEntry(key)).toMatchObject({ status: 'ok' })
+ })
+})
diff --git a/src/lib/plugins/renderer-cache.ts b/src/lib/plugins/renderer-cache.ts
index b3738ca..c2f933d 100644
--- a/src/lib/plugins/renderer-cache.ts
+++ b/src/lib/plugins/renderer-cache.ts
@@ -134,6 +134,23 @@ export function setRenderTransport(pluginId: string, transport: RenderTransport
for (const cb of systemListeners) cb()
}
+/**
+ * P5: a service broker just registered a renderer kind. Renders that
+ * degraded to "not responding" while its iframe was still booting (a
+ * dev-mode cold compile of the serve route can outrun the 12 s boot
+ * grace) get one more attempt — their settled ERROR cells are dropped
+ * and the broker-epoch bump re-kicks every canvas node watching this
+ * plugin. OK renders are never re-requested (deterministic contract).
+ */
+export function notifyRendererKindsChanged(pluginId: string): void {
+ brokerEpoch += 1
+ for (const [key, cell] of renderCache) {
+ if (!key.startsWith(pluginId + '|')) continue
+ if (cell.settled && cell.entry.status === 'error') renderCache.delete(key)
+ }
+ for (const cb of systemListeners) cb()
+}
+
/** Placeholder reason for an element whose plugin cannot render it
* right now (§4.9 matrix). null = render normally. */
export function placeholderReason(el: PluginElement): { reason: 'loading' | 'off' | 'missing' | 'disabled'; label: string } | { reason: 'render'; label: null } | null {
diff --git a/src/lib/plugins/wordcloud.test.ts b/src/lib/plugins/wordcloud.test.ts
new file mode 100644
index 0000000..ebba525
--- /dev/null
+++ b/src/lib/plugins/wordcloud.test.ts
@@ -0,0 +1,235 @@
+// ─────────────────────────────────────────────────────────────
+// Word Cloud layout library tests (P5). The library is the ACTUAL
+// file the shipped plugin loads (public/plugins/wordcloud/
+// wordcloud.js, UMD) — imported here via CommonJS so what we test
+// is byte-for-byte what runs in the sandboxed iframes.
+//
+// The invariants that matter (renderer contract §4.5):
+// 1. DETERMINISM — same data in, byte-identical SVG out (the
+// host's render cache is keyed on a hash of the data; a
+// non-deterministic renderer would poison it)
+// 2. SANITIZER ACCEPTANCE — the output can never be rejected by
+// the P1 accept-or-reject sanitizer (asserted directly, on a
+// battery of inputs incl. hostile words)
+// 3. CONTAINMENT — nothing renders outside the box or the mask
+// 4. CAPS — hostile/large data clamps instead of throwing
+// ─────────────────────────────────────────────────────────────
+
+import { describe, expect, it } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { createRequire } from 'node:module'
+import path from 'node:path'
+import { sanitizePluginSvg } from './sanitize-svg'
+
+// The UMD library executes as CommonJS here (module.exports) and as a
+// classic <script> in the plugin's sandboxed iframes — same bytes.
+const nodeRequire = createRequire(import.meta.url)
+
+interface PlacedWord {
+ text: string
+ cx: number
+ cy: number
+ fontSize: number
+ rotate: number
+ fill: string
+}
+
+const WC = nodeRequire(
+ path.join(process.cwd(), 'public/plugins/wordcloud/wordcloud.js'),
+) as {
+ tokenize: (text: string, extraStops?: string) => { text: string; weight: number }[]
+ toSvg: (data: unknown, width: number, height: number, mode?: string) => string
+ clampData: (
+ data: unknown,
+ ) => { words: { text: string; weight: number }[]; seed: number; density: number; mask: string; palette: string }
+ layout: (data: unknown, width: number, height: number) => PlacedWord[]
+ PALETTES: Record<string, string[]>
+ MASKS: string[]
+ STOPWORDS: Record<string, number>
+}
+
+const WORDS = [
+ { text: 'canvix', weight: 24 },
+ { text: 'design', weight: 18 },
+ { text: 'canvas', weight: 15 },
+ { text: 'plugins', weight: 11 },
+ { text: 'security', weight: 9 },
+ { text: 'sandbox', weight: 7 },
+ { text: 'render', weight: 5 },
+ { text: 'export', weight: 3 },
+]
+
+const BASE_DATA = { words: WORDS, seed: 42, density: 0.7, mask: 'rect', palette: 'canvix' }
+
+describe('tokenize', () => {
+ it('counts frequencies, drops stop words and short tokens, keeps display case', () => {
+ const out = WC.tokenize('The design and the DESIGN; a canvas of Design!', 'canvas')
+ // 'the'/'and'/'a'/'of' are stop words, 'canvas' is a user stop word
+ expect(out).toEqual([{ text: 'design', weight: 3 }])
+ })
+
+ it('caps the result at 150 words, sorted by weight then alphabetically', () => {
+ const text = Array.from({ length: 300 }, (_, i) => `w${i}`).join(' ')
+ const out = WC.tokenize(text)
+ expect(out.length).toBeLessThanOrEqual(150)
+ for (let i = 1; i < out.length; i++) {
+ const prev = out[i - 1]
+ const cur = out[i]
+ const byWeight = cur.weight < prev.weight
+ const sameWeightAlpha = cur.weight === prev.weight && prev.text < cur.text
+ expect(byWeight || sameWeightAlpha).toBe(true)
+ }
+ })
+
+ it('treats punctuation and unicode apostrophes as separators, not words', () => {
+ const out = WC.tokenize("don't stop—me…won't", '')
+ expect(out.map((w: { text: string }) => w.text).sort()).toEqual(["don't", 'stop', "won't"])
+ })
+})
+
+describe('toSvg — determinism (the render-cache contract)', () => {
+ it('returns byte-identical output for the same data', () => {
+ const a = WC.toSvg(BASE_DATA, 640, 400, 'canvas')
+ const b = WC.toSvg(BASE_DATA, 640, 400, 'canvas')
+ expect(a).toBe(b)
+ })
+
+ it('changes when the seed changes, and only then', () => {
+ const a = WC.toSvg(BASE_DATA, 640, 400, 'canvas')
+ const b = WC.toSvg({ ...BASE_DATA, seed: 43 }, 640, 400, 'canvas')
+ const c = WC.toSvg({ ...BASE_DATA, seed: 42 }, 640, 400, 'export')
+ expect(a).not.toBe(b)
+ expect(a).toBe(c) // mode does not alter geometry — deterministic
+ })
+
+ it('renders every word somewhere (8/8 for a roomy box)', () => {
+ const svg = WC.toSvg(BASE_DATA, 800, 500, 'canvas')
+ for (const w of WORDS) {
+ expect(svg).toContain(`>${w.text}<`)
+ }
+ })
+})
+
+describe('toSvg — sanitizer acceptance (asserted, not assumed)', () => {
+ const hostile = [
+ { text: '<script>alert(1)</script>', weight: 9 },
+ { text: 'a&b<c>d"e\'f', weight: 8 },
+ { text: 'xlink:href="javascript:x"', weight: 7 },
+ { text: 'onload=boom', weight: 6 },
+ { text: '</text></svg><script>', weight: 5 },
+ { text: ']]><!-->', weight: 4 },
+ { text: 'macro\u00A0nbsp', weight: 3 },
+ ]
+
+ it('output always passes sanitizePluginSvg — hostile words included', () => {
+ const data = { ...BASE_DATA, words: [...WORDS.slice(0, 4), ...hostile] }
+ for (const mask of WC.MASKS) {
+ for (const palette of Object.keys(WC.PALETTES)) {
+ const svg = WC.toSvg({ ...data, mask, palette }, 600, 380, 'canvas')
+ const clean = sanitizePluginSvg(svg)
+ expect(clean.ok, `mask=${mask} palette=${palette}: ${clean.ok ? '' : clean.error}`).toBe(true)
+ }
+ }
+ })
+
+ it('never emits raw XML-special characters or attr-shaped payloads in text content', () => {
+ const svg = WC.toSvg({ ...BASE_DATA, words: hostile }, 600, 380, 'canvas')
+ // escaped by construction — every hostile word appears as text only
+ expect(svg).not.toMatch(/<(script|foreignObject)/i)
+ // the sanitizer's own attribute-level rules, mirrored: no javascript:
+ // URI and no on*-handler may appear in ATTRIBUTE position
+ expect(svg).not.toMatch(/\s(?:xlink:)?(?:href|src)\s*=\s*["']?\s*javascript\s*:/i)
+ expect(svg).not.toMatch(/\son[a-z]+\s*=/i)
+ // the payloads DID render (as inert, escaped text) — nothing dropped silently
+ expect(svg).toContain('&lt;script&gt;')
+ expect(svg).toContain('a&amp;b&lt;c&gt;')
+ })
+
+ it('empty words render the honest hint, still sanitizer-clean', () => {
+ const svg = WC.toSvg({ ...BASE_DATA, words: [] }, 400, 300, 'canvas')
+ expect(svg).toContain('Word cloud')
+ expect(sanitizePluginSvg(svg).ok).toBe(true)
+ })
+})
+
+describe('toSvg — geometry', () => {
+ it('emits the requested viewBox and machine-independent structure', () => {
+ const svg = WC.toSvg(BASE_DATA, 640, 400, 'canvas')
+ expect(svg.startsWith('<svg xmlns="http://www.w3.org/2000/svg" width="640" height="400"')).toBe(true)
+ expect(svg.trimEnd().endsWith('</svg>')).toBe(true)
+ expect(svg).not.toContain('<?xml')
+ expect(svg).not.toContain('<!--')
+ })
+
+ it('circle mask keeps every placement inside the ellipse', () => {
+ // reconstruct the placed boxes from the layout and re-check
+ const items = WC.layout(WC.clampData({ ...BASE_DATA, mask: 'circle' }), 600, 400)
+ expect(items.length).toBeGreaterThan(3)
+ const rx = (600 / 2) * 0.94
+ const ry = (400 / 2) * 0.94
+ for (const it of items) {
+ // a placement's text box is ~fontSize-tall around (cx, cy)
+ const hw = it.fontSize * 2 // generous half-width bound
+ const hh = it.fontSize * 0.7
+ const dx = hw / rx
+ const dy = hh / ry
+ expect(dx * dx + dy * dy).toBeLessThanOrEqual(1.0001)
+ }
+ })
+
+ it('stays far under the 2 MB output cap even at the word limit', () => {
+ const words = Array.from({ length: 150 }, (_, i) => ({
+ text: `wordnumber${i}extra`,
+ weight: 150 - i,
+ }))
+ const svg = WC.toSvg({ ...BASE_DATA, words }, 1200, 800, 'export')
+ expect(svg.length).toBeLessThan(100 * 1024)
+ expect(sanitizePluginSvg(svg).ok).toBe(true)
+ })
+})
+
+describe('clampData — hostile data never throws', () => {
+ it('normalizes garbage into defaults', () => {
+ const d = WC.clampData(null)
+ expect(d).toEqual({ words: [], seed: 42, density: 0.7, mask: 'rect', palette: 'canvix' })
+ const e = WC.clampData({ words: 'nope', seed: NaN, density: 99, mask: 'star', palette: 'neo' })
+ expect(e.mask).toBe('rect')
+ expect(e.palette).toBe('canvix')
+ expect(e.density).toBe(1)
+ })
+
+ it('caps words at 150, weights at 999, text at 40 chars, seed into range', () => {
+ const words = Array.from({ length: 400 }, () => ({
+ text: 'x'.repeat(120),
+ weight: 10_000,
+ }))
+ const d = WC.clampData({ ...BASE_DATA, words, seed: 999_999 })
+ expect(d.words.length).toBe(150)
+ expect(d.words[0].text.length).toBe(40)
+ expect(d.words[0].weight).toBe(999)
+ expect(d.seed).toBe(9999)
+ })
+
+ it('drops malformed word entries instead of failing', () => {
+ const d = WC.clampData({
+ ...BASE_DATA,
+ words: [null, 5, { text: 'ok', weight: 2 }, { text: '', weight: 3 }, { text: 'noweight' }, { weight: 4 }],
+ })
+ expect(d.words).toEqual([{ text: 'ok', weight: 2 }])
+ expect(() => WC.toSvg(d, 500, 300, 'canvas')).not.toThrow()
+ })
+})
+
+describe('the shipped bundle is internally consistent', () => {
+ it('wordcloud.js parses as the exact file the frames load', () => {
+ // require() above already executed it; assert the file carries no
+ // ESM statement syntax (classic <script> frames cannot import)
+ const src = readFileSync(
+ path.join(process.cwd(), 'public/plugins/wordcloud/wordcloud.js'),
+ 'utf8',
+ )
+ expect(src).not.toMatch(/^\s*import\s/m)
+ expect(src).not.toMatch(/^\s*export\s/m)
+ expect(src).toContain('module.exports')
+ })
+})
diff --git a/tests/e2e-plugins/wordcloud.spec.ts b/tests/e2e-plugins/wordcloud.spec.ts
new file mode 100644
index 0000000..1a9aa70
--- /dev/null
+++ b/tests/e2e-plugins/wordcloud.spec.ts
@@ -0,0 +1,377 @@
+import { expect, test, type Page } from '@playwright/test'
+import { readFileSync } from 'node:fs'
+
+/**
+ * Word Cloud — the v0.13 plugin-system MVP acceptance suite
+ * (research/PLUGIN-SYSTEM.md §5, run with CANVIX_PLUGINS=1 via
+ * playwright.plugins.config.ts).
+ *
+ * The golden path, end to end, in five specs:
+ *
+ * 1. install from the bundled chip → consent screen lists every
+ * permission VERBATIM → the install is listed
+ * 2. mid-session install (the service layer must notice) → panel
+ * handshake → collect this page's text → generate → the service
+ * frame actually RENDERS (console seam) → autosave persists the
+ * element (API truth)
+ * 3. the exported SVG embeds the real cloud — not a placeholder
+ * 4. restyle through the HOST-rendered schema card → disable →
+ * the export degrades to the honest placeholder
+ * 5. a signed-out viewer degrades honestly; uninstall leaves the
+ * design data byte-identical (§4.9 durability)
+ */
+
+// ── fixtures ───────────────────────────────────────────────────
+
+const PAGE_TEXT =
+ 'Canvix makes design feel like play. The canvas is live, the design is yours, ' +
+ 'and every design decision stays yours. Design everywhere, canvas first, play always.'
+
+const CLOUD_ELEMENT = (id: string, name: string, palette = 'canvix') => ({
+ id,
+ type: 'plugin',
+ pluginId: 'com.canvix.wordcloud',
+ kind: 'cloud',
+ pluginVersion: '1.0.0',
+ data: {
+ words: [
+ { text: 'canvix', weight: 24 },
+ { text: 'design', weight: 18 },
+ { text: 'canvas', weight: 15 },
+ { text: 'plugins', weight: 11 },
+ { text: 'security', weight: 9 },
+ { text: 'sandbox', weight: 7 },
+ { text: 'render', weight: 5 },
+ { text: 'export', weight: 3 },
+ ],
+ seed: 42,
+ density: 0.7,
+ mask: 'rect',
+ palette,
+ },
+ x: 120,
+ y: 140,
+ width: 480,
+ height: 300,
+ rotation: 0,
+ opacity: 1,
+ locked: false,
+ visible: true,
+ name,
+ shadow: { enabled: false, color: '#000000', blur: 0, offsetX: 0, offsetY: 0 },
+})
+
+const TEXT_ELEMENT = {
+ id: 'txt_wc_e2e',
+ type: 'text',
+ text: PAGE_TEXT,
+ x: 80,
+ y: 60,
+ width: 400,
+ height: 60,
+ rotation: 0,
+ opacity: 1,
+ locked: false,
+ visible: true,
+ fontSize: 36,
+ fontFamily: 'Inter',
+ bold: false,
+ italic: false,
+ underline: false,
+ strike: false,
+ uppercase: false,
+ fill: '#1F2226',
+ align: 'left',
+ lineHeight: 1.25,
+ letterSpacing: 0,
+ shadow: { enabled: false, color: '#000000', blur: 0, offsetX: 0, offsetY: 0 },
+}
+
+// ── helpers ────────────────────────────────────────────────────
+
+async function register(page: Page, tag: string): Promise<string> {
+ const username = `wc_${tag}_${Date.now().toString(36)}`
+ const res = await page.request.post('/api/auth/register', {
+ data: { username, password: `Wc-E2e-${username}-17!q` },
+ })
+ expect(res.status(), `register ${username}`).toBeLessThan(300)
+ return username
+}
+
+async function createDesign(page: Page, name: string, elements: unknown[]) {
+ const res = await page.request.post('/api/designs', {
+ data: {
+ name,
+ width: 1080,
+ height: 720,
+ pages: [{ id: 'page_wc', background: { type: 'solid', color: '#FFFFFF' }, elements }],
+ },
+ })
+ expect(res.status(), `create design: ${await res.text()}`).toBeLessThan(300)
+ return ((await res.json()) as { id: string }).id
+}
+
+async function openEditor(page: Page, designId: string) {
+ await page.goto(`/design/${designId}`)
+ await page.addStyleTag({ content: 'nextjs-portal { display: none !important; }' })
+ await expect(page.getByLabel('Design canvas')).toBeVisible({ timeout: 60_000 })
+}
+
+/** Install the bundled Word Cloud through the API rail (relative URL). */
+async function installWordCloud(page: Page) {
+ const res = await page.request.post('/api/plugins', {
+ data: { manifestUrl: '/plugins/wordcloud/manifest.json' },
+ })
+ expect(res.status(), `install: ${await res.text()}`).toBeLessThan(300)
+}
+
+async function openAppsPanel(page: Page) {
+ await page.getByRole('button', { name: 'Apps', exact: true }).click()
+ await expect(page.getByPlaceholder('https://example.com/plugin/manifest.json')).toBeVisible()
+}
+
+/** Collect console lines from ANY frame (the service iframe logs its renders). */
+function consoleTape(page: Page): string[] {
+ const lines: string[] = []
+ page.on('console', (m) => lines.push(m.text()))
+ return lines
+}
+
+async function waitForRender(lines: string[], timeoutMs = 30_000): Promise<void> {
+ const start = Date.now()
+ while (Date.now() - start < timeoutMs) {
+ if (lines.some((l) => l.includes('[wordcloud] rendered'))) return
+ await page_sleep(500)
+ }
+ throw new Error(`no [wordcloud] render observed within ${timeoutMs}ms — got: ${lines.slice(-8).join(' | ')}`)
+}
+
+function page_sleep(ms: number): Promise<void> {
+ return new Promise((r) => setTimeout(r, ms))
+}
+
+async function exportSvg(page: Page): Promise<string> {
+ await page.getByRole('button', { name: 'Download', exact: true }).click()
+ await page.getByRole('button', { name: /^SVG\b/ }).click()
+ const [download] = await Promise.all([
+ page.waitForEvent('download'),
+ page.getByRole('button', { name: /Download 1 SVG/i }).click(),
+ ])
+ const path = await download.path()
+ expect(path, 'download landed').toBeTruthy()
+ return readFileSync(path!, 'utf8')
+}
+
+// the four permission lines the consent screen must show VERBATIM
+// (note: the design:write line carries a typographic apostrophe —
+// permissions.ts renders Canvix\u2019s)
+const CONSENT_LINES = [
+ 'Read the design you have open — pages, elements and their properties',
+ 'Add, edit and delete elements in this design (via Canvix’s undoable actions)',
+ 'Add its own element types to the canvas and draw them',
+ 'Remember its settings in this browser (namespaced, 256 KB cap)',
+]
+
+// ── the suite ──────────────────────────────────────────────────
+
+test.describe('Word Cloud bundled plugin — the MVP acceptance (flag ON)', () => {
+ test('install from the bundled chip; consent lists every permission verbatim', async ({ page }) => {
+ await register(page, 'consent')
+ const designId = await createDesign(page, 'cvx_wc_consent', [TEXT_ELEMENT])
+ await openEditor(page, designId)
+ await openAppsPanel(page)
+
+ // the bundled chip
+ const chip = page.getByRole('button', { name: 'Install Word Cloud (bundled)' })
+ await expect(chip).toBeVisible()
+ await chip.click()
+
+ // consent screen — permissions verbatim, in plain language
+ const dialog = page.getByRole('dialog', { name: /Permissions for Word Cloud/ })
+ await expect(dialog).toBeVisible()
+ for (const line of CONSENT_LINES) {
+ await expect(dialog.getByText(line)).toBeVisible()
+ }
+ // zero network permissions — the default-deny proof
+ await expect(dialog.getByText(/Send and receive data with/)).toHaveCount(0)
+
+ await dialog.getByRole('button', { name: 'Keep installed' }).click()
+ await expect(dialog).toBeHidden()
+
+ // listed as installed, openable
+ await expect(page.getByRole('button', { name: 'Open Word Cloud' })).toBeVisible()
+
+ // the API projection the service layer depends on
+ const list = await page.request.get('/api/plugins')
+ expect(list.status()).toBe(200)
+ const body = (await list.json()) as {
+ installs: { installId: string; pluginId: string; elements: { kind: string }[]; entry: { service?: string } }[]
+ }
+ const wc = body.installs.find((i) => i.pluginId === 'com.canvix.wordcloud')
+ expect(wc, 'listed').toBeTruthy()
+ expect(wc!.installId).toBeTruthy() // the bug-2 regression: the layer keys on this
+ expect(wc!.elements[0]?.kind).toBe('cloud')
+ expect(wc!.entry.service).toBe('service.html')
+ })
+
+ test('panel generates a cloud; the service frame renders it; autosave persists it', async ({ page }) => {
+ const lines = consoleTape(page)
+ await register(page, 'golden')
+ const designId = await createDesign(page, 'cvx_wc_golden', [TEXT_ELEMENT])
+
+ // editor FIRST — the install that follows is genuinely mid-session
+ await openEditor(page, designId)
+ await openAppsPanel(page)
+
+ // install through the UI (mid-session — bug 4's regression path)
+ await page.getByRole('button', { name: 'Install Word Cloud (bundled)' }).click()
+ const dialog = page.getByRole('dialog', { name: /Permissions for Word Cloud/ })
+ await dialog.getByRole('button', { name: 'Keep installed' }).click()
+ await expect(page.getByRole('button', { name: 'Open Word Cloud' })).toBeVisible()
+
+ // open the panel (bug 3's regression path: the panel must be able
+ // to generate elements — caller identity + declared kinds)
+ await page.getByRole('button', { name: 'Open Word Cloud' }).click()
+ await expect(page.getByText('Back to apps')).toBeVisible()
+
+ // the panel iframe is identified by its stable title (the host
+ // renders "<name> (sandboxed plugin)")
+ const panel = page.frameLocator('iframe[title="Word Cloud (sandboxed plugin)"]')
+ await expect(panel.locator('#wc-api')).toContainText('plugin API v1', { timeout: 30_000 })
+
+ // collect the page's text through the snapshot API
+ await panel.locator('#wc-use-page').click()
+ await expect(panel.locator('#wc-text')).toHaveValue(/Canvix makes design feel like play/, { timeout: 20_000 })
+ await expect(panel.locator('#wc-status')).toContainText(/Collected 1 text element/)
+
+ // generate → the element lands (and instantly becomes selected — the
+ // panel's selection handler then reports "Selected a cloud…", which is
+ // itself proof the element exists) → the service frame mounts + renders
+ await panel.locator('#wc-add').click()
+ await expect(panel.locator('#wc-status')).toContainText(/Added|Element added|Selected a cloud/, { timeout: 20_000 })
+ await waitForRender(lines)
+
+ // autosave → API truth
+ await page.waitForTimeout(4500)
+ const reread = await page.request.get(`/api/designs/${designId}`)
+ expect(reread.status()).toBe(200)
+ const doc = (await reread.json()) as { pages: { elements: Record<string, unknown>[] }[] }
+ const el = doc.pages[0].elements.find((e) => e.type === 'plugin') as
+ | { pluginId: string; kind: string; data: { words: unknown[]; seed: number } }
+ | undefined
+ expect(el, 'the plugin element was saved').toBeTruthy()
+ expect(el!.pluginId).toBe('com.canvix.wordcloud')
+ expect(el!.kind).toBe('cloud')
+ expect(el!.data.words.length).toBeGreaterThanOrEqual(5)
+ expect(el!.data.seed).toBeGreaterThanOrEqual(1)
+ })
+
+ test('the exported SVG embeds the real cloud', async ({ page }) => {
+ const lines = consoleTape(page)
+ await register(page, 'export')
+ await installWordCloud(page)
+ const designId = await createDesign(page, 'cvx_wc_export', [CLOUD_ELEMENT('plg_wc_export', 'WC export cloud')])
+ await openEditor(page, designId)
+ await waitForRender(lines)
+
+ const svg = await exportSvg(page)
+ // the cloud's words are real SVG text runs…
+ expect(svg).toContain('>canvix<')
+ expect(svg).toContain('>design<')
+ // …and it is NOT the degradation card
+ expect(svg).not.toContain('WC export cloud')
+ })
+
+ test('restyle via the host schema card; disable → placeholder in the export', async ({ page }) => {
+ const lines = consoleTape(page)
+ await register(page, 'restyle')
+ await installWordCloud(page)
+ const designId = await createDesign(page, 'cvx_wc_restyle', [
+ CLOUD_ELEMENT('plg_wc_restyle', 'WC restyle cloud', 'canvix'),
+ ])
+ await openEditor(page, designId)
+ await waitForRender(lines)
+
+ // select the element through the layers tab of the Tools panel
+ // (Konva is DOM-opaque; the topbar also has a "Magic Layers"
+ // button, so the tab is matched exactly)
+ await page.getByRole('button', { name: 'Tools', exact: true }).click()
+ await page.getByRole('button', { name: 'Layers', exact: true }).click()
+ await page.getByText('WC restyle cloud', { exact: true }).click()
+
+ // the HOST-rendered properties slot (manifest schema, no plugin code)
+ const palette = page.getByLabel('Palette')
+ await expect(palette).toBeVisible({ timeout: 10_000 })
+ await palette.selectOption('sunset')
+
+ // autosave → the data changed through the host path
+ await page.waitForTimeout(4500)
+ const reread = await page.request.get(`/api/designs/${designId}`)
+ const doc = (await reread.json()) as { pages: { elements: { id: string; data: { palette: string } }[] }[] }
+ const el = doc.pages[0].elements.find((e) => e.id === 'plg_wc_restyle')
+ expect(el?.data.palette).toBe('sunset')
+
+ // disable the plugin → the export must degrade to the placeholder
+ await page.getByRole('button', { name: 'Apps', exact: true }).click()
+ await page.getByRole('button', { name: 'Disable Word Cloud' }).click()
+ await page.waitForTimeout(1500)
+
+ const svg = await exportSvg(page)
+ expect(svg).toContain('WC restyle cloud') // the honest card names the element
+ expect(svg).not.toContain('>canvix<') // no cloud pixels
+ })
+
+ test('signed-out viewer degrades; uninstall leaves data byte-identical', async ({ page, request }) => {
+ // an OWNERLESS design (created with the cookie-less `request`
+ // fixture) — anyone with the link, signed out included, may open it
+ const created = await request.post('/api/designs', {
+ data: {
+ name: 'cvx_wc_signedout',
+ width: 1080,
+ height: 720,
+ pages: [
+ { id: 'page_wc', background: { type: 'solid', color: '#FFFFFF' }, elements: [CLOUD_ELEMENT('plg_wc_out', 'WC out cloud')] },
+ ],
+ },
+ })
+ expect(created.status(), `ownerless create: ${await created.text()}`).toBeLessThan(300)
+ const designId = ((await created.json()) as { id: string }).id
+
+ const signedOut = await page.context().browser()!.newContext()
+ const outPage = await signedOut.newPage()
+ const errors: string[] = []
+ outPage.on('pageerror', (e) => errors.push(String(e)))
+ await outPage.goto(`/design/${designId}`)
+ await outPage.addStyleTag({ content: 'nextjs-portal { display: none !important; }' })
+ await expect(outPage.getByLabel('Design canvas')).toBeVisible({ timeout: 60_000 })
+ await outPage.waitForTimeout(2000)
+ expect(errors, 'the placeholder path is inert for signed-out viewers').toEqual([])
+ await signedOut.close()
+
+ // uninstall durability: the owner installs, then removes, and the
+ // element survives byte-identical
+ await register(page, 'uninstall')
+ const ownId = await createDesign(page, 'cvx_wc_uninstall', [CLOUD_ELEMENT('plg_wc_un', 'WC un cloud')])
+ await openEditor(page, ownId)
+ await openAppsPanel(page)
+ await page.getByRole('button', { name: 'Install Word Cloud (bundled)' }).click()
+ const dialog = page.getByRole('dialog', { name: /Permissions for Word Cloud/ })
+ await dialog.getByRole('button', { name: 'Keep installed' }).click()
+ await expect(page.getByRole('button', { name: 'Open Word Cloud' })).toBeVisible()
+
+ const before = (await (await page.request.get(`/api/designs/${ownId}`)).json()) as {
+ pages: { elements: unknown[] }[]
+ }
+ const beforeEl = before.pages[0].elements.find((e) => (e as { id?: string }).id === 'plg_wc_un')
+
+ await page.getByRole('button', { name: 'Remove Word Cloud' }).click()
+ await expect(page.getByRole('button', { name: 'Remove Word Cloud' })).toHaveCount(0, { timeout: 10_000 })
+ await page.waitForTimeout(1000)
+
+ const after = (await (await page.request.get(`/api/designs/${ownId}`)).json()) as {
+ pages: { elements: unknown[] }[]
+ }
+ const afterEl = after.pages[0].elements.find((e) => (e as { id?: string }).id === 'plg_wc_un')
+ expect(afterEl, 'uninstall never touches design data').toEqual(beforeEl)
+ })
+})