mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-10-19 05:26:47 +00:00
v3.4.0 (#1540)
* 3.3.0 (#1472) * feat(plugins): grow the frame bridge — fill pages, confirm, openExternal, live context - page/trip-page hosts pass fill: the frame pins to 100% height and ignores trek:resize, so a kit plugin's auto height report no longer collapses a full page into a floating island with dead space below (widgets keep self-sizing) - trek:confirm renders the native ConfirmDialog host-side (the sandbox has no allow-modals) and answers trek:confirm:result; one at a time - trek:openExternal opens validated http(s) URLs in a noopener tab — the sandbox has no allow-popups, so plugins simply couldn't link out before - trek:notify accepts an optional duration, clamped to 1.5-15s - context gains dir (rtl/ltr) and is re-pushed when locale or format settings change, not just on appearance mutations - core events for the trip in view are forwarded as trek:event — names only, never payloads, mirroring the server-side events surface * fix(plugins): move trip warnings out of the content area The warning pills overlaid the top of every planner tab at full width, sitting on the map and its toolbar. Now a warning from a plugin that owns a trip-page tab renders as a compact chip in the navbar centre (click jumps to the tab; the navbar centre is free on trip pages), and everything else floats above the content at the bottom instead. Mobile keeps all warnings in the bottom overlay since the desktop navbar isn't there. The trip tab's frame also opts into the new fill mode. * feat(plugin-sdk): 1.4.0 — motion library + new bridge helpers in the kit Mirrors the host's animation vocabulary 1:1 into TREK_UI_CSS (menu/popover/ modal/backdrop/toast enters, drawer variant under 640px, page-enter, stagger, skeleton shimmer, chart reveals) including the reduced-motion degrade to a gentle fade. window.trek grows confirm(), openExternal(), onEvent() and a notify duration, and applyContext now stamps lang/dir on the document so RTL hosts get RTL plugin UIs. * feat(plugins): surface registry download counts in browse The registry now aggregates GitHub release download counts per plugin (TREK-Plugins#18) as an entry-level downloadCount. Project it through browse/detail and show it as a compact stat on the browse cards and in the detail meta grid. Counts are raw asset downloads (updates and CI included), so the UI says downloads, not installs. * docs(plugins): document the grown bridge surface and motion classes * fix(plugins): harden the new bridge paths Review pass over the bridge additions: - keep the unstable useToast() object out of the effect deps (ref instead) — it re-created the effect on every parent render, and with the new live repost that meant a trek:context flood into the frame - reset loads/height/confirm state and key the iframe when a host swaps pluginId in place (tab bar, /plugins/:id) — the new plugin's document was refused as a 'navigated' frame and every kit promise hung - confirm dialogs always lead with the host-controlled plugin name so a plugin can't dress its dialog up as a TREK system prompt; answer/refuse moved out of setState updaters (StrictMode ran them twice) - Number.isFinite on the notify duration (NaN parked a sticky toast) - don't forward other plugins' namespaced broadcasts as trek:event; a plugin's own plugin:{id}:* broadcasts now reach its frame though - teach the SDK dev preview the confirm/openExternal contract so trek.confirm() resolves in /preview - 999,950 downloads formats as 1M, not 1000k * fix(planner): let plugin warning chips grow wider before truncating The nav-centre chip capped at 340px, so a longer warning (e.g. the TREK x Japan weather prompt) was ellipsised almost immediately. Scale it with the viewport up to 520px so most messages read in full while still yielding on narrow desktops. * feat(plugins): sort the plugin browser by download count Discover now honours the sort dropdown (it was always alphabetical) and adds a 'Most downloads' option that ranks the registry by downloadCount. The sort keys are scoped per tab — updates-first stays with Installed, most-downloads with Discover — and snap back to name when the tab can't offer them. * feat(plugin-sdk): auto-upgrade native <select> to a host-styled dropdown A sandboxed plugin can't reach the host's components, and a native <select> draws its popup from the OS — so plugin dropdowns never matched TREK. The design kit now enhances every <select> into a keyboard-accessible listbox that uses the kit tokens, keeping the real element as the value/form source (it still fires change). Authors write a plain <select> and get the host look for free; opt a field out with data-trek-native. validate warns when a plugin ships a <select> without inlining the kit. * feat(plugins): add issue url link * feat(plugins): reservations write + cross-trip reads - db:write:reservations -> reservations.create/update/delete, gated exactly like the REST/MCP path (reservation_edit + trip membership, acting user host-bound, no impersonation) and delegating to ReservationsService so the accommodation, budget-sync, booking-notification and reservation:* broadcasts match the web app 1:1 — a booking/flight/import plugin can finally write a reservation - trips.listMine / reservations.listMine: enumerate every trip and booking the acting user can access (membership baked into listTrips, never a raw cross-tenant SELECT) — dashboards/aggregates were impossible before - audit: derive auditability from METHOD_PERMISSION so a new capability method can't be added un-audited by omission - typed ctx.reservations.* / ctx.trips.listMine, perm label (en/de), wiki * feat(plugins): read scopes for journal, atlas, vacay and day notes - db:read:journal / db:read:atlas / db:read:vacay expose the acting user's OWN journals / visited countries+regions / vacation plan across all their trips (user-scoped like costs.listMine, each gated on its addon being enabled), reusing the addon's existing readers - db:read:daynotes -> daynotes.list(tripId, dayId), trip-scoped and membership-checked like the other trip reads - typed ctx.journal / atlas / vacay / daynotes, perm labels (en/de), wiki, audit resource labels, tests * feat(plugins): day notes write scope - db:write:daynotes -> daynotes.create/update/delete, gated under the app's 'day_edit' permission (like days) with the day verified to belong to the trip; reuses dayNoteService and broadcasts the same dayNote:* events so open sessions update live - typed ctx.daynotes.create/update/delete, perm label (en/de), wiki, tests * feat(plugins): run declared background jobs on a schedule - plugins already declared jobs {id, schedule} but the cron was never wired. The host now schedules them: host-entry reports each job's schedule, the supervisor starts the jobs (node-cron) when the plugin goes active and stops them on kill/deactivate so nothing leaks - opt-in via a new jobs:run permission — scheduled work runs with NO acting user (its trip reads stay refused; it can only use ctx.db and declared egress), so background execution is a distinct, admin-granted capability. Invalid crons are skipped and a throwing job can't break the host - extracted a small, unit-tested scheduler (plugin-jobs.ts); perm label (en/de), wiki, tests * feat(plugins): read scope for saved-place collections - db:read:collections -> collections.listMine() / collections.get(id): the acting user's own collections (user-scoped, gated on the Collections addon), reusing collectionsService - typed ctx.collections, perm label (en/de), wiki, audit resource labels, tests * fix(plugins): translate new permission labels to all locales + cover the new wiring - add the 8 new admin.plugins.perm.* labels (reservations/day-notes writes, the journal/atlas/vacay/day-notes/collections reads and jobs:run) to the remaining 20 locales so the strict i18n key-parity test passes again - cover the create-rpc-host reservation / day-note / cross-trip / addon-read deps (the real side-effect wiring the mocked rpc-host tests don't exercise) so the src/nest 80% branch-coverage gate holds * feat(plugins): dev-link — hot-reload a local plugin against real data Answers a plugin developer's ask: today you either get `trek-plugin-sdk dev` (fast hot-reload but MOCK/fixture data) or the full build->pack->upload->activate cycle (real data, no watcher). Neither gives "local dir + hot-reload + real data". - POST /admin/plugins/link registers a plugin from a LOCAL built directory by symlinking it into the plugins volume — the loader already forks the resolved real path, so ZERO loader change — and registering it INACTIVE as `local:link`. Validates the manifest + refuses native binaries exactly like a sideload. - POST /admin/plugins/:id/reload re-forks a linked plugin via the existing deactivate->activate primitive (same grants, no re-consent unless the manifest widened perms). A best-effort fs.watch auto-reloads on rebuild. - It runs through the UNCHANGED capability RPC host: real, membership-gated data, acting user host-bound, no impersonation — code origin never touches the gate. - Gated behind TREK_PLUGINS_DEV_LINK on top of admin + kill-switch, because a linked plugin bypasses the install-time signature model and, under `npm run dev`, the OS jail is off. Off by default; never reachable in production. - discovery follows a symlinked <root>/<id>; uninstall/link never delete the author's source (link-safe removal for POSIX symlinks and Windows junctions). * docs(plugins): document the dev-link real-data hot-reload workflow Adds a "Test against a real instance's data (dev-link)" subsection next to the mock-data SDK preview: TREK_PLUGINS_DEV_LINK, POST /link with a local built dir, activate + consent, hot-reload via the file-watch / POST /:id/reload / Restart, and the dev-only security caveats. * feat(plugins): dev-link admin UI - surface devLink (TREK_PLUGINS_DEV_LINK) in GET /admin/plugins so the panel shows the link form only where dev-link is enabled - AdminPluginsPanel: a "Link a local plugin" form (path -> POST /link), a Dev-Link badge for source_repo=local:link, and adminApi.pluginLink/pluginReload - fix: the plugin menu treated any non-local:upload source_repo as a GitHub repo, so a dev-linked plugin rendered github.com/local:link links — exclude local:link - labels for the 6 new dev-link UI strings across all 22 locales * docs(plugins): document the dev-link admin UI The dev-link section showed only the curl call — surface the Admin → Plugins "Link a local plugin" field (the primary path) and the Dev-link badge, with curl kept as the scripting alternative. * feat(plugins): enrich core events with { entity, entityId } Subscribed plugins now learn WHICH entity changed, not just the event name — a reservation/place/day/... id derived host-side from an explicit per-family whitelist. Threaded through the six event hops WITHOUT touching actingUserId: the handler still runs with no user, so the id is not dereferenceable (a trip read is still refused; the id says what to react to, not what it contains). A non-entity id can never surface — budget:member-paid-updated yields the itemId, never the userId — and bulk/reorder/sub-entity payloads carry no id. The mapper is pure, synchronous and never throws into the core broadcast. No new permission (reuses events:subscribe); backend-only. * feat(plugins): packing write scope with #858 privacy-scoped broadcasts - db:write:packing -> packing.create/update/delete, gated under the app's 'packing_edit' permission (like the REST path) with the host-bound acting user as owner; reuses packingService - replicates the packing privacy model 1:1 (the controller/service helpers aren't exported): create/delete fan out to the item's viewers only (owner + recipients, or the whole room for a Common item); update runs the four public<->private transitions, dropping a freshly-privatized item from the room BEFORE re-adding it owner-only so it never leaks. A stale write is BAD_PARAMS with no broadcast - typed ctx.packing.create/update/delete, perm label (22 locales), wiki, tests (rpc-host gating + the four transitions + owner-scoped delete) * feat(plugins): tableContributor hook — host-rendered view columns/actions (backend) The registry backend for plugin-contributed columns/actions in the native planner views (the tabular-reservations use case), mirroring placeDetailProvider: - hook:table-contributor + the tableContributor hook (getContributions(view, tripId, ctx) -> TableContribution[]), double-gated (implement + grant) like the other provider hooks - GET /api/view-contributions/:view/:tripId — view whitelist + membership gate + per-provider timeout/fail-safe, plus the hardening the older provider hooks lack: every field is String-coerced + length-capped, kind/tone/target enum-whitelisted, per-provider counts capped (<=20 columns / <=10 actions), and a column url must be http/https/mailto (a javascript:/data: url is click-XSS into the native DOM) - typed pluginsApi.viewContributions + the ViewContribution union, perm label (22 locales), wiki, hardening tests * feat(plugins): render tableContributor columns/actions in the reservations view The frontend for the tableContributor hook: a reusable PluginContributions layer (usePluginViewContributions + PluginColumns/PluginActions) that renders the host-normalized column/action leaves NATIVELY — a column is text/badge/link, an action is a button that calls the plugin route or opens its sandboxed frame in a modal (plugin markup only ever runs inside the opaque-origin iframe). Wired into the reservations cards (both ReservationCard and TransitJourneyCard) as a strictly- additive footer keyed by reservation id: zero change to a card when no plugin contributes. Fetched once per view, fail-safe. * docs(plugins): bring the permissions wikis current with this cycle Plugin-Permissions.md was missing every permission added this cycle — add rows for the read scopes (journal/atlas/vacay/daynotes/collections), the write scopes (reservations/daynotes/packing, packing noting the #858 owner-scoping), jobs:run and hook:table-contributor, and correct the events:subscribe row for the new { entity, entityId } hint. Add the jobs:run row to Plugin-Development.md too. * fix(maps): stop quick one-finger pans zooming the map on mobile (#1440) The global drag-drop-touch polyfill installs document-level touch listeners on phones. On every single-finger touchend it records a timestamp, and if the next touch starts within 500ms it synthesises a dblclick on the target, which the map's default double-click-zoom turns into a zoom-in. Two quick one-finger pans therefore zoomed instead of panning. The polyfill only bridges HTML5 drag-and-drop to touch for planner reordering, which is already disabled on mobile (#1432), so gate its import to viewports >=1024px (the lg breakpoint useIsMobile uses). Removes the phantom-dblclick source on phones while keeping touch DnD on large viewports; fixes both the Leaflet and GL renderers. * fix(feeds): emit TZID + VTIMEZONE so subscribed calendars respect time zones (#1453) exportICS emitted timed DTSTART/DTEND as bare floating times (no Z, no TZID), which iOS/Google Calendar render in the subscriber's local zone instead of the zone TREK shows. Resolve an IANA zone per timed event — transport endpoints use their stored timezone (departure drives DTSTART, arrival drives DTEND), while assignments and hotel/restaurant reservations derive it from place coordinates via tz-lookup — and attach TZID backed by a VTIMEZONE component. The all-trips feed now carries deduped VTIMEZONE blocks so TZID references still resolve. * feat(plugins): render tableContributor contributions in the places + day views Extends the tableContributor frontend to all three planner views: hoist the shared PluginCardFooter into PluginContributions, wire the places sidebar (keyed by place id, rendered as a sibling after each row so the drag/scroll row stays untouched) and the day panel (keyed by day id, guarded for a null day). Strictly additive + fail-safe like the reservations view — nothing renders when no plugin contributes. * fix(vacay): source holiday subdivisions from ISO 3166-2 so all states show The state/region picker for public-holiday calendars was built from the union of each holiday's counties for the current year, so a subdivision only appeared if some holiday that year was tagged with it. States with no state-specific holiday (e.g. US-WA, and AR/FL/NV/WY in 2026) silently vanished, blocking calendar creation (#1456). Source the full, correctly-named subdivision list per country from ISO 3166-2 instead, merged with any nager county code ISO lacks. Only region-partitioned countries get a picker, so nationwide-only countries keep allowing a country-level calendar. No server change needed — selecting a state already yields federal holidays via applyHolidayCalendars. * fix(costs): settlements honor custom per-member splits (#1458) calculateSettlement read each member's custom split amount but its query never selected budget_item_members.amount, so hasCustomSplit was always false and every settlement fell back to the equal split. Select bm.amount so custom amounts drive the balances. Also blank the Overview 'Per Person' / 'Per Person·Day' columns and CSV for custom-split items, where a single averaged figure is meaningless. * feat(plugins): read-convenience + todos + packing bags + tags + roster A wave of small, high-value capabilities: - weather:read (ctx.weather.get) — the host's cached forecast, tenant-free - db:read:categories (ctx.categories.list) — the global place-category list - db:read:tags / db:write:tags (ctx.tags) — the acting user's own tags, ownership re-checked before each write - trips.members (ctx.trips.members) — the trip roster (id + display fields), membership-checked - db:read:todos / db:write:todos (ctx.todos) — a trip's to-dos, gated by the app's packing_edit like the REST path, broadcasts todo:* - packing bags on ctx.packing (listBags/createBag/updateBag/deleteBag/setBagMembers) under db:write:packing — no privacy, plain room broadcasts perm labels (22 locales), both wikis, rpc-host gating + create-rpc-host wiring tests * fix(dashboard): render next-trip boarding pass stats on Safari (#1459) The boarding-pass bar carved its ticket-stub notches with a two-layer radial-gradient mask composited via mask-composite: intersect (and legacy -webkit-mask-composite: source-in). Safari mis-composites that multi-layer path to fully transparent, hiding the entire stats bar while Chrome renders it fine. Split .hero-pass into an outer wrapper (left notch) and a .hero-pass-inner glass panel (right notch), each carrying a single-layer mask so the mask-composite path is never exercised. Renders identically across engines and degrades safely where mask-image is unsupported. * feat(plugins): write scopes for atlas, vacay, journal and collections The write half of the user-scoped addon reads: - db:write:atlas -> ctx.atlas.markCountry/unmarkCountry/markRegion/unmarkRegion + bucket-list create/delete. Every row is the acting user's own (visited_countries/ visited_regions/bucket) — no trip scoping, no cross-tenant surface. Unblocks AirTrail-style two-way sync (#214) - db:write:vacay -> ctx.vacay.toggleEntry/toggleCompanyHoliday. The plan is resolved HOST-SIDE from the acting user's active plan — a plugin can never name another plan, and toggleEntry only toggles the acting user's own PTO day - db:write:journal -> ctx.journal.createEntry/updateEntry/deleteEntry, self-gated by journeyService.canEdit (owner/contributor) against the acting user - db:write:collections -> ctx.collections.create/update/savePlace/copyToTrip/ deletePlace, schema-validated; the service's per-collection role checks (assertAccess 404 / assertCanEdit 403) map onto RESOURCE_FORBIDDEN All addon-gated, userless contexts refused, audited. Perm labels (22 locales), both wikis, gating + wiring tests. * fix(admin): name the Costs add-on consistently in the catalog The budget add-on catalog entry still resolved to 'Budget' while the feature is labeled 'Costs' everywhere else (trip tab, navbar). Align admin.addons.catalog.budget.name with each locale's trip.tabs.budget label. Closes #1464 * feat(plugins): file attach, collab content and gated member-add - db:write:files -> ctx.files.create/createLink/update/softDelete under the app's separate file_upload/file_edit/file_delete rights. Content arrives as bounded base64 (10MB decoded cap, well under the app's 50MB), the extension is validated against the central blocklist BEFORE anything touches disk, and link targets must live on the same trip (findForeignLinkTarget). Broadcasts file:* - db:write:collab -> ctx.collab.createNote/createPoll/votePoll/createMessage under collab_edit + the Collab addon, emitting the same collab:* events as the app; service-reported errors surface as BAD_PARAMS - db:write:members -> ctx.trips.addMember. Adding a member GRANTS TRIP ACCESS, so it is deliberately its own permission behind the app's member_manage right (default: trip owner only) and never bundled with a lower-risk write; the acting user is recorded as the inviter, target must exist, owner/duplicate adds no-op Perm labels (22 locales), both wikis, gating + wiring tests. * fix(maps): honor check-in/out times for hotel bookend legs (#1465) The day route drew the accommodation as the day's start/end whenever the edge stop was a place, ignoring the morningIsSleptHere/eveningIsOvernight provenance already computed by getDayBookendHotels. On a check-in day an airport placed before check-in got a spurious hotel -> airport leg, and on a check-out day a later "home" stop still got a home -> hotel return leg. Add time-aware shouldDrawMorningLeg/shouldDrawEveningLeg helpers: the morning leg is the home-base default on a check-in day but is dropped when the first place is timed before check-in; the evening return leg is off on a check-out day unless the last place is timed at/before check-out. Wire them into the map polyline, the sidebar hotel connectors, and the Google Maps export so all three stay consistent. * feat(plugins): host-mediated notifications and LLM access Two host-owned integration primitives — the plugin supplies intent, the host owns the sensitive part: - notify:send -> ctx.notify.send({title, body, link?, scope, targetId}). Delegates to notificationService.send with a new plugin_notification event (raw title/body carried as passthrough params), so recipient resolution, channel fan-out (bell inbox + email/ntfy/webhook) and per-user preferences all match core 1:1. Recipients are FORCED to the acting user (scope 'user', targetId === uid) or a trip they belong to (scope 'trip'); scope 'admin' refused; the in-app link must be a relative /path (open-redirect-safe). No arbitrary recipient, no impersonation. Users can mute plugin notifications like any other event. - ai:invoke -> ctx.ai.complete(prompt) / ctx.ai.extract(text, jsonSchema). Runs the admin/user-configured provider via resolveLlmConfig + the existing extraction client under the acting user; the host holds the (encrypted) key, the plugin never sees it. Refused when no provider is configured; 20k-char caps. Output is DATA (complete -> {text}, extract -> {results}) and never auto-written, so prompt-injection can't reach a write without the plugin's own gated call. plugin_notification wired through the shared NotificationEventKey + all 22 locales (inbox passthrough + external channels). Perm labels (22 locales), both wikis, gating + wiring tests. * fix(budget): offer every Frankfurter-supported currency (#1470) The cost currency picker was gated by a hardcoded 47-code list, so currencies the app can actually convert (OMR, CRC, UGX, MKD, ALL, and ~115 more) couldn't be selected. Replace CURRENCIES/SYMBOLS with the full set the Frankfurter v2 FX API supports (archived BGN/HRK dropped), unify the dashboard offline fallback onto it, and teach currencyDecimals about the newly reachable zero- and three-decimal currencies. A currenciesWith helper keeps a previously saved (now-archived) selection selectable so it isn't silently wiped. * feat(plugins): tableContributor into the costs, packing and files views Extends the shipped tableContributor hook to three more native views — no new permission, no new attack surface: the same host-normalized, length-capped, url-allowlisted (http/https/mailto), enum-bounded, fail-safe pipeline, just more render sites. - server: add costs/packing/files to the view-contributions whitelist - client: widen the ViewName union + the api view type; render PluginCardFooter keyed by entityId in the budget category table (a colSpan footer row per item), the packing category group (footer after each item row, drag untouched) and the files list (footer after each row) A currency plugin can now drop a converted-amount column onto a cost row, a receipts plugin a 'view receipt' action onto a file, etc. Controller test asserts the three new views are accepted; both wikis updated. * fix(pdf): repeat day header on overflowing itinerary export pages (#1471) * feat(plugins): map-marker provider hook — plugins can overlay trip-map markers New declarative provider hook `mapMarkerProvider` (#587 "show bookings on map", the single most-requested contribution class, with zero contribution point until now): - hook:map-marker-provider permission + MapMarkerProvider/MapMarkerContribution SDK types + HOOK_PERMISSION wiring - GET /api/map-markers/:tripId (MapMarkersController) mirrors the view-contributions hardening: membership-gated, providers invoked host->plugin on a 5s timeout, fail-safe. Every field normalized server-side — coordinates range-checked (-90..90 / -180..180), strings String-coerced + length-capped, icon/tone enum- whitelisted, popup url http/https/mailto only (a javascript:/data: url would be click-XSS), marker count capped at 200 per plugin - client: PluginMapMarkers layer renders the markers as plain Leaflet Marker+Popup inside the trip map; plugin JS NEVER runs on the map canvas, every value is host-vetted data. Threaded tripId through MapView; fail-safe fetch Declarative-only by design, mirroring placeDetailProvider/tableContributor. Perm label (22 locales), controller hardening test, both wikis. * feat(plugins): show page plugins in the mobile bottom nav Page plugins were reachable from the desktop nav pill (Navbar) but not the mobile tab bar — you had to type /plugins/:id. BottomNav now reads page plugins from the plugin store and appends them the same way global addons are, mirroring Navbar. One-file client nav wiring; no new capability surface. * feat(plugins): per-user plugin settings form + ctx.settings runtime read Users can now enter their own per-plugin config (an API key, a preference) — the prerequisite for almost every real integration, previously unreachable (scope:'user' settings were only listed read-only in the admin panel). - migration: plugin_user_config (plugin_id, user_id, config JSON) — each user's own values, separate from the admin-owned instance plugins.config - PluginsService.getUserConfig / updateUserConfig / getUserConfigDecrypted + readUserSettingDecrypted: secrets encrypted at rest (apiKeyCrypto), masked to the client, an unchanged secret (the mask) keeps its stored ciphertext, and only DECLARED scope:'user' keys are ever stored - GET/POST /api/plugin-settings/:id (PluginUserSettingsController) — its own user-gated path (not the admin surface, not the /:id/* proxy), JwtAuthGuard only, scoped to the acting user - runtime: ctx.settings.get(key) -> the acting user's decrypted value (unconditional RPC, not sensitive cross-tenant; userless job/onLoad gets undefined) - client: a Plugins tab in Settings host-renders each active plugin's scope:'user' fields as an editable form (secrets write-only), reusing the declarative field shape — no plugin markup executes i18n (22 locales), wiki, rpc-host + service + masking/encryption tests. * fix(journey): keep skeleton suggestions in sync with linked trip places (#1473) Journey skeleton suggestions mirror a linked trip's day-assigned places, but sync relied on scattered per-event hooks that several assignment mutation paths never called: unassign, move and time-change fired nothing, no remove-on-unassign capability existed, and every MCP assignment tool synced nothing. Skeletons drifted from the trip. Add an idempotent reconcileTripSkeletons(tripId) that re-mirrors the trip's day-assigned places onto every linked journey (add missing skeletons, refresh date/time/location on move, remove skeletons for unassigned places; filled entries are detached + noted, never destroyed). Call it from every REST assignment handler and MCP assignment tool, and fire onPlaceDeleted on single MCP delete_place for parity. Extract a shared insertSkeletonEntry helper. * fix(memories): drop hidden Immich assets so Live Photo motion parts don't show a broken thumbnail (#1474) * fix(transit): anchor arrive-by search time to the destination timezone (#1479) * feat(plugins): host-brokered OAuth client + trustworthy inbound webhooks Two integration primitives where the host owns the sensitive part. Trustworthy webhooks: - auth:false routes now receive req.headers, but ONLY an explicit, credential-free allowlist (the common provider signature/event headers — stripe-signature, x-hub-signature-256, svix-*, x-gitlab-event, …). Cookie/Authorization/X-Socket-Id and every session/forwarded-auth header are stripped; authenticated routes get {}. A plugin can finally verify a provider signature without any way to leak a session. Host-brokered outbound OAuth (oauth:client): - the HOST runs the whole flow — authorize -> callback -> token exchange -> refresh — with PKCE + single-use, user-bound, TTL'd state, and HOLDS the tokens. The client secret + refresh token never leave the host; the plugin only triggers connect and reads a short-lived access token via ctx.oauth.getAccessToken() for the acting user. - provider config (authorize/token url + scopes + client id/secret) is the plugin's admin-owned instance settings; endpoints must be https (SSRF backstop, private/local hosts refused). Tokens per-user + encrypted at rest (apiKeyCrypto). - GET/POST /api/plugin-oauth/:id/{status,connect,callback,disconnect} — JwtAuth-gated, the callback always redirects to an in-app /settings path (never leaks an error). - Settings -> Plugins gains a Connect/Disconnect control per configured plugin. migration: plugin_oauth_tokens + plugin_oauth_state. Perm labels + form strings (22 locales), both wikis, service (PKCE/state/exchange/refresh/encrypt) + controller + proxy header-allowlist + rpc-host gating + create-rpc-host wiring tests. * fix(navbar): re-measure sliding tab pill after font load and resize (#1481) The active tab pill was measured once in a layout effect keyed only on activeTab, so on a hard reload it captured the active (bold) label's width against fallback-font metrics and never re-ran when the web font swapped in, leaving the pill slightly offset. Re-measure after document.fonts.ready resolves and on ResizeObserver changes (container + active button), with an idempotent state update to avoid redundant renders. * fix(collections): keep the Add-place button reachable after the first save On a wide/desktop layout the collection toolbar (which hosts the Add button) was gated on !mapOverlay, so it unmounted as soon as the list gained its first place with coordinates — leaving only an easy-to-miss "+" in the map overlay. Keep the toolbar rendered whenever the user can add a place, and drop the now-redundant map-overlay Add button so there is a single, predictable Add affordance in every state. Fixes #1485 * feat(plugins): days + accommodations reads/writes, endpoints on the reservation write path Community feedback on the 3.2.1 plugin surface: a plugin could write days but never list them (no way to learn day ids), day_accommodations had no surface at all, and trips.getReservations was the one reservation read that dropped the endpoints/day_positions hydration. - trips.getDays / trips.getAccommodations under db:read:trips (tripRead gate), wired to the same dayService lists the REST GETs use - trips.getReservations now returns the hydrated REST-parity list (endpoints, day_positions, joins, normalized accommodation_id) - strict superset - new db:write:accommodations scope: ctx.accommodations create/update/delete gated by day_edit like the accommodations REST path, with the partner-hotel reservation + delete cascade and broadcasts intact - reservation create/update pin the endpoints shape up front (BadParams instead of a mid-transaction NOT-NULL or a silently dropped row) - perm label in all 22 locales, consent PERM_KEYS, wiki tables * feat(plugins): day-detail widget slot in the day panel Widgets can now mount inside the trip planner's day panel (capabilities.widget.slot: 'day-detail'), scoped to the open day via a dayId in trek:context - the same pattern as the place-detail slot. Covers the requested per-day plugin content (logistics, outfit planning, live flight status) without a new plugin type. Day-detail widgets stay off the dashboard, the consent panel labels the slot in all 22 locales. * feat(plugins): let the frame CSP serve a plugin's own static assets The sandboxed frame runs at an opaque origin, so script-src 'self' never matched and a plugin's own <script src>/<link> files were blocked - authors had to inline entire React builds into index.html. Add a scheme-less host-source pinned to the plugin's own /plugin-frame/<id>/ path (charset-checked Host + plugin id so a stray token can't widen the policy; malformed Host falls back to inline-only). Multi-file client builds now load as-is; remote hosts stay blocked, so script URLs remain useless as an egress channel. * fix(plugin-sdk): catch the package up to the server capability surface The npm SDK's validator still knew only the 3.2.1 permission set, so 'trek-plugin-sdk validate' (and pack/publish, which run it) hard-rejected any manifest using the newer scopes - db:write:reservations, notify:send, hook:map-marker-provider and 25 more. Sync KNOWN_PERMISSIONS with the server envelope (48 entries), mirror the full PluginContext (reservations, accommodations, notify/ai/oauth/settings, packing writes + bags, file writes, collab, tags/todos/daynotes/collections/atlas/vacay/journal, weather, categories), type the tableContributor/mapMarkerProvider hooks + the entity/entityId event hint, accept the day-detail widget slot, and extend createMockHost so plugin unit tests can exercise all of it. * feat(plugins): grant-scoped entity snapshots on core events An events:subscribe handler so far learned only WHICH entity changed - useful for cache busting, useless for reacting to content, and the userless handler can't refetch. Now the broadcast tap derives a whitelisted field snapshot of the changed entity and the supervisor attaches it per plugin, only where the granted set holds the family's matching db:read:* permission (trips family -> db:read:trips, budget -> db:read:costs, packing -> db:read:packing, dayNote -> db:read:daynotes, file -> db:read:files). No acting user is ever synthesized. The whitelists are explicit per family, so user ids (owner/paid_by/uploaded_by/ participants/members), trips.feed_token and future migration columns never travel; a private packing item (#858) yields no snapshot at all because its core broadcast is owner-scoped; deletes/reorders/bulk ops carry none. * feat(plugins): pdf-section, atlas-layer and journal-entry provider hooks Three more declarative provider surfaces in the map-marker mould - plugins return data specs, the host normalizes, caps and renders; a slow or failing provider contributes nothing: - hook:pdf-section-provider: sections (title + paragraphs + a simple table) appended to the trip PDF export, escaped into the same HTML/print pipeline as the core content - hook:atlas-layer-provider: per-user country tint layers on the Atlas map (ISO 3166-1 alpha-2 codes only, tone-whitelisted, non-interactive pane so mark/unmark clicks keep working) - hook:journal-entry-provider: extra rows on a journal entry card, gated by the same journey access check as the journal routes + the Journey addon Permission labels in all 22 locales, consent PERM_KEYS, SDK types + manifest validator in both SDK copies, wiki tables, per-controller hardening tests. * feat(plugins): trip-page plugins can replace core planner tabs and pick their spot A trip-page plugin that takes over a core surface (a transit planner superseding Transports, a costs plugin superseding the budget tab) had to sit awkwardly next to the tab it replaces. capabilities.tripPage now names the core tabs to hide while the plugin is active - whitelisted (transports, buchungen, listen, finanzplan, dateien, collab), 'plan' deliberately not replaceable, and the tabs return the moment the plugin is deactivated - plus an optional 0-based position for the plugin's own tab. The feed re-validates the values out of the DB blob so a hand-edited row can't hide anything else, the admin list chips a replacing plugin (all 22 locales), and a saved session tab that got replaced falls back to the plan view. Also fixes the plugins feed dropping the day-detail widget slot to 'sidebar', which would have mounted a day-panel widget on the dashboard. * fix(plugins): audit follow-ups — normalization, secret cleanup, cron leak, slot filter Adversarial audit of the whole plugin PR surfaced 12 confirmed issues; this addresses them: - place-details provider was the ONE hook controller with no normalization: a plugin's href/label/value went to the client raw and unbounded. Now normalized like journal-entry-rows (safeUrl http/https/mailto, length + count caps). - trip-warnings capped message length + per-provider count (was unbounded). - uninstall(deleteData) now also purges plugin_user_config, plugin_oauth_tokens, plugin_oauth_state, plugin_meta_migrations and the capability audit — encrypted per-user API keys + OAuth refresh tokens no longer survive a 'delete all data' and get silently re-adopted on a same-id reinstall. - supervisor: a crash-restart cycle leaked the dead child's node-cron tasks and re-scheduled fresh ones, so a job fired N+1 times per tick after N crashes. onExit now stops them, mirroring kill(). - dashboard sidebar no longer mounts place-detail/day-detail widgets (they belong in the planner panels). - reservation endpoint validation relaxed to match the 3.2.1 service: a coord-less endpoint is accepted and dropped downstream instead of BadParams (no breaking change), while a bad role/non-string still rejects up front. - a replaced core tab reached by programmatic nav now falls back to the plan view. - trips.update caps title/description like the places path; plugin-db guard bans load_extension as defense-in-depth. - wiki: event snapshots, string-typed context ids, dayId in the payload, the live provider hooks and the costs update/delete grant are now documented correctly. * feat(plugins): phase-0 lifecycle hardening + per-plugin RPC rate limit Operational-readiness fixes from the completeness audit: - Re-activation after a failure worked again: a plugin left in 'error' state by a load-failure or crash-auto-disable stayed in the running map, so the admin's 'enable' button was a silent no-op. activate() now replaces a dead entry. - Per-plugin RPC rate limit at the dispatch boundary: every ctx.* call runs synchronously on the host thread, so a plugin in a tight loop could freeze the whole instance (and the reap sweep). A token bucket (generous burst) + an in-flight cap now throttle a runaway plugin with a retryable HOST_ERROR; a legitimate plugin never notices. - plugin_error_log retention (500 rows/plugin) so a crash-looper can't grow trek.db without bound; the crash-timestamp array is trimmed to its window too. - TREK_PLUGIN_PERMISSIONS=off now logs a loud one-time warning that the OS permission jail is disabled. * feat(plugins): read symmetry + broker — collab/journal/atlas reads, file content, trip create, rates The plugin API leaned write-heavy: collab and journal could be written but not read, files listed but not read, and there was no way to create a trip or see exchange rates. This closes those gaps in the established RPC+gate pattern (zero architecture risk), and it's what unlocks the importer + finance plugin classes: - collab reads: ctx.collab.listNotes/listPolls/listMessages under a new db:read:collab (membership + Collab addon, like the REST GETs) - ctx.journal.getEntries(journeyId): a journey's entries, journey-access-checked, under the existing db:read:journal - ctx.atlas.bucketList(): the acting user's bucket list, under db:read:atlas - ctx.files.getContent(tripId, fileId): a file's bytes as base64 under a NEW db:read:files:content grant (reading a passport scan is more sensitive than its filename), size-capped at 10MB before it crosses the IPC pipe, trashed files refused - ctx.trips.create(input): a new trip owned by the acting user, gated by the app's trip_create right + a bound user — the capability importers need - ctx.rates.get(base): cached currency exchange rates, tenant-free like weather Also caps trips.update title/description like the places path, and the plugin-db guard now bans load_extension (defense-in-depth). SDK, mock-host, i18n (22 locales), consent labels and the wikis are all in lockstep. * feat(plugins): deeper integration + user-facing activity transparency Wave 2 of the completeness work — richer extension points, deeper metadata, and the transparency that makes the broad read grants accountable: - db:meta now attaches to reservations + accommodations too (not just trip/place/day), gated by reservation_edit / day_edit respectively — the natural home for an external-id mapping (AirTrail/calendar/booking-import sync) without forking the core schema. - reservation-detail widget slot: a widget can mount on a booking card, scoped to the open reservation via reservationId in trek:context (the place-detail / day-detail pattern, third instance). - tableContributor gains the transports + todos views, so a plugin can add host-rendered columns/actions there too. - User activity log: GET /api/plugin-activity + a Settings → Plugins panel showing every host-mediated action a plugin took bound to the signed-in user, across all plugins, newest first — the user-facing half of the hash-chained audit. This is what legitimizes the deliberately broad read grants: not just the admin, the person whose data is read can see what was done in their name. - DX: the local dev server now binds a default acting user, so the canonical ctx.trips.getPlaces(tripId) call works locally instead of failing RESOURCE_ FORBIDDEN; the create scaffold drops the dead manifest routes[] / capabilities.nav fields the host ignores. SDK, i18n (22 locales), consent labels and the wikis are all in lockstep. * fix(memories): load Immich album photos on Immich v3 Immich v3 removed the `assets` property from AlbumResponseDto, so `GET /api/albums/:id` no longer carries album contents. TREK read album photos from that property, which now parses as undefined and degrades to an empty array — hence "No photos yet" in the Journey gallery picker even though the album header shows the right count (that count comes from `GET /api/albums` -> assetCount, which v3 still returns). Two call sites read the removed property. Besides getAlbumPhotos (the reported bug), syncAlbumAssets failed silently on v3: it reported `success: true, added: 0` while syncing nothing. Fetch album contents via an `albumIds`-filtered `POST /api/search/metadata` when `assets` is absent, and feature-detect rather than probe a version. The two paths are not interchangeable: on v2, searchMetadata unconditionally scopes results to `[self, ...partners]` (`asset.ownerId = ANY(userIds)`), so an albumIds search against an album shared by a non-partner returns nothing. v3 added an albumIds branch that checks AlbumRead and skips that owner filter. v2 also hard-defaults `visibility` to `timeline`, dropping archived assets. So v2 must keep reading the album detail body, which this preserves exactly. `withExif: true` is required on the search path: it has no default and gates an inner join, so without it Immich omits `exifInfo` entirely and every photo's city/country goes null. The existing test mock returned an album detail body *with* `assets` — it encoded the v2 assumption, which is why this shipped green. It now models v3 by default, with explicit v2 coverage asserting no search call is made. Fixes #1492 * feat(plugins): daily AI/notify budgets, runtime scheduler & reliable event redelivery Per-plugin daily caps on ai.complete/ai.extract and notify.send (defaults 200 / 100, overridable via TREK_PLUGIN_AI_PER_DAY / TREK_PLUGIN_NOTIFY_PER_DAY), seeded from the capability audit so a mid-day restart resumes the count instead of resetting it. Surfaced at GET /plugins/:id/budget. ctx.scheduler (at / in / every / cancel): persistent, userless timers that survive restarts and fire a scheduled() handler, riding the existing jobs:run grant so no new consent or admin setup is needed. Backed by plugin_scheduled_tasks, swept every 30s, capped at 100 tasks/plugin with an 8 KB payload and a 60s recurring floor; rows are removed on uninstall. Core events that fire while a subscriber is mid-restart are now held in a bounded in-memory buffer (200/plugin, 15 min TTL) and replayed once it goes active again, with the events:subscribe grant and snapshot gating re-evaluated at replay time so nothing leaks if a grant was revoked while the plugin was down. * feat(plugins): GDPR data-subject rights — durable per-plugin erasure + export New hook:user-data grant with two userless lifecycle handlers a plugin can put on its definition: deleteUserData and exportUserData. Neither carries an acting user — the plugin only learns the userId and touches its own db — so the grant reads nothing from core data; it exists purely so a plugin can honour a GDPR erasure or data-access request. When a TREK account is deleted (admin or self-service), every installed plugin holding the grant gets a row in a new durable erasure queue and its deleteUserData runs on the next sweep, retried until it ACKs — so erasure survives the plugin being offline or the server restarting. The core deletion path notifies the runtime through a dependency-free relay (like the event sink), keeping the auth/admin services decoupled from the plugins layer, and a plugin bookkeeping error can never fail the account deletion. Portability is served by GET /api/admin/plugins/user-data/:userId/export, which fans exportUserData out to the active granted plugins and aggregates what each holds about the user. Queue rows are purged on uninstall; the grant is labelled in all 22 locales. * feat(plugins): atomic ctx.db.tx for consistent multi-write on a plugin's own db Plugins could already query/exec/migrate their own SQLite file, but a multi-step write (move an item between tables, decrement one row and increment another) had no way to be atomic. db.tx([{sql, args?}, …]) runs up to 100 statements in a single transaction — all commit or all roll back — and reads within the batch see its own earlier writes, so read-modify-write is safe. Each op is one statement: a read returns { rows }, a write { changes }. The same guard (no ATTACH/PRAGMA/ RECURSIVE, size + row caps) applies to every statement in the batch. * fix(memories): filter hidden Immich assets at the source, not just the picker #1474 has the same root cause as #1492: the Immich v3 migration. On v2, searchAssetBuilder hard-defaulted metadata search to `timeline` visibility (`visibility = options.visibility ?? Timeline`), so hidden Live Photo motion parts could never come back from a search. v3 defaults to any visibility except `locked`, so they do — which is why the reporter is on Immich 3.0.1 and why the bug never appeared before. Ask for `visibility: 'timeline'` explicitly on the search path. That restores v2 semantics on both versions and stops hidden assets crossing the wire, which also fixes a pagination wart: a full page half-made of motion parts previously rendered as a half-empty page, because hasMore counts the raw page length while the filter shrinks the rendered set. The client-side filter was display-only, applied in searchPhotos and getAlbumPhotos — both picker-listing paths. Nothing guarded persistence or rendering: getOrCreateTrekPhoto stores any id it is handed, pipeAsset forwards Immich's 400/404 verbatim, and the photo grid is a plain <img> with no onError. So syncAlbumAssets, which filtered `type === 'IMAGE'` only, could persist a hidden IMAGE as a permanently broken tile. It now applies the same guard, extracted as isVisibleAsset(). Albums keep their filter rather than requesting `timeline` visibility: albums legitimately contain archived assets, and both the v2 album body and the v3 album search return them. Does not address tiles already persisted before this — those still render broken and need a separate fix. Refs #1474 * docs(memories): correct Immich version boundaries in the hidden-asset comments Verified against the v1.120.0 → v3.0.0 OpenAPI specs and server source. The previous comments said "Immich v2 hard-defaulted metadata search to timeline visibility". That is true only for 1.133–1.144. - `visibility` was added in 1.133.0. Before that, searchAssetBuilder applied `.$if(options.isVisible !== undefined, ...)` with no default, so pre-1.133 servers returned hidden assets too. #1474 was therefore not purely a v3 regression. - Those servers strip the `visibility: 'timeline'` filter rather than rejecting it: Immich validates with `whitelist: true` and no `forbidNonWhitelisted`. So the request stays valid, the filter is a no-op, and isVisibleAsset() is the ONLY guard there. Say so, so it does not get removed later as redundant. - `albumIds` only exists from 1.135.0. Because unknown properties are stripped, an albumIds search against an older server would silently drop the album filter and return the entire library as the album's contents. Feature detection on `assets` (present through 1.144.1, absent on v3) makes that unreachable; a version probe with a wrong boundary would not. Also cite Immich's own enum, which documents AssetVisibility.Hidden as "Video part of the LivePhotos and MotionPhotos". Comments only — no behavior change. * feat(plugins): dashboard trip-card badges + a mock-host driver for plugin tests Two additions that round out the plugin platform's breadth and its authoring DX. tripCardProvider hook (hook:trip-card-provider): a plugin returns small declarative badges for the dashboard trip cards. The dashboard fetches all visible cards in one call; the host access-checks every tripId for the acting user, bounds each field (label/value length, enum tone, http/https/mailto-only url), caps the count and drops any badge for a card that wasn't requested — plugin JS never runs on the dashboard. Rendered as text chips under the card meta; labelled + gated in all 22 locales. createMockHost now exposes run(def) — the other half of a plugin unit test. Where the ctx recorders capture what a plugin read, run() fires its own entry points (route, job, scheduled, event, plugin-event, deleteUserData, exportUserData, provider hooks) against the same mock ctx, and host.scheduled surfaces the timers it armed. A handler the plugin didn't declare throws a clear error instead of a silent no-op. * feat(plugins): include plugin data + code in backups, applied on restart A TREK backup archived travel.db + uploads + the encryption key, but each plugin's own SQLite file — the ONLY copy of the user data it holds — and its installed code lived in separate trees that were never captured, so a restore left the plugins rows with no data or code behind them. createBackup now adds plugins-data/ (each plugin's db + WAL sidecars, so SQLite recovers a consistent snapshot) and plugins-code/ (skipping dev-links by realpath, so an author's linked source is never bundled). Restore can't swap those live — the runtime holds each plugin db open — so it STAGES the extracted trees beside the live ones and the runtime swaps them in at the next boot, before it opens anything. Same "applies on restart" model the bundled encryption key already uses: no plugin quiesce, no swap under open handles, no new admin setup. Older archives without the trees restore exactly as before. * fix(plugins): audit — runtime robustness, security & data-lifecycle fixes Fixes from an adversarial audit of the plugin system, host/runtime side: Robustness: - getPluginDataDb recreated a handle a terminal-failure dispose had closed but left cached, so a re-enabled plugin's db:own threw on every call — recreate when the cached handle is shut. - ctx.ws.broadcast* now carry _inv, so the host can bind the acting user (the capability was silently refused, i.e. dead, without it). - ctx.events.emit swallows a rejected emit instead of crashing the child into a terminal 'error'; an uncaught throw AFTER activation is treated as a crash (restart with backoff), not a load failure. - A crash-respawned child gets the same activation deadline as a first activation and the buffered-event queue is cleared on the timeout path, so a hung onLoad after a crash can't peg a core and orphan events forever. - Expired buffered events are pruned by the reaper, not only at flush; the scheduler + erasure sweeps scope their LIMIT window to ACTIVE plugins so a backlog for inactive plugins can't starve deliverable work. Security / integrity: - Unix-domain-socket / named-pipe connects are refused by default in the egress guard (a host-local pivot to docker.sock / DB sockets), under the same policy as private IPs. - db.tx refuses transaction-control statements (a raw COMMIT would break its atomicity) and caps rows across the WHOLE batch, not per statement. - plugin_capability_audit is retention-capped per plugin (chain-safe: retained rows stay self-verifying), so it can't grow unbounded in the shared db. - A cap of 0 in TREK_PLUGIN_AI_PER_DAY / _NOTIFY_PER_DAY now disables the broker instead of falling back to the default. GDPR data lifecycle: - Account deletion now erases host-side per-user plugin tables (config, OAuth tokens/state) and enqueues the own-db erasure from the CORE path, so it works even when the runtime is disabled or pre-boot; guest deletion does the same. - uninstall keeps a pending erasure when data is retained (deleteData=false); erasure delivery is no longer grant-re-checked (a queued erasure is a duty); export flags installed-but-inactive plugins as pending instead of omitting them. Backup/restore: - Plugin DBs are WAL-checkpointed before archiving (no torn/stale snapshots). - Restore applies the staged trees immediately by quiescing the plugins (no unbounded gap where a later unrelated restart would revert diverged data); the swap is content-level (safe on a volume-mounted root) and preserves dev-links; the decompressed-size cap is operator-raisable. * fix(plugins): audit — hook-output hardening, dashboard slot & mock-host parity - Map-marker and atlas-layer tones were validated on String(tone) but emitted raw, so a non-string tone (an object with a matching toString) slipped through and crashed the client that renders it — check the raw value against the enum. - View-contribution column/action caps are now PER ENTITY, not per view, so a plugin's columns no longer vanish from every table row past the first 20; the dashboard trip-card badge cap is per card (≥ one on every visible card). - A reservation-detail widget no longer also renders as a context-free dashboard sidebar card (the inline filter was missing that slot). - mock-host matches the real host: it ignores asUserId on trip reads (bind the acting user), throws on a wrong user-scope notify target instead of coercing, enforces the scheduler caps, and detects RETURNING as a read in db.tx — so a passing author test can't hide a production RESOURCE_FORBIDDEN. * feat(plugins): full ctx parity in the dev server + fire jobs/events/hooks locally The trek-plugin dev server injected only ~6 of the ~35 ctx areas, so any plugin touching ctx.costs/packing/files/notify/ai/settings/scheduler/meta/oauth/db.tx/… hit a TypeError in local dev while the same code passed mock-host tests and worked installed. It also could only exercise routes. Delegate every non-db-own capability to a grant-enforcing mock host (the same one unit tests use) while keeping the real node:sqlite for db:own and dev-native ws capture + logging — so the whole surface works in dev with the exact production permission rules. dev-fixtures.json now takes the createMockHost options shape, so you can seed the full surface. New GET /__dev/fire/<kind>[/<name>][/<fn>] fires a job, scheduled timer, event subscription, GDPR handler or provider hook against the dev ctx, closing the "can't test non-routes locally" gap. * feat(plugins): wire the photoProvider + calendarSource hooks to real core consumers Both hooks were declared, typed and documented but NO core code ever invoked them, so an author could build, mock-test and install a photo or calendar plugin that silently did nothing. Give each a real consumer that fans out to it, exactly like the other eight provider hooks: - GET /api/plugin-photos/search (+ /sources, /item) aggregates photoProvider results for the picker — {id, title?, thumbnailUrl, fullUrl, takenAt?}, thumbnail/full URLs http/https-only (they become <img src>), per-source count capped, failing source skipped. - GET /api/plugin-calendar?start=&end= aggregates calendarSource events for the signed-in user — {id, title, start, end, allDay} ISO, count capped, failing source skipped, sensible default window. Both run with the acting user bound. The SDK interfaces now pass ctx as the last arg (so a source can reach ctx.settings/oauth/http for its backend), and the wiki marks them live instead of "reserved — no core consumer". * feat(plugins): close the create-heavy API asymmetries importers/sync hit Core services implemented these but plugins had no path to them, so the flagship importer/sync integrations hit real walls. Added, each reusing the EXISTING grant (no new consent): - ctx.trips.removeMember(tripId, userId) — reconcile DEPARTURES, not just additions (db:write:members + member_manage). Never removes the owner (that would orphan the trip); ownership transfer stays a separate deliberate action. - ctx.journal.createJourney({title, subtitle?, trip_ids?}) / deleteJourney(journeyId) — an importer can now bootstrap the journal it fills with entries and clean it up (db:write:journal), instead of only appending to journals a human created first. Wired end-to-end (envelope → rpc-host → create-rpc-host reusing tripService/ journeyService → both SDK copies → mock-host) and documented. (trips.delete needs its own destructive permission + consent copy and collab edit/delete + collections.delete remain — tracked as small follow-ups.) * feat(plugins): strip emojis from plugin-rendered text so it matches TREK's lucide UI Plugin authors (especially AI-generated ones) sprinkle emojis into the declarative text TREK renders in its OWN chrome — hook contributions (badges, columns, warnings, PDF sections, map-marker/atlas labels, journal rows, place details, trip-card badges, calendar + photo titles) and notifications — which clashes with TREK's lucide-only icon language. A shared stripEmoji() removes emojis (incl. flag/ZWJ/variation-selector sequences) and tidies the leftover whitespace, applied at the render boundary in every hook-contribution normalizer and in notify.send — so no matter what a plugin returns, the text TREK draws stays emoji-free. It does NOT touch a plugin's own sandboxed /ui frame (the author's to design), and it leaves photo ids verbatim (they round-trip to getById). The validate CLI warns when a manifest name/description contains emojis, nudging authors to the declarative `icon` field (a lucide name) instead. * fix(plugins): harden the restore-apply path — regressions from the backup/dev fix pass A final audit of the fix pass caught three regressions clustered in the two newest surfaces; the restore path could both crash the server and destroy data. - CRITICAL: a restore quiesces plugins via supervisor.shutdownAll() AFTER closeDb(), but shutdownAll killed children without first marking them stopped, so each child 'exit' took the CRASH path and wrote crash-accounting rows into the now-closed core DB — the throw escaped an EventEmitter listener as an uncaughtException and killed the whole process mid-restore. shutdownAll now marks every entry stopped and drops it from `running` BEFORE the kills (so onExit early-returns), and the onStatus/onLog DB hooks are wrapped in try/catch (also covers the stderr→onLog path). This also stops a normal shutdown from logging phantom "crashed" rows. - HIGH: swapContents cleared live entries then MOVED staged ones in, so a crash mid-move permanently deleted a plugin's only data copy (staging was already emptied, so a retry couldn't restore it). It now COPIES each staged entry over the live one and only deletes staging at the very end — `staged` stays the complete source of truth, making the whole operation crash-idempotent. - HIGH: the dev server lost the actingUserId=1 default in the mock-host refactor, so a fresh scaffold refused every user-bound capability. Restored. * fix(plugins): final-audit medium/low findings - GDPR export flags an active plugin whose export errored/timed out as `pending` instead of silently omitting it (collectUserExport now returns a discriminated result), so a data-access export never reads complete while missing data. - Account deletion also enqueues an erasure for plugins UNINSTALLED with retained data (an orphan data dir) — a same-id reinstall now honours the deletion instead of re-adopting the user's data forever. - oauth.getToken returns null in a userless context (matching the SDK/mock contract) instead of throwing RESOURCE_FORBIDDEN a background caller can't handle. - Crash-backoff restart is identity-guarded (+ the timer is tracked and cleared like the activation timer), so a disable + re-enable during the backoff window can no longer respawn a ghost child from the replaced entry. - db.tx transaction-control guard strips leading comments first, so `/* */COMMIT` can't slip past the start-anchored check and break batch atomicity. - createJournal inherits its cover only from a trip that was actually LINKED (access-checked), closing a cross-tenant cover-image read on plugin + REST paths. - trip-warnings drops a null array element instead of losing ALL of that provider's warnings; plugin-activity floors a non-integer ?limit so it can't 500. - The trek-plugin dev server binds loopback only and refuses cross-site requests to its side-effectful /__dev/fire endpoints (it serves real routes + no-auth dev actions). * fix(plugins): clear no-misleading-character-class in the emoji stripper The character class listed the ZWJ, variation selectors and combining keycap marks as members, which eslint reads as an accidental combined grapheme and rejected on CI. Pull the emoji glyphs out into Extended_Pictographic / Regional_Indicator alternatives so only the joiner/selector code points stay in the class, with a scoped disable where the rule still can't tell them apart. While here, reset lastIndex before the /g regex is reused in hasEmoji() so a second call can't resume mid-string and miss a leading emoji. * fix(security): trip-scope note-file deletion and guard the LLM base URL Two reported issues: - deleteNoteFile only matched on the note id and file id, so a member of trip A could delete a file attached to a note in trip B by guessing its id. Thread the trip id through the service and controller and scope the delete to it, the way every other collab operation already does. - The LLM extraction clients fetched the user-configured base URL directly, so a user could point it at the cloud-metadata endpoint (169.254.169.254) and read the echoed error body. Route both clients through a new safeFetchLlm() that blocks the link-local/metadata range while still allowing a local or LAN Ollama (loopback and private ranges stay reachable), pinned to the resolved IP so a hostname can't rebind to the metadata address after the check. * fix(security): route every LLM client through the SSRF guard The base-URL SSRF fix covered the openai-compatible and anthropic clients but missed the native Ollama /api/chat client and the /api/tags + /api/pull model- management calls, whic… * fix(plugins): repair plain-HTTP egress and forward the private-egress opt-out Two pre-existing bugs in the plugin egress guard, found by running a plugin against a real service end to end. 1. Every plain-HTTP request a plugin made was refused, whatever host it had declared. Node pre-normalises `net.connect()` args into an [options, cb] array and passes THAT array as the single argument; undici's plain-HTTP connector takes this path, its TLS connector does not. classifyConnect read `host` off the array, got undefined, and fell back to 'localhost' — so a fetch to a declared, public host was rejected with the nonsense message "localhost is not in the plugin's declared hosts". It failed closed, so it was never a security hole, and it went unnoticed because the only shipped egress plugin uses HTTPS. unwrapConnectArgs() unwraps the normalised form before anything reads host/path. 2. TREK_PLUGIN_ALLOW_PRIVATE_EGRESS could never have any effect. The guard that reads it runs INSIDE the child, whose env is scrubbed to a four-entry whitelist that never included it — so a documented setting (wiki/ Environment-Variables.md) was wired to nothing, and no plugin could reach a self-hoster's LAN service no matter what the operator set. Forwarded only when set, so the default stays the secure block-private policy. Regression tests cover the normalised form in both directions: the real host is now resolved, and an undeclared host, a private IP and a unix socket are all still refused when passed that way. * feat(notifications): let a plugin register a notification channel TREK's four channels (in-app, email, webhook, ntfy) were a closed set: notificationService.send() dispatched with four copy-pasted `if` blocks and no provider abstraction, so a fifth channel meant editing eight files by hand. A plugin could produce a notification via ctx.notify.send(), but never deliver one. A plugin now registers a channel with `hooks.notificationChannel` + `hook:notification-channel` on a plain `type: 'integration'` — not a new manifest type, so the TREK-Plugins registry schema and both its CI gates are untouched. Core refactor - New channel registry (services/notifications/): email/webhook/ntfy become ExternalChannel providers wrapping the EXISTING send functions — no delivery logic is rewritten, only relocated. In-app deliberately stays out: it writes typed rows with scope/target/callbacks, not a rendered title+body, the same line shared/ already draws with i18n/externalNotifications. - The event text is now rendered once per recipient instead of once per channel. - The channel set is open: NotifChannel becomes a string, the matrix is registry-derived, and the UI columns are server-driven. The DB column was already bare TEXT and the Zod contract already a string record — only the TypeScript and the two UIs were ever closed. The hook runs USERLESS. Every other hook is user-initiated, so actingUserId falls out of the request; a notification is host-initiated for an ARBITRARY recipient, so ctx.settings.get() would return undefined. The host resolves the recipient's decrypted scope:'user' settings itself and passes them as an argument. That is what lets a channel plugin be handed someone's push token WITHOUT being handed the right to read their trips as them. Enabling the plugin is the opt-in: a plugin channel is not gated on the admin's `notification_channels` list. A built-in always exists in code and needs an explicit switch; a plugin channel only exists because an admin enabled that plugin. (Nothing could write a `plugin:` id into that CSV anyway, and the admin toggle rebuilt it from three booleans, silently dropping anything else — so requiring a second opt-in meant the channel could never be turned on at all.) Also fixed, found while building this: - Plugin settings keys were unvalidated, so a field named `__proto__` or `constructor` resolved off Object.prototype: a REQUIRED field with such a name reported as configured for every user who had configured nothing — enough, for a channel, to be dispatched to everyone with no credentials. Keys are now constrained at install and the config blob is parsed null-prototype, so it is impossible even for an already-installed plugin. - A `select` field's options were cast straight through, so the obvious `["1","5"]` form rendered every dropdown entry BLANK (the client reads value/label). Now coerced, and malformed options are rejected. Also adds: operator-supplied egress hosts (a plugin talking to a self-hosted service can't name the operator's host at publish time, so an admin adds it post-install and the runtime re-spawns the child with the widened allow-list — only for a plugin that DECLARED operatorEgress, and only an admin, never a user); settings-page actions (a "Test connection" button, user-initiated so ctx.settings.get() returns the clicking user's own value); and a Gotify-shaped notification-channel template in the SDK. Verified end to end against a real Gotify container, not just in tests. * docs(wiki): document the plugin notification-channel surface Covers the pieces added in the previous commits, in the pages a reader would actually reach for: - Plugins.md (the admin-facing page) had none of it: notification channels, settings actions, and a full "Allowed hosts" section — including what operator-supplied egress deliberately does NOT let anyone do. - Plugin-Development.md: the notificationChannel hook (and why it is the one hook with no acting user), settings-page actions, operatorEgress, and the manifest reference rows. - Plugin-Cookbook.md: a "become a notification channel" recipe and a "Test connection button" recipe. - Plugin-Permissions.md: hook:notification-channel, operatorEgress under the outbound section, and settings actions under "not a permission". - Notifications.md: plugin channels alongside the four built-ins. * fix(sdk): allow empty egress if and only if operatorEgress is true * ci: don't run repo-specific workflows on forks Guard release, publish, wiki-deploy and issue/PR-triage workflows with a `github.repository` check so they no-op in forks instead of failing or acting on the fork's own issues, PRs, tags and registries. Also skip the Docker Scout scan for pull requests from forks: Docker Hub secrets are never exposed there, so the login step could not succeed. Tests and lint stay ungated — they need no secrets and are the gate for incoming fork PRs. * feat(sdk): add missing methods in mock-host * fix(airports): rebuild the json file * fix(airports.json): add small airports too * fix(public transit): only show public transit option when a trip has actual dates * fix(plugins): reap a queued erasure only once the plugin's data is gone The orphan reap deleted every queue row whose plugin had left the registry, but uninstall(deleteData=false) removes the plugins row while deliberately keeping the data dir AND the queued erasure so a same-id reinstall can still honour it. The reap now deletes a row only when the plugin's data dir is actually gone; a deleteData=true uninstall already clears the rows itself. * fix(backup): snapshot the core DB and swap restores atomically createBackup archived travel.db via the archiver's lazy live-file read, so a WAL auto-checkpoint firing mid-stream could write a torn database into the zip. It now VACUUM INTOs a point-in-time snapshot and archives that, the same guarantee plugin DBs already get. restoreFromZip swapped the DB by unlink-then-copy, which on an interrupted restore could leave no valid travel.db; it now copies to a temp file and renames it into place (atomic), dropping the stale -wal/-shm sidecars first. * fix(deploy): Recreate strategy for the SQLite volume, pin the root compose image The Helm Deployment had no strategy, so the default RollingUpdate would start a second pod holding the same ReadWriteOnce PVC before the old one exits — a Multi-Attach deadlock or two writers on one SQLite file. Default to Recreate (overridable for ReadWriteMany). The root docker-compose.yml pinned trek:dev, a tag no workflow builds, so a clone-and-up at the release tag ran a stale image; pin it to :latest like the README. * fix(security): re-validate LLM endpoint fetch redirects per hop (GHSA-fmq9) safeFetchLlm left undici's default redirect:'follow', so a configured LLM endpoint could 302 to http://169.254.169.254/ and reach cloud-metadata credentials — the DNS pin does not cover an IP-literal redirect hop, since net.connect skips the pinned lookup for a literal IP. Follow redirects manually now, re-resolving/re-checking/re-pinning each hop (allowing LAN/ localhost as before). Also block the Alibaba metadata IPs directly. * fix(plugins): throttle the plugin log channel to prevent host-thread DoS The per-plugin RpcRateLimiter only guarded the ctx.* (req) channel; ctx.log.*, stdout/stderr and unknown evt topics reached a synchronous INSERT+prune on the host thread unthrottled, so a while(true) ctx.log.error(...) loop could freeze the instance. Route every plugin-driven log path through a per-plugin log token bucket; excess lines are dropped with a summary line on resume. * fix(plugin-sdk): serve dev /ui frame at /ui/index.html so relative assets resolve (#1526) The dev server embedded the plugin UI as <iframe src="/ui"> (no trailing slash), so a multi-file build's relative asset URLs (./assets/x.js from Vite base:'./') resolved against the origin root -> /assets/x.js -> 404, even though the files are served at /ui/assets/*. The real host loads the frame at /plugin-frame/<id>/index.html where the same relative URLs resolve correctly, so dev now matches it by loading /ui/index.html (and also serves /ui/ as index.html). * i18n: improve Russian translations (#1539) * v3.4.0 (#1527) * fix(plugins): unknown column * fix(mcp): reuse MCP sessions instead of creating one per tool call The /mcp CORS layer never set exposedHeaders, so Access-Control-Expose-Headers was absent and browser-context MCP clients (Claude Desktop connectors, Claude.ai, MCP Inspector) could not read Mcp-Session-Id off the initialize response. Unable to echo it back, every request looked like a fresh initialize: one McpServer and one session per tool call, until the per-user cap returned a 429 and the integration died until the container was restarted. The idle sweep was not at fault — it expires on lastActivity with a 1h default, so sessions born seconds apart are nowhere near expiry, hence 'cleaned 0'. - expose Mcp-Session-Id, MCP-Protocol-Version and WWW-Authenticate - evict a user's least-recently-active session at the cap rather than refusing the request, so a client that cannot persist its session id (or a proxy that strips the header) can never wedge the server - close the McpServer/transport orphaned by every session-less non-initialize POST, which was leaked: never mapped, never swept, never closed - return the cap error as JSON-RPC so clients surface the real reason - warn on session-less POSTs to make a header-stripping proxy diagnosable * chore(deps): declare @modelcontextprotocol/sdk ^1.29.0 Matches the version already resolved in the lockfile; no dependency-tree change. * docs(mcp): add the reverse proxy specs for MCP * fix(plugins): stop the row ⋯ menu being clipped by the sidebar The menu was an in-flow `absolute` div, and its ancestor (PageSidebar) is `overflow-hidden` — which clips absolutely-positioned descendants regardless of z-index. With enough plugins installed a row sits low enough that its menu runs past the sidebar's bottom edge and gets chopped, taking Delete with it, so the plugin could no longer be uninstalled from the UI. Portal the menu to <body> and position it `fixed` against the ⋯ button, flipping upward when the bottom is tight and re-anchoring on scroll/resize. A fixed child of <body> has no overflow ancestor, so nothing can clip it. Closes #1523 * feat(plugins): surface author-signature status and add a scoped re-trust override TREK has always verified an author's Ed25519 signature and TOFU-pinned the key on first install, but none of it was ever shown: a successfully-installed UNSIGNED plugin looked identical to a signed one, and a signature-refused update left the plugin quietly pinned at its old version with the reason dying in a toast. Give the four refusal conditions machine-readable codes (SIGNATURE_MISSING / _INCOMPLETE / _KEY_CHANGED / _INVALID), persist a refusal on the plugin row so the admin list keeps showing it, and badge Signed/Unsigned in the list and in Discover. Only SIGNATURE_KEY_CHANGED is overridable — an author can legitimately rotate a key; a signature that does not verify means the bytes are not what the author signed, and there is no story where waving that through is right. The override re-pins and updates in ONE call (POST :id/retrust): a re-pin that waited for a follow-up /update would leave the plugin pinned to a key no install had ever been verified against if that second call never came. The artifact must still verify under the new key, so a re-trust moves the pin from one verified key to another. assertRetrustable re-derives the condition server-side, so the UI hiding the button is a convenience, not the control, and it echoes back the full key the admin was shown so a re-key since the dialog rendered is refused. The rotation is written to the admin audit log with both fingerprints — after an incident, "which key did we move from, and to what?" is the question a single key cannot answer. * fix(plugins): let a plugin's frame reach the hosts an admin added for it The frame's connect-src was built from the manifest's http:outbound grants alone, but the child's egress guard is the UNION of those and the hosts an admin added after install for an operatorEgress plugin (a self-hosted Gotify, an ntfy — hosts the author cannot know in advance). So such a plugin WITH A UI could call the operator's host from its server and was CSP-blocked in its own iframe. Match the frame to the child. The admin consented to these hosts at install and the child already reaches them, so this widens no trust boundary that isn't already crossed. Both sources stay validated on the way in, and the interpolation filter is unchanged. * fix(plugins): report a rejected events.emit on the plugin's own log stream The host can reject an emit (an undeclared event name, a rate limit). The rejection must not escape — a detached rejection crashes the child and terminally disables the plugin over one bad emit — but swallowing it silently left an author with no way to discover that `emits` was missing from their manifest. Surface it as a warning instead. * feat(plugin-sdk): expose the raw request body for webhook signature checks A webhook author must run their HMAC over the exact bytes the sender signed. `body` is the PARSED value, and re-serializing it will not reproduce those bytes — key order, whitespace and unicode escaping all differ — so the signature never matches. Document `rawBodyBase64`, which the host already sets on auth:false routes. * fix(plugin-sdk): refuse to overwrite a released artifact, and keep the packed zip A released artifact is IMMUTABLE: the registry pins its sha256, so overwriting the bytes of a release already in the registry breaks the checksum for everyone who installed that version — they can no longer install or update it. The old code blanket-caught every `gh release create` failure (auth, network, a bad repo) and turned it into a --clobber upload. Probe for the release explicitly and refuse unless --force. Also stop deleting plugin.zip on the way out. 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 THAT file, not a rebuild. * fix(plugin-sdk): don't fail submit when the fork already has an upstream remote `gh repo clone` of a fork may already have wired `upstream`, in which case a bare `remote add` exits non-zero and took the whole submit down. Set it either way. * fix(plugin-sdk): make the dev server behave like the host Three ways `dev` lied to an author about how their plugin would run in production: - ctx.db: one try/catch wrapped both the node:sqlite probe AND opening the database, so an mkdir/permission failure silently degraded to the in-memory stub — which swallows every write while reporting success. A db:own plugin "worked" in dev and persisted nothing. Probe separately: fail loudly on a real error, degrade only on old Node, and say plainly that the stub discards writes. - notificationChannel: the host fires it with no acting user and hands the recipient's decrypted settings in as a separate `config` argument — send(msg, config, ctx) / test(config, ctx). Firing it like an ordinary hook passed `ctx` where `config` belongs, so a channel plugin read its settings off ctx and was broken in production. - /preview pinned tripId 42 while the scaffold seeds trip 1, so the widget's first trek:invoke hit assertMember(42) and 500'd. Preview against a trip that exists. * fix(plugin-sdk): reject unknown flags, wire up create's new flags, and add --help `parse()` accepts any --x, so a flag a command does not read was silently dropped: `create --template notification-channel` cheerfully scaffolded a blank plugin. Silently ignoring an author's explicit instruction is worse than refusing it, so unknown flags are now an error, and create actually forwards --template/--egress/--required-addons. A bare --permissions used to split the string "true" into a permission literally named `true`; listFlag() now treats a valueless flag as absent. Since an unknown flag is now fatal, `--help` has to exist: it is intercepted before the flag check and prints usage on stdout with exit 0. * chore(plugins): drop three unused eslint-disable directives The no-console rule is not enabled for these files, so the directives were dead and eslint reports them as unused. * fix(plugin-sdk): bring preflight back in step with the registry's gates preflight exists to tell an author what TREK-Plugins' CI will say before they open the PR. The registry now verifies author signatures, and preflight didn't — so it drifted into the one failure mode it must never have: a false green. An author trusts a green. - Verify the signature against the artifact bytes. preflight already downloads them for the sha256 check, so this costs one call. Without it, signing with the wrong key (or re-packing after signing) sails through and is caught at review. - Check the signature SHAPE (checkSignatureShape): a key with no signed version, a signature with no key, a malformed key or signature. TREK refuses to install a half-signed entry, so such an entry is dead on arrival. - Default apiVersion to 1 before comparing. It is OPTIONAL in the manifest — install/ manifest.ts and `entry` both default it — so a manifest that legally omits it was failing preflight with "manifest apiVersion undefined != entry 1" while the registry passed it. A false RED, which teaches authors to ignore the tool. - Check requiredAddons/pluginDependencies parity, and operatorEgress without an http:outbound grant. The verifier is a port of the host's install/verify-signature.ts (the registry has its own port); sign.ts's verifyArtifact only understands the bare key/signature pair the SDK itself emits and cannot judge a minisign key. A test pins all three to the same verdicts. * feat(plugins): enforce compatibility range * chore: bump sdk version * test(e2e): repair the trip-creation specs create-trip and trip-planner have been failing for a while — long enough for three separate UI changes to drift past them, which nothing caught because CI runs vitest only and never invokes Playwright. Each failure was masking the next: - The release-notice modal greets a freshly seeded user and its backdrop swallowed the click on .add-trip-card. Added a shared dismissSystemNotices() helper (the X only shows on the notice's last page, so it has to page through first). - .modal-backdrop no longer exists — the class was namespaced to .trek-modal-backdrop so content blockers stop hiding it. - input[type=text].first() is no longer the Title field: the cover-image search inputs now sit above it, so the specs were typing the trip name into the photo search box and creating an untitled trip that never matched getByText(title). * fix(planner): gate drag & drop on pointer type, not viewport width (#1432) The 3.2.1 fix disabled drag on "mobile", but nothing in the client has ever detected touch — "mobile" was inferred from viewport width, at four independent breakpoints. A tablet is a coarse-pointer device at a *desktop* width, so an iPad (820-1366px) fell on the wrong side of all four, which is why iPhone was fixed and iPad was not: - useTripPlanner's isMobile (<768px) is what disarmed `draggable`, so on iPad rows stayed draggable and a scroll swipe became an HTML5 drag. - TripPlannerPage hardcoded isMobile={false} on the desktop PlacesSidebar, so its drop handlers and the drop-to-import overlay could never be disabled — that overlay is the reported symptom. - The arrow-button reorder fallback was revealed only below 767px, leaving iPad with no drag *and* no fallback. - touchDragPolyfill loaded drag-drop-touch at >=1024px, synthesising drags from touchmove — on a landscape iPad that re-armed the very gesture hijack 3.2.1 removed. Adds useIsTouch() ((pointer: coarse)) as a signal separate from isMobile: layout stays width-driven, so the iPad keeps the desktop two-pane planner, while every drag affordance is gated on isMobile || isTouch. The reorder arrows now show on coarse pointers, and the polyfill loads only on hybrid laptops ((pointer: fine) and (any-pointer: coarse)), which also removes the #1440 phantom-dblclick map zoom on tablets. Guarded by unit tests plus an e2e spec on real WebKit in an iPad Pro 11 context — the engine matters, since every browser on iPadOS is WebKit underneath, which is why the reporter hit this in all three they tried. * test(planner): guard the day-plan reorder arrows against phantom clicks The hover rule that reveals the reorder arrows had been dead since the TypeScript migration: it targeted `.place-row:hover .reorder-btns`, and neither class exists — the component renders `.reorder-buttons` inside an unclassed row. The buttons sat at opacity:0 on desktop with nothing to reveal them. That was not merely invisible. opacity:0 still hit-tests, so every itinerary row and day note carried an invisible, fully clickable target that silently reordered the trip: opacity: "0", visibility: "visible", pointerEvents: "auto" elementFromPoint(centre) -> BUTTON, inside .reorder-buttons The repair — pointer-events: none while hidden, plus a working .dp-row:hover/:focus-within reveal (focus-within so the buttons are also reachable by keyboard, which the file's JS-hover pattern cannot do) — lives in index.css and DayPlanSidebar.tsx. Both files also carry the #1432 drag gating, so they went with that commit rather than being split mid-file; this commit is the regression guard for them. E2E rather than unit, because jsdom does not evaluate :hover. Against the old CSS it fails on exactly the right assertion: "hidden arrows must not swallow clicks" — expected false, received true. * fix(pdf): keep the header gap on day-header overflow pages (#1531) The repeated <thead> day header (#1471) carried no gap before the first card on overflow pages: the 12px sat in .day-body's block-start padding, which a fragmented box only paints on its first fragment. Move it to the thead cell so it repeats with the header; the day's first page renders pixel-identically. * fix(budget): keep "no one paid yet" when editing an expense (#1533) The ExpenseModal payer initializer fell back to the current user whenever the edited item had no payer, so reopening an expense saved with "no one paid yet" silently reselected "You" — and re-saving then recorded the current user as the payer, corrupting the balances. An absent payer on an existing expense is a deliberate value, so only a brand-new expense defaults to me. * feat(sdk): support for plugin icons * fix(planner): keep the places filter applied and visible across tab switches The category and all/unplanned/tracks filters lived twice: a local copy in the sidebar driving the checkboxes and the list, and a page-level copy driving the map markers, synced only when a checkbox was clicked. Switching planner tabs unmounts the sidebar, so the local copy reset to "All Categories" while the markers stayed filtered — and the only way out was toggling any category on and off again (#1541). The filter now lives once in the trip store, next to selectedDayId: it survives the Plan tab unmounting (and the mobile places sheet closing), keeps both sidebar instances in agreement, and resets when another trip loads. * feat(airtrail): import connecting flights as one multi-leg booking AirTrail flights always imported as separate single-leg reservations, so a layover could not be expressed and the connection country ended up counted as visited in Atlas (#1535). The import picker now detects connection chains among the listed flights — each leg departing from the airport the previous one landed at, onward within 24 hours, and never back to the origin (an out-and-back is a return, not a connection) — and offers to import each chain as one flight with layover stops, on by default. The joined booking keeps per-leg airline, flight number, times and seat in metadata.legs, files every leg on its own trip day, and mirrors the first/last leg flat, exactly like the manual multi-leg form. With the connection stored as a stop endpoint, the existing Atlas role filter excludes the layover country on its own. AirTrail has no multi-leg flight a joined booking could round-trip to, so it imports detached from live sync, with every source flight id recorded in metadata.airtrail_ids — the picker and the server-side dedupe both treat those legs as imported, per leg, even across trip members. The server re-validates each requested chain and falls back to individual imports when it does not actually connect. * fix(airtrail): stop syncing a booking once it grows extra stops A linked flight that becomes multi-leg locally no longer matches the single AirTrail flight it was imported from: pushing would rewrite that flight to span the whole route, and the next pull would flatten the layover chain back to a plain from/to. Both sync directions now detach the link instead — the same state a joined import starts in, surfaced by the existing "Not synced" badge. TransportModal also carries metadata.airtrail_ids through re-saves (like it already does for transit itineraries and day positions), so editing a joined booking cannot cost it its import dedupe and get its legs re-offered in the picker. * fix(planner): default a new accommodation to checking out the next day The hotel picker pre-filled "Apply to days" with the same day for check-in and check-out — a stay that ends the day it begins. New accommodations now default to the following day for check-out; the last trip day keeps the same-day range, and editing still seeds from the stored range. * docs(wiki): document the AirTrail import and connection joining * fix(plugins): fold resolvePluginIcon into PluginIcon pluginIcon.ts and PluginIcon.tsx resolve to the same file on the case-insensitive filesystems dev checkouts commonly sit on (Windows, macOS) — tsc sees both casings of one module and fails with TS1149 in every importer. Keep the resolver and the component in one module. * feat(sdk): add update verification * chore: remove test files * fix(sdk) rework the sdk helpers and DX/UX * fix(sdk) harden dev environment * fix(budget): add back the multi payer selection * fix(map): stop MapLibre mouse rotation from reversing near mid-screen Since MapLibre 5's camera rewrite, the right-button rotate handler flips its sign whenever the cursor sits above a mid-screen line it derives by re-projecting the map center. That line drifts with the bearing by a fraction of a pixel, so inside the 100px band around the screen center a steady horizontal drag lands alternately above and below it — every processed movement reverses the previous one and the camera ping-pongs in place instead of rotating (#1545). A real hand crossing the line mid-drag flips the rotation direction outright. maplibre-gl 4.x rotated from plain horizontal movement and had none of this. Passing aroundCenter: false opts the handler out of the around-center mode and restores the 4.x/mapbox-gl behaviour: horizontal drag rotates, vertical drag pitches, in one continuous motion. Applied to all three GL map builds (planner, journey, settings preview); mapbox-gl keeps its options untouched. * fix(budget): settle in the trip's real currency, not always EUR The settlement route read `currency` off the row returned by canAccessTrip, whose SELECT never included the column. A cast hid the mistake, so trip.currency was always undefined and the settlement was told every trip is in EUR. Balances are netted in the trip currency and converted to the display currency once. With the trip mislabelled EUR, expenses in the trip's own currency still cancelled out, but an expense booked in a foreign currency was divided by its frozen rate into trip-currency units, then converted again as if those were euros — inflating balances by the EUR/trip rate (~27x for a RUB trip with a USD expense, #1543). MCP was unaffected: it reads the currency with its own SELECT. Select the currency in canAccessTrip so the read is real. The settlement maths was correct all along; it was simply being lied to about the base currency. Fixes #1543 * feat(trips): let users set the trip currency, and rebase the budget when it changes The trip currency is the base every expense and settle-up is netted against, but the only picker for it lived in the legacy Budget addon panel — so on the Costs panel a trip was stuck with whatever it was created as. Add the field to the trip form, on create and on edit, gated on trip_edit. The REST and MCP write paths already accepted `currency`; only the form was missing. Changing it is not a rename, though: an expense's frozen `exchange_rate` is "units of its currency per 1 trip currency", and `currency = NULL` means "the trip's own", so both are relative to the outgoing base. Swapping it out from under them redenominates the implicit rows (9 000 RUB becoming 9 000 EUR) and leaves the frozen rates pointing at a currency the trip no longer uses — the same mismatch that inflated #1543. So rebaseTripCurrency() runs first, while the old currency is still on the row: it pins the implicit rows to the outgoing currency and re-freezes every rate against the incoming one, for expenses and settle-up transfers alike. No stored amount is rewritten — each keeps the figure the user typed, in the currency they typed it in, and its real-world value survives the switch. Also covers the #1543 data as a settlement regression test. * feat(budget): give settle-up payments their own currency A transfer settling a shared bill can be made in any currency — paying a rouble debt in euros is normal — and the server has stored `currency` + a frozen `exchange_rate` on every transfer since #1445, re-freezing it on edit. The UI just never let anyone choose one, so a payment silently inherited whatever the viewer's display currency happened to be. Add the picker to the payment modal, mirroring the expense modal, and reopen an existing payment in the currency it was actually recorded in. The ledger row now shows a foreign payment as `$30.00 -> 27,00 EUR` like a foreign expense does, instead of stamping the display currency's symbol onto the raw stored number. The Settle buttons on the suggested flows keep sending the display currency: those amounts are computed in it. * feat(settings): make the display currency optional, falling back to the trip's Costs already resolved `default_currency || trip.currency || 'EUR'`, but the setting could never actually be empty: the store seeded 'USD', so a user who had never touched it silently had every trip converted into dollars, and the picker offered no way to unset it. Seed it empty and lead the picker with a "Trip currency" option, so an unset preference means "show each trip in its own currency" instead of forcing them all through one code. An explicit empty value persists and beats the admin-set instance default — it is a deliberate choice, not an absence. This also brings the public share's fallback to life: the share payload has resolved sharer's currency -> trip currency since #1361, but the trip-currency branch was unreachable while every owner had a currency forced on them. Plugins are handed `formats.currency` as a concrete code, so PluginFrame now resolves the same chain rather than passing an empty string through the bridge. * docs(wiki): explain the three currencies and how they relate Trip currency, expense currency and display currency answer three different questions, and nothing said so: the trip currency wasn't documented at all (it had no picker until now), and Budget-Tracking conflated the other two while still claiming 47 currencies and a display currency that always came from Settings. Add a Currencies page as the one place they're defined together — the trip currency as the accounting base, the expense currency as the receipt with its rate frozen at entry, the display currency as presentation-only — plus what happens when a trip's currency changes, which currency a public share renders in, and what belongs to the Costs addon versus the trip itself. Rewrite Budget-Tracking's currency section against it, document the currency field in Creating-a-Trip and the display currency in Display-Settings (which never mentioned it), and note the sharer-or-trip fallback in Public-Share-Links. * feat(help): serve the in-app wiki from disk instead of fetching GitHub The /help pages fetched their markdown from raw.githubusercontent.com at runtime, so a self-hosted install was served docs from main rather than the version it was actually running, and help was unusable without network access. The wiki/ directory was in the repo the whole time; the bundled-snapshot fallback the code reached for was gitignored and never populated by any build step, so it was dead code. Read wiki/ straight from disk instead. server/{src,dist}/services both sit three levels under the repo root, so a single __dirname anchor resolves in dev, a built source install, vitest and Docker with no copy or build step. GitHub is kept strictly as a fallback for when the directory cannot be resolved, decided once at load by probing for _Sidebar.md: a page missing from a present wiki is a genuine 404, since falling back per-file would reintroduce the version skew this removes. Ship wiki/ in the image: .dockerignore excluded it outright, so the COPY alone would have produced an image with no wiki, and the GitHub fallback would have masked that at runtime. Add a real path-containment check on assets now that the path becomes a filesystem read rather than a URL, and document TREK_WIKI_DIR as an off-by-default escape hatch across the deployment configs. * fix(plugins): serve frame assets root-relative and cross-origin loadable res.sendFile(absolutePath) resolves against the rewritten req.url under the Nest ExpressAdapter and 404s spuriously (files-download already works around the same trap), which broke every plugin frame document. And helmet's CORP: same-origin made the browser drop the opaque-origin frame's own script/style subresources, so a multi-file plugin client could never boot. Serve root-relative and mark frame responses cross-origin — sandbox + per-plugin CSP stay the isolation boundary. * feat(plugins): let a plugin ship its own settings page A plugin that declares capabilities.settingsUi: true gets its client/settings.html framed as a card under Settings -> Plugins — same opaque-origin sandbox and postMessage bridge as its widget, sized via trek:resize. Hosts that predate the flag strip it at install, so old instances keep working and simply don't show the card. * feat(map): open maps framed on their places (builds on #1393) (#1556) * fix(map): fit MapLibre routes reliably * fix(map): default planner map to world view * fix(map): only await route geometry when a route is actually pending The fit armed a pending route-refit slot on every fitKey change, even with no route drawn, and only ever cleared it when a route arrived. So a route toggled on much later — after the user had panned elsewhere — was mistaken for the awaited geometry and yanked the camera back, and only on the first toggle. Arm the slot only when a route is already on screen: updateRouteForDay lays down straight lines in the same batch as the fit and upgrades them to real geometry a moment later, so an empty route at fit time means none is coming. * fix(collections): open the empty collection map on the world view A collection with no mappable places centred on Paris, the same hardcoded default this branch removes everywhere else. * feat(map): open the map framed on its places A trip in Japan opened on the world view at 0,0 and only then animated a fitBounds flight across the planet — the hardcoded default was the map's answer to a question its own places already answer. Each renderer now derives its opening camera from the places it receives, at construction: MapView for Leaflet, MapViewGL for MapLibre and Mapbox (whose zoom runs one level below Leaflet's, measuring against a 512px world tile rather than 256px). Doing it at construction is what confines it to load — the map is built once, and by then the trip's places are in hand. Nothing recomputes it afterwards, so the camera stays where the user leaves it, and the opening fit stands down rather than overruling the gentler zoom a lone place opens at. A trip with no coordinates still falls back to the world view. Collections and the public shared-trip page frame themselves the same way. * refactor(settings): drop the default map centre and zoom Nothing reads them now that every map frames itself on its own places, and a home-city default was the wrong answer for the next trip on the other side of the world. The style preview keeps a fixed location of its own: it needs a city to show label density and 3D buildings, which open ocean cannot. * fix(map): frame the map the way each renderer can actually draw Two defects the unit tests missed and running the app exposed. MapLibre and Mapbox opened on Null Island at zoom 2 regardless of the places: the effect that mirrors an external centre prop onto the camera also ran on mount, so it jumped straight to the default nobody passed and threw away the camera the map had just been built with. It now only responds to actual changes, which is what it was for. Leaflet was unaffected — its controller already guarded on the centre changing. A trip spanning Sydney, Reykjavik and Santiago lost Sydney's marker entirely. The narrowest arc containing all three crosses the antimeridian, and framing there is only sound on a renderer that repeats the world: MapLibre and Mapbox draw a marker on whichever copy is nearest the camera, Leaflet draws one world and puts the marker at its absolute position — off-screen. Leaflet now spans the long way round, as L.latLngBounds would. The test that should have caught this wrapped the x-offset in its own projection helper, quietly assuming behaviour Leaflet does not have; it now models each renderer's real wrapping. --------- Co-authored-by: Azalea <noreply@aza.moe> * feat(mcp): expose public transit planning tools (#1558) * feat(mcp): add public transit planning tools * refactor(transit): reuse local time conversion * fix(mcp): harden transit journey validation * refactor(transit): centralize itinerary processing * fix(mcp): return the transit itineraries the provider actually offers search_transit_routes validated each itinerary leg's mode against SCHEDULED_TRANSIT_MODES, but that constant is the request-side filter whitelist — the modes a caller may ask for — not the modes MOTIS can return. Its default TRANSIT mode expands to TRAM,FERRY,AIRPLANE,BUS,COACH,RAIL,ODM, RIDE_SHARING,FUNICULAR,AERIAL_LIFT,OTHER, and street legs can be BIKE/CAR/ RENTAL. Any itinerary carrying one of those failed the parse and was dropped by the flatMap, so the tool reported fewer routes than exist — or none at all. Against the live provider, Trondheim → Ålesund returns 5 itineraries and 3 of them contain an AIRPLANE leg, so the tool silently discarded them; the web app shows all 5, because it treats mode as a free string and renders anything non-WALK as a transit leg. Accept any mode token on a leg and keep the existing "at least one non-WALK leg" rule as the real gate, which restores parity with the web app. Everything downstream keeps its mode !== 'WALK' semantics, so a journey created over MCP is identical to one created in the app. Dropping an itinerary is still possible when provider data fails the remaining consistency rules, but it is indistinguishable from "no routes exist" — so search_transit_routes now reports a `dropped` count alongside the results. --------- Co-authored-by: Uzini <43294422+Uziniii@users.noreply.github.com> * fix: show map poi search controls on mobile (#1555) * fix(pdf): use the trip's actual currency instead of hardcoded EUR (#1519) * fix(pdf): use the trip's actual currency instead of hardcoded EUR Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * fix(i18n): drop hardcoded currency text from pdf.costLabel across locales Remove redundant EUR/currency references from pdf.costLabel translations across 21 locales now that the PDF export correctly renders amounts with their actual trip currency via formatMoney(). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * fix(pdf): drop hardcoded euro-shaped icon from place price chip svgEuro rendered a fixed € glyph next to the price chip regardless of the trip's actual currency, undermining the currency fix. Swap for a currency-neutral coin icon. --------- Co-authored-by: Nguyen Trong Binh <nguytb15@VN1N07HO1CD1015.local> Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com> * fix(trips): pin place prices when the trip currency changes A place price with no currency of its own means "the trip's own currency" — that is how the PDF export and the place chips read it since #1519. But rebaseTripCurrency() only pinned budget_items and budget_settlements, so switching a trip's currency silently redenominated every implicit place price: a €15 museum on a trip moved to JPY started reading as ¥15. Same class of mismatch as #1543, on the places surface. Pin priced, currency-less places to the outgoing currency inside the same transaction. No amount is rewritten — the figure the user typed keeps its real-world value, it just stops being ambiguous about which unit it is in. Bump updated_at as well: it doubles as the optimistic-concurrency token (#1135), so a client holding the pre-switch row can no longer write the pin away. Document place prices in the wiki's currency model, and drop the now-stale "in EUR" from the PDF export's estimated-cost stat. * fix(budget): re-split expenses when a member is removed * fix(plugins): derive plugin req.user.isAdmin from role, not is_admin * chore(test): make jsdom Storage work under Node's native Web Storage globals * fix: recompute vacay calendar when week start changes (#1554) * fix(websocket): handle socket 'error' events to prevent crash on malformed frames (#1584) * fix(packing): apply templates into the active list tab (#1581) * Fix packing list readability on mobile * Localize packing quantity label in overflow menu * fix(atlas): stream boundary GeoJSON instead of caching parsed bundles (#1585) * fix(atlas): stream boundary GeoJSON instead of caching parsed bundles * fix(atlas): scan admin1 features in one pass to avoid O(n^2) build createFeatureSplitter re-scanned each partial Feature from the start on every gunzip chunk, so a large feature (Canada ~5.5MB, ~340 chunks) made the one-time admin1 store build O(n^2). That pushed the streaming build (~4.2s) past the 15s test timeout under CI coverage/fork contention and added the same latency to the first live region request. Carry scan state (position, brace depth, string state) across chunks so each character is examined once. Output is byte-identical (3228 features, 197 countries) and peak build memory is unchanged (~192MB RSS under a hard 512MB cap); build time drops to ~1.7s. * fix(i18n): add packing.quantity to all locales The packing.quantity key existed only in en (Qty) and de (Menge), so i18n:parity:strict and the client parity test failed for the other 20 locales. Add the key everywhere; en/de are unchanged. --------- Co-authored-by: jubnl <jgunther021@gmail.com> * fix(trips): keep accommodations on their dates when the trip range shifts (#1288) The v3.1.3 fix re-anchored dated bookings after a trip date change but explicitly excluded hotels: day_accommodations has no absolute date columns, so stays remained glued to positionally re-dated day rows and shifted with the range. updateTrip now snapshots day dates before generateDays and a new resyncAccommodationDays re-anchors each stay (and its linked hotel reservation, restamping its stale reservation_time) to the days holding its pre-change dates; out-of-range stays stay glued so whole-trip moves still shift together. Unlinked dated hotels resync like any booking, and the date-change block is wrapped in a transaction. Changing the start date now also asks how plans should follow via a new date_shift_mode field ('keep_bookings' default / 'shift_all', which reuses the reorder/insert restamp path to glue everything), exposed in the trip edit modal (all 22 locales), the shared contract, and the MCP update_trip tool. Clients no longer show stale state: the initiator reloads reservations + accommodations after saving, collaborators refetch on a date-changing trip:updated, and reconnect hydration nudges the planner's accommodations too. * fix(extract): retry with json_object and surface AI import failures (#1546) OpenAI-compatible providers that only support json_object (DeepSeek, Mistral, some vLLM/llama.cpp) reject the json_schema response_format with a 400, and the resulting error was swallowed silently: not logged server-side and never rendered by the background-task widget, leaving only a generic "no reservations" message. - Retry the chat/completions request once with response_format json_object when the json_schema attempt returns 400 (non-NuExtract only); the system prompt already dictates the output shape - Log swallowed llm-parse errors with an [llm-parse] tag so failures show up in server logs - Render task warnings under the empty-preview note in the background tasks widget so the actual provider error reaches the user * fix(costs): keep ticket item amounts visible on narrow screens (#1568) * chore: update repo url * chore: update repo url * chore: update repo url * chore: update repo url * fix(security): block IPv6 transition addresses (NAT64/6to4/Teredo) in SSRF guard An attacker-controlled DNS record pointing at a NAT64 (64:ff9b::/96), 6to4 (2002::/16), or Teredo (2001:0000::/32) address that embeds a private IPv4 (e.g. 64:ff9b::a9fe:a9fe = 169.254.169.254) bypassed the SSRF guard: none of the guard functions recognised these ranges, so on a host that routes the transition prefix the connection reached the embedded private target (cloud metadata / internal SSRF). Add a shared embeddedTransitionIpv4() detector and re-apply each guard's own blocklist to the extracted IPv4 in isAlwaysBlocked, isPrivateNetwork, isLinkLocal (ssrfGuard.ts) and isBlockedIp (egress-policy.ts). A transition address to a public IPv4 stays allowed so legitimate IPv6-only egress is unaffected. egress-policy.ts keeps the detector inline to preserve its dependency-free contract for the isolated plugin subprocess. * chore: Add star history * Revert "chore: Add star history" This reverts commitf9d5f75837. * fix(map): draw transit routes even without other places on the day The reservation overlays hide any transport whose from/to endpoints project closer than a per-type pixel threshold (200px for transit) to declutter tiny no-op straight connectors. A transit journey, though, draws its real rail/bus alignment rather than a straight endpoint line, so on a zoomed-out day — one with no other places to tighten the map onto — its stations fall under the threshold and the whole route vanishes. Exempt a transit booking that carries real per-leg geometry from the proximity gate in both renderers (Leaflet + MapLibre); a geometry-less transit keeps the straight-arc declutter. * fix(atlas): resolve region AND country by coordinates against the bundled polygons Rebased onto dev's streaming atlas index (#1576): region resolution now resolves a place's lat/lng directly against the same bundled admin1 polygons the client renders — offline, deterministic, and guaranteed to match a bundle feature — rather than trusting Nominatim's address level, which can name a subdivision the bundle doesn't carry (Barcelona's ES-B province vs the bundle's ES-CT autonomous community) and never highlight. Country resolution moves to the same coordinates-first order, so a place stored "..., San Francisco, CA" no longer resolves to Canada. admin1 is held as per-country GeoJSON text (never parsed whole, #1576), so a country's regions are flattened to the compact Float64Array form and cached on first use — only visited countries pay the parse. The stale GB constituent-country rescue is removed, and a one-time migration clears the re-derivable place_regions cache so every place re-resolves under the new logic. Closes #1547 * fix(client): convert mixed-currency day/trip cost totals instead of mislabeling raw sums (#1561) Day headers, the plan sidebar footer and the PDF day/cover totals summed raw place prices across currencies and labeled the result with a single currency — a $2,730.27 hotel on a NOK trip read as "2730 NOK". Totals now convert every amount into a base currency via the existing frankfurter rates (sidebar: the user's display currency, falling back to the trip's; PDF: the trip currency, resolved once before rendering so the document is consistent), marked with "≈" when a conversion happened. When a rate is unavailable (offline, blocked egress, unknown code) they fall back to an honest per-currency breakdown ("2 500 kr + $2,730.27") instead of folding foreign amounts into a mislabeled number. All-same-currency trips make no FX request, so offline PDF export keeps working. Also swaps the place inspector's hardcoded € chip icon for a neutral one and formats the price via formatMoney in the place's own currency. Note: day-header totals move from "50 EUR" to Intl formatting ("50 €"). * feat(atlas): let a visited region be hidden, cascading to the country when none remain (server) Countries already have a hide/tombstone mechanism (hidden_countries, #1490): a zero-count derived country can be dismissed and stays gone across reloads. Regions had no equivalent — unmarkRegionVisited only ever deleted a manually-marked visited_regions row, a no-op for the common case of a region derived fresh from place_regions on every request, so there was no way to dismiss one at all (place-derived or otherwise). Adds the region-level counterpart: - New hidden_regions table (user_id, region_code, country_code), mirroring hidden_countries. - getVisitedRegions() filters its result through it, the same way getStats() already filters through getHiddenCountries(). - unmarkRegionVisited() now tombstones unconditionally (not just for a manually-marked region — a region with a real place attached, e.g. one misassigned by a border-simplification gap, is exactly the case this exists for) and derives the country code from the region code's "<country>-<rest>" prefix when there's no visited_regions row to read it from. - Cascade: after hiding a region, if the country has no other visible region left (checked against place_regions + visited_regions, minus hidden_regions), the country is hidden too via the existing unmarkCountryVisited. - markRegionVisited() clears both tombstones on re-mark, so a region (and its cascade-hidden country) can come back. Note the cascade only has a visible effect on a country with no real place attached to it — getStats' places-derived country entries are never suppressed by hidden_countries (#1490's deliberate "reappears with a real place" rule), so hiding every region of a country that DOES have real places leaves the country visible, by the same existing design. Test coverage reflects this. Server-side only — client wiring (a way to trigger this from the map) is a separate commit. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * feat(atlas): let a visited region be hidden, cascading to the country when none remain (client) Client wiring for the server-side hide-region feature (previous commit). Clicking a visited region on the map used to open the hide/unmark confirmation only when it was manually marked (visitedRegions[...].manuallyMarked); a region derived from real place data instead opened the country-detail view, with no way to dismiss it at all. Now any visited region offers the same "Remove this region from your visited list?" confirmation regardless of how it was derived — country details remain reachable via the country search/sidebar, which was never gated on this in the first place. The confirm handler's optimistic country-removal check dropped its `&& r.manuallyMarked` filter on the remaining-regions count, matching the server's unconditional cascade — but keeps the existing "only when the country has zero real places/trips" guard, since a country backed by real data is never actually hidden server-side (#1490) and removing it from the UI early would just flash and reappear on the next reload. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * fix(settings): make fresh-instance unit defaults internally consistent A brand-new instance — no admin-set defaults, no saved value — rendered temperatures in Fahrenheit and times on the 12-hour clock while distances defaulted to metric, a mix that matches no locale. The store also seeded 'fahrenheit'/'12h' while DisplaySettingsTab's fallback said 'celsius', so the two paths disagreed about the intended default in the first place. Default to one system — celsius / metric / 24h — matching the already-metric distance_unit. The unit defaults now live in a single exported DEFAULT_SETTINGS that both the store and DisplaySettingsTab's fallback read, so they can't drift apart again. Admin-set user defaults (getAdminUserDefaults) and any value a user has already saved still take precedence; only the code-level default changed. * feat(i18n): complete Catalan (ca) translation Adds Catalan as a supported language — the full shared/src/i18n/ca locale (all domain files plus the notification texts), registered in SUPPORTED_LANGUAGES and the client locale loader. Rebuilt onto current dev so the locale is at full key parity with en (i18n:parity:strict clean). * fix(map): stop real road-route fetches from dying under StrictMode useTransportRoutes cached its AbortController in a ref that was created once and aborted on unmount. React StrictMode's dev-only mount->cleanup->remount cycle ran that abort during the *simulated* cleanup, permanently poisoning the controller before the real mount's fetch ever started — every road-routed booking (car/bus/taxi/bicycle) silently fell back to a straight line in local dev, while production builds (no StrictMode double-invoke) worked fine. Fix: create a fresh AbortController per effect run instead of a ref-cached singleton, and synchronously un-mark a job as "attempted" in that same run's cleanup if it didn't settle before the cleanup fired — so a StrictMode remount (or any other pre-completion cancellation) retries instead of being skipped forever. Verified against the real OSRM endpoint in a running dev server: all four road-routed legs on a live trip now resolve with real road geometry instead of straight lines. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * feat(map): add reservation route-visibility util Extracts the route-visibility filter that was hand-copied, identically, in both MapView.tsx and MapViewGL.tsx into one pure, unit-tested function: a reservation's route shows on the map when it's a transit booking with the day-route toggle on, or its id is in the caller's visible-ids set. isRoutableReservation (>= 2 endpoints) is exported separately since callers besides the map filter need the same check. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * feat(map): add per-trip connections-visibility resolution util Pure storage/resolution logic for a trip's booking-route visibility preference, keyed trek:visible-connections:<tripId>. Two modes: 'only' (nothing shown except the listed ids — today's existing behavior; a legacy bare-array localStorage value parses as this mode for backward compatibility) and 'all-except' (everything routable shown except the listed ids). A trip with no stored preference falls back to the account-wide default (all or nothing) without writing anything, so flipping the account setting later never silently overrides a trip with an explicit per-trip choice already recorded. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * feat(settings): add always-show-booking-routes account setting New map_always_show_routes account setting, defaulting to off, i18n'd across all 22 supported locales. Lives in Display > Travel & map, directly under Booking route labels — its closest sibling — using that section's immediate-save On/Off pattern rather than a separate toggle+Save flow, since it's a booking-display preference, not a map render-config option. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * feat(map): per-trip booking-route visibility with account default and bulk toggle Lets a user see a booking's route on the map without manually toggling it per item, two ways: - The account setting from the previous commit sets the default for any trip that's never had its routes touched before. - A new bulk "show all / hide all" button in the day-plan toolbar flips a trip explicitly between the two connectionsVisibility modes, independent of the per-item toggle (which still edits whichever mode's id list is active, in both directions, including while the account default is on). useTripPlanner.ts resolves a trip's effective visible-connection ids from connectionsVisibility.ts + the account setting + the trip's routable reservations, and exposes it through the same visibleConnections/toggleConnection contract MapView, MapViewGL and DayPlanSidebar already had, plus allConnectionsShown/ toggleAllConnections for the new bulk control. MapView/MapViewGL consume it via the shared reservationRoutes util instead of each carrying their own copy of the filter. The bulk toggle's tooltip gets its own map.showAllConnections/ hideAllConnections i18n keys (all 22 locales) distinct from the per-item toggle's text, and matches the per-item toggle's active (solid blue) styling rather than the toolbar's generic hover tint. Manually verified end-to-end in a running dev server: the account default seeding an untouched trip, the bulk toggle flipping a trip between all-shown/all-hidden, and a single per-leg override while the trip is in all-shown mode. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * Update documentation for booking visibility change * fix(i18n): add Catalan keys for the booking-route toggle + fix the language-count test #1483 added map.showAllConnections/hideAllConnections and settings.alwaysShowRoutes/Hint to every locale that existed when it was written; Catalan (#1418) landed just after and was missing them, which broke i18n parity. Also bumps the SUPPORTED_LANGUAGES test to 23 entries and asserts the Catalan one — the ca addition left that assertion stale. * test(e2e): add a reproducible documentation screenshot run The wiki screenshots had drifted three months and two releases behind the UI: 39 of 46 assets came from a single commit in April, and pages such as Budget-Tracking carry a disclaimer that their own images are out of date. Retaking them by hand is what created that drift in the first place. This adds a `screenshots` Playwright project that captures them from a dev build instead: - seed.ts populates a demo trip over the REST API — deliberately in JPY, so the 3.4.0 currency work (per-trip currency, frozen FX rates, foreign-currency settle-up) is actually visible rather than hidden behind EUR. - shot.ts settles the page before capturing (fonts, images, transitions) so captures don't catch skeleton loaders, and rewrites /auth/app-config to clear dev_mode — the E2E backend runs NODE_ENV=development, which would otherwise put a "Dev: Notifications" tab no real deployment has into every admin shot. - promote.mjs downscales 2880px captures to 1600px on the way into wiki/assets/, which is 70% smaller for detail the wiki never renders. Tabs are located by their visible label, so a rename like Budget → Costs fails the run loudly instead of quietly capturing the wrong panel. npm run shots && npm run shots:promote * docs(wiki): retake screenshots against 3.4.0 Regenerated with `npm run shots` from the dev build. Replaces 21 assets and adds 13 surfaces that had no screenshot at all. Notable corrections: - Collections.md referenced assets/Collections.png, which was never committed — the only broken image in the wiki. It now exists. - The Budget panel became Costs in 3.3.0 (#1464); every budget image still showed the old label. - The trip-create dialog gained a Currency field in 3.4.0, absent from the old TripCreate.png. - Settings grew a Plugins tab and the admin sidebar a Plugins entry; neither appeared in the old sidebar shots. - Weather now renders in Celsius. A fresh instance defaults to Fahrenheit while distance defaults to metric, so the seed pins both units — the mismatched defaults are a separate bug, not fixed here. Koffi is installed from the community registry rather than dev-linked, because dev-link and sideload both stamp a badge on the plugin card that an ordinary install never shows. Total 3.6 MB for 34 images, against 26 MB for the 46 assets already in the directory. No wiki page text is touched here — pages still point at the old filenames where those were kept, and the newly added images are not referenced yet. * fix(help): make wiki links and anchors work in the in-app reader The wiki pages are written in GitHub-wiki style, and 455 of their links across 81 pages use the bare relative form — `[Currencies](Currencies)` — against only 114 `[[..]]` links. processMarkdown only rewrote the latter, so in-app every one of those 455 fell through to HelpPage's external-link branch, opened a new tab and 404'd. Since6c87bf2fserves the wiki from disk, that is the primary way users read these docs. Rewriting them in the renderer fixes every page at once and keeps the sources GitHub-compatible, so contributors can keep writing either form and neither target breaks. Rewriting the 81 files instead would have fixed today's pages and left the trap open for tomorrow's. Also: - Code is protected from the rewrite. Plugin-Development.md documents `actions[key](ctx)`, which reads as a markdown link and would otherwise be corrupted into `actions[key](/help/ctx)` inside a verbatim snippet. - `[[Page#anchor|Slug]]` no longer renders its anchor as visible link text. - Headings carry GitHub-compatible ids, so the 22 in-page `](#anchor)` links scroll instead of doing nothing. * docs(wiki): correct settings, map and addon docs against 3.4.0 The wiki described settings that no longer exist and pointed at UI labels that had been renamed. Each correction below was checked against the code. - The Settings tab is labelled **General**, not "Display" (shared/src/i18n/en/settings.ts:6). Every "Settings → Display" path was wrong. The *display currency* setting keeps its name — only the tab was renamed. - Colour mode is on the **Appearance** tab, not Display. - The "Route calculation" setting does not exist: no hits for route_calc / routeCalc / auto_route / calculateRoutes anywhere in client or server. - Default map centre and zoom were removed in 3.4.0 (0f4766e1). Replaced with what actually happens now, written from client/src/utils/mapViewport.ts: every map frames itself on its own places, world view when a trip has no coordinates. - A third map provider, MapLibre GL / OpenFreeMap, was undocumented. It needs no access token, which is the reason a reader would choose it over Mapbox. - Budget-Tracking.md said the feature is called Costs everywhere and then told the reader to open the "Budget" tab. The screenshot disclaimer is gone too — the images now show Costs. - The admin tab table was missing Plugins. - The `packing` addon is seeded as "Lists", not "Packing list management". - Install docs pinned `mauriceboe/TREK:3.0.15` as the exact-release example, four minor versions stale. * docs(wiki): document passkeys, calendar feeds, appearance, plugins and help Five shipped features had no user documentation at all: - **Passkeys** — WebAuthn enrolment and sign-in, admin policy, RP ID/origins. Previously mentioned only in passing in Environment-Variables. - **Calendar Feeds** — the subscribable per-trip and per-user ICS feeds. Note Day-Plans-and-Notes documents only the one-off .ics *export*; the two are cross-referenced so it is clear which is which. - **Appearance Settings** — the whole tab, including the custom accent colour and its contrast check. - **Admin: Plugins** — installing from the registry, the pre-install permission review, egress hosts, and what Reviewed/Signed/Unsigned actually guarantee. - **In-App Help** — that the wiki ships in the image and is served from disk since 3.4.0, with the GitHub fallback and TREK_WIKI_DIR. One deliberate deviation from the brief: the Appearance settings are documented as account-level, not per-device. They persist to /api/settings on the user account with nothing in localStorage, so the dashboard widget picker's desktop/mobile split still changes both from either device. All five are listed in _Sidebar.md. * docs(wiki): add screenshots for the remaining surfaces Second capture pass, bringing the run to 42 screenshots. Adds the surfaces that need more than a navigation to reach: collection and journey detail, MCP access, two-factor setup, the settle-up payment dialog, and the trip file manager. Two fixes to the harness itself, both of which had produced misleading images: - The admin captures showed a "Dev: Notifications" tab that only exists when the server runs NODE_ENV=development. The run now clears dev_mode in the /auth/app-config response; switching the server to production instead would have enabled HSTS and broken the run over http://localhost. - The settle-up capture clicked "Settle up", which does not open a view — it records the transfers. It zeroed every balance and photographed "Everyone's square", and because the specs share one database it poisoned Costs.png in the same run. Screenshot specs must not mutate state; it now captures the "Add payment" dialog instead. Koffi is installed from the community registry rather than dev-linked, since dev-link and sideload both badge the plugin card in a way no ordinary install does. * test(e2e): capture the detail pages and dialogs Adds the second wave of screenshot specs (collection/journey detail, MCP access, 2FA, settle-up dialog, files) and enables the mcp, documents and collab addons in the seed so their surfaces render instead of 404ing. * docs(wiki): point plugin authors at the agent skill and the registry Plugin-Development jumped straight into scaffolding without saying that two supporting resources exist. TREK-Plugins was referenced only in passing far down the page, and Plugin-Skill — an agent skill that teaches Claude Code and other SKILL.md-compatible agents to build and publish a plugin — was not mentioned anywhere in the wiki. Both are called out up front, with a note that neither is required: the registry only matters once you want other instances to find your plugin. * test(e2e): capture the four collab surfaces separately One Collab.png illustrated chat, notes, polls and the What's Next widget, so at most one of those four wiki pages showed the feature it described. Each now has its own capture. Two things the collab seed needed: - The conversation is posted by three different people. Every collab write is attributed to the acting user, and a single-voice chat log would misrepresent the feature outright. - Each member therefore gets its OWN request context, created with an explicit `storageState: undefined`. Without that, newContext inherits the project's storageState — the admin's trek_session cookie — and extractToken reads the cookie BEFORE the Authorization header (server/src/middleware/auth.ts:9). The posts still return 200; they are just all recorded as the admin. That is exactly what happened on the first attempt, and the DB was the only place it showed. The collab view is not tabbed — CollabPanel renders all panels at once — so the captures target cards by seeded content rather than clicking tabs or matching headings, whose DOM text is 'Notes'/'Polls' while CSS renders them uppercase. * docs(wiki): show every screenshot on the page it belongs to Finishes the wiring the screenshot commits deliberately left out. - Embeds the 14 images that were committed but displayed nowhere: the Costs panel and settle-up dialog, the trip planner, transports, documents, collection and journey detail, the notifications inbox, the Offline and Account settings tabs, appearance, admin user defaults, registration and password reset. - Splits the four collab pages onto their own images. Chat, Notes, Polls and What's Next each showed the same Collab.png until now; the overview shot moves to Real-Time-Collaboration, which had no image at all. - Day-Plans-and-Notes pointed at TripPlaner.png — one 'n'. It now uses the correctly spelled file, and the misspelled one is deleted since nothing else referenced it. - Removes 45 dead '<!-- TODO: screenshot -->' markers whose screenshot had long since been added. 9 remain, each on a page that genuinely still lacks the image it asks for — so the marker means something again and the gap is greppable, which is how this drifted unnoticed for three months. Every asset in wiki/assets/ is now referenced by a page, and every image reference resolves to a file. * docs(wiki): add the four collab screenshots Chat now shows a real three-person conversation rather than one voice talking to itself, and the poll shows three separate votes across two options. 44 images, 4.6 MB total. * test(help): point the asset test at the correctly spelled screenshot The integration test hard-coded assets/TripPlaner.png — one 'n' — so deleting the misspelled file broke it. It was the only thing keeping that filename alive. * docs(wiki): regenerate the screenshots on top of the rebased devba3733dachanged the fresh-instance defaults to celsius/metric/24h. Every capture showing a clock — chat timestamps, bookings, day plans — and the General settings tab itself were still on the 12-hour clock, so 39 of 44 images needed a new run. Regenerating them is one command, which is the point. The seed keeps pinning the units explicitly: it now matches the new defaults, but stating them keeps the captures reproducible if a default moves again. * docs(wiki): regenerate screenshots after rebasing onto dev dev added a Catalan translation, an always-show-booking-routes account setting and a bulk route toggle in the day-plan toolbar since the last run — all visible on captures we ship. 15 of 44 images changed. Also resolves the Map-Features conflict from41d12e89: upstream's new bulk-options section is kept, with the two 'Settings → Display' paths corrected to 'General'. The tab is labelled General (shared/src/i18n/en/settings.ts:6), and upstream's own i18n key for that section is settings.general.travelMap. * chore: only allow manual trigger for the build&push --------- Co-authored-by: Maurice <61554723+mauriceboe@users.noreply.github.com> Co-authored-by: Dieter Blomme <dieterblomme@gmail.com> Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com> Co-authored-by: sld272 <zjrdmczh@outlook.com> Co-authored-by: Nguyen Trong Binh <nguytb15@VN1N07HO1CD1015.local> Co-authored-by: Maurice <mauriceboe@icloud.com> Co-authored-by: Pavel Zolotarevskiy <code@fxgn.dev> Co-authored-by: Azalea <noreply@aza.moe> Co-authored-by: Uzini <43294422+Uziniii@users.noreply.github.com> Co-authored-by: Daniel <drmoreno271@gmail.com> Co-authored-by: trongbinhnguyen <43725147+trongbinh15@users.noreply.github.com> Co-authored-by: Konstantinos Thermos <info@subdee.org> Co-authored-by: Konstantinos Thermos <subdee@users.noreply.github.com> Co-authored-by: Lucas Español <lucas.espanol@tutanota.com> Co-authored-by: fbnlrz <frlrnzn@gmail.com>
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* Assemble a CheckContext from a plugin directory: read each file ONCE, hand the same
|
||||
* strings to every check. Checks stay pure functions of this object, which is what makes
|
||||
* them table-testable without a temp dir.
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { CheckContext, RegistryEntry } from './types.js';
|
||||
|
||||
function readIfPresent(p: string): string | undefined {
|
||||
try {
|
||||
return fs.readFileSync(p, 'utf8');
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export function loadContext(
|
||||
dir: string,
|
||||
extra: { zipBytes?: Buffer; entry?: RegistryEntry } = {},
|
||||
): CheckContext {
|
||||
const root = path.resolve(dir);
|
||||
|
||||
let manifest: Record<string, unknown> | undefined;
|
||||
let manifestError: string | undefined;
|
||||
const manifestRaw = readIfPresent(path.join(root, 'trek-plugin.json'));
|
||||
if (manifestRaw === undefined) {
|
||||
manifestError = `no trek-plugin.json in ${dir}`;
|
||||
} else {
|
||||
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 parsed: unknown = JSON.parse(text);
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
||||
manifestError = 'trek-plugin.json is not a JSON object';
|
||||
} else {
|
||||
manifest = parsed as Record<string, unknown>;
|
||||
}
|
||||
} catch (e) {
|
||||
manifestError = 'trek-plugin.json is not valid JSON: ' + (e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
dir: root,
|
||||
manifest,
|
||||
manifestError,
|
||||
readme: readIfPresent(path.join(root, 'README.md')),
|
||||
clientHtml: readIfPresent(path.join(root, 'client', 'index.html')),
|
||||
exists: (rel: string) => fs.existsSync(path.join(root, rel)),
|
||||
zipBytes: extra.zipBytes,
|
||||
entry: extra.entry,
|
||||
};
|
||||
}
|
||||
|
||||
/** 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),
|
||||
...over,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* The check registry's public face: one list, run at the depth the caller can afford.
|
||||
*
|
||||
* runOffline(ctx) — `status`, `validate`, and `publish`'s first step. No network, no push.
|
||||
* SYNCHRONOUS, which is what keeps `packPluginDir` (it validates before it
|
||||
* zips) from having to become async and dragging publish/release with it.
|
||||
* runAll(ctx) — `preflight` and `publish`: the offline set PLUS the handful of things
|
||||
* that genuinely need GitHub.
|
||||
*
|
||||
* Nothing here decides how to PRINT a report — that is ./report.ts, so that `status` (a
|
||||
* checklist you read) and `validate` (an exit code a script reads) can render the same
|
||||
* outcomes differently without either owning the rules.
|
||||
*/
|
||||
import { OFFLINE_CHECKS } from './offline.js';
|
||||
import { NETWORK_CHECKS } from './network.js';
|
||||
import type { Check, CheckContext, CheckOutcome, CheckReport, CheckResult } from './types.js';
|
||||
import { summarize } from './types.js';
|
||||
|
||||
export const ALL_CHECKS: Check[] = [...OFFLINE_CHECKS, ...NETWORK_CHECKS];
|
||||
|
||||
/**
|
||||
* A check that throws is a bug in the CHECK, not a verdict on the plugin. Report it as a failure
|
||||
* rather than letting it crash the command: an author who cannot run `status` at all is strictly
|
||||
* worse off than one who sees "this check is broken".
|
||||
*/
|
||||
function threw(e: unknown): CheckResult {
|
||||
return { status: 'fail', detail: 'check threw: ' + (e instanceof Error ? e.message : String(e)) };
|
||||
}
|
||||
|
||||
const outcome = (check: Check, result: CheckResult): CheckOutcome => ({
|
||||
id: check.id,
|
||||
stage: check.stage,
|
||||
severity: check.severity,
|
||||
// Most gates are the REGISTRY's, not the loader's — they stop you publishing, not building.
|
||||
// Only the handful that make a plugin unloadable opt into 'artifact'.
|
||||
blocks: check.blocks ?? 'publish',
|
||||
title: check.title,
|
||||
...result,
|
||||
});
|
||||
|
||||
/** Every gate that is a pure function of the working tree. */
|
||||
export function runOffline(ctx: CheckContext): CheckReport {
|
||||
return summarize(
|
||||
OFFLINE_CHECKS.map((check) => {
|
||||
try {
|
||||
return outcome(check, check.run(ctx));
|
||||
} catch (e) {
|
||||
return outcome(check, threw(e));
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** The offline set plus the network gates. Requires ctx.entry for the network half to do anything. */
|
||||
export async function runAll(ctx: CheckContext): Promise<CheckReport> {
|
||||
const outcomes: CheckOutcome[] = runOffline(ctx).outcomes;
|
||||
for (const check of NETWORK_CHECKS) {
|
||||
try {
|
||||
outcomes.push(outcome(check, await check.run(ctx)));
|
||||
} catch (e) {
|
||||
outcomes.push(outcome(check, threw(e)));
|
||||
}
|
||||
}
|
||||
return summarize(outcomes);
|
||||
}
|
||||
|
||||
export { OFFLINE_CHECKS } from './offline.js';
|
||||
export { NETWORK_CHECKS, DEFAULT_REGISTRY } from './network.js';
|
||||
export * from './types.js';
|
||||
export { loadContext, makeContext } from './context.js';
|
||||
export { renderChecklist, renderPlain, summaryLine, nextStep } from './report.js';
|
||||
@@ -0,0 +1,386 @@
|
||||
/**
|
||||
* The four things that genuinely cannot be known from the working tree.
|
||||
*
|
||||
* Everything else the registry enforces lives in ./offline.ts and fires before you have pushed
|
||||
* anything. What is left here needs GitHub or the registry repo to answer:
|
||||
*
|
||||
* 1. does the tag exist, and does it point at the commit the entry pins?
|
||||
* 2. do the released artifact's bytes hash to the sha256 the entry pins — and do they verify
|
||||
* against the author's key?
|
||||
* 3. is this plugin id already bound to a different GitHub owner?
|
||||
* 4. was this plugin published SIGNED before, and is this update about to drop or rotate the key?
|
||||
*
|
||||
* (3) and (4) are new. The registry has always enforced them and `preflight` never did, which
|
||||
* made a green preflight a promise it could not keep: a signing downgrade merges nowhere and
|
||||
* BRICKS THE UPDATE for every instance that already has the plugin, and the author would only
|
||||
* find out at review. See scripts/validate-entry.mjs, "signing-downgrade guard".
|
||||
*
|
||||
* The manifest and README are ALSO re-graded here, at the pinned commit rather than in the tree.
|
||||
* That is not redundant with the offline pass: an author who fills the README in and forgets to
|
||||
* commit it has a green tree and a red tag, and the tag is what CI grades.
|
||||
*/
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { listZipNames } from '../../zip.js';
|
||||
import { verifyAuthorSignature, checkSignatureShape, SignatureError } from '../verify-signature.js';
|
||||
import type { NetworkCheck, CheckContext, RegistryEntry, RegistryEntryVersion } from './types.js';
|
||||
import { pass, fail, skip } from './types.js';
|
||||
import { REQUIRED_SECTIONS, MIN_PROSE_CHARS, missingSections, placeholders, proseLength, images, undocumentedPermissions } from './readme.js';
|
||||
|
||||
export const DEFAULT_REGISTRY = 'liketrek/TREK-Plugins';
|
||||
|
||||
const NATIVE_RE = /(^|\/)[^/]+\.node$|(^|\/)binding\.gyp$|(^|\/)prebuilds?\//i;
|
||||
|
||||
/** A GitHub token lifts the anonymous API rate limit. `gh` already has one; borrow it. */
|
||||
function ghToken(): string | undefined {
|
||||
if (process.env.GITHUB_TOKEN) return process.env.GITHUB_TOKEN;
|
||||
try {
|
||||
return execFileSync('gh', ['auth', 'token'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim() || undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function ghHeaders(): Record<string, string> {
|
||||
const h: Record<string, string> = { 'User-Agent': 'trek-plugin-preflight', Accept: 'application/vnd.github+json' };
|
||||
const t = ghToken();
|
||||
if (t) h.Authorization = `Bearer ${t}`;
|
||||
return h;
|
||||
}
|
||||
|
||||
const rawUrl = (repo: string, sha: string, p: string): string =>
|
||||
`https://raw.githubusercontent.com/${repo}/${sha}/${p.replace(/^\.?\//, '')}`;
|
||||
|
||||
/** The versions a network check grades: the newest by default, all of them with --all. */
|
||||
function targetVersions(c: CheckContext): RegistryEntryVersion[] {
|
||||
const vs = c.entry?.versions ?? [];
|
||||
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> {
|
||||
try {
|
||||
const r = await fetch(url, { headers });
|
||||
return r.ok ? await r.text() : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ── 1. the tag resolves to the pinned commit ────────────────────────────────────
|
||||
|
||||
const tagResolves: NetworkCheck = {
|
||||
id: 'network.tag-resolves',
|
||||
stage: 'release',
|
||||
depth: 'network',
|
||||
severity: 'error',
|
||||
title: 'Git tag exists and points at the pinned commit',
|
||||
run: async (c) => {
|
||||
if (!c.entry) return skip();
|
||||
const problems: string[] = [];
|
||||
for (const v of targetVersions(c)) {
|
||||
try {
|
||||
const r = await fetch(
|
||||
`https://api.github.com/repos/${c.entry.repo}/git/refs/tags/${encodeURIComponent(v.gitTag)}`,
|
||||
{ headers: ghHeaders() },
|
||||
);
|
||||
if (!r.ok) {
|
||||
problems.push(`• ${v.version}: tag ${v.gitTag} not found on ${c.entry.repo} (${r.status}) — push the tag and cut the release`);
|
||||
continue;
|
||||
}
|
||||
const ref = (await r.json()) as { object?: { sha?: string; type?: string } };
|
||||
let sha = ref.object?.sha;
|
||||
// An annotated tag's ref points at the TAG object, not the commit — deref it, or every
|
||||
// annotated tag looks like a mismatch.
|
||||
if (ref.object?.type === 'tag' && sha) {
|
||||
const tr = await fetch(`https://api.github.com/repos/${c.entry.repo}/git/tags/${sha}`, { headers: ghHeaders() });
|
||||
if (tr.ok) sha = ((await tr.json()) as { object?: { sha?: string } }).object?.sha;
|
||||
}
|
||||
if (sha && sha !== v.commitSha) {
|
||||
problems.push(`• ${v.version}: tag ${v.gitTag} points at ${sha.slice(0, 8)}, entry pins ${v.commitSha.slice(0, 8)}`);
|
||||
}
|
||||
} catch (e) {
|
||||
problems.push(`• ${v.version}: tag check failed: ${(e as Error).message}`);
|
||||
}
|
||||
}
|
||||
return problems.length ? fail(`${problems.length} problem(s)`, problems.join('\n')) : pass();
|
||||
},
|
||||
};
|
||||
|
||||
// ── 2. the manifest at the pinned commit matches the entry ──────────────────────
|
||||
|
||||
const manifestAtCommit: NetworkCheck = {
|
||||
id: 'network.manifest-at-commit',
|
||||
stage: 'release',
|
||||
depth: 'network',
|
||||
severity: 'error',
|
||||
title: 'Manifest at the pinned commit matches the entry',
|
||||
run: async (c) => {
|
||||
if (!c.entry) return skip();
|
||||
const problems: string[] = [];
|
||||
for (const v of targetVersions(c)) {
|
||||
const text = await fetchText(rawUrl(c.entry.repo, v.commitSha, 'trek-plugin.json'));
|
||||
if (text === null) {
|
||||
problems.push(`• ${v.version}: trek-plugin.json not found at ${v.commitSha.slice(0, 8)} — did you push your code?`);
|
||||
continue;
|
||||
}
|
||||
let m: Record<string, unknown>;
|
||||
try {
|
||||
m = JSON.parse(text) as Record<string, unknown>;
|
||||
} catch (e) {
|
||||
problems.push(`• ${v.version}: trek-plugin.json at ${v.commitSha.slice(0, 8)} is not valid JSON: ${(e as Error).message}`);
|
||||
continue;
|
||||
}
|
||||
const p = (msg: string) => problems.push(`• ${v.version}: ${msg}`);
|
||||
if (m.id !== c.entry.id) p(`manifest id "${String(m.id)}" != entry id "${c.entry.id}"`);
|
||||
if (m.version !== v.version) p(`manifest version "${String(m.version)}" != entry "${v.version}"`);
|
||||
if (m.type !== c.entry.type) p(`manifest type "${String(m.type)}" != entry "${c.entry.type}"`);
|
||||
const mApi = typeof m.apiVersion === 'number' ? m.apiVersion : 1;
|
||||
if (mApi !== v.apiVersion) p(`manifest apiVersion ${mApi} != entry ${v.apiVersion}`);
|
||||
if (m.nativeModules === true) p('manifest declares nativeModules:true (forbidden in v1)');
|
||||
if (typeof m.trek === 'string' && m.trek.trim() !== v.trek) p(`manifest trek "${m.trek.trim()}" != entry trek "${v.trek}"`);
|
||||
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() : []);
|
||||
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() : []);
|
||||
if (JSON.stringify(normDeps(m.pluginDependencies)) !== JSON.stringify(normDeps(v.pluginDependencies))) {
|
||||
p('manifest pluginDependencies != entry pluginDependencies');
|
||||
}
|
||||
}
|
||||
return problems.length ? fail(`${problems.length} problem(s)`, problems.join('\n')) : pass();
|
||||
},
|
||||
};
|
||||
|
||||
// ── 3. the released artifact ────────────────────────────────────────────────────
|
||||
|
||||
const artifactMatches: NetworkCheck = {
|
||||
id: 'network.artifact',
|
||||
stage: 'release',
|
||||
depth: 'network',
|
||||
severity: 'error',
|
||||
title: 'Released artifact downloads, hashes and verifies',
|
||||
run: async (c) => {
|
||||
if (!c.entry) return skip();
|
||||
const problems: string[] = [];
|
||||
for (const v of targetVersions(c)) {
|
||||
let bytes: Buffer;
|
||||
try {
|
||||
const r = await fetch(v.downloadUrl, { redirect: 'follow', headers: { 'User-Agent': 'trek-plugin-preflight' } });
|
||||
if (!r.ok) {
|
||||
problems.push(`• ${v.version}: artifact download failed (${r.status}) ${v.downloadUrl}`);
|
||||
continue;
|
||||
}
|
||||
bytes = Buffer.from(await r.arrayBuffer());
|
||||
} catch (e) {
|
||||
problems.push(`• ${v.version}: artifact download failed: ${(e as Error).message}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
// 4096B of slack mirrors the registry: GitHub can pad a release asset slightly.
|
||||
if (bytes.length > v.size + 4096) problems.push(`• ${v.version}: artifact is ${bytes.length}B, entry declares ${v.size}B`);
|
||||
const sha = createHash('sha256').update(bytes).digest('hex');
|
||||
if (sha !== v.sha256) {
|
||||
problems.push(
|
||||
`• ${v.version}: sha256 mismatch — the release has ${sha.slice(0, 12)}…, the entry pins ${v.sha256.slice(0, 12)}…\n` +
|
||||
' (did you re-pack after building the entry? the entry must be built from the EXACT bytes you uploaded)',
|
||||
);
|
||||
}
|
||||
|
||||
// The signature proves the bytes came from the AUTHOR's key; the sha256 only proves they
|
||||
// are what the registry vouches for. TREK verifies this again at install and aborts on a
|
||||
// mismatch, so a bad signature merged here is an entry nobody can install.
|
||||
if (v.signature && c.entry.authorPublicKey) {
|
||||
try {
|
||||
if (!verifyAuthorSignature(bytes, v.signature, c.entry.authorPublicKey)) {
|
||||
problems.push(`• ${v.version}: author signature does not verify — signed with a different key, or re-packed after signing?`);
|
||||
}
|
||||
} catch (e) {
|
||||
if (e instanceof SignatureError) problems.push(`• ${v.version}: signature/key is malformed: ${e.message}`);
|
||||
else throw e;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const names = bytes[0] === 0x50 && bytes[1] === 0x4b ? listZipNames(bytes) : [];
|
||||
if (names.some((n) => NATIVE_RE.test(n))) {
|
||||
problems.push(`• ${v.version}: artifact contains native binaries (.node / binding.gyp / prebuilds) — forbidden in v1`);
|
||||
}
|
||||
} catch {
|
||||
/* not a zip we can read — the sha check above already speaks to the bytes */
|
||||
}
|
||||
}
|
||||
return problems.length ? fail(`${problems.length} problem(s)`, problems.join('\n')) : pass();
|
||||
},
|
||||
};
|
||||
|
||||
// ── 4. the README at the pinned commit ──────────────────────────────────────────
|
||||
|
||||
const readmeAtCommit: NetworkCheck = {
|
||||
id: 'network.readme-at-commit',
|
||||
stage: 'release',
|
||||
depth: 'network',
|
||||
severity: 'error',
|
||||
title: 'README at the pinned commit passes the registry gate',
|
||||
run: async (c) => {
|
||||
if (!c.entry) return skip();
|
||||
const v = c.entry.versions[0];
|
||||
if (!v) return skip();
|
||||
|
||||
const md = await fetchText(rawUrl(c.entry.repo, v.commitSha, 'README.md'));
|
||||
if (md === null) {
|
||||
return fail(
|
||||
`README.md not found at ${v.commitSha.slice(0, 8)}`,
|
||||
'The registry reads the README at the COMMIT, not from your working tree. Commit and push it.',
|
||||
);
|
||||
}
|
||||
|
||||
const problems: string[] = [];
|
||||
for (const s of missingSections(md)) problems.push(`• missing required section "## ${s}"`);
|
||||
for (const p of placeholders(md)) problems.push(`• template placeholder still present: "${p}"`);
|
||||
const n = proseLength(md);
|
||||
if (n < MIN_PROSE_CHARS) problems.push(`• only ${n}/${MIN_PROSE_CHARS} chars of prose`);
|
||||
|
||||
// Resolve every image against the pinned commit. A relative path that exists in your tree
|
||||
// but was never committed 404s here — which is exactly the failure this catches.
|
||||
const imgs = images(md);
|
||||
if (!imgs.length) problems.push('• no screenshot (the registry requires at least one real image)');
|
||||
else {
|
||||
let anyOk = false;
|
||||
const reasons: string[] = [];
|
||||
for (const src of imgs) {
|
||||
const url = /^https?:\/\//.test(src)
|
||||
? src.includes('github.com') && src.includes('/blob/')
|
||||
? src.replace('github.com', 'raw.githubusercontent.com').replace('/blob/', '/')
|
||||
: src
|
||||
: rawUrl(c.entry.repo, v.commitSha, src);
|
||||
try {
|
||||
const r = await fetch(url, { headers: { 'User-Agent': 'trek-plugin-preflight', Range: 'bytes=0-2047' } });
|
||||
const ct = r.headers.get('content-type') || '';
|
||||
if (r.ok && ct.startsWith('image/')) {
|
||||
anyOk = true;
|
||||
break;
|
||||
}
|
||||
reasons.push(`${src} → ${r.status} ${ct || 'no content-type'}`);
|
||||
} catch {
|
||||
reasons.push(`${src} → unreachable`);
|
||||
}
|
||||
}
|
||||
if (!anyOk) problems.push('• no screenshot resolved to a real image:\n ' + reasons.join('\n '));
|
||||
}
|
||||
|
||||
// Permission parity, against the manifest AT THE COMMIT (not the tree — they can differ).
|
||||
const manifestText = await fetchText(rawUrl(c.entry.repo, v.commitSha, 'trek-plugin.json'));
|
||||
if (manifestText) {
|
||||
try {
|
||||
const m = JSON.parse(manifestText) as { permissions?: unknown };
|
||||
const perms = Array.isArray(m.permissions) ? m.permissions.map(String) : [];
|
||||
const undoc = undocumentedPermissions(md, perms);
|
||||
if (undoc.length) problems.push(`• permissions not explained in the README: ${undoc.join(', ')}`);
|
||||
} catch {
|
||||
/* manifest-at-commit already reports a broken manifest */
|
||||
}
|
||||
}
|
||||
|
||||
return problems.length
|
||||
? fail(
|
||||
`${problems.length} problem(s) at ${v.commitSha.slice(0, 8)}`,
|
||||
problems.join('\n') +
|
||||
`\nThese are graded at the pinned commit. If your working tree looks fine, you have uncommitted changes —\ncommit, push, and re-tag.\nRequired sections: ${REQUIRED_SECTIONS.map((s) => `## ${s}`).join(', ')}.`,
|
||||
)
|
||||
: pass();
|
||||
},
|
||||
};
|
||||
|
||||
// ── 5. owner binding (NEW — the registry has always enforced this) ───────────────
|
||||
|
||||
const ownerBinding: NetworkCheck = {
|
||||
id: 'network.owner-binding',
|
||||
stage: 'release',
|
||||
depth: 'network',
|
||||
severity: 'error',
|
||||
title: 'Plugin id is not bound to another GitHub owner',
|
||||
run: async (c) => {
|
||||
if (!c.entry) return skip();
|
||||
const registry = c.registry ?? DEFAULT_REGISTRY;
|
||||
const text = await fetchText(rawUrl(registry, 'main', 'OWNERS.json'));
|
||||
if (text === null) return skip('could not read OWNERS.json — the registry will still check this');
|
||||
let owners: { plugins?: Record<string, { boundOwner?: string }> };
|
||||
try {
|
||||
owners = JSON.parse(text) as typeof owners;
|
||||
} catch {
|
||||
return skip('OWNERS.json is unreadable — the registry will still check this');
|
||||
}
|
||||
const bound = owners.plugins?.[c.entry.id]?.boundOwner;
|
||||
if (!bound) return pass('unclaimed id — it binds to you on merge');
|
||||
const mine = c.entry.repo.split('/')[0];
|
||||
return bound === mine
|
||||
? pass(`bound to ${bound}`)
|
||||
: fail(
|
||||
`"${c.entry.id}" is bound to "${bound}", your repo is "${mine}"`,
|
||||
'The registry binds a plugin id to the GitHub owner who first published it, so nobody can hijack an id.\n' +
|
||||
'Either pick a different id, or ask a maintainer for the allow-owner-change label if this is a genuine transfer.',
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
// ── 6. signing-downgrade guard (NEW — a green here used to hide a bricked update) ─
|
||||
|
||||
const signingDowngrade: NetworkCheck = {
|
||||
id: 'network.signing-downgrade',
|
||||
stage: 'release',
|
||||
depth: 'network',
|
||||
severity: 'error',
|
||||
title: 'Update does not drop or rotate a published signing key',
|
||||
run: async (c) => {
|
||||
if (!c.entry) return skip();
|
||||
const registry = c.registry ?? DEFAULT_REGISTRY;
|
||||
const text = await fetchText(rawUrl(registry, 'main', `registry/plugins/${c.entry.id}.json`));
|
||||
if (text === null) return pass('not published yet — nothing to downgrade from');
|
||||
let published: RegistryEntry;
|
||||
try {
|
||||
published = JSON.parse(text) as RegistryEntry;
|
||||
} catch {
|
||||
return skip('published entry is unreadable');
|
||||
}
|
||||
if (!published.authorPublicKey) return pass('previously published unsigned');
|
||||
|
||||
// TREK pins the author key on FIRST INSTALL (trust on first use). Once a plugin has shipped
|
||||
// signed, an unsigned update — or one signed with a different key — is REFUSED on every
|
||||
// instance that already has it. Merging that would not just fail; it would strand every
|
||||
// existing user on the version they have.
|
||||
const problems: string[] = [];
|
||||
if (!c.entry.authorPublicKey) {
|
||||
problems.push(
|
||||
'• this plugin was published SIGNED, but this entry has no authorPublicKey.\n' +
|
||||
' TREK refuses an unsigned update to a signed plugin — it would break the update for every existing install.\n' +
|
||||
' Sign it: pass --sign (your key should be at ~/.trek-plugin/signing.key).',
|
||||
);
|
||||
} else if (c.entry.authorPublicKey !== published.authorPublicKey) {
|
||||
problems.push(
|
||||
'• this entry changes authorPublicKey. TREK refuses a key rotation until an admin re-trusts the plugin.\n' +
|
||||
' Sign with your ORIGINAL key, or ask a maintainer for the allow-key-change label.',
|
||||
);
|
||||
} else {
|
||||
// Every version must stay signed, not just the newest — TREK verifies whichever version it
|
||||
// installs, so an unsigned older block is a landmine for a pinned install.
|
||||
for (const v of c.entry.versions) {
|
||||
if (!v.signature) problems.push(`• ${v.version} has no signature, but this is a signed plugin — TREK will refuse to install it`);
|
||||
}
|
||||
}
|
||||
return problems.length ? fail(`${problems.length} problem(s)`, problems.join('\n')) : pass('signed with the published key');
|
||||
},
|
||||
};
|
||||
|
||||
/** Every network check, in the order `preflight` runs them. */
|
||||
export const NETWORK_CHECKS: NetworkCheck[] = [
|
||||
tagResolves,
|
||||
manifestAtCommit,
|
||||
artifactMatches,
|
||||
readmeAtCommit,
|
||||
ownerBinding,
|
||||
signingDowngrade,
|
||||
];
|
||||
@@ -0,0 +1,628 @@
|
||||
/**
|
||||
* Every gate that is a pure function of the working tree.
|
||||
*
|
||||
* This is most of them. See ./types.ts for why that matters: the registry grades
|
||||
* `trek-plugin.json` and `README.md` at a pinned commit, but those are the same two files
|
||||
* the author has open right now, so there is no reason to make them push a tag to find out.
|
||||
*
|
||||
* Each check answers ONE question and says what to do about it. The `fix` text is the whole
|
||||
* point — a check that reports "README invalid" and stops has told the author nothing they
|
||||
* can act on.
|
||||
*/
|
||||
import { createHash } from 'node:crypto';
|
||||
import path from 'node:path';
|
||||
import { validateManifest, isSatisfiableRange, isUnboundedRange, KNOWN_ADDONS } from '../../manifest.js';
|
||||
// The hosts a plugin can ACTUALLY reach. See `code.egress-reachable` for why this is the
|
||||
// only list that counts — and permissions.ts for why dev's egress guard uses the same one.
|
||||
import { grantedHosts } from '../../permissions.js';
|
||||
import { LUCIDE_ICON_NAMES } from '../../lucide-icon-names.js';
|
||||
import { listZipNames } from '../../zip.js';
|
||||
import { checkSignatureShape } from '../verify-signature.js';
|
||||
import type { OfflineCheck, CheckContext } from './types.js';
|
||||
import { pass, fail, skip } from './types.js';
|
||||
import {
|
||||
REQUIRED_SECTIONS,
|
||||
MIN_PROSE_CHARS,
|
||||
missingSections,
|
||||
placeholders,
|
||||
proseLength,
|
||||
images,
|
||||
undocumentedPermissions,
|
||||
} from './readme.js';
|
||||
|
||||
/** Mirrors the registry's native-binary scan (validate-entry.mjs) and the installer's. */
|
||||
const NATIVE_RE = /(^|\/)[^/]+\.node$|(^|\/)binding\.gyp$|(^|\/)prebuilds?\//i;
|
||||
|
||||
const str = (v: unknown): string => (typeof v === 'string' ? v : '');
|
||||
const arr = (v: unknown): string[] => (Array.isArray(v) ? v.map(String) : []);
|
||||
|
||||
// ── manifest ────────────────────────────────────────────────────────────────────
|
||||
|
||||
const manifestPresent: OfflineCheck = {
|
||||
id: 'manifest.present',
|
||||
blocks: 'artifact',
|
||||
stage: 'manifest',
|
||||
depth: 'offline',
|
||||
severity: 'error',
|
||||
title: 'trek-plugin.json exists and parses',
|
||||
run: (c) =>
|
||||
c.manifest
|
||||
? pass()
|
||||
: fail(
|
||||
c.manifestError ?? 'no trek-plugin.json',
|
||||
'Every plugin is rooted at a trek-plugin.json manifest. Scaffold one rather than writing it by hand.',
|
||||
'trek-plugin create',
|
||||
),
|
||||
};
|
||||
|
||||
const manifestValid: OfflineCheck = {
|
||||
id: 'manifest.valid',
|
||||
blocks: 'artifact',
|
||||
stage: 'manifest',
|
||||
depth: 'offline',
|
||||
severity: 'error',
|
||||
title: 'Manifest passes the same rules the TREK installer applies',
|
||||
run: (c) => {
|
||||
if (!c.manifest) return skip();
|
||||
const r = validateManifest(c.manifest);
|
||||
if (r.ok) return pass();
|
||||
return fail(
|
||||
`${r.errors.length} problem${r.errors.length === 1 ? '' : 's'}`,
|
||||
r.errors.map((e) => '• ' + e).join('\n'),
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
const manifestIdMatchesDir: OfflineCheck = {
|
||||
id: 'manifest.id-matches-dir',
|
||||
stage: 'manifest',
|
||||
depth: 'offline',
|
||||
severity: 'warn',
|
||||
title: 'Directory name matches the plugin id',
|
||||
run: (c) => {
|
||||
const id = str(c.manifest?.id);
|
||||
if (!id) return skip();
|
||||
const dirName = path.basename(c.dir);
|
||||
return dirName === id
|
||||
? pass()
|
||||
: fail(
|
||||
`directory is "${dirName}", id is "${id}"`,
|
||||
'Not fatal, but the registry files your entry under the id, and every doc assumes the two agree.',
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
const manifestTrekRange: OfflineCheck = {
|
||||
id: 'manifest.trek-range',
|
||||
stage: 'manifest',
|
||||
depth: 'offline',
|
||||
severity: 'warn',
|
||||
title: 'TREK version range is bounded',
|
||||
run: (c) => {
|
||||
const trek = str(c.manifest?.trek);
|
||||
// Unsatisfiable/missing is an ERROR, but manifest.valid already reports it — don't say it twice.
|
||||
if (!isSatisfiableRange(trek)) return skip();
|
||||
return isUnboundedRange(trek)
|
||||
? 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".',
|
||||
)
|
||||
: pass(trek);
|
||||
},
|
||||
};
|
||||
|
||||
const manifestIcon: OfflineCheck = {
|
||||
id: 'manifest.icon',
|
||||
stage: 'manifest',
|
||||
depth: 'offline',
|
||||
severity: 'error',
|
||||
title: 'Icon is a real lucide name',
|
||||
run: (c) => {
|
||||
if (!c.manifest) return skip();
|
||||
const icon = str(c.manifest.icon);
|
||||
// Absent is LEGAL — TREK falls back to Blocks and CI accepts it. But every plugin without
|
||||
// an icon is the same grey square in the store, so say so. Warn-shaped, reported as a pass
|
||||
// with a caveat rather than a failure, because refusing to publish over it would be absurd.
|
||||
if (!icon) return pass('none — TREK will show the generic Blocks glyph');
|
||||
return LUCIDE_ICON_NAMES.has(icon)
|
||||
? pass(icon)
|
||||
: fail(
|
||||
`"${icon}" is not a lucide icon`,
|
||||
'TREK resolves the icon against lucide at render time and silently falls back to Blocks, so a typo is\n' +
|
||||
'invisible locally — but the registry rejects it. Pick a name from https://lucide.dev/icons (PascalCase).',
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* The registry entry's schema, applied to the manifest fields it is built from.
|
||||
*
|
||||
* These are cheap string-length rules, and every one of them is a gate that today fails in CI
|
||||
* — AFTER the release is immutable — because nothing local looks at them. `entry.ts` copies
|
||||
* `description` straight out of the manifest and defaults it to `""`, which trips the schema's
|
||||
* minLength of 5 with an error that names the ENTRY, not the manifest that caused it.
|
||||
*/
|
||||
const manifestEntryFields: OfflineCheck = {
|
||||
id: 'manifest.entry-fields',
|
||||
stage: 'manifest',
|
||||
depth: 'offline',
|
||||
severity: 'error',
|
||||
title: 'name/description/author fit the registry schema',
|
||||
run: (c) => {
|
||||
if (!c.manifest) return skip();
|
||||
const problems: string[] = [];
|
||||
const name = str(c.manifest.name);
|
||||
const description = str(c.manifest.description);
|
||||
const author = str(c.manifest.author);
|
||||
|
||||
if (name && (name.length < 2 || name.length > 60)) problems.push(`• name is ${name.length} chars (registry allows 2–60)`);
|
||||
if (!description) problems.push('• description is missing — the registry requires one (5–200 chars); it is your store-card subtitle');
|
||||
else if (description.length < 5) problems.push(`• description is ${description.length} chars (registry requires at least 5)`);
|
||||
else if (description.length > 200) problems.push(`• description is ${description.length} chars (registry allows at most 200)`);
|
||||
if (!author) problems.push('• author is missing — the entry would be published as "Unknown"');
|
||||
else if (author.length > 80) problems.push(`• author is ${author.length} chars (registry allows at most 80)`);
|
||||
|
||||
// Reject a name that mixes Latin with Cyrillic/Greek look-alikes — the registry treats this
|
||||
// as a spoofing attempt (a plugin that looks like someone else's in the store).
|
||||
if (name && /[A-Za-z]/.test(name) && /[Ѐ-ӿͰ-Ͽ]/.test(name)) {
|
||||
problems.push(`• name "${name}" mixes Latin with Cyrillic/Greek characters — the registry reads that as a homoglyph spoof`);
|
||||
}
|
||||
|
||||
// `tags` and `homepage` are copied VERBATIM out of the manifest into the entry (entry.ts),
|
||||
// and the registry's JSON schema validates both. Nothing local looked at either, so a tag with
|
||||
// a capital or a space — the obvious thing to write — produced an entry CI rejected, after the
|
||||
// release was cut and its bytes pinned.
|
||||
const tags = Array.isArray(c.manifest.tags) ? c.manifest.tags.map(String) : [];
|
||||
for (const t of tags) {
|
||||
if (!/^[a-z0-9-]{2,24}$/.test(t)) {
|
||||
problems.push(`• tag "${t}" is not a lowercase slug of 2–24 chars (the registry's schema rejects it)`);
|
||||
}
|
||||
}
|
||||
if (tags.length > 8) problems.push(`• ${tags.length} tags — the registry allows at most 8`);
|
||||
|
||||
const homepage = str(c.manifest.homepage);
|
||||
if (homepage) {
|
||||
try {
|
||||
// The schema demands format:uri, which in practice means an absolute URL.
|
||||
const u = new URL(homepage);
|
||||
if (!u.protocol) throw new Error('no protocol');
|
||||
} catch {
|
||||
problems.push(`• homepage "${homepage}" is not an absolute URL (the registry's schema requires one, e.g. https://…)`);
|
||||
}
|
||||
}
|
||||
|
||||
return problems.length
|
||||
? fail(`${problems.length} problem${problems.length === 1 ? '' : 's'}`, problems.join('\n'))
|
||||
: pass();
|
||||
},
|
||||
};
|
||||
|
||||
const manifestAddonsKnown: OfflineCheck = {
|
||||
id: 'manifest.addons-known',
|
||||
stage: 'manifest',
|
||||
depth: 'offline',
|
||||
severity: 'warn',
|
||||
title: 'requiredAddons are addons TREK has',
|
||||
run: (c) => {
|
||||
const addons = arr(c.manifest?.requiredAddons);
|
||||
if (!addons.length) return skip();
|
||||
const unknown = addons.filter((a) => !KNOWN_ADDONS.includes(a));
|
||||
return unknown.length
|
||||
? fail(
|
||||
unknown.join(', '),
|
||||
`Not necessarily wrong — you may be targeting a newer TREK than this SDK knows about — but an addon\nTREK does not have can never be enabled, so the plugin would never activate. Known: ${KNOWN_ADDONS.join(', ')}.`,
|
||||
)
|
||||
: pass(addons.join(', '));
|
||||
},
|
||||
};
|
||||
|
||||
const manifestNoEmoji: OfflineCheck = {
|
||||
id: 'manifest.no-emoji',
|
||||
stage: 'manifest',
|
||||
depth: 'offline',
|
||||
severity: 'warn',
|
||||
title: 'No emojis in name/description',
|
||||
run: (c) => {
|
||||
if (!c.manifest) return skip();
|
||||
const EMOJI_RE = /[\p{Extended_Pictographic}\u{1F1E6}-\u{1F1FF}]/u;
|
||||
const hit = EMOJI_RE.test(str(c.manifest.name)) || EMOJI_RE.test(str(c.manifest.description));
|
||||
return hit
|
||||
? fail(
|
||||
'name/description contains emojis',
|
||||
'TREK renders with lucide icons and STRIPS emojis from plugin-rendered text and notifications, so they\n' +
|
||||
'simply vanish at render. Use the `icon` field with a lucide name instead.',
|
||||
)
|
||||
: pass();
|
||||
},
|
||||
};
|
||||
|
||||
// ── code ────────────────────────────────────────────────────────────────────────
|
||||
|
||||
const codeServerEntry: OfflineCheck = {
|
||||
id: 'code.server-entry',
|
||||
blocks: 'artifact',
|
||||
stage: 'code',
|
||||
depth: 'offline',
|
||||
severity: 'error',
|
||||
title: 'server/index.js exists',
|
||||
run: (c) =>
|
||||
c.exists('server/index.js')
|
||||
? pass()
|
||||
: fail(
|
||||
'server/index.js is missing',
|
||||
'Every plugin — even a pure-UI one — is loaded from server/index.js via definePlugin(). If you build from\nTypeScript, build before packing.',
|
||||
),
|
||||
};
|
||||
|
||||
/**
|
||||
* The egress trap, and the reason this check exists at all.
|
||||
*
|
||||
* The manifest has TWO places that look like they control network access, and only one of them
|
||||
* does. `spawnActivated` (server plugin-runtime.service.ts) builds the child's allow-list purely
|
||||
* from `http:outbound:<host>` PERMISSIONS, and the iframe CSP's connect-src comes from the same
|
||||
* place. The manifest's `egress[]` array is never read at runtime at all — it is a declaration
|
||||
* for the consent screen.
|
||||
*
|
||||
* So a plugin with `egress: ["api.example.com"]` and permission `http:outbound` — no host suffix
|
||||
* — installs, activates, consents, and is then SILENTLY BLOCKED from the one host it exists to
|
||||
* call. Nothing in the manifest validator, the packer or the registry catches it. The author
|
||||
* finds out from a production timeout.
|
||||
*/
|
||||
const codeEgressReachable: OfflineCheck = {
|
||||
id: 'code.egress-reachable',
|
||||
stage: 'code',
|
||||
depth: 'offline',
|
||||
severity: 'error',
|
||||
title: 'Every egress host has a matching http:outbound:<host> permission',
|
||||
run: (c) => {
|
||||
if (!c.manifest) return skip();
|
||||
const egress = arr(c.manifest.egress);
|
||||
const permissions = arr(c.manifest.permissions);
|
||||
if (!egress.length) return skip();
|
||||
|
||||
const granted = grantedHosts(permissions);
|
||||
const unreachable = egress.filter((h) => !granted.includes(h));
|
||||
if (!unreachable.length) return pass(`${egress.length} host${egress.length === 1 ? '' : 's'}`);
|
||||
|
||||
return fail(
|
||||
unreachable.join(', '),
|
||||
'TREK opens the network guard and the iframe CSP from the `http:outbound:<host>` PERMISSIONS only — it never\n' +
|
||||
'reads egress[]. These hosts are declared but unreachable: the plugin will install, activate, and then have\n' +
|
||||
'every request to them silently blocked.\n' +
|
||||
'Add to permissions: ' + unreachable.map((h) => `"http:outbound:${h}"`).join(', '),
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
const codeEgressDeclared: OfflineCheck = {
|
||||
id: 'code.egress-declared',
|
||||
stage: 'code',
|
||||
depth: 'offline',
|
||||
severity: 'warn',
|
||||
title: 'Every reachable host is declared in egress[]',
|
||||
run: (c) => {
|
||||
if (!c.manifest) return skip();
|
||||
const egress = arr(c.manifest.egress);
|
||||
const granted = grantedHosts(arr(c.manifest.permissions));
|
||||
if (!granted.length) return skip();
|
||||
const undeclared = granted.filter((h) => !egress.includes(h));
|
||||
return undeclared.length
|
||||
? fail(
|
||||
undeclared.join(', '),
|
||||
'These hosts are reachable (you granted http:outbound:<host>) but absent from egress[]. egress[] is what the\n' +
|
||||
'admin sees on the consent screen, so the plugin is understating its own network reach. Add them to egress[].',
|
||||
)
|
||||
: pass();
|
||||
},
|
||||
};
|
||||
|
||||
const codeDesignKit: OfflineCheck = {
|
||||
id: 'code.design-kit',
|
||||
stage: 'code',
|
||||
depth: 'offline',
|
||||
severity: 'warn',
|
||||
title: 'Client UI inlines the TREK design kit',
|
||||
run: (c) => {
|
||||
if (!c.clientHtml) return skip();
|
||||
const rawSelect = /<select(?![^>]*\bdata-trek-native\b)(\s|>)/i.test(c.clientHtml);
|
||||
const usesKit = c.clientHtml.includes('<!-- trek:ui -->') || c.clientHtml.includes('data-trek-ui');
|
||||
return rawSelect && !usesKit
|
||||
? fail(
|
||||
'a raw <select> with no design kit',
|
||||
'Native dropdowns are drawn by the OS and cannot match TREK. Add the <!-- trek:ui --> marker so selects are\n' +
|
||||
'auto-styled, or mark a field data-trek-native to opt out on purpose.',
|
||||
)
|
||||
: pass();
|
||||
},
|
||||
};
|
||||
|
||||
// ── docs ────────────────────────────────────────────────────────────────────────
|
||||
// The stage where nearly every first publish dies. All four of these are registry gates.
|
||||
|
||||
const docsReadmePresent: OfflineCheck = {
|
||||
id: 'docs.readme-present',
|
||||
stage: 'docs',
|
||||
depth: 'offline',
|
||||
severity: 'error',
|
||||
title: 'README.md exists',
|
||||
run: (c) => (c.readme === undefined ? fail('README.md is missing', 'The registry requires one at the repo root.') : pass()),
|
||||
};
|
||||
|
||||
const docsReadmeSections: OfflineCheck = {
|
||||
id: 'docs.readme-sections',
|
||||
stage: 'docs',
|
||||
depth: 'offline',
|
||||
severity: 'error',
|
||||
title: 'README has all four required sections',
|
||||
run: (c) => {
|
||||
if (c.readme === undefined) return skip();
|
||||
const missing = missingSections(c.readme);
|
||||
return missing.length
|
||||
? fail(
|
||||
`missing ${missing.map((s) => `"## ${s}"`).join(', ')}`,
|
||||
`The registry requires exactly these four headings: ${REQUIRED_SECTIONS.map((s) => `## ${s}`).join(', ')}.`,
|
||||
)
|
||||
: pass();
|
||||
},
|
||||
};
|
||||
|
||||
const docsReadmePlaceholders: OfflineCheck = {
|
||||
id: 'docs.readme-placeholders',
|
||||
stage: 'docs',
|
||||
depth: 'offline',
|
||||
severity: 'error',
|
||||
title: 'README has no template placeholders left',
|
||||
run: (c) => {
|
||||
if (c.readme === undefined) return skip();
|
||||
const hits = placeholders(c.readme);
|
||||
return hits.length
|
||||
? fail(
|
||||
hits.map((h) => `"${h}"`).join(', '),
|
||||
'This is scaffold text you have not replaced yet. The registry rejects it — it is the signal that a README\nwas never actually written.',
|
||||
)
|
||||
: pass();
|
||||
},
|
||||
};
|
||||
|
||||
const docsReadmeProse: OfflineCheck = {
|
||||
id: 'docs.readme-prose',
|
||||
stage: 'docs',
|
||||
depth: 'offline',
|
||||
severity: 'error',
|
||||
title: 'README has enough written content',
|
||||
run: (c) => {
|
||||
if (c.readme === undefined) return skip();
|
||||
const n = proseLength(c.readme);
|
||||
return n < MIN_PROSE_CHARS
|
||||
? fail(
|
||||
`${n}/${MIN_PROSE_CHARS} chars of prose`,
|
||||
'Headings, tables, code blocks, links and images do not count — the registry strips them and measures what is\n' +
|
||||
'left. It has to be sentences: what the plugin does, why someone would install it, how to set it up.',
|
||||
)
|
||||
: pass(`${n} chars`);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* A screenshot that RESOLVES.
|
||||
*
|
||||
* The old check regexed the README for an image *link* and passed if it found one. The scaffold
|
||||
* writes `` and never creates docs/ — so the old check passed
|
||||
* on a link to a file that does not exist, and the author learned the truth from CI, after the
|
||||
* release was immutable. Resolve the path on disk instead.
|
||||
*/
|
||||
const docsScreenshot: OfflineCheck = {
|
||||
id: 'docs.screenshot',
|
||||
stage: 'docs',
|
||||
depth: 'offline',
|
||||
severity: 'error',
|
||||
title: 'README screenshot resolves to a real image',
|
||||
run: (c) => {
|
||||
if (c.readme === undefined) return skip();
|
||||
const imgs = images(c.readme);
|
||||
if (!imgs.length) {
|
||||
return fail(
|
||||
'no images in the README',
|
||||
'The store card shows this image, and the registry rejects a plugin without one. Capture a 16:9 shot\n' +
|
||||
'(1600×900 is ideal — the card crops the edges) and commit it as docs/screenshot.png.',
|
||||
'trek-plugin shot',
|
||||
);
|
||||
}
|
||||
const remote = imgs.filter((u) => /^https?:\/\//.test(u));
|
||||
const local = imgs.filter((u) => !/^https?:\/\//.test(u));
|
||||
const resolved = local.filter((u) => c.exists(u.replace(/^\.?\//, '')));
|
||||
|
||||
if (resolved.length) return pass(resolved[0]);
|
||||
// Nothing local resolves. A remote URL might still satisfy CI, but we cannot know offline —
|
||||
// don't claim a pass we haven't earned, and don't claim a failure we can't prove.
|
||||
if (remote.length) return pass(`${remote.length} remote image(s) — preflight verifies they resolve`);
|
||||
|
||||
const missing = local.filter((u) => !c.exists(u.replace(/^\.?\//, '')));
|
||||
return fail(
|
||||
`${missing.join(', ')} ${missing.length === 1 ? 'does' : 'do'} not exist`,
|
||||
'The README links this image but the file is not there, so the store card would be a broken image and the\n' +
|
||||
'registry rejects it. Capture a 16:9 shot (1600×900 is ideal — the card crops the edges).',
|
||||
'trek-plugin shot',
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
const docsPermissionsExplained: OfflineCheck = {
|
||||
id: 'docs.permissions-explained',
|
||||
stage: 'docs',
|
||||
depth: 'offline',
|
||||
severity: 'error',
|
||||
title: 'Every permission is explained in the README',
|
||||
run: (c) => {
|
||||
if (c.readme === undefined || !c.manifest) return skip();
|
||||
const perms = arr(c.manifest.permissions);
|
||||
if (!perms.length) return skip();
|
||||
const undocumented = undocumentedPermissions(c.readme, perms);
|
||||
return undocumented.length
|
||||
? fail(
|
||||
undocumented.join(', '),
|
||||
'The registry requires every permission string you request to appear verbatim in the README, so a user\n' +
|
||||
'installing your plugin can read why you need it. Add a row per permission to the "## Permissions" table.',
|
||||
)
|
||||
: pass(`${perms.length} permission${perms.length === 1 ? '' : 's'}`);
|
||||
},
|
||||
};
|
||||
|
||||
// ── release ─────────────────────────────────────────────────────────────────────
|
||||
// These need an artifact or an entry, so they skip on the plain `status` path.
|
||||
|
||||
const releaseNoNativeBinaries: OfflineCheck = {
|
||||
id: 'release.no-native-binaries',
|
||||
blocks: 'artifact',
|
||||
stage: 'release',
|
||||
depth: 'offline',
|
||||
severity: 'error',
|
||||
title: 'Artifact contains no native binaries',
|
||||
run: (c) => {
|
||||
if (!c.zipBytes) return skip();
|
||||
let names: string[] = [];
|
||||
try {
|
||||
names = listZipNames(c.zipBytes);
|
||||
} catch {
|
||||
return fail('could not read the artifact as a zip');
|
||||
}
|
||||
const native = names.filter((n) => NATIVE_RE.test(n));
|
||||
return native.length
|
||||
? fail(
|
||||
native.slice(0, 5).join(', '),
|
||||
'Native modules (.node / binding.gyp / prebuilds) are forbidden in v1 — TREK runs plugins under Node\'s\n' +
|
||||
'permission model in a child process and cannot sandbox native code.',
|
||||
)
|
||||
: pass(`${names.length} files`);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Manifest ↔ entry parity, offline.
|
||||
*
|
||||
* The registry re-derives the manifest from the pinned commit and refuses any entry that
|
||||
* disagrees with it. When `entry.ts` builds the entry this is true by construction — but not on
|
||||
* the `--merge` or `preflight --entry <file>` paths, where the entry can be hand-edited. And it
|
||||
* was NOT true by construction until recently: buildEntry silently omitted requiredAddons and
|
||||
* pluginDependencies, so any plugin that actually used one produced an entry CI would reject.
|
||||
*/
|
||||
const releaseEntryParity: OfflineCheck = {
|
||||
id: 'release.entry-parity',
|
||||
stage: 'release',
|
||||
depth: 'offline',
|
||||
severity: 'error',
|
||||
title: 'Registry entry matches the manifest',
|
||||
run: (c) => {
|
||||
if (!c.entry || !c.manifest) return skip();
|
||||
const m = c.manifest;
|
||||
const v = c.entry.versions[0];
|
||||
if (!v) return fail('entry has no versions');
|
||||
|
||||
const problems: string[] = [];
|
||||
if (str(m.id) !== c.entry.id) problems.push(`• manifest id "${str(m.id)}" != entry id "${c.entry.id}"`);
|
||||
if (str(m.version) !== v.version) problems.push(`• manifest version "${str(m.version)}" != entry version "${v.version}"`);
|
||||
if (str(m.type) !== c.entry.type) problems.push(`• manifest type "${str(m.type)}" != entry type "${c.entry.type}"`);
|
||||
const mApi = typeof m.apiVersion === 'number' ? m.apiVersion : 1;
|
||||
if (mApi !== v.apiVersion) problems.push(`• manifest apiVersion ${mApi} != entry ${v.apiVersion}`);
|
||||
if (str(m.trek) !== v.trek) problems.push(`• manifest trek "${str(m.trek)}" != entry trek "${v.trek}"`);
|
||||
if ((m.operatorEgress === true) !== (v.operatorEgress === true)) {
|
||||
problems.push(`• manifest operatorEgress ${m.operatorEgress === true} != entry ${v.operatorEgress === true}`);
|
||||
}
|
||||
|
||||
const normAddons = (a: unknown) => [...arr(a)].sort();
|
||||
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() : []);
|
||||
if (JSON.stringify(normDeps(m.pluginDependencies)) !== JSON.stringify(normDeps(v.pluginDependencies))) {
|
||||
problems.push(`• manifest pluginDependencies [${normDeps(m.pluginDependencies)}] != entry [${normDeps(v.pluginDependencies)}]`);
|
||||
}
|
||||
|
||||
return problems.length
|
||||
? fail(
|
||||
`${problems.length} mismatch${problems.length === 1 ? '' : 'es'}`,
|
||||
problems.join('\n') +
|
||||
'\nThe registry re-reads your manifest at the pinned commit and refuses an entry that disagrees with it.',
|
||||
)
|
||||
: pass();
|
||||
},
|
||||
};
|
||||
|
||||
const releaseArtifactHash: OfflineCheck = {
|
||||
id: 'release.artifact-hash',
|
||||
stage: 'release',
|
||||
depth: 'offline',
|
||||
severity: 'error',
|
||||
title: 'Entry sha256/size match the packed artifact',
|
||||
run: (c) => {
|
||||
if (!c.zipBytes || !c.entry) return skip();
|
||||
const v = c.entry.versions[0];
|
||||
if (!v) return skip();
|
||||
const sha = createHash('sha256').update(c.zipBytes).digest('hex');
|
||||
const problems: string[] = [];
|
||||
if (sha !== v.sha256) problems.push(`• artifact sha256 ${sha.slice(0, 12)}… != entry ${v.sha256.slice(0, 12)}…`);
|
||||
if (c.zipBytes.length !== v.size) problems.push(`• artifact is ${c.zipBytes.length}B, entry declares ${v.size}B`);
|
||||
return problems.length
|
||||
? fail(
|
||||
`${problems.length} mismatch${problems.length === 1 ? '' : 'es'}`,
|
||||
problems.join('\n') + '\nThe entry was built from different bytes than the artifact on disk — re-pack, then rebuild the entry.',
|
||||
)
|
||||
: pass();
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* A key without a signature, or a signature without a key.
|
||||
*
|
||||
* Passes the registry's JSON schema — the two fields sit at different levels, so no schema can
|
||||
* relate them — and is then REFUSED by TREK at install time. A half-signed entry is dead on
|
||||
* arrival, and it is a pure function of the entry, so there is no reason to wait for the network
|
||||
* to say so.
|
||||
*/
|
||||
const releaseSignatureShape: OfflineCheck = {
|
||||
id: 'release.signature-shape',
|
||||
stage: 'release',
|
||||
depth: 'offline',
|
||||
severity: 'error',
|
||||
title: 'Signature and public key are both present or both absent',
|
||||
run: (c) => {
|
||||
if (!c.entry) return skip();
|
||||
const problems = checkSignatureShape(c.entry);
|
||||
return problems.length
|
||||
? fail(
|
||||
`${problems.length} problem${problems.length === 1 ? '' : 's'}`,
|
||||
problems.map((p) => '• ' + p).join('\n') + '\nTREK refuses to install a half-signed entry, so this one could never be installed.',
|
||||
)
|
||||
: pass(c.entry.authorPublicKey ? 'signed' : 'unsigned');
|
||||
},
|
||||
};
|
||||
|
||||
/** Every offline check, in the order `status` prints them. */
|
||||
export const OFFLINE_CHECKS: OfflineCheck[] = [
|
||||
manifestPresent,
|
||||
manifestValid,
|
||||
manifestEntryFields,
|
||||
manifestIcon,
|
||||
manifestTrekRange,
|
||||
manifestIdMatchesDir,
|
||||
manifestAddonsKnown,
|
||||
manifestNoEmoji,
|
||||
codeServerEntry,
|
||||
codeEgressReachable,
|
||||
codeEgressDeclared,
|
||||
codeDesignKit,
|
||||
docsReadmePresent,
|
||||
docsReadmeSections,
|
||||
docsReadmePlaceholders,
|
||||
docsReadmeProse,
|
||||
docsScreenshot,
|
||||
docsPermissionsExplained,
|
||||
releaseSignatureShape,
|
||||
releaseNoNativeBinaries,
|
||||
releaseEntryParity,
|
||||
releaseArtifactHash,
|
||||
];
|
||||
|
||||
export type { CheckContext };
|
||||
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* The README quality gate, as pure functions of the markdown.
|
||||
*
|
||||
* These are a LINE-FOR-LINE port of TREK-Plugins' scripts/check-readme.mjs. They live apart
|
||||
* from the checks that call them because the same gate runs twice, against two different
|
||||
* READMEs, and both must agree with CI:
|
||||
*
|
||||
* - offline, against README.md in the WORKING TREE (`status` / `validate`)
|
||||
* - over the network, against README.md at the PINNED COMMIT (`preflight`)
|
||||
*
|
||||
* The two differ more often than you would think — an author fills the README in and forgets
|
||||
* to commit it, and the tree is green while the tag CI grades is not. Keeping one implementation
|
||||
* means the offline pass can never be more lenient than the network one; only more current.
|
||||
*
|
||||
* If you change a rule here, change scripts/check-readme.mjs to match, or you have built a
|
||||
* false green. test/checks-parity.test.ts asserts the two agree.
|
||||
*/
|
||||
|
||||
/** Every section CI demands, matched case-insensitively as a substring of a heading. */
|
||||
export const REQUIRED_SECTIONS = ['What it does', 'Screenshots', 'Permissions', 'Setup'];
|
||||
|
||||
/** Template prose that means the author never edited the scaffold. */
|
||||
export const PLACEHOLDER_PATTERNS = [
|
||||
/\{\{[^}]*\}\}/,
|
||||
/\bREPLACE_ME\b/i,
|
||||
/\bDescribe (what|the)\b/i,
|
||||
/\byour-name\/trek-plugin/i,
|
||||
];
|
||||
|
||||
export const MIN_PROSE_CHARS = 400;
|
||||
|
||||
/** 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());
|
||||
return REQUIRED_SECTIONS.filter((want) => !headings.some((got) => got.includes(want.toLowerCase())));
|
||||
}
|
||||
|
||||
/** The literal placeholder strings still present, e.g. ['Describe what']. */
|
||||
export function placeholders(md: string): string[] {
|
||||
const hits: string[] = [];
|
||||
for (const re of PLACEHOLDER_PATTERNS) {
|
||||
const hit = md.match(re);
|
||||
if (hit) hits.push(hit[0]);
|
||||
}
|
||||
return hits;
|
||||
}
|
||||
|
||||
/**
|
||||
* The length of the author's actual WRITING, with everything that isn't prose stripped:
|
||||
* comments, code fences, images, links, headings, table rows, then markdown punctuation.
|
||||
*
|
||||
* This is why a scaffold can't game the 400-char floor with a big permissions table — the
|
||||
* table is stripped. It has to be sentences.
|
||||
*/
|
||||
export function proseLength(md: string): number {
|
||||
return md
|
||||
.replace(/<!--[\s\S]*?-->/g, '')
|
||||
.replace(/```[\s\S]*?```/g, '')
|
||||
.replace(/!\[[^\]]*\]\([^)]*\)/g, '')
|
||||
.replace(/\[[^\]]*\]\([^)]*\)/g, '')
|
||||
.replace(/^#{1,6}\s+.*$/gm, '')
|
||||
.replace(/^\s*\|.*$/gm, '')
|
||||
.replace(/[#>*_`|-]/g, '')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim().length;
|
||||
}
|
||||
|
||||
/** Every image src the README references — markdown and <img>, minus data: URIs (CI ignores those). */
|
||||
export function images(md: string): string[] {
|
||||
const mdImgs = [...md.matchAll(/!\[[^\]]*\]\(\s*([^)\s]+)/g)].map((m) => m[1]);
|
||||
const htmlImgs = [...md.matchAll(/<img[^>]+src\s*=\s*["']([^"']+)["']/gi)].map((m) => m[1]);
|
||||
return [...new Set([...mdImgs, ...htmlImgs])].filter((u) => !u.startsWith('data:'));
|
||||
}
|
||||
|
||||
/** Manifest permissions that are never named anywhere in the README. CI rejects these. */
|
||||
export function undocumentedPermissions(md: string, permissions: string[]): string[] {
|
||||
const lower = md.toLowerCase();
|
||||
return permissions.filter((p) => !lower.includes(p.toLowerCase()));
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
/**
|
||||
* Rendering a CheckReport for a human.
|
||||
*
|
||||
* Split from the checks themselves so the same outcomes can be a checklist you READ (`status`)
|
||||
* or an exit code a script reads (`validate`) without either owning the rules.
|
||||
*
|
||||
* The thing that actually makes this useful is `nextStep()`. A list of failures tells an author
|
||||
* what is wrong; it does not tell them what to DO, and with four things red the honest question
|
||||
* is "which one first?". So the report always ends with exactly one command.
|
||||
*/
|
||||
import { STAGES, type CheckOutcome, type CheckReport } from './types.js';
|
||||
|
||||
const GREEN = '\x1b[32m';
|
||||
const RED = '\x1b[31m';
|
||||
const YELLOW = '\x1b[33m';
|
||||
const DIM = '\x1b[2m';
|
||||
const BOLD = '\x1b[1m';
|
||||
const RESET = '\x1b[0m';
|
||||
|
||||
/** Colour only when stderr is a terminal — piped output must stay clean for scripts. */
|
||||
function colour(on: boolean) {
|
||||
const c = (code: string) => (s: string) => (on ? code + s + RESET : s);
|
||||
return { green: c(GREEN), red: c(RED), yellow: c(YELLOW), dim: c(DIM), bold: c(BOLD) };
|
||||
}
|
||||
|
||||
function glyph(o: CheckOutcome): string {
|
||||
if (o.status === 'skip') return '·';
|
||||
if (o.status === 'pass') return '✓';
|
||||
return o.severity === 'error' ? '✗' : '!';
|
||||
}
|
||||
|
||||
/**
|
||||
* The single next command.
|
||||
*
|
||||
* Preference order is deliberate: the FIRST failing error that names a command wins, and checks
|
||||
* are ordered manifest → code → docs → release, so an author is always pointed at the earliest
|
||||
* thing that is broken rather than the last. A plugin with a broken manifest and no screenshot
|
||||
* should be told to fix the manifest; telling it to take a screenshot would be busywork.
|
||||
*/
|
||||
export function nextStep(report: CheckReport): { command?: string; hint: string } {
|
||||
const firstWithCommand = report.errors.find((e) => e.next);
|
||||
if (firstWithCommand?.next) {
|
||||
return { command: firstWithCommand.next, hint: firstWithCommand.title };
|
||||
}
|
||||
const first = report.errors[0];
|
||||
if (first) {
|
||||
return { hint: `fix "${first.title}" above, then re-run \`trek-plugin status\`` };
|
||||
}
|
||||
return { command: 'trek-plugin publish --repo <owner/name> --tag v<x.y.z>', hint: 'everything checks out' };
|
||||
}
|
||||
|
||||
export interface RenderOptions {
|
||||
/** Show passing and skipped checks too. `status` does; `validate` only reports problems. */
|
||||
verbose?: boolean;
|
||||
colour?: boolean;
|
||||
}
|
||||
|
||||
/** The full checklist, grouped by stage. This is what `status` prints. */
|
||||
export function renderChecklist(report: CheckReport, opts: RenderOptions = {}): string {
|
||||
const c = colour(opts.colour ?? false);
|
||||
const lines: string[] = [];
|
||||
|
||||
for (const stage of STAGES) {
|
||||
const outcomes = report.outcomes.filter((o) => o.stage === stage.id);
|
||||
if (!outcomes.length) continue;
|
||||
// A stage where everything skipped has nothing to say (e.g. `release` before you have packed).
|
||||
const shown = opts.verbose ? outcomes : outcomes.filter((o) => o.status === 'fail');
|
||||
if (!shown.length) continue;
|
||||
|
||||
lines.push('');
|
||||
lines.push(' ' + c.bold(stage.title));
|
||||
for (const o of shown) {
|
||||
const g = glyph(o);
|
||||
const paint = o.status === 'pass' ? c.green : o.status === 'skip' ? c.dim : o.severity === 'error' ? c.red : c.yellow;
|
||||
const detail = o.detail ? c.dim(` — ${o.detail}`) : '';
|
||||
const title = o.status === 'skip' ? c.dim(o.title) : o.title;
|
||||
lines.push(` ${paint(g)} ${title}${detail}`);
|
||||
// The `fix` is the part an author can act on, so it is never hidden behind a flag.
|
||||
if (o.status === 'fail' && o.fix) {
|
||||
for (const l of o.fix.split('\n')) lines.push(' ' + c.dim(l));
|
||||
}
|
||||
}
|
||||
}
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
/** The plain one-problem-per-line form, for pipes and CI. `validate` prints this. */
|
||||
export function renderPlain(report: CheckReport): string {
|
||||
const lines: string[] = [];
|
||||
for (const w of report.warnings) {
|
||||
lines.push(`warning: ${w.title}${w.detail ? ` — ${w.detail}` : ''}`);
|
||||
if (w.fix) for (const l of w.fix.split('\n')) lines.push(' ' + l);
|
||||
}
|
||||
for (const e of report.errors) {
|
||||
lines.push(`error: ${e.title}${e.detail ? ` — ${e.detail}` : ''}`);
|
||||
if (e.fix) for (const l of e.fix.split('\n')) lines.push(' ' + l);
|
||||
}
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
/** "3 things block publishing." / "ready to publish." */
|
||||
export function summaryLine(report: CheckReport): string {
|
||||
const e = report.errors.length;
|
||||
const w = report.warnings.length;
|
||||
if (!e && !w) return 'ready to publish.';
|
||||
const parts: string[] = [];
|
||||
if (e) parts.push(`${e} thing${e === 1 ? '' : 's'} block${e === 1 ? 's' : ''} publishing`);
|
||||
if (w) parts.push(`${w} warning${w === 1 ? '' : 's'}`);
|
||||
return parts.join(', ') + '.';
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
/**
|
||||
* The check registry: every gate the TREK-Plugins registry enforces, declared ONCE.
|
||||
*
|
||||
* The problem this solves: the registry's gates are, almost all of them, functions of two
|
||||
* files that are sitting in the author's working directory (`trek-plugin.json`, `README.md`).
|
||||
* But CI reads them over the network at a pinned commit, so we used to only check them over
|
||||
* the network too — from `preflight`, which runs against a PUSHED TAG. By then the author has
|
||||
* cut an immutable GitHub release, and the registry pins its sha256. Learning there that the
|
||||
* README is 61 chars short is learning it one step too late.
|
||||
*
|
||||
* So each check declares what it NEEDS rather than where it runs:
|
||||
*
|
||||
* depth: 'offline' — a pure function of the working tree. Runs in `status`, `validate`,
|
||||
* `preflight` and as `publish`'s first step. This is most of them.
|
||||
* depth: 'network' — genuinely needs GitHub or the registry repo (a tag must resolve to a
|
||||
* commit; an artifact must download and hash). Only four are really
|
||||
* like this. They run in `preflight` and `publish`.
|
||||
*
|
||||
* One list, three depths. The contract inherited from preflight.ts still holds and now covers
|
||||
* `validate` too: A GATE THE REGISTRY HAS AND THIS FILE DOESN'T IS A FALSE GREEN, and an
|
||||
* author trusts a green. When TREK-Plugins' scripts/validate-entry.mjs or check-readme.mjs
|
||||
* grows a rule, it grows one here — test/checks-parity.test.ts is what stops the two drifting.
|
||||
*/
|
||||
|
||||
/**
|
||||
* The journey, in the order an author walks it. `status` prints its checklist grouped by
|
||||
* these, so they double as the answer to "where am I?".
|
||||
*/
|
||||
export type CheckStage = 'manifest' | 'code' | 'docs' | 'release';
|
||||
|
||||
export const STAGES: { id: CheckStage; title: string }[] = [
|
||||
{ id: 'manifest', title: 'Manifest' },
|
||||
{ id: 'code', title: 'Code' },
|
||||
{ id: 'docs', title: 'Docs' },
|
||||
{ id: 'release', title: 'Release' },
|
||||
];
|
||||
|
||||
/** What a check needs in order to run. See the file header. */
|
||||
export type CheckDepth = 'offline' | 'network';
|
||||
|
||||
/**
|
||||
* 'error' fails `validate` (and blocks `publish`). 'warn' never fails a command — it is for
|
||||
* things that are legal but almost always a mistake, where refusing would be presumptuous.
|
||||
*
|
||||
* The bar for 'error' is: THE REGISTRY WOULD REJECT THIS, or TREK WOULD REFUSE TO RUN IT.
|
||||
* Anything softer is a warn. Getting this wrong in the lenient direction is a false green,
|
||||
* which is the bug class this whole module exists to kill.
|
||||
*/
|
||||
export type CheckSeverity = 'error' | 'warn';
|
||||
|
||||
/**
|
||||
* What a failure actually STOPS YOU DOING. Severity says how bad it is; this says when it bites.
|
||||
*
|
||||
* The distinction is not academic. `pack` validates before it zips, so without this axis an
|
||||
* unwritten README would refuse to build an artifact — and packing is how you install a plugin
|
||||
* into a local TREK to try it. Blocking the dev loop on a docs gate that only matters at publish
|
||||
* time would be exactly the over-eager gatekeeping this rework exists to remove.
|
||||
*
|
||||
* 'artifact' — the plugin is broken. It cannot be built, loaded or installed. `pack` refuses.
|
||||
* 'publish' — the plugin works, but the registry would reject it. `pack` allows it; `validate`
|
||||
* and `publish` do not.
|
||||
*
|
||||
* A 'warn' never blocks anything, whatever it is tagged with.
|
||||
*/
|
||||
export type CheckBlocks = 'artifact' | 'publish';
|
||||
|
||||
export type CheckStatus = 'pass' | 'fail' | 'skip';
|
||||
|
||||
export interface CheckResult {
|
||||
status: CheckStatus;
|
||||
/** The specific, quantified finding: "61/400 chars of prose". Shown next to the title. */
|
||||
detail?: string;
|
||||
/** A human sentence: what to actually do about it. Shown indented under a failure. */
|
||||
fix?: string;
|
||||
/** The literal command that fixes this, e.g. `trek-plugin shot`. Drives "next →". */
|
||||
next?: string;
|
||||
}
|
||||
|
||||
export const pass = (detail?: string): CheckResult => ({ status: 'pass', detail });
|
||||
export const skip = (detail?: string): CheckResult => ({ status: 'skip', detail });
|
||||
export const fail = (detail: string, fix?: string, next?: string): CheckResult => ({
|
||||
status: 'fail',
|
||||
detail,
|
||||
fix,
|
||||
next,
|
||||
});
|
||||
|
||||
/**
|
||||
* Everything a check may read. Assembled once by `loadContext()` so that N checks don't do N
|
||||
* reads of the same README, and so tests can hand-build a context without touching a disk.
|
||||
*/
|
||||
export interface CheckContext {
|
||||
/** Absolute path to the plugin directory. */
|
||||
dir: string;
|
||||
/** Parsed `trek-plugin.json`, or undefined when it is missing or unparseable. */
|
||||
manifest?: Record<string, unknown>;
|
||||
/** Why the manifest is absent, when it is — "no trek-plugin.json" / a JSON parse error. */
|
||||
manifestError?: string;
|
||||
/** `README.md`, or undefined when missing. */
|
||||
readme?: string;
|
||||
/** `client/index.html`, when the plugin has one. */
|
||||
clientHtml?: string;
|
||||
/** Does a path relative to `dir` exist? The seam that lets tests fake a tree. */
|
||||
exists: (rel: string) => boolean;
|
||||
/**
|
||||
* The packed artifact's bytes. Present only on the `pack`/`publish` path — checks that
|
||||
* need it must `skip` when it is absent rather than fail, or `status` would demand a zip
|
||||
* from an author who has not packed one and has no reason to.
|
||||
*/
|
||||
zipBytes?: Buffer;
|
||||
/** The built registry entry — network checks only. */
|
||||
entry?: RegistryEntry;
|
||||
/** The registry repo to check owner binding + signing history against. Network checks only. */
|
||||
registry?: string;
|
||||
/** Check every version in the entry, not just the newest. Mirrors `preflight --all`. */
|
||||
allVersions?: boolean;
|
||||
}
|
||||
|
||||
/** The shape `entry.ts` builds and TREK-Plugins stores at registry/plugins/<id>.json. */
|
||||
export interface RegistryEntry {
|
||||
id: string;
|
||||
name: string;
|
||||
author: string;
|
||||
description: string;
|
||||
repo: string;
|
||||
type: string;
|
||||
icon?: string;
|
||||
homepage?: string;
|
||||
tags?: string[];
|
||||
authorPublicKey?: string;
|
||||
versions: RegistryEntryVersion[];
|
||||
}
|
||||
|
||||
export interface RegistryEntryVersion {
|
||||
version: string;
|
||||
gitTag: string;
|
||||
commitSha: string;
|
||||
downloadUrl: string;
|
||||
sha256: string;
|
||||
trek: string;
|
||||
size: number;
|
||||
apiVersion: number;
|
||||
nativeModules: false;
|
||||
operatorEgress?: boolean;
|
||||
signature?: string;
|
||||
publishedAt: string;
|
||||
requiredAddons?: string[];
|
||||
pluginDependencies?: { id: string; version: string }[];
|
||||
}
|
||||
|
||||
interface CheckBase {
|
||||
/** Stable dotted id, e.g. 'readme.prose'. Tests and `--only` address checks by this. */
|
||||
id: string;
|
||||
stage: CheckStage;
|
||||
severity: CheckSeverity;
|
||||
/** When a failure bites. Defaults to 'publish' — most gates are the registry's, not the loader's. */
|
||||
blocks?: CheckBlocks;
|
||||
/** Imperative and specific — it reads as a checklist line: "README has all four sections". */
|
||||
title: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* An offline check is SYNCHRONOUS, and that is enforced by the type rather than by convention.
|
||||
*
|
||||
* It buys two things. It keeps `validate` synchronous, so `packPluginDir` — which validates
|
||||
* before it zips — does not have to become async and drag `publish`/`release`/`entry` with it.
|
||||
* And it makes "this check does no IO" a thing the compiler checks: an offline check that
|
||||
* reaches for the network cannot await, so it cannot quietly become a network check.
|
||||
*/
|
||||
export interface OfflineCheck extends CheckBase {
|
||||
depth: 'offline';
|
||||
run(ctx: CheckContext): CheckResult;
|
||||
}
|
||||
|
||||
export interface NetworkCheck extends CheckBase {
|
||||
depth: 'network';
|
||||
run(ctx: CheckContext): Promise<CheckResult>;
|
||||
}
|
||||
|
||||
export type Check = OfflineCheck | NetworkCheck;
|
||||
|
||||
/** One check plus how it turned out. */
|
||||
export interface CheckOutcome extends CheckResult {
|
||||
id: string;
|
||||
stage: CheckStage;
|
||||
severity: CheckSeverity;
|
||||
blocks: CheckBlocks;
|
||||
title: string;
|
||||
}
|
||||
|
||||
export interface CheckReport {
|
||||
outcomes: CheckOutcome[];
|
||||
/** Failures of severity 'error' — these block `validate` and `publish`. */
|
||||
errors: CheckOutcome[];
|
||||
/** Failures of severity 'warn' — reported, never fatal. */
|
||||
warnings: CheckOutcome[];
|
||||
/** No errors. Warnings do not affect this. */
|
||||
ok: boolean;
|
||||
}
|
||||
|
||||
export function summarize(outcomes: CheckOutcome[]): CheckReport {
|
||||
const failed = outcomes.filter((o) => o.status === 'fail');
|
||||
const errors = failed.filter((o) => o.severity === 'error');
|
||||
const warnings = failed.filter((o) => o.severity === 'warn');
|
||||
return { outcomes, errors, warnings, ok: errors.length === 0 };
|
||||
}
|
||||
|
||||
/**
|
||||
* The subset of a report that blocks a given action. `pack` asks for 'artifact' — it refuses to
|
||||
* zip a plugin that could never load, but does not care that the README is still a stub.
|
||||
*/
|
||||
export function blocking(report: CheckReport, action: CheckBlocks): CheckReport {
|
||||
if (action === 'publish') return report;
|
||||
const errors = report.errors.filter((e) => e.blocks === 'artifact');
|
||||
return { ...report, errors, ok: errors.length === 0 };
|
||||
}
|
||||
+153
-11
@@ -11,10 +11,12 @@ import { execFileSync } from 'node:child_process';
|
||||
import { createRequire } from 'node:module';
|
||||
import {
|
||||
intro, outro, note, logInfo, logSuccess, logWarn, spinner,
|
||||
promptText, promptSelect, promptMultiselect, promptConfirm,
|
||||
PERMISSION_CATALOG,
|
||||
promptText, promptSelect, promptMultiselect, promptGroupMultiselect, promptConfirm,
|
||||
PERMISSION_FAMILIES,
|
||||
} from './ui.js';
|
||||
import { KNOWN_ADDONS } from '../manifest.js';
|
||||
import { LUCIDE_ICON_NAMES } from '../lucide-icon-names.js';
|
||||
import { notifySdkUpdate } from './update-notice.js';
|
||||
|
||||
/** This package's own version, for the scaffold's devDependency range. */
|
||||
function sdkVersionRange(): string {
|
||||
@@ -47,10 +49,38 @@ export interface ScaffoldOptions {
|
||||
* channel is a plain `integration` that implements the `notificationChannel` hook.
|
||||
*/
|
||||
template?: 'blank' | 'notification-channel';
|
||||
/** A lucide icon name (PascalCase). Falls back to a sensible default for the type. */
|
||||
icon?: string;
|
||||
/** Where a `widget` renders. Omitting it silently means 'sidebar'. */
|
||||
slot?: WidgetSlot;
|
||||
}
|
||||
|
||||
export const TEMPLATES = ['blank', 'notification-channel'] as const;
|
||||
|
||||
/** 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];
|
||||
|
||||
export const WIDGET_SLOT_HINTS: Record<WidgetSlot, string> = {
|
||||
sidebar: 'The trip sidebar, alongside weather and countdown (the default)',
|
||||
hero: 'The banner at the top of the trip',
|
||||
'place-detail': "Inside a place's detail panel",
|
||||
'day-detail': "Inside a day's detail panel",
|
||||
'reservation-detail': "Inside a reservation's detail panel",
|
||||
};
|
||||
|
||||
/**
|
||||
* A defensible starting icon per plugin type. Not a guess at what the plugin DOES — it cannot know
|
||||
* that — just a better default than every new plugin sharing the generic `Blocks` glyph.
|
||||
*/
|
||||
function defaultIconFor(type: string, isChannel: boolean): string {
|
||||
if (isChannel) return 'BellRing';
|
||||
if (type === 'widget') return 'LayoutGrid';
|
||||
if (type === 'page') return 'BookOpen';
|
||||
if (type === 'trip-page') return 'Map';
|
||||
return 'Plug';
|
||||
}
|
||||
|
||||
export function scaffold(name: string, type: string, targetDir: string, opts: ScaffoldOptions = {}): void {
|
||||
if (!/^[a-z][a-z0-9-]{2,39}$/.test(name)) throw new Error(`invalid plugin id "${name}" (lowercase slug, 3–40 chars)`);
|
||||
if (!['integration', 'page', 'widget', 'trip-page'].includes(type)) throw new Error(`invalid type "${type}"`);
|
||||
@@ -91,7 +121,11 @@ 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,
|
||||
trek: '>=3.3.0 <4.0.0',
|
||||
// 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',
|
||||
nativeModules: false,
|
||||
permissions: perms,
|
||||
// Dependency declarations (empty by default). `requiredAddons` lists addon ids
|
||||
@@ -100,6 +134,10 @@ export function scaffold(name: string, type: string, targetDir: string, opts: Sc
|
||||
requiredAddons: opts.requiredAddons ?? [],
|
||||
pluginDependencies: opts.pluginDependencies ?? [],
|
||||
};
|
||||
// The store tile, the nav entry, the widget header and the admin row all render this. Omitting
|
||||
// it is legal — TREK falls back to `Blocks` — but then every plugin that skipped it is the same
|
||||
// grey square in the store, so the scaffold picks a real one rather than leaving it out.
|
||||
manifest.icon = opts.icon && LUCIDE_ICON_NAMES.has(opts.icon) ? opts.icon : defaultIconFor(type, isChannel);
|
||||
if (egress.length) manifest.egress = egress;
|
||||
// A notification channel usually targets a SELF-HOSTED service, whose hostname the
|
||||
// author cannot know at publish time. Declaring operatorEgress lets the admin add the
|
||||
@@ -112,7 +150,12 @@ export function scaffold(name: string, type: string, targetDir: string, opts: Sc
|
||||
// host ignores a manifest `routes`. A `page` plugin gets its nav entry
|
||||
// automatically, so there's no `capabilities.nav` either; only `widget` carries a
|
||||
// capability worth scaffolding.
|
||||
if (type === 'widget') manifest.capabilities = { widget: { title: displayName, defaultSize: 'medium' } };
|
||||
// `slot` decides WHERE the widget renders, and omitting it silently means 'sidebar' — so a
|
||||
// widget meant for a place's detail panel would quietly appear in the trip sidebar instead,
|
||||
// with nothing anywhere to say why. Always write it.
|
||||
if (type === 'widget') {
|
||||
manifest.capabilities = { widget: { title: displayName, defaultSize: 'medium', slot: opts.slot ?? 'sidebar' } };
|
||||
}
|
||||
if (isChannel) {
|
||||
manifest.capabilities = { notificationChannel: { title: displayName } };
|
||||
// The recipient's own credential. `scope: 'user'` is what makes it per-user, and
|
||||
@@ -159,8 +202,44 @@ export function scaffold(name: string, type: string, targetDir: string, opts: Sc
|
||||
fs.mkdirSync(path.join(root, 'client'), { recursive: true });
|
||||
fs.writeFileSync(path.join(root, 'client', 'index.html'), CLIENT_HTML);
|
||||
}
|
||||
|
||||
// The README has always linked ./docs/screenshot.png, and the scaffold has never created the
|
||||
// directory — so the very first thing an author was told to do had nowhere to go, and the only
|
||||
// thing that noticed was the registry, after the release was immutable. Make the destination
|
||||
// real, and say what belongs in it.
|
||||
fs.mkdirSync(path.join(root, 'docs'), { recursive: true });
|
||||
fs.writeFileSync(path.join(root, 'docs', 'README.md'), DOCS_README);
|
||||
|
||||
// Normalise line endings. The registry pins the artifact's sha256, and a CRLF checkout produces
|
||||
// different bytes for the same source — so a Windows author re-packing the same commit gets a
|
||||
// hash that no longer matches the entry they published.
|
||||
fs.writeFileSync(path.join(root, '.gitattributes'), GITATTRIBUTES);
|
||||
}
|
||||
|
||||
const DOCS_README = `Put \`screenshot.png\` here.
|
||||
|
||||
It is what the plugin's store card shows, and the registry REJECTS a plugin whose README has no
|
||||
screenshot that resolves to a real image — so this is not optional.
|
||||
|
||||
- 16:9, 1600×900 is ideal. The card crops the edges, so leave some margin.
|
||||
- Show the plugin doing its job, in context, inside TREK.
|
||||
|
||||
The quickest way: run \`trek-plugin dev\`, then \`trek-plugin shot\` in another terminal — it
|
||||
renders your plugin in a themed TREK frame and writes docs/screenshot.png for you.
|
||||
|
||||
This directory is NOT shipped in plugin.zip; it lives in your repo, and the README links it at the
|
||||
commit the registry pins.
|
||||
`;
|
||||
|
||||
const GITATTRIBUTES = `# The registry pins the sha256 of your packed artifact. A CRLF checkout changes those bytes for
|
||||
# the same source, so re-packing the same commit on Windows would produce a hash that no longer
|
||||
# matches the entry you published. Pin the line endings and the artifact stays reproducible.
|
||||
* text=auto eol=lf
|
||||
*.png binary
|
||||
*.jpg binary
|
||||
*.zip binary
|
||||
`;
|
||||
|
||||
const CHANNEL_JS = `// A TREK notification channel — runs in an isolated child process.
|
||||
//
|
||||
// TREK renders every notification into the recipient's language and hands it to you
|
||||
@@ -404,11 +483,21 @@ export async function interactiveScaffold(defaultDir: string, presetName?: strin
|
||||
defaultValue: 'Describe what your plugin does.',
|
||||
});
|
||||
|
||||
const permissions = await promptMultiselect<string>({
|
||||
message: 'Which permissions does it need?',
|
||||
options: PERMISSION_CATALOG.map((p) => ({ value: p.value, label: p.label, hint: p.hint })),
|
||||
// ONE prompt, grouped by area. 58 permissions in a flat list is unreadable, but asking in
|
||||
// two steps (areas → permissions) was worse: Clack has no "back", so picking the wrong
|
||||
// areas was a dead end you could only escape with ^C. A grouped multiselect is a single
|
||||
// scrollable screen — space toggles a permission, or a whole area from its header.
|
||||
const permissions = await promptGroupMultiselect<string>({
|
||||
message: 'Which permissions does it need? (space toggles; a group header toggles the whole area)',
|
||||
options: Object.fromEntries(
|
||||
PERMISSION_FAMILIES.map((f) => [
|
||||
`${f.label} — ${f.hint}`,
|
||||
f.permissions.map((p) => ({ value: p.value, label: p.value, hint: p.hint })),
|
||||
]),
|
||||
),
|
||||
initialValues: ['db:own'],
|
||||
required: false,
|
||||
selectableGroups: true,
|
||||
});
|
||||
|
||||
let egress: string[] | undefined;
|
||||
@@ -435,11 +524,38 @@ export async function interactiveScaffold(defaultDir: string, presetName?: strin
|
||||
required: false,
|
||||
});
|
||||
|
||||
// A widget with no slot silently renders in the sidebar. Ask, rather than let an author
|
||||
// discover months later that `hero` was always available.
|
||||
let slot: WidgetSlot | undefined;
|
||||
if (type === 'widget') {
|
||||
slot = await promptSelect<WidgetSlot>({
|
||||
message: 'Where should the widget appear?',
|
||||
initialValue: 'sidebar',
|
||||
options: WIDGET_SLOTS.map((s) => ({ value: s, label: s, hint: WIDGET_SLOT_HINTS[s] })),
|
||||
});
|
||||
}
|
||||
|
||||
// The store tile, the nav entry and the admin row all render this. The registry REJECTS a name
|
||||
// lucide does not have, so validate it here rather than at publish time.
|
||||
const fallbackIcon = defaultIconFor(type, template === 'notification-channel');
|
||||
const icon = await promptText({
|
||||
message: 'Icon — a lucide name (see https://lucide.dev/icons)',
|
||||
placeholder: fallbackIcon,
|
||||
defaultValue: fallbackIcon,
|
||||
validate: (v) => {
|
||||
const name = (v ?? '').trim();
|
||||
if (!name) return undefined; // the default is used
|
||||
return LUCIDE_ICON_NAMES.has(name) ? undefined : `lucide has no icon called "${name}" — TREK would fall back to Blocks`;
|
||||
},
|
||||
}).then((v) => v.trim() || fallbackIcon);
|
||||
|
||||
note(
|
||||
[
|
||||
`id ${id}`,
|
||||
`type ${type}`,
|
||||
template !== 'blank' ? `template ${template}` : undefined,
|
||||
slot ? `slot ${slot}` : undefined,
|
||||
`icon ${icon}`,
|
||||
`location ${dest}`,
|
||||
`author ${author}`,
|
||||
`permissions ${permissions.join(', ') || '(none)'}`,
|
||||
@@ -456,7 +572,7 @@ export async function interactiveScaffold(defaultDir: string, presetName?: strin
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
scaffold(id, type, parentDir, { author, description, permissions, egress, requiredAddons, template });
|
||||
scaffold(id, type, parentDir, { author, description, permissions, egress, requiredAddons, template, icon, slot });
|
||||
logSuccess(`Created ${dest}`);
|
||||
|
||||
if (!insideGitRepo(parentDir)) {
|
||||
@@ -484,13 +600,38 @@ export async function interactiveScaffold(defaultDir: string, presetName?: strin
|
||||
}
|
||||
}
|
||||
|
||||
const cd = path.relative(process.cwd(), dest) || dest;
|
||||
outro(`Next steps:\n cd ${cd}\n npx trek-plugin-sdk dev`);
|
||||
outro(nextStepsAfterCreate(dest));
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* What to do next, said ONCE.
|
||||
*
|
||||
* There used to be three of these — the wizard's outro, the `create` dispatch branch and the
|
||||
* standalone `create-trek-plugin` bin — and they named three different next commands (`dev`,
|
||||
* `dev`, `validate`). Whichever an author hit was a coin toss, and none of them mentioned that
|
||||
* the plugin they had just been handed could not be published as-is.
|
||||
*
|
||||
* So it points at `dev` (the thing you actually want to do next) and at `status` (the thing that
|
||||
* will tell you the truth about what is still missing), and it does not pretend the scaffold is
|
||||
* finished.
|
||||
*/
|
||||
export function nextStepsAfterCreate(dest: string): string {
|
||||
const cd = path.relative(process.cwd(), dest) || dest;
|
||||
return [
|
||||
'Next steps:',
|
||||
` cd ${cd}`,
|
||||
' trek-plugin dev run it locally, hot-reloaded',
|
||||
' trek-plugin status what is left before you can publish',
|
||||
'',
|
||||
'The scaffold is not publishable yet — it needs a written README and a screenshot.',
|
||||
'`status` lists exactly what, whenever you ask it.',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
// CLI entry
|
||||
if (process.argv[1] && process.argv[1].endsWith('create.js')) {
|
||||
notifySdkUpdate();
|
||||
const args = process.argv.slice(2);
|
||||
const name = args.find((a: string) => !a.startsWith('-'));
|
||||
const typeIdx = args.indexOf('--type');
|
||||
@@ -503,7 +644,8 @@ if (process.argv[1] && process.argv[1].endsWith('create.js')) {
|
||||
}
|
||||
try {
|
||||
scaffold(name, type, process.cwd(), { template });
|
||||
console.log(`Created ${name}/ — fill in the README, build server/index.js, then \`npx trek-plugin-sdk validate ${name}\`.`);
|
||||
// The SAME message the wizard and `trek-plugin create` print. These three used to disagree.
|
||||
console.log(nextStepsAfterCreate(path.join(process.cwd(), name)));
|
||||
} catch (e) {
|
||||
console.error(e instanceof Error ? e.message : e);
|
||||
process.exit(1);
|
||||
|
||||
+151
-25
@@ -7,6 +7,14 @@
|
||||
* node:sqlite, serves your routes over HTTP and your page/widget UI, and reloads
|
||||
* on every save.
|
||||
*
|
||||
* Enforcement is NOT limited to ctx. TREK gates hooks, event subscriptions, jobs
|
||||
* and outbound network BEFORE a plugin's ctx is ever reached, and it does so
|
||||
* SILENTLY — an ungranted hook is simply never called, with no error and no log, so
|
||||
* "my plugin does nothing" is all the author ever sees. Dev therefore refuses the
|
||||
* same things, loudly: it warns at load about every entry point you implement but
|
||||
* did not grant (see grantGaps), returns 403 from /__dev/fire for one, and installs
|
||||
* the real egress guard so an undeclared host fails here rather than after install.
|
||||
*
|
||||
* Dependency-free: node:http + node:sqlite (when present) + built-ins.
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
@@ -16,6 +24,11 @@ import { createRequire } from 'node:module';
|
||||
import * as sdk from '../index.js';
|
||||
import { injectTrekUi } from '../ui/kit.js';
|
||||
import { readJsonFile } from './json.js';
|
||||
import {
|
||||
PermissionDenied, HOOK_PERMISSION, USER_DATA_PERMISSION, EVENTS_PERMISSION, JOBS_PERMISSION,
|
||||
grantGaps, grantedHosts, type GrantGap,
|
||||
} from '../permissions.js';
|
||||
import { installEgressGuard } from '../egress-policy.js';
|
||||
|
||||
// Dev fixtures ARE mock-host options — the dev ctx delegates every non-db-own
|
||||
// capability to a grant-enforcing mock host, so dev-fixtures.json can seed the full
|
||||
@@ -36,7 +49,34 @@ interface PluginLike {
|
||||
hooks?: Record<string, Record<string, Handler>>;
|
||||
}
|
||||
|
||||
class PermissionDenied extends Error {}
|
||||
// /__dev/fire/<kind> → the permission TREK requires before it would ever fire that
|
||||
// entry point. `hook` is resolved per hook name via HOOK_PERMISSION instead.
|
||||
const FIRE_PERMISSION: Readonly<Record<string, string | undefined>> = {
|
||||
job: JOBS_PERMISSION,
|
||||
scheduled: JOBS_PERMISSION,
|
||||
event: EVENTS_PERMISSION,
|
||||
deleteUserData: USER_DATA_PERMISSION,
|
||||
exportUserData: USER_DATA_PERMISSION,
|
||||
};
|
||||
|
||||
/** Refuse an entry point the manifest never granted. An unknown kind/hook has no
|
||||
* permission to check — it falls through to the handler's own 400/404. */
|
||||
function needGrant(grants: ReadonlySet<string>, perm: string | undefined, what: string): void {
|
||||
if (perm && !grants.has(perm)) {
|
||||
throw new PermissionDenied(
|
||||
`PERMISSION_DENIED: ${what} requires "${perm}" — add it to permissions in trek-plugin.json. ` +
|
||||
`TREK would never fire this entry point (it skips ungranted plugins silently).`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Warn about every entry point the plugin implements but cannot run. Printed at load
|
||||
* and on every hot reload, because this failure is invisible in production. */
|
||||
function printGaps(gaps: GrantGap[]): void {
|
||||
for (const g of gaps) {
|
||||
console.warn(` ⚠ ${g.entryPoint} is implemented but "${g.permission}" is NOT granted — ${g.consequence}`);
|
||||
}
|
||||
}
|
||||
|
||||
// The same SQL guards the real host's PluginDataDb applies (plugin-data.service.ts):
|
||||
// forbidden statement types, an sql-length cap, a result-row cap, and — inside tx() —
|
||||
@@ -92,9 +132,31 @@ function flatBind(args: unknown[]): unknown[] {
|
||||
|
||||
/** A dev db backed by node:sqlite if available, else an in-memory recorder that returns []. */
|
||||
export function createDevDb(dbFile: string): { db: PluginContextDb; note: string; close: () => void } {
|
||||
// node:sqlite ships on Node 22.5+. Probe for it SEPARATELY from opening the database:
|
||||
// one try/catch around both meant an mkdir/permission failure silently degraded to the
|
||||
// stub too, and the stub swallows every write while reporting success — a db:own plugin
|
||||
// "works" in dev and persists nothing. Fail loudly on a real error; degrade only on old Node.
|
||||
let DatabaseSync: (new (p: string) => SqliteDb) | undefined;
|
||||
try {
|
||||
// node:sqlite is available on Node 22.5+ (experimental). Fall back gracefully if not.
|
||||
const { DatabaseSync } = createRequire(import.meta.url)('node:sqlite') as { DatabaseSync: new (p: string) => SqliteDb };
|
||||
({ DatabaseSync } = createRequire(import.meta.url)('node:sqlite') as { DatabaseSync: new (p: string) => SqliteDb });
|
||||
} catch {
|
||||
console.warn(
|
||||
`\n ⚠ node:sqlite is unavailable on this Node (${process.version}) — ctx.db is a STUB.\n` +
|
||||
` Every query returns [] and every write reports 0 changes: a db:own plugin will look\n` +
|
||||
` like it works and persist NOTHING. Upgrade to Node 22.5+ to test db:own for real.\n`,
|
||||
);
|
||||
return {
|
||||
note: `db:own → in-memory STUB (writes are discarded — upgrade to Node 22.5+; you are on ${process.version})`,
|
||||
close: () => {},
|
||||
db: {
|
||||
async query(sql: string) { guardSql(sql); return []; },
|
||||
async exec(sql: string) { guardSql(sql); return { changes: 0 }; },
|
||||
async migrate(_id: string, sql: string) { guardSql(sql); return { applied: true }; },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
{
|
||||
fs.mkdirSync(path.dirname(dbFile), { recursive: true });
|
||||
const sq = new DatabaseSync(dbFile);
|
||||
const applied = new Set<string>();
|
||||
@@ -116,16 +178,6 @@ export function createDevDb(dbFile: string): { db: PluginContextDb; note: string
|
||||
async migrate(id: string, sql: string) { guardSql(sql); if (applied.has(id)) return { applied: false }; sq.exec(sql); applied.add(id); return { applied: true }; },
|
||||
},
|
||||
};
|
||||
} catch {
|
||||
return {
|
||||
note: 'db:own → in-memory stub (upgrade to Node 22.5+ for a real SQLite dev db)',
|
||||
close: () => {},
|
||||
db: {
|
||||
async query(sql: string) { guardSql(sql); return []; },
|
||||
async exec(sql: string) { guardSql(sql); return { changes: 0 }; },
|
||||
async migrate(_id: string, sql: string) { guardSql(sql); return { applied: true }; },
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -265,10 +317,18 @@ export async function runDev(dir: string, opts: { port?: number } = {}): Promise
|
||||
const req = createRequire(path.join(abs, 'server', 'index.js'));
|
||||
|
||||
let plugin: PluginLike = {};
|
||||
let gaps: GrantGap[] = [];
|
||||
let version = 0;
|
||||
const { ctx, userlessCtx } = createDevContext(id, grants, fx, db, broadcasts);
|
||||
const port = opts.port ?? 4317;
|
||||
|
||||
// The plugin's outbound network, restricted to the hosts it was granted — with none,
|
||||
// everything is blocked, exactly as in TREK. `operatorEgressHosts` in dev-fixtures.json
|
||||
// stands in for the hosts an admin supplies at runtime to an `operatorEgress` plugin,
|
||||
// which by definition cannot name them in its manifest.
|
||||
const egressHosts = [...grantedHosts(grants), ...(fx.operatorEgressHosts ?? [])];
|
||||
installEgressGuard(egressHosts);
|
||||
|
||||
// Block a browser-initiated cross-site request to the side-effectful endpoints:
|
||||
// modern browsers stamp Sec-Fetch-Site (anything but same-origin is another site;
|
||||
// 'none' is the user's own address bar and stays allowed), and every browser sends
|
||||
@@ -292,17 +352,25 @@ export async function runDev(dir: string, opts: { port?: number } = {}): Promise
|
||||
await plugin.onLoad?.(ctx);
|
||||
version++;
|
||||
console.log(` ↻ loaded ${plugin.routes?.length ?? 0} route(s)`);
|
||||
// Recomputed on every reload: adding a hook (or removing its permission) mid-session
|
||||
// must change the warning, not leave a stale one from boot. The initial load's gaps
|
||||
// are printed by the startup banner; a reload prints its own (see reload()).
|
||||
gaps = grantGaps(plugin, grants);
|
||||
} catch (e) {
|
||||
// A plugin whose load/onLoad throws would fail activation in TREK — don't
|
||||
// keep serving its routes here, or dev would hide exactly that failure.
|
||||
plugin = {};
|
||||
gaps = [];
|
||||
console.error(' ✗ plugin failed to load:', e instanceof Error ? e.message : e);
|
||||
}
|
||||
};
|
||||
await load();
|
||||
|
||||
let timer: NodeJS.Timeout | null = null;
|
||||
const reload = () => { if (timer) clearTimeout(timer); timer = setTimeout(() => { console.log(' change detected'); void load(); }, 120); };
|
||||
const reload = () => {
|
||||
if (timer) clearTimeout(timer);
|
||||
timer = setTimeout(() => { console.log(' change detected'); void load().then(() => printGaps(gaps)); }, 120);
|
||||
};
|
||||
watchTree(path.join(abs, 'server'), reload);
|
||||
watchTree(path.join(abs, 'client'), reload);
|
||||
|
||||
@@ -332,6 +400,10 @@ export async function runDev(dir: string, opts: { port?: number } = {}): Promise
|
||||
if (typeof bodyRaw === 'string') { try { payload = JSON.parse(bodyRaw); } catch { payload = bodyRaw; } }
|
||||
if (payload === undefined) { const q: Record<string, string> = {}; url.searchParams.forEach((v, k) => { q[k] = v; }); if (Object.keys(q).length) payload = q; }
|
||||
try {
|
||||
// TREK gates these entry points on a permission BEFORE the plugin is reached, and
|
||||
// an ungranted one is never invoked — silently. Refuse it here, loudly, or dev
|
||||
// would keep green-lighting a plugin that does nothing at all once installed.
|
||||
needGrant(grants, kind === 'hook' ? HOOK_PERMISSION[name] : FIRE_PERMISSION[kind], `${kind}${name ? `/${name}` : ''}`);
|
||||
// Jobs, scheduled tasks, events and the GDPR handlers run with NO acting user in
|
||||
// production — fire them against the userless ctx so a membership read fails here
|
||||
// exactly like it would in TREK. Hooks stay user-bound.
|
||||
@@ -341,7 +413,26 @@ export async function runDev(dir: string, opts: { port?: number } = {}): Promise
|
||||
else if (kind === 'event') { for (const s of plugin.events ?? []) if (s.on === name || s.on === '*') await s.handler({ event: name, tripId: 0, ...(payload as object) }, userlessCtx); out = { delivered: true }; }
|
||||
else if (kind === 'deleteUserData') { if (!plugin.deleteUserData) return send(404, 'no deleteUserData handler'); out = await plugin.deleteUserData({ userId: Number((payload as { userId?: unknown })?.userId ?? name ?? 0) }, userlessCtx); }
|
||||
else if (kind === 'exportUserData') { if (!plugin.exportUserData) return send(404, 'no exportUserData handler'); out = await plugin.exportUserData({ userId: Number((payload as { userId?: unknown })?.userId ?? name ?? 0) }, userlessCtx); }
|
||||
else if (kind === 'hook') { const impl = plugin.hooks?.[name]; if (!impl || typeof impl[fn] !== 'function') return send(404, `no hook ${name}.${fn}`); out = await impl[fn](...(Array.isArray(payload) ? payload : payload != null ? [payload] : []), ctx); }
|
||||
else if (kind === 'hook') {
|
||||
const impl = plugin.hooks?.[name];
|
||||
if (!impl || typeof impl[fn] !== 'function') return send(404, `no hook ${name}.${fn}`);
|
||||
if (name === 'notificationChannel') {
|
||||
// A notification channel is NOT like the other hooks: the host fires it with no
|
||||
// acting user (it delivers to an arbitrary recipient), and hands the recipient's
|
||||
// decrypted settings in as a separate `config` argument —
|
||||
// send(msg, config, ctx) · test(config, ctx)
|
||||
// Firing it like a normal hook passed `ctx` where `config` belongs, so a channel
|
||||
// plugin read its settings off the ctx object and "worked" in dev while being
|
||||
// broken in production. Mirror the host (and createMockHost) exactly.
|
||||
const config = (fx.userSettings ?? {}) as Record<string, unknown>;
|
||||
const args = Array.isArray(payload) ? (payload as unknown[]) : payload != null ? [payload] : [];
|
||||
out = fn === 'test'
|
||||
? await impl[fn](config, userlessCtx)
|
||||
: await impl[fn](args[0], (args[1] as Record<string, unknown>) ?? config, userlessCtx);
|
||||
} else {
|
||||
out = await impl[fn](...(Array.isArray(payload) ? payload : payload != null ? [payload] : []), ctx);
|
||||
}
|
||||
}
|
||||
else return send(400, `unknown fire kind "${kind}"`);
|
||||
return send(200, JSON.stringify(out ?? { ok: true }, null, 2), 'application/json; charset=utf-8');
|
||||
} catch (e) {
|
||||
@@ -350,19 +441,33 @@ export async function runDev(dir: string, opts: { port?: number } = {}): Promise
|
||||
}
|
||||
}
|
||||
|
||||
if (url.pathname === '/') return send(200, dashboard(id, String(manifest.type), plugin.routes ?? [], dbNote, broadcasts.length), 'text/html; charset=utf-8');
|
||||
if (url.pathname === '/') return send(200, dashboard(id, String(manifest.type), plugin.routes ?? [], dbNote, broadcasts.length, gaps), 'text/html; charset=utf-8');
|
||||
|
||||
// Faithful host preview: embeds /ui in a sandboxed opaque-origin iframe (exactly
|
||||
// like TREK) and plays the host — posts trek:context (with a theme/accent toggle),
|
||||
// proxies trek:invoke to your /api routes, and honours resize/notify/navigate. This
|
||||
// is where the design kit actually renders themed.
|
||||
if (url.pathname === '/preview' && String(manifest.type) !== 'integration') {
|
||||
return send(200, preview(id, String(manifest.type)), 'text/html; charset=utf-8');
|
||||
// Preview against a trip that actually EXISTS in the fixtures. This used to be
|
||||
// hard-coded to 42 while the scaffold seeds trip 1, so the widget's first
|
||||
// trek:invoke hit assertMember(42, …) and 500'd with RESOURCE_FORBIDDEN.
|
||||
const previewTripId = Number(Object.keys(fx.trips ?? {})[0] ?? 1) || 1;
|
||||
// ?chrome=0 strips the dev toolbar and centres the plugin — what `trek-plugin shot`
|
||||
// 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');
|
||||
}
|
||||
|
||||
// Static plugin UI at /ui (page/widget client bundle)
|
||||
// Static plugin UI at /ui (page/widget client bundle). The iframe loads
|
||||
// `/ui/index.html` (not bare `/ui`) so relative asset URLs — `./assets/x.js`
|
||||
// from a multi-file Vite/React build with `base: './'` — resolve to
|
||||
// `/ui/assets/x.js`, exactly as the real host resolves them against
|
||||
// `/plugin-frame/<id>/index.html`. A bare `/ui` document would resolve them
|
||||
// against the origin root (`/assets/x.js`) and 404. Bare `/ui` and `/ui/` both
|
||||
// still serve index.html for direct navigation.
|
||||
if (url.pathname === '/ui' || url.pathname.startsWith('/ui/')) {
|
||||
const relFile = url.pathname === '/ui' ? 'index.html' : url.pathname.slice('/ui/'.length);
|
||||
const relFile = url.pathname === '/ui' ? 'index.html' : (url.pathname.slice('/ui/'.length) || 'index.html');
|
||||
const file = path.join(abs, 'client', relFile);
|
||||
if (!file.startsWith(path.join(abs, 'client'))) return send(403, 'forbidden');
|
||||
if (!fs.existsSync(file) || !fs.statSync(file).isFile()) return send(404, 'not found — build your client/ bundle');
|
||||
@@ -418,6 +523,8 @@ export async function runDev(dir: string, opts: { port?: number } = {}): Promise
|
||||
console.log(`\n trek-plugin dev — ${id} (${String(manifest.type)})`);
|
||||
console.log(` ${dbNote}`);
|
||||
console.log(` granted: ${[...grants].join(', ') || '(none)'}`);
|
||||
console.log(` egress: ${egressHosts.join(', ') || '(none — all outbound is blocked, as in TREK)'}`);
|
||||
printGaps(gaps);
|
||||
console.log(`\n ▸ http://localhost:${port}/ dashboard`);
|
||||
if (String(manifest.type) !== 'integration') {
|
||||
console.log(` ▸ http://localhost:${port}/preview themed host preview`);
|
||||
@@ -452,20 +559,32 @@ function contentType(file: string): string {
|
||||
|
||||
const LIVE_RELOAD = `<script>let __v;setInterval(async()=>{try{const v=await(await fetch('/__dev/version')).text();if(__v&&v!==__v)location.reload();__v=v;}catch(e){}},1000)</script>`;
|
||||
|
||||
function dashboard(id: string, type: string, routes: PluginRouteLike[], dbNote: string, bcasts: number): string {
|
||||
function dashboard(id: string, type: string, routes: PluginRouteLike[], dbNote: string, bcasts: number, gaps: GrantGap[]): string {
|
||||
const rows = routes.length
|
||||
? routes.map((r) => `<tr><td><code>${r.method}</code></td><td><a href="/api${r.path}">/api${r.path}</a></td><td>${r.auth === false ? 'public' : 'auth'}</td></tr>`).join('')
|
||||
: '<tr><td colspan="3" style="opacity:.6">no routes declared</td></tr>';
|
||||
const ui = type !== 'integration'
|
||||
? `<p><a href="/preview">▸ open the themed host preview (/preview)</a> · <a href="/ui">raw /ui</a></p>`
|
||||
: '';
|
||||
// The silent killer, made loud: in TREK these entry points are simply never invoked,
|
||||
// with nothing logged anywhere. If any exist, they are the most important thing here.
|
||||
const warn = gaps.length
|
||||
? `<div class="warn"><strong>⚠ ${gaps.length} entry point(s) TREK would never run</strong><ul>${gaps
|
||||
.map((g) => `<li><code>${g.entryPoint}</code> needs <code>${g.permission}</code> — ${g.consequence}</li>`)
|
||||
.join('')}</ul><p>Add the permission(s) to <code>trek-plugin.json</code>. Until then this works in dev and does nothing once installed.</p></div>`
|
||||
: '';
|
||||
return `<!doctype html><meta charset="utf-8"><title>${id} · trek-plugin dev</title>
|
||||
<style>body{font:15px/1.5 system-ui,sans-serif;max-width:720px;margin:3rem auto;padding:0 1rem;color:#111}
|
||||
h1{font-size:1.4rem}code{background:#f3f4f6;padding:.1em .35em;border-radius:4px}
|
||||
table{border-collapse:collapse;width:100%;margin:1rem 0}td{border-bottom:1px solid #eee;padding:.5rem .4rem;text-align:left}
|
||||
.muted{color:#6b7280;font-size:.9rem}a{color:#4f46e5}@media(prefers-color-scheme:dark){body{background:#111827;color:#e5e7eb}code{background:#1f2937}td{border-color:#374151}}</style>
|
||||
.muted{color:#6b7280;font-size:.9rem}a{color:#4f46e5}
|
||||
.warn{background:#fef2f2;border:1px solid #fecaca;border-radius:8px;padding:.75rem 1rem;margin:1rem 0}
|
||||
.warn ul{margin:.5rem 0;padding-left:1.2rem}.warn p{margin:.5rem 0 0;font-size:.9rem}
|
||||
@media(prefers-color-scheme:dark){body{background:#111827;color:#e5e7eb}code{background:#1f2937}td{border-color:#374151}
|
||||
.warn{background:#3f1d1d;border-color:#7f1d1d}}</style>
|
||||
<h1>${id} <span class="muted">· ${type}</span></h1>
|
||||
<p class="muted">${dbNote} · ${bcasts} ws broadcast(s) captured</p>
|
||||
${warn}
|
||||
${ui}
|
||||
<table><tr><th>Method</th><th>URL</th><th>Auth</th></tr>${rows}</table>
|
||||
<p class="muted">Add <code>?_anon=1</code> to a route to hit it as an unauthenticated request. Edit <code>server/</code> or <code>client/</code> and this reloads.</p>
|
||||
@@ -479,12 +598,19 @@ ${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): string {
|
||||
function preview(id: string, type: string, tripId: number, opts: { chrome?: boolean; theme?: 'light' | 'dark' } = {}): 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:
|
||||
// useful while you build, absurd on a store card. So shot mode strips them and centres the
|
||||
// plugin in the frame, and the shot is of the plugin rather than of the tool that drew it.
|
||||
const chrome = opts.chrome !== false;
|
||||
const dark = opts.theme === 'dark';
|
||||
return `<!doctype html><html lang="en"><head><meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1"><title>${id} · preview</title>
|
||||
<style>
|
||||
*{box-sizing:border-box}
|
||||
${chrome ? '' : 'header,.hint{display:none!important}.stage{min-height:100vh;align-items:center;padding:0 20px}'}
|
||||
body{margin:0;font:14px/1.5 system-ui,-apple-system,sans-serif;background:#f4f5f7;color:#111827}
|
||||
body.dark{background:#0e0e11;color:#e5e7eb}
|
||||
header{display:flex;gap:14px;align-items:center;flex-wrap:wrap;padding:12px 16px;border-bottom:1px solid #e5e7eb;position:sticky;top:0;background:inherit;z-index:2}
|
||||
@@ -504,13 +630,13 @@ iframe{width:100%;border:0;background:transparent;min-height:120px;display:block
|
||||
<header>
|
||||
<strong>${id}</strong><span style="opacity:.5">· ${type} preview</span>
|
||||
<span class="sp"></span>
|
||||
<label>Theme <select id="theme"><option value="light">light</option><option value="dark">dark</option></select></label>
|
||||
<label>Theme <select id="theme"><option value="light"${dark ? '' : ' selected'}>light</option><option value="dark"${dark ? ' selected' : ''}>dark</option></select></label>
|
||||
<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="trip" checked> trip context</label>
|
||||
</header>
|
||||
<div class="stage"><div class="wrap"><iframe id="f" src="/ui" sandbox="allow-scripts allow-forms" referrerpolicy="no-referrer" title="${id}"></iframe></div></div>
|
||||
<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>
|
||||
<p class="hint">The frame runs sandboxed at an opaque origin, exactly like TREK — <code>trek.invoke()</code> is proxied to your /api routes as the dev user.</p>
|
||||
<div class="toast" id="toast"></div>
|
||||
<script>
|
||||
@@ -529,7 +655,7 @@ function ctx(){
|
||||
document.body.classList.toggle("dark", theme==="dark");
|
||||
var tokens={}; var src=theme==="dark"?DA[accent]:LA[accent]; for(var k in src){tokens[k]=src[k];}
|
||||
return {type:"trek:context",theme:theme,locale:"en",hostOrigin:location.origin,
|
||||
tripId: val("trip").checked?42:null, userId:"1",
|
||||
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},
|
||||
|
||||
+67
-11
@@ -4,8 +4,8 @@
|
||||
* [--merge registry/plugins/<id>.json] [--out file]
|
||||
*
|
||||
* Generates the ready-to-PR TREK-Plugins registry entry from the manifest + the
|
||||
* packed plugin.zip + the git tag — so the sha256, size, commitSha, downloadUrl
|
||||
* and minTrekVersion an author would compute by hand all come out of one command.
|
||||
* packed plugin.zip + the git tag — so the sha256, size, commitSha and downloadUrl
|
||||
* an author would compute by hand all come out of one command.
|
||||
* With --merge it prepends the new version onto an existing entry (the update
|
||||
* case), keeping versions newest-first.
|
||||
*/
|
||||
@@ -13,23 +13,62 @@ import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { minVersion, validRange } from 'semver';
|
||||
import { loadPrivateKey, signArtifact, publicKeyBase64 } from './sign.js';
|
||||
import { readJsonFile } from './json.js';
|
||||
|
||||
interface Version {
|
||||
version: string; gitTag: string; commitSha: string; downloadUrl: string;
|
||||
sha256: string; minTrekVersion: string; size: number; apiVersion: number;
|
||||
sha256: string;
|
||||
/**
|
||||
* The manifest's `trek` range, verbatim — the ONE compatibility field an entry carries.
|
||||
* It is what TREK gates installs and activation on, and the only field that can express
|
||||
* an exclusive upper bound.
|
||||
*
|
||||
* There is deliberately no `minTrekVersion` here any more. It said the same thing (the
|
||||
* range's lower bound) in a weaker form, and a second field restating a derived fact is a
|
||||
* second field that can be wrong. The registry still ACCEPTS one on entries published
|
||||
* before `trek` existed — and checks it agrees with the range — but nothing emits one now.
|
||||
*/
|
||||
trek: string;
|
||||
size: number; apiVersion: number;
|
||||
nativeModules: false; operatorEgress?: boolean; publishedAt: string; signature?: string;
|
||||
/**
|
||||
* The manifest's dependency fields, mirrored.
|
||||
*
|
||||
* These are NOT optional decoration. TREK resolves requiredAddons and pluginDependencies from
|
||||
* the registry INDEX, before it ever downloads the artifact — so an entry that omits them
|
||||
* resolves against a dependency set the code does not actually have. Both the registry's CI
|
||||
* (validate-entry.mjs) and `preflight` parity-check them against the manifest at the pinned
|
||||
* commit, which means an entry built without them fails for any plugin that declares one.
|
||||
*
|
||||
* They were missing here until now, so `requiredAddons: ["budget"]` in a manifest produced an
|
||||
* entry CI rejected with "manifest requiredAddons != entry requiredAddons" — after the release
|
||||
* had been cut and its bytes pinned. Emitted only when non-empty, so ordinary entries are
|
||||
* byte-identical to before.
|
||||
*/
|
||||
requiredAddons?: string[]; pluginDependencies?: PluginDependency[];
|
||||
}
|
||||
interface PluginDependency { id: string; version: string }
|
||||
interface Entry {
|
||||
id: string; name: string; author: string; description: string; repo: string;
|
||||
homepage?: string; tags?: string[]; type: string; authorPublicKey?: string; versions: Version[];
|
||||
homepage?: string; tags?: string[]; type: string; icon?: string; authorPublicKey?: string; versions: Version[];
|
||||
}
|
||||
|
||||
/** 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 ">=3.2.0 <4.0.0" -> "3.2.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
|
||||
* would have been published as the minimum — the precise inverse of what the plugin says.
|
||||
*/
|
||||
function minTrekFrom(trek: unknown): string | null {
|
||||
if (typeof trek !== 'string') return null;
|
||||
return trek.match(/(\d+\.\d+\.\d+)/)?.[1] ?? null;
|
||||
if (typeof trek !== 'string' || validRange(trek) === null) return null;
|
||||
try {
|
||||
return minVersion(trek)?.version ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function resolveCommit(dir: string, tag: string, override?: string): string {
|
||||
@@ -50,8 +89,9 @@ export function buildEntry(opts: {
|
||||
}): Entry {
|
||||
const manifest = readJsonFile<Record<string, unknown>>(path.join(opts.dir, 'trek-plugin.json'));
|
||||
if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(opts.repo)) throw new Error(`--repo must be "owner/name", got "${opts.repo}"`);
|
||||
const minTrek = minTrekFrom(manifest.trek);
|
||||
if (!minTrek) throw new Error('manifest has no "trek" version range to derive minTrekVersion from (e.g. "trek": ">=3.2.0 <4.0.0")');
|
||||
// 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 (!fs.existsSync(opts.zipPath)) throw new Error(`artifact not found: ${opts.zipPath} — run \`trek-plugin pack\` first`);
|
||||
|
||||
const buf = fs.readFileSync(opts.zipPath);
|
||||
@@ -62,7 +102,7 @@ export function buildEntry(opts: {
|
||||
commitSha: resolveCommit(opts.dir, opts.tag, opts.commit),
|
||||
downloadUrl: `https://github.com/${opts.repo}/releases/download/${opts.tag}/${asset}`,
|
||||
sha256: createHash('sha256').update(buf).digest('hex'),
|
||||
minTrekVersion: minTrek,
|
||||
trek: String(manifest.trek),
|
||||
size: buf.length,
|
||||
apiVersion: typeof manifest.apiVersion === 'number' ? manifest.apiVersion : 1,
|
||||
nativeModules: false,
|
||||
@@ -73,6 +113,17 @@ export function buildEntry(opts: {
|
||||
// hosts after install). Only emitted when true, so ordinary entries stay unchanged.
|
||||
if (manifest.operatorEgress === true) version.operatorEgress = true;
|
||||
|
||||
// Mirror the dependency fields. See the Version interface for why omitting these was a bug:
|
||||
// TREK resolves them from the index before downloading, and CI refuses an entry that
|
||||
// disagrees with the manifest. Only emitted when non-empty — an empty array and an absent
|
||||
// one normalise identically on both sides of the parity check.
|
||||
const requiredAddons = Array.isArray(manifest.requiredAddons) ? manifest.requiredAddons.map(String) : [];
|
||||
if (requiredAddons.length) version.requiredAddons = requiredAddons;
|
||||
const pluginDependencies = Array.isArray(manifest.pluginDependencies)
|
||||
? (manifest.pluginDependencies as PluginDependency[]).map((d) => ({ id: String(d?.id), version: String(d?.version) }))
|
||||
: [];
|
||||
if (pluginDependencies.length) version.pluginDependencies = pluginDependencies;
|
||||
|
||||
// Optional author signature over the exact artifact bytes.
|
||||
let authorPublicKey: string | undefined;
|
||||
if (opts.signKeyPath) {
|
||||
@@ -90,7 +141,11 @@ export function buildEntry(opts: {
|
||||
throw new Error('this plugin was published signed — sign the update too (pass --sign) or TREK will refuse it.');
|
||||
}
|
||||
const versions = [version, ...existing.versions.filter((v) => v.version !== version.version)];
|
||||
return { ...existing, authorPublicKey: authorPublicKey ?? existing.authorPublicKey, versions };
|
||||
// Refresh the icon from the manifest when this release declares one (an author who adds
|
||||
// or changes it should see it in the store), but never wipe an icon the entry already
|
||||
// carries just because the manifest omits it.
|
||||
const icon = typeof manifest.icon === 'string' && manifest.icon ? manifest.icon : existing.icon;
|
||||
return { ...existing, icon, authorPublicKey: authorPublicKey ?? existing.authorPublicKey, versions };
|
||||
}
|
||||
|
||||
const entry: Entry = {
|
||||
@@ -102,6 +157,7 @@ export function buildEntry(opts: {
|
||||
type: String(manifest.type),
|
||||
versions: [version],
|
||||
};
|
||||
if (typeof manifest.icon === 'string' && manifest.icon) entry.icon = manifest.icon;
|
||||
if (typeof manifest.homepage === 'string') entry.homepage = manifest.homepage;
|
||||
if (Array.isArray(manifest.tags)) entry.tags = manifest.tags.map(String).slice(0, 8);
|
||||
if (authorPublicKey) entry.authorPublicKey = authorPublicKey;
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
/**
|
||||
* Help, tiered.
|
||||
*
|
||||
* The old help was eleven commands in one flat list, one line each, with no order and no
|
||||
* per-command detail — `trek-plugin dev --help` fell through to the same flat list. So the only
|
||||
* description of any command was that one line, and nothing anywhere said which to run first.
|
||||
*
|
||||
* Two changes. The top-level lists THE PATH (create → dev → status → publish) and pushes the
|
||||
* other seven to an "Also" line: they are real commands, and an author who knows what `entry`
|
||||
* is can still reach for it, but nobody has to learn eleven things to publish a plugin. And
|
||||
* every command now has its own page, with what it does, when you would reach for it, and its
|
||||
* flags.
|
||||
*/
|
||||
|
||||
export const VERSION_LINE = (v: string): string => `trek-plugin-sdk ${v}`;
|
||||
|
||||
/** The four commands that ARE the job. Everything else is a step one of these already does. */
|
||||
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 interface CommandHelp {
|
||||
/** One line, for the top-level list. */
|
||||
summary: string;
|
||||
/** Usage line. */
|
||||
usage: string;
|
||||
/** What it does and — more usefully — when you would reach for it. */
|
||||
body: string;
|
||||
}
|
||||
|
||||
export const COMMAND_HELP: Record<string, CommandHelp> = {
|
||||
create: {
|
||||
summary: 'scaffold a new plugin',
|
||||
usage: 'trek-plugin create [name] [--type integration|page|widget|trip-page] [--template blank|notification-channel]',
|
||||
body: `Scaffolds a plugin: manifest, server entry, README, and a client UI for anything that is not
|
||||
an integration. With no name it runs a wizard that asks for the id, type, icon, permissions,
|
||||
egress hosts and required addons.
|
||||
|
||||
The plugin it gives you RUNS immediately — \`dev\` and \`pack\` work — but it is not publishable
|
||||
yet: the README is a template and there is no screenshot. That is deliberate, and \`status\` will
|
||||
tell you exactly what is left.
|
||||
|
||||
--type integration server-only: routes, hooks, background work
|
||||
page a full navigation page (sandboxed iframe UI)
|
||||
widget a dashboard widget (sandboxed iframe UI)
|
||||
trip-page a tab inside every trip (sandboxed iframe UI)
|
||||
--template blank | notification-channel
|
||||
--author author name for the manifest
|
||||
--description one-line description (5-200 chars; the registry requires it)
|
||||
--permissions "db:own db:read:trips"
|
||||
--egress api.example.com,api.other.com
|
||||
--required-addons budget,packing
|
||||
--interactive force the wizard even when a name is given`,
|
||||
},
|
||||
|
||||
dev: {
|
||||
summary: 'run it locally, hot-reloaded',
|
||||
usage: 'trek-plugin dev [dir] [--port 4317]',
|
||||
body: `Runs the plugin against a mock TREK host, with hot reload. It enforces the SAME permissions
|
||||
your manifest declares, so an ungranted call throws PERMISSION_DENIED here exactly as it would in
|
||||
production, and \`db:own\` is backed by a real SQLite file under .trek-dev/.
|
||||
|
||||
/ a dashboard: your routes, your grants, what is wired up
|
||||
/preview your UI in the themed, sandboxed frame TREK actually renders it in
|
||||
/ui your UI raw, unframed
|
||||
/api/* your routes
|
||||
/__dev/fire/<kind> fire a job, a scheduled run, an event or a hook by hand
|
||||
|
||||
Binds 127.0.0.1 only. Editing server/ or client/ reloads.`,
|
||||
},
|
||||
|
||||
status: {
|
||||
summary: "where am I? what's left?",
|
||||
usage: 'trek-plugin status [dir]',
|
||||
body: `The command to run when you are not sure what to do next.
|
||||
|
||||
Runs every check the TREK-Plugins registry enforces that can be answered without a network — which
|
||||
is nearly all of them — and prints the whole journey as a checklist: what passes, what does not,
|
||||
what is still to come, and the ONE command to run next.
|
||||
|
||||
It never fails. It is for orientation, not for gating; \`validate\` is the gate. Run it as often as
|
||||
you like.`,
|
||||
},
|
||||
|
||||
publish: {
|
||||
summary: 'release + open the registry PR',
|
||||
usage: 'trek-plugin publish [dir] --repo <owner/name> --tag <vX.Y.Z> [--sign]',
|
||||
body: `The whole release, in order:
|
||||
|
||||
1. check every registry gate that can be checked locally
|
||||
2. pack build plugin.zip
|
||||
3. release git tag, push, and cut the GitHub release with the artifact
|
||||
4. preflight the gates that need the tag and the release to exist
|
||||
5. submit open the PR against the TREK-Plugins registry
|
||||
|
||||
Step 1 comes first for a reason: a GitHub release is effectively immutable, because the registry
|
||||
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.
|
||||
|
||||
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
|
||||
back: once a plugin has shipped signed, TREK refuses an unsigned update to it. So back the key up.
|
||||
Scripts are never prompted; pass --sign.
|
||||
|
||||
Needs git and an authenticated \`gh\`.
|
||||
|
||||
--sign [key] sign the artifact (default key: ~/.trek-plugin/signing.key)
|
||||
--registry o/n a registry other than liketrek/TREK-Plugins
|
||||
--notes release notes
|
||||
--draft open the registry PR as a draft
|
||||
--force overwrite an existing release's artifact. Breaks the sha256 pin for
|
||||
everyone who already installed that version — only for a release that
|
||||
was never merged into the registry.
|
||||
--no-checks skip step 1. An escape hatch for a re-run; never right on a first publish.
|
||||
--no-preflight skip step 4.`,
|
||||
},
|
||||
|
||||
validate: {
|
||||
summary: 'check it against the registry gates',
|
||||
usage: 'trek-plugin validate [dir]',
|
||||
body: `The gate. Runs the same offline checks as \`status\` and exits non-zero if any of them would
|
||||
be rejected by the registry. This is the form for scripts and CI; \`status\` is the form for humans.
|
||||
|
||||
A plugin that passes \`validate\` will pass every registry gate that does not require the tag and
|
||||
the release to exist. Those four run in \`preflight\`.`,
|
||||
},
|
||||
|
||||
pack: {
|
||||
summary: 'build plugin.zip',
|
||||
usage: 'trek-plugin pack [dir] [--out plugin.zip] [--json]',
|
||||
body: `Builds the exact plugin.zip the TREK installer expects, and prints its sha256 and byte size.
|
||||
|
||||
It refuses to pack a plugin that could not LOAD — a broken manifest, a missing server entry, a
|
||||
native binary. It does not enforce the registry's publish gates (an unwritten README, a missing
|
||||
screenshot), because packing is how you install a plugin into a local TREK to try it, and the docs
|
||||
only matter when you ship.
|
||||
|
||||
--json the PackResult on stdout, for scripts`,
|
||||
},
|
||||
|
||||
shot: {
|
||||
summary: 'capture docs/screenshot.png',
|
||||
usage: 'trek-plugin shot [dir] [--port 4317] [--out docs/screenshot.png] [--dark] [--no-serve]',
|
||||
body: `Boots the dev server, renders your plugin in the themed frame TREK uses, and writes a 1600×900
|
||||
docs/screenshot.png.
|
||||
|
||||
The registry requires a screenshot that resolves to a real image, and the store card shows it. This
|
||||
is the fastest way to have one.
|
||||
|
||||
Needs Playwright, which is NOT a dependency of this SDK (it ships a browser):
|
||||
|
||||
npm i -D playwright && npx playwright install chromium
|
||||
|
||||
An \`integration\` plugin has no UI to render, so \`shot\` cannot help — screenshot the TREK surface
|
||||
your plugin changes instead.
|
||||
|
||||
--dark render in TREK's dark theme
|
||||
--no-serve shoot a dev server you are already running`,
|
||||
},
|
||||
|
||||
keygen: {
|
||||
summary: 'create an Ed25519 signing key',
|
||||
usage: 'trek-plugin keygen [--key file]',
|
||||
body: `Generates a signing key at ~/.trek-plugin/signing.key. One key for all your plugins.
|
||||
|
||||
BACK IT UP. Signing is a one-way door: once a plugin has shipped signed, TREK refuses an unsigned
|
||||
update — and one signed with a different key — on every instance that already has it. Losing the
|
||||
key means you cannot ship an update to your own plugin without a maintainer override.`,
|
||||
},
|
||||
|
||||
sign: {
|
||||
summary: 'print a signature for an artifact',
|
||||
usage: 'trek-plugin sign [zip] [--key file]',
|
||||
body: 'Prints the signature and public key for an artifact. Usually you want `publish --sign` instead.',
|
||||
},
|
||||
|
||||
entry: {
|
||||
summary: 'print the registry entry JSON',
|
||||
usage: 'trek-plugin entry --repo <owner/name> --tag <vX.Y.Z> [--zip plugin.zip] [--merge entry.json] [--out file]',
|
||||
body: `Builds the TREK-Plugins registry entry from your manifest, your packed artifact and your git tag —
|
||||
so the sha256, size, commitSha and downloadUrl all come out of one command instead of being
|
||||
computed by hand.
|
||||
|
||||
\`publish\` does this for you. Reach for it directly only when you are assembling a PR by hand.
|
||||
|
||||
--merge entry.json prepend this version onto an existing entry (the update case)
|
||||
--sign [key] sign the artifact and pin the author key
|
||||
--out file write it instead of printing it`,
|
||||
},
|
||||
|
||||
preflight: {
|
||||
summary: 'run the registry CI checks locally',
|
||||
usage: 'trek-plugin preflight [dir] --repo <owner/name> --tag <vX.Y.Z> [--entry file.json] [--all]',
|
||||
body: `Runs the registry's checks — including the ones that need the network: that your tag resolves to
|
||||
the commit the entry pins, that the released artifact downloads and hashes to the pinned sha256,
|
||||
that your plugin id is not bound to another GitHub owner, and that an update does not drop or
|
||||
rotate a signing key you already published under.
|
||||
|
||||
\`publish\` runs this for you as step 4. Reach for it directly to check an entry you assembled by
|
||||
hand, or to re-check a release you have already cut.
|
||||
|
||||
--all check every version in the entry, not just the newest`,
|
||||
},
|
||||
|
||||
submit: {
|
||||
summary: 'open the registry PR',
|
||||
usage: 'trek-plugin submit [dir] --repo <owner/name> --tag <vX.Y.Z> [--registry o/n] [--draft]',
|
||||
body: `Forks the registry, writes registry/plugins/<id>.json, and opens the PR. Needs an authenticated
|
||||
\`gh\`. \`publish\` does this for you as step 5.`,
|
||||
},
|
||||
|
||||
release: {
|
||||
summary: 'pack + cut the GitHub release',
|
||||
usage: 'trek-plugin release [dir] --repo <owner/name> --tag <vX.Y.Z> [--sign] [--merge entry.json]',
|
||||
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.`,
|
||||
},
|
||||
};
|
||||
|
||||
export function topLevelHelp(version: string): string {
|
||||
const pad = (s: string) => s.padEnd(9);
|
||||
const path = PATH_COMMANDS.map((c) => ` ${pad(c)} ${COMMAND_HELP[c].summary}`).join('\n');
|
||||
return `${VERSION_LINE(version)} — build a plugin for TREK
|
||||
|
||||
The path
|
||||
${path}
|
||||
|
||||
Also: ${OTHER_COMMANDS.join(' ')}
|
||||
\`trek-plugin help <command>\` for any of them
|
||||
|
||||
New here? trek-plugin create
|
||||
Lost? trek-plugin status`;
|
||||
}
|
||||
|
||||
export function commandHelp(command: string): string | undefined {
|
||||
const h = COMMAND_HELP[command];
|
||||
if (!h) return undefined;
|
||||
return `${h.usage}\n\n${h.body}`;
|
||||
}
|
||||
@@ -12,23 +12,30 @@ export interface MenuItem {
|
||||
hint: string;
|
||||
}
|
||||
|
||||
/** The everyday author journey. `advanced`/`exit` are control entries. */
|
||||
/**
|
||||
* The path, in the order you walk it — create, then dev, then status, then publish. The menu is
|
||||
* often the first thing a new author ever sees, so its ORDER is the only documentation some of
|
||||
* them will read. `validate` and `pack` moved to Advanced: `status` says everything `validate`
|
||||
* says and tells you what to do about it, and `publish` packs for you.
|
||||
*/
|
||||
export const PRIMARY_MENU: MenuItem[] = [
|
||||
{ value: 'create', label: 'Create a plugin', hint: 'Scaffold a new plugin' },
|
||||
{ value: 'dev', label: 'Run the dev server', hint: 'Live-reload your plugin locally' },
|
||||
{ value: 'validate', label: 'Validate', hint: 'Check the manifest + layout' },
|
||||
{ value: 'pack', label: 'Pack', hint: 'Build plugin.zip' },
|
||||
{ value: 'publish', label: 'Publish', hint: 'Release + open the registry PR' },
|
||||
{ value: 'advanced', label: 'Advanced…', hint: 'Signing, registry entry, preflight' },
|
||||
{ value: 'status', label: 'Status', hint: "Where am I? What's left before I can publish?" },
|
||||
{ value: 'shot', label: 'Screenshot', hint: 'Capture docs/screenshot.png (the registry needs one)' },
|
||||
{ value: 'publish', label: 'Publish', hint: 'Check → release → open the registry PR' },
|
||||
{ value: 'advanced', label: 'Advanced…', hint: 'Validate, pack, signing, registry entry' },
|
||||
{ value: 'exit', label: 'Exit', hint: '' },
|
||||
];
|
||||
|
||||
/** The less-common signing/registry commands, behind the `advanced` entry. */
|
||||
/** Real commands, just not ones you need in order to publish a plugin. */
|
||||
export const ADVANCED_MENU: MenuItem[] = [
|
||||
{ value: 'validate', label: 'Validate', hint: 'The gate: same checks as status, but it exits non-zero' },
|
||||
{ value: 'pack', label: 'Pack', hint: 'Build plugin.zip without releasing it' },
|
||||
{ value: 'keygen', label: 'Generate a signing key', hint: 'Create an Ed25519 signing key' },
|
||||
{ value: 'sign', label: 'Sign an artifact', hint: 'Print a signature + public key' },
|
||||
{ value: 'entry', label: 'Registry entry', hint: 'Print the ready-to-PR registry JSON' },
|
||||
{ value: 'preflight', label: 'Preflight', hint: 'Run the registry CI checks locally' },
|
||||
{ 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: 'back', label: '← Back', hint: '' },
|
||||
|
||||
@@ -13,7 +13,9 @@ import path from 'node:path';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { makeZip, type ZipInput } from '../zip.js';
|
||||
import { injectTrekUi } from '../ui/kit.js';
|
||||
import { validatePluginDir } from './validate.js';
|
||||
import { loadContext } from './checks/context.js';
|
||||
import { runOffline } from './checks/index.js';
|
||||
import { blocking } from './checks/types.js';
|
||||
|
||||
const MAX_TOTAL = 50 * 1024 * 1024;
|
||||
const MAX_FILE = 25 * 1024 * 1024;
|
||||
@@ -56,8 +58,18 @@ function walk(base: string, rel: string, out: ZipInput[]): void {
|
||||
}
|
||||
|
||||
export function packPluginDir(dir: string, outPath: string): PackResult {
|
||||
const report = validatePluginDir(dir);
|
||||
if (!report.ok) throw new Error('plugin is not valid:\n - ' + report.errors.join('\n - '));
|
||||
// Only the gates that make a plugin UNBUILDABLE — a broken manifest, no server entry, a native
|
||||
// binary. Not the registry's publish gates: packing is how you install a plugin into a local
|
||||
// TREK to try it, and refusing to build a zip because the README is still a stub would block
|
||||
// the dev loop over something that only matters at publish time. `validate`/`status`/`publish`
|
||||
// apply the full set; see checks/types.ts, CheckBlocks.
|
||||
const report = blocking(runOffline(loadContext(dir)), 'artifact');
|
||||
if (!report.ok) {
|
||||
throw new Error(
|
||||
'plugin is not valid:\n - ' +
|
||||
report.errors.map((e) => (e.detail ? `${e.title} — ${e.detail}` : e.title)).join('\n - '),
|
||||
);
|
||||
}
|
||||
|
||||
const outAbs = path.resolve(outPath);
|
||||
const files: ZipInput[] = [];
|
||||
|
||||
+42
-157
@@ -1,169 +1,54 @@
|
||||
/**
|
||||
* trek-plugin preflight — run the registry CI checks locally, over the network,
|
||||
* BEFORE you open a PR. It mirrors TREK-Plugins' validate-entry.mjs (tag→commit,
|
||||
* manifest parity, artifact sha256/size, native-binary scan) and check-readme.mjs
|
||||
* (required sections, real prose, a resolving screenshot, permission parity), so
|
||||
* you catch what CI would reject without a round-trip through review.
|
||||
* trek-plugin preflight — run the registry's CI checks locally, BEFORE you open a PR.
|
||||
*
|
||||
* Dependency-free: global fetch + Node built-ins + our own zip reader.
|
||||
* This used to be the ONLY place the registry's real rules were applied, which made it the place
|
||||
* authors discovered their README was unwritten — over the network, against a pushed tag, after
|
||||
* an immutable GitHub release had been cut. The rules now live in ./checks/ and most of them fire
|
||||
* offline from `status` and `validate`, long before any of that. What preflight adds is the last
|
||||
* mile: the things that can only be known once the tag, the release and the registry exist.
|
||||
*
|
||||
* The contract has not changed, and now covers the whole check registry:
|
||||
* A GATE THE REGISTRY HAS AND WE DON'T IS A FALSE GREEN, and an author trusts a green.
|
||||
* test/checks-parity.test.ts is what keeps this honest.
|
||||
*/
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { listZipNames } from '../zip.js';
|
||||
import { loadContext } from './checks/context.js';
|
||||
import { runAll } from './checks/index.js';
|
||||
import type { RegistryEntry } from './checks/types.js';
|
||||
|
||||
const REQUIRED_HEADINGS = ['what it does', 'screenshots', 'permissions', 'setup'];
|
||||
const PLACEHOLDER_RE = [/\{\{[^}]*\}\}/, /\bREPLACE_ME\b/i, /\bDescribe (what|the)\b/i, /\byour-name\/trek-plugin/i];
|
||||
const MIN_PROSE = 400;
|
||||
const NATIVE_RE = /(^|\/)[^/]+\.node$|(^|\/)binding\.gyp$|(^|\/)prebuilds?\//i;
|
||||
export type { RegistryEntry as Entry, RegistryEntryVersion as EntryVersion } from './checks/types.js';
|
||||
|
||||
export interface EntryVersion {
|
||||
version: string; gitTag: string; commitSha: string; downloadUrl: string;
|
||||
sha256: string; size: number; apiVersion: number; nativeModules?: boolean; operatorEgress?: boolean; signature?: string;
|
||||
}
|
||||
export interface Entry {
|
||||
id: string; name: string; type: string; repo: string; authorPublicKey?: string; versions: EntryVersion[];
|
||||
}
|
||||
export interface PreflightReport { ok: boolean; failures: string[]; passed: string[]; }
|
||||
|
||||
function ghToken(): string | undefined {
|
||||
if (process.env.GITHUB_TOKEN) return process.env.GITHUB_TOKEN;
|
||||
try { return execFileSync('gh', ['auth', 'token'], { encoding: 'utf8' }).trim() || undefined; } catch { return undefined; }
|
||||
export interface PreflightReport {
|
||||
ok: boolean;
|
||||
failures: string[];
|
||||
passed: string[];
|
||||
}
|
||||
|
||||
function raw(repo: string, sha: string, p: string): string {
|
||||
return `https://raw.githubusercontent.com/${repo}/${sha}/${p.replace(/^\.?\//, '')}`;
|
||||
export interface PreflightOptions {
|
||||
/** Check every version in the entry, not just the newest. */
|
||||
all?: boolean;
|
||||
/** The plugin directory, for the offline half. Defaults to cwd. */
|
||||
dir?: string;
|
||||
/** Registry repo to check owner binding + signing history against. */
|
||||
registry?: string;
|
||||
/** The exact artifact bytes the entry was built from, when the caller still holds them. */
|
||||
zipBytes?: Buffer;
|
||||
}
|
||||
|
||||
export async function preflight(entry: Entry, opts: { all?: boolean } = {}): Promise<PreflightReport> {
|
||||
const failures: string[] = [];
|
||||
const passed: string[] = [];
|
||||
const fail = (m: string) => failures.push(m);
|
||||
const ok = (m: string) => passed.push(m);
|
||||
/** Flatten a check outcome into the one-line strings this command has always printed. */
|
||||
const line = (o: { title: string; detail?: string; fix?: string }): string =>
|
||||
(o.detail ? `${o.title} — ${o.detail}` : o.title) + (o.fix ? '\n' + o.fix.split('\n').map((l) => ' ' + l).join('\n') : '');
|
||||
|
||||
const token = ghToken();
|
||||
const ghHeaders: Record<string, string> = { 'User-Agent': 'trek-plugin-preflight', Accept: 'application/vnd.github+json' };
|
||||
if (token) ghHeaders.Authorization = `Bearer ${token}`;
|
||||
export async function preflight(entry: RegistryEntry, opts: PreflightOptions = {}): Promise<PreflightReport> {
|
||||
const ctx = loadContext(opts.dir ?? '.', { entry, zipBytes: opts.zipBytes });
|
||||
ctx.registry = opts.registry;
|
||||
ctx.allVersions = opts.all;
|
||||
|
||||
// Structural checks that mirror the registry schema (fast, offline).
|
||||
if (!/^[a-z][a-z0-9-]{2,39}$/.test(entry.id)) fail(`id "${entry.id}" is not a valid slug (^[a-z][a-z0-9-]{2,39}$)`);
|
||||
if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(entry.repo)) fail(`repo "${entry.repo}" is not "owner/name"`);
|
||||
if (!['integration', 'page', 'widget', 'trip-page'].includes(entry.type)) fail(`type "${entry.type}" is not integration|page|widget|trip-page`);
|
||||
if (entry.authorPublicKey && !entry.versions[0]?.signature) fail('entry has authorPublicKey but the newest version has no signature (sign the version too)');
|
||||
|
||||
const versions = opts.all ? entry.versions : entry.versions.slice(0, 1);
|
||||
for (const v of versions) {
|
||||
const tag = `${v.version}`;
|
||||
// 1. tag exists and resolves to commitSha
|
||||
try {
|
||||
const r = await fetch(`https://api.github.com/repos/${entry.repo}/git/refs/tags/${encodeURIComponent(v.gitTag)}`, { headers: ghHeaders });
|
||||
if (!r.ok) fail(`${tag}: tag ${v.gitTag} not found on GitHub (${r.status}) — push the tag and create the release`);
|
||||
else {
|
||||
const ref = (await r.json()) as { object?: { sha?: string; type?: string } };
|
||||
let sha = ref.object?.sha;
|
||||
if (ref.object?.type === 'tag' && sha) {
|
||||
const tr = await fetch(`https://api.github.com/repos/${entry.repo}/git/tags/${sha}`, { headers: ghHeaders });
|
||||
if (tr.ok) sha = ((await tr.json()) as { object?: { sha?: string } }).object?.sha;
|
||||
}
|
||||
if (sha && sha !== v.commitSha) fail(`${tag}: tag ${v.gitTag} points at ${sha.slice(0, 8)}, entry pins ${v.commitSha.slice(0, 8)}`);
|
||||
else if (sha) ok(`${tag}: tag resolves to the pinned commit`);
|
||||
}
|
||||
} catch (e) { fail(`${tag}: tag check failed: ${(e as Error).message}`); }
|
||||
|
||||
// 2. manifest parity at the pinned commit (+ collect permissions for the README gate)
|
||||
let manifestPerms: string[] = [];
|
||||
try {
|
||||
const mr = await fetch(raw(entry.repo, v.commitSha, 'trek-plugin.json'), { headers: { 'User-Agent': 'trek-plugin-preflight' } });
|
||||
if (!mr.ok) fail(`${tag}: trek-plugin.json not found at ${v.commitSha.slice(0, 8)} (${mr.status})`);
|
||||
else {
|
||||
const m = JSON.parse(await mr.text()) as Record<string, unknown>;
|
||||
if (m.id !== entry.id) fail(`${tag}: manifest id "${m.id}" != entry id "${entry.id}"`);
|
||||
if (m.version !== v.version) fail(`${tag}: manifest version "${m.version}" != entry "${v.version}"`);
|
||||
if (m.type !== entry.type) fail(`${tag}: manifest type "${m.type}" != entry "${entry.type}"`);
|
||||
if (m.apiVersion !== v.apiVersion) fail(`${tag}: manifest apiVersion ${m.apiVersion} != entry ${v.apiVersion}`);
|
||||
if (m.nativeModules === true) fail(`${tag}: manifest declares nativeModules:true (forbidden)`);
|
||||
// Mirrors the registry's operatorEgress parity check (validate-entry.mjs): the entry
|
||||
// must not understate the plugin's network reach.
|
||||
const mOperatorEgress = (m as { operatorEgress?: unknown }).operatorEgress === true;
|
||||
if (mOperatorEgress !== (v.operatorEgress === true)) {
|
||||
fail(`${tag}: manifest operatorEgress ${mOperatorEgress} != entry ${v.operatorEgress === true}`);
|
||||
}
|
||||
manifestPerms = Array.isArray(m.permissions) ? (m.permissions as string[]) : [];
|
||||
if (manifestPerms.some((p) => p === 'http:outbound' || p.startsWith('http:outbound:'))) {
|
||||
const egress = Array.isArray(m.egress) ? (m.egress as string[]) : [];
|
||||
// Empty egress[] is legal only with operatorEgress (hosts are admin-supplied).
|
||||
if (!egress.length && !mOperatorEgress) {
|
||||
fail(`${tag}: http:outbound declared but egress[] is empty (set operatorEgress: true if the hosts are admin-supplied)`);
|
||||
}
|
||||
if (egress.includes('*')) fail(`${tag}: egress[] must not contain a bare "*"`);
|
||||
}
|
||||
if (!failures.some((f) => f.startsWith(`${tag}: manifest`))) ok(`${tag}: manifest at commit matches the entry`);
|
||||
}
|
||||
} catch (e) { fail(`${tag}: manifest parity failed: ${(e as Error).message}`); }
|
||||
|
||||
// 3. artifact download → sha256 + size + native-binary scan
|
||||
try {
|
||||
const dr = await fetch(v.downloadUrl, { redirect: 'follow', headers: { 'User-Agent': 'trek-plugin-preflight' } });
|
||||
if (!dr.ok) fail(`${tag}: artifact download failed (${dr.status}) ${v.downloadUrl}`);
|
||||
else {
|
||||
const bytes = Buffer.from(await dr.arrayBuffer());
|
||||
if (bytes.length > v.size + 4096) fail(`${tag}: artifact (${bytes.length}B) larger than declared size (${v.size}B)`);
|
||||
const sha = createHash('sha256').update(bytes).digest('hex');
|
||||
if (sha !== v.sha256) fail(`${tag}: sha256 mismatch — release has ${sha.slice(0, 12)}…, entry pins ${v.sha256.slice(0, 12)}… (re-pack + re-upload?)`);
|
||||
else ok(`${tag}: artifact sha256 matches the release`);
|
||||
let names: string[] = [];
|
||||
try { names = bytes[0] === 0x50 && bytes[1] === 0x4b ? listZipNames(bytes) : []; } catch { /* not a zip */ }
|
||||
if (names.some((n) => NATIVE_RE.test(n))) fail(`${tag}: artifact contains native binaries (.node / binding.gyp / prebuilds)`);
|
||||
}
|
||||
} catch (e) { fail(`${tag}: artifact check failed: ${(e as Error).message}`); }
|
||||
|
||||
// 4. README quality gate at the pinned commit (mirrors check-readme.mjs)
|
||||
await readmeGate(entry.repo, v.commitSha, manifestPerms, tag, fail, ok);
|
||||
}
|
||||
|
||||
return { ok: failures.length === 0, failures, passed };
|
||||
}
|
||||
|
||||
async function readmeGate(repo: string, sha: string, perms: string[], tag: string, fail: (m: string) => void, ok: (m: string) => void): Promise<void> {
|
||||
let md: string;
|
||||
try {
|
||||
const r = await fetch(raw(repo, sha, 'README.md'), { headers: { 'User-Agent': 'trek-plugin-preflight' } });
|
||||
if (!r.ok) { fail(`${tag}: README.md missing at the repo root (${r.status})`); return; }
|
||||
md = await r.text();
|
||||
} catch (e) { fail(`${tag}: README fetch failed: ${(e as Error).message}`); return; }
|
||||
|
||||
const headings = [...md.matchAll(/^#{1,6}\s+(.+?)\s*$/gm)].map((m) => m[1].toLowerCase());
|
||||
for (const h of REQUIRED_HEADINGS) if (!headings.some((got) => got.includes(h))) fail(`${tag}: README missing required section "## ${h}"`);
|
||||
for (const re of PLACEHOLDER_RE) { const hit = md.match(re); if (hit) fail(`${tag}: README still has a template placeholder "${hit[0]}"`); }
|
||||
|
||||
const prose = md
|
||||
.replace(/<!--[\s\S]*?-->/g, '').replace(/```[\s\S]*?```/g, '')
|
||||
.replace(/!\[[^\]]*\]\([^)]*\)/g, '').replace(/\[[^\]]*\]\([^)]*\)/g, '')
|
||||
.replace(/^#{1,6}\s+.*$/gm, '').replace(/^\s*\|.*$/gm, '')
|
||||
.replace(/[#>*_`|-]/g, '').replace(/\s+/g, ' ').trim();
|
||||
if (prose.length < MIN_PROSE) fail(`${tag}: README has too little prose (${prose.length} chars, need ≥ ${MIN_PROSE})`);
|
||||
|
||||
const imgs = [
|
||||
...[...md.matchAll(/!\[[^\]]*\]\(\s*([^)\s]+)/g)].map((m) => m[1]),
|
||||
...[...md.matchAll(/<img[^>]+src\s*=\s*["']([^"']+)["']/gi)].map((m) => m[1]),
|
||||
].filter((u) => !u.startsWith('data:'));
|
||||
if (!imgs.length) fail(`${tag}: README has no screenshot (at least one image required)`);
|
||||
else {
|
||||
let anyOk = false;
|
||||
for (const src of [...new Set(imgs)]) {
|
||||
const url = /^https?:\/\//.test(src)
|
||||
? (src.includes('github.com') && src.includes('/blob/') ? src.replace('github.com', 'raw.githubusercontent.com').replace('/blob/', '/') : src)
|
||||
: raw(repo, sha, src);
|
||||
try {
|
||||
const r = await fetch(url, { headers: { 'User-Agent': 'trek-plugin-preflight', Range: 'bytes=0-2047' } });
|
||||
if (r.ok && (r.headers.get('content-type') || '').startsWith('image/')) { anyOk = true; break; }
|
||||
} catch { /* try next */ }
|
||||
}
|
||||
if (!anyOk) fail(`${tag}: no README screenshot resolved to a real image at the pinned commit`);
|
||||
else ok(`${tag}: README screenshot resolves`);
|
||||
}
|
||||
|
||||
const lower = md.toLowerCase();
|
||||
const undocumented = perms.filter((p) => !lower.includes(p.toLowerCase()));
|
||||
if (undocumented.length) fail(`${tag}: permissions not explained in the README: ${undocumented.join(', ')}`);
|
||||
else if (perms.length) ok(`${tag}: all permissions documented`);
|
||||
const report = await runAll(ctx);
|
||||
return {
|
||||
ok: report.ok,
|
||||
// Warnings are surfaced by `status`/`validate`; preflight reports only what would REJECT the
|
||||
// entry, because its whole promise is "this will get through CI".
|
||||
failures: report.errors.map(line),
|
||||
passed: report.outcomes.filter((o) => o.status === 'pass').map((o) => (o.detail ? `${o.title} — ${o.detail}` : o.title)),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,19 +1,31 @@
|
||||
/**
|
||||
* trek-plugin publish — the whole release in one command: pack → tag + GitHub
|
||||
* release → preflight (the registry CI checks, locally) → open the registry PR.
|
||||
* If preflight fails it stops before submitting, so a broken entry never becomes
|
||||
* a doomed PR. This is the short path; the individual commands still exist for
|
||||
* when you want a step by hand.
|
||||
* trek-plugin publish — the whole release in one command:
|
||||
* check → pack → tag + GitHub release → preflight → open the registry PR.
|
||||
*
|
||||
* THE ORDER IS THE POINT. It used to be pack → release → preflight → submit, which meant the
|
||||
* checks that catch an unwritten README or a missing screenshot ran AFTER the GitHub release had
|
||||
* been cut. A release is immutable in every way that matters — the registry pins its sha256, so
|
||||
* overwriting the bytes breaks the checksum for everyone who already installed it — and so an
|
||||
* author who failed preflight was stuck: their v1.0.0 tag was burned, and the fix was to throw it
|
||||
* away and cut a v1.0.1 whose only change was the README.
|
||||
*
|
||||
* Now step 1 runs every gate that can be answered from the working tree, and NOTHING is packed,
|
||||
* tagged, pushed or released until they all pass. Preflight still runs (step 4) because the last
|
||||
* few gates genuinely need the tag and the release to exist — but by then it is checking things
|
||||
* that are true by construction, not discovering that the README was never written.
|
||||
*
|
||||
* Requires `git` + `gh` (authenticated), same as `release`/`submit`.
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { packPluginDir } from './pack.js';
|
||||
import { buildEntry } from './entry.js';
|
||||
import { preflight } from './preflight.js';
|
||||
import { submitEntry } from './submit.js';
|
||||
import { loadContext } from './checks/context.js';
|
||||
import { runOffline } from './checks/index.js';
|
||||
import { renderPlain } from './checks/report.js';
|
||||
import { assertSigningAllowed, inspectSigning, type SigningState } from './signing.js';
|
||||
import { plainLog, type LogSink } from './ui.js';
|
||||
|
||||
function git(dir: string, args: string[], quiet = true): string {
|
||||
@@ -22,53 +34,112 @@ function git(dir: string, args: string[], quiet = true): string {
|
||||
function tagExists(dir: string, tag: string): boolean {
|
||||
try { git(dir, ['rev-parse', `${tag}^{commit}`]); return true; } 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; }
|
||||
}
|
||||
|
||||
export async function publishPlugin(opts: {
|
||||
dir: string; repo: string; tag: string; now: string;
|
||||
signKeyPath?: string; registry?: string; draft?: boolean; notes?: string; skipPreflight?: boolean;
|
||||
/** Overwrite the artifact on an existing release. Only safe if it was never merged. */
|
||||
force?: boolean;
|
||||
/** Skip the local gates. An escape hatch for a re-run, never a good idea on a first publish. */
|
||||
skipChecks?: 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.
|
||||
*/
|
||||
signing?: SigningState;
|
||||
/** Progress sink. Defaults to the plain console.error lines (CI parity). */
|
||||
log?: LogSink;
|
||||
}): Promise<{ prUrl: string }> {
|
||||
const dir = path.resolve(opts.dir);
|
||||
const log = opts.log ?? plainLog;
|
||||
const step = (n: number, msg: string) => log(`[${n}/4] ${msg}`);
|
||||
const step = (n: number, msg: string) => log(`[${n}/5] ${msg}`);
|
||||
|
||||
// 1. Pack
|
||||
step(1, 'Packing the artifact…');
|
||||
// 1. The local gates — BEFORE anything is packed, tagged or released.
|
||||
if (opts.skipChecks) {
|
||||
log('[1/5] Local checks skipped (--no-checks).');
|
||||
} else {
|
||||
step(1, 'Checking the plugin against the registry gates…');
|
||||
const ctx = loadContext(dir);
|
||||
const report = runOffline(ctx);
|
||||
if (!report.ok) {
|
||||
const detail = renderPlain({ ...report, warnings: [] });
|
||||
throw new Error(
|
||||
`${report.errors.length} check${report.errors.length === 1 ? '' : 's'} would be rejected by the registry.\n\n` +
|
||||
detail +
|
||||
'\n\nNothing was packed, tagged or released. Fix these and re-run — or `trek-plugin status` for the full picture.',
|
||||
);
|
||||
}
|
||||
|
||||
// Signing is not just a preference once a plugin has shipped signed: TREK refuses an unsigned
|
||||
// update to it, so this publish is doomed. preflight would catch it — at step 4, AFTER the
|
||||
// immutable release is cut, which is precisely the trap this command's reorder exists to close.
|
||||
// So it belongs here, before anything exists to be wasted.
|
||||
const id = typeof ctx.manifest?.id === 'string' ? ctx.manifest.id : '';
|
||||
if (id) {
|
||||
assertSigningAllowed(opts.signing ?? (await inspectSigning(id, { registry: opts.registry })), opts.signKeyPath);
|
||||
}
|
||||
|
||||
log(` ✓ ${report.outcomes.filter((o) => o.status === 'pass').length} checks passed`);
|
||||
}
|
||||
|
||||
// 2. Pack
|
||||
step(2, 'Packing the artifact…');
|
||||
const zip = path.join(dir, 'plugin.zip');
|
||||
const packed = packPluginDir(dir, zip);
|
||||
log(` ✓ ${packed.files.length} files, ${packed.size} bytes`);
|
||||
|
||||
// 2. Tag (if needed) + push + GitHub release with the artifact attached
|
||||
step(2, `Tagging ${opts.tag} + creating the GitHub release…`);
|
||||
// 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 {
|
||||
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})`);
|
||||
}
|
||||
try {
|
||||
execFileSync('gh', ['release', 'create', opts.tag, packed.artifact, '--repo', opts.repo, '--title', opts.tag, '--notes', opts.notes || `Release ${opts.tag}`], { stdio: 'pipe' });
|
||||
} catch {
|
||||
// Release already exists — (re)upload the packed artifact so its bytes match the pin.
|
||||
// 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 (!opts.force) {
|
||||
throw new Error(
|
||||
`release ${opts.tag} already exists on ${opts.repo}.\n` +
|
||||
`Overwriting a released artifact breaks the sha256 pin for everyone who already installed it.\n` +
|
||||
`Cut a new version, or pass --force if this release was never merged into the registry.`,
|
||||
);
|
||||
}
|
||||
log(` ! release ${opts.tag} exists — overwriting the artifact (--force)`);
|
||||
execFileSync('gh', ['release', 'upload', opts.tag, packed.artifact, '--repo', opts.repo, '--clobber'], { stdio: 'pipe' });
|
||||
} else {
|
||||
execFileSync('gh', ['release', 'create', opts.tag, packed.artifact, '--repo', opts.repo, '--title', opts.tag, '--notes', opts.notes || `Release ${opts.tag}`], { stdio: 'pipe' });
|
||||
}
|
||||
log(` ✓ release ${opts.tag} on ${opts.repo}`);
|
||||
|
||||
// 3. Build the entry, then run the registry CI checks locally
|
||||
// 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('[3/4] Preflight skipped (--no-preflight).');
|
||||
log('[4/5] Preflight skipped (--no-preflight).');
|
||||
} else {
|
||||
step(3, 'Preflight — running the registry CI checks…');
|
||||
const rep = await preflight(entry);
|
||||
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) — fix these and re-run (nothing was submitted). Did you push your code to ${opts.repo} before publishing?`);
|
||||
if (!rep.ok) {
|
||||
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?`,
|
||||
);
|
||||
}
|
||||
log(` ✓ all ${rep.passed.length} checks passed`);
|
||||
}
|
||||
|
||||
// 4. Open the registry PR
|
||||
step(4, 'Opening the registry PR…');
|
||||
// 5. Open the registry PR
|
||||
step(5, 'Opening the registry PR…');
|
||||
const { prUrl } = submitEntry(entry, { registry: opts.registry, draft: opts.draft });
|
||||
log(' ✓ done');
|
||||
fs.rmSync(zip, { force: true });
|
||||
// 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 };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
/**
|
||||
* trek-plugin shot — capture docs/screenshot.png.
|
||||
*
|
||||
* The screenshot is the one registry gate an author cannot fake, cannot satisfy by writing more
|
||||
* words, and — until now — could not do anything about from the CLI at all. The scaffold's README
|
||||
* linked `./docs/screenshot.png`, nothing created it, `validate` passed anyway (it only looked for
|
||||
* an image LINK), and the truth arrived from CI after the release was immutable.
|
||||
*
|
||||
* So: boot the dev server, render the plugin in the same themed, sandboxed frame TREK uses
|
||||
* (`/preview`), and write a 1600×900 PNG. One command, and the hardest gate is done.
|
||||
*
|
||||
* Playwright is NOT a dependency of this SDK — it is ~300 MB of browser and most authors never
|
||||
* run this. It is imported lazily, and if it is absent we say exactly how to get it rather than
|
||||
* failing with a module-resolution stack trace.
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import net from 'node:net';
|
||||
import path from 'node:path';
|
||||
import { spawn, type ChildProcess } from 'node:child_process';
|
||||
import { createRequire } from 'node:module';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { readJsonFile } from './json.js';
|
||||
|
||||
/** The store card is 16:9 and crops the edges — 1600×900 leaves margin and stays under a MB. */
|
||||
const WIDTH = 1600;
|
||||
const HEIGHT = 900;
|
||||
|
||||
export interface ShotOptions {
|
||||
port?: number;
|
||||
out?: string;
|
||||
/** Screenshot an already-running dev server instead of booting one. */
|
||||
noServe?: boolean;
|
||||
/** Render in TREK's dark theme instead of light. */
|
||||
dark?: boolean;
|
||||
}
|
||||
|
||||
export class ShotError extends Error {}
|
||||
|
||||
const portOpen = (port: number): Promise<boolean> =>
|
||||
new Promise((resolve) => {
|
||||
const socket = net.connect(port, '127.0.0.1');
|
||||
socket.on('connect', () => { socket.destroy(); resolve(true); });
|
||||
socket.on('error', () => resolve(false));
|
||||
});
|
||||
|
||||
async function waitForPort(port: number, timeoutMs = 30_000): Promise<boolean> {
|
||||
const started = Date.now();
|
||||
while (Date.now() - started < timeoutMs) {
|
||||
if (await portOpen(port)) return true;
|
||||
await new Promise((r) => setTimeout(r, 250));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Playwright, or a message that tells you how to get it.
|
||||
*
|
||||
* Resolved from the PLUGIN's directory first, not ours. A bare `import('playwright')` resolves
|
||||
* relative to this file — which works when the SDK is a devDependency of the plugin (node walks up
|
||||
* into the plugin's node_modules), and silently does not when the SDK is installed globally. The
|
||||
* author would have run exactly the `npm i -D playwright` we told them to and still be told it was
|
||||
* missing. So ask the plugin where its own modules live, and only then fall back to ours.
|
||||
*/
|
||||
async function loadChromium(pluginDir: string): Promise<{ launch: (o?: unknown) => Promise<Chromium> }> {
|
||||
type PW = { chromium: { launch: (o?: unknown) => Promise<Chromium> } };
|
||||
|
||||
const fromPlugin = createRequire(path.join(pluginDir, 'package.json'));
|
||||
for (const resolve of [() => fromPlugin.resolve('playwright'), () => 'playwright']) {
|
||||
try {
|
||||
const specifier = resolve();
|
||||
const pw = (await import(specifier.startsWith('/') ? pathToFileURL(specifier).href : specifier)) as unknown as PW;
|
||||
if (pw.chromium) return pw.chromium;
|
||||
} catch {
|
||||
/* try the next resolution */
|
||||
}
|
||||
}
|
||||
|
||||
throw new ShotError(
|
||||
'trek-plugin shot needs Playwright, which is not installed.\n\n' +
|
||||
' npm i -D playwright && npx playwright install chromium\n\n' +
|
||||
'It is not a dependency of the SDK — it ships a whole browser, and most authors never run this.\n' +
|
||||
'If you would rather not install it: take a 16:9 screenshot yourself (1600×900 is ideal — the\n' +
|
||||
'store card crops the edges) and save it as docs/screenshot.png.',
|
||||
);
|
||||
}
|
||||
|
||||
// Minimal structural types — we never import Playwright's, so it stays a soft dependency.
|
||||
interface Page {
|
||||
goto(url: string, o?: unknown): Promise<unknown>;
|
||||
emulateMedia(o: { colorScheme: 'light' | 'dark' }): Promise<void>;
|
||||
waitForTimeout(ms: number): Promise<void>;
|
||||
screenshot(o: { path: string; fullPage?: boolean }): Promise<unknown>;
|
||||
}
|
||||
interface Browser {
|
||||
newPage(o?: unknown): Promise<Page>;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
type Chromium = Browser;
|
||||
|
||||
export async function runShot(dir: string, opts: ShotOptions = {}): Promise<{ out: string; width: number; height: number }> {
|
||||
const root = path.resolve(dir);
|
||||
const manifestPath = path.join(root, 'trek-plugin.json');
|
||||
if (!fs.existsSync(manifestPath)) throw new ShotError(`no trek-plugin.json in ${dir} — is this a plugin directory?`);
|
||||
|
||||
const manifest = readJsonFile<{ type?: string; id?: string }>(manifestPath);
|
||||
const type = String(manifest.type ?? '');
|
||||
|
||||
// An integration plugin has no UI to render. Refusing outright would be unhelpful — it still
|
||||
// NEEDS a screenshot, it just isn't one we can take. Say what to shoot instead.
|
||||
if (type === 'integration') {
|
||||
throw new ShotError(
|
||||
'An integration plugin has no UI, so there is nothing for the dev server to render.\n\n' +
|
||||
'It still needs a screenshot — the registry requires one and the store card shows it. Capture the\n' +
|
||||
'TREK surface your plugin CHANGES: the notification it sends, the badge it adds to a place, the row\n' +
|
||||
'it contributes to a table, its settings page under Admin → Plugins.\n\n' +
|
||||
'Save it as docs/screenshot.png (16:9, 1600×900 is ideal — the card crops the edges).',
|
||||
);
|
||||
}
|
||||
|
||||
const port = opts.port ?? 4317;
|
||||
const out = path.resolve(root, opts.out ?? path.join('docs', 'screenshot.png'));
|
||||
const chromium = await loadChromium(root);
|
||||
|
||||
let dev: ChildProcess | undefined;
|
||||
let browser: Browser | undefined;
|
||||
try {
|
||||
if (!opts.noServe) {
|
||||
if (await portOpen(port)) {
|
||||
throw new ShotError(
|
||||
`port ${port} is already in use.\n` +
|
||||
`If that is your dev server, pass --no-serve to shoot it. Otherwise pick another port with --port.`,
|
||||
);
|
||||
}
|
||||
// Reuse the real dev server rather than reimplementing the preview frame — a screenshot of
|
||||
// something that isn't what `dev` serves would be worse than no screenshot at all.
|
||||
//
|
||||
// Spawn the CLI, not dev.js: dev.js only EXPORTS runDev, it has no entry block, so running
|
||||
// it as a script imports a module and exits — and the only symptom is a 30-second wait.
|
||||
dev = spawn(process.execPath, [path.join(import.meta.dirname, 'trek-plugin.js'), 'dev', root, '--port', String(port)], {
|
||||
stdio: ['ignore', 'ignore', 'pipe'],
|
||||
});
|
||||
// Keep the child's stderr. If it dies (a plugin that throws on load, a port clash), that
|
||||
// message is the whole diagnosis — swallowing it leaves the author staring at a timeout.
|
||||
let devErr = '';
|
||||
dev.stderr?.on('data', (b: Buffer) => { devErr += b.toString(); });
|
||||
|
||||
if (!(await waitForPort(port))) {
|
||||
throw new ShotError(
|
||||
`the dev server did not come up on port ${port} within 30s.` +
|
||||
(devErr.trim() ? `\n\n${devErr.trim()}` : '\n\nRun `trek-plugin dev` yourself to see why.'),
|
||||
);
|
||||
}
|
||||
} else if (!(await portOpen(port))) {
|
||||
throw new ShotError(`--no-serve was passed but nothing is listening on port ${port}`);
|
||||
}
|
||||
|
||||
browser = await chromium.launch();
|
||||
const page = await browser.newPage({ viewport: { width: WIDTH, height: HEIGHT }, deviceScaleFactor: 2 });
|
||||
await page.emulateMedia({ colorScheme: opts.dark ? 'dark' : 'light' });
|
||||
// chrome=0 strips the dev toolbar and the "runs sandboxed at an opaque origin" note, and
|
||||
// centres the plugin. Without it the store card would show the theme picker of the tool that
|
||||
// took the screenshot, which is not a picture of anybody's plugin.
|
||||
const theme = opts.dark ? 'dark' : 'light';
|
||||
await page.goto(`http://localhost:${port}/preview?chrome=0&theme=${theme}`, { waitUntil: 'networkidle' });
|
||||
// The plugin's own UI loads inside a sandboxed iframe and then fetches. Give it a beat, or we
|
||||
// photograph a skeleton — a screenshot of a loading spinner passes every gate and helps nobody.
|
||||
await page.waitForTimeout(1200);
|
||||
|
||||
fs.mkdirSync(path.dirname(out), { recursive: true });
|
||||
await page.screenshot({ path: out });
|
||||
return { out, width: WIDTH, height: HEIGHT };
|
||||
} finally {
|
||||
await browser?.close().catch(() => {});
|
||||
dev?.kill();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
/**
|
||||
* Signing, proposed rather than buried.
|
||||
*
|
||||
* `keygen` lived under "Advanced…" in the menu and `--sign` was a flag you had to already know
|
||||
* about, so the default path — the one almost everyone takes — shipped unsigned, and nothing
|
||||
* anywhere mentioned that signing existed. That is the wrong default to arrive at by accident,
|
||||
* because of what signing actually means (server registry.service.ts, verifySignatureAndTofu):
|
||||
*
|
||||
* - Unsigned throughout is fine. The sha256 pin is the only guarantee, and TREK accepts it.
|
||||
* - UNSIGNED → SIGNED later is allowed. Nothing is pinned until a signed version installs, so
|
||||
* adding a key at v1.4.0 breaks nobody. Signing late is a real option, not a lost cause.
|
||||
* - SIGNED → UNSIGNED is refused forever (SIGNATURE_MISSING) on every instance that already has
|
||||
* the plugin. And rotating the key needs a registry maintainer override AND an admin re-trust
|
||||
* on every instance.
|
||||
*
|
||||
* So it is a one-way door you may walk through late, but never back out of. That makes the right
|
||||
* prompt an honest recommendation with the consequence attached — not a scare, and not silence.
|
||||
*
|
||||
* The other half of this file is the guard. If a plugin was published signed and you publish
|
||||
* unsigned, the registry refuses it — and `preflight` caught that at step 4, AFTER the immutable
|
||||
* GitHub release was cut. Same trap as the one `publish`'s reorder closed. It belongs in step 1.
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import { defaultKeyPath, generateKeypair } from './sign.js';
|
||||
import { DEFAULT_REGISTRY } from './checks/network.js';
|
||||
import { isInteractive, promptConfirm, note, logWarn, logSuccess } from './ui.js';
|
||||
|
||||
export interface SigningState {
|
||||
/** A signing key exists on this machine. */
|
||||
hasKey: boolean;
|
||||
keyPath: string;
|
||||
/** This plugin is ALREADY PUBLISHED SIGNED — TREK refuses an unsigned update to it. */
|
||||
publishedSigned: boolean;
|
||||
/** The key it was published under, when publishedSigned. */
|
||||
publishedKey?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* What we know about this plugin's signing situation.
|
||||
*
|
||||
* The registry lookup is best-effort: offline, or a registry we cannot read, yields
|
||||
* `publishedSigned: false`. That is the safe direction — we may fail to *insist* on signing, and
|
||||
* preflight still catches it before the PR — but we never wrongly insist on it, which would block
|
||||
* an author who has done nothing wrong.
|
||||
*/
|
||||
export async function inspectSigning(
|
||||
pluginId: string,
|
||||
opts: { registry?: string; keyPath?: string } = {},
|
||||
): Promise<SigningState> {
|
||||
const keyPath = opts.keyPath ?? defaultKeyPath();
|
||||
const state: SigningState = { hasKey: fs.existsSync(keyPath), keyPath, publishedSigned: false };
|
||||
|
||||
const registry = opts.registry ?? DEFAULT_REGISTRY;
|
||||
try {
|
||||
const r = await fetch(`https://raw.githubusercontent.com/${registry}/main/registry/plugins/${pluginId}.json`, {
|
||||
headers: { 'User-Agent': 'trek-plugin' },
|
||||
});
|
||||
if (!r.ok) return state; // not published yet — nothing to be bound by
|
||||
const published = (await r.json()) as { authorPublicKey?: string };
|
||||
if (published.authorPublicKey) {
|
||||
state.publishedSigned = true;
|
||||
state.publishedKey = published.authorPublicKey;
|
||||
}
|
||||
} catch {
|
||||
/* offline, or an unreadable registry — see the doc comment */
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
/**
|
||||
* The guard: refuse to start a publish that is going to be rejected for a signing reason.
|
||||
*
|
||||
* Runs BEFORE anything is packed, tagged or released. Getting this wrong is expensive in a way
|
||||
* most check failures are not: the release is immutable, so an author who learns at step 4 that
|
||||
* their update had to be signed has burned the tag.
|
||||
*/
|
||||
export function assertSigningAllowed(state: SigningState, signKeyPath: string | undefined): void {
|
||||
if (!state.publishedSigned || signKeyPath) return;
|
||||
|
||||
throw new Error(
|
||||
'this plugin was published SIGNED, so this update must be signed too.\n\n' +
|
||||
'TREK pins the author key on first install. An unsigned update to a signed plugin is REFUSED on every\n' +
|
||||
'instance that already has it — publishing this would strand every existing user on the version they have.\n\n' +
|
||||
(state.hasKey
|
||||
? `Re-run with --sign (your key is at ${state.keyPath}).`
|
||||
: `No signing key found at ${state.keyPath}.\n` +
|
||||
'If you have a backup of the key you published with, restore it there. If you have LOST it, the key\n' +
|
||||
'cannot be rotated without a registry maintainer override (the `allow-key-change` label).'),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ask, in a terminal, whether to sign — and create the key if there isn't one.
|
||||
*
|
||||
* Returns the key path to sign with, or undefined to publish unsigned. Only ever called
|
||||
* interactively: a script or CI run that did not pass --sign gets exactly the behaviour it always
|
||||
* got, because prompting a pipeline is how you hang a pipeline.
|
||||
*/
|
||||
export async function proposeSigning(state: SigningState): Promise<string | undefined> {
|
||||
if (!isInteractive()) return undefined;
|
||||
|
||||
// Already published signed: this is not a choice, and pretending it is would be a lie. Say so
|
||||
// and sign. (assertSigningAllowed handles the no-key case with a much longer explanation.)
|
||||
if (state.publishedSigned) {
|
||||
if (!state.hasKey) return undefined; // let the guard produce the real error
|
||||
logWarn('This plugin was published signed — TREK refuses an unsigned update, so this release will be signed.');
|
||||
return state.keyPath;
|
||||
}
|
||||
|
||||
if (state.hasKey) {
|
||||
const sign = await promptConfirm({
|
||||
message: `Sign this release with your key? (${state.keyPath})`,
|
||||
initialValue: true,
|
||||
});
|
||||
return sign ? state.keyPath : undefined;
|
||||
}
|
||||
|
||||
note(
|
||||
'A signature proves the artifact came from YOU, not just that its bytes match what the registry saw.\n' +
|
||||
'TREK pins your key the first time someone installs a signed version, and refuses anything not signed\n' +
|
||||
'with it after that.\n\n' +
|
||||
'It is a one-way door — but you can walk through it late. Publishing unsigned now and signing at v1.4.0\n' +
|
||||
'breaks nobody. Publishing SIGNED and then unsigned breaks everybody.\n\n' +
|
||||
'If you sign: back the key up. Losing it means you cannot ship an update to your own plugin without a\n' +
|
||||
'registry maintainer override.',
|
||||
'Signing',
|
||||
);
|
||||
|
||||
const create = await promptConfirm({
|
||||
message: 'Create a signing key and sign this release? (recommended)',
|
||||
initialValue: true,
|
||||
});
|
||||
if (!create) {
|
||||
logWarn('Publishing unsigned. You can add signing later with `trek-plugin keygen`, and it will break nobody.');
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const { publicKey } = generateKeypair(state.keyPath);
|
||||
logSuccess(`Signing key written to ${state.keyPath}`);
|
||||
note(
|
||||
`${publicKey}\n\n` +
|
||||
'This is your authorPublicKey — it goes into the registry entry, and `publish` puts it there for you.\n' +
|
||||
'BACK UP THE PRIVATE KEY. It is the only thing that can sign an update to this plugin.',
|
||||
'Back this up',
|
||||
);
|
||||
return state.keyPath;
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
/**
|
||||
* trek-plugin status [dir] — where am I, and what do I do next?
|
||||
*
|
||||
* The command an author runs when they are lost, which — before this existed — was most of the
|
||||
* time. It runs every offline gate the registry enforces, prints the whole journey as a
|
||||
* checklist, and names ONE next command.
|
||||
*
|
||||
* It deliberately never exits non-zero. `status` is for orientation; `validate` is the gate. A
|
||||
* command you are afraid to run because it might fail your build is not a command you reach for
|
||||
* when you are stuck.
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { loadContext } from './checks/context.js';
|
||||
import { runOffline } from './checks/index.js';
|
||||
import { renderChecklist, nextStep, summaryLine } from './checks/report.js';
|
||||
|
||||
/** Has this version already been tagged locally? Cheap, offline — no fetch, no API. */
|
||||
function isTagged(dir: string, version: string): boolean {
|
||||
for (const tag of [`v${version}`, version]) {
|
||||
try {
|
||||
execFileSync('git', ['-C', dir, 'rev-parse', `${tag}^{commit}`], { stdio: 'pipe' });
|
||||
return true;
|
||||
} catch {
|
||||
/* not this one */
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Are there uncommitted changes? The registry grades the COMMIT, so a dirty tree is worth saying. */
|
||||
function isDirty(dir: string): boolean {
|
||||
try {
|
||||
return execFileSync('git', ['-C', dir, 'status', '--porcelain'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim().length > 0;
|
||||
} catch {
|
||||
return false; // not a git repo — `publish` will say so far more usefully than we can here
|
||||
}
|
||||
}
|
||||
|
||||
export interface StatusOptions {
|
||||
/** Show passing checks too, not just problems. Defaults to true — the whole point is the map. */
|
||||
verbose?: boolean;
|
||||
colour?: boolean;
|
||||
}
|
||||
|
||||
export function runStatus(dir: string, opts: StatusOptions = {}): { ok: boolean; text: string } {
|
||||
const root = path.resolve(dir);
|
||||
const out: string[] = [];
|
||||
|
||||
if (!fs.existsSync(path.join(root, 'trek-plugin.json'))) {
|
||||
return {
|
||||
ok: false,
|
||||
text:
|
||||
` No plugin here.\n\n ${path.relative(process.cwd(), root) || '.'} has no trek-plugin.json.\n\n` +
|
||||
' next → trek-plugin create',
|
||||
};
|
||||
}
|
||||
|
||||
const ctx = loadContext(root);
|
||||
const report = runOffline(ctx);
|
||||
|
||||
const id = typeof ctx.manifest?.id === 'string' ? ctx.manifest.id : path.basename(root);
|
||||
const type = typeof ctx.manifest?.type === 'string' ? ctx.manifest.type : '?';
|
||||
const version = typeof ctx.manifest?.version === 'string' ? ctx.manifest.version : '?';
|
||||
|
||||
out.push('');
|
||||
out.push(` ${id} · ${type} · v${version}`);
|
||||
out.push(renderChecklist(report, { verbose: opts.verbose ?? true, colour: opts.colour }));
|
||||
|
||||
// Git state is not a "gate" — it is context. A plugin can be perfectly valid and simply not
|
||||
// released yet, and calling that a failure would be a lie.
|
||||
out.push('');
|
||||
out.push(' Repo');
|
||||
out.push(' ' + (isTagged(root, version) ? `· v${version} is tagged locally` : `· v${version} is not tagged yet`));
|
||||
if (isDirty(root)) {
|
||||
out.push(' ! uncommitted changes — the registry grades the COMMIT, not your working tree');
|
||||
}
|
||||
|
||||
const next = nextStep(report);
|
||||
out.push('');
|
||||
out.push(' ' + summaryLine(report));
|
||||
out.push(next.command ? ` next → ${next.command}` : ` next → ${next.hint}`);
|
||||
out.push('');
|
||||
|
||||
return { ok: report.ok, text: out.join('\n') };
|
||||
}
|
||||
@@ -12,7 +12,7 @@ import path from 'node:path';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { readJsonFile } from './json.js';
|
||||
|
||||
const DEFAULT_REGISTRY = 'mauriceboe/TREK-Plugins';
|
||||
const DEFAULT_REGISTRY = 'liketrek/TREK-Plugins';
|
||||
|
||||
interface EntryLike {
|
||||
id: string; name?: string; authorPublicKey?: string;
|
||||
@@ -61,7 +61,10 @@ export function submitEntry(entry: EntryLike, opts: { registry?: string; branch?
|
||||
}
|
||||
if (!cloned) throw new Error(`could not clone your fork ${login}/${name} (is the fork ready on GitHub?)`);
|
||||
|
||||
git(tmp, 'remote', 'add', 'upstream', `https://github.com/${registry}.git`);
|
||||
// `gh repo clone` of a fork may already have wired an `upstream` remote, in which case a
|
||||
// bare `remote add` exits non-zero and takes the whole submit down. Set it either way.
|
||||
try { git(tmp, 'remote', 'add', 'upstream', `https://github.com/${registry}.git`); }
|
||||
catch { git(tmp, 'remote', 'set-url', 'upstream', `https://github.com/${registry}.git`); }
|
||||
git(tmp, 'fetch', '--depth=1', 'upstream', 'main');
|
||||
git(tmp, 'checkout', '-B', branch, 'upstream/main');
|
||||
|
||||
|
||||
@@ -2,36 +2,33 @@
|
||||
/**
|
||||
* `trek-plugin <command>` — the plugin author CLI (#plugins).
|
||||
*
|
||||
* create [name] [--type t] [--interactive] scaffold a plugin (wizard if no name)
|
||||
* dev [dir] [--port 4317] run locally with hot reload
|
||||
* validate [dir] check the manifest + layout
|
||||
* pack [dir] [--out plugin.zip] [--json] build plugin.zip, print sha256 + size
|
||||
* keygen [--key file] create an Ed25519 signing key
|
||||
* sign [zip] [--key file] print a signature + public key for an artifact
|
||||
* entry --repo o/n --tag vX [--zip z] print the ready-to-PR registry entry
|
||||
* [--merge entry.json] [--sign [key]] [--out f]
|
||||
* preflight [dir] --repo o/n --tag vX run the registry CI checks locally
|
||||
* submit [dir] --repo o/n --tag vX open the registry PR for you
|
||||
* [--sign [key]] [--registry o/n] [--draft]
|
||||
* release [dir] --repo o/n --tag vX pack -> gh release -> print entry
|
||||
* [--sign [key]] [--merge entry.json]
|
||||
* publish [dir] --repo o/n --tag vX the lot: pack -> tag+release ->
|
||||
* [--sign [key]] [--no-preflight] preflight -> open the registry PR
|
||||
* This file is the ROUTER, and nothing more: it parses flags, decides interactive vs not, and
|
||||
* hands off. The per-command help lives in ./help.ts (single source of truth, so `--help` and the
|
||||
* docs cannot drift), and the rules every command is judged by live in ./checks/.
|
||||
*
|
||||
* The goal: create -> dev -> publish, and never hand-compute sha256/size/commitSha
|
||||
* or hand-write the registry JSON.
|
||||
* The path is four commands — create → dev → status → publish. The other nine are steps one of
|
||||
* those already does, and are listed under "Also" rather than presented as things you must learn.
|
||||
*
|
||||
* The goal: never hand-compute sha256/size/commitSha, never hand-write the registry JSON, and
|
||||
* never discover a problem after the release that pins it has been cut.
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { validatePluginDir } from './validate.js';
|
||||
import { packPluginDir } from './pack.js';
|
||||
import { buildEntry } from './entry.js';
|
||||
import { scaffold, interactiveScaffold } from './create.js';
|
||||
import { scaffold, interactiveScaffold, nextStepsAfterCreate, type WidgetSlot } from './create.js';
|
||||
import { runDev } from './dev.js';
|
||||
import { runStatus } from './status.js';
|
||||
import { runShot } from './shot.js';
|
||||
import { preflight } from './preflight.js';
|
||||
import { submitEntry } from './submit.js';
|
||||
import { publishPlugin } from './publish.js';
|
||||
import { loadContext } from './checks/context.js';
|
||||
import { runOffline } from './checks/index.js';
|
||||
import { renderPlain } from './checks/report.js';
|
||||
import { topLevelHelp, commandHelp, VERSION_LINE } from './help.js';
|
||||
import { inspectSigning, proposeSigning, type SigningState } from './signing.js';
|
||||
import { generateKeypair, loadPrivateKey, signArtifact, publicKeyBase64, defaultKeyPath } from './sign.js';
|
||||
import { readJsonFile } from './json.js';
|
||||
import {
|
||||
@@ -39,6 +36,7 @@ import {
|
||||
promptText, promptConfirm, clackLogSink, missingArgs,
|
||||
} from './ui.js';
|
||||
import { runMenu } from './menu.js';
|
||||
import { notifySdkUpdate } from './update-notice.js';
|
||||
|
||||
const [cmd, ...args] = process.argv.slice(2);
|
||||
|
||||
@@ -64,6 +62,45 @@ const { flags, pos } = parse(args);
|
||||
|
||||
type Flags = Record<string, string>;
|
||||
|
||||
/**
|
||||
* Every flag each command reads. `parse()` accepts any `--x`, so a flag a command
|
||||
* does NOT read used to be silently dropped — `create --template notification-channel`
|
||||
* cheerfully scaffolded a blank plugin. Silently ignoring an author's explicit
|
||||
* instruction is worse than refusing it, so unknown flags are now an error.
|
||||
*/
|
||||
const COMMAND_FLAGS: Record<string, readonly string[]> = {
|
||||
create: ['type', 'interactive', 'author', 'description', 'permissions', 'template', 'egress', 'required-addons', 'icon', 'slot'],
|
||||
dev: ['port'],
|
||||
status: [],
|
||||
shot: ['port', 'out', 'dark', 'no-serve'],
|
||||
validate: [],
|
||||
pack: ['out', 'json'],
|
||||
keygen: ['key'],
|
||||
sign: ['key'],
|
||||
entry: ['repo', 'tag', 'dir', 'zip', 'commit', 'asset', 'merge', 'sign', 'key', 'out'],
|
||||
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'],
|
||||
};
|
||||
|
||||
function assertKnownFlags(command: string, f: Flags): void {
|
||||
const known = COMMAND_FLAGS[command];
|
||||
if (!known) return;
|
||||
const unknown = Object.keys(f).filter((k) => !known.includes(k));
|
||||
if (unknown.length) {
|
||||
const list = unknown.map((u) => `--${u}`).join(', ');
|
||||
fail(`unknown flag${unknown.length > 1 ? 's' : ''} for \`${command}\`: ${list}\n ${command} accepts: ${known.map((k) => '--' + k).join(', ') || '(none)'}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** `--egress a,b` / `--permissions "a b"` → a string[]. */
|
||||
function listFlag(v: string | undefined): string[] | undefined {
|
||||
if (!v || v === 'true') return undefined;
|
||||
const parts = v.split(/[\s,]+/).filter(Boolean);
|
||||
return parts.length ? parts : undefined;
|
||||
}
|
||||
|
||||
/** --sign, --sign <keyfile>, or absent → the key path to sign with (or undefined). */
|
||||
function signKey(f: Flags): string | undefined {
|
||||
if (!f.sign) return undefined;
|
||||
@@ -89,47 +126,156 @@ async function ensureRepoTag(f: Flags, failMsg: string): Promise<{ repo: string;
|
||||
return { repo: repo.trim(), tag: tag.trim() };
|
||||
}
|
||||
|
||||
const USAGE = 'usage: trek-plugin <create|dev|validate|pack|keygen|sign|entry|preflight|submit|release|publish> [...]';
|
||||
const USAGE = 'usage: trek-plugin <create|dev|status|publish|...> (`trek-plugin help` for the full list)';
|
||||
|
||||
/** The SDK's own version, for `--version` and the help banner. */
|
||||
function sdkVersion(): string {
|
||||
try {
|
||||
const pkg = readJsonFile<{ version?: string }>(path.join(import.meta.dirname, '..', '..', 'package.json'));
|
||||
return pkg.version ?? '0.0.0';
|
||||
} catch {
|
||||
return '0.0.0';
|
||||
}
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
// Advisory only (update-notifier): prints from cache on stderr, refreshes in the
|
||||
// background, never blocks. `dev` never returns, so this runs up front.
|
||||
notifySdkUpdate();
|
||||
|
||||
// `--version` used to fall through to the `else` branch and print the usage line with exit 2,
|
||||
// which is a strange way to answer a question every CLI is expected to answer.
|
||||
if (cmd === 'version' || cmd === '--version' || cmd === '-v') {
|
||||
console.log(VERSION_LINE(sdkVersion()));
|
||||
return;
|
||||
}
|
||||
|
||||
// Handled before dispatch, so assertKnownFlags never sees `--help` and rejects it as unknown.
|
||||
// Help is not an error: it goes to stdout and exits 0.
|
||||
// trek-plugin help the path, plus where to find everything else
|
||||
// trek-plugin help <cmd> that command's own page
|
||||
// trek-plugin <cmd> --help the same page — this is what people actually type
|
||||
if (cmd === 'help' || cmd === '--help' || cmd === '-h') {
|
||||
const topic = pos[0];
|
||||
if (topic) {
|
||||
const page = commandHelp(topic);
|
||||
if (!page) fail(`no such command: ${topic}\n ${USAGE}`);
|
||||
console.log(page);
|
||||
return;
|
||||
}
|
||||
console.log(topLevelHelp(sdkVersion()));
|
||||
return;
|
||||
}
|
||||
if (cmd && flags.help) {
|
||||
const page = commandHelp(cmd);
|
||||
if (!page) fail(`no such command: ${cmd}\n ${USAGE}`);
|
||||
console.log(page);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!cmd) {
|
||||
// Bare invocation: a menu in a terminal, the usage line for scripts.
|
||||
if (!isInteractive()) { console.error(USAGE); process.exit(2); }
|
||||
const chosen = await runMenu();
|
||||
if (chosen) await dispatch(chosen, {}, []);
|
||||
if (chosen) {
|
||||
// The menu used to dispatch with EMPTY positionals, so picking "Validate" or "Pack"
|
||||
// silently ran against the cwd — which is very often not a plugin at all. Ask.
|
||||
const dir = await promptPluginDir(chosen);
|
||||
await dispatch(chosen, {}, dir ? [dir] : []);
|
||||
}
|
||||
return;
|
||||
}
|
||||
await dispatch(cmd, flags, pos);
|
||||
}
|
||||
|
||||
/** The plugin's id, or '' if this isn't a plugin directory. Never throws — the caller has better errors. */
|
||||
function readPluginId(dir: string): string {
|
||||
try {
|
||||
const m = readJsonFile<{ id?: unknown }>(path.join(path.resolve(dir), 'trek-plugin.json'));
|
||||
return typeof m.id === 'string' ? m.id : '';
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
/** Commands that operate on a plugin directory, and so need one when the menu launched them. */
|
||||
const DIR_COMMANDS = new Set(['dev', 'status', 'validate', 'pack', 'shot', 'publish', 'preflight', 'submit', 'release']);
|
||||
|
||||
async function promptPluginDir(command: string): Promise<string | undefined> {
|
||||
if (!DIR_COMMANDS.has(command)) return undefined;
|
||||
// If the cwd IS a plugin, that is overwhelmingly what was meant — don't make them type a dot.
|
||||
if (fs.existsSync(path.join(process.cwd(), 'trek-plugin.json'))) return undefined;
|
||||
const dir = await promptText({
|
||||
message: 'Which plugin directory?',
|
||||
placeholder: './my-plugin',
|
||||
defaultValue: '.',
|
||||
validate: (v) => {
|
||||
const d = (v || '.').trim();
|
||||
if (!fs.existsSync(d)) return `${d} does not exist`;
|
||||
if (!fs.existsSync(path.join(d, 'trek-plugin.json'))) return `${d} has no trek-plugin.json`;
|
||||
return undefined;
|
||||
},
|
||||
});
|
||||
return dir.trim() || '.';
|
||||
}
|
||||
|
||||
async function dispatch(command: string, f: Flags, positional: string[]): Promise<void> {
|
||||
const tui = isInteractive();
|
||||
assertKnownFlags(command, f);
|
||||
if (command === 'create') {
|
||||
const name = positional[0];
|
||||
if (!name || f.interactive) {
|
||||
if (!tui) fail('create needs a plugin name in non-interactive mode: create <name> [--type integration|page|widget]');
|
||||
if (!tui) fail('create needs a plugin name in non-interactive mode: create <name> [--type integration|page|widget|trip-page]');
|
||||
await interactiveScaffold(process.cwd(), name);
|
||||
return;
|
||||
}
|
||||
scaffold(name, f.type || 'integration', process.cwd(), {
|
||||
author: f.author, description: f.description,
|
||||
permissions: f.permissions ? f.permissions.split(/[\s,]+/).filter(Boolean) : undefined,
|
||||
permissions: listFlag(f.permissions),
|
||||
egress: listFlag(f.egress),
|
||||
requiredAddons: listFlag(f['required-addons']),
|
||||
template: f.template as 'blank' | 'notification-channel' | undefined,
|
||||
icon: f.icon,
|
||||
slot: f.slot as WidgetSlot | undefined,
|
||||
});
|
||||
console.log(`Created ${name}/ — build server/index.js, add docs/screenshot.png, then \`npx trek-plugin-sdk dev ${name}\`.`);
|
||||
// The SAME text the wizard and the `create-trek-plugin` bin print. These three used to
|
||||
// name three different next commands.
|
||||
console.log(nextStepsAfterCreate(path.join(process.cwd(), name)));
|
||||
} else if (command === 'dev') {
|
||||
if (tui) intro(`trek-plugin dev — ${positional[0] || '.'}`);
|
||||
await runDev(positional[0] || '.', { port: f.port ? Number(f.port) : undefined });
|
||||
} else if (command === 'validate') {
|
||||
const r = validatePluginDir(positional[0] || '.');
|
||||
} else if (command === 'status') {
|
||||
// Never exits non-zero: `status` is for orientation, not gating. A command you are afraid
|
||||
// to run because it might fail your build is not one you reach for when you are stuck.
|
||||
const r = runStatus(positional[0] || '.', { colour: tui });
|
||||
console.log(r.text);
|
||||
} else if (command === 'shot') {
|
||||
const dir = positional[0] || '.';
|
||||
if (tui) {
|
||||
for (const w of r.warnings) logWarn(w);
|
||||
if (!r.ok) { for (const e of r.errors) logError(e); outro('✗ plugin has errors'); process.exit(1); }
|
||||
outro('✓ plugin is valid');
|
||||
const s = spinner();
|
||||
s.start('Rendering your plugin');
|
||||
try {
|
||||
const r = await runShot(dir, { port: f.port ? Number(f.port) : undefined, out: f.out, dark: !!f.dark, noServe: !!f['no-serve'] });
|
||||
s.stop(`Wrote ${path.relative(process.cwd(), r.out) || r.out} (${r.width}×${r.height})`);
|
||||
outro('next → trek-plugin status');
|
||||
} catch (e) {
|
||||
s.stop('Could not take the screenshot');
|
||||
throw e;
|
||||
}
|
||||
} else {
|
||||
for (const w of r.warnings) console.warn('warning: ' + w);
|
||||
if (!r.ok) { for (const e of r.errors) console.error('error: ' + e); process.exit(1); }
|
||||
console.log('✓ plugin is valid');
|
||||
const r = await runShot(dir, { port: f.port ? Number(f.port) : undefined, out: f.out, dark: !!f.dark, noServe: !!f['no-serve'] });
|
||||
console.log(`Wrote ${r.out} (${r.width}×${r.height})`);
|
||||
}
|
||||
} else if (command === 'validate') {
|
||||
const report = runOffline(loadContext(positional[0] || '.'));
|
||||
const text = renderPlain(report);
|
||||
if (text) console.error(text);
|
||||
if (!report.ok) {
|
||||
// Don't just fail — say where to see the whole picture.
|
||||
console.error(`\n${report.errors.length} of these would be rejected by the registry. \`trek-plugin status\` shows the full checklist.`);
|
||||
process.exit(1);
|
||||
}
|
||||
if (tui) outro('✓ plugin is valid'); else console.log('✓ plugin is valid');
|
||||
} else if (command === 'pack') {
|
||||
const r = packPluginDir(positional[0] || '.', f.out || 'plugin.zip');
|
||||
const rel = path.relative(process.cwd(), r.artifact) || r.artifact;
|
||||
@@ -137,23 +283,25 @@ async function dispatch(command: string, f: Flags, positional: string[]): Promis
|
||||
console.log(JSON.stringify(r, null, 2)); // machine output — never decorated
|
||||
} else if (tui) {
|
||||
note([...r.files, '', `sha256: ${r.sha256}`, `size: ${r.size}`].join('\n'), `Packed ${r.files.length} files → ${rel}`);
|
||||
logInfo('Upload plugin.zip to your release, then run `npx trek-plugin-sdk entry`.');
|
||||
// This used to point at `entry` — the low-level, assemble-the-PR-by-hand path — rather than
|
||||
// at `publish`, which does the release, the entry and the PR and gets the ORDER right.
|
||||
logInfo('Install this into a local TREK to try it. To ship it: `trek-plugin publish`.');
|
||||
} else {
|
||||
console.log(`Packed ${r.files.length} files -> ${rel}`);
|
||||
for (const file of r.files) console.log(' ' + file);
|
||||
console.log(`\nsha256: ${r.sha256}\nsize: ${r.size}`);
|
||||
console.log('\nUpload this plugin.zip to your release, then run `npx trek-plugin-sdk entry` to generate the registry entry.');
|
||||
console.log('\nInstall this into a local TREK to try it. To ship it: `trek-plugin publish --repo <owner/name> --tag <vX.Y.Z>`.');
|
||||
}
|
||||
} else if (command === 'keygen') {
|
||||
const keyPath = f.key || defaultKeyPath();
|
||||
const { publicKey } = generateKeypair(keyPath);
|
||||
if (tui) {
|
||||
note(`Signing key written to ${keyPath}\nKeep it safe + BACK IT UP — losing it means you can't ship signed updates.\n\nauthorPublicKey (goes in your registry entry):\n${publicKey}`, 'Signing key');
|
||||
logInfo('Sign releases with `npx trek-plugin-sdk release --sign` (or `entry --sign`).');
|
||||
logInfo('`trek-plugin publish` will now offer to sign with this key — you do not need to pass --sign.');
|
||||
} else {
|
||||
console.log(`Signing key written to ${keyPath} (keep it safe + BACK IT UP — losing it means you can't ship signed updates).`);
|
||||
console.log(`\nauthorPublicKey (goes in your registry entry): ${publicKey}`);
|
||||
console.log('\nSign releases with `npx trek-plugin-sdk release --sign` (or `entry --sign`).');
|
||||
console.log('\nPass --sign to `trek-plugin publish` to sign a release with it (interactively, publish offers).');
|
||||
}
|
||||
} else if (command === 'sign') {
|
||||
const zip = positional[0] || 'plugin.zip';
|
||||
@@ -208,15 +356,35 @@ async function dispatch(command: string, f: Flags, positional: string[]): Promis
|
||||
}
|
||||
} else if (command === 'publish') {
|
||||
const { repo, tag } = await ensureRepoTag(f, 'publish needs --repo <owner/name> and --tag <vX.Y.Z>');
|
||||
const dir = positional[0] || '.';
|
||||
|
||||
// Signing used to be a flag you had to already know about, with `keygen` buried under
|
||||
// "Advanced…" — so the default path shipped unsigned and never mentioned that signing existed.
|
||||
// Offer it, once, at the moment it is actually a decision. A script that did not pass --sign
|
||||
// gets exactly the behaviour it always got: prompting a pipeline is how you hang a pipeline.
|
||||
let signKeyPath = signKey(f);
|
||||
let signing: SigningState | undefined;
|
||||
if (tui && !signKeyPath) {
|
||||
const id = readPluginId(dir);
|
||||
if (id) {
|
||||
signing = await inspectSigning(id, { registry: f.registry, keyPath: f.key });
|
||||
signKeyPath = await proposeSigning(signing);
|
||||
}
|
||||
}
|
||||
|
||||
if (tui) {
|
||||
note(`repo ${repo}\ntag ${tag}\ndir ${positional[0] || '.'}`, 'Publish');
|
||||
note(
|
||||
`repo ${repo}\ntag ${tag}\ndir ${dir}\nsign ${signKeyPath ? `yes (${signKeyPath})` : 'no — unsigned'}`,
|
||||
'Publish',
|
||||
);
|
||||
const ok = await promptConfirm({ message: 'Create the GitHub release and open the registry PR?', initialValue: true });
|
||||
if (!ok) { outro('Cancelled — nothing was published.'); return; }
|
||||
}
|
||||
const { prUrl } = await publishPlugin({
|
||||
dir: positional[0] || '.', repo, tag,
|
||||
signKeyPath: signKey(f), registry: f.registry, draft: !!f.draft,
|
||||
notes: f.notes, skipPreflight: !!f['no-preflight'], now: new Date().toISOString(),
|
||||
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,
|
||||
now: new Date().toISOString(),
|
||||
log: tui ? clackLogSink : undefined,
|
||||
});
|
||||
if (tui) logSuccess('Published — registry PR:'); else console.error('\n✓ published — registry PR:');
|
||||
@@ -265,7 +433,7 @@ async function dispatch(command: string, f: Flags, positional: string[]): Promis
|
||||
process.stdout.write(JSON.stringify(entry, null, 2) + '\n');
|
||||
}
|
||||
} else {
|
||||
console.error(USAGE);
|
||||
console.error(`unknown command: ${command}\n${USAGE}`);
|
||||
process.exit(2);
|
||||
}
|
||||
}
|
||||
|
||||
+187
-23
@@ -18,10 +18,12 @@ import {
|
||||
text as clackText,
|
||||
select as clackSelect,
|
||||
multiselect as clackMultiselect,
|
||||
groupMultiselect as clackGroupMultiselect,
|
||||
confirm as clackConfirm,
|
||||
type TextOptions,
|
||||
type SelectOptions,
|
||||
type MultiSelectOptions,
|
||||
type GroupMultiSelectOptions,
|
||||
type ConfirmOptions,
|
||||
type SpinnerResult,
|
||||
} from '@clack/prompts';
|
||||
@@ -67,38 +69,200 @@ export const promptSelect = async <Value>(opts: Omit<SelectOptions<Value>, 'outp
|
||||
export const promptMultiselect = async <Value>(opts: Omit<MultiSelectOptions<Value>, 'output'>): Promise<Value[]> =>
|
||||
orCancel(await clackMultiselect({ ...opts, output: OUT }));
|
||||
|
||||
/**
|
||||
* One multiselect, options rendered under group headers. Used for permissions: 58 of them
|
||||
* in a flat list is unreadable, but splitting the pick across TWO prompts was worse — Clack
|
||||
* has no "back", so choosing the wrong group was a dead end you could only escape with ^C.
|
||||
* Grouping keeps it a single screen you can scroll, with no navigation to get lost in.
|
||||
*/
|
||||
export const promptGroupMultiselect = async <Value>(
|
||||
opts: Omit<GroupMultiSelectOptions<Value>, 'output'>,
|
||||
): Promise<Value[]> => orCancel(await clackGroupMultiselect({ ...opts, output: OUT }));
|
||||
|
||||
export const promptConfirm = async (opts: Omit<ConfirmOptions, 'output'>): Promise<boolean> =>
|
||||
orCancel(await clackConfirm({ ...opts, output: OUT }));
|
||||
|
||||
// ── permissions ──────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* The permissions an author can grant, each with a human hint for the multiselect.
|
||||
* This list must stay in lockstep with the host's `KNOWN_PERMISSIONS`
|
||||
* (server `src/nest/plugins/protocol/envelope.ts`) — same strings, same order.
|
||||
* The manifest validator's `KNOWN_PERMISSIONS` (`../manifest.ts`) mirrors it too.
|
||||
* Every permission an author can grant, grouped into the areas of TREK they touch.
|
||||
*
|
||||
* This used to be a hand-written list, and it silently fell 40 permissions behind the
|
||||
* host — `create` could not offer `jobs:run`, `events:subscribe` or 7 of the 12 hooks,
|
||||
* so a scaffolded plugin that needed one had no way to ask for it. The families below
|
||||
* are now the ONLY place a permission may be listed, and `test/cli.test.ts` fails if a
|
||||
* permission in the manifest validator's KNOWN_PERMISSIONS has no entry here. Add a
|
||||
* permission to TREK ⇒ the test tells you to describe it ⇒ `create` offers it.
|
||||
*
|
||||
* `db:read:*` grants read the data the REQUESTING USER can already see; `db:write:*`
|
||||
* grants act on trips that user can edit. Neither is a superuser grant.
|
||||
*/
|
||||
export const PERMISSION_CATALOG: { value: string; label: string; hint: string }[] = [
|
||||
{ value: 'db:own', label: 'db:own', hint: 'A private database only this plugin can read/write' },
|
||||
{ value: 'db:read:trips', label: 'db:read:trips', hint: 'Read trips the requesting user can access' },
|
||||
{ value: 'db:read:users', label: 'db:read:users', hint: 'Read basic user profiles' },
|
||||
{ value: 'db:read:costs', label: 'db:read:costs', hint: 'Read costs (budget items) the requesting user can access' },
|
||||
{ value: 'db:write:costs', label: 'db:write:costs', hint: 'Create costs (budget items) on trips the user can edit' },
|
||||
{ value: 'db:write:places', label: 'db:write:places', hint: 'Add, edit and remove places on trips the user can edit' },
|
||||
{ value: 'db:write:days', label: 'db:write:days', hint: 'Add, edit and remove days on trips the user can edit' },
|
||||
{ value: 'db:write:itinerary', label: 'db:write:itinerary', hint: 'Assign and remove places on days of trips the user can edit' },
|
||||
{ value: 'db:write:trips', label: 'db:write:trips', hint: 'Edit trip details (title, dates, currency…) on trips the user can edit' },
|
||||
{ value: 'db:meta', label: 'db:meta', hint: 'Attach its own private data to trips, places and days the user can access' },
|
||||
{ value: 'ws:broadcast:trip', label: 'ws:broadcast:trip', hint: 'Push realtime events to everyone on a trip' },
|
||||
{ value: 'ws:broadcast:user', label: 'ws:broadcast:user', hint: 'Push realtime events to a single user' },
|
||||
{ value: 'hook:photo-provider', label: 'hook:photo-provider', hint: 'Supply place photos to TREK' },
|
||||
{ value: 'hook:calendar-source', label: 'hook:calendar-source', hint: 'Supply calendar events to TREK' },
|
||||
{ value: 'hook:notification-channel', label: 'hook:notification-channel', hint: 'Deliver TREK notifications over your own channel' },
|
||||
{ value: 'hook:place-detail-provider', label: 'hook:place-detail-provider', hint: 'Contribute extra details (reviews, ratings, links) to a place' },
|
||||
{ value: 'hook:trip-warning-provider', label: 'hook:trip-warning-provider', hint: 'Raise validation warnings on a trip (shown in the planner)' },
|
||||
{ value: 'http:outbound', label: 'http:outbound', hint: 'Call external HTTP hosts (needs an egress allow-list)' },
|
||||
export interface PermissionFamily {
|
||||
id: string;
|
||||
label: string;
|
||||
hint: string;
|
||||
permissions: { value: string; hint: string }[];
|
||||
}
|
||||
|
||||
export const PERMISSION_FAMILIES: PermissionFamily[] = [
|
||||
{
|
||||
id: 'storage',
|
||||
label: 'Its own storage',
|
||||
hint: 'Where the plugin keeps data of its own',
|
||||
permissions: [
|
||||
{ value: 'db:own', hint: 'A private database only this plugin can read/write' },
|
||||
{ value: 'db:meta', hint: 'Attach its own private data to trips, places and days the user can access' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'trips',
|
||||
label: 'Trips & members',
|
||||
hint: 'The trip itself, and who is on it',
|
||||
permissions: [
|
||||
{ value: 'db:read:trips', hint: 'Read trips the requesting user can access' },
|
||||
{ value: 'db:write:trips', hint: 'Edit trip details (title, dates, currency…) on trips the user can edit' },
|
||||
{ value: 'db:create:trips', hint: 'Create new trips for the requesting user' },
|
||||
{ value: 'db:read:users', hint: 'Read basic user profiles' },
|
||||
{ value: 'db:write:members', hint: 'Add and remove trip members' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'itinerary',
|
||||
label: 'Places, days & itinerary',
|
||||
hint: 'The plan itself — the planner\'s core',
|
||||
permissions: [
|
||||
{ value: 'db:write:places', hint: 'Add, edit and remove places on trips the user can edit' },
|
||||
{ value: 'db:write:days', hint: 'Add, edit and remove days on trips the user can edit' },
|
||||
{ value: 'db:write:itinerary', hint: 'Assign and remove places on days of trips the user can edit' },
|
||||
{ value: 'db:read:categories', hint: 'Read the place categories TREK ships' },
|
||||
{ value: 'db:read:tags', hint: 'Read the tags used to label places' },
|
||||
{ value: 'db:write:tags', hint: 'Create, rename and delete tags' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'bookings',
|
||||
label: 'Reservations & accommodation',
|
||||
hint: 'Flights, trains, hotels',
|
||||
permissions: [
|
||||
{ value: 'db:write:reservations', hint: 'Create, edit and delete reservations (flights, trains, restaurants…)' },
|
||||
{ value: 'db:write:accommodations', hint: 'Create, edit and delete accommodation (hotels, rentals)' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'budget',
|
||||
label: 'Budget',
|
||||
hint: 'Costs and splits — needs the budget addon enabled',
|
||||
permissions: [
|
||||
{ value: 'db:read:costs', hint: 'Read costs (budget items) the requesting user can access' },
|
||||
{ value: 'db:write:costs', hint: 'Create, edit and delete costs on trips the user can edit' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'packing',
|
||||
label: 'Packing & todos',
|
||||
hint: 'Checklists — packing needs the packing addon',
|
||||
permissions: [
|
||||
{ value: 'db:read:packing', hint: 'Read packing lists and bags' },
|
||||
{ value: 'db:write:packing', hint: 'Create, edit, tick and delete packing items and bags' },
|
||||
{ value: 'db:read:todos', hint: 'Read the trip todo list' },
|
||||
{ value: 'db:write:todos', hint: 'Create, edit, tick and delete todos' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'files',
|
||||
label: 'Files & documents',
|
||||
hint: 'Uploads — needs the documents addon enabled',
|
||||
permissions: [
|
||||
{ value: 'db:read:files', hint: 'List a trip\'s files and their metadata (NOT their contents)' },
|
||||
{ value: 'db:read:files:content', hint: 'Read the actual BYTES of a file — grant this only if you truly need them' },
|
||||
{ value: 'db:write:files', hint: 'Upload, link, rename and delete files' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'collab',
|
||||
label: 'Collaboration',
|
||||
hint: 'Notes, polls, chat — needs the collab addon enabled',
|
||||
permissions: [
|
||||
{ value: 'db:read:collab', hint: 'Read shared notes, polls and chat messages' },
|
||||
{ value: 'db:write:collab', hint: 'Create notes and polls, vote, and post messages' },
|
||||
{ value: 'db:read:daynotes', hint: 'Read the notes pinned to a day' },
|
||||
{ value: 'db:write:daynotes', hint: 'Create, edit and delete day notes' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'journal',
|
||||
label: 'Journal, Atlas, Vacay & collections',
|
||||
hint: 'The cross-trip features — each needs its addon enabled',
|
||||
permissions: [
|
||||
{ value: 'db:read:journal', hint: 'Read journeys and their entries' },
|
||||
{ value: 'db:write:journal', hint: 'Create and edit journeys and journal entries' },
|
||||
{ value: 'db:read:atlas', hint: 'Read visited countries/regions and the bucket list' },
|
||||
{ value: 'db:write:atlas', hint: 'Mark places visited and edit the bucket list' },
|
||||
{ value: 'db:read:vacay', hint: 'Read vacation-day plans and balances' },
|
||||
{ value: 'db:write:vacay', hint: 'Toggle vacation days and company holidays' },
|
||||
{ value: 'db:read:collections', hint: 'Read saved place collections' },
|
||||
{ value: 'db:write:collections', hint: 'Create collections, save places into them, and copy them to a trip' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'hooks',
|
||||
label: 'Provider hooks (render inside TREK natively)',
|
||||
hint: 'TREK calls YOU. Without the matching grant a hook is NEVER invoked — silently',
|
||||
permissions: [
|
||||
{ value: 'hook:photo-provider', hint: 'Supply place photos to TREK' },
|
||||
{ value: 'hook:calendar-source', hint: 'Supply calendar events to TREK' },
|
||||
{ value: 'hook:place-detail-provider', hint: 'Contribute extra details (reviews, ratings, links) to a place' },
|
||||
{ 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: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' },
|
||||
{ value: 'hook:trip-card-provider', hint: 'Add a badge/card to the trip list' },
|
||||
{ value: 'hook:notification-channel', hint: 'Deliver TREK notifications over your own channel' },
|
||||
{ value: 'hook:user-data', hint: 'Implement GDPR erasure/export of the data you hold for a user' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'background',
|
||||
label: 'Background work',
|
||||
hint: 'Run without a user present. Ungranted, these never run at all',
|
||||
permissions: [
|
||||
{ value: 'jobs:run', hint: 'Run cron jobs and ctx.scheduler timers (no acting user)' },
|
||||
{ value: 'events:subscribe', hint: 'Receive TREK events (place:created, trip:updated…) as they happen' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'realtime',
|
||||
label: 'Realtime push',
|
||||
hint: 'Push to connected clients over the websocket',
|
||||
permissions: [
|
||||
{ value: 'ws:broadcast:trip', hint: 'Push realtime events to everyone on a trip' },
|
||||
{ value: 'ws:broadcast:user', hint: 'Push realtime events to a single user' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'services',
|
||||
label: 'Network & host services',
|
||||
hint: 'Reach the outside world, or borrow a TREK service',
|
||||
permissions: [
|
||||
{ value: 'http:outbound', hint: 'Call external HTTP hosts (you name the hosts next)' },
|
||||
{ value: 'weather:read', hint: 'Read forecasts through TREK\'s weather service' },
|
||||
{ value: 'rates:read', hint: 'Read currency exchange rates through TREK' },
|
||||
{ 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' },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
/** Flat view of every permission, for the non-interactive path and the tests. */
|
||||
export const PERMISSION_CATALOG: { value: string; label: string; hint: string; family: string }[] =
|
||||
PERMISSION_FAMILIES.flatMap((f) =>
|
||||
f.permissions.map((p) => ({ value: p.value, label: p.value, hint: p.hint, family: f.id })),
|
||||
);
|
||||
|
||||
/** Every grantable permission id. Derived — never hand-maintained. */
|
||||
export const KNOWN_PERMISSIONS: string[] = PERMISSION_CATALOG.map((p) => p.value);
|
||||
|
||||
// ── reporter seam (for commands that log their own progress, e.g. publish) ────
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* "Your SDK is out of date" — the advisory update notice (#plugins).
|
||||
*
|
||||
* A stale SDK is not cosmetic: the registry-entry format, the manifest validator and
|
||||
* the permission catalog all move with the host, so an author on an old SDK can `pack`
|
||||
* and `submit` an entry that today's registry CI rejects.
|
||||
*
|
||||
* This is a thin wrapper over `update-notifier` (the de-facto standard for npm CLIs):
|
||||
* a detached background process checks the registry at most once a day, the notice is
|
||||
* printed from cache on stderr, and CI / non-TTY / `NO_UPDATE_NOTIFIER` all silence it.
|
||||
* We hand it off rather than hand-roll the same detached-child + cache dance ourselves.
|
||||
*/
|
||||
import updateNotifier from 'update-notifier';
|
||||
import { createRequire } from 'node:module';
|
||||
|
||||
export function notifySdkUpdate(): void {
|
||||
try {
|
||||
// `../../package.json` resolves to the package root from dist/cli/ (prod) and
|
||||
// src/cli/ (tests) alike. createRequire keeps it working on every Node >=18,
|
||||
// unlike `import ... with { type: 'json' }`, which Node 18 does not accept.
|
||||
const pkg = createRequire(import.meta.url)('../../package.json') as { name: string; version: string };
|
||||
updateNotifier({ pkg }).notify();
|
||||
} catch {
|
||||
// An update notice is never worth disturbing a command over.
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,20 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* trek-plugin validate [dir] (#plugins, M6). Runs the SAME manifest checks the
|
||||
* registry CI runs, plus a light README sanity check — so a local pass predicts
|
||||
* a CI pass. Returns a structured result; the CLI prints + exits non-zero on
|
||||
* failure.
|
||||
* trek-plugin validate [dir] — the gate.
|
||||
*
|
||||
* Runs every check the registry enforces that can be answered from the working tree, and exits
|
||||
* non-zero if any of them would reject the plugin. That is a much stronger claim than it used to
|
||||
* be: this file previously ran about a fifth of the registry's rules, and demoted the two that
|
||||
* bite hardest — a bad `icon` and an unwritten README — to warnings. A green validate was not
|
||||
* evidence of anything, and the first real verdict arrived from `preflight`, over the network,
|
||||
* against a tag whose GitHub release was already immutable.
|
||||
*
|
||||
* The rules themselves live in ./checks/, shared with `status`, `preflight` and `publish`. This
|
||||
* file is now only a printer and an exit code.
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { validateManifest, KNOWN_ADDONS } from '../manifest.js';
|
||||
import { readJsonFile } from './json.js';
|
||||
import { loadContext } from './checks/context.js';
|
||||
import { runOffline } from './checks/index.js';
|
||||
import { renderPlain } from './checks/report.js';
|
||||
|
||||
export interface ValidateReport {
|
||||
ok: boolean;
|
||||
@@ -16,80 +22,35 @@ export interface ValidateReport {
|
||||
warnings: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* One string per problem, for callers that want a flat list rather than a rendered checklist.
|
||||
*
|
||||
* The `fix` is folded in, not dropped. Several checks summarise in `detail` ("2 problems") and put
|
||||
* the specifics in `fix` ("• tag \"Flight Tracking\" is not a lowercase slug…") — so a flat list
|
||||
* built from title + detail alone would report a failure without ever saying WHAT failed, which
|
||||
* is the exact uselessness this rework is about.
|
||||
*/
|
||||
function flatten(outcomes: { title: string; detail?: string; fix?: string }[]): string[] {
|
||||
return outcomes.map((o) => {
|
||||
const head = o.detail ? `${o.title} — ${o.detail}` : o.title;
|
||||
return o.fix ? `${head}\n${o.fix}` : head;
|
||||
});
|
||||
}
|
||||
|
||||
export function validatePluginDir(dir: string): ValidateReport {
|
||||
const errors: string[] = [];
|
||||
const warnings: string[] = [];
|
||||
|
||||
const manifestPath = path.join(dir, 'trek-plugin.json');
|
||||
if (!fs.existsSync(manifestPath)) return { ok: false, errors: ['no trek-plugin.json in ' + dir], warnings };
|
||||
|
||||
let manifestId = '';
|
||||
try {
|
||||
const raw = readJsonFile<Record<string, unknown>>(manifestPath);
|
||||
const res = validateManifest(raw);
|
||||
errors.push(...res.errors);
|
||||
manifestId = res.manifest?.id ?? String(raw.id ?? '');
|
||||
// dir name should match the id
|
||||
if (manifestId && path.basename(path.resolve(dir)) !== manifestId) {
|
||||
warnings.push(`directory name should equal the plugin id "${manifestId}"`);
|
||||
}
|
||||
// A well-formed but unrecognised addon id is not an error (the plugin may target
|
||||
// a newer TREK), but it can never enable here — surface it as a warning.
|
||||
for (const a of res.manifest?.requiredAddons ?? []) {
|
||||
if (!KNOWN_ADDONS.includes(a)) warnings.push(`requiredAddons: "${a}" is not a known TREK addon on this SDK version`);
|
||||
}
|
||||
// TREK renders its UI with lucide icons only. It STRIPS emojis from the declarative
|
||||
// text your hooks return (badges, columns, warnings, PDF sections, map/calendar/photo
|
||||
// labels) and from notifications, so emojis in that text simply vanish at render.
|
||||
// Emojis in the manifest name/description are the tell-tale sign — nudge the author
|
||||
// to use the `icon` field with a lucide name instead.
|
||||
const EMOJI_RE = /[\p{Extended_Pictographic}\u{1F1E6}-\u{1F1FF}]/u;
|
||||
if (EMOJI_RE.test(String(raw.name ?? '')) || EMOJI_RE.test(String(raw.description ?? ''))) {
|
||||
warnings.push('name/description contains emojis — TREK uses lucide icons and strips emojis from plugin-rendered text + notifications. Use the declarative `icon` field (a lucide name) instead of emojis in labels.');
|
||||
}
|
||||
} catch (e) {
|
||||
errors.push('trek-plugin.json is not valid JSON: ' + (e instanceof Error ? e.message : e));
|
||||
}
|
||||
|
||||
// README sanity
|
||||
const readmePath = path.join(dir, 'README.md');
|
||||
if (!fs.existsSync(readmePath)) {
|
||||
errors.push('README.md is missing');
|
||||
} else {
|
||||
const md = fs.readFileSync(readmePath, 'utf8');
|
||||
if (!/!\[[^\]]*\]\([^)]+\)/.test(md)) warnings.push('README has no screenshot (registry requires at least one)');
|
||||
if (/\{\{[^}]*\}\}|REPLACE_ME|Describe (what|the)|One sentence:/i.test(md)) {
|
||||
warnings.push('README still contains template placeholders — fill it in before publishing');
|
||||
}
|
||||
}
|
||||
|
||||
// Client UI: a raw <select> without the design kit falls back to the OS-drawn
|
||||
// dropdown, which can't match TREK. The kit auto-upgrades selects, so nudge the
|
||||
// author to inline it (or opt a field out on purpose).
|
||||
const clientHtml = path.join(dir, 'client', 'index.html');
|
||||
if (fs.existsSync(clientHtml)) {
|
||||
const html = fs.readFileSync(clientHtml, 'utf8');
|
||||
const rawSelect = /<select(?![^>]*\bdata-trek-native\b)(\s|>)/i.test(html);
|
||||
const usesKit = html.includes('<!-- trek:ui -->') || html.includes('data-trek-ui');
|
||||
if (rawSelect && !usesKit) {
|
||||
warnings.push('client/index.html has a <select> but does not inline the design kit — native dropdowns will not match TREK. Add the <!-- trek:ui --> marker so selects are auto-styled, or mark a field data-trek-native to opt out.');
|
||||
}
|
||||
}
|
||||
|
||||
// Server entry present
|
||||
if (!fs.existsSync(path.join(dir, 'server', 'index.js'))) errors.push('server/index.js is missing (build your plugin first)');
|
||||
|
||||
return { ok: errors.length === 0, errors, warnings };
|
||||
const report = runOffline(loadContext(dir));
|
||||
return {
|
||||
ok: report.ok,
|
||||
errors: flatten(report.errors),
|
||||
warnings: flatten(report.warnings),
|
||||
};
|
||||
}
|
||||
|
||||
if (process.argv[1] && process.argv[1].endsWith('validate.js')) {
|
||||
const dir = process.argv[2] || '.';
|
||||
const r = validatePluginDir(dir);
|
||||
for (const w of r.warnings) console.warn('warning: ' + w);
|
||||
if (r.ok) {
|
||||
console.log('✓ plugin is valid');
|
||||
} else {
|
||||
for (const e of r.errors) console.error('error: ' + e);
|
||||
process.exit(1);
|
||||
}
|
||||
const report = runOffline(loadContext(dir));
|
||||
const text = renderPlain(report);
|
||||
if (text) console.error(text);
|
||||
if (!report.ok) process.exit(1);
|
||||
console.log('✓ plugin is valid');
|
||||
}
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
/**
|
||||
* Author-signature verification for `trek-plugin preflight`.
|
||||
*
|
||||
* This is a port of TREK's installer-side verifier (server/src/nest/plugins/install/
|
||||
* verify-signature.ts), and of the registry's port of it (TREK-Plugins'
|
||||
* scripts/lib/verify-signature.mjs). All three MUST accept exactly the same inputs.
|
||||
*
|
||||
* The point of preflight is to tell an author what the registry's CI would say before
|
||||
* they open the PR. `sign.ts`'s verifyArtifact only understands the bare key/signature
|
||||
* pair the SDK itself emits, so it cannot answer that question for a minisign key — and
|
||||
* a preflight that says "green" on a signature the registry would reject is worse than
|
||||
* no preflight at all, because the author trusts it.
|
||||
*
|
||||
* node:crypto only, like the rest of the SDK.
|
||||
*/
|
||||
import crypto from 'node:crypto';
|
||||
|
||||
// SPKI DER prefix for a raw 32-byte Ed25519 public key (RFC 8410).
|
||||
const ED25519_SPKI_PREFIX = Buffer.from('302a300506032b6570032100', 'hex');
|
||||
|
||||
export class SignatureError extends Error {}
|
||||
|
||||
/** Wrap a raw 32-byte Ed25519 public key as a node KeyObject. */
|
||||
function ed25519KeyFromRaw(raw: Buffer): crypto.KeyObject {
|
||||
if (raw.length !== 32) throw new SignatureError('public key is not a 32-byte Ed25519 key');
|
||||
return crypto.createPublicKey({ key: Buffer.concat([ED25519_SPKI_PREFIX, raw]), format: 'der', type: 'spki' });
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a minisign public key: either the two-line minisign format (comment + base64
|
||||
* payload) or a bare base64 payload. The 10-byte payload header is `Ed` + an 8-byte key
|
||||
* id; the trailing 32 bytes are the key. A bare 32-byte base64 key (what `keygen` emits)
|
||||
* is also accepted.
|
||||
*/
|
||||
function parseMinisignPubKey(pub: string): { key: crypto.KeyObject; keyId: Buffer | null } {
|
||||
const line = pub.trim().split(/\r?\n/).map((l) => l.trim()).filter((l) => l && !l.startsWith('untrusted comment')).pop();
|
||||
if (!line) throw new SignatureError('empty public key');
|
||||
const buf = Buffer.from(line, 'base64');
|
||||
if (buf.length === 32) return { key: ed25519KeyFromRaw(buf), keyId: null };
|
||||
if (buf.length === 42 && buf.subarray(0, 2).toString('latin1') === 'Ed') {
|
||||
return { key: ed25519KeyFromRaw(buf.subarray(10)), keyId: buf.subarray(2, 10) };
|
||||
}
|
||||
throw new SignatureError('unrecognized public key format');
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a minisign signature: 2-byte algorithm (`Ed` legacy | `ED` prehashed) + 8-byte
|
||||
* key id + 64-byte signature. A bare 64-byte base64 signature (what `sign` emits, over
|
||||
* the raw artifact bytes) is also accepted.
|
||||
*/
|
||||
function parseMinisignSignature(sig: string): { algo: 'Ed' | 'ED' | 'raw'; keyId: Buffer | null; signature: Buffer } {
|
||||
const line = sig.trim().split(/\r?\n/).map((l) => l.trim()).filter((l) => l && !l.startsWith('untrusted comment')).shift();
|
||||
if (!line) throw new SignatureError('empty signature');
|
||||
const buf = Buffer.from(line, 'base64');
|
||||
if (buf.length === 64) return { algo: 'raw', keyId: null, signature: buf };
|
||||
if (buf.length === 74) {
|
||||
const algo = buf.subarray(0, 2).toString('latin1');
|
||||
if (algo !== 'Ed' && algo !== 'ED') throw new SignatureError(`unsupported signature algorithm ${algo}`);
|
||||
return { algo, keyId: buf.subarray(2, 10), signature: buf.subarray(10) };
|
||||
}
|
||||
throw new SignatureError('unrecognized signature format');
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify that `bytes` were signed by the holder of `publicKeyB64`'s private key. Returns
|
||||
* true on a valid signature, false on a well-formed but non-matching one, and throws
|
||||
* SignatureError on malformed input.
|
||||
*/
|
||||
export function verifyAuthorSignature(bytes: Buffer, signatureB64: string, publicKeyB64: string): boolean {
|
||||
const { key, keyId } = parseMinisignPubKey(publicKeyB64);
|
||||
const { algo, keyId: sigKeyId, signature } = parseMinisignSignature(signatureB64);
|
||||
|
||||
// If both carry a key id, they must name the same key (catches a wrong-key mixup).
|
||||
if (keyId && sigKeyId && !keyId.equals(sigKeyId)) return false;
|
||||
|
||||
const message = algo === 'ED' ? crypto.createHash('blake2b512').update(bytes).digest() : bytes;
|
||||
try {
|
||||
return crypto.verify(null, message, key, signature);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Structural check that needs no artifact (and so no network): a key and a signature must
|
||||
* be both-present or both-absent, and each must parse.
|
||||
*
|
||||
* TREK refuses to install a half-signed entry ("incomplete signature: an author key and a
|
||||
* version signature must both be present"), so such an entry is dead on arrival. Mirrors
|
||||
* the registry's checkSignatureShape. Returns a list of problems (empty === fine).
|
||||
*/
|
||||
export function checkSignatureShape(entry: { authorPublicKey?: string; versions?: Array<{ version: string; signature?: string }> }): string[] {
|
||||
const problems: string[] = [];
|
||||
const key = entry.authorPublicKey;
|
||||
const versions = Array.isArray(entry.versions) ? entry.versions : [];
|
||||
|
||||
if (key) {
|
||||
try {
|
||||
parseMinisignPubKey(key);
|
||||
} catch (e) {
|
||||
problems.push(`authorPublicKey is not a valid Ed25519/minisign public key: ${(e as Error).message}`);
|
||||
}
|
||||
}
|
||||
|
||||
for (const v of versions) {
|
||||
if (v.signature && !key) {
|
||||
problems.push(`${v.version}: has a signature but the entry has no authorPublicKey — TREK refuses to install a half-signed entry`);
|
||||
}
|
||||
if (v.signature) {
|
||||
try {
|
||||
parseMinisignSignature(v.signature);
|
||||
} catch (e) {
|
||||
problems.push(`${v.version}: signature is malformed: ${(e as Error).message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A key with no signed version at all is a publishing mistake: TREK pins the key on
|
||||
// first install and then requires every later version to be signed by it.
|
||||
if (key && versions.length && !versions.some((v) => v.signature)) {
|
||||
problems.push('authorPublicKey is set but no version carries a signature — either sign the release or drop the key');
|
||||
}
|
||||
|
||||
return problems;
|
||||
}
|
||||
Reference in New Issue
Block a user