feat(plugins): let a plugin ship its own settings page

A plugin that declares capabilities.settingsUi: true gets its
client/settings.html framed as a card under Settings -> Plugins — same
opaque-origin sandbox and postMessage bridge as its widget, sized via
trek:resize. Hosts that predate the flag strip it at install, so old
instances keep working and simply don't show the card.
This commit is contained in:
Maurice
2026-07-14 09:58:13 +02:00
parent 4fad7f04a9
commit a907946244
10 changed files with 103 additions and 4 deletions
@@ -97,6 +97,12 @@ interface PluginFrameProps {
fill?: boolean
className?: string
title?: string
/**
* Entry document inside the plugin's client/ dir. Defaults to the widget's
* index.html; the user-settings surface loads settings.html instead. Host-set
* literals only — never user input (it becomes part of the frame URL).
*/
path?: string
}
type Inbound =
@@ -118,7 +124,7 @@ interface ConfirmRequest {
danger: boolean
}
export default function PluginFrame({ pluginId, tripId = null, placeId = null, dayId = null, reservationId = null, fill = false, className, title }: PluginFrameProps) {
export default function PluginFrame({ pluginId, tripId = null, placeId = null, dayId = null, reservationId = null, fill = false, className, title, path = 'index.html' }: PluginFrameProps) {
const frameRef = useRef<HTMLIFrameElement | null>(null)
// A sandboxed frame may navigate ITSELF (connect-src can't stop that), and its
// window identity keeps matching our iframe afterwards. Track loads and refuse
@@ -369,7 +375,7 @@ export default function PluginFrame({ pluginId, tripId = null, placeId = null, d
<iframe
key={pluginId}
ref={frameRef}
src={`/plugin-frame/${pluginId}/index.html`}
src={`/plugin-frame/${pluginId}/${path}`}
// Deliver the context as soon as the document is parsed (the plugin sets up its
// message listener during parse), closing the trek:ready race so the theme is
// right on first paint. A 2nd load is a self-navigation — don't bridge to it.
@@ -1,6 +1,7 @@
import { useEffect, useState } from 'react'
import { Save, Loader2, Link2, Unlink, CheckCircle } from 'lucide-react'
import PluginIcon from '../shared/PluginIcon'
import PluginFrame from '../Plugins/PluginFrame'
import { pluginsApi, type PluginUserSettingField, type PluginAction } from '../../api/client'
import { usePluginStore } from '../../store/pluginStore'
import { useToast } from '../shared/Toast'
@@ -221,6 +222,32 @@ function PluginSettingsForm({ id, name, icon }: { id: string; name: string; icon
)
}
/**
* A plugin's OWN settings surface (capabilities.settingsUi): its sandboxed
* client/settings.html framed inside the familiar settings card. Unlike the
* declared-fields form above, the plugin renders this itself — same opaque-origin
* sandbox and postMessage bridge as its widget, so it can only reach its own
* routes. The frame auto-sizes via trek:resize like a dashboard widget.
*/
function PluginSettingsUiCard({ id, name, icon }: { id: string; name: string; icon: string | null }) {
return (
<div className="rounded-xl border border-border bg-surface p-5">
<div className="flex items-center gap-2 mb-4">
<PluginIcon name={icon} className="w-4 h-4 text-content-secondary" />
<h3 className="text-sm font-semibold text-content">{name}</h3>
</div>
{/* min-height covers the beat before the frame's first trek:resize lands.
color-scheme light on the frame element matches the sandboxed document's
default ("normal"): mismatched schemes make Chromium paint an opaque
white canvas behind the transparent frame (same trap .hero-overlay-frame
guards against), which glares in dark mode. */}
<div className="min-h-[120px]">
<PluginFrame pluginId={id} path="settings.html" title={name} className="[color-scheme:light]" />
</div>
</div>
)
}
export default function PluginSettingsTab() {
const { t } = useTranslation()
const plugins = usePluginStore(s => s.plugins)
@@ -233,7 +260,12 @@ export default function PluginSettingsTab() {
</div>
{plugins.length === 0
? <p className="text-sm text-content-muted">{t('settings.plugins.empty')}</p>
: plugins.map(p => <PluginSettingsForm key={p.id} id={p.id} name={p.name} icon={p.icon} />)}
: plugins.map(p => (
<div key={p.id} className="space-y-4">
<PluginSettingsForm id={p.id} name={p.name} icon={p.icon} />
{p.settingsUi && <PluginSettingsUiCard id={p.id} name={p.name} icon={p.icon} />}
</div>
))}
<PluginActivityPanel />
</div>
)
+2
View File
@@ -17,6 +17,8 @@ export interface ActivePlugin {
* replaces while active ('plan' never — enforced server-side) and its
* preferred 0-based tab index. */
tripPage?: { replaces?: string[]; position?: number }
/** The plugin ships a settings.html the user-settings page frames. */
settingsUi?: true
}
interface PluginState {
+4
View File
@@ -180,7 +180,11 @@ export function validateManifest(raw: unknown): ValidationResult {
notificationChannel?: { title?: unknown; events?: unknown };
provides?: unknown;
emits?: unknown;
settingsUi?: unknown;
} | undefined;
if (capabilities?.settingsUi !== undefined && typeof capabilities.settingsUi !== 'boolean') {
errors.push('capabilities.settingsUi must be a boolean');
}
const widget = capabilities?.widget;
if (widget?.slot !== undefined && widget.slot !== 'sidebar' && widget.slot !== 'hero' && widget.slot !== 'place-detail' && widget.slot !== 'day-detail' && widget.slot !== 'reservation-detail') {
errors.push(`widget slot must be "sidebar", "hero", "place-detail", "day-detail" or "reservation-detail", got "${String(widget.slot)}"`);
+5
View File
@@ -100,6 +100,11 @@ describe('validateManifest', () => {
expect(validateManifest({ ...page, capabilities: { tripPage: { replaces: ['nope'] } } }).ok).toBe(false);
expect(validateManifest({ ...page, capabilities: { tripPage: { position: -1 } } }).ok).toBe(false);
});
it('validates settingsUi as a boolean', () => {
expect(validateManifest({ ...base, capabilities: { settingsUi: true } }).ok).toBe(true);
expect(validateManifest({ ...base, capabilities: { settingsUi: false } }).ok).toBe(true);
expect(validateManifest({ ...base, capabilities: { settingsUi: 'yes' } }).ok).toBe(false);
});
});
describe('createMockHost', () => {
@@ -70,6 +70,8 @@ export interface PluginCapabilities {
provides?: string[];
/** Event names this plugin publishes to its dependents via ctx.events.emit. */
emits?: string[];
/** The plugin ships client/settings.html; the host frames it on the user's settings page. */
settingsUi?: boolean;
}
/** A declared dependency on another plugin, pinned by a semver range. */
@@ -308,6 +310,10 @@ function parseCapabilities(raw: unknown): PluginCapabilities {
}
if (Object.keys(page).length) out.tripPage = page;
}
if (c.settingsUi !== undefined) {
if (typeof c.settingsUi !== 'boolean') throw new ManifestError('capabilities.settingsUi must be a boolean');
if (c.settingsUi) out.settingsUi = true;
}
if (c.notificationChannel && typeof c.notificationChannel === 'object') {
const nc = c.notificationChannel as Record<string, unknown>;
const channel: NotificationChannelCapability = {};
@@ -18,6 +18,8 @@ interface ActivePlugin {
slot: 'sidebar' | 'hero' | 'place-detail' | 'day-detail' | 'reservation-detail';
/** How a trip-page plugin sits in the planner tab bar (replaced core tabs + position). */
tripPage?: { replaces?: string[]; position?: number };
/** The plugin ships a settings.html the user-settings page frames. */
settingsUi?: true;
}
@Controller('api/plugins')
@@ -31,7 +33,12 @@ export class PluginsFeedController {
.all() as Array<Omit<ActivePlugin, 'slot' | 'tripPage'> & { capabilities: string }>;
const plugins = rows.map(({ capabilities, ...p }) => {
const tripPage = p.type === 'trip-page' ? tripPageOf(capabilities) : undefined;
return { ...p, slot: slotOf(capabilities), ...(tripPage ? { tripPage } : {}) };
return {
...p,
slot: slotOf(capabilities),
...(tripPage ? { tripPage } : {}),
...(settingsUiOf(capabilities) ? { settingsUi: true as const } : {}),
};
});
return { plugins };
}
@@ -52,6 +59,15 @@ function slotOf(capabilities: string): ActivePlugin['slot'] {
// must never be steerable by a hand-edited row ('plan' stays unhideable).
const REPLACEABLE_TABS: ReadonlySet<string> = new Set(['transports', 'buchungen', 'listen', 'finanzplan', 'dateien', 'collab']);
function settingsUiOf(capabilities: string): boolean {
try {
const c = JSON.parse(capabilities || '{}') as { settingsUi?: unknown };
return c.settingsUi === true;
} catch {
return false;
}
}
function tripPageOf(capabilities: string): ActivePlugin['tripPage'] {
try {
const c = JSON.parse(capabilities || '{}') as { tripPage?: { replaces?: unknown; position?: unknown } };
@@ -127,6 +127,13 @@ describe('parseManifest capabilities', () => {
expect(() => parseManifest({ ...base, capabilities: { widget: { slot: 'floating' } } })).toThrow(ManifestError);
});
it('parses settingsUi as a strict boolean, dropping false', () => {
expect(parseManifest({ ...base, capabilities: { settingsUi: true } }).capabilities.settingsUi).toBe(true);
// false means "none" — it must not linger in the stored capabilities blob
expect(parseManifest({ ...base, capabilities: { settingsUi: false } }).capabilities.settingsUi).toBeUndefined();
expect(() => parseManifest({ ...base, capabilities: { settingsUi: 'yes' } })).toThrow(ManifestError);
});
it('parses tripPage replaces + position, deduplicated', () => {
const m = parseManifest({ ...base, capabilities: { tripPage: { replaces: ['transports', 'buchungen', 'transports'], position: 1 } } });
expect(m.capabilities.tripPage).toEqual({ replaces: ['transports', 'buchungen'], position: 1 });
@@ -158,6 +158,15 @@ describe('PluginsFeedController (client feed)', () => {
expect(new PluginsFeedController().list().plugins.find((p) => p.id === 'd')?.slot).toBe('day-detail');
});
it('exposes settingsUi only when the capability is exactly true', () => {
testDb.prepare("INSERT INTO plugins (id, name, type, icon, status, capabilities) VALUES ('su','S','widget','Box','active','{\"settingsUi\":true}')").run();
testDb.prepare("INSERT INTO plugins (id, name, type, icon, status, capabilities) VALUES ('no','N','widget','Box','active','{\"settingsUi\":\"yes\"}')").run();
process.env.TREK_PLUGINS_ENABLED = 'true';
const out = new PluginsFeedController().list();
expect(out.plugins.find((p) => p.id === 'su')?.settingsUi).toBe(true);
expect(out.plugins.find((p) => p.id === 'no')?.settingsUi).toBeUndefined();
});
it('exposes the reservation-detail slot (a booking-card widget must not fall back to the dashboard)', () => {
testDb.prepare("INSERT INTO plugins (id, name, type, icon, status, capabilities) VALUES ('r','R','widget','Box','active','{\"widget\":{\"slot\":\"reservation-detail\"}}')").run();
process.env.TREK_PLUGINS_ENABLED = 'true';
+12
View File
@@ -551,6 +551,18 @@ settings are per-user. `secret: true` fields are stored encrypted and delivered
decrypted through `ctx.config` (server-side only) — never to the iframe. Resolved
values arrive in `ctx.config`.
### A custom settings page (`capabilities.settingsUi`)
When declared fields aren't enough — a picker with previews, anything visual —
set `"capabilities": { "settingsUi": true }` and ship a `client/settings.html`.
TREK frames it as a card on the user's **Settings → Plugins** page, in the same
opaque-origin sandbox and postMessage bridge as your widget: it can only reach
your own declared routes (`trek:invoke`), receives `trek:context`, and should
report its height via `trek:resize`. Persist whatever it edits through one of
your own routes (e.g. into your `db:own` database keyed by `req.user.id`) — the
settings page has no special storage powers. Hosts older than this capability
simply ignore the flag, so declaring it never breaks an install.
## Host-brokered OAuth (`ctx.oauth`)
A plugin can act as an OAuth *client* of a third-party service **without ever handling the secrets**. The **host** runs the entire flow — authorize → callback → token exchange → refresh — with PKCE (S256) and a `state` check, and holds the tokens. The plugin only triggers "connect" and reads a **short-lived access token** at runtime.