mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-10-18 21:16:47 +00:00
3.3.0 (#1520)
* 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. --------- Co-authored-by: jubnl <jgunther021@gmail.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>
This commit is contained in:
@@ -52,7 +52,10 @@ trek.notify('success', 'Saved')
|
||||
```
|
||||
|
||||
The kit applies the theme, mirrors the appearance flags (reduced-motion,
|
||||
no-transparency) and auto-reports your height. See the
|
||||
no-transparency) and auto-reports your height. It also upgrades any native
|
||||
`<select>` into a host-styled, keyboard-accessible dropdown that matches TREK —
|
||||
the OS-drawn popup never could. Write a plain `<select>` and it just works; add
|
||||
`data-trek-native` to opt a field out. See the
|
||||
[Plugin Development wiki](https://github.com/mauriceboe/TREK/wiki/Plugin-Development)
|
||||
for the full component + token reference.
|
||||
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "trek-plugin-sdk",
|
||||
"version": "1.3.0",
|
||||
"version": "1.4.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "trek-plugin-sdk",
|
||||
"version": "1.3.0",
|
||||
"version": "1.4.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@clack/prompts": "^1.7.0",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "trek-plugin-sdk",
|
||||
"version": "1.3.1",
|
||||
"version": "1.4.0",
|
||||
"description": "SDK for building TREK plugins: types, definePlugin, a mock host, manifest validation, and the create-trek-plugin / trek-plugin CLIs.",
|
||||
"type": "module",
|
||||
"license": "MIT",
|
||||
|
||||
+180
-20
@@ -10,7 +10,7 @@ import os from 'node:os';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { createRequire } from 'node:module';
|
||||
import {
|
||||
intro, outro, note, logSuccess, logWarn, spinner,
|
||||
intro, outro, note, logInfo, logSuccess, logWarn, spinner,
|
||||
promptText, promptSelect, promptMultiselect, promptConfirm,
|
||||
PERMISSION_CATALOG,
|
||||
} from './ui.js';
|
||||
@@ -30,32 +30,68 @@ export interface ScaffoldOptions {
|
||||
author?: string;
|
||||
description?: string;
|
||||
permissions?: string[];
|
||||
/** External hosts the plugin may call — required by the manifest when `http:outbound` is granted. */
|
||||
/**
|
||||
* External hosts the plugin may call — required by the manifest when `http:outbound` is
|
||||
* granted, UNLESS the plugin is an operatorEgress one (below), whose hosts an admin adds
|
||||
* after install because the author cannot know them (a self-hosted Gotify, an ntfy).
|
||||
*/
|
||||
egress?: string[];
|
||||
/** The admin supplies the hosts post-install. Defaults on for a channel, and whenever `http:outbound` is wanted with no `egress`. */
|
||||
operatorEgress?: boolean;
|
||||
/** Addon ids that must be enabled for this plugin to activate. */
|
||||
requiredAddons?: string[];
|
||||
/** Other plugins this one depends on, each pinned by a semver range. */
|
||||
pluginDependencies?: Array<{ id: string; version: string }>;
|
||||
/**
|
||||
* Which starter to generate. This is NOT the manifest `type` — a notification
|
||||
* channel is a plain `integration` that implements the `notificationChannel` hook.
|
||||
*/
|
||||
template?: 'blank' | 'notification-channel';
|
||||
}
|
||||
|
||||
export const TEMPLATES = ['blank', 'notification-channel'] as const;
|
||||
|
||||
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}"`);
|
||||
|
||||
const template = opts.template ?? 'blank';
|
||||
if (!TEMPLATES.includes(template)) throw new Error(`invalid template "${template}"`);
|
||||
const isChannel = template === 'notification-channel';
|
||||
// A notification channel is server-only by construction: it takes a rendered
|
||||
// message and pushes it somewhere. Nothing else makes sense.
|
||||
if (isChannel && type !== 'integration') throw new Error('the notification-channel template requires type "integration"');
|
||||
|
||||
const root = path.join(targetDir, name);
|
||||
if (fs.existsSync(root)) throw new Error(`${root} already exists`);
|
||||
fs.mkdirSync(path.join(root, 'server'), { recursive: true });
|
||||
|
||||
const perms = opts.permissions?.length ? opts.permissions : ['db:own'];
|
||||
const displayName = name.replace(/-/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
|
||||
let perms = opts.permissions?.length ? opts.permissions : ['db:own'];
|
||||
const egress = opts.egress ?? [];
|
||||
if (isChannel) {
|
||||
// The grants a channel cannot work without. With known hosts it gets a per-host grant
|
||||
// each; with none — the usual case for a self-hosted target — it gets the bare
|
||||
// `http:outbound` and relies on operatorEgress below, rather than a fake placeholder
|
||||
// host that would otherwise ship in the published manifest.
|
||||
const outbound = egress.length ? egress.map((h) => `http:outbound:${h}`) : ['http:outbound'];
|
||||
const required = ['hook:notification-channel', ...outbound];
|
||||
perms = [...new Set([...perms.filter((p) => p !== 'db:own'), ...required])];
|
||||
}
|
||||
// A plugin that wants outbound but names no host is only valid as an operatorEgress
|
||||
// plugin — the admin supplies the hosts after install.
|
||||
const wantsOutbound = perms.some((p) => p === 'http:outbound' || p.startsWith('http:outbound:'));
|
||||
const operatorEgress = opts.operatorEgress ?? (isChannel || (wantsOutbound && egress.length === 0));
|
||||
|
||||
const manifest: Record<string, unknown> = {
|
||||
id: name,
|
||||
name: name.replace(/-/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase()),
|
||||
name: displayName,
|
||||
version: '1.0.0',
|
||||
apiVersion: 1,
|
||||
author: opts.author || 'Your Name',
|
||||
description: opts.description || 'Describe what your plugin does.',
|
||||
description: opts.description || (isChannel ? `Deliver TREK notifications over ${displayName}.` : 'Describe what your plugin does.'),
|
||||
type,
|
||||
trek: '>=3.2.1 <4.0.0',
|
||||
trek: '>=3.3.0 <4.0.0',
|
||||
nativeModules: false,
|
||||
permissions: perms,
|
||||
// Dependency declarations (empty by default). `requiredAddons` lists addon ids
|
||||
@@ -63,15 +99,51 @@ export function scaffold(name: string, type: string, targetDir: string, opts: Sc
|
||||
// ({ id, version-range }) that must be installed + satisfied first.
|
||||
requiredAddons: opts.requiredAddons ?? [],
|
||||
pluginDependencies: opts.pluginDependencies ?? [],
|
||||
routes: [{ method: 'GET', path: '/hello', auth: true }],
|
||||
};
|
||||
if (opts.egress?.length) manifest.egress = opts.egress;
|
||||
if (type === 'page') manifest.capabilities = { nav: { label: manifest.name, icon: 'Blocks', position: 'main' } };
|
||||
if (type === 'widget') manifest.capabilities = { widget: { title: manifest.name, defaultSize: 'medium' } };
|
||||
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
|
||||
// real host after install; without it the plugin only ever reaches the hosts above.
|
||||
if (operatorEgress) manifest.operatorEgress = true;
|
||||
// A settings-page button so the user can verify their credentials without waiting for
|
||||
// a real notification. Actions are USER-INITIATED, so ctx.settings.get() works inside.
|
||||
if (isChannel) manifest.actions = [{ key: 'testConnection', label: 'Test connection' }];
|
||||
// Routes are declared in server/index.js (definePlugin), NOT the manifest — the
|
||||
// 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' } };
|
||||
if (isChannel) {
|
||||
manifest.capabilities = { notificationChannel: { title: displayName } };
|
||||
// The recipient's own credential. `scope: 'user'` is what makes it per-user, and
|
||||
// the host hands the decrypted value to your hook as `config` at send time.
|
||||
manifest.settings = [
|
||||
{
|
||||
key: 'serverUrl',
|
||||
label: 'Server URL',
|
||||
input_type: 'text',
|
||||
placeholder: 'https://gotify.example.com',
|
||||
hint: egress.length
|
||||
? 'Your Gotify server. Must match an entry in the manifest `egress` list.'
|
||||
: 'Your Gotify server. Its host must be allowed by an admin (Admin → Plugins → Allowed hosts).',
|
||||
required: true,
|
||||
scope: 'user',
|
||||
},
|
||||
{
|
||||
key: 'appToken',
|
||||
label: 'App token',
|
||||
input_type: 'text',
|
||||
hint: 'Create an application in Gotify and paste its token here.',
|
||||
required: true,
|
||||
secret: true,
|
||||
scope: 'user',
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
fs.writeFileSync(path.join(root, 'trek-plugin.json'), JSON.stringify(manifest, null, 2) + '\n');
|
||||
fs.writeFileSync(path.join(root, 'server', 'index.js'), SERVER_JS(perms.includes('db:own')));
|
||||
fs.writeFileSync(path.join(root, 'README.md'), readme(name, opts.description ?? '> One sentence: what this plugin does.', perms));
|
||||
fs.writeFileSync(path.join(root, 'server', 'index.js'), isChannel ? CHANNEL_JS : SERVER_JS(perms.includes('db:own')));
|
||||
fs.writeFileSync(path.join(root, 'README.md'), readme(name, opts.description ?? (isChannel ? `> Deliver your TREK notifications to ${displayName}.` : '> One sentence: what this plugin does.'), perms));
|
||||
// `type: commonjs` pins how the entry is parsed everywhere (dev, tests, TREK);
|
||||
// the SDK is a devDependency ONLY (types + mock host) — at runtime both the
|
||||
// dev server and TREK inject it, so it is never vendored into the artifact.
|
||||
@@ -89,6 +161,69 @@ export function scaffold(name: string, type: string, targetDir: string, opts: Sc
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
// ready to send. You never touch i18n, and you never pick a recipient: the host does
|
||||
// that, then calls you once per recipient who has this channel switched on.
|
||||
//
|
||||
// This hook is HOST-initiated, so there is NO acting user while it runs:
|
||||
// - ctx.settings.get() returns undefined here (it resolves against the acting user)
|
||||
// - trip reads are refused
|
||||
// The recipient's own settings — the fields you declared with scope: 'user' in
|
||||
// trek-plugin.json — arrive DECRYPTED as the \`config\` argument. That is the only way
|
||||
// to reach them, and it is why a channel plugin cannot enumerate anyone's trips.
|
||||
const { definePlugin } = require('trek-plugin-sdk');
|
||||
|
||||
async function push(config, title, message) {
|
||||
// Every host you call must be listed in the manifest's \`egress\` array AND granted
|
||||
// via http:outbound:<host>, or the child's network guard blocks the request.
|
||||
const res = await fetch(String(config.serverUrl).replace(/\\/+$/, '') + '/message', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
'X-Gotify-Key': String(config.appToken),
|
||||
},
|
||||
body: JSON.stringify({ title, message, priority: 5 }),
|
||||
});
|
||||
// Throw on failure: the host logs it and isolates it, so one dead channel can never
|
||||
// stop the others (or the in-app notification) from being delivered.
|
||||
if (!res.ok) throw new Error('Gotify responded ' + res.status + ' ' + (await res.text().catch(() => '')));
|
||||
}
|
||||
|
||||
module.exports = definePlugin({
|
||||
// A button on your settings page. USER-INITIATED, so unlike the channel hook there IS
|
||||
// an acting user (whoever clicked) — ctx.settings.get() returns THEIR values, which is
|
||||
// what makes "test my credentials" possible.
|
||||
actions: {
|
||||
async testConnection(ctx) {
|
||||
const config = {
|
||||
serverUrl: await ctx.settings.get('serverUrl'),
|
||||
appToken: await ctx.settings.get('appToken'),
|
||||
};
|
||||
await push(config, 'TREK', 'Test notification. If you can read this, your channel works.');
|
||||
return { ok: true, message: 'Connected.' };
|
||||
},
|
||||
},
|
||||
|
||||
hooks: {
|
||||
notificationChannel: {
|
||||
async send(msg, config, ctx) {
|
||||
// msg = { event, title, body, url?, tripName? } — already localized.
|
||||
const body = msg.url ? msg.body + '\\n\\n' + msg.url : msg.body;
|
||||
await push(config, msg.title, body);
|
||||
ctx.log.info('delivered ' + msg.event);
|
||||
},
|
||||
|
||||
// Optional — backs the "Send test" button in the user's notification settings.
|
||||
async test(config) {
|
||||
await push(config, 'TREK', 'Test notification. If you can read this, your channel works.');
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
`;
|
||||
|
||||
const SERVER_JS = (has_db: boolean) => `// Built plugin entry — runs in an isolated child process.
|
||||
const { definePlugin } = require('trek-plugin-sdk');
|
||||
|
||||
@@ -248,6 +383,20 @@ export async function interactiveScaffold(defaultDir: string, presetName?: strin
|
||||
],
|
||||
});
|
||||
|
||||
// A starter, not a manifest type — a notification channel is a plain `integration`
|
||||
// that implements the notificationChannel hook, so it only makes sense to offer here.
|
||||
let template: 'blank' | 'notification-channel' = 'blank';
|
||||
if (type === 'integration') {
|
||||
template = await promptSelect<'blank' | 'notification-channel'>({
|
||||
message: 'Start from a template?',
|
||||
initialValue: 'blank',
|
||||
options: [
|
||||
{ value: 'blank', label: 'blank', hint: 'an empty plugin with one example route' },
|
||||
{ value: 'notification-channel', label: 'notification channel', hint: 'deliver TREK notifications to Gotify/Pushover/…' },
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
const author = await promptText({ message: 'Author', placeholder: 'Your Name', defaultValue: 'Your Name' });
|
||||
const description = await promptText({
|
||||
message: 'One-line description',
|
||||
@@ -263,13 +412,20 @@ export async function interactiveScaffold(defaultDir: string, presetName?: strin
|
||||
});
|
||||
|
||||
let egress: string[] | undefined;
|
||||
if (permissions.includes('http:outbound')) {
|
||||
// The scaffold turns each host into a matching http:outbound:<host> grant. Leaving it
|
||||
// blank is legitimate — a plugin for a service that is only ever SELF-HOSTED has no host
|
||||
// to name, so it ships as an operatorEgress plugin and the admin adds the real host.
|
||||
if (permissions.includes('http:outbound') || template === 'notification-channel') {
|
||||
const raw = await promptText({
|
||||
message: 'External hosts it may call (comma-separated)',
|
||||
placeholder: 'api.example.com, api.other.com',
|
||||
validate: (v) => ((v ?? '').split(',').map((s) => s.trim()).filter(Boolean).length ? undefined : 'list at least one host'),
|
||||
message: template === 'notification-channel'
|
||||
? 'Which host does your notification service live on? (blank if it is always self-hosted)'
|
||||
: 'External hosts it may call (comma-separated; blank if only the admin can know them)',
|
||||
placeholder: template === 'notification-channel' ? 'gotify.example.com' : 'api.example.com, api.other.com',
|
||||
});
|
||||
egress = raw.split(',').map((s) => s.trim()).filter(Boolean);
|
||||
if (!egress.length) {
|
||||
logInfo('No hosts named — the plugin will declare operatorEgress, and the TREK admin adds the real hosts after installing it.');
|
||||
}
|
||||
}
|
||||
|
||||
const requiredAddons = await promptMultiselect<string>({
|
||||
@@ -283,10 +439,12 @@ export async function interactiveScaffold(defaultDir: string, presetName?: strin
|
||||
[
|
||||
`id ${id}`,
|
||||
`type ${type}`,
|
||||
template !== 'blank' ? `template ${template}` : undefined,
|
||||
`location ${dest}`,
|
||||
`author ${author}`,
|
||||
`permissions ${permissions.join(', ') || '(none)'}`,
|
||||
egress ? `egress ${egress.join(', ')}` : undefined,
|
||||
egress?.length ? `egress ${egress.join(', ')}` : undefined,
|
||||
egress && !egress.length ? 'egress (admin-supplied — operatorEgress)' : undefined,
|
||||
requiredAddons.length ? `addons ${requiredAddons.join(', ')}` : undefined,
|
||||
].filter(Boolean).join('\n'),
|
||||
'Review',
|
||||
@@ -298,7 +456,7 @@ export async function interactiveScaffold(defaultDir: string, presetName?: strin
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
scaffold(id, type, parentDir, { author, description, permissions, egress, requiredAddons });
|
||||
scaffold(id, type, parentDir, { author, description, permissions, egress, requiredAddons, template });
|
||||
logSuccess(`Created ${dest}`);
|
||||
|
||||
if (!insideGitRepo(parentDir)) {
|
||||
@@ -337,12 +495,14 @@ if (process.argv[1] && process.argv[1].endsWith('create.js')) {
|
||||
const name = args.find((a: string) => !a.startsWith('-'));
|
||||
const typeIdx = args.indexOf('--type');
|
||||
const type = typeIdx >= 0 ? args[typeIdx + 1] : 'integration';
|
||||
const tplIdx = args.indexOf('--template');
|
||||
const template = (tplIdx >= 0 ? args[tplIdx + 1] : 'blank') as ScaffoldOptions['template'];
|
||||
if (!name) {
|
||||
console.error('usage: create-trek-plugin <name> [--type integration|page|widget|trip-page]');
|
||||
console.error('usage: create-trek-plugin <name> [--type integration|page|widget|trip-page] [--template blank|notification-channel]');
|
||||
process.exit(2);
|
||||
}
|
||||
try {
|
||||
scaffold(name, type, process.cwd());
|
||||
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}\`.`);
|
||||
} catch (e) {
|
||||
console.error(e instanceof Error ? e.message : e);
|
||||
|
||||
+200
-35
@@ -17,16 +17,70 @@ import * as sdk from '../index.js';
|
||||
import { injectTrekUi } from '../ui/kit.js';
|
||||
import { readJsonFile } from './json.js';
|
||||
|
||||
interface Fixtures {
|
||||
config?: Record<string, unknown>;
|
||||
trips?: Record<number, { members: number[]; data?: unknown; places?: unknown[]; reservations?: unknown[] }>;
|
||||
users?: Record<number, unknown>;
|
||||
}
|
||||
// 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
|
||||
// surface (trips, costs, packing, files, users, settings, weather, ai, …), exactly the
|
||||
// shape a mock-host unit test uses. `actingUserId` binds the dev user (like the prod
|
||||
// invocation user), defaulting to 1.
|
||||
type Fixtures = NonNullable<Parameters<typeof sdk.createMockHost>[0]>;
|
||||
interface PluginRouteLike { method: string; path: string; auth?: boolean; handler: (req: unknown, ctx: unknown) => Promise<{ status: number; headers?: Record<string, string>; body?: unknown }>; }
|
||||
interface PluginLike { onLoad?: (ctx: unknown) => unknown; routes?: PluginRouteLike[]; }
|
||||
type Handler = (...a: unknown[]) => unknown;
|
||||
interface PluginLike {
|
||||
onLoad?: (ctx: unknown) => unknown;
|
||||
routes?: PluginRouteLike[];
|
||||
jobs?: Array<{ id: string; handler: Handler }>;
|
||||
scheduled?: Handler;
|
||||
events?: Array<{ on: string; handler: Handler }>;
|
||||
deleteUserData?: Handler;
|
||||
exportUserData?: Handler;
|
||||
hooks?: Record<string, Record<string, Handler>>;
|
||||
}
|
||||
|
||||
class PermissionDenied extends Error {}
|
||||
|
||||
// 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() —
|
||||
// no transaction control plus a batch-size cap. Without them a statement production
|
||||
// refuses would silently work in dev, and the author would debug a phantom.
|
||||
const MAX_SQL_LENGTH = 100_000;
|
||||
const FORBIDDEN_SQL = /\b(ATTACH|DETACH|VACUUM|PRAGMA|RECURSIVE|LOAD_EXTENSION)\b/i;
|
||||
const TX_CONTROL = /^\s*(BEGIN|COMMIT|ROLLBACK|SAVEPOINT|RELEASE|END)\b/i;
|
||||
const MAX_TX_OPS = 100;
|
||||
const MAX_ROWS = 100_000;
|
||||
|
||||
function guardSql(sql: string): void {
|
||||
if (typeof sql !== 'string') throw new Error('sql must be a string');
|
||||
if (sql.length > MAX_SQL_LENGTH) throw new Error('sql too long');
|
||||
if (FORBIDDEN_SQL.test(sql)) throw new Error('statement type not allowed for plugin databases');
|
||||
}
|
||||
|
||||
/** Strip LEADING comments/whitespace so a COMMIT hidden behind a comment can't slip
|
||||
* past the start-anchored TX_CONTROL check (mirrors the host's tx() guard). */
|
||||
function stripLeadingComments(sql: string): string {
|
||||
return String(sql ?? '').replace(/^(?:\s|--[^\n]*\n?|\/\*[\s\S]*?\*\/)*/, '');
|
||||
}
|
||||
|
||||
// The credential-free inbound-header allowlist TREK's proxy forwards to auth:false
|
||||
// routes (webhooks) — never Cookie/Authorization/session. Kept in lockstep with
|
||||
// SAFE_INBOUND_HEADERS in plugins-proxy.controller.ts.
|
||||
const SAFE_INBOUND_HEADERS = new Set([
|
||||
'content-type', 'user-agent', 'x-request-id', 'x-idempotency-key',
|
||||
'x-hub-signature', 'x-hub-signature-256', 'x-github-event', 'x-github-delivery',
|
||||
'stripe-signature',
|
||||
'svix-id', 'svix-timestamp', 'svix-signature',
|
||||
'x-gitlab-event', 'x-gitlab-token',
|
||||
'x-signature', 'x-signature-256', 'x-webhook-signature', 'x-event-type',
|
||||
]);
|
||||
|
||||
function pickInboundHeaders(raw: http.IncomingHttpHeaders): Record<string, string> {
|
||||
const out: Record<string, string> = {};
|
||||
for (const [k, v] of Object.entries(raw)) {
|
||||
if (!SAFE_INBOUND_HEADERS.has(k.toLowerCase())) continue;
|
||||
out[k.toLowerCase()] = Array.isArray(v) ? v.join(', ') : String(v ?? '');
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Accept both bind shapes the real host accepts: spread positional args AND a
|
||||
* single array of them (better-sqlite3 binds an array; node:sqlite does not,
|
||||
@@ -48,12 +102,18 @@ export function createDevDb(dbFile: string): { db: PluginContextDb; note: string
|
||||
note: `db:own → real SQLite at ${dbFile}`,
|
||||
close: () => { try { sq.close(); } catch { /* ignore */ } },
|
||||
db: {
|
||||
async query(sql: string, ...args: unknown[]) { return sq.prepare(sql).all(...flatBind(args)) as unknown[]; },
|
||||
async query(sql: string, ...args: unknown[]) {
|
||||
guardSql(sql);
|
||||
const rows = sq.prepare(sql).all(...flatBind(args)) as unknown[];
|
||||
if (rows.length > MAX_ROWS) throw new Error(`query returned more than ${MAX_ROWS} rows`);
|
||||
return rows;
|
||||
},
|
||||
async exec(sql: string, ...args: unknown[]) {
|
||||
guardSql(sql);
|
||||
if (args.length) { const r = sq.prepare(sql).run(...flatBind(args)); return { changes: Number(r.changes ?? 0) }; }
|
||||
sq.exec(sql); return { changes: 0 };
|
||||
},
|
||||
async migrate(id: string, sql: string) { if (applied.has(id)) return { applied: false }; sq.exec(sql); applied.add(id); return { applied: true }; },
|
||||
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 {
|
||||
@@ -61,9 +121,9 @@ export function createDevDb(dbFile: string): { db: PluginContextDb; note: string
|
||||
note: 'db:own → in-memory stub (upgrade to Node 22.5+ for a real SQLite dev db)',
|
||||
close: () => {},
|
||||
db: {
|
||||
async query() { return []; },
|
||||
async exec() { return { changes: 0 }; },
|
||||
async migrate() { return { applied: true }; },
|
||||
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 }; },
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -74,33 +134,74 @@ interface PluginContextDb { query(sql: string, ...a: unknown[]): Promise<unknown
|
||||
|
||||
function createDevContext(id: string, grants: Set<string>, fx: Fixtures, db: PluginContextDb, broadcasts: unknown[]) {
|
||||
const need = (perm: string, method: string) => { if (!grants.has(perm)) throw new PermissionDenied(`PERMISSION_DENIED: ${method} requires ${perm}`); };
|
||||
const member = (tripId: number, asUser: number) => {
|
||||
const t = fx.trips?.[tripId];
|
||||
if (!t || !t.members.includes(asUser)) throw new Error(`RESOURCE_FORBIDDEN: no access to trip ${tripId}`);
|
||||
return t;
|
||||
// Full parity: delegate EVERY capability to a grant-enforcing mock host (the same one
|
||||
// used in unit tests), so ctx.costs/packing/files/notify/ai/settings/scheduler/meta/
|
||||
// oauth/weather/rates/journal/… all work in dev instead of throwing TypeErrors — then
|
||||
// override just the three surfaces dev does natively: db:own (real node:sqlite so your
|
||||
// migrations/queries actually persist), ws broadcasts (captured for the dashboard),
|
||||
// and logging (to the dev console). The mock enforces the SAME grants, so a missing
|
||||
// permission fails identically here and in production.
|
||||
// Default the dev acting user to 1 (like the prod invocation user) so the documented
|
||||
// one-arg calls work on a fresh scaffold — without this, a fixtures file that omits
|
||||
// actingUserId leaves the mock userless and every user-bound capability throws.
|
||||
const mock = sdk.createMockHost({ ...fx, actingUserId: fx.actingUserId ?? 1, grants: [...grants] });
|
||||
const isRead = (sql: string) => /^\s*(SELECT|WITH|VALUES)\b/i.test(sql) || /\bRETURNING\b/i.test(sql);
|
||||
const devDb = {
|
||||
query: (sql: string, ...a: unknown[]) => { need('db:own', 'db.query'); return db.query(sql, ...a); },
|
||||
exec: (sql: string, ...a: unknown[]) => { need('db:own', 'db.exec'); return db.exec(sql, ...a); },
|
||||
migrate: (mid: string, sql: string) => { need('db:own', 'db.migrate'); return db.migrate(mid, sql); },
|
||||
// A functional (not strictly atomic) tx over the real dev db so read-modify-write
|
||||
// batches work in dev; production runs it in one better-sqlite3 transaction.
|
||||
tx: async (ops: Array<{ sql: string; args?: unknown[] }>) => {
|
||||
need('db:own', 'db.tx');
|
||||
// Validate the WHOLE batch up front, like the host's PluginDataDb.tx — a bad
|
||||
// op must fail before anything ran, not leave earlier writes behind.
|
||||
if (!Array.isArray(ops)) throw new Error('tx requires an array of { sql, args }');
|
||||
if (ops.length > MAX_TX_OPS) throw new Error(`tx allows at most ${MAX_TX_OPS} statements`);
|
||||
for (const op of ops) {
|
||||
guardSql(op?.sql as string);
|
||||
if (TX_CONTROL.test(stripLeadingComments(op?.sql as string))) throw new Error('transaction-control statements are not allowed inside tx()');
|
||||
}
|
||||
const results: Array<{ changes?: number; rows?: unknown[] }> = [];
|
||||
for (const op of ops) {
|
||||
if (isRead(op.sql)) results.push({ rows: await db.query(op.sql, ...(op.args ?? [])) as unknown[] });
|
||||
else { const r = await db.exec(op.sql, ...(op.args ?? [])) as { changes?: number }; results.push({ changes: r?.changes ?? 0 }); }
|
||||
}
|
||||
return { results };
|
||||
},
|
||||
};
|
||||
return {
|
||||
id, config: Object.freeze({ ...(fx.config ?? {}) }),
|
||||
db: {
|
||||
query: (sql: string, ...a: unknown[]) => { need('db:own', 'db.query'); return db.query(sql, ...a); },
|
||||
exec: (sql: string, ...a: unknown[]) => { need('db:own', 'db.exec'); return db.exec(sql, ...a); },
|
||||
migrate: (mid: string, sql: string) => { need('db:own', 'db.migrate'); return db.migrate(mid, sql); },
|
||||
},
|
||||
trips: {
|
||||
getById: async (t: number, u: number) => { need('db:read:trips', 'trips.getById'); return member(t, u).data ?? null; },
|
||||
getPlaces: async (t: number, u: number) => { need('db:read:trips', 'trips.getPlaces'); return member(t, u).places ?? []; },
|
||||
getReservations: async (t: number, u: number) => { need('db:read:trips', 'trips.getReservations'); return member(t, u).reservations ?? []; },
|
||||
},
|
||||
users: { getById: async (uid: number) => { need('db:read:users', 'users.getById'); return fx.users?.[uid] ?? null; } },
|
||||
const wrap = (base: typeof mock.ctx, actingUserId: number | undefined) => ({
|
||||
...base,
|
||||
id,
|
||||
db: devDb,
|
||||
ws: {
|
||||
broadcastToTrip: async (t: number, event: string, data: unknown) => { need('ws:broadcast:trip', 'ws.broadcastToTrip'); broadcasts.push({ kind: 'trip', target: t, event, data }); },
|
||||
broadcastToUser: async (u: number, event: string, data: unknown) => { need('ws:broadcast:user', 'ws.broadcastToUser'); broadcasts.push({ kind: 'user', target: u, event, data }); },
|
||||
// Same target gates as production: a trip room only for a member acting user,
|
||||
// a user push only to the acting user themself.
|
||||
broadcastToTrip: async (t: number, event: string, data: unknown) => {
|
||||
need('ws:broadcast:trip', 'ws.broadcastToTrip');
|
||||
if (actingUserId === undefined) throw new Error('RESOURCE_FORBIDDEN: broadcasts require an authenticated user context');
|
||||
const trip = fx.trips?.[t];
|
||||
if (!trip || !trip.members.includes(actingUserId)) throw new Error(`RESOURCE_FORBIDDEN: no access to trip ${t}`);
|
||||
broadcasts.push({ kind: 'trip', target: t, event, data });
|
||||
},
|
||||
broadcastToUser: async (u: number, event: string, data: unknown) => {
|
||||
need('ws:broadcast:user', 'ws.broadcastToUser');
|
||||
if (actingUserId === undefined || u !== actingUserId) throw new Error('RESOURCE_FORBIDDEN: a plugin may only broadcast to the acting user');
|
||||
broadcasts.push({ kind: 'user', target: u, event, data });
|
||||
},
|
||||
},
|
||||
log: {
|
||||
info: (m: string) => console.log(` [plugin] ${m}`),
|
||||
warn: (m: string) => console.warn(` [plugin] ${m}`),
|
||||
error: (m: string) => console.error(` [plugin] ${m}`),
|
||||
},
|
||||
});
|
||||
// Routes (and hooks) run user-bound; jobs, scheduled tasks, event deliveries and the
|
||||
// GDPR handlers run with NO acting user — exactly the split production makes, so a
|
||||
// membership read from a job fails here the same way it would in TREK.
|
||||
return {
|
||||
ctx: wrap(mock.ctx, fx.actingUserId ?? 1),
|
||||
userlessCtx: wrap(mock.userlessCtx, undefined),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -165,7 +266,21 @@ export async function runDev(dir: string, opts: { port?: number } = {}): Promise
|
||||
|
||||
let plugin: PluginLike = {};
|
||||
let version = 0;
|
||||
const ctx = createDevContext(id, grants, fx, db, broadcasts);
|
||||
const { ctx, userlessCtx } = createDevContext(id, grants, fx, db, broadcasts);
|
||||
const port = opts.port ?? 4317;
|
||||
|
||||
// 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
|
||||
// Origin on cross-origin fetches — refuse an Origin that isn't this dev server.
|
||||
// curl/devtools-on-the-page pass both checks.
|
||||
const isCrossSite = (request: http.IncomingMessage): boolean => {
|
||||
const site = request.headers['sec-fetch-site'];
|
||||
if (typeof site === 'string' && site !== 'same-origin' && site !== 'none') return true;
|
||||
const origin = request.headers['origin'];
|
||||
if (typeof origin === 'string' && origin !== `http://localhost:${port}` && origin !== `http://127.0.0.1:${port}`) return true;
|
||||
return false;
|
||||
};
|
||||
|
||||
const load = async () => {
|
||||
const entry = path.join(abs, 'server', 'index.js');
|
||||
@@ -200,6 +315,41 @@ export async function runDev(dir: string, opts: { port?: number } = {}): Promise
|
||||
};
|
||||
|
||||
if (url.pathname === '/__dev/version') return send(200, String(version));
|
||||
|
||||
// Fire a NON-route entry point against the dev ctx — the half the dev server used to
|
||||
// be unable to reach. GET /__dev/fire/<kind>[/<name>][/<fn>], e.g.
|
||||
// /__dev/fire/job/refresh · /__dev/fire/scheduled/daily · /__dev/fire/event/place:created
|
||||
// /__dev/fire/hook/tripCardProvider/getCards · /__dev/fire/deleteUserData
|
||||
// Query params become the payload/args; a JSON body is used verbatim when present.
|
||||
if (url.pathname.startsWith('/__dev/fire/')) {
|
||||
// These endpoints are side-effectful (fire a job, wipe user data, …). Even bound to
|
||||
// loopback, a drive-by <img src="http://127.0.0.1:PORT/__dev/fire/deleteUserData?…">
|
||||
// from an open browser tab could hit them — block a cross-site request.
|
||||
if (isCrossSite(request)) return send(403, 'cross-site request refused');
|
||||
const [kind, name, fn] = url.pathname.slice('/__dev/fire/'.length).split('/');
|
||||
const bodyRaw = await readBody(request); // already JSON-parsed when sent as application/json
|
||||
let payload: unknown = bodyRaw;
|
||||
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 {
|
||||
// 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.
|
||||
let out: unknown;
|
||||
if (kind === 'job') { const j = plugin.jobs?.find((x) => x.id === name); if (!j) return send(404, `no job "${name}"`); out = await j.handler(userlessCtx); }
|
||||
else if (kind === 'scheduled') { if (!plugin.scheduled) return send(404, 'plugin has no scheduled handler'); out = await plugin.scheduled({ name, payload }, userlessCtx); }
|
||||
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 return send(400, `unknown fire kind "${kind}"`);
|
||||
return send(200, JSON.stringify(out ?? { ok: true }, null, 2), 'application/json; charset=utf-8');
|
||||
} catch (e) {
|
||||
const denied = e instanceof PermissionDenied;
|
||||
return send(denied ? 403 : 500, e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
}
|
||||
|
||||
if (url.pathname === '/') return send(200, dashboard(id, String(manifest.type), plugin.routes ?? [], dbNote, broadcasts.length), 'text/html; charset=utf-8');
|
||||
|
||||
// Faithful host preview: embeds /ui in a sandboxed opaque-origin iframe (exactly
|
||||
@@ -229,16 +379,24 @@ export async function runDev(dir: string, opts: { port?: number } = {}): Promise
|
||||
|
||||
// Plugin API routes mounted under /api/<route path>
|
||||
if (url.pathname.startsWith('/api/')) {
|
||||
// Same drive-by guard as /__dev/fire: routes are side-effectful against the real
|
||||
// dev db with no auth — an off-site page must not reach them on 127.0.0.1.
|
||||
if (isCrossSite(request)) return send(403, 'cross-site request refused');
|
||||
const pluginPath = url.pathname.slice('/api'.length); // "/api/hello" -> "/hello"
|
||||
const route = (plugin.routes ?? []).find((r) => r.method.toUpperCase() === request.method && r.path === pluginPath);
|
||||
if (!route) return send(404, `no ${request.method} route ${pluginPath}`);
|
||||
const anon = url.searchParams.get('_anon') === '1';
|
||||
if (route.auth !== false && anon) return send(401, 'this route requires auth (drop ?_anon=1 to send the dev user)');
|
||||
const user = anon ? null : { id: 1, username: 'dev', isAdmin: true };
|
||||
// The dev user matches the ctx's acting user and is a regular account — the prod
|
||||
// proxy never hands a plugin an admin session it didn't authenticate.
|
||||
const user = anon ? null : { id: fx.actingUserId ?? 1, username: 'dev', isAdmin: false };
|
||||
const body = await readBody(request);
|
||||
const query: Record<string, unknown> = {}; url.searchParams.forEach((v, k) => { if (k !== '_anon') query[k] = v; });
|
||||
// headers is always present on a PluginRequest; only auth:false routes (webhooks)
|
||||
// receive the allowlisted, credential-free inbound subset — like the prod proxy.
|
||||
const headers = route.auth === false ? pickInboundHeaders(request.headers) : {};
|
||||
try {
|
||||
const r = await route.handler({ method: route.method, path: route.path, query, body, user }, ctx);
|
||||
const r = await route.handler({ method: route.method, path: route.path, query, body, headers, user }, ctx);
|
||||
const out = typeof r.body === 'string' || Buffer.isBuffer(r.body) ? String(r.body) : JSON.stringify(r.body ?? null);
|
||||
return send(r.status ?? 200, out, r.headers?.['content-type'] || 'application/json; charset=utf-8', r.headers ?? {});
|
||||
} catch (e) {
|
||||
@@ -249,11 +407,12 @@ export async function runDev(dir: string, opts: { port?: number } = {}): Promise
|
||||
return send(404, 'not found');
|
||||
}
|
||||
|
||||
const port = opts.port ?? 4317;
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once('error', (e: NodeJS.ErrnoException) =>
|
||||
reject(e.code === 'EADDRINUSE' ? new Error(`port ${port} is already in use — pass --port <n> to pick another`) : e));
|
||||
server.listen(port, resolve);
|
||||
// Bind loopback only: the dev server serves the plugin's routes AND the side-effectful
|
||||
// /__dev/fire endpoints against a real db with no auth — never expose that to the LAN.
|
||||
server.listen(port, '127.0.0.1', resolve);
|
||||
});
|
||||
const routes = plugin.routes ?? [];
|
||||
console.log(`\n trek-plugin dev — ${id} (${String(manifest.type)})`);
|
||||
@@ -385,6 +544,12 @@ window.addEventListener("message", function(ev){
|
||||
else if(m.type==="trek:resize"){ if(m.height>0) f.style.height=Math.min(m.height,2000)+"px"; }
|
||||
else if(m.type==="trek:notify"){ toast((m.level?("["+m.level+"] "):"")+(m.message||"")); }
|
||||
else if(m.type==="trek:navigate"){ toast("navigate \\u2192 "+m.to); }
|
||||
else if(m.type==="trek:openExternal"){ toast("openExternal \\u2192 "+m.url); try{ var u=new URL(String(m.url||"")); if(u.protocol==="https:"||u.protocol==="http:") window.open(u.href,"_blank","noopener,noreferrer"); }catch(e){} }
|
||||
else if(m.type==="trek:confirm"){
|
||||
// Mirror the host contract so trek.confirm() resolves in the preview too.
|
||||
var ok=window.confirm((m.title?m.title+"\\n\\n":"")+(m.message||""));
|
||||
f.contentWindow.postMessage({type:"trek:confirm:result",requestId:m.requestId,confirmed:ok},"*");
|
||||
}
|
||||
else if(m.type==="trek:invoke"){
|
||||
fetch("/api"+m.sub,{method:m.method||"GET",headers:{"content-type":"application/json"},body:m.body!=null?JSON.stringify(m.body):undefined})
|
||||
.then(function(r){var ct=r.headers.get("content-type")||"";return (ct.indexOf("json")>=0?r.json():r.text());})
|
||||
|
||||
@@ -19,7 +19,7 @@ import { readJsonFile } from './json.js';
|
||||
interface Version {
|
||||
version: string; gitTag: string; commitSha: string; downloadUrl: string;
|
||||
sha256: string; minTrekVersion: string; size: number; apiVersion: number;
|
||||
nativeModules: false; publishedAt: string; signature?: string;
|
||||
nativeModules: false; operatorEgress?: boolean; publishedAt: string; signature?: string;
|
||||
}
|
||||
interface Entry {
|
||||
id: string; name: string; author: string; description: string; repo: string;
|
||||
@@ -68,6 +68,10 @@ export function buildEntry(opts: {
|
||||
nativeModules: false,
|
||||
publishedAt: opts.now,
|
||||
};
|
||||
// Mirror the manifest's operatorEgress onto the entry — CI parity-checks it, because the
|
||||
// flag says the egress[] list is NOT the plugin's full network reach (an admin may add
|
||||
// hosts after install). Only emitted when true, so ordinary entries stay unchanged.
|
||||
if (manifest.operatorEgress === true) version.operatorEgress = true;
|
||||
|
||||
// Optional author signature over the exact artifact bytes.
|
||||
let authorPublicKey: string | undefined;
|
||||
|
||||
@@ -18,7 +18,7 @@ const NATIVE_RE = /(^|\/)[^/]+\.node$|(^|\/)binding\.gyp$|(^|\/)prebuilds?\//i;
|
||||
|
||||
export interface EntryVersion {
|
||||
version: string; gitTag: string; commitSha: string; downloadUrl: string;
|
||||
sha256: string; size: number; apiVersion: number; nativeModules?: boolean; signature?: 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[];
|
||||
@@ -81,10 +81,19 @@ export async function preflight(entry: Entry, opts: { all?: boolean } = {}): Pro
|
||||
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[]) : [];
|
||||
if (!egress.length) fail(`${tag}: http:outbound declared but egress[] is empty`);
|
||||
// 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`);
|
||||
|
||||
@@ -93,6 +93,7 @@ export const PERMISSION_CATALOG: { value: string; label: string; hint: string }[
|
||||
{ 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)' },
|
||||
|
||||
@@ -38,6 +38,15 @@ export function validatePluginDir(dir: string): ValidateReport {
|
||||
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));
|
||||
}
|
||||
@@ -54,6 +63,19 @@ export function validatePluginDir(dir: string): ValidateReport {
|
||||
}
|
||||
}
|
||||
|
||||
// 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)');
|
||||
|
||||
|
||||
+417
-15
@@ -26,27 +26,233 @@ export interface User { id: number; username?: string; display_name?: string | n
|
||||
export interface PluginContext {
|
||||
readonly id: string;
|
||||
readonly config: Readonly<Record<string, unknown>>;
|
||||
/** The ACTING USER's own value for one of this plugin's `scope:'user'` settings fields
|
||||
* (decrypted host-side). Undefined for an unset value or a userless context (job/onLoad)
|
||||
* — fall back to `config` (the admin-owned instance settings) there. */
|
||||
settings: {
|
||||
get(key: string): Promise<unknown>;
|
||||
};
|
||||
db: {
|
||||
query<T = unknown>(sql: string, ...args: unknown[]): Promise<T[]>;
|
||||
exec(sql: string, ...args: unknown[]): Promise<{ changes: number }>;
|
||||
migrate(id: string, sql: string): Promise<{ applied: boolean }>;
|
||||
/** Run several statements atomically on your OWN db — all commit or all roll
|
||||
* back. Each op is one statement; reads see the batch's own earlier writes.
|
||||
* A read returns `{ rows }`, a write `{ changes }`. Max 100 statements. */
|
||||
tx(ops: Array<{ sql: string; args?: unknown[] }>): Promise<{ results: Array<{ changes?: number; rows?: unknown[] }> }>;
|
||||
};
|
||||
trips: {
|
||||
getById(tripId: number, asUserId?: number): Promise<Trip | null>;
|
||||
getPlaces(tripId: number, asUserId?: number): Promise<Place[]>;
|
||||
/** Hydrated like the REST list: each row carries `endpoints`, `day_positions` + the day/place joins. */
|
||||
getReservations(tripId: number, asUserId?: number): Promise<Reservation[]>;
|
||||
/** The trip's days with their `assignments` + `notes_items` (the planner GET's shape). Needs `db:read:trips`. */
|
||||
getDays(tripId: number): Promise<Day[]>;
|
||||
/** The trip's lodging blocks (day_accommodations) with joined place fields. Needs `db:read:trips`. */
|
||||
getAccommodations(tripId: number): Promise<unknown[]>;
|
||||
/** Every trip the acting user owns or is a member of (for dashboards/aggregates). Needs `db:read:trips`. */
|
||||
listMine(): Promise<Trip[]>;
|
||||
/** Update trip fields; needs `db:write:trips` + the acting user's trip_edit permission. Route context only. */
|
||||
update(tripId: number, input: Record<string, unknown>): Promise<Trip>;
|
||||
/** Create a new trip owned by the acting user (importers). `title` required. Needs `db:create:trips` + the acting user's trip_create. */
|
||||
create(input: { title: string; description?: string; start_date?: string; end_date?: string; currency?: string; reminder_days?: number; day_count?: number }): Promise<Trip>;
|
||||
/** The trip's member roster (id + display fields only). Membership-checked. Needs `db:read:trips`. */
|
||||
members(tripId: number): Promise<User[]>;
|
||||
/** Add a user to a trip (GRANTS ACCESS — its own permission). Needs `db:write:members` + the acting user's member_manage. */
|
||||
addMember(tripId: number, userId: number): Promise<{ joined: boolean; tripId: number }>;
|
||||
/** Remove a member from a trip (not the owner). Needs `db:write:members` + member_manage. */
|
||||
removeMember(tripId: number, userId: number): Promise<{ removed: boolean }>;
|
||||
};
|
||||
// Reservations (bookings). `listMine` reads across every accessible trip (needs
|
||||
// `db:read:trips`); create/update/delete need `db:write:reservations` + the acting
|
||||
// user's reservation_edit permission, and reuse the app's accommodation/budget/
|
||||
// notification side effects 1:1.
|
||||
reservations: {
|
||||
/** Every reservation across the acting user's accessible trips. Needs `db:read:trips`. */
|
||||
listMine(): Promise<Reservation[]>;
|
||||
/** Create a booking on a trip. An `endpoints` array (from/to/stop legs for flights,
|
||||
* trains, ferries) is persisted with it. */
|
||||
create(tripId: number, input: Record<string, unknown>): Promise<Reservation>;
|
||||
/** Update a booking. `endpoints` semantics: omitted = keep, [] = delete all,
|
||||
* array = replace (endpoint ids are NOT stable). */
|
||||
update(tripId: number, reservationId: number, input: Record<string, unknown>): Promise<Reservation>;
|
||||
delete(tripId: number, reservationId: number): Promise<{ deleted: boolean }>;
|
||||
};
|
||||
// Lodging blocks (day_accommodations): a hotel span from a start day to an end day.
|
||||
// Reads ride on `db:read:trips` (ctx.trips.getAccommodations); writes need
|
||||
// `db:write:accommodations` + the acting user's day_edit permission (like the REST
|
||||
// path — accommodations live in the day service, not the bookings one). Creating one
|
||||
// auto-creates its partner hotel reservation, exactly like the app.
|
||||
accommodations: {
|
||||
create(tripId: number, input: { place_id: number; start_day_id: number; end_day_id: number; check_in?: string | null; check_in_end?: string | null; check_out?: string | null; confirmation?: string | null; notes?: string | null }): Promise<unknown>;
|
||||
update(tripId: number, accommodationId: number, input: Record<string, unknown>): Promise<unknown>;
|
||||
delete(tripId: number, accommodationId: number): Promise<{ deleted: boolean }>;
|
||||
};
|
||||
// Read-only views of other trip subsystems (#1429 eco). Membership-checked against
|
||||
// the current user; each needs its own db:read:* scope.
|
||||
packing: {
|
||||
/** A trip's packing items (hydrated bags/assignees). Needs `db:read:packing`. */
|
||||
list(tripId: number): Promise<PackingItem[]>;
|
||||
/** Add a packing item (owner = acting user). Needs `db:write:packing` + packing_edit. */
|
||||
create(tripId: number, input: { name: string; category?: string; checked?: boolean; is_private?: boolean; visibility?: 'common' | 'personal' | 'shared'; recipient_ids?: number[] }): Promise<PackingItem>;
|
||||
/** Update a packing item. Needs `db:write:packing` + packing_edit. */
|
||||
update(tripId: number, itemId: number, input: Record<string, unknown>): Promise<PackingItem>;
|
||||
/** Delete a packing item. Needs `db:write:packing` + packing_edit. */
|
||||
delete(tripId: number, itemId: number): Promise<{ deleted: boolean }>;
|
||||
/** List/create/update/delete packing bags + set members (no privacy). Needs `db:write:packing` + packing_edit. */
|
||||
listBags(tripId: number): Promise<unknown[]>;
|
||||
createBag(tripId: number, input: { name: string; color?: string }): Promise<unknown>;
|
||||
updateBag(tripId: number, bagId: number, input: Record<string, unknown>): Promise<unknown>;
|
||||
deleteBag(tripId: number, bagId: number): Promise<{ deleted: boolean }>;
|
||||
setBagMembers(tripId: number, bagId: number, userIds: number[]): Promise<unknown>;
|
||||
};
|
||||
files: {
|
||||
/** A trip's files, trash excluded. Needs `db:read:files`. */
|
||||
list(tripId: number): Promise<TripFile[]>;
|
||||
/** A file's bytes as base64 (10MB cap; trashed files refused). Needs `db:read:files:content`. */
|
||||
getContent(tripId: number, fileId: number): Promise<{ name: string; mimetype: string; size: number; content_base64: string }>;
|
||||
/** Store base64 content as a trip file (10MB cap, blocked extensions refused). Needs `db:write:files` + file_upload. */
|
||||
create(tripId: number, input: { name: string; content_base64: string; mimetype?: string; description?: string; place_id?: number; reservation_id?: number }): Promise<TripFile>;
|
||||
/** Link an existing file to a same-trip reservation/place/assignment. Needs `db:write:files` + file_edit. */
|
||||
createLink(tripId: number, fileId: number, opts: { reservation_id?: number; assignment_id?: number; place_id?: number }): Promise<unknown>;
|
||||
/** Update a file's description/links. Needs `db:write:files` + file_edit. */
|
||||
update(tripId: number, fileId: number, input: { description?: string; place_id?: number | null; reservation_id?: number | null }): Promise<TripFile>;
|
||||
/** Move a file to the trash. Needs `db:write:files` + file_delete. */
|
||||
softDelete(tripId: number, fileId: number): Promise<{ deleted: boolean }>;
|
||||
};
|
||||
/** Collab content (notes/polls/chat). Reads need `db:read:collab`; writes need `db:write:collab` + the acting user's collab_edit. Both need the Collab addon. */
|
||||
collab: {
|
||||
/** A trip's collab notes (hydrated with author + attachments). Needs `db:read:collab`. */
|
||||
listNotes(tripId: number): Promise<unknown[]>;
|
||||
/** A trip's polls (with options + voters). Needs `db:read:collab`. */
|
||||
listPolls(tripId: number): Promise<unknown[]>;
|
||||
/** A trip's chat messages (newest 100, oldest first; `before` = a message id to page back). Needs `db:read:collab`. */
|
||||
listMessages(tripId: number, before?: number): Promise<unknown[]>;
|
||||
createNote(tripId: number, input: { title: string; content?: string; category?: string; color?: string; website?: string; pinned?: boolean }): Promise<unknown>;
|
||||
createPoll(tripId: number, input: { question: string; options: unknown[]; multiple?: boolean; deadline?: string }): Promise<unknown>;
|
||||
votePoll(tripId: number, pollId: number, optionIndex: number): Promise<unknown>;
|
||||
createMessage(tripId: number, text: string, replyTo?: number): Promise<unknown>;
|
||||
};
|
||||
/** Host-mediated notification. The plugin supplies only target + plain text; the host
|
||||
* owns delivery + preferences. Recipient is FORCED to the acting user (scope 'user',
|
||||
* targetId = the acting user) or a trip they belong to (scope 'trip'). Needs `notify:send`. */
|
||||
notify: {
|
||||
send(input: { title: string; body: string; link?: string; scope: 'user' | 'trip'; targetId: number }): Promise<{ sent: boolean }>;
|
||||
};
|
||||
/** Host-mediated LLM using the admin/user-configured provider — the plugin never holds a
|
||||
* key. `complete` returns { text }; `extract` returns { results } for your JSON schema.
|
||||
* Output is DATA: to persist it, push it through the gated write methods yourself. Needs `ai:invoke`. */
|
||||
ai: {
|
||||
complete(prompt: string, system?: string): Promise<{ text: string }>;
|
||||
extract(text: string, jsonSchema: object, prompt?: string): Promise<{ results: Record<string, unknown>[] }>;
|
||||
};
|
||||
/** Host-brokered outbound OAuth: a short-lived access token for the ACTING USER of a
|
||||
* third-party service the host connected on their behalf (Settings → Plugins → Connect).
|
||||
* Returns null when the user hasn't connected or in a userless context. The host holds
|
||||
* the refresh token + client secret — you never see them. Needs `oauth:client`. */
|
||||
oauth: {
|
||||
getAccessToken(): Promise<string | null>;
|
||||
};
|
||||
/** Persistent, userless scheduling — a future callback into your `scheduled` handler
|
||||
* that survives restarts. Same risk class + grant as background jobs: needs `jobs:run`,
|
||||
* runs with NO acting user (trip reads refused; own db + declared egress only). Caps:
|
||||
* up to 100 tasks/plugin, 8 KB payload, recurring interval >= 60 s, <= ~1 year out.
|
||||
* `set` is an upsert by name; `cancel` removes it. */
|
||||
scheduler: {
|
||||
/** Fire once at an absolute epoch-ms time. */
|
||||
at(whenMs: number, name: string, payload?: unknown): Promise<{ scheduled: boolean }>;
|
||||
/** Fire once after `ms` from now. */
|
||||
in(ms: number, name: string, payload?: unknown): Promise<{ scheduled: boolean }>;
|
||||
/** Fire repeatedly every `ms` (first fire after `ms`). */
|
||||
every(ms: number, name: string, payload?: unknown): Promise<{ scheduled: boolean }>;
|
||||
/** Cancel a scheduled task by name. */
|
||||
cancel(name: string): Promise<{ cancelled: boolean }>;
|
||||
};
|
||||
/** Host weather cache by coordinates (+ optional YYYY-MM-DD). Tenant-free. Needs `weather:read`. */
|
||||
weather: {
|
||||
get(lat: number, lng: number, date?: string): Promise<unknown>;
|
||||
};
|
||||
/** Exchange rates (tenant-free, cached upstream). Needs `rates:read`. */
|
||||
rates: {
|
||||
/** A map of quote → rate relative to `base` (e.g. base 'EUR' → { USD: 1.08, ... }). `null` on an upstream failure. */
|
||||
get(base: string): Promise<Record<string, number> | null>;
|
||||
};
|
||||
/** The global place-category reference list (read-only). Needs `db:read:categories`. */
|
||||
categories: {
|
||||
list(): Promise<unknown[]>;
|
||||
};
|
||||
/** The acting user's own tags. Needs `db:read:tags` (list) / `db:write:tags` (create/update/delete). */
|
||||
tags: {
|
||||
list(): Promise<unknown[]>;
|
||||
create(input: { name: string; color?: string }): Promise<unknown>;
|
||||
update(tagId: number, input: { name?: string; color?: string }): Promise<unknown>;
|
||||
delete(tagId: number): Promise<{ deleted: boolean }>;
|
||||
};
|
||||
/** A trip's to-dos. Needs `db:read:todos` (list) / `db:write:todos` + packing_edit (create/update/delete). */
|
||||
todos: {
|
||||
list(tripId: number): Promise<unknown[]>;
|
||||
create(tripId: number, input: { name: string; category?: string; due_date?: string; description?: string; assigned_user_id?: number; priority?: number }): Promise<unknown>;
|
||||
update(tripId: number, todoId: number, input: Record<string, unknown>): Promise<unknown>;
|
||||
delete(tripId: number, todoId: number): Promise<{ deleted: boolean }>;
|
||||
};
|
||||
// The acting user's OWN subsystem data across all their trips (not one trip), each
|
||||
// gated on its addon being enabled — mirrors the addon's own REST/MCP readers.
|
||||
journal: {
|
||||
/** The acting user's journals. Needs `db:read:journal` + the journey addon. */
|
||||
listMine(): Promise<unknown[]>;
|
||||
/** The entries of one of the acting user's journeys (photos/story/checkins), access-checked. Needs `db:read:journal`. */
|
||||
getEntries(journeyId: number): Promise<unknown[]>;
|
||||
/** Create an entry on a journey the acting user can edit. Needs `db:write:journal`. */
|
||||
createEntry(journeyId: number, input: { entry_date: string; [k: string]: unknown }): Promise<unknown>;
|
||||
/** Create a journal owned by the acting user (importers bootstrap the journal they fill). Needs `db:write:journal`. */
|
||||
createJourney(input: { title: string; subtitle?: string; trip_ids?: number[] }): Promise<unknown>;
|
||||
/** Delete one of the acting user's journals. Needs `db:write:journal`. */
|
||||
deleteJourney(journeyId: number): Promise<{ deleted: boolean }>;
|
||||
/** Update an entry (owner/contributor-gated). Needs `db:write:journal`. */
|
||||
updateEntry(entryId: number, input: Record<string, unknown>): Promise<unknown>;
|
||||
/** Delete an entry (owner/contributor-gated). Needs `db:write:journal`. */
|
||||
deleteEntry(entryId: number): Promise<{ deleted: boolean }>;
|
||||
};
|
||||
atlas: {
|
||||
/** The acting user's visited countries + regions. Needs `db:read:atlas` + the atlas addon. */
|
||||
visited(): Promise<{ countries: unknown[]; regions: unknown[] }>;
|
||||
/** The acting user's bucket-list items. Needs `db:read:atlas`. */
|
||||
bucketList(): Promise<unknown[]>;
|
||||
/** Mark/unmark the ACTING USER's own visited countries/regions + bucket list. Needs `db:write:atlas`. */
|
||||
markCountry(code: string): Promise<unknown>;
|
||||
unmarkCountry(code: string): Promise<unknown>;
|
||||
markRegion(regionCode: string, countryCode: string, regionName?: string): Promise<unknown>;
|
||||
unmarkRegion(regionCode: string): Promise<unknown>;
|
||||
createBucketItem(input: { name: string; lat?: number; lng?: number; country_code?: string; notes?: string; target_date?: string }): Promise<unknown>;
|
||||
deleteBucketItem(itemId: number): Promise<{ deleted: boolean }>;
|
||||
};
|
||||
vacay: {
|
||||
/** The acting user's vacation plan data. Needs `db:read:vacay` + the vacay addon. */
|
||||
mine(): Promise<unknown>;
|
||||
/** Toggle the ACTING USER's own PTO day on their active plan. Needs `db:write:vacay`. */
|
||||
toggleEntry(date: string): Promise<{ action: string }>;
|
||||
/** Toggle a company holiday on the acting user's active plan. Needs `db:write:vacay`. */
|
||||
toggleCompanyHoliday(date: string, note?: string): Promise<{ action: string }>;
|
||||
};
|
||||
collections: {
|
||||
/** The acting user's saved-place collections. Needs `db:read:collections` + the collections addon. */
|
||||
listMine(): Promise<unknown>;
|
||||
/** One of the acting user's collections by id. Needs `db:read:collections` + the collections addon. */
|
||||
get(id: number): Promise<unknown>;
|
||||
/** Collections write (per-collection role enforced by the service). Needs `db:write:collections`. */
|
||||
create(input: Record<string, unknown>): Promise<unknown>;
|
||||
update(id: number, input: Record<string, unknown>): Promise<unknown>;
|
||||
savePlace(input: Record<string, unknown>): Promise<unknown>;
|
||||
copyToTrip(input: Record<string, unknown>): Promise<unknown>;
|
||||
deletePlace(placeId: number): Promise<{ deleted: boolean }>;
|
||||
};
|
||||
daynotes: {
|
||||
/** A day's notes on a trip (membership-checked). Needs `db:read:daynotes`. */
|
||||
list(tripId: number, dayId: number): Promise<unknown[]>;
|
||||
/** Add a note to a day. Needs `db:write:daynotes` + the acting user's day_edit. */
|
||||
create(tripId: number, dayId: number, input: Record<string, unknown>): Promise<unknown>;
|
||||
/** Update a day note. Needs `db:write:daynotes` + day_edit. */
|
||||
update(tripId: number, dayId: number, noteId: number, input: Record<string, unknown>): Promise<unknown>;
|
||||
/** Delete a day note. Needs `db:write:daynotes` + day_edit. */
|
||||
delete(tripId: number, dayId: number, noteId: number): Promise<{ deleted: boolean }>;
|
||||
};
|
||||
// "Costs" = budget items. The acting user is bound by the host to the current
|
||||
// invocation; create/update/delete also need 'budget_edit' and the Costs addon
|
||||
@@ -78,10 +284,10 @@ export interface PluginContext {
|
||||
// entities without forking the schema. Needs `db:meta`; the entity must belong to
|
||||
// a trip the current user can access. Values are JSON-serialisable.
|
||||
meta: {
|
||||
get(entityType: 'trip' | 'place' | 'day', entityId: number, key: string): Promise<unknown>;
|
||||
set(entityType: 'trip' | 'place' | 'day', entityId: number, key: string, value: unknown): Promise<unknown>;
|
||||
list(entityType: 'trip' | 'place' | 'day', entityId: number): Promise<Record<string, unknown>>;
|
||||
delete(entityType: 'trip' | 'place' | 'day', entityId: number, key: string): Promise<{ deleted: boolean }>;
|
||||
get(entityType: 'trip' | 'place' | 'day' | 'reservation' | 'accommodation', entityId: number, key: string): Promise<unknown>;
|
||||
set(entityType: 'trip' | 'place' | 'day' | 'reservation' | 'accommodation', entityId: number, key: string, value: unknown): Promise<unknown>;
|
||||
list(entityType: 'trip' | 'place' | 'day' | 'reservation' | 'accommodation', entityId: number): Promise<Record<string, unknown>>;
|
||||
delete(entityType: 'trip' | 'place' | 'day' | 'reservation' | 'accommodation', entityId: number, key: string): Promise<{ deleted: boolean }>;
|
||||
};
|
||||
users: { getById(id: number): Promise<User | null> };
|
||||
ws: {
|
||||
@@ -111,6 +317,11 @@ export interface PluginRequest {
|
||||
path: string;
|
||||
query: Record<string, unknown>;
|
||||
body: unknown;
|
||||
/** Inbound headers — ONLY populated on `auth:false` routes (webhooks), and only an
|
||||
* explicit, credential-free allowlist (signature + event headers from the common
|
||||
* providers; never Cookie/Authorization/session). Empty on authenticated routes.
|
||||
* Verify a provider signature against a secret you hold in `ctx.config`/`ctx.settings`. */
|
||||
headers: Record<string, string>;
|
||||
user: { id: number; username: string; isAdmin: boolean } | null;
|
||||
}
|
||||
export interface PluginResponse {
|
||||
@@ -141,9 +352,55 @@ export interface Photo {
|
||||
takenAt?: string;
|
||||
}
|
||||
export interface PhotoProvider {
|
||||
search(query: string, opts: { page: number; limit: number }): Promise<{ photos: Photo[]; total: number; hasMore: boolean }>;
|
||||
getById(id: string): Promise<Photo | null>;
|
||||
/** Search your photo backend. `ctx` is the last arg so you can reach it via
|
||||
* ctx.settings/oauth/http. Needs `hook:photo-provider`. Surfaced in the photo picker
|
||||
* and at `GET /api/plugin-photos/search`; thumbnail/full URLs must be http/https. */
|
||||
search(query: string, opts: { page: number; limit: number }, ctx: PluginContext): Promise<{ photos: Photo[]; total: number; hasMore: boolean }>;
|
||||
getById(id: string, ctx: PluginContext): Promise<Photo | null>;
|
||||
}
|
||||
/**
|
||||
* A notification, already rendered by the host into the recipient's language.
|
||||
* A channel plugin never touches i18n — it only delivers.
|
||||
*/
|
||||
export interface NotificationMessage {
|
||||
/** The TREK event that produced this, e.g. `trip_invite`. */
|
||||
event: string;
|
||||
title: string;
|
||||
body: string;
|
||||
/** Absolute deep link back into TREK, when the event has one. */
|
||||
url?: string;
|
||||
tripName?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deliver TREK notifications over a channel TREK doesn't ship (Gotify, Pushover, …).
|
||||
* Needs `hook:notification-channel`.
|
||||
*
|
||||
* Unlike every other hook, this one is HOST-initiated for an arbitrary recipient, so
|
||||
* it runs WITHOUT an acting user: `ctx.settings.get()` returns undefined here and trip
|
||||
* reads are refused. The recipient's own `scope:'user'` settings are decrypted by the
|
||||
* host and handed to you as `config` instead — that is the only way to reach them, and
|
||||
* it is why a channel plugin cannot enumerate the recipient's trips.
|
||||
*
|
||||
* Declare the channel in your manifest:
|
||||
* "capabilities": { "notificationChannel": { "title": "Gotify" } }
|
||||
*/
|
||||
export interface NotificationChannel {
|
||||
send(msg: NotificationMessage, config: Record<string, unknown>, ctx: PluginContext): Promise<void>;
|
||||
/** Backs the "Send test" button in the user's notification settings. */
|
||||
test?(config: Record<string, unknown>, ctx: PluginContext): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Result of a settings-page action. `message` is shown to the user beside the button
|
||||
* (bounded + emoji-stripped host-side); throwing is equivalent to `{ ok: false }` with
|
||||
* the error message.
|
||||
*/
|
||||
export interface PluginActionResult {
|
||||
ok?: boolean;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
export interface CalendarEvent {
|
||||
id: string;
|
||||
title: string;
|
||||
@@ -152,10 +409,12 @@ export interface CalendarEvent {
|
||||
allDay: boolean;
|
||||
}
|
||||
export interface CalendarSource {
|
||||
getName(): string;
|
||||
/** A short label for this source (shown in the calendar UI). Needs `hook:calendar-source`. */
|
||||
getName(ctx: PluginContext): string;
|
||||
// start/end are ISO strings — the host->plugin boundary is JSON, so a Date would
|
||||
// arrive as a string anyway (kept in lockstep with the runtime SDK copy).
|
||||
getEvents(userId: number, start: string, end: string): Promise<CalendarEvent[]>;
|
||||
// arrive as a string anyway (kept in lockstep with the runtime SDK copy). `ctx` is the
|
||||
// last arg. Aggregated for the signed-in user at `GET /api/plugin-calendar`.
|
||||
getEvents(userId: number, start: string, end: string, ctx: PluginContext): Promise<CalendarEvent[]>;
|
||||
}
|
||||
/** One row of extra place info TREK renders natively (reviews/ratings/links/…). */
|
||||
export interface PlaceDetailItem { label: string; value?: string; url?: string; }
|
||||
@@ -170,12 +429,128 @@ export interface WarningProvider {
|
||||
getWarnings(tripId: number, ctx: PluginContext): Promise<TripWarning[]>;
|
||||
}
|
||||
|
||||
/** A core-event subscription (#1429 eco). Handlers run with NO user (like a job)
|
||||
* and receive only the event name + tripId — never the payload. Needs `events:subscribe`. */
|
||||
/** Host-rendered contributions into a native trip-planner view (reservations/places/day),
|
||||
* keyed to an entity by id. DECLARATIVE ONLY — a column is text/badge/link, an action is
|
||||
* a labelled button whose target opens your sandboxed frame or calls a route. Never raw
|
||||
* HTML/markup; the host renders + sanitizes everything. */
|
||||
export type ContributionTone = 'default' | 'success' | 'warn' | 'danger';
|
||||
/** An extra read-only cell/badge on an entity's row/card. */
|
||||
export interface TableColumnContribution {
|
||||
kind: 'column';
|
||||
entityId: number; // the reservation/place/day id this attaches to
|
||||
id: string; // stable per-contribution id (for React keys / dedupe)
|
||||
label: string;
|
||||
value?: string;
|
||||
url?: string; // http/https/mailto only — the host rejects any other scheme
|
||||
icon?: string; // a lucide icon name, resolved by the host
|
||||
tone?: ContributionTone;
|
||||
}
|
||||
/** A labelled button on an entity's row/card; its target opens your sandboxed frame
|
||||
* (`{kind:'frame', sub}`) or invokes one of your routes (`{kind:'route', method, sub}`). */
|
||||
export interface TableActionContribution {
|
||||
kind: 'action';
|
||||
entityId: number;
|
||||
id: string;
|
||||
label: string;
|
||||
icon?: string;
|
||||
target: { kind: 'frame'; sub: string } | { kind: 'route'; method: 'GET' | 'POST'; sub: string };
|
||||
}
|
||||
export type TableContribution = TableColumnContribution | TableActionContribution;
|
||||
export interface TableContributor {
|
||||
/** `view` is one of 'reservations' | 'places' | 'day' | 'costs' | 'packing' | 'files'.
|
||||
* Runs with the current user bound, on a short timeout; a slow/failing call is
|
||||
* skipped, never fatal. Needs `hook:table-contributor`. */
|
||||
getContributions(view: string, tripId: number, ctx: PluginContext): Promise<TableContribution[]>;
|
||||
}
|
||||
|
||||
/** A bounded marker the host renders onto the trip map (#587). Declarative only —
|
||||
* the host draws a Leaflet marker + popup; plugin JS never runs on the map canvas. */
|
||||
export interface MapMarkerContribution {
|
||||
id: string; // stable per-marker id (React key / dedupe)
|
||||
lat: number; // -90..90
|
||||
lng: number; // -180..180
|
||||
label?: string; // short label shown in the popup title
|
||||
popupText?: string; // one line of body text (host-sanitized, plain text)
|
||||
url?: string; // http/https/mailto only — the host rejects any other scheme
|
||||
icon?: string; // a lucide icon name, resolved by the host
|
||||
tone?: ContributionTone;
|
||||
}
|
||||
export interface MapMarkerProvider {
|
||||
/** Return markers to overlay on a trip's map. Runs with the current user bound,
|
||||
* on a short timeout; the host caps the marker count and skips a failing call.
|
||||
* Needs `hook:map-marker-provider`. */
|
||||
getMarkers(tripId: number, ctx: PluginContext): Promise<MapMarkerContribution[]>;
|
||||
}
|
||||
|
||||
/** A text-only section the host appends to a trip's PDF export. Declarative only —
|
||||
* plain strings the host lays out and escapes; no markup ever reaches the document. */
|
||||
export interface PdfSection {
|
||||
title: string; // section heading (capped at 120 chars)
|
||||
paragraphs?: string[]; // body text — ≤20 paragraphs of ≤2000 chars each
|
||||
table?: { headers: string[]; rows: string[][] }; // simple table — ≤8 headers, ≤50 rows
|
||||
}
|
||||
export interface PdfSectionProvider {
|
||||
/** Return sections to append to a trip's PDF export. Runs with the current user
|
||||
* bound, on a short timeout; the host caps counts/lengths and skips a failing
|
||||
* call. Needs `hook:pdf-section-provider`. */
|
||||
getSections(tripId: number, ctx: PluginContext): Promise<PdfSection[]>;
|
||||
}
|
||||
|
||||
/** One country in an Atlas tint layer. `code` is ISO-3166 alpha-2 (uppercased by the host). */
|
||||
export interface AtlasLayerCountry { code: string; tone?: ContributionTone; label?: string; }
|
||||
/** A country tint layer the host draws over the Atlas world map (wishlists, advisories, …). */
|
||||
export interface AtlasLayer {
|
||||
id: string; // stable per-layer id (React key / dedupe)
|
||||
name?: string; // short layer name
|
||||
countries: AtlasLayerCountry[]; // ≤300 countries per layer
|
||||
}
|
||||
export interface AtlasLayerProvider {
|
||||
/** Return tint layers for the ACTING USER's Atlas map. User-scoped — the host binds
|
||||
* the current user; the hook takes no target parameter. Runs on a short timeout;
|
||||
* the host caps the layer/country counts and skips a failing call.
|
||||
* Needs `hook:atlas-layer-provider`. */
|
||||
getLayers(ctx: PluginContext): Promise<AtlasLayer[]>;
|
||||
}
|
||||
|
||||
/** One badge the host renders on a dashboard trip card. Declarative primitives only —
|
||||
* the host draws the badge; plugin JS never runs on the dashboard. */
|
||||
export interface TripCardContribution {
|
||||
tripId: number; // which of the passed-in trips this badge belongs to
|
||||
id: string; // stable per-badge id (React key / dedupe)
|
||||
label: string; // short label (e.g. "Visa ✓", "3 tasks")
|
||||
value?: string; // optional secondary text
|
||||
icon?: string; // a lucide icon name, resolved by the host
|
||||
tone?: ContributionTone;
|
||||
url?: string; // http/https/mailto only — the host rejects any other scheme
|
||||
}
|
||||
export interface TripCardProvider {
|
||||
/** Return badges for the dashboard trip cards currently on screen. `tripIds` are
|
||||
* exactly those cards (each already access-checked for the acting user). Runs with
|
||||
* the current user bound, on a short timeout; the host caps the badge count and
|
||||
* skips a failing call. Needs `hook:trip-card-provider`. */
|
||||
getCards(tripIds: number[], ctx: PluginContext): Promise<TripCardContribution[]>;
|
||||
}
|
||||
|
||||
/** One row of extra info TREK renders under a journal entry (same shape as PlaceDetailItem). */
|
||||
export interface JournalEntryRow { label: string; value?: string; url?: string; }
|
||||
export interface JournalEntryProvider {
|
||||
/** Return rows for a journal entry. Runs with the current user bound, on a short
|
||||
* timeout; the host caps the row count and skips a failing call.
|
||||
* Needs `hook:journal-entry-provider`. */
|
||||
getRows(entryId: number, ctx: PluginContext): Promise<JournalEntryRow[]>;
|
||||
}
|
||||
|
||||
/** A core-event subscription (#1429 eco). Handlers run with NO user (like a job).
|
||||
* Needs `events:subscribe`. */
|
||||
export interface PluginEventSubscription {
|
||||
/** A core event name (e.g. `place:created`, `day:updated`, `file:created`) or `*` for all. */
|
||||
on: string;
|
||||
handler(payload: { event: string; tripId: number }, ctx: PluginContext): Promise<void> | void;
|
||||
// `entity` = the event family (e.g. 'reservation'); `entityId` = WHICH entity changed,
|
||||
// when known. `snapshot` = a whitelisted field view of the changed entity, delivered
|
||||
// only when the plugin also holds the family's db:read:* grant — never user ids,
|
||||
// private packing items or secrets; delete/reorder/bulk events carry none. Still no
|
||||
// acting user: a trip read from the handler is refused.
|
||||
handler(payload: { event: string; tripId: number; entity?: string; entityId?: number; snapshot?: Record<string, unknown> }, ctx: PluginContext): Promise<void> | void;
|
||||
}
|
||||
|
||||
/** A function this plugin exposes to its dependents (declared in `capabilities.provides`). */
|
||||
@@ -194,12 +569,39 @@ export interface PluginDefinition {
|
||||
onUnload?(ctx: PluginContext): Promise<void> | void;
|
||||
routes?: PluginRoute[];
|
||||
jobs?: PluginJob[];
|
||||
/** Handles a callback registered via ctx.scheduler (userless, like a job). The
|
||||
* `name` identifies which scheduled task fired; `payload` is what you passed. */
|
||||
scheduled?(input: { name: string; payload: unknown }, ctx: PluginContext): Promise<void> | void;
|
||||
/** GDPR erasure: a TREK account was deleted — remove everything you hold about it
|
||||
* from your OWN db. Userless (no acting user). Needs `hook:user-data`. The host
|
||||
* calls this durably (queued, retried until it succeeds), so make it idempotent. */
|
||||
deleteUserData?(input: { userId: number }, ctx: PluginContext): Promise<void> | void;
|
||||
/** GDPR portability: return the data you hold about a user (own db only), as a
|
||||
* JSON-serialisable value the host aggregates. Userless. Needs `hook:user-data`. */
|
||||
exportUserData?(input: { userId: number }, ctx: PluginContext): Promise<unknown> | unknown;
|
||||
events?: PluginEventSubscription[];
|
||||
/**
|
||||
* Buttons on the plugin's own settings page ("Test connection", "Sync now"). The key
|
||||
* must match an entry in the manifest's `actions`.
|
||||
*
|
||||
* USER-INITIATED, so unlike the notificationChannel hook there IS an acting user — the
|
||||
* person who clicked. `ctx.settings.get()` returns THEIR value and trip reads are
|
||||
* membership-checked against them, which is what makes a "test my credentials" button
|
||||
* possible at all.
|
||||
*/
|
||||
actions?: Record<string, (ctx: PluginContext) => Promise<PluginActionResult | void> | PluginActionResult | void>;
|
||||
hooks?: {
|
||||
photoProvider?: PhotoProvider;
|
||||
calendarSource?: CalendarSource;
|
||||
placeDetailProvider?: PlaceDetailProvider;
|
||||
warningProvider?: WarningProvider;
|
||||
tableContributor?: TableContributor;
|
||||
mapMarkerProvider?: MapMarkerProvider;
|
||||
pdfSectionProvider?: PdfSectionProvider;
|
||||
atlasLayerProvider?: AtlasLayerProvider;
|
||||
journalEntryProvider?: JournalEntryProvider;
|
||||
tripCardProvider?: TripCardProvider;
|
||||
notificationChannel?: NotificationChannel;
|
||||
};
|
||||
/** Functions exposed to dependents (names must match manifest `capabilities.provides`). */
|
||||
exports?: Record<string, PluginExport>;
|
||||
@@ -212,7 +614,7 @@ export function definePlugin(def: PluginDefinition): PluginDefinition {
|
||||
return def;
|
||||
}
|
||||
|
||||
export { validateManifest, type PluginManifest, type ValidationResult } from './manifest.js';
|
||||
export { validateManifest, CHANNEL_EVENTS, type PluginManifest, type ValidationResult } from './manifest.js';
|
||||
export { createMockHost, type MockHostOptions } from './mock-host.js';
|
||||
// The design kit for page/widget UIs: inline these into your client/index.html
|
||||
// (or drop a `<!-- trek:ui -->` marker and let `dev`/`pack` expand it) to get the
|
||||
|
||||
+128
-7
@@ -46,12 +46,47 @@ export const KNOWN_ADDONS = [
|
||||
// no spaces (mirrors the server manifest validator).
|
||||
const HOST_RE = /^(\*\.[a-z0-9-]+(\.[a-z0-9-]+)+|[a-z0-9-]+(\.[a-z0-9-]+)*)$/i;
|
||||
const TYPES = ['integration', 'page', 'widget', 'trip-page'];
|
||||
|
||||
/** Mirrors the server's settings-key rules (install/manifest.ts). */
|
||||
const SETTING_KEY_RE = /^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/;
|
||||
const RESERVED_SETTING_KEYS = new Set(['constructor', 'prototype', '__proto__']);
|
||||
|
||||
/**
|
||||
* Events a plugin notification channel may carry (mirrors the server's
|
||||
* PLUGIN_CHANNEL_EVENTS). Admin-scoped and in-app-only events are excluded.
|
||||
*/
|
||||
export const CHANNEL_EVENTS = [
|
||||
'trip_invite',
|
||||
'booking_change',
|
||||
'trip_reminder',
|
||||
'todo_due',
|
||||
'vacay_invite',
|
||||
'collection_invite',
|
||||
'photos_shared',
|
||||
'collab_message',
|
||||
'packing_tagged',
|
||||
'plugin_notification',
|
||||
];
|
||||
// Mirror of the server's KNOWN_PERMISSIONS (server envelope.ts) — the host hard-rejects
|
||||
// anything not in this list at activation, so validate must know the full set.
|
||||
const KNOWN_PERMISSIONS = [
|
||||
'db:own', 'db:read:trips', 'db:read:users', 'db:read:costs', 'db:read:packing', 'db:read:files', 'db:write:costs',
|
||||
'db:write:places', 'db:write:days', 'db:write:itinerary', 'db:write:trips',
|
||||
'db:own',
|
||||
'db:read:trips', 'db:read:users', 'db:read:costs', 'db:read:packing', 'db:read:files',
|
||||
'db:read:files:content', 'db:read:collab',
|
||||
'db:read:journal', 'db:read:atlas', 'db:read:vacay', 'db:read:daynotes', 'db:read:collections',
|
||||
'db:read:categories', 'db:read:tags', 'db:read:todos',
|
||||
'db:write:costs', 'db:write:places', 'db:write:days', 'db:write:itinerary', 'db:write:trips',
|
||||
'db:write:reservations', 'db:write:accommodations', 'db:write:packing', 'db:write:files',
|
||||
'db:write:collab', 'db:write:members', 'db:write:collections', 'db:write:atlas', 'db:write:vacay',
|
||||
'db:write:journal', 'db:write:tags', 'db:write:todos', 'db:write:daynotes',
|
||||
'db:create:trips',
|
||||
'db:meta',
|
||||
'ws:broadcast:trip', 'ws:broadcast:user',
|
||||
'hook:photo-provider', 'hook:calendar-source', 'hook:place-detail-provider', 'hook:trip-warning-provider', 'events:subscribe', 'http:outbound',
|
||||
'hook:photo-provider', 'hook:calendar-source', 'hook:place-detail-provider', 'hook:trip-warning-provider',
|
||||
'hook:table-contributor', 'hook:map-marker-provider', 'hook:pdf-section-provider', 'hook:atlas-layer-provider',
|
||||
'hook:journal-entry-provider', 'hook:trip-card-provider', 'hook:notification-channel', 'hook:user-data',
|
||||
'events:subscribe', 'jobs:run', 'http:outbound',
|
||||
'weather:read', 'rates:read', 'notify:send', 'ai:invoke', 'oauth:client',
|
||||
];
|
||||
|
||||
function isKnownPermission(p: string): boolean {
|
||||
@@ -85,14 +120,100 @@ export function validateManifest(raw: unknown): ValidationResult {
|
||||
|
||||
const egress = Array.isArray(m.egress) ? m.egress.map(String) : [];
|
||||
const wantsOutbound = permissions.some((p) => p === 'http:outbound' || p.startsWith('http:outbound:'));
|
||||
if (wantsOutbound && egress.length === 0) errors.push('http:outbound declared but egress[] is empty');
|
||||
// Empty egress[] is legal only with operatorEgress: the hosts are admin-supplied
|
||||
// post-install. Until an admin adds one the child blocks ALL outbound — not allow-all.
|
||||
if (wantsOutbound && egress.length === 0 && m.operatorEgress !== true) {
|
||||
errors.push('http:outbound declared but egress[] is empty (set operatorEgress: true if the hosts are admin-supplied)');
|
||||
}
|
||||
if (egress.includes('*')) errors.push('egress[] must not contain a bare "*"');
|
||||
for (const h of egress) if (!HOST_RE.test(h)) errors.push(`invalid egress host "${h}"`);
|
||||
|
||||
const capabilities = (m.capabilities ?? undefined) as { widget?: { slot?: unknown }; provides?: unknown; emits?: unknown } | undefined;
|
||||
// A plugin whose target host only the OPERATOR knows (a self-hosted Gotify/ntfy).
|
||||
// The admin adds the real hosts post-install; see Plugin-Development → Egress.
|
||||
if (m.operatorEgress !== undefined && typeof m.operatorEgress !== 'boolean') {
|
||||
errors.push('operatorEgress must be a boolean');
|
||||
}
|
||||
if (m.operatorEgress === true && !permissions.some((p) => p === 'http:outbound' || p.startsWith('http:outbound:'))) {
|
||||
errors.push('operatorEgress requires an http:outbound permission');
|
||||
}
|
||||
|
||||
const capabilities = (m.capabilities ?? undefined) as {
|
||||
widget?: { slot?: unknown };
|
||||
tripPage?: { replaces?: unknown; position?: unknown };
|
||||
notificationChannel?: { title?: unknown; events?: unknown };
|
||||
provides?: unknown;
|
||||
emits?: unknown;
|
||||
} | undefined;
|
||||
const widget = capabilities?.widget;
|
||||
if (widget?.slot !== undefined && widget.slot !== 'sidebar' && widget.slot !== 'hero' && widget.slot !== 'place-detail') {
|
||||
errors.push(`widget slot must be "sidebar", "hero" or "place-detail", got "${String(widget.slot)}"`);
|
||||
if (widget?.slot !== undefined && widget.slot !== 'sidebar' && widget.slot !== 'hero' && widget.slot !== 'place-detail' && widget.slot !== 'day-detail' && widget.slot !== 'reservation-detail') {
|
||||
errors.push(`widget slot must be "sidebar", "hero", "place-detail", "day-detail" or "reservation-detail", got "${String(widget.slot)}"`);
|
||||
}
|
||||
// Mirrors the server's REPLACEABLE_TABS — 'plan' is never replaceable.
|
||||
const tripPage = capabilities?.tripPage;
|
||||
if (tripPage !== undefined) {
|
||||
const REPLACEABLE = ['transports', 'buchungen', 'listen', 'finanzplan', 'dateien', 'collab'];
|
||||
if (tripPage.replaces !== undefined) {
|
||||
if (!Array.isArray(tripPage.replaces)) errors.push('capabilities.tripPage.replaces must be an array');
|
||||
else for (const t of tripPage.replaces) {
|
||||
if (typeof t !== 'string' || !REPLACEABLE.includes(t)) errors.push(`capabilities.tripPage.replaces: "${String(t)}" is not a replaceable tab (${REPLACEABLE.join(', ')})`);
|
||||
}
|
||||
}
|
||||
if (tripPage.position !== undefined && (typeof tripPage.position !== 'number' || !Number.isInteger(tripPage.position) || tripPage.position < 0 || tripPage.position > 50)) {
|
||||
errors.push('capabilities.tripPage.position must be an integer between 0 and 50');
|
||||
}
|
||||
}
|
||||
// Mirrors the server's PLUGIN_CHANNEL_EVENTS. Admin-scoped events (version_available)
|
||||
// and inapp-only ones are absent by design: a plugin channel never carries them.
|
||||
const notificationChannel = capabilities?.notificationChannel;
|
||||
if (notificationChannel !== undefined) {
|
||||
if (!permissions.includes('hook:notification-channel')) {
|
||||
errors.push('capabilities.notificationChannel requires the "hook:notification-channel" permission');
|
||||
}
|
||||
if (notificationChannel.title !== undefined && typeof notificationChannel.title !== 'string') {
|
||||
errors.push('capabilities.notificationChannel.title must be a string');
|
||||
}
|
||||
if (notificationChannel.events !== undefined) {
|
||||
if (!Array.isArray(notificationChannel.events)) errors.push('capabilities.notificationChannel.events must be an array');
|
||||
else for (const e of notificationChannel.events) {
|
||||
if (typeof e !== 'string' || !CHANNEL_EVENTS.includes(e)) {
|
||||
errors.push(`capabilities.notificationChannel.events: "${String(e)}" is not a plugin-deliverable event (${CHANNEL_EVENTS.join(', ')})`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Settings keys become JSON object keys in the plugin's stored config, so they are
|
||||
// constrained (mirrors the server's SETTING_KEY_RE). `__proto__`/`constructor` would
|
||||
// resolve off Object.prototype on read and make a required field look configured for
|
||||
// a user who configured nothing.
|
||||
if (Array.isArray(m.settings)) {
|
||||
for (const s of m.settings as Array<Record<string, unknown>>) {
|
||||
if (!s || typeof s !== 'object' || s.key === undefined) continue;
|
||||
const key = String(s.key);
|
||||
if (!key) continue;
|
||||
if (!SETTING_KEY_RE.test(key) || RESERVED_SETTING_KEYS.has(key)) {
|
||||
errors.push(`invalid settings key "${key}" (letters, digits, . _ - ; must start with a letter; 1–64 chars)`);
|
||||
}
|
||||
if (s.scope !== undefined && s.scope !== 'user' && s.scope !== 'instance') {
|
||||
errors.push(`settings["${key}"].scope must be "user" or "instance"`);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Settings-page action buttons ("Test connection"). Keys share the settings-key rules.
|
||||
if (m.actions !== undefined) {
|
||||
if (!Array.isArray(m.actions)) errors.push('actions must be an array');
|
||||
else {
|
||||
if (m.actions.length > 8) errors.push('at most 8 actions');
|
||||
const seen = new Set<string>();
|
||||
for (const a of m.actions as Array<Record<string, unknown>>) {
|
||||
if (!a || typeof a !== 'object') { errors.push('each action must be an object'); continue; }
|
||||
const key = String(a.key ?? '');
|
||||
if (!key) { errors.push('action must have a "key"'); continue; }
|
||||
if (!SETTING_KEY_RE.test(key) || RESERVED_SETTING_KEYS.has(key)) errors.push(`invalid action key "${key}"`);
|
||||
if (seen.has(key)) errors.push(`duplicate action "${key}"`);
|
||||
seen.add(key);
|
||||
if (a.label !== undefined && typeof a.label !== 'string') errors.push(`action "${key}" label must be a string`);
|
||||
}
|
||||
}
|
||||
}
|
||||
validateCapabilityNames(capabilities?.provides, 'provides', errors);
|
||||
validateCapabilityNames(capabilities?.emits, 'emits', errors);
|
||||
|
||||
+1374
-258
File diff suppressed because it is too large
Load Diff
+342
-2
@@ -150,6 +150,44 @@ body.trek-ui {
|
||||
}
|
||||
.trek-label { display: block; font-size: 12px; font-weight: 600; color: var(--text-secondary); margin-bottom: 6px; }
|
||||
|
||||
/* Enhanced select — the kit upgrades a native <select> into this listbox so the
|
||||
dropdown matches the host (a native popup is drawn by the OS and can't be
|
||||
themed). The real <select> stays in the DOM as the value source. */
|
||||
.trek-select-wrap { position: relative; }
|
||||
.trek-select-native-hidden {
|
||||
position: absolute !important; width: 1px; height: 1px;
|
||||
padding: 0; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); border: 0;
|
||||
}
|
||||
.trek-select-trigger {
|
||||
display: flex; align-items: center; justify-content: space-between; gap: 8px;
|
||||
text-align: start; cursor: pointer;
|
||||
}
|
||||
.trek-select-trigger:disabled { opacity: .5; cursor: not-allowed; }
|
||||
.trek-select-trigger[aria-expanded="true"] {
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 0 0 3px color-mix(in oklch, var(--accent) 22%, transparent);
|
||||
}
|
||||
.trek-select-value { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.trek-select-caret { flex: none; display: inline-flex; color: var(--text-faint); transition: transform .15s; }
|
||||
.trek-select-trigger[aria-expanded="true"] .trek-select-caret { transform: rotate(180deg); }
|
||||
.trek-select-menu {
|
||||
position: absolute; left: 0; right: 0; top: 100%; z-index: 50;
|
||||
margin-top: 6px; padding: 4px;
|
||||
max-height: 260px; overflow-y: auto;
|
||||
background: var(--bg-card); color: var(--text-primary);
|
||||
border: 1px solid var(--border-primary); border-radius: 10px;
|
||||
box-shadow: var(--shadow-md);
|
||||
}
|
||||
.trek-select-menu[data-placement="top"] { top: auto; bottom: 100%; margin-top: 0; margin-bottom: 6px; }
|
||||
.trek-select-option {
|
||||
display: flex; align-items: center; gap: 8px;
|
||||
padding: 8px 10px; border-radius: 7px; cursor: pointer;
|
||||
font-size: 13px; white-space: nowrap;
|
||||
}
|
||||
.trek-select-option.trek-active { background: var(--bg-hover); }
|
||||
.trek-select-option[aria-selected="true"] { color: var(--accent); font-weight: 600; }
|
||||
.trek-select-option[aria-disabled="true"] { opacity: .45; cursor: not-allowed; }
|
||||
|
||||
/* Chips + badges ----------------------------------------------------------- */
|
||||
.trek-chip {
|
||||
display: inline-flex; align-items: center; gap: 6px;
|
||||
@@ -178,6 +216,101 @@ body.trek-ui {
|
||||
.trek-stack { display: flex; flex-direction: column; gap: 12px; }
|
||||
.trek-cluster { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; }
|
||||
|
||||
/* Motion library — the host's animation vocabulary, mirrored 1:1 from
|
||||
index.css so plugin UI moves exactly like TREK does. ---------------------- */
|
||||
@keyframes trek-menu-enter {
|
||||
from { opacity: 0; transform: scale(0.95) translateY(-4px); }
|
||||
to { opacity: 1; transform: scale(1) translateY(0); }
|
||||
}
|
||||
@keyframes trek-popover-enter {
|
||||
from { opacity: 0; transform: scale(0.96); }
|
||||
to { opacity: 1; transform: scale(1); }
|
||||
}
|
||||
@keyframes trek-modal-enter {
|
||||
from { opacity: 0; transform: scale(0.97); }
|
||||
to { opacity: 1; transform: scale(1); }
|
||||
}
|
||||
@keyframes trek-backdrop-enter {
|
||||
from { opacity: 0; }
|
||||
to { opacity: 1; }
|
||||
}
|
||||
@keyframes trek-toast-enter {
|
||||
from { opacity: 0; transform: translateY(8px) scale(0.96); }
|
||||
to { opacity: 1; transform: translateY(0) scale(1); }
|
||||
}
|
||||
@keyframes trek-progress-fill {
|
||||
from { width: 0%; }
|
||||
to { width: var(--trek-progress-to, 0%); }
|
||||
}
|
||||
@keyframes trek-pie-reveal {
|
||||
from { opacity: 0; transform: rotate(-90deg) scale(0.85); }
|
||||
to { opacity: 1; transform: rotate(0deg) scale(1); }
|
||||
}
|
||||
@keyframes trek-bar-fill {
|
||||
from { transform: scaleX(0); }
|
||||
to { transform: scaleX(1); }
|
||||
}
|
||||
@keyframes trek-page-enter {
|
||||
from { opacity: 0; transform: translateY(6px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
@keyframes trek-shimmer {
|
||||
from { background-position: -200% 0; }
|
||||
to { background-position: 200% 0; }
|
||||
}
|
||||
@keyframes trek-drawer-enter {
|
||||
from { opacity: 0; transform: translateY(100%); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
@keyframes trek-fade-up {
|
||||
from { opacity: 0; transform: translateY(6px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
.trek-menu-enter {
|
||||
animation: trek-menu-enter 200ms var(--trek-ease-quint);
|
||||
transform-origin: top right; will-change: transform, opacity;
|
||||
}
|
||||
.trek-menu-enter-left {
|
||||
animation: trek-menu-enter 200ms var(--trek-ease-quint);
|
||||
transform-origin: top left; will-change: transform, opacity;
|
||||
}
|
||||
.trek-popover-enter { animation: trek-popover-enter 180ms var(--trek-ease-quint); will-change: transform, opacity; }
|
||||
.trek-modal-enter { animation: trek-modal-enter 220ms var(--trek-ease-quint); will-change: transform, opacity; }
|
||||
@media (max-width: 639px) {
|
||||
.trek-modal-enter { animation: trek-drawer-enter 320ms cubic-bezier(0.32, 0.72, 0, 1); }
|
||||
}
|
||||
.trek-backdrop-enter { animation: trek-backdrop-enter 180ms var(--trek-ease-quint); }
|
||||
.trek-toast-enter { animation: trek-toast-enter 260ms var(--trek-ease-quint); will-change: transform, opacity; }
|
||||
.trek-pie-reveal {
|
||||
animation: trek-pie-reveal 900ms var(--trek-ease-quint) both;
|
||||
transform-origin: center; will-change: transform, opacity;
|
||||
}
|
||||
.trek-bar-fill {
|
||||
animation: trek-bar-fill 700ms var(--trek-ease-quint) both;
|
||||
transform-origin: left center; will-change: transform;
|
||||
}
|
||||
.trek-page-enter { animation: trek-page-enter 220ms var(--trek-ease-quint) both; }
|
||||
.trek-skeleton {
|
||||
background: linear-gradient(90deg, var(--bg-tertiary) 0%, var(--bg-hover) 50%, var(--bg-tertiary) 100%);
|
||||
background-size: 200% 100%;
|
||||
animation: trek-shimmer 1.6s linear infinite;
|
||||
border-radius: 8px; color: transparent; user-select: none;
|
||||
}
|
||||
[data-theme="dark"] .trek-skeleton {
|
||||
background: linear-gradient(90deg, rgba(255,255,255,0.04) 0%, rgba(255,255,255,0.08) 50%, rgba(255,255,255,0.04) 100%);
|
||||
background-size: 200% 100%;
|
||||
}
|
||||
.trek-stagger > * { animation: trek-fade-up 280ms var(--trek-ease-quint) both; }
|
||||
.trek-stagger > *:nth-child(1) { animation-delay: 0ms; }
|
||||
.trek-stagger > *:nth-child(2) { animation-delay: 40ms; }
|
||||
.trek-stagger > *:nth-child(3) { animation-delay: 80ms; }
|
||||
.trek-stagger > *:nth-child(4) { animation-delay: 120ms; }
|
||||
.trek-stagger > *:nth-child(5) { animation-delay: 160ms; }
|
||||
.trek-stagger > *:nth-child(6) { animation-delay: 200ms; }
|
||||
.trek-stagger > *:nth-child(7) { animation-delay: 240ms; }
|
||||
.trek-stagger > *:nth-child(8) { animation-delay: 280ms; }
|
||||
.trek-stagger > *:nth-child(n+9) { animation-delay: 320ms; }
|
||||
|
||||
/* Accessibility: mirror the host's own graceful-degrade rules. -------------- */
|
||||
[data-no-transparency] .trek-glass {
|
||||
background: var(--bg-card); border-color: var(--border-primary);
|
||||
@@ -189,9 +322,26 @@ body.trek-ui {
|
||||
[data-reduce-motion] .trek-row { transition: none; }
|
||||
[data-reduce-motion] .trek-interactive:hover,
|
||||
[data-reduce-motion] .trek-btn:active { transform: none; }
|
||||
[data-reduce-motion] .trek-menu-enter, [data-reduce-motion] .trek-menu-enter-left,
|
||||
[data-reduce-motion] .trek-popover-enter, [data-reduce-motion] .trek-modal-enter,
|
||||
[data-reduce-motion] .trek-toast-enter, [data-reduce-motion] .trek-stagger > *,
|
||||
[data-reduce-motion] .trek-page-enter {
|
||||
animation: trek-backdrop-enter 120ms ease-out;
|
||||
}
|
||||
[data-reduce-motion] .trek-pie-reveal, [data-reduce-motion] .trek-bar-fill {
|
||||
animation: trek-backdrop-enter 120ms ease-out both;
|
||||
}
|
||||
[data-reduce-motion] .trek-skeleton { animation: none; background: var(--bg-tertiary); }
|
||||
[data-reduce-motion] .trek-select-caret { transition: none; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.trek-interactive, .trek-btn, .trek-row, .trek-input, .trek-textarea, .trek-select { transition: none; }
|
||||
.trek-interactive, .trek-btn, .trek-row, .trek-input, .trek-textarea, .trek-select, .trek-select-caret { transition: none; }
|
||||
.trek-interactive:hover, .trek-btn:active { transform: none; }
|
||||
.trek-menu-enter, .trek-menu-enter-left, .trek-popover-enter,
|
||||
.trek-modal-enter, .trek-toast-enter, .trek-stagger > *, .trek-page-enter {
|
||||
animation: trek-backdrop-enter 120ms ease-out;
|
||||
}
|
||||
.trek-pie-reveal, .trek-bar-fill { animation: trek-backdrop-enter 120ms ease-out both; }
|
||||
.trek-skeleton { animation: none; background: var(--bg-tertiary); }
|
||||
}`;
|
||||
|
||||
/**
|
||||
@@ -205,8 +355,10 @@ export const TREK_THEME_JS = `(function () {
|
||||
'use strict';
|
||||
var docEl = document.documentElement;
|
||||
var ctxHandlers = [];
|
||||
var evtHandlers = [];
|
||||
var lastCtx = null;
|
||||
var pending = {};
|
||||
var pendingConfirms = {};
|
||||
var seq = 0;
|
||||
var lastH = -1;
|
||||
|
||||
@@ -215,6 +367,8 @@ export const TREK_THEME_JS = `(function () {
|
||||
|
||||
function applyContext(m) {
|
||||
if (m.theme) { docEl.setAttribute('data-theme', m.theme); }
|
||||
if (m.locale) { docEl.setAttribute('lang', m.locale); }
|
||||
docEl.setAttribute('dir', m.dir === 'rtl' ? 'rtl' : 'ltr');
|
||||
var t = m.tokens || {};
|
||||
for (var k in t) {
|
||||
if (Object.prototype.hasOwnProperty.call(t, k) && t[k]) { docEl.style.setProperty(k, t[k]); }
|
||||
@@ -249,6 +403,11 @@ export const TREK_THEME_JS = `(function () {
|
||||
} else if (m.type === 'trek:error') {
|
||||
var q = pending[m.requestId];
|
||||
if (q) { delete pending[m.requestId]; var err = new Error(m.message || 'invoke failed'); err.code = m.code; q.reject(err); }
|
||||
} else if (m.type === 'trek:confirm:result') {
|
||||
var c = pendingConfirms[m.requestId];
|
||||
if (c) { delete pendingConfirms[m.requestId]; c(!!m.confirmed); }
|
||||
} else if (m.type === 'trek:event') {
|
||||
for (var j = 0; j < evtHandlers.length; j++) { try { evtHandlers[j](m.event, m.tripId); } catch (e) {} }
|
||||
}
|
||||
});
|
||||
|
||||
@@ -297,9 +456,26 @@ export const TREK_THEME_JS = `(function () {
|
||||
if (lastCtx) { try { cb(lastCtx); } catch (e) {} }
|
||||
return function () { var i = ctxHandlers.indexOf(cb); if (i >= 0) { ctxHandlers.splice(i, 1); } };
|
||||
},
|
||||
notify: function (level, message) { send({ type: 'trek:notify', level: level, message: message }); },
|
||||
notify: function (level, message, duration) { send({ type: 'trek:notify', level: level, message: message, duration: duration }); },
|
||||
navigate: function (to) { send({ type: 'trek:navigate', to: to }); },
|
||||
openExternal: function (url) { send({ type: 'trek:openExternal', url: url }); },
|
||||
resize: function (px) { var h = px | 0; if (h > 0) { lastH = h; send({ type: 'trek:resize', height: h }); } },
|
||||
// Host-rendered native confirm dialog; resolves true/false. The host shows one
|
||||
// at a time — a second concurrent request resolves false immediately.
|
||||
confirm: function (opts) {
|
||||
opts = typeof opts === 'string' ? { message: opts } : (opts || {});
|
||||
var id = 'c' + (++seq);
|
||||
return new Promise(function (resolve) {
|
||||
pendingConfirms[id] = resolve;
|
||||
send({ type: 'trek:confirm', requestId: id, title: opts.title, message: opts.message, confirmLabel: opts.confirmLabel, cancelLabel: opts.cancelLabel, danger: opts.danger });
|
||||
});
|
||||
},
|
||||
// Core-event names for the trip in view ({ event, tripId } only, no payloads) —
|
||||
// refetch via invoke() when something relevant fires instead of polling.
|
||||
onEvent: function (cb) {
|
||||
evtHandlers.push(cb);
|
||||
return function () { var i = evtHandlers.indexOf(cb); if (i >= 0) { evtHandlers.splice(i, 1); } };
|
||||
},
|
||||
invoke: function (sub, opts) {
|
||||
opts = opts || {};
|
||||
var id = 'r' + (++seq);
|
||||
@@ -311,8 +487,172 @@ export const TREK_THEME_JS = `(function () {
|
||||
};
|
||||
window.trek = api;
|
||||
|
||||
// --- Native <select> -> host-styled listbox ---------------------------------
|
||||
// A native select's popup is drawn by the OS and can't match TREK. Upgrade each
|
||||
// one to a keyboard-accessible listbox that uses the kit tokens, while the real
|
||||
// <select> stays in the DOM as the value/form source (kept in sync both ways).
|
||||
// Opt out per field with data-trek-native; multi/size selects are left alone.
|
||||
function dispatch(el, type) {
|
||||
var ev;
|
||||
try { ev = new Event(type, { bubbles: true }); }
|
||||
catch (e) { ev = document.createEvent('Event'); ev.initEvent(type, true, false); }
|
||||
el.dispatchEvent(ev);
|
||||
}
|
||||
function enhanceSelect(sel) {
|
||||
if (!sel || sel.__trekSelect || sel.hasAttribute('data-trek-native')) { return; }
|
||||
if (sel.multiple || sel.size > 1 || !sel.parentNode) { return; }
|
||||
sel.__trekSelect = true;
|
||||
|
||||
var wrap = document.createElement('div');
|
||||
wrap.className = 'trek-select-wrap';
|
||||
sel.parentNode.insertBefore(wrap, sel);
|
||||
wrap.appendChild(sel);
|
||||
sel.classList.add('trek-select-native-hidden');
|
||||
sel.setAttribute('tabindex', '-1');
|
||||
sel.setAttribute('aria-hidden', 'true');
|
||||
|
||||
var trigger = document.createElement('button');
|
||||
trigger.type = 'button';
|
||||
trigger.className = 'trek-select trek-select-trigger';
|
||||
trigger.setAttribute('aria-haspopup', 'listbox');
|
||||
trigger.setAttribute('aria-expanded', 'false');
|
||||
if (sel.disabled) { trigger.disabled = true; }
|
||||
var valueEl = document.createElement('span');
|
||||
valueEl.className = 'trek-select-value';
|
||||
var caret = document.createElement('span');
|
||||
caret.className = 'trek-select-caret';
|
||||
caret.innerHTML = '<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M6 9l6 6 6-6"/></svg>';
|
||||
trigger.appendChild(valueEl);
|
||||
trigger.appendChild(caret);
|
||||
wrap.appendChild(trigger);
|
||||
|
||||
var menu = document.createElement('div');
|
||||
menu.className = 'trek-select-menu';
|
||||
menu.setAttribute('role', 'listbox');
|
||||
menu.hidden = true;
|
||||
wrap.appendChild(menu);
|
||||
|
||||
var activeIdx = -1;
|
||||
|
||||
function syncTrigger() {
|
||||
var o = sel.options[sel.selectedIndex];
|
||||
valueEl.textContent = o ? o.text : '';
|
||||
}
|
||||
function buildMenu() {
|
||||
menu.innerHTML = '';
|
||||
for (var i = 0; i < sel.options.length; i++) {
|
||||
var o = sel.options[i];
|
||||
var item = document.createElement('div');
|
||||
item.className = 'trek-select-option';
|
||||
item.setAttribute('role', 'option');
|
||||
item.setAttribute('data-idx', String(i));
|
||||
item.setAttribute('aria-selected', i === sel.selectedIndex ? 'true' : 'false');
|
||||
if (o.disabled) { item.setAttribute('aria-disabled', 'true'); }
|
||||
item.textContent = o.text;
|
||||
menu.appendChild(item);
|
||||
}
|
||||
}
|
||||
function highlight(idx) {
|
||||
var opts = menu.children;
|
||||
for (var i = 0; i < opts.length; i++) {
|
||||
opts[i].className = i === idx ? 'trek-select-option trek-active' : 'trek-select-option';
|
||||
}
|
||||
if (idx >= 0 && opts[idx] && opts[idx].scrollIntoView) { opts[idx].scrollIntoView({ block: 'nearest' }); }
|
||||
activeIdx = idx;
|
||||
}
|
||||
function onDocDown(e) { if (!wrap.contains(e.target)) { closeMenu(); } }
|
||||
function openMenu() {
|
||||
if (trigger.disabled || !menu.hidden) { return; }
|
||||
buildMenu();
|
||||
menu.hidden = false;
|
||||
trigger.setAttribute('aria-expanded', 'true');
|
||||
// Flip above the trigger when there isn't room below in the frame viewport.
|
||||
var r = trigger.getBoundingClientRect();
|
||||
var below = window.innerHeight - r.bottom;
|
||||
if (below < Math.min(260, menu.scrollHeight + 12) && r.top > below) { menu.setAttribute('data-placement', 'top'); }
|
||||
else { menu.removeAttribute('data-placement'); }
|
||||
highlight(sel.selectedIndex);
|
||||
reportHeight();
|
||||
document.addEventListener('mousedown', onDocDown, true);
|
||||
}
|
||||
function closeMenu() {
|
||||
if (menu.hidden) { return; }
|
||||
menu.hidden = true;
|
||||
trigger.setAttribute('aria-expanded', 'false');
|
||||
document.removeEventListener('mousedown', onDocDown, true);
|
||||
reportHeight();
|
||||
}
|
||||
function nextEnabled(from, dir) {
|
||||
var i = from;
|
||||
for (var n = 0; n < sel.options.length; n++) {
|
||||
i += dir;
|
||||
if (i < 0) { i = sel.options.length - 1; }
|
||||
if (i >= sel.options.length) { i = 0; }
|
||||
if (!sel.options[i].disabled) { return i; }
|
||||
}
|
||||
return from;
|
||||
}
|
||||
function commit(idx) {
|
||||
if (idx < 0 || idx >= sel.options.length || sel.options[idx].disabled) { return; }
|
||||
if (sel.selectedIndex !== idx) { sel.selectedIndex = idx; dispatch(sel, 'input'); dispatch(sel, 'change'); }
|
||||
syncTrigger();
|
||||
closeMenu();
|
||||
trigger.focus();
|
||||
}
|
||||
|
||||
trigger.addEventListener('click', function () { if (menu.hidden) { openMenu(); } else { closeMenu(); } });
|
||||
trigger.addEventListener('keydown', function (e) {
|
||||
var k = e.key;
|
||||
if (menu.hidden) {
|
||||
if (k === 'ArrowDown' || k === 'ArrowUp' || k === 'Enter' || k === ' ' || k === 'Spacebar') { e.preventDefault(); openMenu(); }
|
||||
return;
|
||||
}
|
||||
if (k === 'Escape') { e.preventDefault(); closeMenu(); trigger.focus(); }
|
||||
else if (k === 'ArrowDown') { e.preventDefault(); highlight(nextEnabled(activeIdx, 1)); }
|
||||
else if (k === 'ArrowUp') { e.preventDefault(); highlight(nextEnabled(activeIdx, -1)); }
|
||||
else if (k === 'Home') { e.preventDefault(); highlight(nextEnabled(-1, 1)); }
|
||||
else if (k === 'End') { e.preventDefault(); highlight(nextEnabled(0, -1)); }
|
||||
else if (k === 'Enter' || k === ' ' || k === 'Spacebar') { e.preventDefault(); commit(activeIdx); }
|
||||
else if (k === 'Tab') { closeMenu(); }
|
||||
});
|
||||
menu.addEventListener('mousedown', function (e) { e.preventDefault(); }); // keep focus on the trigger
|
||||
menu.addEventListener('click', function (e) {
|
||||
var t = e.target;
|
||||
while (t && t !== menu && !(t.getAttribute && t.hasAttribute('data-idx'))) { t = t.parentNode; }
|
||||
if (t && t.getAttribute && t.hasAttribute('data-idx')) { commit(parseInt(t.getAttribute('data-idx'), 10)); }
|
||||
});
|
||||
menu.addEventListener('mousemove', function (e) {
|
||||
var t = e.target;
|
||||
while (t && t !== menu && !(t.getAttribute && t.hasAttribute('data-idx'))) { t = t.parentNode; }
|
||||
if (t && t.getAttribute && t.hasAttribute('data-idx')) { highlight(parseInt(t.getAttribute('data-idx'), 10)); }
|
||||
});
|
||||
// The plugin may set select.value itself — mirror it back to the trigger.
|
||||
sel.addEventListener('change', syncTrigger);
|
||||
syncTrigger();
|
||||
}
|
||||
function enhanceAllSelects(root) {
|
||||
var live = (root || document).getElementsByTagName('select');
|
||||
var arr = [];
|
||||
for (var i = 0; i < live.length; i++) { arr.push(live[i]); }
|
||||
for (var j = 0; j < arr.length; j++) { enhanceSelect(arr[j]); }
|
||||
}
|
||||
|
||||
function boot() {
|
||||
if (document.body) { document.body.classList.add('trek-ui'); }
|
||||
enhanceAllSelects(document);
|
||||
if (typeof MutationObserver !== 'undefined' && document.body) {
|
||||
new MutationObserver(function (muts) {
|
||||
for (var i = 0; i < muts.length; i++) {
|
||||
var added = muts[i].addedNodes;
|
||||
for (var j = 0; j < added.length; j++) {
|
||||
var n = added[j];
|
||||
if (!n || n.nodeType !== 1) { continue; }
|
||||
if (n.tagName === 'SELECT') { enhanceSelect(n); }
|
||||
else if (n.getElementsByTagName) { enhanceAllSelects(n); }
|
||||
}
|
||||
}
|
||||
}).observe(document.body, { childList: true, subtree: true });
|
||||
}
|
||||
api.ready();
|
||||
reportHeight();
|
||||
if (typeof ResizeObserver !== 'undefined' && document.body) {
|
||||
|
||||
+109
-3
@@ -19,11 +19,15 @@ describe('scaffold egress (http:outbound)', () => {
|
||||
expect(validateManifest(m).ok).toBe(true);
|
||||
});
|
||||
|
||||
it('without egress the same manifest is invalid — which the wizard now prevents', () => {
|
||||
it('without egress it scaffolds an operatorEgress plugin (the admin names the hosts)', () => {
|
||||
// The author of a plugin for an always-self-hosted service has no host to write down.
|
||||
// The scaffold must NOT invent a placeholder — it declares operatorEgress instead, which
|
||||
// is the one way an empty egress[] is a valid manifest.
|
||||
scaffold('net-plug', 'integration', tmp, { permissions: ['http:outbound'] });
|
||||
const m = JSON.parse(fs.readFileSync(path.join(tmp, 'net-plug', 'trek-plugin.json'), 'utf8'));
|
||||
expect(m.egress).toBeUndefined();
|
||||
expect(validateManifest(m).ok).toBe(false); // http:outbound requires an egress allow-list
|
||||
expect(m.operatorEgress).toBe(true);
|
||||
expect(validateManifest(m).ok).toBe(true);
|
||||
});
|
||||
|
||||
it('omits egress entirely when none is given (no empty array noise)', () => {
|
||||
@@ -40,7 +44,7 @@ describe('permission catalog', () => {
|
||||
'db:write:places', 'db:write:days', 'db:write:itinerary', 'db:write:trips',
|
||||
'db:meta',
|
||||
'ws:broadcast:trip', 'ws:broadcast:user',
|
||||
'hook:photo-provider', 'hook:calendar-source', 'hook:place-detail-provider', 'hook:trip-warning-provider', 'http:outbound',
|
||||
'hook:photo-provider', 'hook:calendar-source', 'hook:notification-channel', 'hook:place-detail-provider', 'hook:trip-warning-provider', 'http:outbound',
|
||||
]);
|
||||
for (const p of PERMISSION_CATALOG) expect(p.hint.length).toBeGreaterThan(0); // every option is described
|
||||
});
|
||||
@@ -120,3 +124,105 @@ describe('validateManifest dependency rules', () => {
|
||||
expect(validateManifest({ ...base, pluginDependencies: [{ id: 'koffi', version: '*' }, { id: 'koffi', version: '^1' }] }).ok).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('notification-channel template', () => {
|
||||
let tmp: string;
|
||||
beforeEach(() => { tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'chan-')); });
|
||||
afterEach(() => { fs.rmSync(tmp, { recursive: true, force: true }); });
|
||||
|
||||
function make(over: Parameters<typeof scaffold>[3] = {}) {
|
||||
scaffold('my-gotify', 'integration', tmp, { template: 'notification-channel', ...over });
|
||||
return JSON.parse(fs.readFileSync(path.join(tmp, 'my-gotify', 'trek-plugin.json'), 'utf8'));
|
||||
}
|
||||
|
||||
it('scaffolds a valid manifest with the hook grant, matching egress, and the capability', () => {
|
||||
const m = make({ egress: ['gotify.example.com'] });
|
||||
expect(m.type).toBe('integration'); // a channel is NOT a new plugin type
|
||||
expect(m.permissions).toContain('hook:notification-channel');
|
||||
expect(m.permissions).toContain('http:outbound:gotify.example.com');
|
||||
expect(m.egress).toEqual(['gotify.example.com']);
|
||||
expect(m.capabilities.notificationChannel.title).toBe('My Gotify');
|
||||
expect(validateManifest(m).ok).toBe(true);
|
||||
});
|
||||
|
||||
it('names no host when the author names none — bare http:outbound + operatorEgress', () => {
|
||||
// The common case: a Gotify/ntfy channel targets the USER's own server. Inventing a
|
||||
// `gotify.example.com` placeholder would ship a host nobody actually calls in the
|
||||
// published manifest, and grant an outbound host the plugin never needs.
|
||||
const m = make();
|
||||
expect(m.permissions).toContain('hook:notification-channel');
|
||||
expect(m.permissions).toContain('http:outbound');
|
||||
expect(m.permissions.some((p: string) => p.startsWith('http:outbound:'))).toBe(false);
|
||||
expect('egress' in m).toBe(false);
|
||||
expect(m.operatorEgress).toBe(true);
|
||||
expect(validateManifest(m).ok).toBe(true);
|
||||
});
|
||||
|
||||
it('declares the per-user credential as a secret, required, user-scoped field', () => {
|
||||
const m = make();
|
||||
const token = m.settings.find((s: { key: string }) => s.key === 'appToken');
|
||||
// These three flags are exactly what makes the host hand it to the hook as `config`.
|
||||
expect(token.scope).toBe('user');
|
||||
expect(token.secret).toBe(true);
|
||||
expect(token.required).toBe(true);
|
||||
});
|
||||
|
||||
it('generates a server entry that implements the hook', () => {
|
||||
make();
|
||||
const js = fs.readFileSync(path.join(tmp, 'my-gotify', 'server', 'index.js'), 'utf8');
|
||||
expect(js).toContain('notificationChannel');
|
||||
expect(js).toContain('async send(msg, config, ctx)');
|
||||
expect(js).toContain('config.appToken');
|
||||
|
||||
// The invariant is about WHERE ctx.settings.get() may be used, not whether:
|
||||
// - the HOOK is userless, so it must read credentials from its `config` argument;
|
||||
// - an ACTION is user-initiated, so it SHOULD read them via ctx.settings.get().
|
||||
const hookBody = js.slice(js.indexOf('notificationChannel:'));
|
||||
expect(hookBody).not.toContain('ctx.settings.get');
|
||||
const actionBody = js.slice(js.indexOf('actions:'), js.indexOf('hooks:'));
|
||||
expect(actionBody).toContain('await ctx.settings.get');
|
||||
});
|
||||
|
||||
it('scaffolds a Test connection action so the user can verify credentials', () => {
|
||||
const m = make();
|
||||
expect(m.actions).toEqual([{ key: 'testConnection', label: 'Test connection' }]);
|
||||
expect(validateManifest(m).ok).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects a malformed action key', () => {
|
||||
const m = make();
|
||||
expect(validateManifest({ ...m, actions: [{ key: '__proto__', label: 'x' }] }).ok).toBe(false);
|
||||
expect(validateManifest({ ...m, actions: [{ key: 'a', label: 'x' }, { key: 'a', label: 'y' }] }).ok).toBe(false);
|
||||
});
|
||||
|
||||
it('is server-only: no client/ dir, and a UI type is refused', () => {
|
||||
make();
|
||||
expect(fs.existsSync(path.join(tmp, 'my-gotify', 'client'))).toBe(false);
|
||||
expect(() => scaffold('my-widget', 'widget', tmp, { template: 'notification-channel' })).toThrow(/requires type "integration"/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('capabilities.notificationChannel validation', () => {
|
||||
const base = {
|
||||
id: 'chan', name: 'Chan', version: '1.0.0', apiVersion: 1, type: 'integration',
|
||||
nativeModules: false, permissions: ['hook:notification-channel'],
|
||||
};
|
||||
|
||||
it('accepts a narrowed event list', () => {
|
||||
const r = validateManifest({ ...base, capabilities: { notificationChannel: { events: ['trip_invite', 'booking_change'] } } });
|
||||
expect(r.ok).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects an event a plugin channel can never carry', () => {
|
||||
// version_available is admin-scoped — it goes out over the admin's own credentials.
|
||||
const r = validateManifest({ ...base, capabilities: { notificationChannel: { events: ['version_available'] } } });
|
||||
expect(r.ok).toBe(false);
|
||||
expect(r.errors!.join(' ')).toMatch(/not a plugin-deliverable event/);
|
||||
});
|
||||
|
||||
it('rejects the capability without the matching grant', () => {
|
||||
const r = validateManifest({ ...base, permissions: ['db:own'], capabilities: { notificationChannel: { title: 'X' } } });
|
||||
expect(r.ok).toBe(false);
|
||||
expect(r.errors!.join(' ')).toMatch(/requires the "hook:notification-channel" permission/);
|
||||
});
|
||||
});
|
||||
|
||||
+344
-7
@@ -1,4 +1,4 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
@@ -57,10 +57,47 @@ describe('validateManifest', () => {
|
||||
expect(validateManifest({ ...base, permissions: ['http:outbound'] }).ok).toBe(false);
|
||||
expect(validateManifest({ ...base, permissions: ['http:outbound'], egress: ['api.x.com'] }).ok).toBe(true);
|
||||
});
|
||||
it('waives the egress requirement for an operatorEgress plugin', () => {
|
||||
// A self-hosted target (Gotify, ntfy) has no host the author can name at publish
|
||||
// time — the admin supplies it after install, and TREK blocks all outbound until then.
|
||||
expect(validateManifest({ ...base, permissions: ['http:outbound'], operatorEgress: true }).ok).toBe(true);
|
||||
// The waiver is tied to the flag: no flag, still an error.
|
||||
expect(validateManifest({ ...base, permissions: ['http:outbound'], operatorEgress: false }).ok).toBe(false);
|
||||
// …and the flag alone never grants reach: it still needs an http:outbound permission.
|
||||
expect(validateManifest({ ...base, permissions: ['db:own'], operatorEgress: true }).ok).toBe(false);
|
||||
});
|
||||
it('rejects native modules and non-objects', () => {
|
||||
expect(validateManifest({ ...base, nativeModules: true }).ok).toBe(false);
|
||||
expect(validateManifest('nope').ok).toBe(false);
|
||||
});
|
||||
it('accepts the newer host permissions (writes, notify, map-marker hook)', () => {
|
||||
const permissions = ['db:write:reservations', 'db:write:accommodations', 'notify:send', 'hook:map-marker-provider'];
|
||||
const r = validateManifest({ ...base, permissions });
|
||||
expect(r.errors).toEqual([]);
|
||||
expect(r.ok).toBe(true);
|
||||
expect(r.manifest?.permissions).toEqual(permissions);
|
||||
});
|
||||
it('accepts hook:trip-card-provider and hook:user-data (server accepts them)', () => {
|
||||
const permissions = ['hook:trip-card-provider', 'hook:user-data'];
|
||||
const r = validateManifest({ ...base, permissions });
|
||||
expect(r.ok).toBe(true);
|
||||
expect(r.manifest?.permissions).toEqual(permissions);
|
||||
});
|
||||
|
||||
it('accepts the read-symmetry + broker permissions (collab, file content, trip create, rates)', () => {
|
||||
const permissions = ['db:read:collab', 'db:create:trips', 'rates:read', 'db:read:files:content'];
|
||||
const r = validateManifest({ ...base, permissions });
|
||||
expect(r.errors).toEqual([]);
|
||||
expect(r.ok).toBe(true);
|
||||
expect(r.manifest?.permissions).toEqual(permissions);
|
||||
});
|
||||
it('validates tripPage: replaceable tabs only (never plan), position 0-50', () => {
|
||||
const page = { ...base, type: 'trip-page' };
|
||||
expect(validateManifest({ ...page, capabilities: { tripPage: { replaces: ['transports', 'buchungen'], position: 1 } } }).ok).toBe(true);
|
||||
expect(validateManifest({ ...page, capabilities: { tripPage: { replaces: ['plan'] } } }).ok).toBe(false);
|
||||
expect(validateManifest({ ...page, capabilities: { tripPage: { replaces: ['nope'] } } }).ok).toBe(false);
|
||||
expect(validateManifest({ ...page, capabilities: { tripPage: { position: -1 } } }).ok).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('createMockHost', () => {
|
||||
@@ -70,15 +107,23 @@ describe('createMockHost', () => {
|
||||
await expect(ctx.trips.getById(1, 1)).rejects.toThrow(/PERMISSION_DENIED/);
|
||||
});
|
||||
|
||||
it('membership-checks trip reads and records broadcasts', async () => {
|
||||
const { ctx, broadcasts } = createMockHost({
|
||||
it('membership-checks trip reads against the ACTING user (asUserId is ignored, like the real host) and records broadcasts', async () => {
|
||||
const member = createMockHost({
|
||||
grants: ['db:read:trips', 'ws:broadcast:trip'],
|
||||
actingUserId: 42,
|
||||
trips: { 1: { members: [42], data: { id: 1, name: 'Japan' } } },
|
||||
});
|
||||
await expect(ctx.trips.getById(1, 99)).rejects.toThrow(/RESOURCE_FORBIDDEN/);
|
||||
expect(await ctx.trips.getById(1, 42)).toEqual({ id: 1, name: 'Japan' });
|
||||
await ctx.ws.broadcastToTrip(1, 'ping', { a: 1 });
|
||||
expect(broadcasts).toEqual([{ kind: 'trip', target: 1, event: 'ping', data: { a: 1 } }]);
|
||||
expect(await member.ctx.trips.getById(1)).toEqual({ id: 1, name: 'Japan' });
|
||||
await member.ctx.ws.broadcastToTrip(1, 'ping', { a: 1 });
|
||||
expect(member.broadcasts).toEqual([{ kind: 'trip', target: 1, event: 'ping', data: { a: 1 } }]);
|
||||
// asUserId is accepted for source-compat but IGNORED: a non-member acting user is
|
||||
// refused even when it passes a member id as asUserId (the #13 divergence, now fixed).
|
||||
const outsider = createMockHost({
|
||||
grants: ['db:read:trips'],
|
||||
actingUserId: 99,
|
||||
trips: { 1: { members: [42], data: { id: 1, name: 'Japan' } } },
|
||||
});
|
||||
await expect(outsider.ctx.trips.getById(1, 42)).rejects.toThrow(/RESOURCE_FORBIDDEN/);
|
||||
});
|
||||
|
||||
it('returns canned db.query results + records logs', async () => {
|
||||
@@ -150,6 +195,70 @@ describe('createMockHost', () => {
|
||||
await expect(ungranted.ctx.meta.get('trip', 1, 'x')).rejects.toThrow(/PERMISSION_DENIED/);
|
||||
});
|
||||
|
||||
it('serves days + accommodations from the trip fixture and creates lodging blocks', async () => {
|
||||
const { ctx } = createMockHost({
|
||||
grants: ['db:read:trips', 'db:write:accommodations'],
|
||||
actingUserId: 42,
|
||||
trips: {
|
||||
1: {
|
||||
members: [42],
|
||||
days: [{ id: 1, date: '2026-07-01' }, { id: 2, date: '2026-07-02' }],
|
||||
accommodations: [{ id: 9, place_id: 3, start_day_id: 1, end_day_id: 2 }],
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(await ctx.trips.getDays(1)).toEqual([{ id: 1, date: '2026-07-01' }, { id: 2, date: '2026-07-02' }]);
|
||||
expect(await ctx.trips.getAccommodations(1)).toHaveLength(1);
|
||||
const created = await ctx.accommodations.create(1, { place_id: 7, start_day_id: 1, end_day_id: 2 });
|
||||
expect(created).toMatchObject({ trip_id: 1, place_id: 7 });
|
||||
expect(await ctx.trips.getAccommodations(1)).toHaveLength(2);
|
||||
// ungranted read stays refused
|
||||
const ungranted = createMockHost({ grants: [], actingUserId: 42, trips: { 1: { members: [42] } } });
|
||||
await expect(ungranted.ctx.trips.getDays(1)).rejects.toThrow(/PERMISSION_DENIED/);
|
||||
});
|
||||
|
||||
it('removeMember + journey create/delete round out the write symmetry, grant-gated', async () => {
|
||||
const host = createMockHost({
|
||||
grants: ['db:write:members', 'db:write:journal'],
|
||||
actingUserId: 42,
|
||||
trips: { 1: { members: [42, 7] } },
|
||||
});
|
||||
expect(await host.ctx.trips.removeMember(1, 7)).toEqual({ removed: true });
|
||||
expect(await host.ctx.trips.removeMember(1, 999)).toEqual({ removed: true }); // prod's DELETE reports removed:true either way
|
||||
const j = await host.ctx.journal.createJourney({ title: 'Imported', trip_ids: [1] });
|
||||
expect(j).toMatchObject({ title: 'Imported' });
|
||||
expect(await host.ctx.journal.deleteJourney(1)).toEqual({ deleted: true });
|
||||
// grants enforced identically to production
|
||||
const ungranted = createMockHost({ grants: [], actingUserId: 42, trips: { 1: { members: [42, 7] } } });
|
||||
await expect(ungranted.ctx.trips.removeMember(1, 7)).rejects.toThrow(/PERMISSION_DENIED/);
|
||||
await expect(ungranted.ctx.journal.createJourney({ title: 'x' })).rejects.toThrow(/PERMISSION_DENIED/);
|
||||
});
|
||||
|
||||
it('creates a trip for the acting user and serves rates + collab reads against the grants', async () => {
|
||||
const { ctx } = createMockHost({
|
||||
grants: ['db:create:trips', 'rates:read', 'db:read:collab'],
|
||||
actingUserId: 42,
|
||||
trips: { 1: { members: [42], notes: [{ id: 1, title: 'Museum tips' }] } },
|
||||
ratesResult: { USD: 1.08, GBP: 0.85 },
|
||||
});
|
||||
expect(await ctx.trips.create({ title: 'Japan 2027', currency: 'JPY' })).toMatchObject({ title: 'Japan 2027', user_id: 42 });
|
||||
expect(await ctx.collab.listNotes(1)).toEqual([{ id: 1, title: 'Museum tips' }]);
|
||||
expect(await ctx.rates.get('EUR')).toEqual({ USD: 1.08, GBP: 0.85 });
|
||||
// ungranted capability (file content) stays refused
|
||||
await expect(ctx.files.getContent(1, 1)).rejects.toThrow(/PERMISSION_DENIED/);
|
||||
});
|
||||
|
||||
it('serves file bytes via files.getContent under db:read:files:content', async () => {
|
||||
const content = Buffer.from('voucher bytes').toString('base64');
|
||||
const { ctx } = createMockHost({
|
||||
grants: ['db:read:files:content'],
|
||||
actingUserId: 42,
|
||||
trips: { 1: { members: [42], files: [{ id: 3, name: 'voucher.pdf', mimetype: 'application/pdf', content_base64: content }] } },
|
||||
});
|
||||
expect(await ctx.files.getContent(1, 3)).toEqual({ name: 'voucher.pdf', mimetype: 'application/pdf', size: 13, content_base64: content });
|
||||
await expect(ctx.files.getContent(1, 99)).rejects.toThrow(/RESOURCE_FORBIDDEN/);
|
||||
});
|
||||
|
||||
it('refuses costs when the permission is missing or the addon is disabled', async () => {
|
||||
const ungranted = createMockHost({ grants: [], actingUserId: 42, trips: { 1: { members: [42] } } });
|
||||
await expect(ungranted.ctx.costs.getByTrip(1)).rejects.toThrow(/PERMISSION_DENIED/);
|
||||
@@ -162,6 +271,124 @@ describe('createMockHost', () => {
|
||||
});
|
||||
await expect(addonOff.ctx.costs.getByTrip(1)).rejects.toThrow(/RESOURCE_FORBIDDEN/);
|
||||
});
|
||||
|
||||
it('host.run drives the plugin\'s own handlers (route, job, scheduled, event, GDPR, hook)', async () => {
|
||||
const seen: string[] = [];
|
||||
const def = definePlugin({
|
||||
routes: [{ method: 'GET', path: '/ping', async handler(req) { return { status: 200, body: { user: req.user?.id } }; } }],
|
||||
jobs: [{ id: 'refresh', schedule: '* * * * *', async handler() { seen.push('job'); } }],
|
||||
async scheduled({ name, payload }) { seen.push(`sched:${name}:${JSON.stringify(payload)}`); },
|
||||
events: [{ on: 'place:created', handler(p) { seen.push(`evt:${p.event}:${p.entityId}`); } }],
|
||||
async deleteUserData({ userId }) { seen.push(`del:${userId}`); },
|
||||
async exportUserData({ userId }) { return { userId, rows: 2 }; },
|
||||
hooks: { tripCardProvider: { async getCards(tripIds) { return tripIds.map((id) => ({ tripId: id, id: 'b', label: 'X' })); } } },
|
||||
});
|
||||
const host = createMockHost({ grants: ['jobs:run', 'hook:trip-card-provider'], actingUserId: 7 });
|
||||
const d = host.run(def);
|
||||
|
||||
const res = await d.route({ method: 'GET', path: '/ping' });
|
||||
expect(res).toEqual({ status: 200, body: { user: 7 } });
|
||||
await d.job('refresh');
|
||||
await d.scheduled('daily', { x: 1 });
|
||||
await d.event('place:created', { tripId: 1, entity: 'place', entityId: 9 });
|
||||
await d.deleteUserData(42);
|
||||
expect(await d.exportUserData(42)).toEqual({ userId: 42, rows: 2 });
|
||||
expect(await d.hook('tripCardProvider', 'getCards', [1, 2])).toEqual([
|
||||
{ tripId: 1, id: 'b', label: 'X' }, { tripId: 2, id: 'b', label: 'X' },
|
||||
]);
|
||||
expect(seen).toEqual(['job', 'sched:daily:{"x":1}', 'evt:place:created:9', 'del:42']);
|
||||
|
||||
// missing handlers / unknown ids throw a clear error, not a silent no-op
|
||||
await expect(d.job('nope')).rejects.toThrow(/no job/);
|
||||
await expect(host.run(definePlugin({})).scheduled('x')).rejects.toThrow(/no scheduled handler/);
|
||||
});
|
||||
|
||||
it('exposes the scheduler timers a plugin armed via ctx.scheduler', async () => {
|
||||
const def = definePlugin({ async onLoad(ctx) { await ctx.scheduler.every(3_600_000, 'sync', { n: 1 }); } });
|
||||
const host = createMockHost({ grants: ['jobs:run'] });
|
||||
await host.run(def).load();
|
||||
expect(host.scheduled.get('sync')).toMatchObject({ everyMs: 3_600_000, payload: { n: 1 } });
|
||||
});
|
||||
|
||||
it('runs jobs USERLESS like production — a membership read refuses, the same read from a route works', async () => {
|
||||
const seen: string[] = [];
|
||||
const def = definePlugin({
|
||||
jobs: [{ id: 'sync', schedule: '* * * * *', async handler(ctx) {
|
||||
try { await ctx.trips.getById(1); seen.push('read-ok'); } catch (e) { seen.push((e as Error).message.split(':')[0]); }
|
||||
} }],
|
||||
routes: [{ method: 'GET', path: '/t', async handler(_req, ctx) { return { status: 200, body: await ctx.trips.getById(1) }; } }],
|
||||
});
|
||||
const host = createMockHost({ grants: ['db:read:trips', 'jobs:run'], actingUserId: 42, trips: { 1: { members: [42], data: { id: 1 } } } });
|
||||
const d = host.run(def);
|
||||
await d.job('sync');
|
||||
expect(seen).toEqual(['RESOURCE_FORBIDDEN']);
|
||||
expect(await d.route(0)).toEqual({ status: 200, body: { id: 1 } });
|
||||
});
|
||||
|
||||
it('notify.send strips emojis and enforces the host caps + in-app link rule', async () => {
|
||||
const host = createMockHost({ grants: ['notify:send'], actingUserId: 7, trips: { 1: { members: [7] } } });
|
||||
await expect(host.ctx.notify.send({ title: '🎉🎉', body: 'x', scope: 'user', targetId: 7 })).rejects.toThrow(/title is required/);
|
||||
await expect(host.ctx.notify.send({ title: 't', body: 'x'.repeat(1001), scope: 'user', targetId: 7 })).rejects.toThrow(/max 1000/);
|
||||
await expect(host.ctx.notify.send({ title: 't', body: 'b', scope: 'user', targetId: 7, link: 'https://evil.example' })).rejects.toThrow(/in-app path/);
|
||||
await host.ctx.notify.send({ title: 'Trip 🎉 ready', body: 'b', scope: 'trip', targetId: 1, link: '/trips/1' });
|
||||
expect(host.notifications).toEqual([{ title: 'Trip ready', body: 'b', link: '/trips/1', scope: 'trip', targetId: 1 }]);
|
||||
});
|
||||
|
||||
it('db guards match the host: forbidden statements, tx control, op cap', async () => {
|
||||
const { ctx } = createMockHost({ grants: ['db:own'] });
|
||||
await expect(ctx.db.query('PRAGMA user_version')).rejects.toThrow(/not allowed/);
|
||||
await expect(ctx.db.tx([{ sql: ' COMMIT' }])).rejects.toThrow(/transaction-control/);
|
||||
await expect(ctx.db.tx([{ sql: '/* x */ROLLBACK' }])).rejects.toThrow(/transaction-control/);
|
||||
await expect(ctx.db.tx(Array.from({ length: 101 }, () => ({ sql: 'SELECT 1' })))).rejects.toThrow(/at most 100/);
|
||||
});
|
||||
|
||||
it('member writes need member_manage + protect the owner; users.getById serves only public fields', async () => {
|
||||
const host = createMockHost({
|
||||
grants: ['db:write:members', 'db:read:users'],
|
||||
actingUserId: 42,
|
||||
users: { 7: { id: 7, username: 'ada', email: 'secret@example.com' }, 42: { id: 42, username: 'me' } },
|
||||
trips: { 1: { members: [42, 7], data: { id: 1, user_id: 42 } }, 2: { members: [42], can: { member_manage: false } } },
|
||||
});
|
||||
await expect(host.ctx.trips.removeMember(1, 42)).rejects.toThrow(/trip owner/);
|
||||
await expect(host.ctx.trips.addMember(2, 7)).rejects.toThrow(/RESOURCE_FORBIDDEN/);
|
||||
await expect(host.ctx.trips.addMember(1, 999)).rejects.toThrow(/no user 999/);
|
||||
const u = await host.ctx.users.getById(7) as Record<string, unknown>;
|
||||
expect(u).toMatchObject({ id: 7, username: 'ada' });
|
||||
expect('email' in u).toBe(false);
|
||||
await expect(host.ctx.users.getById(999)).rejects.toThrow(/no access to user 999/); // no shared trip
|
||||
});
|
||||
|
||||
it('addon toggles gate journal/vacay/collections like production; atlas normalizes codes', async () => {
|
||||
const off = createMockHost({
|
||||
grants: ['db:read:journal', 'db:read:atlas', 'db:write:atlas', 'db:read:vacay', 'db:read:collections'],
|
||||
actingUserId: 1,
|
||||
journeyAddonEnabled: false, vacayAddonEnabled: false, collectionsAddonEnabled: false,
|
||||
});
|
||||
await expect(off.ctx.journal.listMine()).rejects.toThrow(/journey addon is disabled/);
|
||||
await expect(off.ctx.vacay.mine()).rejects.toThrow(/vacay addon is disabled/);
|
||||
await expect(off.ctx.collections.listMine()).rejects.toThrow(/collections addon is disabled/);
|
||||
expect(await off.ctx.atlas.markCountry('de')).toEqual({ visited: true }); // atlas stays enabled
|
||||
expect(await off.ctx.atlas.visited()).toMatchObject({ countries: ['DE'] });
|
||||
await expect(off.ctx.atlas.markCountry('not-a-code!')).rejects.toThrow(/short code/);
|
||||
});
|
||||
|
||||
it('scheduler refuses a non-finite or >1-year dueAt, like the host', async () => {
|
||||
const { ctx } = createMockHost({ grants: ['jobs:run'] });
|
||||
await expect(ctx.scheduler.at(Number.NaN, 'x')).rejects.toThrow(/dueAt out of range/);
|
||||
await expect(ctx.scheduler.at(Date.now() + 400 * 24 * 3600 * 1000, 'x')).rejects.toThrow(/dueAt out of range/);
|
||||
await expect(ctx.scheduler.every(1000, 'x')).rejects.toThrow(/>= 60000/);
|
||||
});
|
||||
|
||||
it('declaredEmits drops an undeclared emit with a warning — production refuses it', () => {
|
||||
const host = createMockHost({ declaredEmits: ['rate.updated'] });
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
try {
|
||||
host.ctx.events.emit('rate.updated', { a: 1 });
|
||||
host.ctx.events.emit('undeclared.event', {});
|
||||
expect(warn).toHaveBeenCalledOnce();
|
||||
} finally { warn.mockRestore(); }
|
||||
expect(host.emitted).toEqual([{ name: 'rate.updated', payload: { a: 1 } }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('scaffold + validate CLIs', () => {
|
||||
@@ -291,6 +518,18 @@ describe('dev db bind shapes', () => {
|
||||
close();
|
||||
}
|
||||
});
|
||||
|
||||
it.runIf(hasNodeSqlite)('refuses the statements the real host forbids for plugin databases', async () => {
|
||||
const { createDevDb } = await import('../src/cli/dev.js');
|
||||
const { db, close } = createDevDb(path.join(tmp, 'db.sqlite'));
|
||||
try {
|
||||
await expect(db.query('PRAGMA user_version')).rejects.toThrow(/not allowed/);
|
||||
await expect(db.exec("ATTACH DATABASE 'x' AS y")).rejects.toThrow(/not allowed/);
|
||||
await expect(db.migrate('001', 'PRAGMA journal_mode = OFF')).rejects.toThrow(/not allowed/);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('reference plugin (examples/koffi)', () => {
|
||||
@@ -468,6 +707,104 @@ describe('mock-host inter-plugin (plugins.call + events.emit)', () => {
|
||||
ctx.events.emit('rate.updated', { pair: 'USD/EUR' });
|
||||
expect(emitted).toEqual([{ name: 'rate.updated', payload: { pair: 'USD/EUR' } }]);
|
||||
});
|
||||
|
||||
it('drives a notificationChannel USERLESS, with the recipient config passed in', async () => {
|
||||
const sent: unknown[] = [];
|
||||
const def = definePlugin({
|
||||
hooks: {
|
||||
notificationChannel: {
|
||||
async send(msg, config, ctx) {
|
||||
// The whole point of the userless dispatch: the credentials arrive as `config`,
|
||||
// and the channel canNOT read anything as the recipient.
|
||||
sent.push({ msg, token: config.token, settings: await ctx.settings.get('token') });
|
||||
},
|
||||
async test(config) { if (!config.token) throw new Error('no token'); },
|
||||
},
|
||||
},
|
||||
});
|
||||
const host = createMockHost({
|
||||
grants: ['hook:notification-channel', 'db:read:trips'],
|
||||
actingUserId: 7,
|
||||
userSettings: { token: 'abc' },
|
||||
trips: { 1: { members: [7] } },
|
||||
});
|
||||
const d = host.run(def);
|
||||
|
||||
await d.channel.send({ event: 'trip_invite', title: 'Hi', body: 'Japan' });
|
||||
expect(sent).toEqual([{
|
||||
msg: { event: 'trip_invite', title: 'Hi', body: 'Japan' },
|
||||
token: 'abc',
|
||||
// Userless: ctx.settings.get() resolves against the ACTING user, and there is none.
|
||||
settings: undefined,
|
||||
}]);
|
||||
|
||||
await expect(d.channel.test({ token: 'x' })).resolves.toBeUndefined();
|
||||
await expect(d.channel.test({})).rejects.toThrow(/no token/);
|
||||
});
|
||||
|
||||
it('refuses a channel event the host would never dispatch, and a manifest may narrow the set', async () => {
|
||||
const def = definePlugin({ hooks: { notificationChannel: { async send() { /* delivered */ } } } });
|
||||
const d = createMockHost({ grants: ['hook:notification-channel'] }).run(def);
|
||||
// Admin-scoped / in-app-only events are not in CHANNEL_EVENTS.
|
||||
await expect(d.channel.send({ event: 'admin_alert', title: 'T', body: 'B' })).rejects.toThrow(/never dispatches/);
|
||||
await expect(d.channel.send({ event: 'trip_invite', title: 'T', body: 'B' })).resolves.toBeUndefined();
|
||||
|
||||
const narrowed = createMockHost({ grants: ['hook:notification-channel'], channelEvents: ['todo_due'] }).run(def);
|
||||
await expect(narrowed.channel.send({ event: 'trip_invite', title: 'T', body: 'B' })).rejects.toThrow(/never dispatches/);
|
||||
await expect(narrowed.channel.send({ event: 'todo_due', title: 'T', body: 'B' })).resolves.toBeUndefined();
|
||||
|
||||
await expect(createMockHost({}).run(definePlugin({})).channel.send({ event: 'todo_due', title: 'T', body: 'B' }))
|
||||
.rejects.toThrow(/no notificationChannel hook/);
|
||||
});
|
||||
|
||||
it('a plugin with no notificationChannel.test is a clear error, not a silent pass', async () => {
|
||||
const def = definePlugin({ hooks: { notificationChannel: { async send() {} } } });
|
||||
await expect(createMockHost({}).run(def).channel.test()).rejects.toThrow(/no notificationChannel\.test/);
|
||||
});
|
||||
|
||||
it('runs a settings action as the CLICKING user and shapes the result like the host', async () => {
|
||||
const def = definePlugin({
|
||||
actions: {
|
||||
test: async (ctx) => ({ ok: true, message: `token=${await ctx.settings.get('token')} ✅` }),
|
||||
quiet: () => {},
|
||||
boom: () => { throw new Error('credentials rejected'); },
|
||||
loud: () => ({ ok: false, message: 'x'.repeat(500) }),
|
||||
},
|
||||
});
|
||||
const host = createMockHost({ actingUserId: 7, userSettings: { token: 'abc' } });
|
||||
const d = host.run(def);
|
||||
|
||||
// User-initiated: ctx.settings.get() returns the clicker's own value. The message is
|
||||
// emoji-stripped and bounded, exactly as the host does before showing it.
|
||||
expect(await d.action('test')).toEqual({ ok: true, message: 'token=abc' });
|
||||
// A handler that returns nothing succeeded.
|
||||
expect(await d.action('quiet')).toEqual({ ok: true, message: undefined });
|
||||
// Throwing is the documented "action failed" path, not a rejected promise.
|
||||
expect(await d.action('boom')).toEqual({ ok: false, message: 'credentials rejected' });
|
||||
expect((await d.action('loud')).message).toHaveLength(200);
|
||||
|
||||
await expect(d.action('nope')).rejects.toThrow(/no action/);
|
||||
});
|
||||
|
||||
it('refuses an action key the manifest does not declare', async () => {
|
||||
const def = definePlugin({ actions: { sync: () => ({ ok: true }) } });
|
||||
const d = createMockHost({ actingUserId: 7, declaredActions: ['test'] }).run(def);
|
||||
await expect(d.action('sync')).rejects.toThrow(/RESOURCE_FORBIDDEN/);
|
||||
});
|
||||
|
||||
it('never resolves a settings key off Object.prototype', async () => {
|
||||
// The bug this models: `__proto__`/`constructor` used to resolve to a truthy object,
|
||||
// reporting a REQUIRED field as configured for a user who had configured nothing.
|
||||
const { ctx } = createMockHost({ actingUserId: 7, userSettings: { token: 'abc' } });
|
||||
expect(await ctx.settings.get('__proto__')).toBeUndefined();
|
||||
expect(await ctx.settings.get('constructor')).toBeUndefined();
|
||||
expect(await ctx.settings.get('token')).toBe('abc');
|
||||
// And a fixture the host would have refused at install fails the test up front. Note a
|
||||
// `__proto__` OWN key only exists via JSON.parse (in a literal it sets the prototype) —
|
||||
// which is exactly the shape a stored config blob arrives in.
|
||||
expect(() => createMockHost({ userSettings: JSON.parse('{"__proto__":{"evil":1}}') })).toThrow(/settings key/);
|
||||
expect(() => createMockHost({ userSettings: { '9lives': 1 } })).toThrow(/settings key/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('validateManifest capabilities.provides/emits', () => {
|
||||
|
||||
@@ -46,6 +46,19 @@ describe('design kit', () => {
|
||||
expect(out).toContain('window.trek');
|
||||
});
|
||||
|
||||
it('auto-upgrades native <select> into a host-styled, opt-out-able listbox', () => {
|
||||
// Styles for the enhanced control ship in the kit.
|
||||
for (const cls of ['.trek-select-trigger', '.trek-select-menu', '.trek-select-option']) {
|
||||
expect(TREK_UI_CSS).toContain(cls);
|
||||
}
|
||||
// The bootstrap enhances selects as a listbox, keeps a per-field opt-out, and
|
||||
// re-emits real change events so form/plugin code still works.
|
||||
expect(TREK_THEME_JS).toContain('enhanceSelect');
|
||||
expect(TREK_THEME_JS).toContain('data-trek-native');
|
||||
expect(TREK_THEME_JS).toContain("'listbox'");
|
||||
expect(TREK_THEME_JS).toContain("dispatch(sel, 'change')");
|
||||
});
|
||||
|
||||
it('injectTrekUi is a no-op without the marker and expands every occurrence', () => {
|
||||
const plain = '<html><body><h1>hi</h1></body></html>';
|
||||
expect(injectTrekUi(plain)).toBe(plain);
|
||||
|
||||
Reference in New Issue
Block a user