Release branch for 4.0.0.
This commit is contained in:
jubnl
2026-08-27 13:22:39 +02:00
committed by GitHub
parent e60427f813
commit 77dddd5e8a
3355 changed files with 403744 additions and 67215 deletions
+59
View File
@@ -0,0 +1,59 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## What this package is
`trek-plugin-sdk` — the author-facing SDK and CLI for building TREK plugins. It lives inside the TREK monorepo but is **not one of the root npm workspaces**: it has its own `package-lock.json`, is versioned and published to npm independently, and must ship standalone (a published copy has no access to the rest of the repo). Run all commands from `plugin-sdk/`, not the repo root. The repo root's CLAUDE.md covers the main app; its conventions (target `dev` branch, conventional commits) still apply.
It ships three bins from one codebase: `trek-plugin-sdk` / `trek-plugin` (same entry, `src/cli/trek-plugin.ts`) and `create-trek-plugin` (`src/cli/create.ts`).
## Commands
```bash
npm install
npm run build # tsc ESM build + tsc CJS build + scripts/finish-cjs.mjs
npm run typecheck # tsc --noEmit
npm test # vitest run
npx vitest run test/sdk.test.ts # single test file
npx vitest run -t "name of the test" # by test-name pattern
node scripts/gen-lucide-icon-names.mjs # regenerate src/lucide-icon-names.ts (uses repo-root lucide-react)
```
Node >= 18. The package is `"type": "module"`; the dual build emits ESM to `dist/` and CJS to `dist/cjs/` (finish-cjs.mjs writes the `{"type":"commonjs"}` scope marker there — without it Node parses the CJS output as ESM).
## The load-bearing principle: mirrored host code + parity tests
The SDK's core promise is that local results equal host/registry results: `dev` enforces what a real TREK enforces, and `validate` passes iff the TREK-Plugins registry CI passes. A drift in the lenient direction is the worst bug in this package — a **false green** lets an author cut an effectively immutable GitHub release (the registry pins its sha256) that the registry then rejects.
Because the package ships standalone, it cannot import server code, so several files are deliberate **copies** of host sources, each guarded by a parity test that reads the original source directly. These tests skip outside the monorepo, but in this checkout they run — keep the pairs in sync when touching either side:
| SDK copy | Source of truth | Parity test |
|---|---|---|
| `src/permissions.ts` (`HOOK_PERMISSION`) | `server/src/nest/plugins/protocol/envelope.ts` via `server/scripts/gen-plugin-facts.ts` | `test/permissions-parity.test.ts` |
| `src/egress-policy.ts` (pure helpers, kept **byte-identical**) | `server/src/nest/plugins/runtime/egress-policy.ts` | `test/permissions-parity.test.ts` |
| `src/manifest.ts` (validation rules, `KNOWN_ADDONS`) | server plugin loader / `server/src/addons.ts` | — kept in sync by hand |
| `src/cli/checks/*` (registry gates) | TREK-Plugins registry repo (`scripts/validate-entry.mjs`, `check-readme.mjs`) | `test/checks-parity.test.ts` (runs the registry's real script; set `TREK_PLUGINS_REPO` to point at a checkout) |
| `src/zip.ts` (ZIP writer) | server `safe-extract.ts` reader | format is frozen against the reader |
`src/permissions.ts` also documents a subtlety worth preserving: ctx methods fail loudly at call time, but hooks/events/jobs are gated *before* the plugin is reached and fail **silently** in production — so the dev server and mock host deliberately make those failures loud (an ungranted `run(def).hook(...)` throws).
**Direction: single-source the contract.** The protocol core — permissions, RPC methods, hooks, the event catalog — is already single-sourced: `src/generated/host-facts.ts` is **machine-written** by `server/scripts/gen-plugin-facts.ts` from `server/src/nest/plugins/protocol/envelope.ts` (never hand-edit it; the server's `check:plugin-facts` CI gate catches drift). The remaining hand-kept copies (egress-policy, manifest rules, registry gates, the ZIP writer) are the residual risk, and the `skipIf(!inMonorepo)` escape hatch means the published SDK's own CI can green-light drift in those — so keep moving copies into the generated/parity-tested set, never away from it. Until then: changing an egress rule, manifest rule, or registry gate means touching **every** copy in one change; parity gates fail closed, never leniently; and version/compat checks fail **closed** on unknown host versions rather than assuming compatibility.
## Architecture
- **`src/index.ts`** — the plugin API surface: all types, `definePlugin`, `PLUGIN_API_VERSION` (bump on any breaking API change). Pure and dependency-free; it mirrors exactly what TREK's isolated plugin runtime injects. Runtime deps for the whole package are only `@clack/prompts`, `semver`, `update-notifier` — keep it that way (e.g. Playwright for `shot` is intentionally the author's devDependency, and the ZIP writer is in-tree instead of a dependency).
- **Two package exports**: `.` (the SDK) and `./testing` (`src/mock-host.ts`) — a mock `PluginContext` + driver enforcing the same permission model against configured fixtures.
- **`src/cli/`** — one file per command, dispatched by `trek-plugin.ts`; `menu.ts` is the no-command guided menu. Interactive TTY sessions get prompts; non-TTY (CI, pipes) stays flag-driven — machine output (`entry` JSON, `pack --json`, PR URLs) goes to stdout, notices to stderr.
- **`src/cli/checks/`** — one check registry, two depths: `runOffline` (synchronous on purpose, so `packPluginDir` can validate before zipping without going async) and `runAll` (adds the GitHub-dependent gates used by `preflight`/`publish`). Printing lives in `report.ts`: `status` renders the checklist and never exits non-zero; `validate` is the same checks with an exit code.
- **`src/ui/kit.ts`** — the design kit (`TREK_UI_CSS`, `TREK_THEME_JS`) as plain strings, inlined into a plugin's `client/index.html` where the `<!-- trek:ui -->` marker sits (`dev`/`pack` expand it; the opaque-origin iframe CSP forbids external link/script). Not a security boundary.
- **`src/lucide-icon-names.ts`** — generated snapshot (see command above); an unknown icon is a validate **warning**, never an error.
- **`test/helpers.ts`** — `makePublishable(dir)` turns a fresh scaffold into a registry-passing plugin (README with per-permission lines, ≥400 prose chars, screenshot); the scaffold deliberately fails publish gates, so tests choose "fresh" vs "publishable" explicitly.
- **`examples/`** — complete example plugins (`trip-doctor`, `koffi`).
## Behavioral contracts to not break
- `status` never exits non-zero; `validate` is the enforcing form.
- `publish` order is check → pack → release → preflight → submit, and a check failure must stop anything from being tagged/released (releases are immutable in practice).
- Signed → unsigned is refused forever; unsigned → signed is always allowed.
- Update notices (update-notifier) print to stderr only and are silent in CI/`NODE_ENV=test`/non-TTY, so JSON output stays pipeable.
+97 -2
View File
@@ -76,6 +76,28 @@ const data = await trek.invoke('/status') // calls your own route, host-proxie
trek.notify('success', 'Saved')
```
### Keep UI state for this browser tab
The opaque frame cannot use browser storage directly. The bridge provides
host-managed, JSON-only session state instead. It survives an iframe remount and
page reload in the same browser tab, but is not durable data. Do not use it to
store secrets.
```js
// Default: this user + this plugin + this browser tab.
await trek.session.set('dismissed-onboarding', true)
const dismissed = await trek.session.get('dismissed-onboarding')
// Explicitly partition state by the trip in view (fails without a trip context).
await trek.session.set('filters', ['flight', 'hotel'], { scope: 'trip' })
```
`get()` returns `undefined` for a missing key. `set`, `get`, `remove`, and
`clear` accept `{ scope: 'plugin' | 'trip' }`; `plugin` is the default. Use your
plugin's own logical key (for example `reservation:88:expanded`) for any finer
partitioning. Each plugin or individual trip scope is limited to 32 keys,
64 characters per key, and 1 KiB per JSON value.
The kit applies the theme, mirrors the appearance flags (reduced-motion,
no-transparency) and auto-reports your height. It also upgrades any native
`<select>` into a host-styled, keyboard-accessible dropdown that matches TREK —
@@ -118,6 +140,54 @@ const { ctx, broadcasts } = createMockHost({
// degrades gracefully when a permission is missing.
```
## Runtime limits
The host enforces these limits on every ctx call and hook invocation. They are generous
for a legitimate plugin and only bite a runaway or abusive one — build against them so
`dev`/`mock-host` behavior matches production.
| Area | Limit |
|---|---|
| `ctx.ai` | 200 calls/day per plugin (UTC midnight rollover); past it throws `"daily AI budget exhausted (resets at UTC midnight)"` |
| `ctx.notify` | 100 calls/day per plugin (UTC midnight rollover); past it throws `"daily notification budget exhausted (resets at UTC midnight)"` |
| RPC (every `ctx.*` call) | burst 60, sustained 20/s, 16 in-flight per plugin; a throttled call is refused with `HOST_ERROR: rate limit exceeded — slow down ctx.* calls` |
| `ctx.db` (your own sqlite) | 256 MB per plugin |
| `ctx.meta` | 64 KB per value, 256 chars per key, 100 keys per (plugin, entity) |
| Plugin process | 300 MB RSS ceiling; auto-disabled after 5 crashes in 5 minutes |
| Event redelivery buffer | 200 events held per plugin, dropped unreplayed after 15 minutes |
Hook contribution caps (declarative content the host renders — a slow/failing call is
skipped, never fatal):
| Hook | Cap |
|---|---|
| `pdfSectionProvider` | ≤5 sections per provider |
| `atlasLayerProvider` | ≤3 layers per provider |
| `mapMarkerProvider` | ≤200 markers per provider |
| `warningProvider` | ≤20 warnings per provider, each message ≤300 chars |
| `placeDetailProvider` | ≤12 items per provider |
| `photoProvider` | ≤60 photos per page |
| `calendarSource` | ≤500 events per source per request |
| `tableContributor` | ≤20 columns / ≤10 actions per entity |
| `tripCardProvider` | ≤4 badges per trip, ≤240 total per provider |
## OAuth broker
`ctx.oauth.getAccessToken()` is host-brokered outbound OAuth: the plugin never becomes a
direct OAuth client. The host runs the whole flow (authorize → callback → token exchange
→ refresh) with PKCE and a 10-minute state TTL, and holds the refresh token + client
secret — a plugin only ever sees a short-lived access token for the ACTING USER, or
`null` when they haven't connected (or in a userless context).
Provider config is the plugin's admin-owned INSTANCE settings — declare `scope:'instance'`
manifest fields named `oauth_authorize_url`, `oauth_token_url`, `oauth_scopes` (optional),
`oauth_client_id`, `oauth_client_secret`, and the admin fills them in from Settings →
Plugins → Connect. Both endpoint URLs must be `https` and may not point at loopback,
`.local`/`.internal` names, or private/metadata addresses — the host refuses to start a
flow against them. The host exposes
`/api/plugin-oauth/:id/status|connect|callback|disconnect` to drive the connect UI;
plugin code itself only ever calls `getAccessToken()`.
## Capture the screenshot
The registry requires a screenshot that resolves to a real image, and the store card
@@ -158,7 +228,28 @@ Needs `git` and an authenticated `gh`. It prints the PR URL at the end.
**Updating** a listed plugin: bump `version` in the manifest, commit, and run
`publish` again with the new tag — it detects the existing entry and prepends the
new version, newest-first.
new version, newest-first. Your TREK-Plugins fork is fast-forwarded automatically
before the PR branch is cut, so a fork left behind doesn't break the submit (a
*diverged* fork gets a warning and the `gh repo sync --force` command to fix it).
### When a publish fails
A failure **after** the release is cut (a preflight or PR problem) rolls back
exactly what that run created — the GitHub release, the pushed tag, the local
tag — so the same tag is free to re-run against once you've fixed the problem.
Nothing that existed before the run is ever touched. Pass `--keep-release` to
keep the release instead; the error then prints the manual cleanup commands.
Two related conveniences:
- A leftover tag from an earlier failed run (it has no release and doesn't point
at `HEAD`) is recognised as debris and **moved to your current commit** instead
of silently releasing the stale one.
- `trek-plugin unrelease <vX.Y.Z> --repo you/repo` deletes a stranded release +
remote tag + local tag in one go. It checks the published registry index first
and **refuses to touch a version that is actually published** — those artifacts
are immutable (the registry pins their sha256), so the only way forward there is
a new version.
Prefer to drive the steps yourself? They still exist individually — `pack`,
`release` (pack → GitHub release → entry), `preflight`, `submit` (opens the PR),
@@ -177,7 +268,10 @@ It is a one-way door you may walk through **late**:
- Unsigned throughout is fine — the sha256 pin is the only guarantee, and TREK accepts it.
- **Unsigned → signed later breaks nobody.** Nothing is pinned until a signed version
installs, so adding a key at v1.4.0 is a real option, not a lost cause.
installs, so adding a key at v1.4.0 is a real option, not a lost cause. The registry
does require every version signed once your key appears in the entry — your first
signed update **retro-signs the older versions for you** (each pinned artifact is
downloaded, verified against its sha256, and signed with the same key).
- **Signed → unsigned is refused forever**, on every instance that already has the plugin.
`publish` refuses that at step 1, before anything is tagged or released.
@@ -220,6 +314,7 @@ bin if you install the package). `trek-plugin help <command>` — or
- `preflight [dir] --repo o/n --tag vX [--entry f] [--all]` — the registry checks that need the network: the tag resolves to the pinned commit, the released artifact downloads and hashes, the id is not bound to another owner, and an update does not drop or rotate a published signing key.
- `submit [dir] --repo o/n --tag vX [--registry o/n] [--draft]` — open the registry PR for you.
- `release [dir] --repo o/n --tag vX [--sign [key]] [--merge f]` — pack → GitHub release → entry, without opening the PR.
- `unrelease <vX.Y.Z> [dir] --repo o/n [--yes]` — delete a stranded release + remote tag + local tag. Refuses a version that is published in the registry (immutable); `--yes` consents when the registry index can't be checked.
## Update notice
+442 -257
View File
File diff suppressed because it is too large Load Diff
+3 -1
View File
@@ -1,6 +1,6 @@
{
"name": "trek-plugin-sdk",
"version": "1.5.0",
"version": "1.6.0",
"description": "SDK for building TREK plugins: types, definePlugin, a mock host, manifest validation, and the create-trek-plugin / trek-plugin CLIs.",
"type": "module",
"license": "MIT",
@@ -71,12 +71,14 @@
"build": "tsc -p tsconfig.json && tsc -p tsconfig.cjs.json && node scripts/finish-cjs.mjs",
"typecheck": "tsc -p tsconfig.json --noEmit",
"test": "vitest run",
"test:coverage": "vitest run --coverage",
"prepublishOnly": "npm run build && npm test"
},
"devDependencies": {
"@types/node": "^22.20.0",
"@types/semver": "^7.7.1",
"@types/update-notifier": "^6.0.8",
"@vitest/coverage-v8": "^4.1.9",
"typescript": "^5.9.3",
"vitest": "^4.1.9"
},
+3 -3
View File
@@ -30,7 +30,7 @@ export function loadContext(
try {
// Tolerate a UTF-8 BOM. Windows editors add one, and a bare JSON.parse then fails with a
// cryptic "Unexpected token" pointing at an invisible character. Same rule as readJsonFile.
const text = manifestRaw.charCodeAt(0) === 0xfeff ? manifestRaw.slice(1) : manifestRaw;
const text = manifestRaw.codePointAt(0) === 0xfeff ? manifestRaw.slice(1) : manifestRaw;
const parsed: unknown = JSON.parse(text);
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
manifestError = 'trek-plugin.json is not a JSON object';
@@ -56,10 +56,10 @@ export function loadContext(
/** Convenience for tests and for callers that already hold the strings. */
export function makeContext(over: Partial<CheckContext> & { dir?: string }): CheckContext {
const files = new Set<string>();
return {
dir: over.dir ?? '/plugin',
exists: (rel: string) => files.has(rel),
// Nothing is on disk here unless the caller passes its own `exists`.
exists: () => false,
...over,
};
}
+5 -3
View File
@@ -57,7 +57,9 @@ function targetVersions(c: CheckContext): RegistryEntryVersion[] {
return c.allVersions ? vs : vs.slice(0, 1);
}
async function fetchText(url: string, headers: Record<string, string> = { 'User-Agent': 'trek-plugin-preflight' }): Promise<string | null> {
const PLAIN_HEADERS: Record<string, string> = { 'User-Agent': 'trek-plugin-preflight' };
async function fetchText(url: string, headers: Record<string, string> = PLAIN_HEADERS): Promise<string | null> {
try {
const r = await fetch(url, { headers });
return r.ok ? await r.text() : null;
@@ -141,12 +143,12 @@ const manifestAtCommit: NetworkCheck = {
if ((m.operatorEgress === true) !== (v.operatorEgress === true)) {
p(`manifest operatorEgress ${m.operatorEgress === true} != entry ${v.operatorEgress === true}`);
}
const normAddons = (a: unknown) => (Array.isArray(a) ? [...a].map(String).sort() : []);
const normAddons = (a: unknown) => (Array.isArray(a) ? [...a].map(String).sort((x, y) => (x < y ? -1 : x > y ? 1 : 0)) : []);
if (JSON.stringify(normAddons(m.requiredAddons)) !== JSON.stringify(normAddons(v.requiredAddons))) {
p('manifest requiredAddons != entry requiredAddons');
}
const normDeps = (d: unknown) =>
(Array.isArray(d) ? d.map((x) => `${(x as { id?: string })?.id}@${(x as { version?: string })?.version}`).sort() : []);
(Array.isArray(d) ? d.map((x) => `${(x as { id?: string })?.id}@${(x as { version?: string })?.version}`).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)) : []);
if (JSON.stringify(normDeps(m.pluginDependencies)) !== JSON.stringify(normDeps(v.pluginDependencies))) {
p('manifest pluginDependencies != entry pluginDependencies');
}
+3 -3
View File
@@ -106,7 +106,7 @@ const manifestTrekRange: OfflineCheck = {
? fail(
`trek: "${trek}"`,
'This claims support for every TREK version, including ones that do not exist yet. It opts you out of the\n' +
'one mechanism that stops your plugin running on a host it was never tested against. Pin a range like ">=3.4.0 <4.0.0".',
'one mechanism that stops your plugin running on a host it was never tested against. Pin a range like ">=4.0.0 <5.0.0".',
)
: pass(trek);
},
@@ -530,12 +530,12 @@ const releaseEntryParity: OfflineCheck = {
problems.push(`• manifest operatorEgress ${m.operatorEgress === true} != entry ${v.operatorEgress === true}`);
}
const normAddons = (a: unknown) => [...arr(a)].sort();
const normAddons = (a: unknown) => [...arr(a)].sort((x, y) => (x < y ? -1 : x > y ? 1 : 0));
if (JSON.stringify(normAddons(m.requiredAddons)) !== JSON.stringify(normAddons(v.requiredAddons))) {
problems.push(`• manifest requiredAddons [${normAddons(m.requiredAddons)}] != entry [${normAddons(v.requiredAddons)}]`);
}
const normDeps = (d: unknown) =>
(Array.isArray(d) ? d.map((x) => `${(x as { id?: string })?.id}@${(x as { version?: string })?.version}`).sort() : []);
(Array.isArray(d) ? d.map((x) => `${(x as { id?: string })?.id}@${(x as { version?: string })?.version}`).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)) : []);
if (JSON.stringify(normDeps(m.pluginDependencies)) !== JSON.stringify(normDeps(v.pluginDependencies))) {
problems.push(`• manifest pluginDependencies [${normDeps(m.pluginDependencies)}] != entry [${normDeps(v.pluginDependencies)}]`);
}
+21 -3
View File
@@ -29,11 +29,29 @@ export const PLACEHOLDER_PATTERNS = [
export const MIN_PROSE_CHARS = 400;
/**
* The heading body, with the trailing HTML comment authors use to hide anchors cut off.
*
* Cut with indexOf rather than a regex on purpose. The obvious spellings — the
* `(.+?)\s*(?:<!--.*)?$` this used to be, or a `replace(/\s*<!--.*$/, '')` in front of it —
* put two quantifiers on the same run of spaces, and both then backtrack quadratically:
* a heading line padded with 80k spaces takes ~12s, 200k takes ~30s. This gate runs over
* READMEs anyone can submit to the registry, so that is a stall someone can post. Same
* failure the wiki sidebar parser was rewritten for (server/src/nest/help/wiki.ts).
*/
function headingBody(line: string): string {
const comment = line.indexOf('<!--');
return comment < 0 ? line : line.slice(0, comment);
}
/** Which of REQUIRED_SECTIONS have no matching heading. */
export function missingSections(md: string): string[] {
// The `(?:<!--.*)?` tail mirrors check-readme.mjs — it tolerates a trailing HTML comment
// on a heading line, which authors use to hide anchors.
const headings = [...md.matchAll(/^#{1,6}\s+(.+?)\s*(?:<!--.*)?$/gm)].map((m) => m[1].toLowerCase());
const headings = md
.split('\n')
// `\S.*\S|\S` instead of a lazy body: the edges are pinned to non-space, so nothing
// competes with the trailing `\s*`.
.map((line) => /^#{1,6}\s+(\S.*\S|\S)\s*$/.exec(headingBody(line))?.[1].toLowerCase())
.filter((h): h is string => h !== undefined);
return REQUIRED_SECTIONS.filter((want) => !headings.some((got) => got.includes(want.toLowerCase())));
}
+35 -6
View File
@@ -57,6 +57,23 @@ export interface ScaffoldOptions {
export const TEMPLATES = ['blank', 'notification-channel'] as const;
/**
* The credential fields the OAuth broker (server-side `oauth.getToken`) needs to run the
* authorization-code flow on the plugin's behalf. ALL `scope: 'instance'` — unlike the
* notification-channel template's `scope: 'user'` settings above, these are configured ONCE
* per install by an admin, not per recipient: the broker itself reads them at token-exchange
* time, there is no per-user client id/secret. Deliberately not user-scoped.
*/
const OAUTH_SETTINGS: Array<{
key: string; label: string; input_type: string; required: boolean; secret?: boolean; scope: 'instance';
}> = [
{ key: 'oauth_authorize_url', label: 'OAuth authorize URL', input_type: 'text', required: true, scope: 'instance' },
{ key: 'oauth_token_url', label: 'OAuth token URL', input_type: 'text', required: true, scope: 'instance' },
{ key: 'oauth_scopes', label: 'OAuth scopes (space-separated)', input_type: 'text', required: false, scope: 'instance' },
{ key: 'oauth_client_id', label: 'OAuth client id', input_type: 'text', required: true, scope: 'instance' },
{ key: 'oauth_client_secret', label: 'OAuth client secret', input_type: 'text', required: true, secret: true, scope: 'instance' },
];
/** Mirrors the server's widget slots (and the manifest validator's). */
export const WIDGET_SLOTS = ['sidebar', 'hero', 'place-detail', 'day-detail', 'reservation-detail'] as const;
export type WidgetSlot = (typeof WIDGET_SLOTS)[number];
@@ -96,7 +113,7 @@ export function scaffold(name: string, type: string, targetDir: string, opts: Sc
if (fs.existsSync(root)) throw new Error(`${root} already exists`);
fs.mkdirSync(path.join(root, 'server'), { recursive: true });
const displayName = name.replace(/-/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
const displayName = name.replaceAll('-', ' ').replaceAll(/\b\w/g, (c) => c.toUpperCase());
let perms = opts.permissions?.length ? opts.permissions : ['db:own'];
const egress = opts.egress ?? [];
if (isChannel) {
@@ -121,11 +138,13 @@ export function scaffold(name: string, type: string, targetDir: string, opts: Sc
author: opts.author || 'Your Name',
description: opts.description || (isChannel ? `Deliver TREK notifications over ${displayName}.` : 'Describe what your plugin does.'),
type,
// 3.4.0, not 3.3.0. The `ctx` namespaces this scaffold is written against — ctx.meta,
// ctx.places, ctx.days, ctx.itinerary, ctx.costs, ctx.packing, ctx.files — only exist from
// 3.4.0. Claiming 3.3.0 lets the plugin install on a host where they are `undefined`, which
// fails at the first call with a TypeError instead of a clear "incompatible" at install.
trek: '>=3.4.0 <4.0.0',
// Floor 4.0.0: the host surface this scaffold is written against — the enforced
// apiVersion gate, the generated core-event catalog (EVENT_FAMILIES /
// EVENT_SNAPSHOT_GRANT), the OAuth-broker settings contract — is the TREK 4 surface.
// Claiming an older floor lets the plugin install on a host where parts of it are
// missing, which fails at the first call instead of a clear "incompatible" at install.
// Ceiling 5.0.0: bounded, per the trek-range rule; widen only against a tested host.
trek: '>=4.0.0 <5.0.0',
nativeModules: false,
permissions: perms,
// Dependency declarations (empty by default). `requiredAddons` lists addon ids
@@ -183,6 +202,16 @@ export function scaffold(name: string, type: string, targetDir: string, opts: Sc
},
];
}
// The broker (ctx.oauth.getToken) needs somewhere to read the authorize/token URLs and the
// app's client id/secret — an admin configures them once, instance-wide, and the broker
// reads them at token-exchange time. Merge with any settings the template above already
// wrote (a channel template never grants oauth:client today, so there is no real overlap,
// but keys are deduped anyway rather than trusting that stays true).
if (perms.includes('oauth:client')) {
const existing = (manifest.settings as Array<{ key: string }> | undefined) ?? [];
const seen = new Set(existing.map((s) => s.key));
manifest.settings = [...existing, ...OAUTH_SETTINGS.filter((s) => !seen.has(s.key))];
}
fs.writeFileSync(path.join(root, 'trek-plugin.json'), JSON.stringify(manifest, null, 2) + '\n');
fs.writeFileSync(path.join(root, 'server', 'index.js'), isChannel ? CHANNEL_JS : SERVER_JS(perms.includes('db:own')));
+58 -4
View File
@@ -456,7 +456,7 @@ export async function runDev(dir: string, opts: { port?: number } = {}): Promise
// renders into docs/screenshot.png. ?theme=dark picks the dark palette.
const chrome = url.searchParams.get('chrome') !== '0';
const theme = url.searchParams.get('theme') === 'dark' ? 'dark' : 'light';
return send(200, preview(id, String(manifest.type), previewTripId, { chrome, theme }), 'text/html; charset=utf-8');
return send(200, preview(id, String(manifest.type), previewTripId, { chrome, theme, geoAllowed: grants.has('geolocation:read') }), 'text/html; charset=utf-8');
}
// Static plugin UI at /ui (page/widget client bundle). The iframe loads
@@ -598,7 +598,7 @@ ${LIVE_RELOAD}`;
* toggle), proxies trek:invoke to the dev server's /api routes with the dev user,
* and surfaces resize/notify/navigate. This is where the design kit renders themed.
*/
function preview(id: string, type: string, tripId: number, opts: { chrome?: boolean; theme?: 'light' | 'dark' } = {}): string {
export function preview(id: string, type: string, tripId: number, opts: { chrome?: boolean; theme?: 'light' | 'dark'; geoAllowed?: boolean } = {}): string {
const maxW = type === 'widget' ? '440px' : '1000px';
// `trek-plugin shot` renders this page into docs/screenshot.png — the image the plugin store
// shows. The theme picker and the "runs sandboxed at an opaque origin" note are DEV furniture:
@@ -634,6 +634,7 @@ iframe{width:100%;border:0;background:transparent;min-height:120px;display:block
<label>Accent <select id="accent"><option value="default">default</option><option value="indigo">indigo</option><option value="teal">teal</option><option value="rose">rose</option></select></label>
<label><input type="checkbox" id="rm"> reduce motion</label>
<label><input type="checkbox" id="nt"> no transparency</label>
<label><input type="checkbox" id="blur"> blur booking codes</label>
<label><input type="checkbox" id="trip" checked> trip context</label>
</header>
<div class="stage"><div class="wrap"><iframe id="f" src="/ui/index.html" sandbox="allow-scripts allow-forms" referrerpolicy="no-referrer" title="${id}"></iframe></div></div>
@@ -658,11 +659,42 @@ function ctx(){
tripId: val("trip").checked?${tripId}:null, userId:"1",
user:{name:"Dev User",avatar:null,isAdmin:true},
appearance:{scheme:accent,density:"comfortable",reducedMotion:val("rm").checked,noTransparency:val("nt").checked},
formats:{locale:"en",currency:"EUR",timeFormat:"24h",distanceUnit:"metric",temperatureUnit:"celsius",timezone:Intl.DateTimeFormat().resolvedOptions().timeZone},
formats:{locale:"en",currency:"EUR",timeFormat:"24h",distanceUnit:"metric",temperatureUnit:"celsius",timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,blurBookingCodes:val("blur").checked},
tokens:tokens};
}
function postCtx(){ if(f.contentWindow) f.contentWindow.postMessage(ctx(),"*"); }
var tt; function toast(msg){var el=document.getElementById("toast");el.textContent=msg;el.classList.add("on");clearTimeout(tt);tt=setTimeout(function(){el.classList.remove("on");},2200);}
var SESSION_PREFIX="trek:plugin-session:1:"+encodeURIComponent(${JSON.stringify(id)})+":";
var SESSION_MAX_KEYS=32,SESSION_MAX_KEY_LENGTH=64,SESSION_MAX_VALUE_BYTES=1024;
var GEO_ALLOWED=${opts.geoAllowed ? 'true' : 'false'};
function sessionFail(m,code,message){f.contentWindow.postMessage({type:"trek:error",requestId:m.requestId,code:code,message:message},"*");}
function sessionMessage(m){
try {
var trip=ctx().tripId, scope=m.scope==="trip"?"trip":"plugin";
if(scope==="trip"&&!trip){f.contentWindow.postMessage({type:"trek:error",requestId:m.requestId,code:"NO_TRIP_CONTEXT",message:"trip session storage requires a trip context"},"*");return;}
var prefix=SESSION_PREFIX+scope+(scope==="trip"?":"+encodeURIComponent(String(trip)):"")+":";
var data;
if(m.type==="trek:session:clear"){
var doomed=[];for(var i=0;i<sessionStorage.length;i++){var stored=sessionStorage.key(i);if(stored&&stored.indexOf(prefix)===0)doomed.push(stored);}doomed.forEach(function(stored){sessionStorage.removeItem(stored);});
} else {
if(typeof m.key!=="string"||!m.key||m.key.length>SESSION_MAX_KEY_LENGTH){sessionFail(m,"SESSION_INVALID_KEY","session key must be 1-"+SESSION_MAX_KEY_LENGTH+" characters");return;}
var key=prefix+encodeURIComponent(m.key);
if(m.type==="trek:session:get"){var raw=sessionStorage.getItem(key);data=raw===null?undefined:JSON.parse(raw);}
else if(m.type==="trek:session:remove"){sessionStorage.removeItem(key);}
else {
var json=JSON.stringify(m.value);
if(json===undefined){sessionFail(m,"SESSION_INVALID_VALUE","session value must be JSON-serialisable");return;}
var bytes=new TextEncoder().encode(json).length;
if(bytes>SESSION_MAX_VALUE_BYTES){sessionFail(m,"SESSION_VALUE_TOO_LARGE","session value exceeds "+SESSION_MAX_VALUE_BYTES+" bytes");return;}
var count=0,exists=false;
for(var j=0;j<sessionStorage.length;j++){var sk=sessionStorage.key(j);if(sk&&sk.indexOf(prefix)===0){count++;if(sk===key)exists=true;}}
if(!exists&&count>=SESSION_MAX_KEYS){sessionFail(m,"SESSION_KEY_LIMIT","plugin session storage allows at most "+SESSION_MAX_KEYS+" keys");return;}
sessionStorage.setItem(key,json);
}
}
f.contentWindow.postMessage({type:"trek:response",requestId:m.requestId,data:data},"*");
} catch(e) { sessionFail(m,"SESSION_STORAGE_ERROR",String(e&&e.message||e)); }
}
window.addEventListener("message", function(ev){
if(ev.source!==f.contentWindow) return;
var m=ev.data; if(!m||typeof m!=="object") return;
@@ -682,8 +714,30 @@ window.addEventListener("message", function(ev){
.then(function(data){ f.contentWindow.postMessage({type:"trek:response",requestId:m.requestId,data:data},"*"); })
.catch(function(e){ f.contentWindow.postMessage({type:"trek:error",requestId:m.requestId,code:"error",message:String(e&&e.message||e)},"*"); });
}
else if(m.type==="trek:geolocation"){
// Mirror the host's geolocation bridge with a fixed dev position, so
// trek.geolocation.* works in the preview without a browser prompt. The grant
// still gates it: without geolocation:read the host answers "forbidden"
// (PluginFrame.tsx), and a preview that answered anyway would green-light a
// plugin that production then refuses.
if(!GEO_ALLOWED){ f.contentWindow.postMessage({type:"trek:geolocation:result",requestId:m.requestId,error:"forbidden"},"*"); return; }
var pos={lat:52.5163,lng:13.3777,accuracy:12,heading:null,speed:null,timestamp:Date.now()};
var act=m.action||"get";
if(act==="clear"){ clearInterval(geoTick); geoTick=null; f.contentWindow.postMessage({type:"trek:geolocation:result",requestId:m.requestId,cleared:true},"*"); }
else if(act==="watch"){
f.contentWindow.postMessage({type:"trek:geolocation:result",requestId:m.requestId,watching:true},"*");
clearInterval(geoTick);
geoTick=setInterval(function(){ pos=Object.assign({},pos,{lng:pos.lng+0.0002,timestamp:Date.now()}); f.contentWindow.postMessage({type:"trek:geolocation:update",position:pos},"*"); },2000);
f.contentWindow.postMessage({type:"trek:geolocation:update",position:pos},"*");
}
else { f.contentWindow.postMessage({type:"trek:geolocation:result",requestId:m.requestId,position:pos},"*"); }
}
else if(m.type==="trek:session:get"||m.type==="trek:session:set"||m.type==="trek:session:remove"||m.type==="trek:session:clear"){
sessionMessage(m);
}
});
["theme","accent","rm","nt","trip"].forEach(function(id){ val(id).addEventListener("change",postCtx); });
var geoTick=null;
["theme","accent","rm","nt","blur","trip"].forEach(function(id){ val(id).addEventListener("change",postCtx); });
f.addEventListener("load", function(){ f.style.height="120px"; postCtx(); });
var __v; setInterval(function(){ fetch("/__dev/version").then(function(r){return r.text();}).then(function(v){ if(__v&&v!==__v){ f.src=f.src; } __v=v; }).catch(function(){}); },1000);
</script>
+2 -2
View File
@@ -56,7 +56,7 @@ interface Entry {
}
/**
* Lower bound of a `trek` range like ">=3.2.0 <4.0.0" -> "3.2.0" (matches the server).
* Lower bound of a `trek` range like ">=4.0.0 <5.0.0" -> "4.0.0" (matches the server).
*
* Read off the range with semver rather than by finding the first version-shaped substring:
* for "<4.0.0" the first such substring is 4.0.0, which is the range's *upper* bound and
@@ -91,7 +91,7 @@ export function buildEntry(opts: {
if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(opts.repo)) throw new Error(`--repo must be "owner/name", got "${opts.repo}"`);
// minVersion() is null for a range nothing can satisfy (">=4.0.0 <3.0.0" parses fine), so
// this doubles as the satisfiability check — TREK would refuse to install such a plugin.
if (!minTrekFrom(manifest.trek)) throw new Error('manifest has no valid "trek" version range (e.g. "trek": ">=3.2.0 <4.0.0")');
if (!minTrekFrom(manifest.trek)) throw new Error('manifest has no valid "trek" version range (e.g. "trek": ">=4.0.0 <5.0.0")');
if (!fs.existsSync(opts.zipPath)) throw new Error(`artifact not found: ${opts.zipPath} — run \`trek-plugin pack\` first`);
const buf = fs.readFileSync(opts.zipPath);
+21 -2
View File
@@ -18,7 +18,7 @@ export const VERSION_LINE = (v: string): string => `trek-plugin-sdk ${v}`;
export const PATH_COMMANDS = ['create', 'dev', 'status', 'publish'] as const;
/** Real, supported, and not what a newcomer needs to see first. */
export const OTHER_COMMANDS = ['validate', 'pack', 'shot', 'keygen', 'sign', 'entry', 'preflight', 'submit', 'release'] as const;
export const OTHER_COMMANDS = ['validate', 'pack', 'shot', 'keygen', 'sign', 'entry', 'preflight', 'submit', 'release', 'unrelease'] as const;
export interface CommandHelp {
/** One line, for the top-level list. */
@@ -85,7 +85,7 @@ you like.`,
publish: {
summary: 'release + open the registry PR',
usage: 'trek-plugin publish [dir] --repo <owner/name> --tag <vX.Y.Z> [--sign]',
usage: 'trek-plugin publish [dir] --repo <owner/name> --tag <vX.Y.Z> [--sign] [--keep-release]',
body: `The whole release, in order:
1. check every registry gate that can be checked locally
@@ -98,6 +98,12 @@ Step 1 comes first for a reason: a GitHub release is effectively immutable, beca
pins its sha256. If a check fails, NOTHING is packed, tagged, pushed or released — so you can fix
it and re-run against the same version.
And when a LATER step fails, publish rolls back exactly what the run created — the release, the
pushed tag, the local tag — so the same tag is free to re-run against once you have fixed the
problem. Pass --keep-release to leave them in place instead (the error then prints the manual
cleanup). Anything that existed before the run is never touched. A leftover tag from an earlier
failed run is recognised (no release for it, not on HEAD) and moved to HEAD rather than reused.
In a terminal it OFFERS TO SIGN, and creates a key for you if you have none. A signature proves the
artifact came from you, not just that its bytes match what the registry saw. You can add signing
later — publishing unsigned now and signing at v1.4.0 breaks nobody — but you can never take it
@@ -217,6 +223,19 @@ hand, or to re-check a release you have already cut.
body: `Packs, cuts the GitHub release, and prints the registry entry — but does NOT open the registry PR.
For when you want to release now and submit later. \`publish\` is the whole thing.`,
},
unrelease: {
summary: 'delete a stranded tag + release (never a published one)',
usage: 'trek-plugin unrelease <vX.Y.Z> [dir] --repo <owner/name> [--registry owner/name] [--yes]',
body: `Undoes a release that never made it into the registry: deletes the GitHub release, the remote
tag, and the local tag — each reported, each skipped when already gone. For when a publish
failed halfway (though \`publish\` now rolls its own failures back), or you changed your mind
before the registry PR merged.
The one hard rule: a version that IS published in the registry is immutable — the registry pins
the artifact's sha256, so deleting its release breaks install/update for everyone who has it.
unrelease checks the published index first and refuses those outright, with no override. If the
registry cannot be reached to check, it refuses unless you pass --yes.`,
},
};
export function topLevelHelp(version: string): string {
+1 -1
View File
@@ -7,5 +7,5 @@ import fs from 'node:fs';
*/
export function readJsonFile<T = unknown>(p: string): T {
const text = fs.readFileSync(p, 'utf8');
return JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text) as T;
return JSON.parse(text.codePointAt(0) === 0xfeff ? text.slice(1) : text) as T;
}
+1
View File
@@ -38,6 +38,7 @@ export const ADVANCED_MENU: MenuItem[] = [
{ value: 'preflight', label: 'Preflight', hint: 'The registry checks that need the release to exist' },
{ value: 'submit', label: 'Submit', hint: 'Open the registry PR' },
{ value: 'release', label: 'Release', hint: 'Pack → GitHub release → print entry' },
{ value: 'unrelease', label: 'Unrelease', hint: 'Delete a stranded tag + release (never a published one)' },
{ value: 'back', label: '← Back', hint: '' },
];
+1 -1
View File
@@ -100,6 +100,6 @@ export function packPluginDir(dir: string, outPath: string): PackResult {
artifact: outAbs,
sha256: createHash('sha256').update(buf).digest('hex'),
size: buf.length,
files: filtered.map((f) => f.name).sort(),
files: filtered.map((f) => f.name).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)),
};
}
+90 -28
View File
@@ -31,8 +31,12 @@ import { plainLog, type LogSink } from './ui.js';
function git(dir: string, args: string[], quiet = true): string {
return execFileSync('git', ['-C', dir, ...args], { encoding: 'utf8', stdio: quiet ? 'pipe' : 'inherit' }).toString().trim();
}
function tagExists(dir: string, tag: string): boolean {
try { git(dir, ['rev-parse', `${tag}^{commit}`]); return true; } catch { return false; }
/** The commit a local tag points at, or null when the tag does not exist. */
function tagSha(dir: string, tag: string): string | null {
try { return git(dir, ['rev-parse', `${tag}^{commit}`]); } catch { return null; }
}
function remoteTagExists(dir: string, tag: string): boolean {
try { return git(dir, ['ls-remote', '--tags', 'origin', `refs/tags/${tag}`]) !== ''; } catch { return false; }
}
function releaseExists(repo: string, tag: string): boolean {
try { execFileSync('gh', ['release', 'view', tag, '--repo', repo], { stdio: 'pipe' }); return true; } catch { return false; }
@@ -45,6 +49,8 @@ export async function publishPlugin(opts: {
force?: boolean;
/** Skip the local gates. An escape hatch for a re-run, never a good idea on a first publish. */
skipChecks?: boolean;
/** On failure, leave the tag/release this run created in place instead of rolling them back. */
keepRelease?: boolean;
/**
* A signing state the CLI already looked up (it does, to know whether to offer signing). Passed
* in so a single publish does not hit the registry twice for the same answer.
@@ -93,14 +99,36 @@ export async function publishPlugin(opts: {
// 3. Tag (if needed) + push + GitHub release with the artifact attached
step(3, `Tagging ${opts.tag} + creating the GitHub release…`);
if (!tagExists(dir, opts.tag)) git(dir, ['tag', opts.tag]);
try { git(dir, ['push', 'origin', opts.tag]); } catch {
const head = git(dir, ['rev-parse', 'HEAD']);
const existingTagSha = tagSha(dir, opts.tag);
const relExisted = releaseExists(opts.repo, opts.tag);
let createdLocalTag = false;
let movedTag = false;
if (existingTagSha === null) {
git(dir, ['tag', opts.tag]);
createdLocalTag = true;
} else if (existingTagSha !== head) {
// A tag that doesn't point at HEAD and has no release is debris from a failed run — reusing
// it silently would release the UNFIXED commit. Move it. One that HAS a release is immutable.
if (relExisted && !opts.force) {
throw new Error(
`tag ${opts.tag} points at ${existingTagSha.slice(0, 7)}, not HEAD (${head.slice(0, 7)}) — and its release already exists on ${opts.repo}.\n` +
`A released artifact is immutable (the registry pins its sha256). Cut a new version,\n` +
`or pass --force if this release was never merged into the registry.`,
);
}
log(` ! tag ${opts.tag} pointed at ${existingTagSha.slice(0, 7)} (debris from an earlier run) — moving it to HEAD`);
git(dir, ['tag', '-f', opts.tag]);
movedTag = true;
}
const remoteTagExisted = remoteTagExists(dir, opts.tag);
try { git(dir, ['push', ...(movedTag ? ['--force'] : []), 'origin', opts.tag]); } catch {
throw new Error(`could not push tag ${opts.tag} — is "origin" your plugin's GitHub repo and are you authenticated? (git push origin ${opts.tag})`);
}
// A released artifact is IMMUTABLE: the registry pins its sha256, so overwriting the bytes of a
// release that is already in the registry breaks the checksum for everyone who has that version
// — they can no longer install or update it. Refuse by default.
if (releaseExists(opts.repo, opts.tag)) {
if (relExisted) {
if (!opts.force) {
throw new Error(
`release ${opts.tag} already exists on ${opts.repo}.\n` +
@@ -115,31 +143,65 @@ export async function publishPlugin(opts: {
}
log(` ✓ release ${opts.tag} on ${opts.repo}`);
// 4. Build the entry, then run the gates that need the tag and the release to exist
const entry = buildEntry({ dir, repo: opts.repo, tag: opts.tag, zipPath: packed.artifact, signKeyPath: opts.signKeyPath, now: opts.now });
if (opts.skipPreflight) {
log('[4/5] Preflight skipped (--no-preflight).');
} else {
step(4, 'Preflight — the gates that need the release to exist…');
const rep = await preflight(entry, { dir, registry: opts.registry });
for (const f of rep.failures) log(' ✗ ' + f);
if (!rep.ok) {
// What THIS run created — the exact scope of a rollback. Anything that existed before the run
// (a merged release, a pre-pushed tag) is deliberately out of bounds.
const created = { release: !relExisted, remoteTag: !remoteTagExisted, localTag: createdLocalTag || movedTag };
const manualCleanup =
` gh release delete ${opts.tag} --repo ${opts.repo} --yes\n` +
` git push origin :refs/tags/${opts.tag}\n` +
` git tag -d ${opts.tag}`;
const rollback = () => {
if (created.release) {
try { execFileSync('gh', ['release', 'delete', opts.tag, '--repo', opts.repo, '--yes'], { stdio: 'pipe' }); log(` ↩ deleted release ${opts.tag}`); }
catch { log(` ! could not delete release ${opts.tag} — run: gh release delete ${opts.tag} --repo ${opts.repo} --yes`); }
}
if (created.remoteTag) {
try { git(dir, ['push', 'origin', `:refs/tags/${opts.tag}`]); log(` ↩ deleted remote tag ${opts.tag}`); }
catch { log(` ! could not delete remote tag ${opts.tag} — run: git push origin :refs/tags/${opts.tag}`); }
}
if (created.localTag) {
try { git(dir, ['tag', '-d', opts.tag]); log(` ↩ deleted local tag ${opts.tag}`); }
catch { log(` ! could not delete local tag ${opts.tag} — run: git tag -d ${opts.tag}`); }
}
};
try {
// 4. Build the entry, then run the gates that need the tag and the release to exist
const entry = buildEntry({ dir, repo: opts.repo, tag: opts.tag, zipPath: packed.artifact, signKeyPath: opts.signKeyPath, now: opts.now });
if (opts.skipPreflight) {
log('[4/5] Preflight skipped (--no-preflight).');
} else {
step(4, 'Preflight — the gates that need the release to exist…');
const rep = await preflight(entry, { dir, registry: opts.registry });
for (const f of rep.failures) log(' ✗ ' + f);
if (!rep.ok) {
throw new Error(
`preflight found ${rep.failures.length} problem(s) — nothing was submitted.\n` +
`Did you push your code to ${opts.repo} before publishing?`,
);
}
log(` ✓ all ${rep.passed.length} checks passed`);
}
// 5. Open the registry PR
step(5, 'Opening the registry PR…');
const { prUrl } = await submitEntry(entry, { registry: opts.registry, draft: opts.draft, signKeyPath: opts.signKeyPath });
log(' ✓ done');
// Keep the artifact. It is the exact bytes the release and the entry's sha256 pin were computed
// from — a re-pack on another machine or SDK version can differ (CRLF, walk order), so anyone
// re-running `entry`/`sign` afterwards must hash THIS file, not a rebuild.
log(` artifact kept at ${zip}`);
return { prUrl };
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
if (opts.keepRelease) {
throw new Error(
`preflight found ${rep.failures.length} problem(s) — nothing was submitted.\n` +
`The release is cut, so fix these, commit, and re-run against a NEW tag (or --force if this one was never merged).\n` +
`Did you push your code to ${opts.repo} before publishing?`,
`${msg}\n\nThe tag and release were left in place (--keep-release). To clean up by hand:\n${manualCleanup}`,
);
}
log(` ✓ all ${rep.passed.length} checks passed`);
rollback();
throw new Error(
`${msg}\n\nEverything this run created was rolled back — the tag ${opts.tag} is free again. Fix the problem and re-run.`,
);
}
// 5. Open the registry PR
step(5, 'Opening the registry PR…');
const { prUrl } = submitEntry(entry, { registry: opts.registry, draft: opts.draft });
log(' ✓ done');
// Keep the artifact. It is the exact bytes the release and the entry's sha256 pin were computed
// from — a re-pack on another machine or SDK version can differ (CRLF, walk order), so anyone
// re-running `entry`/`sign` afterwards must hash THIS file, not a rebuild.
log(` artifact kept at ${zip}`);
return { prUrl };
}
+81
View File
@@ -0,0 +1,81 @@
/**
* Retro-signing: the missing half of "you can start signing late".
*
* Server-side, adding a key at v1.4.0 breaks nobody — TREK pins the key only when a signed
* version installs. But the REGISTRY refuses a mixed entry (key present, older versions
* unsigned), and for good reason: once an instance pins your key, it refuses the unsigned
* older versions, and "install latest compatible" can legitimately resolve an older host to
* one of them. So every version must be signed the moment a key appears — which used to mean
* downloading each old artifact and signing it by hand.
*
* This does that tedious part: for each unsigned version it downloads the pinned artifact,
* verifies the bytes still hash to the entry's pinned sha256 (a mismatch means the release
* asset was changed — a far bigger problem than signing), and signs those exact bytes.
*/
import { createHash } from 'node:crypto';
import { loadPrivateKey, publicKeyBase64, signArtifact } from './sign.js';
export interface RetroSignableEntry {
id?: string;
authorPublicKey?: string;
versions: Array<{ version: string; downloadUrl: string; sha256: string; signature?: string }>;
}
/** True when the entry carries a key but not a signature on every version. */
export function needsRetroSign(entry: RetroSignableEntry): boolean {
return !!entry.authorPublicKey && entry.versions.some((v) => !v.signature);
}
/**
* Sign every unsigned version in place with the key at `keyPath`. Returns the versions it
* signed. Throws — without half-signing the entry — when the key doesn't match the entry's
* `authorPublicKey`, or when any artifact can't be fetched or no longer matches its pin.
*/
export async function retroSignVersions(
entry: RetroSignableEntry,
keyPath: string,
log: (line: string) => void = () => {},
): Promise<string[]> {
if (!needsRetroSign(entry)) return [];
const key = loadPrivateKey(keyPath);
if (publicKeyBase64(key) !== entry.authorPublicKey) {
throw new Error(
'this signing key differs from the entry\'s authorPublicKey — retro-signing older versions with it would produce signatures TREK rejects. Use the original key.',
);
}
const unsigned = entry.versions.filter((v) => !v.signature);
const signatures = new Map<string, string>();
const failures: string[] = [];
for (const v of unsigned) {
try {
const r = await fetch(v.downloadUrl, { headers: { 'User-Agent': 'trek-plugin' } });
if (!r.ok) { failures.push(`v${v.version}: HTTP ${r.status} fetching ${v.downloadUrl}`); continue; }
const bytes = Buffer.from(await r.arrayBuffer());
const hash = createHash('sha256').update(bytes).digest('hex');
if (hash !== v.sha256) {
failures.push(`v${v.version}: the release asset no longer hashes to its pinned sha256 (got ${hash.slice(0, 12)}…, pinned ${v.sha256.slice(0, 12)}…) — the artifact was changed after publishing, which is a bigger problem than signing`);
continue;
}
signatures.set(v.version, signArtifact(bytes, key));
} catch (e) {
failures.push(`v${v.version}: ${e instanceof Error ? e.message : String(e)}`);
}
}
if (failures.length) {
throw new Error(
`could not retro-sign ${failures.length} older version(s) — the registry requires every version signed once a key is present:\n` +
failures.map((f) => ` ✗ ${f}`).join('\n') +
'\n\nNothing was signed. Fix the artifacts above (or remove those versions from the entry) and re-run.',
);
}
// All-or-nothing: only mutate the entry once every artifact verified and signed.
for (const v of unsigned) {
v.signature = signatures.get(v.version)!;
log(` ✓ retro-signed v${v.version}`);
}
return unsigned.map((v) => v.version);
}
+27 -2
View File
@@ -11,12 +11,13 @@ import os from 'node:os';
import path from 'node:path';
import { execFileSync } from 'node:child_process';
import { readJsonFile } from './json.js';
import { needsRetroSign, retroSignVersions } from './retro-sign.js';
const DEFAULT_REGISTRY = 'liketrek/TREK-Plugins';
interface EntryLike {
id: string; name?: string; authorPublicKey?: string;
versions: { version: string }[];
versions: { version: string; downloadUrl: string; sha256: string; signature?: string }[];
}
function git(cwd: string, ...a: string[]): string {
@@ -42,7 +43,7 @@ function mergeOnto(existing: EntryLike, fresh: EntryLike): EntryLike {
return merged;
}
export function submitEntry(entry: EntryLike, opts: { registry?: string; branch?: string; draft?: boolean; keep?: boolean } = {}): { prUrl: string } {
export async function submitEntry(entry: EntryLike, opts: { registry?: string; branch?: string; draft?: boolean; keep?: boolean; signKeyPath?: string } = {}): Promise<{ prUrl: string }> {
const registry = opts.registry || DEFAULT_REGISTRY;
const name = registry.split('/')[1];
const login = gh('api', 'user', '--jq', '.login');
@@ -51,6 +52,17 @@ export function submitEntry(entry: EntryLike, opts: { registry?: string; branch?
// Ensure the fork exists (idempotent — prints "already exists" if it does).
try { gh('repo', 'fork', registry, '--clone=false'); } catch { /* already forked */ }
// Fast-forward the fork from the registry. The PR branch is based on upstream/main either
// way, but a fork left far behind has broken pushes and PRs in the wild — and costs nothing
// to keep current. Best-effort: a diverged fork can't be fast-forwarded, and that alone
// must not sink the submit.
try { gh('repo', 'sync', `${login}/${name}`, '--source', registry); } catch {
console.error(
`! could not fast-forward your fork ${login}/${name} (diverged?) — continuing, the PR branch is based on the registry's main.\n` +
` If the push or PR fails, reset the fork with: gh repo sync ${login}/${name} --force`,
);
}
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'trek-submit-'));
try {
// Clone the fork (pushable via gh auth), then base a branch on the CURRENT upstream main.
@@ -77,6 +89,19 @@ export function submitEntry(entry: EntryLike, opts: { registry?: string; branch?
toWrite = mergeOnto(existing, entry);
action = 'update';
}
// First signed update onto an unsigned history: the registry refuses a mixed entry (key
// present, older versions unsigned) — see retro-sign.ts for why. Sign the older versions
// with the same key, or say exactly what is missing.
if (needsRetroSign(toWrite)) {
if (!opts.signKeyPath) {
throw new Error(
`this update adds your signing key, but ${toWrite.versions.filter((v) => !v.signature).length} older version(s) are unsigned — ` +
'the registry requires every version signed once a key is present. Re-run with --sign so they can be signed for you.',
);
}
console.error(' older versions are unsigned — signing them with your key so the registry accepts the update');
await retroSignVersions(toWrite, opts.signKeyPath, (line) => console.error(line));
}
fs.mkdirSync(path.dirname(abs), { recursive: true });
fs.writeFileSync(abs, JSON.stringify(toWrite, null, 2) + '\n');
+48 -3
View File
@@ -24,6 +24,8 @@ import { runShot } from './shot.js';
import { preflight } from './preflight.js';
import { submitEntry } from './submit.js';
import { publishPlugin } from './publish.js';
import { unrelease } from './unrelease.js';
import { needsRetroSign, retroSignVersions } from './retro-sign.js';
import { loadContext } from './checks/context.js';
import { runOffline } from './checks/index.js';
import { renderPlain } from './checks/report.js';
@@ -81,7 +83,8 @@ const COMMAND_FLAGS: Record<string, readonly string[]> = {
preflight: ['repo', 'tag', 'entry', 'zip', 'commit', 'sign', 'key', 'all', 'registry'],
submit: ['repo', 'tag', 'zip', 'commit', 'sign', 'key', 'registry', 'branch', 'draft', 'keep'],
release: ['repo', 'tag', 'out', 'notes', 'commit', 'merge', 'sign', 'key'],
publish: ['repo', 'tag', 'sign', 'key', 'registry', 'draft', 'notes', 'no-preflight', 'no-checks', 'force'],
publish: ['repo', 'tag', 'sign', 'key', 'registry', 'draft', 'notes', 'no-preflight', 'no-checks', 'force', 'keep-release'],
unrelease: ['repo', 'tag', 'registry', 'yes'],
};
function assertKnownFlags(command: string, f: Flags): void {
@@ -107,6 +110,26 @@ function signKey(f: Flags): string | undefined {
return f.sign === 'true' ? (f.key || defaultKeyPath()) : f.sign;
}
/**
* First signed update onto an unsigned history (`--merge` + `--sign`): the registry requires
* every version signed once a key is present, so sign the older versions too — or say exactly
* what is missing. See retro-sign.ts.
*/
async function maybeRetroSign(
entry: { authorPublicKey?: string; versions: Array<{ version: string; downloadUrl: string; sha256: string; signature?: string }> },
keyPath: string | undefined,
): Promise<void> {
if (!needsRetroSign(entry)) return;
if (!keyPath) {
fail(
`this entry carries your signing key, but ${entry.versions.filter((v) => !v.signature).length} older version(s) are unsigned — ` +
'the registry requires every version signed once a key is present. Re-run with --sign so they can be signed for you.',
);
}
console.error('older versions are unsigned — signing them with your key so the registry accepts the update');
await retroSignVersions(entry, keyPath!, (line) => console.error(line));
}
/**
* Resolve the repo + tag every publishing command needs. Interactive: prompt for
* whatever is missing. Non-interactive: reproduce the command's exact error so
@@ -322,6 +345,7 @@ async function dispatch(command: string, f: Flags, positional: string[]): Promis
commit: f.commit, asset: f.asset, mergePath: f.merge,
signKeyPath: signKey(f), now: new Date().toISOString(),
});
await maybeRetroSign(entry, signKey(f));
const json = JSON.stringify(entry, null, 2) + '\n';
if (f.out) {
fs.writeFileSync(f.out, json);
@@ -384,6 +408,7 @@ async function dispatch(command: string, f: Flags, positional: string[]): Promis
dir, repo, tag,
signKeyPath, signing, registry: f.registry, draft: !!f.draft,
notes: f.notes, skipPreflight: !!f['no-preflight'], skipChecks: !!f['no-checks'], force: !!f.force,
keepRelease: !!f['keep-release'],
now: new Date().toISOString(),
log: tui ? clackLogSink : undefined,
});
@@ -400,12 +425,12 @@ async function dispatch(command: string, f: Flags, positional: string[]): Promis
const ok = await promptConfirm({ message: 'Open the registry PR now?', initialValue: true });
if (!ok) { outro('Cancelled — no PR opened.'); return; }
const s = spinner(); s.start('Opening the registry PR');
const { prUrl } = submitEntry(entry, { registry: f.registry, branch: f.branch, draft: !!f.draft, keep: !!f.keep });
const { prUrl } = await submitEntry(entry, { registry: f.registry, branch: f.branch, draft: !!f.draft, keep: !!f.keep, signKeyPath: signKey(f) });
s.stop('Registry PR opened');
console.log(prUrl);
} else {
console.error(`Opening a registry PR for ${entry.id} ${entry.versions[0].version}…`);
const { prUrl } = submitEntry(entry, { registry: f.registry, branch: f.branch, draft: !!f.draft, keep: !!f.keep });
const { prUrl } = await submitEntry(entry, { registry: f.registry, branch: f.branch, draft: !!f.draft, keep: !!f.keep, signKeyPath: signKey(f) });
console.log(prUrl);
}
} else if (command === 'release') {
@@ -421,6 +446,7 @@ async function dispatch(command: string, f: Flags, positional: string[]): Promis
execFileSync('gh', ['release', 'create', tag, packed.artifact, '--repo', repo, '--title', tag, '--notes', f.notes || `Release ${tag}`], { stdio: 'pipe' });
s.stop(`Released ${tag} on ${repo}`);
const entry = buildEntry({ dir, repo, tag, zipPath: packed.artifact, commit: f.commit, mergePath: f.merge, signKeyPath: signKey(f), now: new Date().toISOString() });
await maybeRetroSign(entry, signKey(f));
logInfo(`Registry entry (add as registry/plugins/${entry.id}.json, or run \`npx trek-plugin-sdk submit\`):`);
process.stdout.write(JSON.stringify(entry, null, 2) + '\n');
} else {
@@ -429,9 +455,28 @@ async function dispatch(command: string, f: Flags, positional: string[]): Promis
console.error(`Creating GitHub release ${tag} on ${repo}…`);
execFileSync('gh', ['release', 'create', tag, packed.artifact, '--repo', repo, '--title', tag, '--notes', f.notes || `Release ${tag}`], { stdio: 'inherit' });
const entry = buildEntry({ dir, repo, tag, zipPath: packed.artifact, commit: f.commit, mergePath: f.merge, signKeyPath: signKey(f), now: new Date().toISOString() });
await maybeRetroSign(entry, signKey(f));
console.error('\nRegistry entry (add as registry/plugins/' + entry.id + '.json in a TREK-Plugins PR, or run `npx trek-plugin-sdk submit`):\n');
process.stdout.write(JSON.stringify(entry, null, 2) + '\n');
}
} else if (command === 'unrelease') {
if (positional[0]) f.tag = positional[0];
const { repo, tag } = await ensureRepoTag(f, 'unrelease needs a tag and --repo <owner/name>: trek-plugin unrelease vX.Y.Z --repo <owner/name>');
const dir = positional[1] || '.';
let yes = !!f.yes;
if (tui && !yes) {
const ok = await promptConfirm({
message: `Delete the GitHub release, remote tag and local tag ${tag} on ${repo}?`,
initialValue: false,
});
if (!ok) { outro('Cancelled — nothing was deleted.'); return; }
yes = true; // the human just consented — that covers the registry-unreachable guard too
}
const { deleted } = await unrelease({ dir, tag, repo, registry: f.registry, yes, log: tui ? clackLogSink : undefined });
const summary = deleted.length
? `Deleted: ${deleted.join(', ')} — ${tag} is free to publish again.`
: `Nothing to delete — no release or tags found for ${tag}.`;
if (tui) logSuccess(summary); else console.error(summary);
} else {
console.error(`unknown command: ${command}\n${USAGE}`);
process.exit(2);
+6 -1
View File
@@ -215,6 +215,10 @@ export const PERMISSION_FAMILIES: PermissionFamily[] = [
{ value: 'hook:trip-warning-provider', hint: 'Raise validation warnings on a trip (shown in the planner)' },
{ value: 'hook:table-contributor', hint: 'Add columns to TREK\'s tables' },
{ value: 'hook:map-marker-provider', hint: 'Add your own markers to the map' },
{ value: 'hook:map-layer-provider', hint: 'Draw routes, corridors and zones on the trip map' },
{ value: 'hook:route-provider', hint: 'Offer routing profiles the planner can route days with (e.g. EV with charging stops)' },
{ value: 'hook:day-schedule-provider', hint: 'Attach time contributions to the day plan (charging, security, buffers)' },
{ value: 'hook:day-tint-provider', hint: 'Colour-code days in the day plan (e.g. which leg of the trip each day belongs to)' },
{ value: 'hook:pdf-section-provider', hint: 'Add a section to the exported trip PDF' },
{ value: 'hook:atlas-layer-provider', hint: 'Add a layer to the Atlas map' },
{ value: 'hook:journal-entry-provider', hint: 'Contribute entries to a journey' },
@@ -252,6 +256,7 @@ export const PERMISSION_FAMILIES: PermissionFamily[] = [
{ value: 'notify:send', hint: 'Send a TREK notification to a user or trip' },
{ value: 'ai:invoke', hint: 'Call the instance\'s configured AI model' },
{ value: 'oauth:client', hint: 'Obtain OAuth access tokens for the user' },
{ value: 'geolocation:read', hint: 'Ask the host for the browser\'s live position in your frames (browser prompt still applies)' },
],
},
];
@@ -263,7 +268,7 @@ export const PERMISSION_CATALOG: { value: string; label: string; hint: string; f
);
/** Every grantable permission id. Derived — never hand-maintained. */
export const KNOWN_PERMISSIONS: string[] = PERMISSION_CATALOG.map((p) => p.value);
export const PICKER_PERMISSIONS: string[] = PERMISSION_CATALOG.map((p) => p.value);
// ── reporter seam (for commands that log their own progress, e.g. publish) ────
+110
View File
@@ -0,0 +1,110 @@
/**
* trek-plugin unrelease <tag> — undo a release that never made it into the registry.
*
* A failed publish (or a change of heart before the PR merges) leaves up to three things
* behind: the GitHub release, the remote tag, and the local tag. Cleaning them up by hand
* is three commands in the right order; this is that, with one hard safety rail:
*
* A version that IS published in the registry is immutable — the registry pins the
* artifact's sha256, so deleting or re-cutting its release breaks install/update for
* everyone who already has it. unrelease refuses those outright, with no override.
*/
import path from 'node:path';
import { execFileSync } from 'node:child_process';
import { readJsonFile } from './json.js';
import { DEFAULT_REGISTRY } from './checks/network.js';
import { plainLog, type LogSink } from './ui.js';
function git(dir: string, args: string[]): string {
return execFileSync('git', ['-C', dir, ...args], { encoding: 'utf8', stdio: 'pipe' }).toString().trim();
}
interface PublishedIndex { plugins?: Array<{ id?: string; versions?: Array<{ version?: string }> }> }
/**
* The published registry index, or null when it cannot be read (offline, mirror down).
* Null is the dangerous answer — the caller must then have explicit consent (--yes).
*/
async function publishedIndex(registry: string): Promise<PublishedIndex | null> {
try {
const r = await fetch(`https://raw.githubusercontent.com/${registry}/main/dist/index.json`, {
headers: { 'User-Agent': 'trek-plugin' },
});
if (!r.ok) return null;
return (await r.json()) as PublishedIndex;
} catch {
return null;
}
}
export async function unrelease(opts: {
dir: string; tag: string; repo: string; registry?: string;
/** Consent to delete when the registry index cannot be verified. */
yes?: boolean;
log?: LogSink;
}): Promise<{ deleted: string[] }> {
const log = opts.log ?? plainLog;
const dir = path.resolve(opts.dir);
const { tag, repo } = opts;
const registry = opts.registry || DEFAULT_REGISTRY;
const manifest = readJsonFile<{ id?: unknown }>(path.join(dir, 'trek-plugin.json'));
const id = String(manifest.id ?? '');
const version = tag.replace(/^v/, '');
const index = await publishedIndex(registry);
if (index === null) {
if (!opts.yes) {
throw new Error(
`could not read the registry index (${registry}) to verify ${id} ${version} is not published.\n` +
`Deleting a PUBLISHED version's release breaks its sha256 pin for everyone who installed it.\n` +
`If you are sure this version never merged into the registry, re-run with --yes.`,
);
}
log(` ! registry unreachable — proceeding on --yes`);
} else {
const mine = index.plugins?.find((p) => p.id === id);
if (mine?.versions?.some((v) => v.version === version)) {
throw new Error(
`${id} ${version} is PUBLISHED in the registry (${registry}) — its release is immutable.\n` +
`The registry pins this artifact's sha256; deleting the release would break install/update\n` +
`for everyone who has it. Ship a new version instead. (There is deliberately no override.)`,
);
}
}
// Delete in blast-radius order: release, remote tag, local tag. Each is best-effort and
// reported, so a partial previous cleanup doesn't stop the rest.
const deleted: string[] = [];
let hasRelease = false;
try { execFileSync('gh', ['release', 'view', tag, '--repo', repo], { stdio: 'pipe' }); hasRelease = true; } catch { /* absent */ }
if (hasRelease) {
execFileSync('gh', ['release', 'delete', tag, '--repo', repo, '--yes'], { stdio: 'pipe' });
deleted.push('release');
log(` ✓ deleted release ${tag} on ${repo}`);
} else {
log(` - no release ${tag} on ${repo}`);
}
let hasRemoteTag = false;
try { hasRemoteTag = git(dir, ['ls-remote', '--tags', 'origin', `refs/tags/${tag}`]) !== ''; } catch { /* no origin — nothing to delete */ }
if (hasRemoteTag) {
git(dir, ['push', 'origin', `:refs/tags/${tag}`]);
deleted.push('remote tag');
log(` ✓ deleted remote tag ${tag}`);
} else {
log(` - no tag ${tag} on origin`);
}
let hasLocalTag = false;
try { git(dir, ['rev-parse', `${tag}^{commit}`]); hasLocalTag = true; } catch { /* absent */ }
if (hasLocalTag) {
git(dir, ['tag', '-d', tag]);
deleted.push('local tag');
log(` ✓ deleted local tag ${tag}`);
} else {
log(` - no local tag ${tag}`);
}
return { deleted };
}
+6 -3
View File
@@ -91,7 +91,10 @@ function embeddedTransitionIpv4(g: number[]): string | null {
/** Expand an IPv6 literal into its 8 numeric hextets, or null if not a valid IPv6. */
function expandV6(ip: string): number[] | null {
let h = ip.toLowerCase().replace(/%.*$/, '');
// Cut the zone id off (`fe80::1%eth0`): indexOf rather than a `%.*$` regex, whose
// greedy tail rescans the whole string once per `%` on a host that never matches.
const zone = ip.indexOf('%');
let h = (zone === -1 ? ip : ip.slice(0, zone)).toLowerCase();
if (!h.includes(':')) return null;
const dotted = h.match(/^(.*:)(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/);
if (dotted) {
@@ -104,9 +107,9 @@ function expandV6(ip: string): number[] | null {
const head = halves[0] ? halves[0].split(':') : [];
const tail = halves.length === 2 && halves[1] ? halves[1].split(':') : [];
const groups =
halves.length === 2 ? [...head, ...Array(8 - head.length - tail.length).fill('0'), ...tail] : head;
halves.length === 2 ? [...head, ...new Array(8 - head.length - tail.length).fill('0'), ...tail] : head;
if (groups.length !== 8) return null;
const nums = groups.map((x) => (x === '' ? NaN : parseInt(x, 16)));
const nums = groups.map((x) => (x === '' ? Number.NaN : Number.parseInt(x, 16)));
return nums.some((n) => !Number.isInteger(n) || n < 0 || n > 0xffff) ? null : nums;
}
+351
View File
@@ -0,0 +1,351 @@
// GENERATED — do not edit by hand.
// Source: server/src/nest/plugins/protocol/envelope.ts + server/src/plugin-event-sink.ts
// Regenerate: node --import tsx server/scripts/gen-plugin-facts.ts
export const HOOK_PERMISSION: Readonly<Record<string, string>> = {
photoProvider: 'hook:photo-provider',
calendarSource: 'hook:calendar-source',
placeDetailProvider: 'hook:place-detail-provider',
warningProvider: 'hook:trip-warning-provider',
tableContributor: 'hook:table-contributor',
mapMarkerProvider: 'hook:map-marker-provider',
mapLayerProvider: 'hook:map-layer-provider',
routeProvider: 'hook:route-provider',
dayScheduleProvider: 'hook:day-schedule-provider',
dayTintProvider: 'hook:day-tint-provider',
pdfSectionProvider: 'hook:pdf-section-provider',
atlasLayerProvider: 'hook:atlas-layer-provider',
journalEntryProvider: 'hook:journal-entry-provider',
tripCardProvider: 'hook:trip-card-provider',
notificationChannel: 'hook:notification-channel',
};
export const KNOWN_PERMISSIONS: string[] = [
'db:own',
'db:read:trips',
'db:read:users',
'db:read:costs',
'db:read:packing',
'db:write:packing',
'db:read:files',
'db:read:files:content',
'db:write:files',
'db:read:collab',
'db:write:collab',
'db:write:members',
'db:create:trips',
'db:read:journal',
'db:read:atlas',
'rates:read',
'db:read:vacay',
'db:read:daynotes',
'db:read:collections',
'db:write:collections',
'db:write:atlas',
'db:write:vacay',
'db:write:journal',
'db:read:categories',
'db:read:tags',
'db:write:tags',
'db:read:todos',
'db:write:todos',
'weather:read',
'db:write:daynotes',
'db:write:costs',
'db:write:places',
'db:write:days',
'db:write:itinerary',
'db:write:trips',
'db:write:reservations',
'db:write:accommodations',
'db:meta',
'ws:broadcast:trip',
'ws:broadcast:user',
'hook:photo-provider',
'hook:calendar-source',
'hook:place-detail-provider',
'hook:trip-warning-provider',
'hook:table-contributor',
'hook:map-marker-provider',
'hook:map-layer-provider',
'hook:route-provider',
'hook:day-schedule-provider',
'hook:day-tint-provider',
'hook:pdf-section-provider',
'hook:atlas-layer-provider',
'hook:journal-entry-provider',
'hook:trip-card-provider',
'hook:notification-channel',
'hook:user-data',
'events:subscribe',
'jobs:run',
'http:outbound',
'notify:send',
'ai:invoke',
'oauth:client',
'geolocation:read',
];
export const METHOD_PERMISSION: Readonly<Record<string, string>> = {
'db.exec': 'db:own',
'db.query': 'db:own',
'db.migrate': 'db:own',
'db.tx': 'db:own',
'trips.getById': 'db:read:trips',
'trips.getPlaces': 'db:read:trips',
'trips.getReservations': 'db:read:trips',
'trips.getDays': 'db:read:trips',
'trips.getAccommodations': 'db:read:trips',
'trips.listMine': 'db:read:trips',
'reservations.listMine': 'db:read:trips',
'reservations.create': 'db:write:reservations',
'reservations.update': 'db:write:reservations',
'reservations.delete': 'db:write:reservations',
'accommodations.create': 'db:write:accommodations',
'accommodations.update': 'db:write:accommodations',
'accommodations.delete': 'db:write:accommodations',
'packing.list': 'db:read:packing',
'packing.create': 'db:write:packing',
'packing.update': 'db:write:packing',
'packing.delete': 'db:write:packing',
'packing.listBags': 'db:write:packing',
'packing.createBag': 'db:write:packing',
'packing.updateBag': 'db:write:packing',
'packing.deleteBag': 'db:write:packing',
'packing.setBagMembers': 'db:write:packing',
'files.list': 'db:read:files',
'files.getContent': 'db:read:files:content',
'files.create': 'db:write:files',
'files.createLink': 'db:write:files',
'files.update': 'db:write:files',
'files.softDelete': 'db:write:files',
'collab.listNotes': 'db:read:collab',
'collab.listPolls': 'db:read:collab',
'collab.listMessages': 'db:read:collab',
'collab.createNote': 'db:write:collab',
'collab.createPoll': 'db:write:collab',
'collab.votePoll': 'db:write:collab',
'collab.createMessage': 'db:write:collab',
'trips.addMember': 'db:write:members',
'trips.removeMember': 'db:write:members',
'trips.create': 'db:create:trips',
'journal.listMine': 'db:read:journal',
'journal.getEntries': 'db:read:journal',
'atlas.visited': 'db:read:atlas',
'atlas.bucketList': 'db:read:atlas',
'rates.get': 'rates:read',
'vacay.mine': 'db:read:vacay',
'daynotes.list': 'db:read:daynotes',
'daynotes.create': 'db:write:daynotes',
'daynotes.update': 'db:write:daynotes',
'daynotes.delete': 'db:write:daynotes',
'collections.listMine': 'db:read:collections',
'collections.get': 'db:read:collections',
'collections.create': 'db:write:collections',
'collections.update': 'db:write:collections',
'collections.savePlace': 'db:write:collections',
'collections.copyToTrip': 'db:write:collections',
'collections.deletePlace': 'db:write:collections',
'atlas.markCountry': 'db:write:atlas',
'atlas.unmarkCountry': 'db:write:atlas',
'atlas.markRegion': 'db:write:atlas',
'atlas.unmarkRegion': 'db:write:atlas',
'atlas.createBucketItem': 'db:write:atlas',
'atlas.deleteBucketItem': 'db:write:atlas',
'vacay.toggleEntry': 'db:write:vacay',
'vacay.toggleCompanyHoliday': 'db:write:vacay',
'journal.createEntry': 'db:write:journal',
'journal.updateEntry': 'db:write:journal',
'journal.deleteEntry': 'db:write:journal',
'journal.createJourney': 'db:write:journal',
'journal.deleteJourney': 'db:write:journal',
'weather.get': 'weather:read',
'categories.list': 'db:read:categories',
'tags.list': 'db:read:tags',
'tags.create': 'db:write:tags',
'tags.update': 'db:write:tags',
'tags.delete': 'db:write:tags',
'trips.members': 'db:read:trips',
'todos.list': 'db:read:todos',
'todos.create': 'db:write:todos',
'todos.update': 'db:write:todos',
'todos.delete': 'db:write:todos',
'costs.getByTrip': 'db:read:costs',
'costs.listMine': 'db:read:costs',
'costs.create': 'db:write:costs',
'costs.update': 'db:write:costs',
'costs.delete': 'db:write:costs',
'places.create': 'db:write:places',
'places.update': 'db:write:places',
'places.delete': 'db:write:places',
'days.create': 'db:write:days',
'days.update': 'db:write:days',
'days.delete': 'db:write:days',
'itinerary.assign': 'db:write:itinerary',
'itinerary.unassign': 'db:write:itinerary',
'trips.update': 'db:write:trips',
'meta.get': 'db:meta',
'meta.set': 'db:meta',
'meta.list': 'db:meta',
'meta.delete': 'db:meta',
'users.getById': 'db:read:users',
'ws.broadcastToTrip': 'ws:broadcast:trip',
'ws.broadcastToUser': 'ws:broadcast:user',
'notify.send': 'notify:send',
'ai.complete': 'ai:invoke',
'ai.extract': 'ai:invoke',
'oauth.getToken': 'oauth:client',
'scheduler.set': 'jobs:run',
'scheduler.cancel': 'jobs:run',
};
export const KNOWN_METHODS: string[] = [
'db.exec',
'db.query',
'db.migrate',
'db.tx',
'trips.getById',
'trips.getPlaces',
'trips.getReservations',
'trips.getDays',
'trips.getAccommodations',
'trips.listMine',
'reservations.listMine',
'reservations.create',
'reservations.update',
'reservations.delete',
'accommodations.create',
'accommodations.update',
'accommodations.delete',
'packing.list',
'packing.create',
'packing.update',
'packing.delete',
'packing.listBags',
'packing.createBag',
'packing.updateBag',
'packing.deleteBag',
'packing.setBagMembers',
'files.list',
'files.getContent',
'files.create',
'files.createLink',
'files.update',
'files.softDelete',
'collab.listNotes',
'collab.listPolls',
'collab.listMessages',
'collab.createNote',
'collab.createPoll',
'collab.votePoll',
'collab.createMessage',
'trips.addMember',
'trips.removeMember',
'trips.create',
'journal.listMine',
'journal.getEntries',
'atlas.visited',
'atlas.bucketList',
'rates.get',
'vacay.mine',
'daynotes.list',
'daynotes.create',
'daynotes.update',
'daynotes.delete',
'collections.listMine',
'collections.get',
'collections.create',
'collections.update',
'collections.savePlace',
'collections.copyToTrip',
'collections.deletePlace',
'atlas.markCountry',
'atlas.unmarkCountry',
'atlas.markRegion',
'atlas.unmarkRegion',
'atlas.createBucketItem',
'atlas.deleteBucketItem',
'vacay.toggleEntry',
'vacay.toggleCompanyHoliday',
'journal.createEntry',
'journal.updateEntry',
'journal.deleteEntry',
'journal.createJourney',
'journal.deleteJourney',
'weather.get',
'categories.list',
'tags.list',
'tags.create',
'tags.update',
'tags.delete',
'trips.members',
'todos.list',
'todos.create',
'todos.update',
'todos.delete',
'costs.getByTrip',
'costs.listMine',
'costs.create',
'costs.update',
'costs.delete',
'places.create',
'places.update',
'places.delete',
'days.create',
'days.update',
'days.delete',
'itinerary.assign',
'itinerary.unassign',
'trips.update',
'meta.get',
'meta.set',
'meta.list',
'meta.delete',
'users.getById',
'ws.broadcastToTrip',
'ws.broadcastToUser',
'notify.send',
'ai.complete',
'ai.extract',
'oauth.getToken',
'scheduler.set',
'scheduler.cancel',
];
export const USER_DATA_PERMISSION = 'hook:user-data';
export const EVENTS_PERMISSION = 'events:subscribe';
export const JOBS_PERMISSION = 'jobs:run';
export const HTTP_OUTBOUND_PREFIX = 'http:outbound:';
/**
* Core-event catalog. Delivery names are the WebSocket broadcast names,
* `<family>:<verb>` (e.g. `place:created`). A subscribed plugin receives
* `{event, tripId, entity?, entityId?, snapshot?}`; `snapshot` is delivered only
* when the plugin also holds EVENT_SNAPSHOT_GRANT[family]. Delete/reorder/bulk
* events carry no snapshot.
*/
export const EVENT_FAMILIES: readonly string[] = [
'accommodation',
'assignment',
'budget',
'day',
'dayNote',
'file',
'packing',
'place',
'reservation',
'trip',
];
export const EVENT_SNAPSHOT_GRANT: Readonly<Record<string, string>> = {
place: 'db:read:trips',
day: 'db:read:trips',
reservation: 'db:read:trips',
accommodation: 'db:read:trips',
assignment: 'db:read:trips',
trip: 'db:read:trips',
budget: 'db:read:costs',
packing: 'db:read:packing',
dayNote: 'db:read:daynotes',
file: 'db:read:files',
};
+250 -19
View File
@@ -23,6 +23,11 @@ export interface BudgetItem { id: number; trip_id?: number; name?: string; total
export interface Assignment { id: number; day_id?: number; place_id?: number; notes?: string | null; [k: string]: unknown }
export interface User { id: number; username?: string; display_name?: string | null; avatar?: string | null; [k: string]: unknown }
/** Every ctx.* call is rate-limited per plugin at the host RPC dispatch boundary:
* burst 60, sustained 20/s, 16 in-flight. A throttled call is refused (retryable)
* rather than executed, with:
* HOST_ERROR: rate limit exceeded — slow down ctx.* calls
* A legitimate plugin never hits the generous burst. See README § Runtime limits. */
export interface PluginContext {
readonly id: string;
readonly config: Readonly<Record<string, unknown>>;
@@ -32,6 +37,9 @@ export interface PluginContext {
settings: {
get(key: string): Promise<unknown>;
};
/** Your OWN sqlite database (`db:own`) — a separate file the plugin never gets a
* path or connection to directly. Quota: 256 MB per plugin (writes past it fail);
* result sets are capped at 100,000 rows. See `tx()` below for the atomic-batch cap. */
db: {
query<T = unknown>(sql: string, ...args: unknown[]): Promise<T[]>;
exec(sql: string, ...args: unknown[]): Promise<{ changes: number }>;
@@ -42,10 +50,15 @@ export interface PluginContext {
tx(ops: Array<{ sql: string; args?: unknown[] }>): Promise<{ results: Array<{ changes?: number; rows?: unknown[] }> }>;
};
trips: {
getById(tripId: number, asUserId?: number): Promise<Trip | null>;
getPlaces(tripId: number, asUserId?: number): Promise<Place[]>;
// `asUserId` is accepted for source compatibility but IGNORED by the host —
// trip reads are always membership-checked against the authenticated user of
// the current invocation (the request's `req.user`), which the plugin cannot
// override. Only reachable from a route handler (a user context); a job has
// no user and its trip reads are refused.
getById(tripId: number, /** @deprecated ignored by the host */ asUserId?: number): Promise<Trip | null>;
getPlaces(tripId: number, /** @deprecated ignored by the host */ asUserId?: number): Promise<Place[]>;
/** Hydrated like the REST list: each row carries `endpoints`, `day_positions` + the day/place joins. */
getReservations(tripId: number, asUserId?: number): Promise<Reservation[]>;
getReservations(tripId: number, /** @deprecated ignored by the host */ asUserId?: number): Promise<Reservation[]>;
/** The trip's days with their `assignments` + `notes_items` (the planner GET's shape). Needs `db:read:trips`. */
getDays(tripId: number): Promise<Day[]>;
/** The trip's lodging blocks (day_accommodations) with joined place fields. Needs `db:read:trips`. */
@@ -97,7 +110,9 @@ export interface PluginContext {
update(tripId: number, itemId: number, input: Record<string, unknown>): Promise<PackingItem>;
/** Delete a packing item. Needs `db:write:packing` + packing_edit. */
delete(tripId: number, itemId: number): Promise<{ deleted: boolean }>;
/** List/create/update/delete packing bags + set members (no privacy). Needs `db:write:packing` + packing_edit. */
// List/create/update/delete packing bags + set members (no privacy). Needs
// `db:write:packing` + packing_edit.
/** Needs 'db:write:packing' (intentional — bags are the write-side structure; packing.list is the read surface). */
listBags(tripId: number): Promise<unknown[]>;
createBag(tripId: number, input: { name: string; color?: string }): Promise<unknown>;
updateBag(tripId: number, bagId: number, input: Record<string, unknown>): Promise<unknown>;
@@ -133,13 +148,17 @@ export interface PluginContext {
};
/** Host-mediated notification. The plugin supplies only target + plain text; the host
* owns delivery + preferences. Recipient is FORCED to the acting user (scope 'user',
* targetId = the acting user) or a trip they belong to (scope 'trip'). Needs `notify:send`. */
* targetId = the acting user) or a trip they belong to (scope 'trip'). Needs `notify:send`.
* Daily budget: 100/day per plugin (UTC midnight rollover); past it `send` throws
* "daily notification budget exhausted (resets at UTC midnight)". See README § Runtime limits. */
notify: {
send(input: { title: string; body: string; link?: string; scope: 'user' | 'trip'; targetId: number }): Promise<{ sent: boolean }>;
};
/** Host-mediated LLM using the admin/user-configured provider — the plugin never holds a
* key. `complete` returns { text }; `extract` returns { results } for your JSON schema.
* Output is DATA: to persist it, push it through the gated write methods yourself. Needs `ai:invoke`. */
* Output is DATA: to persist it, push it through the gated write methods yourself. Needs `ai:invoke`.
* Daily budget: 200/day per plugin (UTC midnight rollover); past it these throw
* "daily AI budget exhausted (resets at UTC midnight)". See README § Runtime limits. */
ai: {
complete(prompt: string, system?: string): Promise<{ text: string }>;
extract(text: string, jsonSchema: object, prompt?: string): Promise<{ results: Record<string, unknown>[] }>;
@@ -147,7 +166,17 @@ export interface PluginContext {
/** Host-brokered outbound OAuth: a short-lived access token for the ACTING USER of a
* third-party service the host connected on their behalf (Settings → Plugins → Connect).
* Returns null when the user hasn't connected or in a userless context. The host holds
* the refresh token + client secret — you never see them. Needs `oauth:client`. */
* the refresh token + client secret — you never see them. Needs `oauth:client`.
*
* The host runs the whole flow (authorize -> callback -> token exchange -> refresh)
* with PKCE + a 10-minute state TTL. Provider config is the plugin's admin-owned
* INSTANCE settings — declare `scope:'instance'` manifest fields named
* `oauth_authorize_url`, `oauth_token_url`, `oauth_scopes` (optional),
* `oauth_client_id`, `oauth_client_secret` and the admin fills them in. Both
* endpoint URLs must be https and may not point at loopback/`.local`/`.internal`/
* private/metadata addresses. The host exposes
* `/api/plugin-oauth/:id/status|connect|callback|disconnect` for the connect UI —
* plugin code only ever calls `getAccessToken()`. See README § OAuth broker. */
oauth: {
getAccessToken(): Promise<string | null>;
};
@@ -282,7 +311,9 @@ export interface PluginContext {
};
// Your OWN namespaced key/value store on a trip/place/day (#1429) — enrich core
// entities without forking the schema. Needs `db:meta`; the entity must belong to
// a trip the current user can access. Values are JSON-serialisable.
// a trip the current user can access. Values are JSON-serialisable. Quotas (per
// plugin + entity): 64 KB serialized JSON per value, 256 chars per key, 100 keys.
// See README § Runtime limits.
meta: {
get(entityType: 'trip' | 'place' | 'day' | 'reservation' | 'accommodation', entityId: number, key: string): Promise<unknown>;
set(entityType: 'trip' | 'place' | 'day' | 'reservation' | 'accommodation', entityId: number, key: string, value: unknown): Promise<unknown>;
@@ -361,7 +392,8 @@ export interface Photo {
export interface PhotoProvider {
/** Search your photo backend. `ctx` is the last arg so you can reach it via
* ctx.settings/oauth/http. Needs `hook:photo-provider`. Surfaced in the photo picker
* and at `GET /api/plugin-photos/search`; thumbnail/full URLs must be http/https. */
* and at `GET /api/plugin-photos/search`; thumbnail/full URLs must be http/https.
* The host caps results at 60 photos per page. */
search(query: string, opts: { page: number; limit: number }, ctx: PluginContext): Promise<{ photos: Photo[]; total: number; hasMore: boolean }>;
getById(id: string, ctx: PluginContext): Promise<Photo | null>;
}
@@ -421,18 +453,21 @@ export interface CalendarSource {
// start/end are ISO strings — the host->plugin boundary is JSON, so a Date would
// arrive as a string anyway (kept in lockstep with the runtime SDK copy). `ctx` is the
// last arg. Aggregated for the signed-in user at `GET /api/plugin-calendar`.
// The host caps results at 500 events per source per request.
getEvents(userId: number, start: string, end: string, ctx: PluginContext): Promise<CalendarEvent[]>;
}
/** One row of extra place info TREK renders natively (reviews/ratings/links/…). */
export interface PlaceDetailItem { label: string; value?: string; url?: string; }
export interface PlaceDetailProvider {
/** Extra info for a place; core calls this for a `place-detail` panel. Needs `hook:place-detail-provider`. */
/** Extra info for a place; core calls this for a `place-detail` panel. Needs `hook:place-detail-provider`.
* The host caps results at 12 items per provider. */
getDetails(placeId: number, ctx: PluginContext): Promise<PlaceDetailItem[]>;
}
/** A validation/warning a plugin raises on a trip; TREK surfaces it in the planner. */
export interface TripWarning { level: 'info' | 'warning' | 'error'; message: string; dayId?: number; placeId?: number; }
export interface WarningProvider {
/** Problems/warnings for a trip (e.g. overpacked day, place closed). Needs `hook:trip-warning-provider`. */
/** Problems/warnings for a trip (e.g. overpacked day, place closed). Needs `hook:trip-warning-provider`.
* The host caps results at 20 warnings per provider, each message truncated to 300 chars. */
getWarnings(tripId: number, ctx: PluginContext): Promise<TripWarning[]>;
}
@@ -466,7 +501,8 @@ export type TableContribution = TableColumnContribution | TableActionContributio
export interface TableContributor {
/** `view` is one of 'reservations' | 'places' | 'day' | 'costs' | 'packing' | 'files'.
* Runs with the current user bound, on a short timeout; a slow/failing call is
* skipped, never fatal. Needs `hook:table-contributor`. */
* skipped, never fatal. Needs `hook:table-contributor`. The host caps results at
* 20 columns and 10 actions per entity. */
getContributions(view: string, tripId: number, ctx: PluginContext): Promise<TableContribution[]>;
}
@@ -485,10 +521,163 @@ export interface MapMarkerContribution {
export interface MapMarkerProvider {
/** Return markers to overlay on a trip's map. Runs with the current user bound,
* on a short timeout; the host caps the marker count and skips a failing call.
* Needs `hook:map-marker-provider`. */
* Needs `hook:map-marker-provider`. The host caps results at 200 markers per provider. */
getMarkers(tripId: number, ctx: PluginContext): Promise<MapMarkerContribution[]>;
}
/** One shape in a map layer. Declarative only — the host draws it; styling is the
* tone palette plus clamped numerics (width 1–8, opacity 0.05–1) and a dash enum. */
export interface MapLayerFeature {
type: 'polyline' | 'polygon' | 'circle';
points?: Array<[number, number]>; // [lat,lng] pairs — polyline (≥2) / polygon (≥3)
center?: [number, number]; // circle center [lat,lng]
radiusM?: number; // circle radius in metres (1..2,000,000)
tone?: ContributionTone;
width?: number; // stroke width, clamped 1..8 (default 3)
dash?: 'solid' | 'dash' | 'dot'; // stroke style (default solid)
opacity?: number; // stroke opacity, clamped 0.05..1 (default 0.8)
fill?: boolean; // polygon/circle: tint the inside (default true)
label?: string; // short tooltip text (≤80 chars)
}
/** A bounded vector overlay the host renders onto the trip map — a computed route,
* a reachable-range corridor, a zone. Complements mapMarkerProvider (points). */
export interface MapLayerContribution {
id: string; // stable per-layer id (React key / dedupe)
name?: string; // short layer name
features: MapLayerFeature[]; // host caps: 4 layers + 150 features + 8000 vertices per plugin
}
export interface MapLayerProvider {
/** Return layers to overlay on a trip's map. Runs with the current user bound,
* on a short timeout; the host caps the vertex budget and skips a failing call.
* Needs `hook:map-layer-provider`. */
getLayers(tripId: number, ctx: PluginContext): Promise<MapLayerContribution[]>;
}
/** One waypoint of a route request — a located stop of the day being routed. */
export interface RouteWaypoint {
lat: number;
lng: number;
name?: string; // the stop's display name, when known
placeId?: number; // the TREK place behind this stop, when it is one
}
/** What the planner asks a routeProvider to route. */
export interface RouteRequest {
tripId: number;
dayId: number | null; // the selected day, when the request is day-scoped
profile: string; // one of the plugin's declared capabilities.routeProfiles ids
waypoints: RouteWaypoint[]; // 2..30 located stops, in visit order
}
/** One leg of the returned route — between consecutive request waypoints. */
export interface RouteLeg {
distance: number; // metres
duration: number; // seconds (driving + any stop time you fold into the leg)
note?: string; // short text shown on the leg connector (e.g. "25 min charge"), ≤120 chars
}
/** An intermediate stop on the returned route (a charging stop, a rest area). */
export interface RouteViaPoint {
lat: number;
lng: number;
label?: string; // short marker text, ≤80 chars
tone?: ContributionTone;
dwellSeconds?: number; // planned time at the stop (0..86400)
}
/** A computed route. The host validates it whole: coordinates are range-checked
* (≤10000 vertices), legs must be exactly waypoints-1 entries, vias are capped
* at 40 — a malformed result is discarded and the planner falls back to straight
* lines, like an OSRM outage. */
export interface RouteProviderResult {
coordinates: Array<[number, number]>; // [lat,lng] polyline of the whole route
distance: number; // metres, whole route
duration: number; // seconds, whole route
legs: RouteLeg[];
viaPoints?: RouteViaPoint[];
}
export interface RouteProvider {
/** Route the given waypoints under one of the plugin's declared profiles
* (`capabilities.routeProfiles`). Runs with the current user bound, on a 20 s
* timeout (room for an external solver via declared egress); a failing call
* falls back to straight lines. Needs `hook:route-provider`. */
getRoute(request: RouteRequest, ctx: PluginContext): Promise<RouteProviderResult>;
}
/** A time contribution the host renders into the day plan — "35 min charging at
* this stop", "45 min security before this flight". Anchored to an assignment or
* reservation row (or the start/end of a day); `minutes` also counts into the
* day's route-footer total. */
export interface DayScheduleContribution {
id: string; // stable per-item id (React key / dedupe)
dayId: number; // must be a day of the requested trip
assignmentId?: number; // anchor under this itinerary place row…
reservationId?: number; // …or under this booking row…
position?: 'start' | 'end'; // …or at the start/end of the day (default 'end')
minutes?: number; // planned time, 1..1440 — shown and totalled
label: string; // short text (≤120 chars)
tone?: ContributionTone;
}
export interface DayScheduleProvider {
/** Return schedule contributions for a trip's days. Runs with the current user
* bound, on a short timeout; the host caps the item count (≤60/plugin) and
* skips a failing call. Needs `hook:day-schedule-provider`. */
getSchedule(tripId: number, ctx: PluginContext): Promise<DayScheduleContribution[]>;
}
/** A colour the host paints into one day card in the Plan sidebar (and into that day's
* mobile chip) — so a trip split into legs shows its leg membership while you scroll
* the itinerary.
*
* Pick a `tone` from the shared palette, or send your own `#rrggbb` when four tones
* cannot keep your legs apart — a twenty-stop trip needs twenty colours. Either way
* you choose the hue and the host chooses the weight: it sets the alpha per theme and
* per region and clamps a colour's lightness into a band that reads on both the light
* and the dark sidebar. So the tint always lands as a wash behind the day, never as a
* fill, and no colour you send can make a day unreadable. Anything that is not exactly
* six hex digits is ignored (`#RGB` shorthand and CSS names included).
*
* The card has three separately tintable regions. Set `tone` / `color` to paint all of
* them, or name regions individually for finer control — e.g. a bold badge marking the
* leg with the activity list left plain, so a dense day stays easy to read.
*
* The regions map onto the DESKTOP day card's layout. The mobile day strip is built
* differently and honours only the badge region, as the day chip's tint; header and
* activity tints do not render on phones. So treat the badge (or the shorthands, which
* include it) as the one region every user sees, and the finer regions as desktop
* refinement.
*
* Colour is decoration, not information: pair it with `label` (and with a
* dayScheduleProvider row where it matters) so the meaning survives for anyone who
* cannot tell your legs apart by hue. */
export interface DayTintContribution {
dayId: number; // must be a day of the requested trip
/** Shorthands: paint every region you do NOT name below. Omit both and only the
* regions you name are tinted. `color` wins over `tone` at the same level. */
tone?: ContributionTone;
color?: string; // your own colour, `#rrggbb` only
/** The day-number badge — the smallest, boldest mark. Also tints the mobile day chip. */
badgeTone?: ContributionTone;
badgeColor?: string;
/** The day header row (number, title, date, cost). Its hover state deepens the tint. */
headerTone?: ContributionTone;
headerColor?: string;
/** The expanded activity list — places, bookings and transport for the day. The
* largest surface and the one behind the densest text, so it is tinted faintest. */
activityTone?: ContributionTone;
activityColor?: string;
label?: string; // optional tooltip on the day (≤60 chars)
}
export interface DayTintProvider {
/** Return one tint per day you want coloured — the natural cap is the trip's day
* count, so this scales to a six-month itinerary where a per-day dayScheduleProvider
* item would hit the ≤60 limit. Runs with the current user bound, on a short
* timeout; a failing call is skipped.
*
* A day takes at most one contribution — it is resolved whole, per day, never
* per region. Within your own list the first entry for a day wins; across plugins
* the first granted provider wins. Both are deterministic, so a day never flickers
* between two colours, and two plugins can never each own part of one card.
* Needs `hook:day-tint-provider`. */
getDayTints(tripId: number, ctx: PluginContext): Promise<DayTintContribution[]>;
}
/** A text-only section the host appends to a trip's PDF export. Declarative only —
* plain strings the host lays out and escapes; no markup ever reaches the document. */
export interface PdfSection {
@@ -499,7 +688,8 @@ export interface PdfSection {
export interface PdfSectionProvider {
/** Return sections to append to a trip's PDF export. Runs with the current user
* bound, on a short timeout; the host caps counts/lengths and skips a failing
* call. Needs `hook:pdf-section-provider`. */
* call. Needs `hook:pdf-section-provider`. The host caps results at 5 sections
* per provider (see `PdfSection` above for the per-section paragraph/table caps). */
getSections(tripId: number, ctx: PluginContext): Promise<PdfSection[]>;
}
@@ -515,7 +705,8 @@ export interface AtlasLayerProvider {
/** Return tint layers for the ACTING USER's Atlas map. User-scoped — the host binds
* the current user; the hook takes no target parameter. Runs on a short timeout;
* the host caps the layer/country counts and skips a failing call.
* Needs `hook:atlas-layer-provider`. */
* Needs `hook:atlas-layer-provider`. The host caps results at 3 layers per provider
* (see `AtlasLayer` above for the per-layer country cap). */
getLayers(ctx: PluginContext): Promise<AtlasLayer[]>;
}
@@ -534,7 +725,8 @@ export interface TripCardProvider {
/** Return badges for the dashboard trip cards currently on screen. `tripIds` are
* exactly those cards (each already access-checked for the acting user). Runs with
* the current user bound, on a short timeout; the host caps the badge count and
* skips a failing call. Needs `hook:trip-card-provider`. */
* skips a failing call. Needs `hook:trip-card-provider`. The host caps results at
* 4 badges per trip, 240 total per provider. */
getCards(tripIds: number[], ctx: PluginContext): Promise<TripCardContribution[]>;
}
@@ -550,11 +742,12 @@ export interface JournalEntryProvider {
/** A core-event subscription (#1429 eco). Handlers run with NO user (like a job).
* Needs `events:subscribe`. */
export interface PluginEventSubscription {
/** A core event name (e.g. `place:created`, `day:updated`, `file:created`) or `*` for all. */
/** A core event name `<family>:<verb>` (e.g. `place:created`, `day:updated`, `file:created`)
* where `<family>` is a value in EVENT_FAMILIES, or `*` for all. */
on: string;
// `entity` = the event family (e.g. 'reservation'); `entityId` = WHICH entity changed,
// when known. `snapshot` = a whitelisted field view of the changed entity, delivered
// only when the plugin also holds the family's db:read:* grant — never user ids,
// only when the plugin also holds EVENT_SNAPSHOT_GRANT[family] — never user ids,
// private packing items or secrets; delete/reorder/bulk events carry none. Still no
// acting user: a trip read from the handler is refused.
handler(payload: { event: string; tripId: number; entity?: string; entityId?: number; snapshot?: Record<string, unknown> }, ctx: PluginContext): Promise<void> | void;
@@ -604,6 +797,10 @@ export interface PluginDefinition {
warningProvider?: WarningProvider;
tableContributor?: TableContributor;
mapMarkerProvider?: MapMarkerProvider;
mapLayerProvider?: MapLayerProvider;
routeProvider?: RouteProvider;
dayScheduleProvider?: DayScheduleProvider;
dayTintProvider?: DayTintProvider;
pdfSectionProvider?: PdfSectionProvider;
atlasLayerProvider?: AtlasLayerProvider;
journalEntryProvider?: JournalEntryProvider;
@@ -621,7 +818,16 @@ export function definePlugin(def: PluginDefinition): PluginDefinition {
return def;
}
export { validateManifest, CHANNEL_EVENTS, type PluginManifest, type ValidationResult } from './manifest.js';
export {
validateManifest,
CHANNEL_EVENTS,
type PluginManifest,
type NormalizedManifest,
type ValidationResult,
type ManifestSettingField,
type ManifestAction,
type ManifestCapabilities,
} from './manifest.js';
export { createMockHost, type MockHostOptions } from './mock-host.js';
// The permissions TREK enforces OUTSIDE ctx — hooks, events, jobs, egress. An entry
// point you implement without its grant is never called in production, silently; these
@@ -630,6 +836,31 @@ export {
PermissionDenied, HOOK_PERMISSION, USER_DATA_PERMISSION, EVENTS_PERMISSION, JOBS_PERMISSION,
grantGaps, grantedHosts, type GrantGap, type PluginEntryPoints,
} from './permissions.js';
// The core-event catalog: families and the snapshot-delivery permission each family requires.
export {
EVENT_FAMILIES, EVENT_SNAPSHOT_GRANT, KNOWN_PERMISSIONS,
} from './generated/host-facts.js';
/** Scope for host-managed, per-user session state in a sandboxed plugin UI. */
export type PluginSessionStorageScope = 'plugin' | 'trip';
/** Limits enforced independently for the plugin scope and each trip scope. */
export const PLUGIN_SESSION_MAX_KEYS = 32;
export const PLUGIN_SESSION_MAX_KEY_LENGTH = 64;
export const PLUGIN_SESSION_MAX_VALUE_BYTES = 1024;
export interface PluginSessionStorageOptions {
scope?: PluginSessionStorageScope;
}
/** The `window.trek.session` surface. Values must be JSON-serialisable. */
export interface PluginSessionStorage {
get<T = unknown>(key: string, options?: PluginSessionStorageOptions): Promise<T | undefined>;
set(key: string, value: unknown, options?: PluginSessionStorageOptions): Promise<void>;
remove(key: string, options?: PluginSessionStorageOptions): Promise<void>;
clear(options?: PluginSessionStorageOptions): Promise<void>;
}
// The design kit for page/widget UIs: inline these into your client/index.html
// (or drop a `<!-- trek:ui -->` marker and let `dev`/`pack` expand it) to get the
// native TREK look — glass, hover, buttons, inputs — plus a `window.trek` bridge.
+145 -41
View File
@@ -10,24 +10,69 @@ export interface PluginDependency {
id: string;
version: string;
}
export interface ManifestSettingField {
key: string;
label?: string;
input_type?: string;
placeholder?: string;
hint?: string;
required?: boolean;
secret?: boolean;
scope?: 'instance' | 'user';
options?: Array<string | number | { value: string | number; label?: string }>;
oauth?: { initPath?: string; callbackPath?: string };
}
export interface ManifestAction {
key: string;
label?: string;
hint?: string;
danger?: boolean;
}
export interface ManifestCapabilities {
settingsUi?: boolean;
widget?: { title?: string; defaultSize?: string; slot?: 'sidebar' | 'hero' | 'place-detail' | 'day-detail' | 'reservation-detail' };
tripPage?: { replaces?: string[]; position?: number };
notificationChannel?: { title?: string; events?: string[] };
routeProfiles?: Array<{ id: string; label: string; icon?: string }>;
provides?: string[];
emits?: string[];
}
export interface PluginManifest {
id: string;
name: string;
version: string;
apiVersion: number;
/** The semver RANGE of TREK versions this plugin supports (">=3.2.0 <4.0.0"). */
/** The semver RANGE of TREK versions this plugin supports (">=4.0.0 <5.0.0"). */
trek: string;
type: 'integration' | 'page' | 'widget' | 'trip-page';
apiVersion?: number;
permissions?: string[];
egress?: string[];
nativeModules?: boolean;
operatorEgress?: boolean;
requiredAddons?: string[];
pluginDependencies?: PluginDependency[];
capabilities?: ManifestCapabilities;
settings?: ManifestSettingField[];
actions?: ManifestAction[];
icon?: string;
author?: string;
description?: string;
homepage?: string;
tags?: string[];
license?: string;
}
export interface NormalizedManifest extends PluginManifest {
apiVersion: number;
permissions: string[];
egress: string[];
nativeModules?: boolean;
nativeModules: false;
requiredAddons: string[];
pluginDependencies: PluginDependency[];
}
export interface ValidationResult {
ok: boolean;
errors: string[];
manifest?: PluginManifest;
manifest?: NormalizedManifest;
}
const ID_RE = /^[a-z][a-z0-9-]{2,39}$/;
@@ -75,25 +120,8 @@ export const CHANNEL_EVENTS = [
// This is THE list. `create`'s permission picker is built from it (see PERMISSION_FAMILIES
// in cli/ui.ts, which only supplies the grouping and hints), so a permission added here can
// never again go missing from the scaffolder — test/cli.test.ts fails until it has an entry.
export const KNOWN_PERMISSIONS = [
'db:own',
'db:read:trips', 'db:read:users', 'db:read:costs', 'db:read:packing', 'db:read:files',
'db:read:files:content', 'db:read:collab',
'db:read:journal', 'db:read:atlas', 'db:read:vacay', 'db:read:daynotes', 'db:read:collections',
'db:read:categories', 'db:read:tags', 'db:read:todos',
'db:write:costs', 'db:write:places', 'db:write:days', 'db:write:itinerary', 'db:write:trips',
'db:write:reservations', 'db:write:accommodations', 'db:write:packing', 'db:write:files',
'db:write:collab', 'db:write:members', 'db:write:collections', 'db:write:atlas', 'db:write:vacay',
'db:write:journal', 'db:write:tags', 'db:write:todos', 'db:write:daynotes',
'db:create:trips',
'db:meta',
'ws:broadcast:trip', 'ws:broadcast:user',
'hook:photo-provider', 'hook:calendar-source', 'hook:place-detail-provider', 'hook:trip-warning-provider',
'hook:table-contributor', 'hook:map-marker-provider', 'hook:pdf-section-provider', 'hook:atlas-layer-provider',
'hook:journal-entry-provider', 'hook:trip-card-provider', 'hook:notification-channel', 'hook:user-data',
'events:subscribe', 'jobs:run', 'http:outbound',
'weather:read', 'rates:read', 'notify:send', 'ai:invoke', 'oauth:client',
];
export { KNOWN_PERMISSIONS } from './generated/host-facts.js';
import { KNOWN_PERMISSIONS } from './generated/host-facts.js';
function isKnownPermission(p: string): boolean {
return KNOWN_PERMISSIONS.includes(p) || p.startsWith('http:outbound:');
@@ -140,8 +168,8 @@ export function validateManifest(raw: unknown): ValidationResult {
if (!isSatisfiableRange(m.trek)) {
errors.push(
typeof m.trek === 'string' && m.trek
? `"trek" is not a satisfiable semver range: "${m.trek}" (e.g. ">=3.2.0 <4.0.0")`
: 'missing "trek" — declare the TREK versions this plugin supports, e.g. ">=3.2.0 <4.0.0"',
? `"trek" is not a satisfiable semver range: "${m.trek}" (e.g. ">=4.0.0 <5.0.0")`
: 'missing "trek" — declare the TREK versions this plugin supports, e.g. ">=4.0.0 <5.0.0"',
);
}
if (m.apiVersion !== undefined && typeof m.apiVersion !== 'number') errors.push('apiVersion must be a number');
@@ -178,6 +206,7 @@ export function validateManifest(raw: unknown): ValidationResult {
widget?: { slot?: unknown };
tripPage?: { replaces?: unknown; position?: unknown };
notificationChannel?: { title?: unknown; events?: unknown };
routeProfiles?: unknown;
provides?: unknown;
emits?: unknown;
settingsUi?: unknown;
@@ -222,6 +251,39 @@ export function validateManifest(raw: unknown): ValidationResult {
}
}
}
// Mirrors the server's routeProfiles parsing: the planner's route picker shows these,
// so they must be well-formed and only exist alongside the routeProvider grant.
const routeProfiles = capabilities?.routeProfiles;
// Normalized routeProfiles entries (icon dropped when non-string, like the server's
// optStr()) — populated only when routeProfiles is present and shaped as an array;
// used to build the output below in place of the raw, possibly-dirty input array.
let normalizedRouteProfiles: Array<{ id: string; label: string; icon?: string }> | undefined;
if (routeProfiles !== undefined) {
if (!permissions.includes('hook:route-provider')) {
errors.push('capabilities.routeProfiles requires the "hook:route-provider" permission');
}
if (!Array.isArray(routeProfiles)) errors.push('capabilities.routeProfiles must be an array');
else {
if (routeProfiles.length > 3) errors.push('capabilities.routeProfiles: at most 3 profiles');
const seen = new Set<string>();
normalizedRouteProfiles = [];
for (const v of routeProfiles) {
const p = (v && typeof v === 'object' ? v : {}) as { id?: unknown; label?: unknown; icon?: unknown };
const id = typeof p.id === 'string' ? p.id : '';
if (!/^[a-z][a-z0-9-]{0,23}$/.test(id)) errors.push('capabilities.routeProfiles: id must be lowercase [a-z][a-z0-9-], max 24 chars');
else if (seen.has(id)) errors.push(`capabilities.routeProfiles: duplicate id "${id}"`);
else seen.add(id);
const label = typeof p.label === 'string' ? p.label.trim() : '';
if (!label || label.length > 40) errors.push('capabilities.routeProfiles: label is required (max 40 chars)');
// icon is optional; a non-string icon is silently dropped, not rejected — mirrors
// the server's optStr() (server/src/nest/plugins/install/manifest.ts:519-521),
// which returns undefined for a non-string value rather than throwing. Length is
// never rejected either — the server slices to 40 chars at install time.
const icon = typeof p.icon === 'string' ? p.icon : undefined;
normalizedRouteProfiles.push(icon !== undefined ? { id, label, icon } : { id, label });
}
}
}
// Settings keys become JSON object keys in the plugin's stored config, so they are
// constrained (mirrors the server's SETTING_KEY_RE). `__proto__`/`constructor` would
// resolve off Object.prototype on read and make a required field look configured for
@@ -237,6 +299,33 @@ export function validateManifest(raw: unknown): ValidationResult {
if (s.scope !== undefined && s.scope !== 'user' && s.scope !== 'instance') {
errors.push(`settings["${key}"].scope must be "user" or "instance"`);
}
if (s.options !== undefined) {
if (!Array.isArray(s.options)) {
errors.push('settings option list must be an array');
} else {
for (const o of s.options) {
if (typeof o === 'string' || typeof o === 'number') continue;
if (o && typeof o === 'object') {
const value = (o as { value?: unknown }).value;
if (value === undefined || value === null || String(value) === '') {
errors.push('settings option must have a non-empty "value"');
}
} else {
errors.push(`invalid settings option ${JSON.stringify(o)} (expected a string or { value, label })`);
}
}
}
}
if (s.oauth !== undefined) {
if (!s.oauth || typeof s.oauth !== 'object' || Array.isArray(s.oauth)) {
errors.push('settings oauth must be an object');
} else {
for (const k of ['initPath', 'callbackPath'] as const) {
const v = (s.oauth as Record<string, unknown>)[k];
if (v !== undefined && typeof v !== 'string') errors.push(`settings oauth.${k} must be a string`);
}
}
}
}
}
// Settings-page action buttons ("Test connection"). Keys share the settings-key rules.
@@ -263,23 +352,38 @@ export function validateManifest(raw: unknown): ValidationResult {
const pluginDependencies = validatePluginDependencies(m.pluginDependencies, typeof m.id === 'string' ? m.id : '', errors);
if (errors.length) return { ok: false, errors };
return {
ok: true,
errors: [],
manifest: {
id: m.id as string,
name: m.name as string,
version: m.version as string,
apiVersion: typeof m.apiVersion === 'number' ? m.apiVersion : 1,
trek: m.trek as string,
type: m.type as PluginManifest['type'],
permissions,
egress,
nativeModules: false,
requiredAddons,
pluginDependencies,
},
const manifest: NormalizedManifest = {
id: m.id as string,
name: m.name as string,
version: m.version as string,
apiVersion: typeof m.apiVersion === 'number' ? m.apiVersion : 1,
trek: m.trek as string,
type: m.type as PluginManifest['type'],
permissions,
egress,
nativeModules: false,
requiredAddons,
pluginDependencies,
};
// Carried through verbatim when present — absent stays absent (no undefined keys) — except
// routeProfiles, which is rebuilt from normalizedRouteProfiles so a dropped (non-string)
// icon doesn't leak the raw input value back out.
if (m.capabilities !== undefined) {
const rawCapabilities = m.capabilities as ManifestCapabilities;
manifest.capabilities = normalizedRouteProfiles !== undefined
? { ...rawCapabilities, routeProfiles: normalizedRouteProfiles }
: rawCapabilities;
}
if (m.settings !== undefined) manifest.settings = m.settings as ManifestSettingField[];
if (m.actions !== undefined) manifest.actions = m.actions as ManifestAction[];
if (m.operatorEgress !== undefined) manifest.operatorEgress = m.operatorEgress as boolean;
if (m.icon !== undefined) manifest.icon = m.icon as string;
if (m.author !== undefined) manifest.author = m.author as string;
if (m.description !== undefined) manifest.description = m.description as string;
if (m.homepage !== undefined) manifest.homepage = m.homepage as string;
if (m.tags !== undefined) manifest.tags = m.tags as string[];
if (m.license !== undefined) manifest.license = m.license as string;
return { ok: true, errors: [], manifest };
}
// Export/event names exposed to other plugins (dots allowed for event names).
+114 -5
View File
@@ -1,4 +1,5 @@
import type { PluginContext, PluginDefinition, PluginRequest, PluginResponse, Trip, Place, Day, Reservation, PackingItem, TripFile, BudgetItem, User, NotificationMessage, PluginActionResult } from './index.js';
import { PLUGIN_SESSION_MAX_KEYS, PLUGIN_SESSION_MAX_KEY_LENGTH, PLUGIN_SESSION_MAX_VALUE_BYTES } from './index.js';
import type { PluginContext, PluginDefinition, PluginRequest, PluginResponse, Trip, Place, Day, Reservation, PackingItem, TripFile, BudgetItem, User, NotificationMessage, PluginActionResult, PluginSessionStorage } from './index.js';
import { CHANNEL_EVENTS } from './manifest.js';
import { PermissionDenied, HOOK_PERMISSION, USER_DATA_PERMISSION, EVENTS_PERMISSION, JOBS_PERMISSION } from './permissions.js';
@@ -49,6 +50,8 @@ export interface MockHostOptions {
queryResults?: Record<string, unknown[]>;
/** The host-bound acting user for costs.* (a job/onLoad has none → refused). */
actingUserId?: number;
/** Trip bound to the mock plugin UI's `session` helper. Required for scope: 'trip'. */
sessionTripId?: number | string;
/** Whether the Costs (budget) addon is enabled; gates all costs.* (default true). */
budgetAddonEnabled?: boolean;
/** Same idea for the other gated subsystems (default true): journey gates
@@ -104,6 +107,18 @@ export interface MockHostOptions {
aiResults?: Record<string, unknown>[];
/** The acting user's connected-service token for ctx.oauth.getAccessToken (default null). */
oauthAccessToken?: string | null;
/** Daily cap on ctx.ai.complete/ctx.ai.extract calls, mirroring the host's
* per-plugin daily-budget broker (daily-budget.ts). Default 200; `0` disables
* the broker entirely, so the FIRST call fails with the exhaustion string.
* Unlike the real host, this is a plain in-memory counter for the life of this
* mock host: it never rolls over at UTC midnight — there is no timer here, and
* no wall-clock window. A test that wants to see the budget "reset" should
* create a fresh mock host rather than wait. */
aiPerDay?: number;
/** Same idea as `aiPerDay`, for ctx.notify.send. Default 100; `0` disables the
* broker (first call fails with the exhaustion string). See `aiPerDay` for the
* no-rollover caveat — this counter never resets on its own either. */
notifyPerDay?: number;
}
/** Drives a plugin's OWN entry points against the mock ctx — the missing half of a
@@ -157,6 +172,8 @@ export interface MockHost {
* read or write refuses with RESOURCE_FORBIDDEN). Shares this host's fixtures,
* grants and recorders. */
userlessCtx: PluginContext;
/** In-memory equivalent of `window.trek.session`, with production quota enforcement. */
session: PluginSessionStorage;
/** Everything the plugin did, for assertions. */
calls: { method: string; args: unknown[] }[];
logs: { level: string; msg: string }[];
@@ -197,11 +214,14 @@ function stripLeadingComments(sql: string): string {
// The host's stripEmoji (text-sanitize.ts), copied so notify.send cleans/rejects the
// same strings without a server import: colour emoji + sequence glue removed, then
// the horizontal gaps they leave are collapsed. An all-emoji title becomes ''.
const EMOJI_RE = /\p{Emoji_Presentation}|\p{Emoji_Modifier}|\p{Regional_Indicator}|[\u200D\uFE00-\uFE0F\u20E3\u{E0020}-\u{E007F}]/gu;
const EMOJI_RE = /\p{Emoji_Presentation}|\p{Emoji_Modifier}|\p{Regional_Indicator}|\u200D|[\uFE00-\uFE0F\u20E3\u{E0020}-\u{E007F}]/gu;
function stripEmoji(s: string): string {
const stripped = s.replace(EMOJI_RE, '');
if (stripped === s) return s;
return stripped.replace(/[^\S\r\n]{2,}/g, ' ').replace(/ +$/gm, '').trim();
// Trailing-space trim as the host spells it: the char in front of the run (or the
// line start) comes into the match and goes back out, so the run is only walked
// from its own start instead of restarting inside every space of a long one.
return stripped.replace(/[^\S\r\n]{2,}/g, ' ').replace(/(^|[^ ]) +$/gm, '$1').trim();
}
// The host's settings-key rules (install/manifest.ts). A field the host would refuse to
@@ -229,6 +249,13 @@ function settingsBlob(src: Record<string, unknown> | undefined, what: string): R
const PLACE_STR_LIMITS: Record<string, number> = { name: 200, description: 2000, address: 500, notes: 2000 };
const TRIP_STR_LIMITS: Record<string, number> = { title: 200, description: 2000 };
// ctx.meta quotas, mirrored from meta.rpc.ts's disk-DoS guard: value size (characters
// of the serialized JSON, matching the host — UTF-16 code units, not UTF-8 bytes),
// key length, and keys per (plugin, entity).
const META_VALUE_MAX = 64 * 1024;
const META_KEY_MAX = 256;
const META_KEYS_MAX = 100;
export function createMockHost(opts: MockHostOptions = {}): MockHost {
const grants = new Set(opts.grants ?? []);
const calls: MockHost['calls'] = [];
@@ -236,6 +263,60 @@ export function createMockHost(opts: MockHostOptions = {}): MockHost {
const broadcasts: MockHost['broadcasts'] = [];
const emitted: MockHost['emitted'] = [];
const notifications: MockHost['notifications'] = [];
const sessionValues = new Map<string, string>();
// The real bridge rejects with a plain Error carrying the code on `.code`
// (ui/kit.ts). Keep the `CODE: message` text the rest of this mock uses, but
// attach `.code` too, so a plugin that branches on it behaves the same here.
const sessionError = (code: string, message: string) => {
const err = new Error(`${code}: ${message}`) as Error & { code: string };
err.code = code;
return err;
};
const sessionPrefix = (scope: 'plugin' | 'trip') => {
if (scope === 'trip' && opts.sessionTripId === undefined) {
throw sessionError('NO_TRIP_CONTEXT', 'trip session storage requires a trip context');
}
return scope === 'trip' ? `trip:${opts.sessionTripId}:` : 'plugin:';
};
const sessionKey = (key: string, scope: 'plugin' | 'trip') => {
// Scope before key, in the host's order — otherwise the same bad call
// reports a different code here than it does in the app.
const prefix = sessionPrefix(scope);
if (!key || key.length > PLUGIN_SESSION_MAX_KEY_LENGTH) {
throw sessionError('SESSION_INVALID_KEY', `session key must be 1-${PLUGIN_SESSION_MAX_KEY_LENGTH} characters`);
}
return `${prefix}${key}`;
};
const session: PluginSessionStorage = {
async get(key, options) {
const raw = sessionValues.get(sessionKey(key, options?.scope === 'trip' ? 'trip' : 'plugin'));
return raw === undefined ? undefined : JSON.parse(raw);
},
async set(key, value, options) {
const fullKey = sessionKey(key, options?.scope === 'trip' ? 'trip' : 'plugin');
const serialized = JSON.stringify(value);
if (serialized === undefined) throw sessionError('SESSION_INVALID_VALUE', 'session value must be JSON-serialisable');
const valueBytes = Buffer.byteLength(serialized, 'utf8');
if (valueBytes > PLUGIN_SESSION_MAX_VALUE_BYTES) {
throw sessionError('SESSION_VALUE_TOO_LARGE', `session value exceeds ${PLUGIN_SESSION_MAX_VALUE_BYTES} bytes`);
}
const prefix = sessionPrefix(options?.scope === 'trip' ? 'trip' : 'plugin');
const scopedKeyCount = [...sessionValues.keys()].filter((storedKey) => storedKey.startsWith(prefix)).length;
if (!sessionValues.has(fullKey) && scopedKeyCount >= PLUGIN_SESSION_MAX_KEYS) {
throw sessionError('SESSION_KEY_LIMIT', `plugin session storage allows at most ${PLUGIN_SESSION_MAX_KEYS} keys`);
}
sessionValues.set(fullKey, serialized);
},
async remove(key, options) {
sessionValues.delete(sessionKey(key, options?.scope === 'trip' ? 'trip' : 'plugin'));
},
async clear(options) {
const prefix = sessionPrefix(options?.scope === 'trip' ? 'trip' : 'plugin');
for (const key of sessionValues.keys()) {
if (key.startsWith(prefix)) sessionValues.delete(key);
}
},
};
// Validated once, up front: a fixture the host could never have installed should fail
// the test at construction, not silently at the first get().
const userSettings = settingsBlob(opts.userSettings, 'userSettings');
@@ -313,6 +394,14 @@ export function createMockHost(opts: MockHostOptions = {}): MockHost {
const metaStore: Record<string, unknown> = {};
const metaKey = (et: string, eid: number, key: string) => `${et}:${eid}:${key}`;
// Per-host daily budgets for ai.*/notify.send, mirroring daily-budget.ts. Plain
// counters, no timers: this mock never rolls the window over at UTC midnight (see
// the MockHostOptions docblocks) — a test wanting a fresh budget creates a new host.
const aiPerDay = opts.aiPerDay ?? 200;
const notifyPerDay = opts.notifyPerDay ?? 100;
let aiUsed = 0;
let notifyUsed = 0;
const buildCtx = (actingUserId: number | undefined): PluginContext => {
const requireActingUser = (): number => {
if (actingUserId === undefined) throw new Error('RESOURCE_FORBIDDEN: this call requires an authenticated user context');
@@ -757,6 +846,8 @@ export function createMockHost(opts: MockHostOptions = {}): MockHost {
if (!input.link.startsWith('/') || input.link.startsWith('//')) throw new Error('link must be an in-app path starting with /');
link = input.link.slice(0, 512);
}
if (notifyUsed >= notifyPerDay) throw new Error('daily notification budget exhausted (resets at UTC midnight)');
notifyUsed += 1;
notifications.push({ title, body, ...(link ? { link } : {}), scope, targetId: input.targetId });
return { sent: true };
},
@@ -764,10 +855,14 @@ export function createMockHost(opts: MockHostOptions = {}): MockHost {
ai: {
async complete() {
need('ai:invoke', 'ai.complete');
if (aiUsed >= aiPerDay) throw new Error('daily AI budget exhausted (resets at UTC midnight)');
aiUsed += 1;
return { text: opts.aiText ?? '' };
},
async extract() {
need('ai:invoke', 'ai.extract');
if (aiUsed >= aiPerDay) throw new Error('daily AI budget exhausted (resets at UTC midnight)');
aiUsed += 1;
return { results: opts.aiResults ?? [] };
},
},
@@ -1292,7 +1387,21 @@ export function createMockHost(opts: MockHostOptions = {}): MockHost {
async set(entityType, entityId, key, value) {
need('db:meta', 'meta.set');
metaGate(entityType, entityId);
metaStore[metaKey(entityType, entityId, key)] = value ?? null;
// Quota order mirrors meta.rpc.ts: key length -> value size -> key count.
if (key.length > META_KEY_MAX) throw new Error(`metadata key too long (>${META_KEY_MAX} chars)`);
const json = JSON.stringify(value ?? null);
// Matches the host exactly: json.length (UTF-16 code units of the serialized
// JSON), not Buffer.byteLength (UTF-8 bytes) — see meta.rpc.ts:71.
if (json.length > META_VALUE_MAX) {
throw new Error(`metadata value too large (>${META_VALUE_MAX} bytes)`);
}
const fullKey = metaKey(entityType, entityId, key);
if (!(fullKey in metaStore)) {
const prefix = `${entityType}:${entityId}:`;
const count = Object.keys(metaStore).filter((k) => k.startsWith(prefix)).length;
if (count >= META_KEYS_MAX) throw new Error(`too many metadata keys on this ${entityType} (max ${META_KEYS_MAX})`);
}
metaStore[fullKey] = value ?? null;
return { key, value: value ?? null };
},
async list(entityType, entityId) {
@@ -1486,7 +1595,7 @@ export function createMockHost(opts: MockHostOptions = {}): MockHost {
},
});
return { ctx, userlessCtx, calls, logs, broadcasts, emitted, notifications, scheduled: scheduledTasks, run };
return { ctx, userlessCtx, session, calls, logs, broadcasts, emitted, notifications, scheduled: scheduledTasks, run };
}
// `trek-plugin-sdk/testing` resolves to this module, so re-export what a test needs to
+21 -25
View File
@@ -14,32 +14,28 @@
export class PermissionDenied extends Error {}
/**
* hooks.<key> → the permission that must ALSO be granted for TREK to ever call it.
* Mirrors HOOK_PERMISSION in the host's supervisor (plugin-supervisor.ts): a plugin
* provides a hook only if it BOTH implements it and holds this grant.
* hooks.<key> -> the permission that must ALSO be granted for TREK to ever call it, plus
* the three capability gates that are not hooks.* keys.
*
* These are GENERATED from the host's single source, server/src/nest/plugins/protocol/
* envelope.ts, by server/scripts/gen-plugin-facts.ts. They used to be a hand-kept copy
* guarded by a regex scrape of plugin-supervisor.ts in test/permissions-parity.test.ts -
* which only ran from prepublishOnly, so drift would have surfaced as a broken release.
*
* The re-exported types stay WIDE (Readonly<Record<string, string>>), exactly as before:
* grantGaps below indexes HOOK_PERMISSION with a plain string, and this package compiles
* under "strict": true.
*/
export const HOOK_PERMISSION: Readonly<Record<string, string>> = {
photoProvider: 'hook:photo-provider',
calendarSource: 'hook:calendar-source',
placeDetailProvider: 'hook:place-detail-provider',
warningProvider: 'hook:trip-warning-provider',
tableContributor: 'hook:table-contributor',
mapMarkerProvider: 'hook:map-marker-provider',
pdfSectionProvider: 'hook:pdf-section-provider',
atlasLayerProvider: 'hook:atlas-layer-provider',
journalEntryProvider: 'hook:journal-entry-provider',
tripCardProvider: 'hook:trip-card-provider',
notificationChannel: 'hook:notification-channel',
};
/** Gates the GDPR handlers (deleteUserData / exportUserData). Not a hooks.* key. */
export const USER_DATA_PERMISSION = 'hook:user-data';
/** Gates event subscriptions — without it the host delivers the plugin nothing. */
export const EVENTS_PERMISSION = 'events:subscribe';
/** Gates jobs, and the ctx.scheduler timers that fire `scheduled`. */
export const JOBS_PERMISSION = 'jobs:run';
const HTTP_OUTBOUND = 'http:outbound:';
export {
HOOK_PERMISSION,
USER_DATA_PERMISSION,
EVENTS_PERMISSION,
JOBS_PERMISSION,
} from './generated/host-facts.js';
import {
HOOK_PERMISSION, USER_DATA_PERMISSION, EVENTS_PERMISSION, JOBS_PERMISSION,
HTTP_OUTBOUND_PREFIX as HTTP_OUTBOUND,
} from './generated/host-facts.js';
/** The structural shape of a loaded plugin that grantGaps needs. */
export interface PluginEntryPoints {
+214 -3
View File
@@ -279,6 +279,125 @@ body.trek-ui {
@media (max-width: 639px) {
.trek-modal-enter { animation: trek-drawer-enter 320ms cubic-bezier(0.32, 0.72, 0, 1); }
}
/* Mobile layer ------------------------------------------------------------- *
* TREK 4 gives the phone its own design: a translucent, border-led surface over
* a gradient, no drop shadows, and touch feedback rather than hover. The host
* hands the mobile palette (--m-*) down with the rest of the tokens whenever a
* frame is mounted inside the mobile shell, so these rules only restate the
* SHAPE — the colours come from the same variables the native screens use.
*
* Everything here is keyed on [data-form-factor="phone"], which the host sets
* from the viewport it reports. On desktop not a single rule below applies. */
[data-form-factor="phone"] .trek-ui,
[data-form-factor="phone"] body.trek-ui { font-size: 15px; }
/* The card is the workhorse. On the phone it is a translucent tile with a hairline
border and no shadow — a drop shadow over the gradient reads as a sticker. */
[data-form-factor="phone"] .trek-card {
background: var(--m-card, var(--bg-card));
border: 1px solid var(--m-cbr, var(--border-primary));
border-radius: 16px;
box-shadow: none;
padding: 14px;
-webkit-backdrop-filter: blur(30px) saturate(1.8);
backdrop-filter: blur(30px) saturate(1.8);
}
[data-form-factor="phone"] .trek-glass {
background: var(--m-glass, var(--glass-bg));
border-color: var(--m-gbr, var(--glass-border));
border-radius: 20px;
box-shadow: none;
padding: 16px;
}
/* Touch has no hover. The lift on hover never fires on a phone and the pressed
state never existed, so a tap gave no feedback at all. */
[data-form-factor="phone"] .trek-card.trek-interactive:hover,
[data-form-factor="phone"] .trek-glass.trek-interactive:hover { transform: none; box-shadow: none; }
[data-form-factor="phone"] .trek-interactive:active,
[data-form-factor="phone"] .trek-btn:active,
[data-form-factor="phone"] .trek-row:active { transform: scale(.985); opacity: .9; }
[data-form-factor="phone"] .trek-btn:hover { filter: none; }
/* 44px is the smallest target that reliably hits on a phone. */
[data-form-factor="phone"] .trek-btn { min-height: 44px; border-radius: 12px; }
[data-form-factor="phone"] .trek-row { min-height: 48px; }
/* An input below 16px makes iOS Safari zoom the page on focus, and the zoom does
not come back. This is the single most common mobile bug in embedded UI. */
[data-form-factor="phone"] .trek-input,
[data-form-factor="phone"] .trek-select,
[data-form-factor="phone"] .trek-textarea { font-size: 16px; min-height: 44px; border-radius: 12px; }
/* Ink follows the mobile palette where it exists. */
[data-form-factor="phone"] .trek-title { color: var(--m-ink, var(--text-primary)); }
[data-form-factor="phone"] .trek-sub,
[data-form-factor="phone"] .trek-muted { color: var(--m-muted, var(--text-muted)); }
/* A filling surface owns its own scrolling: the host will not scroll for it, and
a height report is discarded. Anchor the body and scroll the content. */
[data-fill] .trek-ui, [data-fill] body.trek-ui { height: 100%; overflow: hidden; }
[data-fill] .trek-scroll {
height: 100%; overflow-y: auto; -webkit-overflow-scrolling: touch;
overscroll-behavior: contain;
}
/* Building blocks the native mobile screens are made of, so a plugin does not
have to reverse-engineer them from screenshots. */
.trek-eyebrow {
font-size: 10px; font-weight: 700; letter-spacing: .09em; text-transform: uppercase;
color: var(--m-faint, var(--text-faint));
}
.trek-countpill {
display: inline-flex; align-items: center; justify-content: center;
min-width: 20px; height: 20px; padding: 0 6px; border-radius: 999px;
background: var(--m-ic, var(--bg-tertiary)); color: var(--m-muted, var(--text-muted));
font-size: 11px; font-weight: 700; font-variant-numeric: tabular-nums;
}
.trek-sectionhead {
display: flex; align-items: center; gap: 7px; width: 100%;
margin: 15px 0 2px; padding: 0 2px; background: none; border: 0;
font: inherit; text-align: left; cursor: pointer;
}
.trek-statusdot { width: 8px; height: 8px; border-radius: 999px; flex: none; background: var(--m-st-neutral, var(--text-faint)); }
.trek-statusdot[data-status="confirmed"] { background: var(--m-st-confirmed, var(--success)); }
.trek-statusdot[data-status="pending"] { background: var(--m-st-pending, var(--warning)); }
.trek-statusdot[data-status="info"] { background: var(--m-st-info, var(--info)); }
.trek-statusdot[data-status="danger"] { background: var(--m-st-danger, var(--danger)); }
.trek-iconbtn {
display: inline-grid; place-items: center; flex: none;
width: 38px; height: 38px; border-radius: 999px; cursor: pointer;
background: var(--m-ic, var(--bg-tertiary));
border: 1px solid var(--m-gbr, var(--border-primary));
color: var(--m-ink, var(--text-primary));
}
.trek-iconbtn:active { transform: scale(.94); }
.trek-field { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
.trek-field > .trek-field-label {
font-size: 9px; font-weight: 700; letter-spacing: .07em; text-transform: uppercase;
color: var(--m-faint, var(--text-faint));
}
.trek-field > .trek-field-value {
font-size: 13px; font-weight: 600; color: var(--m-ink, var(--text-primary));
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
}
.trek-segmented {
display: inline-flex; align-items: center; gap: 2px; padding: 3px; border-radius: 999px;
background: var(--m-glass, var(--bg-tertiary));
border: 1px solid var(--m-gbr, var(--border-primary));
}
.trek-segmented > button {
border: 0; background: none; cursor: pointer; font: inherit;
padding: 8px 16px; border-radius: 999px; white-space: nowrap;
font-size: 13px; font-weight: 500; color: var(--m-ink, var(--text-primary));
}
.trek-segmented > button[aria-pressed="true"],
.trek-segmented > button.on {
background: var(--m-act, var(--accent)); color: var(--m-actfg, var(--accent-text)); font-weight: 600;
}
.trek-backdrop-enter { animation: trek-backdrop-enter 180ms var(--trek-ease-quint); }
.trek-toast-enter { animation: trek-toast-enter 260ms var(--trek-ease-quint); will-change: transform, opacity; }
.trek-pie-reveal {
@@ -359,16 +478,35 @@ export const TREK_THEME_JS = `(function () {
var lastCtx = null;
var pending = {};
var pendingConfirms = {};
var pendingGeo = {};
var geoWatchers = [];
var seq = 0;
var lastH = -1;
function send(msg) { try { window.parent.postMessage(msg, '*'); } catch (e) {} }
function send(msg) { try { window.parent.postMessage(msg, '*'); return true; } catch (e) { return false; } }
// postMessage throws synchronously on a value structured clone cannot carry (a
// function, a DOM node, a Proxy). Swallowing that left the request registered and
// the promise pending forever, so the same call rejects under the mock host and
// hangs in the real one. Drop the entry and reject with the host's own code.
function unsendable(bucket, id, code, message) { delete bucket[id]; var e = new Error(message); e.code = code; return e; }
function setFlag(name, on) { if (on) { docEl.setAttribute(name, ''); } else { docEl.removeAttribute(name); } }
function applyContext(m) {
if (m.theme) { docEl.setAttribute('data-theme', m.theme); }
if (m.locale) { docEl.setAttribute('lang', m.locale); }
docEl.setAttribute('dir', m.dir === 'rtl' ? 'rtl' : 'ltr');
// Where this frame sits, and in what shape. data-form-factor drives the
// mobile layer of this stylesheet; data-surface lets a plugin tell a
// full-height tab from a widget that reports its height. The insets are the
// space the HOST already keeps clear — exposed so a plugin can align its own
// sticky chrome with the host's, not so it adds padding on top.
var vp = m.viewport || {};
if (vp.formFactor) { docEl.setAttribute('data-form-factor', vp.formFactor); }
if (vp.surface) { docEl.setAttribute('data-surface', vp.surface); }
setFlag('data-fill', vp.fill);
var ins = vp.insets || {};
docEl.style.setProperty('--trek-inset-top', (ins.top || 0) + 'px');
docEl.style.setProperty('--trek-inset-bottom', (ins.bottom || 0) + 'px');
var t = m.tokens || {};
for (var k in t) {
if (Object.prototype.hasOwnProperty.call(t, k) && t[k]) { docEl.style.setProperty(k, t[k]); }
@@ -406,6 +544,15 @@ export const TREK_THEME_JS = `(function () {
} else if (m.type === 'trek:confirm:result') {
var c = pendingConfirms[m.requestId];
if (c) { delete pendingConfirms[m.requestId]; c(!!m.confirmed); }
} else if (m.type === 'trek:geolocation:result') {
var g = pendingGeo[m.requestId];
if (g) {
delete pendingGeo[m.requestId];
if (m.error) { var gerr = new Error('geolocation: ' + m.error); gerr.code = m.error; g.reject(gerr); }
else { g.resolve(m.position || m); }
}
} else if (m.type === 'trek:geolocation:update') {
for (var w = 0; w < geoWatchers.length; w++) { try { geoWatchers[w](m.position || null, m.error || null); } catch (e) {} }
} else if (m.type === 'trek:event') {
for (var j = 0; j < evtHandlers.length; j++) { try { evtHandlers[j](m.event, m.tripId); } catch (e) {} }
}
@@ -446,9 +593,41 @@ export const TREK_THEME_JS = `(function () {
mount: function (node, target) { (target || document.body).appendChild(node); return node; }
};
var session = {
get: function (key, opts) {
var id = 's' + (++seq);
return new Promise(function (resolve, reject) {
pending[id] = { resolve: resolve, reject: reject };
if (!send({ type: 'trek:session:get', requestId: id, key: key, scope: opts && opts.scope })) { reject(unsendable(pending, id, 'SESSION_INVALID_VALUE', 'session value must be JSON-serialisable')); }
});
},
set: function (key, value, opts) {
var id = 's' + (++seq);
return new Promise(function (resolve, reject) {
pending[id] = { resolve: resolve, reject: reject };
if (!send({ type: 'trek:session:set', requestId: id, key: key, value: value, scope: opts && opts.scope })) { reject(unsendable(pending, id, 'SESSION_INVALID_VALUE', 'session value must be JSON-serialisable')); }
});
},
remove: function (key, opts) {
var id = 's' + (++seq);
return new Promise(function (resolve, reject) {
pending[id] = { resolve: resolve, reject: reject };
if (!send({ type: 'trek:session:remove', requestId: id, key: key, scope: opts && opts.scope })) { reject(unsendable(pending, id, 'SESSION_INVALID_VALUE', 'session value must be JSON-serialisable')); }
});
},
clear: function (opts) {
var id = 's' + (++seq);
return new Promise(function (resolve, reject) {
pending[id] = { resolve: resolve, reject: reject };
if (!send({ type: 'trek:session:clear', requestId: id, scope: opts && opts.scope })) { reject(unsendable(pending, id, 'SESSION_INVALID_VALUE', 'session value must be JSON-serialisable')); }
});
}
};
var api = {
context: null,
ui: ui,
session: session,
ready: function () { send({ type: 'trek:ready' }); },
requestContext: function () { send({ type: 'trek:context:request' }); },
onContext: function (cb) {
@@ -467,7 +646,7 @@ export const TREK_THEME_JS = `(function () {
var id = 'c' + (++seq);
return new Promise(function (resolve) {
pendingConfirms[id] = resolve;
send({ type: 'trek:confirm', requestId: id, title: opts.title, message: opts.message, confirmLabel: opts.confirmLabel, cancelLabel: opts.cancelLabel, danger: opts.danger });
if (!send({ type: 'trek:confirm', requestId: id, title: opts.title, message: opts.message, confirmLabel: opts.confirmLabel, cancelLabel: opts.cancelLabel, danger: opts.danger })) { delete pendingConfirms[id]; resolve(false); }
});
},
// Core-event names for the trip in view ({ event, tripId } only, no payloads) —
@@ -481,8 +660,40 @@ export const TREK_THEME_JS = `(function () {
var id = 'r' + (++seq);
return new Promise(function (resolve, reject) {
pending[id] = { resolve: resolve, reject: reject };
send({ type: 'trek:invoke', requestId: id, sub: sub, method: opts.method, body: opts.body });
if (!send({ type: 'trek:invoke', requestId: id, sub: sub, method: opts.method, body: opts.body })) { reject(unsendable(pending, id, 'error', 'invoke body must be JSON-serialisable')); }
});
},
// Host-brokered browser position (needs the geolocation:read grant; the
// browser's own site prompt still applies). get() resolves one position;
// watch(cb) streams updates — cb(position, error) — until every returned
// unsubscribe ran, which also releases the host's GPS watch.
geolocation: {
get: function () {
var id = 'g' + (++seq);
return new Promise(function (resolve, reject) {
pendingGeo[id] = { resolve: resolve, reject: reject };
send({ type: 'trek:geolocation', requestId: id, action: 'get' });
});
},
watch: function (cb) {
geoWatchers.push(cb);
if (geoWatchers.length === 1) {
var id = 'g' + (++seq);
// The start ack resolves silently; a start error (e.g. forbidden) is
// surfaced through the callback so watch() itself never throws.
pendingGeo[id] = { resolve: function () {}, reject: function (e) { try { cb(null, e && e.code ? e.code : 'unavailable'); } catch (x) {} } };
send({ type: 'trek:geolocation', requestId: id, action: 'watch' });
}
return function () {
var i = geoWatchers.indexOf(cb);
if (i >= 0) { geoWatchers.splice(i, 1); }
if (geoWatchers.length === 0) {
var cid = 'g' + (++seq);
pendingGeo[cid] = { resolve: function () {}, reject: function () {} };
send({ type: 'trek:geolocation', requestId: cid, action: 'clear' });
}
};
}
}
};
window.trek = api;
+1 -1
View File
@@ -58,7 +58,7 @@ export function makeZip(files: ZipInput[]): Buffer {
let offset = 0;
for (const f of files) {
const nameBuf = Buffer.from(f.name.replace(/\\/g, '/'), 'utf8');
const nameBuf = Buffer.from(f.name.replaceAll(/\\/g, '/'), 'utf8');
const crc = crc32(f.data);
// Deflate; fall back to stored if that somehow grows the data.
const deflated = zlib.deflateRawSync(f.data, { level: 9 });
+18
View File
@@ -241,6 +241,24 @@ describe('README helpers mirror the registry exactly', () => {
expect(missingSections('## What it does')).toEqual(['Screenshots', 'Permissions', 'Setup']);
});
it('still ignores the trailing anchor comment authors hide on a heading', () => {
const md = '## What it does <!-- #what -->\n## Screenshots<!--x-->\n##\tPermissions \n## Setup <!-- unterminated';
expect(missingSections(md)).toEqual([]);
// A heading that is nothing but a comment names no section.
expect(missingSections('# <!-- only -->')).toEqual(['What it does', 'Screenshots', 'Permissions', 'Setup']);
});
it('does not stall on a heading padded with spaces', () => {
// The old `(.+?)\s*(?:<!--.*)?$` was quadratic: ~12s at 80k spaces, ~75s at 200k.
// READMEs reach this gate from the registry's submission CI, so the padding is
// attacker-supplied. The bound is 1000x the real cost, so it fails on the shape
// of the regression, not on a slow machine.
const md = `## What it does${' '.repeat(200_000)}x\n## Screenshots\n## Permissions\n## Setup`;
const started = performance.now();
expect(missingSections(md)).toEqual([]);
expect(performance.now() - started).toBeLessThan(1000);
});
it('ignores data: URIs when looking for a screenshot, like the registry does', () => {
expect(images('![a](data:image/png;base64,xxx)')).toEqual([]);
expect(images('<img src="shot.png">')).toEqual(['shot.png']);
+36 -3
View File
@@ -4,7 +4,7 @@ import os from 'node:os';
import path from 'node:path';
import { validateManifest } from '../src/index.js';
import { scaffold } from '../src/cli/create.js';
import { PERMISSION_CATALOG, PERMISSION_FAMILIES, KNOWN_PERMISSIONS, isInteractive, missingArgs } from '../src/cli/ui.js';
import { PERMISSION_CATALOG, PERMISSION_FAMILIES, PICKER_PERMISSIONS, isInteractive, missingArgs } from '../src/cli/ui.js';
// The authoritative set — what the HOST accepts at activation. The picker must match it.
import { KNOWN_PERMISSIONS as MANIFEST_PERMISSIONS } from '../src/manifest.js';
import { resolveMenuChoice, PRIMARY_MENU, ADVANCED_MENU } from '../src/cli/menu.js';
@@ -47,7 +47,7 @@ describe('permission catalog', () => {
// list the host actually honours — so a new TREK permission fails here until `create`
// can offer it.
it('offers every permission the host accepts — no more, no less', () => {
expect([...KNOWN_PERMISSIONS].sort()).toEqual([...MANIFEST_PERMISSIONS].sort());
expect([...PICKER_PERMISSIONS].sort()).toEqual([...MANIFEST_PERMISSIONS].sort());
});
it('describes every permission, and files it in exactly one family', () => {
@@ -57,7 +57,7 @@ describe('permission catalog', () => {
.toHaveLength(1);
}
// No duplicates across families — a permission listed twice would render twice.
expect(new Set(KNOWN_PERMISSIONS).size).toBe(KNOWN_PERMISSIONS.length);
expect(new Set(PICKER_PERMISSIONS).size).toBe(PICKER_PERMISSIONS.length);
});
it('every family is non-empty and described (an empty one is a dead prompt entry)', () => {
@@ -245,3 +245,36 @@ describe('capabilities.notificationChannel validation', () => {
expect(r.errors!.join(' ')).toMatch(/requires the "hook:notification-channel" permission/);
});
});
describe('scaffold oauth:client settings', () => {
let tmp: string;
beforeEach(() => { tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'oauth-')); });
afterEach(() => { fs.rmSync(tmp, { recursive: true, force: true }); });
const OAUTH_KEYS = ['oauth_authorize_url', 'oauth_token_url', 'oauth_scopes', 'oauth_client_id', 'oauth_client_secret'];
it('scaffolds the five instance-scoped broker settings when oauth:client is granted', () => {
scaffold('oauth-plug', 'integration', tmp, { permissions: ['db:own', 'oauth:client'] });
const m = JSON.parse(fs.readFileSync(path.join(tmp, 'oauth-plug', 'trek-plugin.json'), 'utf8'));
const settings = m.settings as Array<{ key: string; secret?: boolean; scope?: string }>;
for (const key of OAUTH_KEYS) {
expect(settings.some((s) => s.key === key), `missing setting "${key}"`).toBe(true);
}
const secret = settings.find((s) => s.key === 'oauth_client_secret')!;
expect(secret.secret).toBe(true);
for (const key of OAUTH_KEYS) {
const s = settings.find((x) => x.key === key)!;
expect(s.scope, `${key}.scope`).toBe('instance');
}
expect(validateManifest(m).ok).toBe(true);
});
it('scaffolds none of the broker settings without oauth:client', () => {
scaffold('plain-oauth-plug', 'integration', tmp, { permissions: ['db:own'] });
const m = JSON.parse(fs.readFileSync(path.join(tmp, 'plain-oauth-plug', 'trek-plugin.json'), 'utf8'));
const settings = (m.settings ?? []) as Array<{ key: string }>;
for (const key of OAUTH_KEYS) {
expect(settings.some((s) => s.key === key), `unexpected setting "${key}"`).toBe(false);
}
});
});
@@ -0,0 +1,44 @@
import { describe, it, expect } from 'vitest';
import { validateManifest } from '../src/manifest.js';
describe('validateManifest normalized output', () => {
it('normalized manifest keeps every recognized field', () => {
const input = {
id: 'my-plugin', name: 'My Plugin', version: '1.0.0', type: 'widget', trek: '>=4.0.0 <5.0.0',
permissions: ['db:own'], operatorEgress: false, icon: 'Bell', author: 'A', description: 'Does things.',
homepage: 'https://example.com', tags: ['fun'], license: 'MIT',
capabilities: { widget: { title: 'W', slot: 'hero' }, provides: ['getState'] },
settings: [{ key: 'mode', scope: 'user', options: ['a', 'b'] }],
actions: [{ key: 'ping', label: 'Ping' }],
};
const r = validateManifest(input);
expect(r.ok).toBe(true);
const m = r.manifest!;
expect(m.capabilities?.widget?.slot).toBe('hero');
expect(m.settings?.[0].options).toEqual(['a', 'b']);
expect(m.actions?.[0]).toEqual({ key: 'ping', label: 'Ping' });
expect(m.icon).toBe('Bell');
expect(m.operatorEgress).toBe(false);
expect(m.nativeModules).toBe(false); // still forced
expect(m.apiVersion).toBe(1); // still defaulted
expect(m.requiredAddons).toEqual([]);
});
it('accepts routeProfiles icon', () => {
const r = validateManifest({
id: 'rt-plug', name: 'R', version: '1.0.0', type: 'integration', trek: '>=4.0.0 <5.0.0',
permissions: ['hook:route-provider'], capabilities: { routeProfiles: [{ id: 'hike', label: 'Hiking', icon: 'Mountain' }] },
});
expect(r.ok).toBe(true);
expect(r.manifest!.capabilities?.routeProfiles?.[0].icon).toBe('Mountain');
});
it('drops a non-string routeProfiles icon instead of rejecting the manifest', () => {
const r = validateManifest({
id: 'rt-plug', name: 'R', version: '1.0.0', type: 'integration', trek: '>=4.0.0 <5.0.0',
permissions: ['hook:route-provider'], capabilities: { routeProfiles: [{ id: 'hike', label: 'Hiking', icon: 42 }] },
});
expect(r.ok).toBe(true);
expect(r.manifest!.capabilities?.routeProfiles?.[0].icon).toBeUndefined();
});
});
+35
View File
@@ -0,0 +1,35 @@
import { describe, it, expect } from 'vitest';
import { validateManifest } from '../src/manifest.js';
const base = () => ({ id: 'my-plugin', name: 'My Plugin', version: '1.0.0', type: 'integration', trek: '>=4.0.0 <5.0.0' });
const withSetting = (extra: object) => ({ ...base(), settings: [{ key: 'mode', ...extra }] });
describe('validateManifest settings[].options / settings[].oauth', () => {
it('accepts string/number option lists', () => {
expect(validateManifest(withSetting({ options: ['a', 'b'] })).ok).toBe(true);
expect(validateManifest(withSetting({ options: [1, 2] })).ok).toBe(true);
});
it('accepts {value,label} options incl. value 0', () => {
expect(validateManifest(withSetting({ options: [{ value: 0, label: 'Zero' }] })).ok).toBe(true);
});
it('rejects a non-array options', () => {
const r = validateManifest(withSetting({ options: 'a,b' }));
expect(r.ok).toBe(false);
expect(r.errors).toContain('settings option list must be an array');
});
it('rejects an option with empty value', () => {
const r = validateManifest(withSetting({ options: [{ value: '', label: 'x' }] }));
expect(r.errors).toContain('settings option must have a non-empty "value"');
});
it('rejects a garbage option entry', () => {
const r = validateManifest(withSetting({ options: [true] }));
expect(r.errors).toContain('invalid settings option true (expected a string or { value, label })');
});
it('rejects a non-object oauth', () => {
expect(validateManifest(withSetting({ oauth: 'x' })).errors).toContain('settings oauth must be an object');
});
it('rejects non-string oauth paths, accepts valid oauth', () => {
expect(validateManifest(withSetting({ oauth: { initPath: 3 } })).errors).toContain('settings oauth.initPath must be a string');
expect(validateManifest(withSetting({ oauth: { initPath: '/oauth/init' } })).ok).toBe(true);
});
});
+134
View File
@@ -0,0 +1,134 @@
import { describe, it, expect } from 'vitest';
import { createMockHost } from '../src/index.js';
/**
* Mock-host fidelity for the two host-mediated daily budgets (ai.complete/extract and
* notify.send, daily-budget.ts) and the ctx.meta quotas (meta.rpc.ts). Error strings
* and check order are copied verbatim from the server so a plugin author sees the
* exact same failure locally that production would give them.
*/
describe('daily budgets', () => {
it('exhausts the AI budget', async () => {
const host = createMockHost({ grants: ['ai:invoke'], actingUserId: 1, aiPerDay: 2 });
await host.ctx.ai.complete('hi');
await host.ctx.ai.complete('hi');
await expect(host.ctx.ai.complete('hi')).rejects.toThrow('daily AI budget exhausted (resets at UTC midnight)');
});
it('ai.extract shares the same per-host AI budget as ai.complete', async () => {
const host = createMockHost({ grants: ['ai:invoke'], actingUserId: 1, aiPerDay: 1 });
await host.ctx.ai.complete('hi');
await expect(host.ctx.ai.extract('text', {})).rejects.toThrow('daily AI budget exhausted (resets at UTC midnight)');
});
it('aiPerDay: 0 disables the broker — the first call fails', async () => {
const host = createMockHost({ grants: ['ai:invoke'], actingUserId: 1, aiPerDay: 0 });
await expect(host.ctx.ai.complete('hi')).rejects.toThrow('daily AI budget exhausted (resets at UTC midnight)');
});
it('defaults to 200/day for ai, far above what a normal test suite calls', async () => {
const host = createMockHost({ grants: ['ai:invoke'], actingUserId: 1 });
for (let i = 0; i < 200; i++) await host.ctx.ai.complete('hi');
await expect(host.ctx.ai.complete('hi')).rejects.toThrow('daily AI budget exhausted (resets at UTC midnight)');
});
it('exhausts the notify budget', async () => {
const host = createMockHost({
grants: ['notify:send'],
actingUserId: 1,
trips: { 1: { members: [1] } },
notifyPerDay: 1,
});
await host.ctx.notify.send({ title: 't', body: 'b', scope: 'user', targetId: 1 });
await expect(host.ctx.notify.send({ title: 't', body: 'b', scope: 'user', targetId: 1 })).rejects.toThrow(
'daily notification budget exhausted (resets at UTC midnight)',
);
});
it('notifyPerDay: 0 disables the broker — the first call fails', async () => {
const host = createMockHost({
grants: ['notify:send'],
actingUserId: 1,
trips: { 1: { members: [1] } },
notifyPerDay: 0,
});
await expect(host.ctx.notify.send({ title: 't', body: 'b', scope: 'user', targetId: 1 })).rejects.toThrow(
'daily notification budget exhausted (resets at UTC midnight)',
);
});
it('defaults to 100/day for notify, far above what a normal test suite calls', async () => {
const host = createMockHost({ grants: ['notify:send'], actingUserId: 1, trips: { 1: { members: [1] } } });
for (let i = 0; i < 100; i++) await host.ctx.notify.send({ title: 't', body: 'b', scope: 'user', targetId: 1 });
await expect(host.ctx.notify.send({ title: 't', body: 'b', scope: 'user', targetId: 1 })).rejects.toThrow(
'daily notification budget exhausted (resets at UTC midnight)',
);
});
});
describe('ctx.meta quotas', () => {
const fixture = () =>
createMockHost({ grants: ['db:meta'], actingUserId: 1, trips: { 1: { members: [1] } } });
it('meta value quota: 65536 bytes passes, 65537 rejects', async () => {
const { ctx } = fixture();
// Size the payload via Buffer.byteLength(JSON.stringify(v)), same as the server's
// notion of "serialized JSON bytes" — a bare string serializes with 2 quote bytes,
// so budget those into the repeat count.
const okValue = 'x'.repeat(65536 - 2);
expect(Buffer.byteLength(JSON.stringify(okValue), 'utf8')).toBe(65536);
await expect(ctx.meta.set('trip', 1, 'k', okValue)).resolves.toEqual({ key: 'k', value: okValue });
const tooBig = 'x'.repeat(65537 - 2);
expect(Buffer.byteLength(JSON.stringify(tooBig), 'utf8')).toBe(65537);
await expect(ctx.meta.set('trip', 1, 'k2', tooBig)).rejects.toThrow('metadata value too large (>65536 bytes)');
});
it('meta key length: 256 chars passes, 257 rejects', async () => {
const { ctx } = fixture();
const okKey = 'k'.repeat(256);
await expect(ctx.meta.set('trip', 1, okKey, 'v')).resolves.toEqual({ key: okKey, value: 'v' });
const tooLongKey = 'k'.repeat(257);
await expect(ctx.meta.set('trip', 1, tooLongKey, 'v')).rejects.toThrow('metadata key too long (>256 chars)');
});
it('meta key count: 100 keys per (plugin, entity) passes, the 101st rejects', async () => {
const { ctx } = fixture();
for (let i = 0; i < 100; i++) {
await ctx.meta.set('trip', 1, `key-${i}`, i);
}
await expect(ctx.meta.set('trip', 1, 'key-100', 100)).rejects.toThrow(
'too many metadata keys on this trip (max 100)',
);
});
it('overwriting an existing key never counts against the 100-key cap', async () => {
const { ctx } = fixture();
for (let i = 0; i < 100; i++) {
await ctx.meta.set('trip', 1, `key-${i}`, i);
}
// The entity already has 100 keys; updating one of them must still succeed.
await expect(ctx.meta.set('trip', 1, 'key-0', 'updated')).resolves.toEqual({ key: 'key-0', value: 'updated' });
});
it('checks in server order: key length before value size before key count', async () => {
const { ctx } = fixture();
// A key that is simultaneously too long AND paired with an oversized value must
// fail on the key-length check first.
const tooLongKey = 'k'.repeat(257);
const tooBigValue = 'x'.repeat(70000);
await expect(ctx.meta.set('trip', 1, tooLongKey, tooBigValue)).rejects.toThrow('metadata key too long (>256 chars)');
// Fill the entity to the cap, then a value that is ALSO too large must fail on
// the value-size check (raised before the key-count check ever runs).
const full = fixture();
for (let i = 0; i < 100; i++) {
await full.ctx.meta.set('trip', 1, `key-${i}`, i);
}
await expect(full.ctx.meta.set('trip', 1, 'new-key', tooBigValue)).rejects.toThrow(
'metadata value too large (>65536 bytes)',
);
});
});
+58 -14
View File
@@ -1,5 +1,7 @@
/**
* The SDK hand-mirrors two things the server owns: the hook→permission map, and the
* The hook->permission map is no longer hand-mirrored: gen-plugin-facts.ts generates
* src/generated/host-facts.ts from the server's protocol/envelope.ts, and that
* generator's --check mode is a CI gate. What is still hand-vendored here is the
* pure egress-policy helpers. trek-plugin-sdk ships standalone and cannot import across
* the package boundary, so the copies are real copies — and a silent drift here is the
* worst possible bug in this module: `dev` would confidently green-light a plugin that
@@ -13,26 +15,33 @@ import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { HOOK_PERMISSION } from '../src/permissions.js';
import { PLUGIN_SESSION_MAX_KEYS, PLUGIN_SESSION_MAX_KEY_LENGTH, PLUGIN_SESSION_MAX_VALUE_BYTES, EVENT_FAMILIES, EVENT_SNAPSHOT_GRANT, KNOWN_PERMISSIONS } from '../src/index.js';
const here = path.dirname(fileURLToPath(import.meta.url));
const serverPlugins = path.resolve(here, '../../server/src/nest/plugins');
const supervisor = path.join(serverPlugins, 'supervisor/plugin-supervisor.ts');
const envelopeFile = path.join(serverPlugins, 'protocol/envelope.ts');
const serverEgress = path.join(serverPlugins, 'runtime/egress-policy.ts');
const inMonorepo = fs.existsSync(supervisor) && fs.existsSync(serverEgress);
const inMonorepo = fs.existsSync(envelopeFile) && fs.existsSync(serverEgress);
const hostFrame = path.resolve(here, '../../client/src/components/Plugins/PluginFrame.tsx');
describe.skipIf(!inMonorepo)('parity with the host', () => {
it('HOOK_PERMISSION matches the supervisor\'s map exactly', () => {
const src = fs.readFileSync(supervisor, 'utf8');
const block = src.match(/const HOOK_PERMISSION[^{]*\{([\s\S]*?)\n\};/);
expect(block, 'could not find HOOK_PERMISSION in plugin-supervisor.ts').toBeTruthy();
it("the generated host facts match the server's envelope.ts", () => {
// Not a regex scrape any more: server/scripts/gen-plugin-facts.ts imports envelope.ts
// and writes src/generated/host-facts.ts, and its --check mode is a CI gate. This
// asserts the checked-in artefact is the one the host would produce, so a standalone
// publish (which has no server present) still ships the right list.
//
// Compared as whole maps, both ways round: asserting the artefact merely CONTAINS
// each entry passed when the host grew a hook the artefact never learned about,
// which is the drift that actually ships a wrong permission list.
const envelope = fs.readFileSync(envelopeFile, 'utf8');
const block = envelope.match(/HOOK_PERMISSION[^{]*\{([\s\S]*?)\n\}/);
expect(block, 'HOOK_PERMISSION not found in envelope.ts').toBeTruthy();
const theirs: Record<string, string> = {};
for (const m of block![1].matchAll(/^\s*(\w+):\s*'([^']+)'/gm)) theirs[m[1]] = m[2];
const host: Record<string, string> = {};
for (const [, key, perm] of block![1].matchAll(/^\s*(\w+):\s*'([^']+)'/gm)) host[key] = perm;
// Both directions: a hook the host gates that we don't know about means dev fires it
// when TREK never would; one we gate that the host doesn't means dev refuses for nothing.
expect(Object.keys(host).length).toBeGreaterThan(0);
expect(HOOK_PERMISSION).toEqual(host);
expect(theirs).toEqual({ ...HOOK_PERMISSION });
expect(Object.keys(HOOK_PERMISSION).length).toBeGreaterThan(0);
});
it('the vendored egress-policy helpers are byte-identical to the server\'s', () => {
@@ -52,3 +61,38 @@ describe.skipIf(!inMonorepo)('parity with the host', () => {
for (const fn of fns) expect(body(ours, fn), `${fn} has drifted from the server`).toBe(body(theirs, fn));
});
});
describe.skipIf(!fs.existsSync(hostFrame))('parity with the host frame', () => {
it('the session storage contract is one contract in all three copies', () => {
// Nothing generates these: the limits are written out by hand in the SDK export
// authors import, in the dev preview's inlined host, and in the real frame, because
// the SDK ships standalone and cannot import across the package boundary. Bump one
// and the preview happily stores what production then rejects.
const frame = fs.readFileSync(hostFrame, 'utf8');
const devServer = fs.readFileSync(path.resolve(here, '../src/cli/dev.ts'), 'utf8');
expect(frame).toContain(`const PLUGIN_SESSION_MAX_KEYS = ${PLUGIN_SESSION_MAX_KEYS}`);
expect(frame).toContain(`const PLUGIN_SESSION_MAX_KEY_LENGTH = ${PLUGIN_SESSION_MAX_KEY_LENGTH}`);
expect(frame).toContain(`const PLUGIN_SESSION_MAX_VALUE_BYTES = ${PLUGIN_SESSION_MAX_VALUE_BYTES}`);
expect(devServer).toContain(
`SESSION_MAX_KEYS=${PLUGIN_SESSION_MAX_KEYS},SESSION_MAX_KEY_LENGTH=${PLUGIN_SESSION_MAX_KEY_LENGTH},SESSION_MAX_VALUE_BYTES=${PLUGIN_SESSION_MAX_VALUE_BYTES}`,
);
// Same for the codes a plugin branches on — a rename in one copy is a silent
// behaviour change for anyone who developed against the other.
for (const code of ['SESSION_INVALID_KEY', 'SESSION_INVALID_VALUE', 'SESSION_VALUE_TOO_LARGE', 'SESSION_KEY_LIMIT', 'NO_TRIP_CONTEXT', 'SESSION_STORAGE_ERROR']) {
expect(frame, `${code} missing from the host frame`).toContain(`'${code}'`);
expect(devServer, `${code} missing from the dev preview`).toContain(`"${code}"`);
}
});
});
describe.skipIf(!inMonorepo)('core event catalog', () => {
it('event snapshot grants are known read permissions on known families', () => {
expect(EVENT_FAMILIES.length).toBeGreaterThan(0);
for (const [family, perm] of Object.entries(EVENT_SNAPSHOT_GRANT)) {
expect(EVENT_FAMILIES).toContain(family);
expect(KNOWN_PERMISSIONS).toContain(perm);
}
});
});
+128 -2
View File
@@ -6,6 +6,11 @@ import path from 'node:path';
// publish shells out to git + gh; drive those from here so we can assert what it WOULD run.
const calls: Array<{ bin: string; args: string[] }> = [];
let releaseExistsOnRemote = false;
/** The commit the local tag points at; null = no local tag. `git tag` mutates it like git would. */
let localTagSha: string | null = null;
let remoteTagOnOrigin = false;
let failPrCreate = false;
const HEAD_SHA = 'headfeedheadfeedheadfeedheadfeedheadfeed';
vi.mock('node:child_process', () => ({
execFileSync: (bin: string, args: string[]) => {
@@ -14,8 +19,24 @@ vi.mock('node:child_process', () => ({
if (!releaseExistsOnRemote) throw new Error('release not found');
return Buffer.from('');
}
// `git rev-parse <tag>^{commit}` — pretend the tag does not exist yet.
if (bin === 'git' && args.includes('rev-parse')) throw new Error('unknown revision');
if (bin === 'gh' && args[0] === 'pr' && args[1] === 'create' && failPrCreate) throw new Error('pr create exploded');
if (bin === 'gh' && args[0] === 'api') return Buffer.from('someone');
if (bin === 'git' && args.includes('ls-remote')) {
return Buffer.from(remoteTagOnOrigin ? `${HEAD_SHA}\trefs/tags/v1.0.0` : '');
}
if (bin === 'git' && args.includes('tag')) {
// Mirror git's behaviour so later rev-parses see what the run did.
const i = args.indexOf('tag');
if (args[i + 1] === '-d') localTagSha = null;
else localTagSha = HEAD_SHA; // `git tag <t>` and `git tag -f <t>` both land on HEAD
return Buffer.from('');
}
if (bin === 'git' && args.includes('rev-parse')) {
const target = args[args.indexOf('rev-parse') + 1];
if (target === 'HEAD') return Buffer.from(HEAD_SHA);
if (localTagSha === null) throw new Error('unknown revision');
return Buffer.from(localTagSha);
}
return Buffer.from('');
},
}));
@@ -24,6 +45,12 @@ const { publishPlugin } = await import('../src/cli/publish.js');
const { scaffold } = await import('../src/cli/create.js');
const { makePublishable } = await import('./helpers.js');
beforeEach(() => {
localTagSha = null;
remoteTagOnOrigin = false;
failPrCreate = false;
});
describe('publish — a released artifact is immutable', () => {
let tmp: string;
let dir: string;
@@ -139,6 +166,105 @@ describe('publish — the local gates run before anything is cut', () => {
* cut at step 3 — so the author learned it with their tag already burned, for a fact that was
* knowable before a single byte was packed. The check belongs in step 1, and this pins it there.
*/
/**
* The cleanup half of the immutability story. Step 3 creates a local tag, pushes it, and cuts
* the release; when step 4/5 then failed, all three were stranded and the author had to delete
* them by hand before re-running. A failed publish now rolls back exactly what IT created —
* and only that: anything that existed before the run (a merged release, a pre-pushed tag) is
* never touched.
*/
describe('publish — a failed run rolls back what it created', () => {
let tmp: string;
let dir: string;
beforeEach(() => {
calls.length = 0;
releaseExistsOnRemote = false;
tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'publish-rollback-'));
scaffold('rollback-plug', 'integration', tmp);
dir = path.join(tmp, 'rollback-plug');
makePublishable(dir);
});
afterEach(() => { fs.rmSync(tmp, { recursive: true, force: true }); });
const run = (opts: { force?: boolean; keepRelease?: boolean } = {}) => publishPlugin({
dir, repo: 'someone/trek-plugin-rollback-plug', tag: 'v1.0.0',
now: '2026-01-01T00:00:00Z', skipPreflight: true, log: () => {}, ...opts,
});
it('deletes the release, remote tag, and local tag this run created', async () => {
failPrCreate = true;
await expect(run()).rejects.toThrow(/rolled back/i);
expect(calls.some((c) => c.bin === 'gh' && c.args[0] === 'release' && c.args[1] === 'delete' && c.args.includes('v1.0.0'))).toBe(true);
expect(calls.some((c) => c.bin === 'git' && c.args.includes(':refs/tags/v1.0.0'))).toBe(true);
expect(calls.some((c) => c.bin === 'git' && c.args.includes('tag') && c.args.includes('-d'))).toBe(true);
});
it('--keep-release leaves everything in place and prints the manual cleanup', async () => {
failPrCreate = true;
await expect(run({ keepRelease: true })).rejects.toThrow(/gh release delete/);
expect(calls.some((c) => c.bin === 'gh' && c.args[1] === 'delete')).toBe(false);
expect(calls.some((c) => c.args.includes(':refs/tags/v1.0.0'))).toBe(false);
});
it('never deletes a release or remote tag that existed BEFORE the run', async () => {
releaseExistsOnRemote = true;
remoteTagOnOrigin = true;
failPrCreate = true;
await run({ force: true }).catch(() => {});
expect(calls.some((c) => c.bin === 'gh' && c.args[1] === 'delete')).toBe(false);
expect(calls.some((c) => c.args.includes(':refs/tags/v1.0.0'))).toBe(false);
// the local tag WAS created by this run, so that one goes
expect(calls.some((c) => c.bin === 'git' && c.args.includes('tag') && c.args.includes('-d'))).toBe(true);
});
});
/**
* The stale-tag trap: a failed publish leaves a tag; the author commits a fix and re-runs; the
* old flow silently reused the stale tag and released the UNFIXED code. A tag that does not
* point at HEAD and has no release is debris — move it. One that HAS a release is immutable.
*/
describe('publish — a stale tag from a failed run is moved, not reused', () => {
let tmp: string;
let dir: string;
beforeEach(() => {
calls.length = 0;
releaseExistsOnRemote = false;
tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'publish-stale-'));
scaffold('stale-plug', 'integration', tmp);
dir = path.join(tmp, 'stale-plug');
makePublishable(dir);
});
afterEach(() => { fs.rmSync(tmp, { recursive: true, force: true }); });
const run = () => publishPlugin({
dir, repo: 'someone/trek-plugin-stale-plug', tag: 'v1.0.0',
now: '2026-01-01T00:00:00Z', skipPreflight: true, log: () => {},
});
it('re-points a debris tag (no release) at HEAD and force-pushes it', async () => {
localTagSha = 'stalestalestalestalestalestalestalestale';
await run().catch(() => {});
expect(calls.some((c) => c.bin === 'git' && c.args.includes('tag') && c.args.includes('-f'))).toBe(true);
const push = calls.find((c) => c.bin === 'git' && c.args.includes('push') && c.args.includes('v1.0.0'));
expect(push?.args).toContain('--force');
});
it('refuses a mismatched tag whose release already exists', async () => {
localTagSha = 'stalestalestalestalestalestalestalestale';
releaseExistsOnRemote = true;
await expect(run()).rejects.toThrow(/points at/i);
expect(calls.some((c) => c.bin === 'git' && c.args.includes('-f'))).toBe(false);
});
it('reuses a tag already on HEAD without touching it', async () => {
localTagSha = HEAD_SHA;
await run().catch(() => {});
expect(calls.some((c) => c.bin === 'git' && c.args.includes('tag') && !c.args.includes('-d'))).toBe(false);
});
});
describe('publish — a signed plugin cannot quietly go unsigned', () => {
let tmp: string;
let dir: string;
+77
View File
@@ -0,0 +1,77 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { createHash } from 'node:crypto';
import { generateKeypair, loadPrivateKey, publicKeyBase64, verifyArtifact } from '../src/cli/sign.js';
import { retroSignVersions } from '../src/cli/retro-sign.js';
const V1_BYTES = Buffer.from('the exact bytes of the v1.0.0 release asset');
const sha = (b: Buffer) => createHash('sha256').update(b).digest('hex');
describe('retro-sign — first signed update signs the older versions too', () => {
let tmp: string;
let keyPath: string;
let publicKey: string;
beforeEach(() => {
tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'retro-sign-'));
keyPath = path.join(tmp, 'signing.key');
publicKey = generateKeypair(keyPath).publicKey;
vi.stubGlobal('fetch', async (url: string) => {
if (String(url).includes('v1.0.0')) return { ok: true, arrayBuffer: async () => V1_BYTES } as unknown as Response;
return { ok: false, status: 404 } as Response;
});
});
afterEach(() => {
fs.rmSync(tmp, { recursive: true, force: true });
vi.unstubAllGlobals();
});
const entry = (v1: Partial<{ sha256: string; signature: string }> = {}) => ({
id: 'retro-plug',
authorPublicKey: publicKey,
versions: [
{ version: '1.1.0', downloadUrl: 'https://github.com/x/y/releases/download/v1.1.0/plugin.zip', sha256: 'deadbeef', signature: 'already-signed' },
{ version: '1.0.0', downloadUrl: 'https://github.com/x/y/releases/download/v1.0.0/plugin.zip', sha256: sha(V1_BYTES), ...v1 },
],
});
it('downloads, verifies, and signs each unsigned older version', async () => {
const e = entry();
const signed = await retroSignVersions(e, keyPath, () => {});
expect(signed).toEqual(['1.0.0']);
const sig = e.versions[1].signature!;
expect(verifyArtifact(V1_BYTES, sig, publicKey)).toBe(true);
expect(e.versions[0].signature).toBe('already-signed'); // untouched
});
it('REFUSES when the downloaded bytes no longer hash to the pinned sha256', async () => {
const e = entry({ sha256: 'not-the-real-hash' });
await expect(retroSignVersions(e, keyPath, () => {})).rejects.toThrow(/1\.0\.0.*sha256/is);
expect(e.versions[1].signature).toBeUndefined();
});
it('REFUSES a key that does not match the entry authorPublicKey', async () => {
const otherKey = path.join(tmp, 'other.key');
generateKeypair(otherKey);
await expect(retroSignVersions(entry(), otherKey, () => {})).rejects.toThrow(/key/i);
});
it('is a no-op for an unsigned entry or one with nothing to sign', async () => {
const unsignedEntry = { id: 'x', versions: [{ version: '1.0.0', downloadUrl: 'u', sha256: 'h' }] };
expect(await retroSignVersions(unsignedEntry, keyPath, () => {})).toEqual([]);
const fullySigned = entry({ signature: 'sig' });
expect(await retroSignVersions(fullySigned, keyPath, () => {})).toEqual([]);
});
it('names every version whose artifact could not be fetched', async () => {
const e = entry();
e.versions[1].downloadUrl = 'https://github.com/x/y/releases/download/v9.9.9/plugin.zip'; // 404s
await expect(retroSignVersions(e, keyPath, () => {})).rejects.toThrow(/1\.0\.0/);
});
it('key sanity: publicKeyBase64 round-trips through loadPrivateKey', () => {
expect(publicKeyBase64(loadPrivateKey(keyPath))).toBe(publicKey);
});
});
+62
View File
@@ -86,6 +86,29 @@ describe('validateManifest', () => {
expect(r.manifest?.permissions).toEqual(permissions);
});
it('accepts hook:map-layer-provider, hook:day-schedule-provider, hook:day-tint-provider and geolocation:read', () => {
const r = validateManifest({ ...base, permissions: ['hook:map-layer-provider', 'hook:day-schedule-provider', 'hook:day-tint-provider', 'geolocation:read'] });
expect(r.errors).toEqual([]);
expect(r.ok).toBe(true);
});
it('validates capabilities.routeProfiles and ties it to hook:route-provider', () => {
const profiles = [{ id: 'ev', label: 'EV' }];
const ok = validateManifest({ ...base, permissions: ['hook:route-provider'], capabilities: { routeProfiles: profiles } });
expect(ok.errors).toEqual([]);
expect(ok.ok).toBe(true);
// profiles without the grant are dead buttons — rejected at validate time
expect(validateManifest({ ...base, capabilities: { routeProfiles: profiles } }).ok).toBe(false);
// id shape, label cap, count cap, duplicates
const bad = (routeProfiles: unknown) => validateManifest({ ...base, permissions: ['hook:route-provider'], capabilities: { routeProfiles } }).ok;
expect(bad([{ id: 'EV', label: 'x' }])).toBe(false);
expect(bad([{ id: 'ev' }])).toBe(false);
expect(bad([{ id: 'ev', label: 'L'.repeat(41) }])).toBe(false);
expect(bad([{ id: 'ev', label: 'a' }, { id: 'ev', label: 'b' }])).toBe(false);
expect(bad([1, 2, 3, 4].map(i => ({ id: `p${i}`, label: 'x' })))).toBe(false);
expect(bad('ev')).toBe(false);
});
it('accepts the read-symmetry + broker permissions (collab, file content, trip create, rates)', () => {
const permissions = ['db:read:collab', 'db:create:trips', 'rates:read', 'db:read:files:content'];
const r = validateManifest({ ...base, permissions });
@@ -108,6 +131,30 @@ describe('validateManifest', () => {
});
describe('createMockHost', () => {
it('mocks plugin UI session storage with scope isolation and production limits', async () => {
const host = createMockHost({ sessionTripId: 42 });
await host.session.set('filters', ['hotel']);
await host.session.set('filters', ['flight'], { scope: 'trip' });
await expect(host.session.get('filters')).resolves.toEqual(['hotel']);
await expect(host.session.get('filters', { scope: 'trip' })).resolves.toEqual(['flight']);
await expect(host.session.set('x'.repeat(65), true)).rejects.toThrow(/SESSION_INVALID_KEY/);
await expect(host.session.set('large', 'x'.repeat(1024))).rejects.toThrow(/SESSION_VALUE_TOO_LARGE/);
await expect(host.session.set('x'.repeat(64), 'x'.repeat(1022))).resolves.toBeUndefined();
await host.session.clear();
await host.session.clear({ scope: 'trip' });
for (let index = 0; index < 32; index += 1) await host.session.set(`key-${index}`, index);
await expect(host.session.set('key-32', 32)).rejects.toThrow(/SESSION_KEY_LIMIT/);
await expect(host.session.set('trip-key', true, { scope: 'trip' })).resolves.toBeUndefined();
});
it('requires a trip context for trip-scoped mock session storage', async () => {
const { session } = createMockHost();
await expect(session.get('filters', { scope: 'trip' })).rejects.toThrow(/NO_TRIP_CONTEXT/);
});
it('enforces the granted permission set', async () => {
const { ctx } = createMockHost({ grants: ['db:own'] });
await expect(ctx.db.migrate('1', 'CREATE TABLE t (x)')).resolves.toEqual({ applied: true });
@@ -622,6 +669,21 @@ describe('dev-server SDK injection', () => {
});
});
describe('dev-server preview', () => {
// The preview plays the host, so it has to refuse what the host refuses. A preview
// that answered trek:geolocation without the grant green-lights a plugin production
// then breaks — the one drift direction this package cannot afford.
it('gates the geolocation bridge on geolocation:read, like PluginFrame', async () => {
const { preview } = await import('../src/cli/dev.js');
const without = preview('demo', 'widget', 1, {});
expect(without).toContain('var GEO_ALLOWED=false;');
expect(without).toContain('if(!GEO_ALLOWED){');
expect(without).toContain('error:"forbidden"');
expect(preview('demo', 'widget', 1, { geoAllowed: true })).toContain('var GEO_ALLOWED=true;');
});
});
describe('dev db bind shapes', () => {
let tmp: string;
beforeEach(() => { tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'devdb-')); });
+110
View File
@@ -0,0 +1,110 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { createHash } from 'node:crypto';
const calls: Array<{ bin: string; args: string[] }> = [];
let failSync = false;
/** Seeded into the fake fork clone as the plugin's existing registry entry (update case). */
let existingEntry: unknown = null;
let lastCloneDir = '';
// submit's git()/gh() run execFileSync with encoding:'utf8', which returns STRINGS — the
// mock must too, or `.trim()` explodes on a Buffer.
vi.mock('node:child_process', () => ({
execFileSync: (bin: string, args: string[]) => {
calls.push({ bin, args });
if (bin === 'gh' && args[0] === 'api') return 'someone';
if (bin === 'gh' && args[0] === 'repo' && args[1] === 'sync' && failSync) throw new Error('fork has diverged');
if (bin === 'gh' && args[0] === 'repo' && args[1] === 'clone') {
lastCloneDir = args[3];
if (existingEntry !== null) {
const p = path.join(lastCloneDir, 'registry', 'plugins', `${(existingEntry as { id: string }).id}.json`);
fs.mkdirSync(path.dirname(p), { recursive: true });
fs.writeFileSync(p, JSON.stringify(existingEntry, null, 2));
}
return '';
}
if (bin === 'gh' && args[0] === 'pr' && args[1] === 'create') return 'https://github.com/liketrek/TREK-Plugins/pull/999';
return '';
},
}));
const { submitEntry } = await import('../src/cli/submit.js');
const { generateKeypair } = await import('../src/cli/sign.js');
const { verifyArtifact } = await import('../src/cli/sign.js');
const V1_BYTES = Buffer.from('old release asset bytes');
const sha = (b: Buffer) => createHash('sha256').update(b).digest('hex');
describe('submit — fork sync and retro-signing', () => {
let tmp: string;
let keyPath: string;
let publicKey: string;
beforeEach(() => {
calls.length = 0;
failSync = false;
existingEntry = null;
lastCloneDir = '';
tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'submit-'));
keyPath = path.join(tmp, 'signing.key');
publicKey = generateKeypair(keyPath).publicKey;
vi.stubGlobal('fetch', async (url: string) => {
if (String(url).includes('v1.0.0')) return { ok: true, arrayBuffer: async () => V1_BYTES } as unknown as Response;
return { ok: false, status: 404 } as Response;
});
});
afterEach(() => {
fs.rmSync(tmp, { recursive: true, force: true });
vi.unstubAllGlobals();
});
const freshEntry = (signed = false) => ({
id: 'sync-plug',
name: 'Sync Plug',
...(signed ? { authorPublicKey: publicKey } : {}),
versions: [{
version: '1.1.0', downloadUrl: 'https://github.com/x/y/releases/download/v1.1.0/plugin.zip',
sha256: 'deadbeef', ...(signed ? { signature: 'fresh-sig' } : {}),
}],
});
it('fast-forwards the fork from the registry before branching', async () => {
await submitEntry(freshEntry(), {});
const sync = calls.find((c) => c.bin === 'gh' && c.args[0] === 'repo' && c.args[1] === 'sync');
expect(sync?.args).toContain('someone/TREK-Plugins');
expect(sync?.args).toContain('--source');
expect(sync?.args).toContain('liketrek/TREK-Plugins');
});
it('a diverged fork warns but does not stop the submit', async () => {
failSync = true;
const { prUrl } = await submitEntry(freshEntry(), {});
expect(prUrl).toContain('/pull/999');
});
it('retro-signs unsigned older versions on the first signed update', async () => {
existingEntry = {
id: 'sync-plug', name: 'Sync Plug',
versions: [{ version: '1.0.0', downloadUrl: 'https://github.com/x/y/releases/download/v1.0.0/plugin.zip', sha256: sha(V1_BYTES) }],
};
await submitEntry(freshEntry(true), { signKeyPath: keyPath, keep: true });
const written = JSON.parse(fs.readFileSync(path.join(lastCloneDir, 'registry', 'plugins', 'sync-plug.json'), 'utf8')) as {
versions: Array<{ version: string; signature?: string }>;
};
const v1 = written.versions.find((v) => v.version === '1.0.0')!;
expect(v1.signature).toBeDefined();
expect(verifyArtifact(V1_BYTES, v1.signature!, publicKey)).toBe(true);
fs.rmSync(lastCloneDir, { recursive: true, force: true });
});
it('refuses a first signed update when no key is available to retro-sign the older versions', async () => {
existingEntry = {
id: 'sync-plug', name: 'Sync Plug',
versions: [{ version: '1.0.0', downloadUrl: 'https://github.com/x/y/releases/download/v1.0.0/plugin.zip', sha256: sha(V1_BYTES) }],
};
await expect(submitEntry(freshEntry(true), {})).rejects.toThrow(/--sign/);
});
});
+55
View File
@@ -27,6 +27,9 @@ describe('design kit', () => {
expect(TREK_THEME_JS).toContain('trek:resize');
// Trusts only the real parent window (opaque frame has a 'null' origin).
expect(TREK_THEME_JS).toContain('ev.source !== window.parent');
// Host-managed tab state uses the same request/response channel.
expect(TREK_THEME_JS).toContain("trek:session:get");
expect(TREK_THEME_JS).toContain('session: session');
});
it('never contains a closing tag that would break <style>/<script> inlining', () => {
@@ -67,3 +70,55 @@ describe('design kit', () => {
expect(out.match(/<style data-trek-ui>/g)?.length).toBe(2);
});
});
/**
* Boot the kit bootstrap against a stub window, so the bridge's promise handling can be
* exercised without a DOM. `document.readyState` stays 'loading', which parks boot() on
* DOMContentLoaded and leaves only the message plumbing live. The stub's postMessage runs
* structuredClone first, exactly like the browser's — a value it cannot carry throws.
*/
function bootBridge() {
const sent: Record<string, unknown>[] = [];
const parent = { postMessage: (msg: Record<string, unknown>) => { structuredClone(msg); sent.push(msg); } };
let onMessage: ((ev: { source: unknown; data: unknown }) => void) | null = null;
const win: Record<string, unknown> = {
parent,
addEventListener: (type: string, cb: (ev: { source: unknown; data: unknown }) => void) => { if (type === 'message') onMessage = cb; },
};
const docEl = { setAttribute: () => {}, removeAttribute: () => {}, style: { setProperty: () => {} } };
const doc = { documentElement: docEl, readyState: 'loading', addEventListener: () => {}, body: null };
new Function('window', 'document', TREK_THEME_JS)(win, doc);
return {
trek: win.trek as {
session: { set: (k: string, v: unknown) => Promise<unknown>; get: (k: string) => Promise<unknown> };
invoke: (sub: string, opts?: { body?: unknown }) => Promise<unknown>;
confirm: (opts: unknown) => Promise<boolean>;
},
sent,
deliver: (data: unknown) => onMessage?.({ source: parent, data }),
};
}
describe('bridge requests never hang', () => {
it('rejects session.set with a value the frame cannot post, instead of pending forever', async () => {
const { trek, sent } = bootBridge();
// A function can't be structured-cloned: postMessage throws synchronously and the
// request never reaches the host, so the promise has to settle here.
await expect(trek.session.set('k', () => 1)).rejects.toMatchObject({ code: 'SESSION_INVALID_VALUE' });
expect(sent).toEqual([]);
});
it('rejects invoke with an unpostable body and resolves confirm as declined', async () => {
const { trek } = bootBridge();
await expect(trek.invoke('/x', { body: { cb: () => 1 } })).rejects.toMatchObject({ code: 'error' });
await expect(trek.confirm({ message: 'ok?', title: () => 'x' })).resolves.toBe(false);
});
it('still settles a normal request from the host response', async () => {
const { trek, sent, deliver } = bootBridge();
const p = trek.session.get('k');
expect(sent).toHaveLength(1);
deliver({ type: 'trek:response', requestId: sent[0].requestId, data: 'v' });
await expect(p).resolves.toBe('v');
});
});
+99
View File
@@ -0,0 +1,99 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
// unrelease shells out to git + gh; drive those from here so we can assert what it deletes.
const calls: Array<{ bin: string; args: string[] }> = [];
let releaseExistsOnRemote = false;
let remoteTagOnOrigin = false;
let localTagExists = false;
vi.mock('node:child_process', () => ({
execFileSync: (bin: string, args: string[]) => {
calls.push({ bin, args });
if (bin === 'gh' && args[0] === 'release' && args[1] === 'view') {
if (!releaseExistsOnRemote) throw new Error('release not found');
return Buffer.from('');
}
if (bin === 'git' && args.includes('ls-remote')) {
return Buffer.from(remoteTagOnOrigin ? 'abc\trefs/tags/v1.0.0' : '');
}
if (bin === 'git' && args.includes('rev-parse')) {
if (!localTagExists) throw new Error('unknown revision');
return Buffer.from('abc');
}
return Buffer.from('');
},
}));
const { unrelease } = await import('../src/cli/unrelease.js');
/** The published registry index the immutability guard consults. */
let indexBody: unknown = { plugins: [] };
let indexFails = false;
describe('unrelease — delete a stranded tag + release safely', () => {
let tmp: string;
beforeEach(() => {
calls.length = 0;
releaseExistsOnRemote = false;
remoteTagOnOrigin = false;
localTagExists = false;
indexBody = { plugins: [] };
indexFails = false;
tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'unrelease-'));
fs.writeFileSync(path.join(tmp, 'trek-plugin.json'), JSON.stringify({ id: 'doomed-plug', version: '1.0.0' }));
vi.stubGlobal('fetch', async () => {
if (indexFails) throw new Error('offline');
return { ok: true, json: async () => indexBody } as Response;
});
});
afterEach(() => {
fs.rmSync(tmp, { recursive: true, force: true });
vi.unstubAllGlobals();
});
const run = (yes?: boolean) => unrelease({
dir: tmp, tag: 'v1.0.0', repo: 'someone/trek-plugin-doomed-plug', yes, log: () => {},
});
it('REFUSES when that version is published in the registry — those artifacts are immutable', async () => {
indexBody = { plugins: [{ id: 'doomed-plug', versions: [{ version: '1.0.0' }] }] };
releaseExistsOnRemote = true;
await expect(run(true)).rejects.toThrow(/published in the registry/i);
expect(calls.some((c) => c.bin === 'gh' && c.args[1] === 'delete')).toBe(false);
});
it('deletes the release, remote tag, and local tag when they exist', async () => {
releaseExistsOnRemote = true;
remoteTagOnOrigin = true;
localTagExists = true;
const { deleted } = await run();
expect(deleted).toEqual(['release', 'remote tag', 'local tag']);
expect(calls.some((c) => c.bin === 'gh' && c.args[0] === 'release' && c.args[1] === 'delete' && c.args.includes('--yes'))).toBe(true);
expect(calls.some((c) => c.bin === 'git' && c.args.includes(':refs/tags/v1.0.0'))).toBe(true);
expect(calls.some((c) => c.bin === 'git' && c.args.includes('tag') && c.args.includes('-d'))).toBe(true);
});
it('reports what was already absent without failing', async () => {
const { deleted } = await run();
expect(deleted).toEqual([]);
});
it('when the registry cannot be checked, refuses without --yes and proceeds with it', async () => {
indexFails = true;
localTagExists = true;
await expect(run()).rejects.toThrow(/--yes/);
const { deleted } = await run(true);
expect(deleted).toEqual(['local tag']);
});
it('a different published version of the same plugin does not block this tag', async () => {
indexBody = { plugins: [{ id: 'doomed-plug', versions: [{ version: '0.9.0' }] }] };
localTagExists = true;
const { deleted } = await run();
expect(deleted).toEqual(['local tag']);
});
});
+20
View File
@@ -0,0 +1,20 @@
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
coverage: {
provider: 'v8',
reporter: ['lcov', 'text'],
reportsDirectory: './coverage',
include: ['src/**/*.ts'],
// Mirrored in the repo root's sonar.coverage.exclusions — a file skipped
// here emits no lcov entry, so Sonar must not count it as uncovered either.
exclude: [
// Machine-written by server/scripts/gen-plugin-facts.ts.
'src/generated/**',
// Generated snapshot (scripts/gen-lucide-icon-names.mjs) — pure data.
'src/lucide-icon-names.ts',
],
},
},
});