Canvix — Free & open-source graphic design tool. A community-built Canva alternative with a drag-and-drop editor, templates, shapes, text, images & one-click export. Works on desktop, tablet & mobile.
TypeScript canva-alternativecanvasdesigndesign-tooldrag-and-dropeditorgraphic-designkonvanextjsopen-sourcereactself-hostedtemplatestypescript
feat(v0.13): plugin install rail — CANVIX_PLUGINS flag (default off), POST/GET/PATCH/DELETE /api/plugins, DB-served asset route with per-manifest CSP, sha256-pinned bundles via safeFetch, migration 0006 (P2) (#18)
Ashiq Hussain Mir03107dc63c4b
diff --git a/.dev.vars.example b/.dev.vars.exampleindex 79d7ef3..4e3aa40 100644--- a/.dev.vars.example+++ b/.dev.vars.example@@ -13,3 +13,6 @@ DATABASE_URL=postgresql://postgres.[PROJECT-REF]:[PASSWORD]@aws-0-[REGION].poole# ── AI provider (optional — all local features work without it) ──# ZAI_BASE_URL=# ZAI_API_KEY=++# Plugins (v0.13) — sandboxed third-party apps; default off+# CANVIX_PLUGINS=1diff --git a/.env.example b/.env.exampleindex 14a67d1..8a1ad90 100644--- a/.env.example+++ b/.env.example@@ -68,3 +68,14 @@ DATABASE_URL=postgresql://postgres.[YOUR-PROJECT-REF]:[YOUR-PASSWORD]@aws-0-eu-c# latency probe (no env needed, counts only — never ids).# CANVIX_LOG=requests# CANVIX_ERROR_WEBHOOK_URL=++# ── Plugins (optional, v0.13) ─────────────────────────────────+# The plugin system is OFF unless you opt in. Third-party plugin+# code runs inside a sandboxed iframe and only ever touches data+# through the permission-checked RPC broker — but it is still+# third-party code, so the choice stays yours.+#+# CANVIX_PLUGINS=1 → enable /api/plugins (install/list/+# uninstall) and plugin elements. Values:+# 1 | true | on. Default: off.+# CANVIX_PLUGINS=1diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bf0c5a5..e91e878 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -67,6 +67,54 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).with spec-correct prerelease ordering — no `semver` dependency,per the zero-dependency rule.+## [0.13.1] — 2026-11-02++### Added++- **Plugin system, part 2 of 5 — the install rail (P2).**+ The store half of research §4.2: submit → fetch → validate →+ consent → store. Everything ships behind `CANVIX_PLUGINS`+ (default **off** — the same opt-in pattern as the MCP token;+ with the flag off every plugin route answers 503+ `PLUGINS_DISABLED` and behavior is byte-identical to v0.12.5):+ - **`POST /api/plugins`** — install from a manifest URL. The+ server fetches the manifest + every declared file through+ the existing `safeFetch` SSRF guard (DNS pinning, private-+ range denial, per-hop redirect revalidation), enforcing the+ §4.7 caps: 2 MB total bundle, ≤ 50 files, 10 s per file.+ Each file is sha256-pinned; `.html` files re-pass the P1+ packaging check at install; the whole snapshot lands in one+ transaction (a reinstall atomically replaces the previous+ row — no version mixing, no orphan assets). CSRF + per-IP+ rate limit (`plugins:install`, 10/min) + session required.+ - **`GET /api/plugins`** — the user's installs as a consent+ payload: name/version/author, the file list with integrity+ hashes, and **every permission in plain language** — the+ exact lines the consent screen will show. Never bytes.+ - **`PATCH/DELETE /api/plugins/<installId>`** — the per-plugin+ enable/disable kill switch and uninstall. Uninstall deletes+ the row + assets (FK cascade) and **never touches elements**:+ plugin elements are plain jsonb data and degrade to+ placeholders, not data loss.+ - **`GET /api/plugins/<installId>/serve/<path>`** — the asset+ route: DB-served, extension-allowlisted mime types, sha256+ ETag with 304 revalidation, `nosniff`, and the **per-manifest+ CSP** from the v0.12.1 pre-staged `plugin-csp.ts` — consented+ `network:` origins become `connect-src`, zero grants collapse+ to `'none'`. Documented auth decision: the route is not+ session-gated (sandboxed iframes cannot carry SameSite=Lax+ cookies); the boundary is unguessable cuids ++ `frame-ancestors 'self'` + per-IP rate limiting + the flag,+ and design data never flows through it.+ - **Migration 0006** — `PluginInstall` + `PluginAsset`+ (additive only; rollback = flag off, no data removed).+ - Manifest validator extended with the **`files` list** (the+ install fetch list): safe paths only, entry panel must be+ declared, ≤ 50 files, deduped.+ - New rate-limit buckets `plugins:install` (10/min) and+ `plugins:serve` (600/min); `.env.example` documents+ `CANVIX_PLUGINS`.+## [0.12.5] — 2026-11-02### Addeddiff --git a/README.md b/README.mdindex 2907bd0..bc5ec71 100644--- a/README.md+++ b/README.md@@ -905,7 +905,11 @@ tool descriptions so agents pick the right format.collab parity, and the accept-or-reject renderer-SVG sanitizer —all pinned by a protocol-level security regression suite(20 hostile manifests, 16 hostile SVGs, RPC replay/spoof corpus)- *(v0.13.0)*+ *(v0.13.0)*; the **install rail** (P2) followed — `CANVIX_PLUGINS`+ (default off) gates `/api/plugins` install/list/uninstall ++ a DB-served asset route with the per-manifest CSP,+ sha256-pinned bundles fetched through the SSRF guard+ *(v0.13.1)*- [ ] Mobile editor polish — touch-first selection handles, gesturezoom/pan without modifier keys, bottom-sheet property panels(the responsive groundwork from v0.11.3 makes this tractable)diff --git a/package-lock.json b/package-lock.jsonindex cd5bc13..4918d83 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "canvix",- "version": "0.13.0",+ "version": "0.13.1","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "canvix",- "version": "0.13.0",+ "version": "0.13.1","hasInstallScript": true,"dependencies": {"@imgly/background-removal": "^1.7.0",diff --git a/package.json b/package.jsonindex 9ada1e1..7ce11f4 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "canvix",- "version": "0.13.0",+ "version": "0.13.1","private": false,"description": "Canvix — free & open-source graphic design tool. A community-built Canva alternative.","scripts": {diff --git a/prisma/migrations/0006_plugin_system/migration.sql b/prisma/migrations/0006_plugin_system/migration.sqlnew file mode 100644index 0000000..e0da016--- /dev/null+++ b/prisma/migrations/0006_plugin_system/migration.sql@@ -0,0 +1,37 @@+-- v0.13 — plugin system install records (research/PLUGIN-SYSTEM.md §4.2).+--+-- Per-user snapshots of third-party plugin files, pinned at install+-- (sha256 per asset). Additive only: no existing table is touched, so+-- the rollback story is simply CANVIX_PLUGINS=0 (installs go dormant).+CREATE TABLE "PluginInstall" (+ "id" TEXT NOT NULL,+ "userId" TEXT NOT NULL,+ "pluginId" TEXT NOT NULL,+ "version" TEXT NOT NULL,+ "manifest" JSONB NOT NULL,+ "enabled" BOOLEAN NOT NULL DEFAULT true,+ "createdAt" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updatedAt" TIMESTAMP NOT NULL,+ CONSTRAINT "PluginInstall_pkey" PRIMARY KEY ("id")+);++CREATE TABLE "PluginAsset" (+ "id" TEXT NOT NULL,+ "installId" TEXT NOT NULL,+ "path" TEXT NOT NULL,+ "mime" TEXT NOT NULL,+ "bytes" BYTEA NOT NULL,+ "sha256" TEXT NOT NULL,+ CONSTRAINT "PluginAsset_pkey" PRIMARY KEY ("id")+);++-- one install per (user, plugin); a reinstall replaces the row (and assets)+CREATE UNIQUE INDEX "PluginInstall_userId_pluginId_key" ON "PluginInstall"("userId", "pluginId");+CREATE INDEX "PluginInstall_userId_idx" ON "PluginInstall"("userId");+CREATE UNIQUE INDEX "PluginAsset_installId_path_key" ON "PluginAsset"("installId", "path");++-- referential integrity: deleting an install cascades its assets.+-- (Deleting a USER does not cascade installs — accounts have no+-- hard-delete path in Canvix today; if one appears, sweep first.)+ALTER TABLE "PluginAsset" ADD CONSTRAINT "PluginAsset_installId_fkey"+ FOREIGN KEY ("installId") REFERENCES "PluginInstall"("id") ON DELETE CASCADE ON UPDATE CASCADE;diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex 0e97922..7225fb9 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -208,3 +208,37 @@ model AIUsage {@@index([createdAt])}++// ── v0.13: plugin system (research/PLUGIN-SYSTEM.md §4.2) ────+// A plugin install is a per-user snapshot of a third-party plugin's+// files, pinned at install time (sha256 per file). After install the+// instance is fully offline — the runtime never fetches anything.+// Updates are explicit reinstalls; `enabled` is the user's kill switch+// and CANVIX_PLUGINS=0 the instance-wide one. Elements created by a+// plugin survive uninstall (they are plain elements in design jsonb).+model PluginInstall {+ id String @id @default(cuid())+ userId String+ pluginId String+ version String+ manifest Json+ enabled Boolean @default(true)+ assets PluginAsset[]+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ @@unique([userId, pluginId])+ @@index([userId])+}++model PluginAsset {+ id String @id @default(cuid())+ installId String+ install PluginInstall @relation(fields: [installId], references: [id], onDelete: Cascade)+ path String+ mime String+ bytes Bytes+ sha256 String++ @@unique([installId, path])+}diff --git a/src/app/api/plugins/[installId]/route.ts b/src/app/api/plugins/[installId]/route.tsnew file mode 100644index 0000000..829b3f8--- /dev/null+++ b/src/app/api/plugins/[installId]/route.ts@@ -0,0 +1,80 @@+import { NextRequest, NextResponse } from 'next/server'+import { db } from '@/lib/db'+import { dbErrorResponse } from '@/lib/db-errors'+import { getSessionUser } from '@/lib/auth/session'+import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'+import { withLogging } from '@/lib/observability'+import { PLUGINS_DISABLED, pluginsEnabled } from '@/lib/plugins/flag'++// ─────────────────────────────────────────────────────────────+// /api/plugins/<installId> — the user's controls on one install+// (research §4.2/§4.3):+//+// PATCH { enabled: boolean } → the per-plugin kill switch+// DELETE → uninstall (row + assets)+//+// Uninstall NEVER deletes elements — plugin elements are plain+// elements in design jsonb; worst case they degrade to+// placeholders (P4). Data is never the price of an uninstall.+// ─────────────────────────────────────────────────────────────++function notEnabled() {+ return NextResponse.json(PLUGINS_DISABLED, { status: 503 })+}++function unauthorized() {+ return NextResponse.json(+ { error: 'Sign in to manage plugins.', code: 'AUTH_REQUIRED' },+ { status: 401 },+ )+}++async function __canvix_patch(req: NextRequest, { params }: { params: Promise<{ installId: string }> }) {+ if (!pluginsEnabled()) return notEnabled()+ if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })+ const user = await getSessionUser(req)+ if (!user) return unauthorized()+ const { installId } = await params+ try {+ const body = (await req.json().catch(() => ({}))) as { enabled?: unknown }+ if (typeof body.enabled !== 'boolean') {+ return NextResponse.json(+ { error: 'enabled (boolean) is required.', code: 'E_BODY' },+ { status: 400 },+ )+ }+ const row = await db.pluginInstall.updateMany({+ where: { id: installId, userId: user.id },+ data: { enabled: body.enabled },+ })+ if (row.count === 0) {+ return NextResponse.json({ error: 'No such install.', code: 'E_NOT_FOUND' }, { status: 404 })+ }+ return NextResponse.json({ ok: true, enabled: body.enabled })+ } catch (error) {+ return dbErrorResponse(error, 'PATCH /api/plugins/[installId]')+ }+}++async function __canvix_delete(req: NextRequest, { params }: { params: Promise<{ installId: string }> }) {+ if (!pluginsEnabled()) return notEnabled()+ if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })+ const user = await getSessionUser(req)+ if (!user) return unauthorized()+ const { installId } = await params+ try {+ // assets cascade on install delete (FK onDelete: Cascade)+ const row = await db.pluginInstall.deleteMany({+ where: { id: installId, userId: user.id },+ })+ if (row.count === 0) {+ return NextResponse.json({ error: 'No such install.', code: 'E_NOT_FOUND' }, { status: 404 })+ }+ return NextResponse.json({ ok: true })+ } catch (error) {+ return dbErrorResponse(error, 'DELETE /api/plugins/[installId]')+ }+}++export const PATCH = withLogging('PATCH /api/plugins/[installId]', __canvix_patch)+export const DELETE = withLogging('DELETE /api/plugins/[installId]', __canvix_delete)diff --git a/src/app/api/plugins/[installId]/serve/[...path]/route.ts b/src/app/api/plugins/[installId]/serve/[...path]/route.tsnew file mode 100644index 0000000..1e104db--- /dev/null+++ b/src/app/api/plugins/[installId]/serve/[...path]/route.ts@@ -0,0 +1,108 @@+import { NextRequest, NextResponse } from 'next/server'+import { db } from '@/lib/db'+import { dbErrorResponse } from '@/lib/db-errors'+import { withLogging } from '@/lib/observability'+import { checkRateLimit, rateLimitResponse } from '@/lib/rate-limit'+import { PLUGINS_DISABLED, pluginsEnabled } from '@/lib/plugins/flag'+import { mimeForPath } from '@/lib/plugins/install'+import { pluginServeCsp } from '@/lib/security/plugin-csp'++// ─────────────────────────────────────────────────────────────+// GET /api/plugins/<installId>/serve/<path> — the plugin asset+// route (research §4.2/§4.6). Files are served from the Postgres+// snapshot (sha256-pinned at install); the runtime never fetches.+//+// Every response carries the per-manifest CSP built by+// plugin-csp.ts from the CONSENTED network origins — an empty+// grant list collapses connect-src to 'none', which is a real+// exfiltration wall (CSP governs fetch/XHR/beacons in every+// mode, including no-cors).+//+// Auth design (deliberate, documented):+// The route requires NO session. Plugin assets are third-party+// code the user already consented to — not user data — and the+// sandboxed iframe (<iframe sandbox> = opaque origin) cannot+// reliably carry SameSite=Lax cookies on its navigation or+// subresource loads anyway. The boundary that matters:+// · installIds are unguessable cuids+// · frame-ancestors 'self' — only this Canvix may embed it+// · per-IP rate limit ('plugins:serve') bounds scraping+// · CANVIX_PLUGINS off + enabled=false both hard-disable+// Design data NEVER flows through this route (that is the RPC+// broker's job, P3). If per-user asset privacy ever becomes a+// requirement (it is not in the MVP model — plugins are public+// URLs at install time), the upgrade path is short-lived+// signed serve tokens minted by the mounting component.+// ─────────────────────────────────────────────────────────────++async function __canvix_get(+ req: NextRequest,+ { params }: { params: Promise<{ installId: string; path?: string[] }> },+) {+ if (!pluginsEnabled()) {+ return NextResponse.json(PLUGINS_DISABLED, { status: 503 })+ }+ const limit = checkRateLimit(req, 'plugins:serve')+ if (!limit.ok) return rateLimitResponse(limit)+ const { installId, path } = await params+ try {+ // normalize: reject traversal outright, join the segments+ const rel = (path ?? []).join('/')+ if (!rel || rel.includes('..') || rel.includes('\\') || rel.startsWith('/')) {+ return NextResponse.json({ error: 'Bad path.', code: 'E_PATH' }, { status: 400 })+ }+ const mime = mimeForPath(rel)+ if (!mime) {+ return NextResponse.json(+ { error: 'Unsupported file type.', code: 'E_MIME' },+ { status: 415 },+ )+ }++ const install = await db.pluginInstall.findUnique({+ where: { id: installId },+ select: {+ enabled: true,+ manifest: true,+ assets: { where: { path: rel }, select: { bytes: true, sha256: true }, take: 1 },+ },+ })+ if (!install || !install.enabled || install.assets.length === 0) {+ // one shape for "not yours / disabled / missing" — no oracle+ return NextResponse.json({ error: 'No such file.', code: 'E_NOT_FOUND' }, { status: 404 })+ }++ const asset = install.assets[0]+ const manifest = install.manifest as unknown as { permissions?: string[] }+ const networkOrigins = (manifest.permissions ?? [])+ .filter((p) => p.startsWith('network:'))+ .map((p) => p.slice('network:'.length))++ const etag = `"${asset.sha256}"`+ if (req.headers.get('if-none-match') === etag) {+ return new NextResponse(null, {+ status: 304,+ headers: {+ ETag: etag,+ 'Content-Security-Policy': pluginServeCsp(networkOrigins),+ },+ })+ }++ return new NextResponse(Buffer.from(asset.bytes), {+ status: 200,+ headers: {+ 'Content-Type': mime,+ 'Content-Security-Policy': pluginServeCsp(networkOrigins),+ 'Cache-Control': 'private, max-age=300, must-revalidate',+ ETag: etag,+ 'X-Content-Type-Options': 'nosniff',+ 'Referrer-Policy': 'no-referrer',+ },+ })+ } catch (error) {+ return dbErrorResponse(error, 'GET /api/plugins/[installId]/serve/[...path]')+ }+}++export const GET = withLogging('GET /api/plugins/[installId]/serve/[...path]', __canvix_get)diff --git a/src/app/api/plugins/plugins.test.ts b/src/app/api/plugins/plugins.test.tsnew file mode 100644index 0000000..216fb82--- /dev/null+++ b/src/app/api/plugins/plugins.test.ts@@ -0,0 +1,291 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'++// Route tests for the v0.13 plugin API (mocked db + session ++// collectBundle — no network, no Postgres). Invariants:+// 1. CANVIX_PLUGINS off → 503 PLUGINS_DISABLED everywhere+// 2. installs are per-user: 401 without a session, never another+// account's rows+// 3. CSRF on every mutation+// 4. the serve route emits the per-manifest CSP and honors ETag++const dbMock = vi.hoisted(() => ({+ pluginInstall: {+ findMany: vi.fn(),+ findUnique: vi.fn(),+ create: vi.fn(),+ updateMany: vi.fn(),+ deleteMany: vi.fn(),+ },+ pluginAsset: { deleteMany: vi.fn() },+ $transaction: vi.fn(),+}))+vi.mock('@/lib/db', () => ({ db: dbMock }))++const getSessionUser = vi.hoisted(() => vi.fn())+vi.mock('@/lib/auth/session', () => ({ getSessionUser }))++const collectBundleMock = vi.hoisted(() => vi.fn())+vi.mock('@/lib/plugins/install', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/lib/plugins/install')>()),+ collectBundle: collectBundleMock,+ // keep the real mime map — the serve route uses it+}))++import { NextRequest } from 'next/server'+import { GET as listInstalls, POST as installPlugin } from './route'+import { GET as serveAsset } from './[installId]/serve/[...path]/route'++const USER = { id: 'user-1', username: 'plugfan', createdAt: new Date() }++const GOOD_BUNDLE = {+ manifest: {+ canvixPluginApi: '1',+ id: 'net.example.wordcloud',+ name: 'Word Cloud',+ version: '1.0.0',+ engines: { canvix: '>=0.13.0 <0.14.0' },+ entry: { panel: 'panel.html' },+ files: ['panel.html', 'app.js'],+ permissions: ['design:read', 'network:https://api.example.com'],+ elements: [],+ },+ networkOrigins: ['https://api.example.com'],+ assets: [+ { path: 'panel.html', mime: 'text/html; charset=utf-8', bytes: new Uint8Array([60]), sha256: 'a'.repeat(64) },+ { path: 'app.js', mime: 'text/javascript; charset=utf-8', bytes: new Uint8Array([61]), sha256: 'b'.repeat(64) },+ ],+ totalBytes: 1234,+}++function req(url: string, init?: Omit<RequestInit, 'signal' | 'headers'> & { headers?: Record<string, string> }) {+ return new NextRequest(url, {+ ...init,+ headers: { host: 'canvix.test', ...(init?.headers ?? {}) },+ })+}++beforeEach(() => {+ vi.unstubAllEnvs()+ vi.stubEnv('CANVIX_PLUGINS', '1')+ getSessionUser.mockReset().mockResolvedValue(USER)+ dbMock.pluginInstall.findMany.mockReset().mockResolvedValue([])+ dbMock.pluginInstall.findUnique.mockReset().mockResolvedValue(null)+ dbMock.pluginInstall.updateMany.mockReset().mockResolvedValue({ count: 1 })+ dbMock.pluginInstall.deleteMany.mockReset().mockResolvedValue({ count: 1 })+ dbMock.pluginAsset.deleteMany.mockReset().mockResolvedValue({ count: 2 })+ dbMock.$transaction.mockReset().mockImplementation(async (fn) =>+ fn({+ pluginAsset: { deleteMany: dbMock.pluginAsset.deleteMany },+ pluginInstall: {+ deleteMany: dbMock.pluginInstall.deleteMany,+ create: dbMock.pluginInstall.create.mockReset().mockResolvedValue({+ id: 'install-1',+ pluginId: GOOD_BUNDLE.manifest.id,+ version: '1.0.0',+ enabled: true,+ createdAt: new Date(),+ manifest: GOOD_BUNDLE.manifest,+ assets: GOOD_BUNDLE.assets.map((a) => ({ path: a.path, sha256: a.sha256 })),+ }),+ },+ }),+ )+ collectBundleMock.mockReset().mockResolvedValue({ ok: true, bundle: GOOD_BUNDLE })+})++afterEach(() => {+ vi.unstubAllEnvs()+})++describe('flag gating — CANVIX_PLUGINS off disables the whole surface', () => {+ it('every method answers 503 PLUGINS_DISABLED', async () => {+ vi.stubEnv('CANVIX_PLUGINS', '')+ const list = await listInstalls(req('http://canvix.test/api/plugins'))+ expect(list.status).toBe(503)+ await expect(list.json()).resolves.toMatchObject({ code: 'PLUGINS_DISABLED' })++ const post = await installPlugin(+ req('http://canvix.test/api/plugins', { method: 'POST', body: '{"manifestUrl":"https://x/m.json"}' }),+ )+ expect(post.status).toBe(503)++ const serve = await serveAsset(+ req('http://canvix.test/api/plugins/i1/serve/panel.html'),+ { params: Promise.resolve({ installId: 'i1', path: ['panel.html'] }) },+ )+ expect(serve.status).toBe(503)+ })+})++describe('GET /api/plugins — list', () => {+ it('requires a session', async () => {+ getSessionUser.mockResolvedValue(null)+ const res = await listInstalls(req('http://canvix.test/api/plugins'))+ expect(res.status).toBe(401)+ })++ it('returns the consent payload: permissions in plain language, no bytes', async () => {+ dbMock.pluginInstall.findMany.mockResolvedValue([+ {+ id: 'install-1',+ pluginId: 'net.example.wordcloud',+ version: '1.0.0',+ enabled: true,+ createdAt: new Date('2026-11-02T00:00:00Z'),+ 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).toHaveLength(1)+ const install = body.installs[0]+ expect(install.name).toBe('Word Cloud')+ expect(install.permissions).toEqual([+ {+ permission: 'design:read',+ description: expect.stringContaining('Read the design'),+ },+ {+ permission: 'network:https://api.example.com',+ description: expect.stringContaining('api.example.com'),+ },+ ])+ expect(JSON.stringify(body)).not.toContain('bytes')+ })+})++describe('POST /api/plugins — install', () => {+ it('enforces CSRF (cross-site origin rejected)', async () => {+ const res = await installPlugin(+ req('http://canvix.test/api/plugins', {+ method: 'POST',+ headers: { origin: 'https://evil.example.com' },+ body: '{"manifestUrl":"https://x/m.json"}',+ }),+ )+ expect(res.status).toBe(403)+ await expect(res.json()).resolves.toMatchObject({ code: 'CSRF_REJECTED' })+ })++ it('requires a session', async () => {+ getSessionUser.mockResolvedValue(null)+ const res = await installPlugin(+ req('http://canvix.test/api/plugins', {+ method: 'POST',+ body: '{"manifestUrl":"https://x/m.json"}',+ }),+ )+ expect(res.status).toBe(401)+ })++ it('rejects a missing manifestUrl', async () => {+ const res = await installPlugin(+ req('http://canvix.test/api/plugins', { method: 'POST', body: '{}' }),+ )+ expect(res.status).toBe(400)+ })++ it('surfaces manifest validation failures as 422 with the plain-language message', async () => {+ collectBundleMock.mockResolvedValue({+ ok: false,+ error: { code: 'E_MANIFEST', message: 'manifest rejected: this plugin needs plugin API v2' },+ })+ const res = await installPlugin(+ req('http://canvix.test/api/plugins', {+ method: 'POST',+ body: '{"manifestUrl":"https://x/m.json"}',+ }),+ )+ expect(res.status).toBe(422)+ await expect(res.json()).resolves.toMatchObject({ code: 'E_MANIFEST' })+ })++ it('stores a pinned snapshot: manifest + assets with sha256, 201', async () => {+ const res = await installPlugin(+ req('http://canvix.test/api/plugins', {+ method: 'POST',+ body: '{"manifestUrl":"https://x/m.json"}',+ }),+ )+ expect(res.status).toBe(201)+ const body = await res.json()+ expect(body.install.pluginId).toBe('net.example.wordcloud')+ expect(body.files).toEqual([+ { path: 'panel.html', sha256: 'a'.repeat(64) },+ { path: 'app.js', sha256: 'b'.repeat(64) },+ ])+ expect(body.networkOrigins).toEqual(['https://api.example.com'])+ // the transaction replaced any prior install of the same plugin id+ expect(dbMock.pluginInstall.deleteMany).toHaveBeenCalledWith({+ where: { userId: USER.id, pluginId: 'net.example.wordcloud' },+ })+ expect(dbMock.pluginAsset.deleteMany).toHaveBeenCalledWith({+ where: { install: { userId: USER.id, pluginId: 'net.example.wordcloud' } },+ })+ })+})++describe('GET /api/plugins/[id]/serve/[...path]', () => {+ function serveReq(url: string, headers: Record<string, string> = {}) {+ const m = url.match(/\/api\/plugins\/([^/]+)\/serve\/(.+)$/)!+ return [+ req(url, { headers }),+ { params: Promise.resolve({ installId: m[1], path: m[2].split('/') }) },+ ] as const+ }++ it('rejects traversal paths and unsupported extensions', async () => {+ const bad1 = await serveAsset(...serveReq('http://canvix.test/api/plugins/i1/serve/../secret.env'))+ expect(bad1.status).toBe(400)+ const bad2 = await serveAsset(...serveReq('http://canvix.test/api/plugins/i1/serve/app.exe'))+ expect(bad2.status).toBe(415)+ })++ it('404s (one shape) for unknown install, disabled install, missing file', async () => {+ dbMock.pluginInstall.findUnique.mockResolvedValue(null)+ const res = await serveAsset(...serveReq('http://canvix.test/api/plugins/nope/serve/panel.html'))+ expect(res.status).toBe(404)++ dbMock.pluginInstall.findUnique.mockResolvedValue({+ enabled: false,+ manifest: GOOD_BUNDLE.manifest,+ assets: [],+ })+ const res2 = await serveAsset(...serveReq('http://canvix.test/api/plugins/i1/serve/panel.html'))+ expect(res2.status).toBe(404)+ })++ it('serves bytes with the per-manifest CSP, ETag, nosniff and 304 revalidation', async () => {+ dbMock.pluginInstall.findUnique.mockResolvedValue({+ enabled: true,+ manifest: GOOD_BUNDLE.manifest,+ assets: [{ bytes: Buffer.from('<html></html>'), sha256: 'c'.repeat(64) }],+ })+ const res = await serveAsset(...serveReq('http://canvix.test/api/plugins/i1/serve/panel.html'))+ expect(res.status).toBe(200)+ expect(res.headers.get('content-security-policy')).toBe(+ "default-src 'none'; script-src 'self'; style-src 'unsafe-inline'; img-src data: blob:; connect-src https://api.example.com; font-src data:; frame-ancestors 'self'; form-action 'none'; base-uri 'none'",+ )+ expect(res.headers.get('etag')).toBe(`"${'c'.repeat(64)}"`)+ expect(res.headers.get('x-content-type-options')).toBe('nosniff')+ expect(res.headers.get('cache-control')).toContain('private')++ const res304 = await serveAsset(+ ...serveReq('http://canvix.test/api/plugins/i1/serve/panel.html', {+ 'if-none-match': `"${'c'.repeat(64)}"`,+ }),+ )+ expect(res304.status).toBe(304)+ })++ it('zero network grants collapse connect-src to none — the exfil wall', async () => {+ dbMock.pluginInstall.findUnique.mockResolvedValue({+ enabled: true,+ manifest: { ...GOOD_BUNDLE.manifest, permissions: ['design:read'] },+ assets: [{ bytes: Buffer.from('console.log(1)'), sha256: 'd'.repeat(64) }],+ })+ const res = await serveAsset(...serveReq('http://canvix.test/api/plugins/i1/serve/app.js'))+ expect(res.headers.get('content-security-policy')).toContain("connect-src 'none'")+ })+})diff --git a/src/app/api/plugins/route.ts b/src/app/api/plugins/route.tsnew file mode 100644index 0000000..433a37c--- /dev/null+++ b/src/app/api/plugins/route.ts@@ -0,0 +1,180 @@+import { NextRequest, NextResponse } from 'next/server'+import type { Prisma } from '@/generated/prisma/client'+import { db } from '@/lib/db'+import { dbErrorResponse } from '@/lib/db-errors'+import { getSessionUser } from '@/lib/auth/session'+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 { describePermission, parsePermission } from '@/lib/plugins/permissions'++// ─────────────────────────────────────────────────────────────+// /api/plugins — list + install (research §4.2).+//+// GET /api/plugins → this user's installs (metadata ++// consent-screen payload, never bytes)+// POST /api/plugins → install from a manifest URL:+// safeFetch → validate → pin → store+//+// Gating: CANVIX_PLUGINS (default off) → 503 for every method.+// Auth: installs are per-user rows — a signed-in session is+// required (401 otherwise). CSRF: same-origin on the POST (the+// existing discipline). Rate: 'plugins:install' per IP.+//+// Consent happens CLIENT-side between POST and use: the response+// carries the full manifest + plain-language permission lines so+// the UI can show exactly what is being granted before the first+// iframe ever mounts. The install row is the grant of record.+// ─────────────────────────────────────────────────────────────++function notEnabled() {+ return NextResponse.json(PLUGINS_DISABLED, { status: 503 })+}++function unauthorized() {+ return NextResponse.json(+ { error: 'Sign in to manage plugins.', code: 'AUTH_REQUIRED' },+ { status: 401 },+ )+}++/** The client-facing projection of an install row (no bytes, no userId). */+function installSummary(row: {+ id: string+ pluginId: string+ version: string+ enabled: boolean+ createdAt: Date+ manifest: Prisma.JsonValue+}) {+ const m = row.manifest as unknown as {+ name?: string+ description?: string+ author?: { name?: string }+ permissions?: string[]+ entry?: { panel?: string }+ }+ const permissions = (m.permissions ?? []).map((p) => {+ const parsed = parsePermission(p)+ return parsed+ ? { permission: parsed.permission, description: describePermission(parsed) }+ : { permission: p, description: p }+ })+ return {+ id: row.id,+ pluginId: row.pluginId,+ name: m.name ?? row.pluginId,+ description: m.description ?? null,+ author: m.author?.name ?? null,+ version: row.version,+ enabled: row.enabled,+ entry: m.entry ?? {},+ permissions,+ createdAt: row.createdAt,+ }+}++async function __canvix_get(req: NextRequest) {+ if (!pluginsEnabled()) return notEnabled()+ const user = await getSessionUser(req)+ if (!user) return unauthorized()+ try {+ const rows = await db.pluginInstall.findMany({+ where: { userId: user.id },+ orderBy: { createdAt: 'desc' },+ select: {+ id: true,+ pluginId: true,+ version: true,+ enabled: true,+ createdAt: true,+ manifest: true,+ },+ })+ return NextResponse.json({ installs: rows.map(installSummary) })+ } catch (error) {+ return dbErrorResponse(error, 'GET /api/plugins')+ }+}++async function __canvix_post(req: NextRequest) {+ if (!pluginsEnabled()) return notEnabled()+ if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })+ const limit = checkRateLimit(req, 'plugins:install')+ if (!limit.ok) return rateLimitResponse(limit)+ const user = await getSessionUser(req)+ if (!user) return unauthorized()+ try {+ const body = (await req.json().catch(() => ({}))) as { manifestUrl?: unknown }+ const manifestUrl = typeof body.manifestUrl === 'string' ? body.manifestUrl.trim() : ''+ if (!manifestUrl) {+ return NextResponse.json(+ { error: 'manifestUrl is required.', code: 'E_URL' },+ { status: 400 },+ )+ }++ const hostVersion = APP_VERSION.includes('.') ? APP_VERSION : '0.13.0'+ const collected = await collectBundle(manifestUrl, {+ hostAppVersion: hostVersion,+ })+ if (!collected.ok) {+ const status =+ collected.error.code === 'E_MANIFEST' || collected.error.code === 'E_URL' ? 422 : 502+ return NextResponse.json(+ { error: collected.error.message, code: collected.error.code },+ { status },+ )+ }++ const { manifest, networkOrigins, assets, totalBytes } = collected.bundle++ // one row per (userId, pluginId): a reinstall atomically replaces+ // the previous snapshot — no version mixing, no orphan assets+ const row = await db.$transaction(async (tx) => {+ await tx.pluginAsset.deleteMany({+ where: { install: { userId: user.id, pluginId: manifest.id } },+ })+ await tx.pluginInstall.deleteMany({+ where: { userId: user.id, pluginId: manifest.id },+ })+ return tx.pluginInstall.create({+ data: {+ userId: user.id,+ pluginId: manifest.id,+ version: manifest.version,+ manifest: manifest as unknown as Prisma.InputJsonValue,+ enabled: true,+ assets: {+ create: assets.map((a) => ({+ path: a.path,+ mime: a.mime,+ bytes: Buffer.from(a.bytes),+ sha256: a.sha256,+ })),+ },+ },+ include: { assets: { select: { path: true, sha256: true } } },+ })+ })++ return NextResponse.json(+ {+ install: installSummary(row),+ files: row.assets.map((a) => ({ path: a.path, sha256: a.sha256 })),+ networkOrigins,+ totalBytes,+ },+ { status: 201 },+ )+ } catch (error) {+ return dbErrorResponse(error, 'POST /api/plugins')+ }+}++// v0.12.5 (H7): opt-in request logging wrapper — passthrough+// unless CANVIX_LOG=requests (see src/lib/observability.ts)+export const GET = withLogging('GET /api/plugins', __canvix_get)+export const POST = withLogging('POST /api/plugins', __canvix_post)diff --git a/src/lib/plugins/flag.ts b/src/lib/plugins/flag.tsnew file mode 100644index 0000000..f3f3d20--- /dev/null+++ b/src/lib/plugins/flag.ts@@ -0,0 +1,22 @@+// ─────────────────────────────────────────────────────────────+// CANVIX_PLUGINS — the instance-wide plugin kill switch+// (research §4.2). Default OFF: self-hosters get third-party+// code only when they explicitly ask for it — the same opt-in+// pattern as CANVIX_MCP_TOKEN and the AI keys. With the flag+// off every plugin route answers 503 PLUGINS_DISABLED, the+// runtime import never fires, and behavior is byte-identical+// to a plugin-less Canvix.+// ─────────────────────────────────────────────────────────────++/** True when this instance has opted into the plugin system. */+export function pluginsEnabled(): boolean {+ const v = process.env.CANVIX_PLUGINS+ return v === '1' || v === 'true' || v === 'on'+}++/** Shared 503 body for disabled instances. */+export const PLUGINS_DISABLED = {+ error: 'Plugins are disabled on this instance.',+ code: 'PLUGINS_DISABLED',+ hint: 'Set CANVIX_PLUGINS=1 to enable the plugin system.',+} as constdiff --git a/src/lib/plugins/install.test.ts b/src/lib/plugins/install.test.tsnew file mode 100644index 0000000..6bdcfea--- /dev/null+++ b/src/lib/plugins/install.test.ts@@ -0,0 +1,183 @@+import { describe, expect, it } from 'vitest'+import {+ MAX_BUNDLE_BYTES,+ assetUrl,+ collectBundle,+ mimeForPath,+ type FetchLike,+} from './install'++// The install pipeline with a fake network — the same discipline+// as ssrf-guard.test.ts's transport override. Every cap from §4.7+// is pinned here: 2 MB total, per-file fetch, manifest JSON,+// packaging rules on html files, sha256 pinning.++const HOST = { hostAppVersion: '0.13.0' }++const MANIFEST = {+ canvixPluginApi: '1',+ id: 'net.example.wordcloud',+ name: 'Word Cloud',+ version: '1.0.0',+ engines: { canvix: '>=0.13.0 <0.14.0' },+ entry: { panel: 'panel.html' },+ files: ['panel.html', 'app.js'],+ permissions: ['design:read', 'design:write'],+}++const PANEL_HTML =+ '<!doctype html><html><body><div id="app"></div><script src="app.js"></script></body></html>'+const APP_JS = 'console.log("word cloud")'++function fakeNet(files: Record<string, { body: string; status?: number }>, manifest = MANIFEST): FetchLike {+ return async (url) => {+ if (url.endsWith('manifest.canvix.json')) {+ const status = files['@manifest']?.status ?? 200+ return {+ ok: status === 200,+ status,+ arrayBuffer: async () =>+ new TextEncoder().encode(JSON.stringify(manifest)).buffer as ArrayBuffer,+ }+ }+ for (const [path, file] of Object.entries(files)) {+ if (url.endsWith(path)) {+ return {+ ok: (file.status ?? 200) === 200,+ status: file.status ?? 200,+ arrayBuffer: async () => new TextEncoder().encode(file.body).buffer as ArrayBuffer,+ }+ }+ }+ return { ok: false, status: 404, arrayBuffer: async () => new ArrayBuffer(0) }+ }+}++const URL_ = 'https://plugins.example.net/wordcloud/manifest.canvix.json'++describe('collectBundle — the golden path', () => {+ it('fetches, validates, package-checks and pins every file', async () => {+ const r = await collectBundle(URL_, {+ ...HOST,+ fetcher: fakeNet({ 'panel.html': { body: PANEL_HTML }, 'app.js': { body: APP_JS } }),+ })+ expect(r.ok).toBe(true)+ if (!r.ok) return+ expect(r.bundle.manifest.id).toBe('net.example.wordcloud')+ expect(r.bundle.networkOrigins).toEqual([])+ expect(r.bundle.assets.map((a) => a.path).sort()).toEqual(['app.js', 'panel.html'])+ expect(r.bundle.assets[0].sha256).toMatch(/^[0-9a-f]{64}$/)+ expect(r.bundle.totalBytes).toBeGreaterThan(0)+ })++ it('network permissions flow through to the consent payload', async () => {+ const r = await collectBundle(URL_, {+ ...HOST,+ fetcher: fakeNet(+ { 'panel.html': { body: PANEL_HTML }, 'app.js': { body: APP_JS } },+ { ...MANIFEST, permissions: ['design:read', 'network:https://api.example.com'] },+ ),+ })+ expect(r.ok).toBe(true)+ if (r.ok) expect(r.bundle.networkOrigins).toEqual(['https://api.example.com'])+ })+})++describe('collectBundle — every cap and hostile case', () => {+ it('rejects non-http(s) and unparseable manifest URLs', async () => {+ for (const bad of ['', 'not a url', 'ftp://x/y.json']) {+ const r = await collectBundle(bad, { ...HOST, fetcher: fakeNet({}) })+ expect(r.ok, JSON.stringify(bad)).toBe(false)+ if (!r.ok) expect(r.error.code).toBe('E_URL')+ }+ })++ it('rejects a manifest that is not JSON / not an object / invalid', async () => {+ const notJson: FetchLike = async () => ({+ ok: true,+ status: 200,+ arrayBuffer: async () => new TextEncoder().encode('this is not json').buffer as ArrayBuffer,+ })+ const r1 = await collectBundle(URL_, { ...HOST, fetcher: notJson })+ expect(r1.ok).toBe(false)+ if (!r1.ok) expect(r1.error.code).toBe('E_MANIFEST')++ const r2 = await collectBundle(URL_, {+ ...HOST,+ fetcher: fakeNet({}, { ...MANIFEST, canvixPluginApi: '9' }),+ })+ expect(r2.ok).toBe(false)+ if (!r2.ok) expect(r2.error.message).toMatch(/manifest rejected/)+ })++ it('rejects missing files (404) and fetch failures', async () => {+ const r = await collectBundle(URL_, {+ ...HOST,+ fetcher: fakeNet({ 'panel.html': { body: PANEL_HTML } }), // app.js missing+ })+ expect(r.ok).toBe(false)+ if (!r.ok) {+ expect(r.error.code).toBe('E_FETCH')+ expect(r.error.message).toMatch(/app\.js/)+ }+ })++ it('enforces the 2 MB total cap with a named error', async () => {+ const big = 'x'.repeat(Math.ceil(MAX_BUNDLE_BYTES / 2) + 100)+ const r = await collectBundle(URL_, {+ ...HOST,+ fetcher: fakeNet(+ { 'panel.html': { body: PANEL_HTML }, 'app.js': { body: big }, 'extra.css': { body: big } },+ { ...MANIFEST, files: ['panel.html', 'app.js', 'extra.css'] },+ ),+ })+ expect(r.ok).toBe(false)+ if (!r.ok) expect(r.error.message).toMatch(/bundle exceeds/)+ })++ it('rejects hostile panel HTML at install, not at run', async () => {+ for (const html of [+ '<script>inline()</script>',+ '<img src=x onerror=alert(1)>',+ '<script src="https://evil.example.com/x.js"></script>',+ ]) {+ const r = await collectBundle(URL_, {+ ...HOST,+ fetcher: fakeNet({ 'panel.html': { body: html }, 'app.js': { body: APP_JS } }),+ })+ expect(r.ok, html.slice(0, 40)).toBe(false)+ if (!r.ok) expect(r.error.code).toBe('E_MANIFEST')+ }+ })++ it('never follows an unvalidated redirect chain — safeFetch is the default transport', async () => {+ // (the fake fetcher stands in for safeFetch here; the SSRF+ // guard's own suite pins the redirect/dns behavior)+ const r = await collectBundle(URL_, {+ ...HOST,+ fetcher: async () => ({ ok: false, status: 500, arrayBuffer: async () => new ArrayBuffer(0) }),+ })+ expect(r.ok).toBe(false)+ if (!r.ok) expect(r.error.code).toBe('E_FETCH')+ })+})++describe('assetUrl / mimeForPath', () => {+ it('resolves declared paths against the manifest URL', () => {+ expect(assetUrl('https://x.example/plug/manifest.canvix.json', 'panel.html')).toBe(+ 'https://x.example/plug/panel.html',+ )+ expect(assetUrl('https://x.example/plug/manifest.canvix.json', 'js/app.js')).toBe(+ 'https://x.example/plug/js/app.js',+ )+ })++ it('maps only allowlisted extensions to mime types', () => {+ expect(mimeForPath('a.html')).toContain('text/html')+ expect(mimeForPath('a.js')).toContain('text/javascript')+ expect(mimeForPath('a.woff2')).toBe('font/woff2')+ expect(mimeForPath('a.exe')).toBeNull()+ expect(mimeForPath('a')).toBeNull()+ expect(mimeForPath('a.php')).toBeNull()+ })+})diff --git a/src/lib/plugins/install.ts b/src/lib/plugins/install.tsnew file mode 100644index 0000000..79f68f3--- /dev/null+++ b/src/lib/plugins/install.ts@@ -0,0 +1,192 @@+// ─────────────────────────────────────────────────────────────+// Plugin install pipeline — fetch, validate, pin (research §4.2).+//+// submit → fetch → validate → consent → store+// ^^^^^^^^^^^^^^^^^^ this module (pure, fetcher-injected,+// unit-testable with zero network)+//+// Every network hop goes through the existing safeFetch SSRF guard+// (denylist + DNS pinning + per-hop redirect revalidation). Caps per+// §4.7: 2 MB total bundle, ≤ 50 files (validator), 10 s per file.+// Each file is sha256-pinned at install; the runtime NEVER fetches+// again — a self-hoster's instance is fully offline post-install.+// ─────────────────────────────────────────────────────────────++import { createHash } from 'node:crypto'+import { safeFetch } from '@/lib/mcp/ssrf-guard'+import {+ checkEntryHtml,+ validateManifest,+ type PluginManifest,+ type ValidateManifestOptions,+} from './manifest'++/** Total bundle size cap (§4.7). */+export const MAX_BUNDLE_BYTES = 2 * 1024 * 1024+/** Per-file fetch timeout. */+export const FILE_FETCH_TIMEOUT_MS = 10_000+/** Manifest fetch timeout. */+export const MANIFEST_FETCH_TIMEOUT_MS = 10_000+/** Max bytes for a single file (implied by total, but fail early). */+export const MAX_FILE_BYTES = MAX_BUNDLE_BYTES++export interface BundleAsset {+ path: string+ mime: string+ bytes: Uint8Array+ sha256: string+}++export interface InstalledBundle {+ manifest: PluginManifest+ networkOrigins: string[]+ assets: BundleAsset[]+ totalBytes: number+}++export type InstallError = { code: string; message: string }++/** Content types the serve route may emit (also the validator's extension list). */+export const ASSET_MIME: Record<string, string> = {+ html: 'text/html; charset=utf-8',+ js: 'text/javascript; charset=utf-8',+ mjs: 'text/javascript; charset=utf-8',+ css: 'text/css; charset=utf-8',+ png: 'image/png',+ jpg: 'image/jpeg',+ jpeg: 'image/jpeg',+ gif: 'image/gif',+ svg: 'image/svg+xml',+ json: 'application/json; charset=utf-8',+ txt: 'text/plain; charset=utf-8',+ woff2: 'font/woff2',+ map: 'application/json; charset=utf-8',+ ico: 'image/x-icon',+}++export function mimeForPath(path: string): string | null {+ const ext = path.split('.').pop()?.toLowerCase() ?? ''+ return Object.hasOwn(ASSET_MIME, ext) ? ASSET_MIME[ext] : null+}++/** Minimal Response-ish surface collectBundle needs from a fetcher. */+export interface FetchLike {+ (url: string, init?: { signal?: AbortSignal; redirect?: RequestRedirect }): Promise<{+ ok: boolean+ status: number+ arrayBuffer(): Promise<ArrayBuffer>+ }>+}++export interface CollectOptions extends ValidateManifestOptions {+ /** injectable transport — tests use this; default is safeFetch */+ fetcher?: FetchLike+ /** abort the whole install (user navigated away, request cancelled) */+ signal?: AbortSignal+}++function err(code: string, message: string): { ok: false; error: InstallError } {+ return { ok: false, error: { code, message } }+}++/** Resolve a bundle file path against the manifest URL (no traversal — path is pre-validated). */+export function assetUrl(manifestUrl: string, path: string): string {+ return new URL(path, manifestUrl).toString()+}++/**+ * Fetch and validate a whole plugin bundle from its manifest URL.+ * Returns the pinned assets ready for DB storage, or a typed error.+ */+export async function collectBundle(+ manifestUrl: string,+ opts: CollectOptions,+): Promise<{ ok: true; bundle: InstalledBundle } | { ok: false; error: InstallError }> {+ const doFetch: FetchLike = opts.fetcher ?? ((url, init) => safeFetch(url, init))++ let manifestHref: string+ try {+ manifestHref = new URL(manifestUrl).toString()+ } catch {+ return err('E_URL', 'manifestUrl must be an absolute http(s) URL')+ }+ if (!manifestHref.startsWith('https://') && !manifestHref.startsWith('http://')) {+ return err('E_URL', 'manifestUrl must be http(s)')+ }++ // 1. fetch the manifest+ let manifestRes: Awaited<ReturnType<FetchLike>>+ try {+ manifestRes = await doFetch(manifestHref, {+ signal: AbortSignal.any([AbortSignal.timeout(MANIFEST_FETCH_TIMEOUT_MS), ...(opts.signal ? [opts.signal] : [])]),+ redirect: 'follow',+ })+ } catch {+ return err('E_FETCH', 'could not fetch the manifest (timeout or network error)')+ }+ if (!manifestRes.ok) {+ return err('E_FETCH', `manifest fetch failed with HTTP ${manifestRes.status}`)+ }+ const manifestBuf = await manifestRes.arrayBuffer()+ if (manifestBuf.byteLength > 64 * 1024) {+ return err('E_PAYLOAD', 'manifest is larger than 64 KB')+ }+ let manifestJson: unknown+ try {+ manifestJson = JSON.parse(new TextDecoder().decode(manifestBuf))+ } catch {+ return err('E_MANIFEST', 'manifest is not valid JSON')+ }++ // 2. validate it (all §4.1 rules incl. the files list)+ const result = validateManifest(manifestJson, opts)+ if (!result.ok) {+ return err('E_MANIFEST', `manifest rejected: ${result.errors.join('; ')}`)+ }+ const { manifest, networkOrigins } = result++ // 3. fetch every declared file, cap + sha256 + package-check each+ const assets: BundleAsset[] = []+ let totalBytes = manifestBuf.byteLength+ for (const path of manifest.files) {+ if (opts.signal?.aborted) return err('E_ABORTED', 'install cancelled')+ let res: Awaited<ReturnType<FetchLike>>+ try {+ res = await doFetch(assetUrl(manifestHref, path), {+ signal: AbortSignal.any([AbortSignal.timeout(FILE_FETCH_TIMEOUT_MS), ...(opts.signal ? [opts.signal] : [])]),+ redirect: 'follow',+ })+ } catch {+ return err('E_FETCH', `could not fetch "${path}" (timeout or network error)`)+ }+ if (!res.ok) {+ return err('E_FETCH', `file "${path}" fetch failed with HTTP ${res.status}`)+ }+ const buf = await res.arrayBuffer()+ if (buf.byteLength > MAX_FILE_BYTES) {+ return err('E_PAYLOAD', `file "${path}" is larger than ${Math.round(MAX_FILE_BYTES / 1024)} KB`)+ }+ totalBytes += buf.byteLength+ if (totalBytes > MAX_BUNDLE_BYTES) {+ return err('E_PAYLOAD', `bundle exceeds ${Math.round(MAX_BUNDLE_BYTES / 1024)} KB in total`)+ }+ const mime = mimeForPath(path)+ if (!mime) {+ return err('E_MANIFEST', `file "${path}" has an unsupported extension`)+ }+ const bytes = new Uint8Array(buf)+ // packaging rule on every html file (belt-and-braces for the CSP)+ if (path.endsWith('.html')) {+ const htmlErr = checkEntryHtml(new TextDecoder().decode(bytes))+ if (htmlErr) return err('E_MANIFEST', `"${path}": ${htmlErr}`)+ }+ assets.push({ path, mime, bytes, sha256: sha256Hex(bytes) })+ }++ return { ok: true, bundle: { manifest, networkOrigins, assets, totalBytes } }+}++/** sha256 hex digest of a byte array (the install-time integrity pin). */+export function sha256Hex(bytes: Uint8Array): string {+ return createHash('sha256').update(bytes).digest('hex')+}diff --git a/src/lib/plugins/manifest.test.ts b/src/lib/plugins/manifest.test.tsindex ddf1079..ec95d4b 100644--- a/src/lib/plugins/manifest.test.ts+++ b/src/lib/plugins/manifest.test.ts@@ -16,6 +16,7 @@ const WORDCLOUD = {author: { name: 'Canvix team' },engines: { canvix: '>=0.13.0 <0.14.0' },entry: { panel: 'panel.html' },+ files: ['panel.html', 'app.js'],permissions: ['design:read', 'design:write', 'element:plugin', 'storage'],elements: [{@@ -44,6 +45,7 @@ interface ManifestFixture {engines: { canvix: string }entry: { panel?: string }permissions: string[]+ files?: string[]elements?: Array<{kind: stringlabel: string@@ -175,7 +177,7 @@ describe('validateManifest — structural rules', () => {}})- it('entry paths must be relative and safe', () => {+ it('entry paths must be relative and safe (files list follows the entry)', () => {for (const bad of ['/abs.html', '../escape.html', 'a/../b.html', 'a\\\\b.html', 'no-ext', 'x.ht', 'a//b.html', 'https://evil/x.html']) {const m = base()m.entry = { panel: bad }@@ -184,6 +186,7 @@ describe('validateManifest — structural rules', () => {for (const good of ['panel.html', 'ui/panel.html', 'a/b/c/d/panel.html']) {const m = base()m.entry = { panel: good }+ m.files = [good, 'app.js']expect(validateManifest(m, HOST).ok, `entry "${good}"`).toBe(true)}})diff --git a/src/lib/plugins/manifest.ts b/src/lib/plugins/manifest.tsindex 113467d..d4a0ae8 100644--- a/src/lib/plugins/manifest.ts+++ b/src/lib/plugins/manifest.ts@@ -29,6 +29,8 @@ export const MAX_MANIFEST_BYTES = 64 * 1024export const MAX_ELEMENTS = 20/** Max property fields per element schema. */export const MAX_FIELDS = 24+/** Max files in a plugin bundle (§4.2). */+export const MAX_BUNDLE_FILES = 50const API_RE = /^\d+(\.\d+)?$/const ID_RE = /^[a-z0-9][a-z0-9-]{1,62}(\.[a-z0-9-]+){0,3}$/@@ -37,6 +39,9 @@ const FIELD_KEY_RE = /^[a-z][a-zA-Z0-9]{0,30}$/const HEX_RE = /^#[0-9a-fA-F]{6}$/const ENTRY_PATH_RE = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,118}\.html$/+/** Asset extensions a plugin bundle may ship (§4.2: no zip format — plain files). */+const ASSET_EXT_RE = /\.(html|js|mjs|css|png|jpe?g|gif|svg|json|txt|woff2|map|ico)$/i+export type PluginFieldType = 'text' | 'number' | 'color' | 'select' | 'range'export interface PluginFieldSpec {@@ -67,6 +72,8 @@ export interface PluginManifest {engines: { canvix: string }entry: { panel?: string }permissions: string[]+ /** every file the bundle ships — the install route fetches exactly these */+ files: string[]elements: PluginElementSpec[]}@@ -100,6 +107,22 @@ export function isSafeEntryPath(p: unknown): p is string {return true}+/** Same safety rules for ANY declared bundle asset (any allowlisted extension). */+export function isSafeAssetPath(p: unknown): p is string {+ return (+ typeof p === 'string' &&+ ASSET_EXT_RE.test(p) &&+ !p.includes('..') &&+ !p.includes('\\') &&+ !p.startsWith('/') &&+ /^[A-Za-z0-9][A-Za-z0-9._/-]{0,118}$/.test(p) &&+ (() => {+ const segs = p.split('/')+ return segs.length <= 8 && segs.every((s) => s.length > 0)+ })()+ )+}+/** Validate one field spec; return its error or null. */function validateField(f: unknown, where: string): string | null {if (!isPlainObject(f)) return `${where}: each schema field must be an object`@@ -272,6 +295,32 @@ export function validateManifest(raw: unknown, opts: ValidateManifestOptions): Merrors.push('a plugin must declare entry.panel and/or elements — otherwise it does nothing')}+ // ── files (the install fetch list, §4.2) ──+ const files: string[] = []+ if (raw.files === undefined) {+ if (isPlainObject(entry) && entry.panel !== undefined) {+ errors.push('files must list every file the plugin ships (including "' + String(entry.panel) + '")')+ }+ } else if (!Array.isArray(raw.files) || raw.files.length === 0) {+ errors.push('files must be a non-empty array when present')+ } else if (raw.files.length > MAX_BUNDLE_FILES) {+ errors.push(`at most ${MAX_BUNDLE_FILES} files per plugin`)+ } else {+ const seen = new Set<string>()+ for (const f of raw.files) {+ if (!isSafeAssetPath(f)) {+ errors.push(`files: "${String(f)}" is not a safe relative path with an allowed extension`)+ continue+ }+ if (seen.has(f)) errors.push(`files: duplicate "${f}"`)+ seen.add(f)+ files.push(f)+ }+ if (isPlainObject(entry) && typeof entry.panel === 'string' && !seen.has(entry.panel)) {+ errors.push(`files must include the entry panel "${entry.panel}"`)+ }+ }+// ── permissions ──const perms = normalizePermissions(raw.permissions)if (!perms.ok) {@@ -365,6 +414,7 @@ export function validateManifest(raw: unknown, opts: ValidateManifestOptions): M: {}: {},permissions: perms.ok ? perms.permissions : [],+ files,elements,}return {diff --git a/src/lib/plugins/security-regression.test.ts b/src/lib/plugins/security-regression.test.tsindex d257351..2f407b4 100644--- a/src/lib/plugins/security-regression.test.ts+++ b/src/lib/plugins/security-regression.test.ts@@ -33,6 +33,7 @@ function manifest(overrides: Record<string, unknown>): Record<string, unknown> {version: '1.0.0',engines: { canvix: '>=0.13.0 <0.14.0' },entry: { panel: 'panel.html' },+ files: ['panel.html'],permissions: [],...overrides,}diff --git a/src/lib/rate-limit.ts b/src/lib/rate-limit.tsindex d4c6401..ebefb12 100644--- a/src/lib/rate-limit.ts+++ b/src/lib/rate-limit.ts@@ -38,6 +38,8 @@ export type RateLimitBucket =| 'collab:presence'| 'comments:create'| 'media:init'+ | 'plugins:install'+ | 'plugins:serve'export interface RateLimitConfig {/** window length in milliseconds */@@ -59,6 +61,12 @@ export const RATE_LIMITS: Record<RateLimitBucket, RateLimitConfig> = {'collab:presence': { windowMs: 60_000, max: 120 },'comments:create': { windowMs: 60_000, max: 60 },'media:init': { windowMs: 60_000, max: 30 },+ // installs are rare and heavy (server-side fetch fan-out) — a+ // generous ceiling that still blocks scripted bulk installs+ 'plugins:install': { windowMs: 60_000, max: 10 },+ // one panel mount loads ~5–10 assets; 600/min covers a session+ // of panel open/close without inviting scrape-the-DB abuse+ 'plugins:serve': { windowMs: 60_000, max: 600 },}export function rateLimitsDisabled(): boolean {