* docs(wiki): document the snap Docker + no-new-privileges startup failure

* fix(setup): warn when ADMIN_EMAIL/ADMIN_PASSWORD are ignored, ship reset-admin

The first-run seeder only applies ADMIN_EMAIL/ADMIN_PASSWORD on an empty
database and then silently ignores them. People add the vars after the first
boot, or pull a fresh image without clearing ./data, restart, and cannot log
in with no hint why (#1339). The default is a generated password (not the
.env.example placeholder), printed once in the first-run box. Now: warn loudly
when the vars are set but a user already exists, and warn on a partial
(one-of-two) config instead of quietly falling back.

Also ship the reset-admin recovery script in the image -- it was never COPYed in
despite the wiki referencing it. node server/reset-admin.js resets/creates
admin@trek.local with a generated password (RESET_ADMIN_EMAIL/RESET_ADMIN_PASSWORD
overridable), picks a free username so it cannot trip UNIQUE(username), and sets
must_change_password.

* feat(extract): extract data using LLM

* fix(extract): auto-run the AI fallback when the addon is enabled

Booking import only fell back to the LLM when each user flipped an 'always retry with AI' toggle, so by default files kitinerary returned nothing for just failed. Run the fallback automatically whenever the AI Parsing addon is on (fallback-on-empty); drop the now-redundant per-user toggle and its setting.

* fix(extract): make AI imports reliable and fast on local models

client: the import call inherited the global 8s axios timeout and aborted long LLM extractions even though the server finished it; remove the timeout. server: raise the OpenAI-compatible LLM timeout 60s->180s (a cold Ollama model can take ~45s to first token). server: cap extracted text to 8000 chars before the LLM - multi-page T&C tails (30k+ chars) overflowed the context window, truncating the relevant head and making CPU inference crawl; booking details sit at the top.

* feat(extract): fill transport/booking fields, geocode endpoints, assign days

- rental car: request+map dropoffLocation, emit pickup->return from/to endpoints, set a location string (G1/G2/G3). - geocode endpoints (stations/stops/terminals/rental desks) on confirm via Nominatim; mapper now emits coordless named endpoints and confirm persists only the geocoded ones (G6). - assign every dated booking to the nearest trip day so it still shows when slightly out of range, and keep hotel accommodation from vanishing when a check date misses (G5/G10). - fix bus mislabelled as train + add bus_number metadata (G7/G8), flag malformed boats (G9), accept root start/end time for events (G11). - raise the local-LLM timeout to 300s for CPU-only Ollama.

* perf(extract): cap LLM input at 4000 chars for CPU-only speed

On a GPU-less host the model's prompt-eval time scales with input length and dominates total latency. Booking details sit at the top of a confirmation, so capping the extracted text at 4000 chars (was 8000) roughly halves extraction time (~50s warm for a capable local 7B model) with no loss of fields on real hotel/rental confirmations. Tunable if a long multi-segment itinerary needs more.

* feat(extract): capture seat, class, platform, price + event venue contact

Request and map root-level seat/class/platform and a total price/currency into reservation metadata (shown on the card; price reuses the existing label). Read both the root and reservationFor and tolerate common field-name aliases (priceAmount, priceCurrencyISO4217Code, fareClass, ...) since models name these inconsistently. Also capture event/attraction venue telephone + url onto the auto-created place, matching lodging/restaurant.

* feat(extract): create a linked cost from the booking price on import

When a confirmation carries a total price, record it as a real expense
linked to the reservation (in the matching Costs category) instead of
leaving the amount in metadata only. Gated on the Costs addon.

* fix(extract): refresh accommodations after a booking import

A freshly imported hotel links to an accommodation that lives outside the
trip store, so loadTrip alone left the reservation edit modal with blank
place/date fields. Reload the accommodations list once the import finishes.

* feat(extract): drive NuExtract with its native template

NuExtract isn't an instruct model — fed a plain chat prompt it just echoes the
schema back. Detect a NuExtract model by id and talk to it the way the model
cards document: the JSON template inlined in a single user message, no system
prompt, no json_schema, temperature 0. Its flat result is mapped back to the
same KiReservation shape the rest of the pipeline already uses, so nothing
downstream changes; every other model keeps the generic prompt.

Money is taken as a verbatim string and parsed locally (German "1.580,22 €"
otherwise comes back as 1.49772), a rental car's pickup/return ride the from/to
fields so a stray form label doesn't become the location, and a lodging with no
name falls back to its address instead of being dropped.

* fix(admin): tidy the AI parsing settings and recommend the 2B model

The provider picker is the shared CustomSelect now and the form is split into
clear sections rather than a flat stack of inputs. NuExtract 2.0 2B is the
recommended default — fastest on a CPU-only host and MIT licensed; the 4B
carries a non-commercial licence, so it's no longer flagged as recommended.

* feat(import): review each parsed booking before it's saved

Instead of writing parsed items straight to the trip, the import opens the
normal edit modal pre-filled for each one, so you can check and fix it before
saving — useful when a model guesses a wrong date or address. Hotels gained an
editable address field; on save an existing place is matched by name, otherwise
the reviewed address is geocoded and a new place is created.

* feat(extract): drive local parsing through a layered extraction router

The single-shot prompt was unreliable on multi-leg flights and longer
documents, and slow on a CPU host. For the local provider, run a small
router instead:

- deterministic vendor templates first, with no model call at all
- exactly one grammar-enforced call per document via Ollama's native
  `format` (flights as a flat array of legs, everything else as one flat
  reservation, the type picked from keywords or a union schema)
- booking-wide fields (booking reference, total price, the overnight
  arrival day) filled deterministically from the text afterwards, and
  dates coerced to ISO so a natural-language date can't slip through

Recommend qwen2.5 in the AI-parsing settings instead of NuExtract.

* feat(import): parse bookings in the background with a progress widget

Parsing a booking can take a while on a CPU host, so don't hold the
upload modal open for it. The async import endpoint returns a job id
right away; the parse runs server-side (one at a time per user) and
pushes progress over the user's WebSocket, and a small widget in the
bottom corner tracks it while the user keeps navigating and editing.
A finished job opens the per-item review from the widget.

* fix(import): create linked costs and accommodations from reviewed bookings

Reviewing an imported booking saves it through the normal reservation
form, which dropped the parsed price (so no linked cost was created) and
only created the accommodation when both nights matched a trip day.
Carry the parsed price into a linked cost on save, and create the
accommodation from whichever day the check-in/out dates resolve to.

* feat(extract): add Expedia and rental-broker booking templates

Pull the hotel/rental fields these vendors print in a stable text layout (name, address, stay/pickup dates, price, reference) deterministically, so the import stops depending on the local model for them. Handles German long/abbreviated months and English dates incl. 12-hour and comma forms.

* fix(extract): backfill booking code/total and harden the reference match

Apply the deterministic confirmation-code and total fill to vendor-template results too (not just model output), and require the captured reference to contain a digit so a bare 'Confirmation'/'Reference' label no longer grabs the next prose word.

* fix(import): keep the parse-progress widget across a reload

Persist the background-import tasks (id/trip/status only) and re-fetch each job's status on mount, so a parse still running when the page reloads keeps its widget instead of vanishing; expired jobs (404) are dropped and a restored 'done' task re-fetches its items.

* fix(reservations): skip un-geocoded endpoints instead of failing the save

reservation_endpoints.lat/lng are NOT NULL, so saving a reviewed transport whose pick-up/return couldn't be geocoded threw a 500 and lost the whole booking (dates, linked cost). Skip those rows; the dates still persist on reservation_time/reservation_end_time.

* fix(import): resolve an imported transport's day from its parsed dates

A reviewed transport (e.g. a rental car) arrived with only its parsed pick-up/return dates and no day_id, so the modal kept just the time and saved a bare "HH:MM" with no date. Resolve start/end day from the parsed dates (exact match, else nearest trip day) so the booking lands on the right days.

* fix(import): refresh costs after a booking review so imported expenses appear without a reload

Imported bookings auto-create their linked budget items server-side, but the saving client suppresses its own budget:created echo, so the Costs list stayed stale until a manual reload. Reload the budget items when the review session ends.

* refactor(extract): dedupe currency/day helpers, drop redundant casts, support JPY vouchers

Code-audit clean-ups: share one normCurrency between the router and the templates, lift the duplicated nearest-day resolver into formatters.resolveDayId, drop two needless as-unknown-as casts at the fillBookingWideFields call sites, restore routeExtraction's doc comment, and give the broker template readable names. Plus recognise ¥/JPY and fall back to a standalone symbol amount, so a Klook-style voucher whose price sits far from any label still yields a cost.

* feat(import): attach the parsed source document to each booking

Keep the uploaded files on the background task and hand them to the review flow, so each reviewed booking pre-fills its Files with the document it was parsed from (uploaded with the booking on save). The two modals also adopt the shared resolveDayId helper.

* fix(extract): disable model thinking for grammar-constrained extraction

Hybrid/reasoning models (Qwen3 and similar) default to emitting reasoning tokens, which collide with Ollama's format-grammar constraint — on CPU this produced null/unparseable output and blew the latency budget (qwen3:8b: null or 300s timeouts vs ~20s with thinking off). Send think:false on the /api/chat call; Ollama ignores it for non-thinking models (verified on qwen2.5:7b), so it's safe and unlocks the stronger Qwen3 family.

* feat(extract): recommend Qwen3-8B as the local extraction model

A/B against the prior default (qwen2.5:7b) on CPU showed Qwen3-8B is both faster and more accurate on tricky/multilingual booking docs (correct Airbnb year+price, correct DisneySea admission date), once thinking is disabled — which the router now does. Feature it as the recommended pull, keep qwen2.5:7b as the fallback.

* refactor(extract): drop vendor templates, let the model drive with deterministic backfill

Now that a capable instruct model (Qwen3-8B, thinking off) reads name/address/dates/legs reliably across formats, the per-vendor template short-circuit distorted more than it fixed: brittle on layout variations and overriding the better model output. Remove the template layer; the model extracts the structure and Schicht 2 backfills the confirmation/total and takes the currency from the document's own symbol (correcting model misreads like ¥→$). Per-type prompts now also ask for address and price/currency.

* fix(extract): require the hotel address and ask for the rental company

After dropping the vendor templates, the model skipped the (often unlabeled) Expedia-style hotel address — making address a required schema field forces it to emit the street-address line, restoring the booking's location/place. Also hint the rental company so a car booking gets a real title instead of the generic fallback.

* fix(import): refresh costs immediately after an imported booking is saved

The saving client gets no budget:created echo (X-Socket-Id) and the create response omits the linked budget item, so the booking's Costs section and the Costs tab stayed stale until a manual reload. Reload the budget items right after a create that carried a budget entry.

* perf(extract): cap single-booking text tighter; require rental company

A long single-booking PDF (e.g. an 11-page rental voucher) spent ~200s on CPU prompt-eval at the 16k cap, though its data sits in the first ~2k. Cap non-flight docs at 6k (flights keep 16k for all legs). Also make the rental operator a required field so the car gets a real title.

* fix(import): preview the parsed cost as linked in the review modal

During the per-item import review the booking isn't saved yet, so the Costs section showed an empty 'Create expense' even though a linked cost will be created on save. Show the parsed price (amount + category) as the pending linked expense so the user can verify it up front. Reuses existing i18n keys.

* fix(import): persist source files in IndexedDB so attach survives a reload

The source document was only kept in memory on the background task, so a page reload during the (now always-LLM ~25s) parse lost it and the booking saved without its file. Store the uploaded files in IndexedDB keyed by job id; the review loads them from there when the in-memory copy is gone, and a 1h TTL prunes abandoned imports.

* chore(extract): recommend only Qwen3-8B (drop Qwen2.5 from the curated list)

Qwen3-8B is the identified default; the prior Qwen2.5 entries are no longer needed in the pull list.

* feat(settings): let users set their own AI parsing model

Adds an "AI parsing" section under Settings -> Integrations where a user can choose the LLM provider, model, base URL, API key and multimodal option used for booking extraction. This per-user config applies when an admin has not configured an instance-wide model. Reuses the existing encrypted user settings: the API key is stored encrypted, never prefilled, and a blank field keeps the stored one. Adds settings.aiParsing.* across all 20 locales.

* fix(settings): show the Integrations tab when only AI parsing is enabled

hasIntegrations gated the tab on memories/mcp/airtrail only, so a user with just the llm_parsing addon enabled saw no Integrations tab and could not reach the AI parsing config. Include llmEnabled in the gate.

* feat(settings): use the shared custom dropdown for the AI parsing provider

Swap the native select for CustomSelect so the provider picker matches the rest of the app's styling (dark mode, portal dropdown).

* refactor(planner): move the import-review bridge effect into the page hook

TripPlannerPage held a useEffect (the background-import → review bridge), which trips the page-pattern check (pages must stay wiring containers). Move the effect and its store/IndexedDB wiring into useTripPlanner where the rest of the import-review state already lives.

* test(llm-parse): cover the extraction router, client factory and import jobs

The new LLM extraction router shipped with little branch coverage, dropping src/nest below the 80% gate. Add unit tests for routeExtraction (flights/single/union/error paths, deterministic booking-wide fill), the native Ollama format client, the provider factory, the local-router service path with its type-aware text cap, the flat->schema.org mapper's remaining reservation types, and the background import-jobs runner. Also remove the now-unused validate.ts (only its FlatLike type was still referenced; moved to flat-schemas).

* test(setup): stub websocket addListener/removeListener in the global mock

BackgroundTasksWidget (mounted globally in App) subscribes via addListener/removeListener from api/websocket, but the global test mock didn't export them, so every test that renders <App/> threw on mount. Add the two stubs. (Surfaced now that the page-pattern check passes and the client test step actually runs.)

* fix(i18n): add Swedish translations for the AI booking-import settings

The Swedish (sv) locale landed on dev (#1325) after this branch added the
AI-parsing settings/reservation keys to the other locales, so sv was missing
them — strict i18n key parity failed after rebasing onto dev. Adds the 3
reservations.import.* and 17 settings.aiParsing/aiAlwaysRetry keys in sv.

* fix(extract): don't let the day-clamp fallback break reservation resync (#1288)

This branch added a clamp-to-nearest-day fallback to resolveDayIdFromTime so an
imported booking whose exact date has no day row still lands on a day. After
rebasing onto dev, that collided with #1288's resyncReservationDays, which
relies on the original "null when no exact day" semantics to leave a booking
whose date now falls outside the range untouched — instead it snapped to an edge
day (TRIP-SVC-019 failed: expected day_id kept, got the clamped one).

Make clampToNearest an opt-in parameter (default true, preserving the import
behaviour for create/update) and have resyncReservationDays pass false, so
out-of-range bookings keep their day_id. Full server suite green (4082).

* Added focus to search places in placeFormModal

* fix(airtrail): import departure/arrival times for manually-entered flights (#1336)

The mapper read only `departureScheduled`/`arrivalScheduled`, but those columns
are optional in AirTrail and stay null for manually-entered flights — where
`departure`/`arrival` are the only times set. So the import dropped the departure
clock (date-only) and the whole arrival (no date, no time), exactly as reported.

AirTrail's own rule is "use departure if available, otherwise fall back to
departureScheduled". Mirror that: prefer the scheduled instant, fall back to the
primary departure/arrival, in mapFlightToReservation, normalizeFlight, and the
sync hash. Hashing the resolved instant means flights already imported without a
scheduled time re-sync once and pick up their clock automatically; flights that
do have scheduled times are unaffected (no spurious re-sync).

Tests: 3 new mapper cases (fallback mapping, picker preview, hash tracking);
two existing cases that asserted the scheduled-only behaviour updated to the
"neither time set" case. Full server suite green (4085).

* fix(pwa): stop unregistering the service worker on offline boot (#1346)

Opening the installed PWA offline showed Chrome's "no internet" page instead of
the cached app. On boot the axios response interceptor reacts to a failed
request with no response by probing /api/health; the probe collapsed "genuinely
offline" and "edge-proxy auth wall" into a single reachable=false, so the
interceptor unregistered the service worker and reloaded — straight into a dead
network. navigator.onLine is true on mobile while offline, so the existing guard
didn't help. This also defeated the offline data layer (withOfflineFallback,
authStore's offline branch), which runs later in the chain.

Fix: connectivity.probe() now returns a discriminated state
('online' | 'offline' | 'proxy-wall'). A fetch that throws, or navigator.onLine
false, is 'offline'; a cross-origin redirect (CF Access, via redirect:'manual'
→ opaqueredirect) or an HTML auth wall (Pangolin) is 'proxy-wall'. The
interceptor only tears down the SW on 'proxy-wall'; on plain offline it lets the
request reject so the cached shell + IndexedDB serve the app. CF Access /
Pangolin reauth still works — the proxy always presents a reachable redirect or
HTML wall, which the probe now detects positively.

Regression dates to v3.0.16 (#964), surfaced by the 3.1.0 rewrite.

Tests: 6 new connectivity cases (offline/online/proxy-wall discrimination);
client tsc clean, full client suite green (2850).

* fix(map): keep the mobile GPS button above the day-detail panel (#1348)

On mobile the location (GPS) FAB sat at bottom: calc(var(--bottom-nav-h) + 12px),
which only clears the bottom nav. When a day is selected, DayDetailPanel slides
up over the map from bottom: navh+20 and spans nearly full width at z-index
10000, covering the button's band — so the button was hidden behind it.

DayDetailPanel now publishes its live measured height to a root CSS var
--day-panel-h (ResizeObserver, reset to 0 on unmount), and both map renderers
lift the button above the panel when it's open, reusing the hasDayDetail prop
they already receive:

  hasDayDetail
    ? calc(var(--bottom-nav-h) + 20px + var(--day-panel-h) + 12px)
    : calc(var(--bottom-nav-h) + 12px)

Applied to both the Leaflet (MapView) and GL (MapViewGL) renderers. When the
panel closes, hasDayDetail is false and the offset falls back to the bottom-nav
value. Desktop is unaffected — the button is mobile-only.

Tests: new DayDetailPanel case asserting --day-panel-h is published and reset on
unmount; client tsc clean, full client suite green (2851).

* feat(mobile): make the bottom-nav "+" context-aware per trip tab (#1349)

On mobile the bottom-nav "+" always created a new place (except on the Costs tab,
where it added an expense). It now matches the active trip tab: Bookings adds a
reservation, Transports adds a transport, Costs adds an expense, and everything
else (Plan, plus tabs that have no create modal — Lists / Files / Collab) keeps
adding a place.

Follows the existing ?create=<intent> pattern: BottomNav.useCreateAction emits the
per-tab intent, and useTripPlanner consumes create=reservation|transport to open
the booking / transport modals (both already mounted at page level). Place and
expense were already wired; this just extends the mapping.

Tests: 4 new BottomNav cases (plan/bookings/transports/costs → correct intent +
navigate target); client tsc clean, full client suite green (2855).

Implements mauriceboe/TREK#1349

* [+] Unsplash

* [+] i18n

* feat(trips): download chosen Unsplash covers into uploads (#1277)

Previously a selected Unsplash photo was stored as a remote
images.unsplash.com hot-link, so covers broke offline and on link
rot. The trip PUT handler now fetches the picked image through the
SSRF guard and saves it under uploads/covers, rewriting cover_image
to the local path (502 if the download fails). Also debounces the
cover search so a slow earlier request can no longer overwrite newer
results, drops a dead userId parameter, and reverts an unrelated
vite proxy change.

* test(trips): cover the Unsplash cover download and search-race guard (#1277)

Adds unit coverage for saveUnsplashCover (host check, content-type
and size limits, download failure), the searchUnsplashPhotos error
and success paths, and the PUT handler internalising a hot-link.
Updates the existing PUT tests for the now-async handler.

* fix(docker): keep server/reset-admin.js in the build context (#1339)

The Dockerfile copies server/reset-admin.js (the admin recovery
script), but .dockerignore also listed it, so it was stripped from
the build context and the image build failed with a not-found error.
Drop the ignore entry so the COPY resolves again.

* fix(llm): stop the browser autofilling the LLM base URL (#1301)

The AI-parsing base URL and model inputs had no autoComplete, so a
browser password manager could drop the saved login email into the
base URL field. In the admin addon config onBlur then fired a model
lookup against e.g. "admin@trek.local", which the server rejected
with 400. Mark the base URL and model inputs as type=url /
autoComplete=off in both the admin addon config and the per-user
connection section.

* feat(appearance): add per-user appearance config contract

Shared AppearanceConfig (color scheme, accent, transparency, per-tier type scale, density, reduce-motion and per-device dashboard widgets) stored as one JSON blob under the existing settings key. normalizeAppearance never throws, so a malformed/partial/future blob degrades to the neutral default and can never reach the DOM. No DB migration; the default reproduces today's look exactly.

* feat(appearance): token-driven theme engine with schemes and FOUC-safe boot

applyAppearance is the single writer of styling to the DOM (the .dark class plus data-scheme/-no-transparency/-density/-reduce-motion and the custom-accent/type-scale CSS vars). An external pre-paint /theme-boot.js replays a cached snapshot before first paint and complies with the production CSP (script-src 'self'), fixing the long-standing theme FOUC. Adds seven color schemes (incl. a true high-contrast that raises neutral contrast), a custom accent with auto-derived legible text, an extended token layer (accent variants, status/shadow/overlay/inverse), a scheme-gated legacy accent bridge, and a transparency-off layer. The default scheme sets no attributes, so existing users are unaffected.

* feat(settings): appearance settings tab

New Appearance tab with color mode (moved out of Display), color-scheme swatches, a custom accent picker with a live WCAG contrast hint, transparency and reduce-motion toggles, density, a global text-size slider with advanced per-tier controls, and per-device dashboard widget toggles. Edits preview live and commit on a short debounce. i18n keys added across all locales, translated for German.

* feat(dashboard): per-device widget visibility with layout reflow

Dashboard widgets (currency, timezones, upcoming reservations, atlas and the stat tiles) can be shown or hidden independently on desktop and mobile from the appearance settings. The stat grid spreads its visible tiles to full width, and disabling the right sidebar collapses the layout to a single centered column.

* chore(appearance): add theme:lint guard for hardcoded styles

A theme:lint script (modeled on i18n:parity) flags new inline color/fontSize literals and arbitrary-hex Tailwind classes that bypass the design tokens, so future code stays themeable. Map/PDF surfaces are exempt. The token taxonomy and the six theming rules are documented in src/theme/README.md.

* fix(appearance): scale inline px font sizes so text-size reaches all content

The global text-size control only set the root font-size, which scales rem-based text (navbar, menus) but not the dense inline px sizes used across the trip planner, budget, journey and panels — so place titles and addresses stayed fixed. applyAppearance now also exposes the factor as --fs-scale-text, and a codemod wraps inline numeric fontSize in calc(<px> * var(--fs-scale-text, 1)) across components and pages (map popups and PDF excluded). Sizes are byte-identical at 100%; the control now visibly resizes the actual content.

* fix(appearance): clearer widget settings, density hint, solid surfaces with transparency off

Dashboard widget settings are grouped by where they sit on the dashboard (below the hero / right sidebar / bottom of page); the right-sidebar master toggle now nests its individual widgets and greys them out when the sidebar is off, instead of a confusing flat list mixing the master with its children. Density gains an explanatory hint plus a real compact spacing effect. Transparency-off also solidifies the Atlas glass panels and tooltip, Leaflet zoom controls and GL popups — class-based surfaces via CSS, the Atlas inline panels via a noTransparency flag.

* fix(appearance): keep i18n key parity and update the scaled-emoji test

Add the new appearance settings keys (widget group titles, sidebar/density hints) to every locale so the strict key-parity check passes, and update the single-emoji chat test to expect the now-scalable calc() font size.

* feat(appearance): granular per-size text scaling with live preview

The text-size control now adjusts each size class (Large / Medium / Normal / Small) independently as well as all-at-once. Inline px sizes are mapped to a class by their value, so the per-class sliders reach real content; each class variable = global factor x its per-class factor (no double-scaling with the root font-size that handles rem text). The settings UI gains a live preview that resizes as you drag, and the four size sliders sit behind a clear toggle.

* feat(appearance): show per-size text controls inline with examples

The four size-class sliders (Large/Medium/Normal/Small) are now always visible instead of behind a disclosure, each with a live sample rendered at that size and an example of what it affects (e.g. Normal = place names/descriptions, Small = addresses/labels).

* fix(appearance): shorten the Auto color-mode label to 'Auto' on mobile

* fix(appearance): make the dashboard hero boarding-pass solid with transparency off

* feat(appearance): mark the Readability section as experimental

Transparency-off, density and per-size typography are best-effort while the token migration is ongoing, so the section carries an Experimental badge. Adds the i18n key across all locales.

* chore(about): remove the monthly supporters section

* refactor(settings): rename the Display tab to General and group its settings

The Display tab became a catch-all once theming moved to its own Appearance tab, and its 'Display' label no longer fit. It is now 'General' (Allgemein) and split into 'Language & region' and 'Travel & map' sections. Tab labels and the new section titles are added across all locales.

* refactor(admin): group the admin sidebar tabs into sections

The admin sidebar had 11 flat tabs. PageSidebar now supports optional group headings (backward-compatible; the Settings sidebar stays flat), and the admin tabs are grouped into Users, Configuration, Integrations and Maintenance. Group labels added across all locales.

* feat(help): embed the TREK wiki as an in-app help centre

Add a Help section (profile menu, /help) that renders the GitHub wiki inside
TREK. /api/help fetches the wiki markdown — the nav from _Sidebar.md, pages,
and proxied images — from GitHub and caches it (1h TTL, serves stale on
outage), so it auto-syncs on wiki edits with no redeploy and the client never
calls GitHub directly. The page is styled to match TREK with a section
sidebar, search and react-markdown; wiki [[links]] are rewritten to in-app
routes and HTML-comment placeholders are stripped. Page state lives in a
useHelp() hook per the page pattern. Adds nav.help and a help namespace
across all locales.

* feat(auth): explain the plain-HTTP secure-cookie gotcha on login

When the server issues a Secure session cookie but the request arrived over
plain HTTP (the common LAN install over http://ip:3000), the browser drops
the cookie and the next request dead-ends on a bare "Access token required" —
the top source of avoidable install issues. The login response now flags this
exact case and the login page shows a localized box explaining the fix (use
HTTPS, or set COOKIE_SECURE=false) with a link to the Troubleshooting guide.
It only triggers in the real failure case, never for correct HTTPS setups.

* feat(costs): Splitwise-like cost splitting

Add per-payer and per-member custom split amounts with Equally, Custom and
Ticket split modes on top of the existing equal split, keep legacy "paid by"
expenses working, and document the modes in the Budget Tracking wiki page.

* feat(i18n): add Vietnamese translations

* chore(i18n): sync Vietnamese with latest dev keys

Add the keys dev gained since this PR opened so the new vi locale keeps full
parity: the help namespace (wiki help center), settings appearance options,
costs split modes, dashboard Unsplash cover search, the insecure-cookie login
hint, nav.help and the admin group labels.

* feat(helm): Add existingClaim variable for custom PVC usage.

* fix(helm): emptyDir is used as a fallback when persistence is disabled.

* docs(helm): clean up existingClaim notes

Strip stray zero-width characters from the persistence docs, move the PVC
note out of the ENCRYPTION_KEY usage block into its own Persistence section
in NOTES.txt, and document that persistence.enabled=false falls back to an
ephemeral emptyDir.

* feat(feeds): subscribable ICS calendar feeds for trips

Adds TripIt-style live calendar subscriptions alongside the existing one-time
.ics download. A trip (or all of a user's trips) exposes a secret, revocable
feed URL that Google/Apple/Outlook poll to stay in sync.

- Public read endpoints GET /api/feed/trip/:token.ics and /api/feed/user/:token.ics
  (no auth — the secret token is the credential), reusing the existing exportICS()
  generator and adding REFRESH-INTERVAL / X-PUBLISHED-TTL hints.
- JWT-guarded token endpoints to generate (lazy, idempotent) and regenerate/revoke
  per-trip and per-user feed tokens; tokens stored in nullable feed_token columns.
- All-trips feed excludes archived trips and trips ended >90 days ago.
- UI: ICS toolbar button becomes a Download/Subscribe menu; modal offers one-click
  "Add to Google Calendar" (render?cid=webcal://) and a webcal:// link for
  Apple/Outlook, plus copy-link fallbacks. All-trips feed reachable from dashboard.
- Feed base URL read from the existing APP_URL env var.

Purely additive: new endpoints + two nullable columns, no breaking changes.

Tests: server/tests/e2e/feeds.e2e.test.ts covers lazy token generate + idempotency,
regenerate-invalidates-old, 401/404 auth+access, public feed content-type + hint
injection, unknown-token 404, and the archived/>90-day all-trips exclusion.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* harden calendar feeds: absolute URLs, real disable, folding, schema sync

- Resolve feed URLs against the request host when APP_URL is unset, so the
  webcal:// / Add-to-Google links work on a default install (not just behind a
  configured reverse proxy).
- Give the public link a real off switch: POST enables, PUT rotates, DELETE
  clears the token (feed_token = NULL). The subscribe dialog no longer mints a
  token just from being opened — the user opts in explicitly.
- Fold ICS content lines at 75 octets (UTF-8 safe) in exportICS, so download
  and feed both stay RFC 5545-compliant for long/non-ASCII summaries.
- Extract VEVENTs by structural line scan instead of a lazy END:VEVENT regex
  that user text could truncate.
- URL-encode the Google Calendar cid; mirror feed_token into schema.ts.
- Collapse the duplicated all-trips modal into the shared IcsSubscribeModal.

* feat(mcp): add bulk_update_places tool

Apply the same field values to many places in one call instead of one
update_place per place — e.g. re-categorising 80 POIs at once. Adds the
updatePlacesMany service (one transaction, trip-scoped, partial patch
built on updatePlace) and the bulk_update_places MCP tool with the usual
demo/access/place_edit guards and a place:updated broadcast per place.

* feat(dashboard): show the year on trip dates from other years

Trip dates only showed month + day, so trips from other years were ambiguous
(#1323). Dashboard cards and the boarding-pass hero now include the year, and
so does the shared formatDate (planner day headers etc.) — but only when it
isn't the current year, so this year's trips stay compact. Order and
punctuation follow the locale (EN "Sep 10, 2026", DE "10. Sep 2026").

* feat(places): bulk "change category" from the selection toolbar

Closes the UI half of #1168: in the Places selection mode, a new tag button
before delete opens a category picker that applies one category (or "No
category") to every selected place in a single request. Adds a REST
/places/bulk-update endpoint reusing updatePlacesMany, an offline-aware repo +
store action that patches both the place pool and the day-assignment
projections, undo grouped by each place's prior category, and the i18n keys
across all locales.

* feat(map): include the day's route in the map fit (#1128)

Selecting a day already fits the map to that day's destinations; this also
folds the route polyline into the bounds. BoundsController fits the
destinations immediately, then re-fits once — when the day's route finishes
computing asynchronously — to destinations + the full route, so a route that
bulges past its stops (a detour or ferry) stays in view. One-shot per day
selection, so later route-profile toggles don't re-zoom.

* feat(offline): detect update conflicts on the server for places and packing

Update handlers accept an optional X-Base-Updated-At token and reject a stale overwrite with 409, returning the current server row. An absent token keeps the existing last-write-wins behaviour, so older clients are unaffected. packing_items gains an updated_at column (migration + stamped on every insert) so it can take part in conflict detection too.

* feat(offline): force-offline mode, selective sync and a conflict queue

A force-offline override routes every read to the cache and every write to the queue; preparing for offline downloads trip data, documents and map tiles up front and waits for them to finish. Map tiles and individual trips can be left out of the cache. Queued edits carry the version they were based on so the queue can surface server conflicts for a keep-mine / keep-theirs decision; chained offline edits to one entity no longer conflict with each other, and evicting a trip preserves its unsynced writes.

* feat(offline): Settings -> Offline controls and a status banner

The Offline tab gains a force-offline switch, a prepare-for-offline download with progress, per-trip and map-tile storage toggles, and a conflict resolver with a default strategy. The floating status pill now reflects forced-offline and unresolved conflicts.

* i18n(offline): offline settings strings across all locales

* docs(wiki): document force-offline, selective storage and conflicts

* feat(video): media_type discriminator + local gallery video upload (server)

trek_photos gains a media_type column (migration) so the registry can hold video as well as images. A new POST :id/gallery/video endpoint accepts a video plus a client-captured poster (500 MB cap, video MIME/extension allowlist), stores the poster as the thumbnail, and the photo stream serves the poster for the thumbnail kind and the raw file (HTTP Range) for the original — without running the image thumbnailer on video bytes.

* feat(video): play local gallery videos in the journey gallery

Picking a video in the journey gallery now captures a poster frame + duration in the browser and uploads the raw clip; the grid shows the poster with a play badge and the lightbox plays it with a native video player (HTTP Range seeking). Images keep their existing HEIC-normalised path. No server-side transcoding.

Server media_type work was committed separately.

* feat(video): use Plyr for the gallery video player

Swaps the bare <video> element for a Plyr-wrapped player so playback controls match a consistent, cleaner skin. The instance is created per source and destroyed on unmount, so the lightbox stops playback when you navigate away.

* feat(video): link and stream Immich videos in the journey gallery

Immich timeline and album listings no longer filter out videos; each asset now carries its media type, which the provider picker forwards when linking. A linked video streams through Immich's transcoded /video/playback endpoint, and the asset proxy forwards the viewer's Range header (and passes 206/Content-Range back) so the player can seek. Synology video stays excluded until its stream API is verified.

Adds media_type/media_types to the provider-photos request contract.

* test(photos): assert the forwarded Range arg on the original stream

Follow-up to the Range-aware photo proxy.

* feat(video): upload and play videos in the trip file manager

The file manager (which already attaches files to a place/activity) now accepts video uploads up to the larger video cap — other types stay at the document limit — and the lightbox plays them with the Plyr player over the plain same-origin download URL, so cookie auth and HTTP Range both work. Videos are excluded from the offline blob prefetch so one clip can't evict a trip's documents.

* fix(video): harden upload handling and fix video playback edge cases

Security: the gallery-video poster is now always stored as .jpg instead of the client-supplied extension, so a poster declared image/* but named x.html / x.js can't be written with that extension and served inline same-origin; local gallery files are also served with X-Content-Type-Options: nosniff.

Robustness: rejected/unauthorised uploads no longer orphan their bytes on disk (the gallery-video and file-manager handlers unlink before throwing); the file-manager per-type size cap is keyed on the extension like the filter, so a real video labelled application/octet-stream isn't wrongly rejected. UX: the file-manager thumbnail strip shows a play placeholder for video instead of a broken image; shared (public) journeys now return media_type and play videos with a play badge; and a poster-less video shows a neutral tile instead of a broken thumbnail.

* test(video): update gallery accept selector + complete fileService mocks

The gallery upload input now accepts image/*,video/* — update the two JourneyDetailPage selectors that matched the old value. The files/journey e2e suites mock fileService and were missing the new MAX_VIDEO_SIZE / isVideoExtension / isVideoMime exports, which broke module load.

* test(video): cover the new upload-handler branches

Add controller tests for the gallery-video route (success / no-video / not-allowed / cleanup-on-reject), the per-asset media_types loops (gallery + entry, batch + single), and the file-manager per-type cap + unlink-on-rejection — restoring branch coverage on src/nest above the 80% gate.

* feat(bookings): add a dedicated URL field to reservations (#935)

Bookings get a first-class url column (migration) instead of users pasting links into notes. It's editable in the booking modal and rendered as a clickable link on the reservation card. The reservation request schemas are open passthroughs, so only the entity schema + service SQL enumerate it.

* feat(files): render uploaded Markdown files inline (#1345)

Markdown (.md/.markdown) is now an allowed upload type and opens in a rendered preview in the file manager instead of just downloading. Reuses the existing react-markdown stack with rehype-sanitize (these are untrusted uploads, so output is sanitized) and detects markdown by extension first since browsers send unreliable MIME for .md.

* feat(lists): reorder packing/to-do lists and private packing items (#969, #858)

Add drag-to-reorder to the packing and to-do lists, mirroring the budget
panel's native HTML5 drag pattern. A drag within a filtered/grouped view is
mapped back onto the global order so untouched items keep their place, and the
order persists optimistically via the existing reorder endpoints.

Packing items can now be marked private (#858): a private item is visible only
to its owner. createItem/bulkImport stamp the owner, listItems filters by the
viewer, and the WebSocket broadcasts are scoped to the owner so a private item
never reaches another member's screen — including the public/private toggle
transitions. Owners get a lock toggle and a private indicator on their items.

* feat(trips): transfer trip ownership to a member (#973)

Add POST /api/trips/:id/transfer so the owner can hand a trip to one of its
existing members. The swap runs in a transaction: the new owner takes
trips.user_id and the former owner is kept on as a regular member, so nobody
loses access. The endpoint is owner-only, writes a trip.transfer_ownership
audit entry and broadcasts the refreshed trip. The members modal gains a
"Make owner" action, shown only to the current owner.

* i18n: translate the booking link field across all locales (#935)

Fan out reservations.urlLabel / reservations.urlPlaceholder to the remaining
locales so the dedicated booking URL field is localised everywhere.

* fix(packing): drop the always-true guard in the row drag handler (#969)

The onDragOver guard `drag.isDragging || true` is a constant condition (eslint
no-constant-condition). The handler is already gated by canDrag, so run the
drag-over logic directly, matching the to-do row.

* feat(trips): guest members for accountless participants (#1362, #1291)

Add "guest" trip participants — people without a Trek account who can still be
assigned to costs, packing, to-dos and day-plan activities. A guest is a
credential-less users row (is_guest=1) joined into trip_members, so it is
assignable everywhere a real member is, with the cost-splitting, settlement,
packing and assignment paths working unchanged.

Guests are firewalled from everything account-related: they can never sign in
(password, OIDC and reset lookups skip them), never appear in the global user
directory, the member-add picker or admin user management, are never resolved as
notification recipients, can't be invited to another trip, and can't be made
owner. The trip owner manages guests from the share dialog in a dedicated,
clearly-labelled section (add / rename / remove), and guests carry a "Guest"
badge wherever members are picked. All 22 locales stay in parity.

* feat(packing): three-tier sharing — personal, shared-with-people, common pool (#858)

Rework the private-packing flag into a full sharing model. Every item is now
Common (the group pool — where all existing items live, so nothing breaks),
Personal (private to its owner) or Shared with specific people (it shows up on
those travelers' own lists, marked "by <bringer>"). is_private discriminates
restricted from common; a new packing_item_recipients table holds who a shared
item covers, and packing_item_contributors records "I can bring that too"
pledges on Common items.

The panel gains a Gemeinsam / Meine Liste view switch, each item a sharing
control (owner sets the tier + the people it covers), and Common items can be
co-brought or cloned onto your personal list. Visibility is enforced server-side
in listItems and the WebSocket broadcasts are scoped to exactly who can see an
item across every tier transition. All 22 locales stay in parity.

* style(packing): small gap between the list and the luggage sidebar divider

The luggage sidebar's left border sat flush against the right-hand category
card. Add a little left margin so the divider has minimal breathing room.

* feat(map): group GL place markers into clusters on zoom-out (#1385)

MapLibre/Mapbox showed every place as its own rich HTML marker with no
grouping when zoomed out, unlike the Leaflet map. Feed the place points
through a clustered GeoJSON source: clustered points render as a dark
count bubble (click to zoom in and expand) while the rich HTML photo
markers are only drawn for the points the source reports as unclustered.
Always on, matching the Leaflet MarkerClusterGroup.

* fix(map): match the GL place hover tooltip to the Leaflet map (#1385)

The MapLibre/Mapbox hover showed an anchored popup with a large photo
thumbnail, completely unlike the Leaflet map's slim, cursor-following
name/category/address card. Drop the anchored photo popup for places and
render the same cursor-following overlay the Leaflet map uses (no photo,
matching fonts/padding/shadow), so the two maps hover identically.

* feat(collections): backend for the Overall Places addon (#1081)

Adds the Collections addon backend: a server-wide-per-user library of saved
places, independent of any trip, with multiple named lists, an idea/want/visited
status, and Vacay-style fusion invitations to share a list with other users.

- Data: collection / collection_members / collection_places / collection_place_tags
  tables (+ migration and baseline schema). Saved places carry the owner plus a
  nullable saved_by so a member deleting their account can't drop shared content.
- Service: list + place CRUD with owner-or-accepted-member visibility, dedup,
  status, save-from-trip and copy-to-trip (reusing the trip copy column list),
  and the full fusion-invitation state machine mirrored from vacay (send / accept
  / decline / cancel / leave) with a websocket broadcast and an invite
  notification. Deleting a list snapshots its members and notifies them.
- NestJS module + addon guard (404 before auth), registered in the app module.
- Widens the place photo cache reference check to count collection places so the
  nightly sweep no longer evicts photos a saved place still uses.
- collection_invite notification wired across all 22 locales.

* feat(collections): /collections page, entry points and i18n (#1081)

Adds the client side of the Collections addon:
- A distinct /collections page (Atlas pattern, page/hook split) gated behind the
  addon: a multi-list rail, a Grid (default) / List / Map view switch, the
  idea/want/visited status with a one-tap badge, search and status filters, and
  considered empty states. Store + hook + model + websocket wiring; the place
  detail reuses the trip place inspector via a mode guard.
- Entry points: a "Save to Collection" button next to Open-in-Google-Maps in the
  place inspector (and the two sidebar context menus), a "Copy to trip" modal,
  and a desktop-only two-column add-place picker (mobile keeps the single-column
  form).
- The collection namespace and the new keys across all 22 locales.

* feat(collections): fusion sharing UI + dashboard widget + per-user toggle (#1081)

- ShareCollectionModal: the owner manages a list's members and invites users
  (available-users picker → invite, cancel pending); a member can leave a shared
  list. The incoming accept/decline surface stays in the lists rail. A Share
  button is added to the collections header for owners (and members, to reach
  Leave).
- CollectionsWidget: a dashboard glass card after the currency widget showing the
  saved count and the most recent saved places, double-gated by the admin addon
  and a new per-user appearance flag.
- Appearance: a 'collections' dashboard-widget flag (desktop + mobile defaults)
  wired into the appearance settings, surviving normalize.
- Sharing + settings strings across all 22 locales (parity strict passes).

* feat(collections): redesign the page on the dashboard glass language (#1081)

Rebuilds the /collections page from the functional placeholder into the
dashboard's glass visual language (light + dark):

- A colour-washed hero per list: eyebrow + member avatars, big title, and
  stat chips (All / Idea / Want / Visited) that double as the status filter.
- A sticky glass list rail (owned + shared + invites) with a mobile drawer.
- Gradient/photo cover place cards modelled on the trip cards, via a new
  rectangular PlaceCover (photoService-backed, gradient fallback) + a shared
  gradients util. List and map views restyled to match.
- Status pill rendered as a role=button span so it survives the .trek-dash
  button reset and can nest inside the card; the share member-count badge is
  now owner-only.
- New hero eyebrow strings across all locales.

* feat(collections): list+map split, taller rail, list-menu popover fix (#1081)

- List view splits into a scrollable list + a sticky map on wide screens;
  clicking a place pans/highlights it on the map (single selectedPlaceId, no
  inspector over the map). Narrow screens keep the single-column list.
- Keep the list rail at least as tall as the hero (measure the hero via a
  small useElementSize hook and feed its height as the rail's min-height).
- List row kebab menu: portal the menu/colour popover to the body so the
  rail's overflow + backdrop-filter can't clip it ("renders only in the
  module"), and fade the place count on hover so the kebab stops overlapping it.

* feat(collections): list+map default, map-only toggle, deselect + tooltip fixes (#1081)

- Drop the grid/tile view. The list view is now the default and, on wide
  screens, a list + persistent map split; a top-left control on the map
  collapses the list to a full-width map (and back), animating smoothly (the
  map stays mounted and is nudged to re-layout during the transition). The
  place search moves onto the map (top-right); mobile keeps a list/map toggle.
- Let a place be deselected again: clicking it once more, clicking the map
  background, or picking another all toggle the selection (collections map now
  wires onMapClick).
- Fix the stuck hover tooltip: selecting a place swaps its marker's DOM node so
  the browser never fires mouseout/mouseleave, orphaning the fixed-position
  tooltip (it hung on screen and drifted with scroll). Both map stacks now clear
  the hover on selection change and on scroll.
- Remove CollectionGrid + PlaceCover; add hero eyebrow + map control strings.

* feat(collections): list details, place detail sheet, add-place, fusion kick (#1081)

Dashboard widget (B): the collections tool now shows the user's LISTS as
compact colour-washed badges (cover image tinted with the list colour, or a
gradient) that jump to the list — one list() call, no N+1.

List details (C): lists gain a description, a custom cover image (uploaded to
/uploads/covers, tinted with the list colour in the hero) and links. A shared
ListEditorModal handles both create and edit; the hero shows the description +
link chips. New `links` JSON column on collections + collection_places
(migration 151) with parse/serialize in the service; a POST :id/cover upload
endpoint mirroring trips; cover-file cleanup path-confined locally.

Place detail (D): clicking a place opens a bottom sheet (no backdrop, so the
map stays visible) — status cycle, copy-to-trip, remove, and an edit mode with
a markdown description + links editor (collectionsApi.updatePlace, now wired
via a store action). A "+" next to the search adds a place to the list via the
maps search.

Fusion + fixes (E): the owner can now remove an accepted member (kick) — new
removeMember service/route/store + a button in ShareCollectionModal, with a
collections:removed WS bounce. findMembership no longer matches on name alone
(coordinate proximity required, killing "Starbucks everywhere" false positives).
loadCollection swallows a 403/404 after a leave/remove so the URL sync can't
throw uncaught. Grid remnants gone; the map select toggle moved onto the map.

New strings across all 22 locales; i18n parity strict passes.

* fix(collections): review follow-ups on the B–E work (#1081)

- Block the list-cover upload in demo mode (mirror the trips cover endpoint).
- Restrict list/place links to http(s) (schema) and normalise scheme-less URLs
  to https:// on save, so a bare "booking.com" no longer resolves as a relative
  SPA route (and javascript:/data: hrefs are rejected).
- Place detail: surface save errors with a toast instead of silently swallowing
  a 400 and leaving the sheet stuck in edit mode.
- List editor: don't create a duplicate list when a retry follows a cover-upload
  failure (reuse the created id); revoke the cover preview object URL.
- Map controls: one top bar (left toggle/select, right add/search) so they can't
  overlap on a narrow split map — the search shrinks instead.
- Dashboard list badge: full-opacity colour wash so the name stays legible over
  bright covers.

* fix(collections): detail-sheet, edit-refresh, map + rail polish (#1081)

- Editing a place (status, description, title, …) no longer reloads the view or
  closes the detail: the WS echo now refreshes via loadCollection, which keeps
  the current selection + select-mode instead of setActive resetting them.
- Place detail: docks over the list column on the desktop split (measured rect)
  instead of centred over the map, and the card is now opaque (was too see-through).
- Map: click a marker in full-map view to drop back to the split; picking a place
  scrolls its list row into view; the select toggle is disabled in full-map view;
  the floating controls are one non-overlapping top bar and less transparent.
- Hero: drop the New-list button (it's already in the rail).
- Rail: the kebab is always visible (easy to hit); menu is Edit + Delete only
  (colour moved into the editor); "Rename" → "Edit".
- Add-place: pick a result, then set description (markdown) / links / status
  before saving, all in one step.
- Share modal: member roster as cards with clearer role badges + a count.

* feat(collections): detail redesign + categories, close-on-map, highlight fix (#1081)

- Rebuild the place detail as a clean, opaque, sectioned sheet (cover → meta →
  status segment → description → links) with a proper footer action bar — the
  loose "white lower half" is gone.
- Assign a place to a central (admin-defined) category, both in the detail edit
  and when adding a place; categories are fetched once for the page.
- Add-place now sets category + description (markdown) + links + status in the
  same step, closer to the trip's place form.
- Switching to the full-map view now closes the (list-docked) detail.
- Fix the selected-row highlight: it was clipped by the column's overflow — use
  an inset ring and only clip during the map-collapse animation; a picked row
  now scrolls into view above the detail sheet.
- New category strings across all 22 locales.

* feat(collections): filters, add-place popup, category badges, map-click hardening (#1081)

- Map: markers no longer rebuild on every unrelated re-render (memoised the
  mappable list + only update the hero size when it really changes), the floating
  controls bar is click-through except its buttons, and the collection map runs
  with the hover tooltip off. Together these stop a marker click from landing on
  a mid-rebuild element / the tooltip so the pick actually registers.
- Filters moved out of the hero into a compact status + category dropdown row
  above the places (custom dropdowns); the hero no longer carries the stat chips.
- Add-place is a single popup now: search fills the location, and name / status /
  category / description / links are all editable together before saving.
- Category shown as a badge top-left on the detail cover and next to the status
  in each list row (divided by a hairline).
- Slimmer hero: shorter, tighter spacing, links tucked into the eyebrow row
  instead of their own line.

* feat(collections): hero edit/share row, place photos, edit-echo fix, wider page (#1081)

- Editing a place (category, status, …) no longer reloads the view: the mutating
  client's own socket is now excluded from the WS broadcast (x-socket-id threaded
  through save/update/status/delete + list update/cover), so the optimistic update
  stands on its own instead of being chased by an echoed refetch.
- Detail sheet pulls a higher-res cover photo from the maps provider when the
  place has no image of its own (the avatar thumbnail was too low-res).
- Hero: Share moved onto the title row (no more empty top band) with an Edit
  button beside it; editing/deleting a list now happens there. The list rail drops
  its per-row kebab entirely (and with it the janky open animation).
- The list editor can delete the collection from its footer (owner only).
- Wider, screen-relative page (max-width min(2100px, 95vw)).
- List rows: the place avatar no longer shrinks when the address is long.

* fix(collections): copy-to-trip labels + Unsplash cover search (#1081)

- Copy-to-trip modal showed blank rows: trips are keyed by `title`, not `name`,
  so nothing rendered. Read `title` and add the trip's date range under it.
- List editor gains an Unsplash cover search (same source as trip creation) next
  to the upload button; picking a photo sets it as the list cover.
- Add-place result rows: pin keeps a hard min width so a long address can't
  squeeze it.

* fix(collections): stop the address pin from shrinking on long addresses (#1081)

The little map pin in front of a place's address sits in a flex row with the
address text but had no flex-shrink guard, so a long address squeezed the icon
smaller. Pin the SVG to its size.

* fix(collections): white screen when editing a place (undefined in places) (#1081)

updatePlace wrote `res.place` into the places list, but the endpoint returns the
updated place directly (not wrapped in { place }, unlike savePlace) — so an
`undefined` slipped into the list and the category-filter's presentCategories()
crashed on `undefined.category_id`, blanking the whole page. The WS echo used to
mask it by refetching; excluding the editor's own socket exposed it.

- Read the updated place directly and guard against a falsy response.
- Fix the api return types to match (updatePlace/setStatus return the place).
- Harden filterPlaces / statusCounts / presentCategories / mappablePlaces against
  a stray undefined entry so a single bad row can never white-screen the page.

* feat(collections): select toolbar — select-all, move/duplicate to another list (#1081)

- The select toggle now sits at the right of the filter row (same height as the
  status/category dropdowns) instead of the top toolbar.
- Select mode gains a "select all / deselect all" toggle and shows even with
  nothing selected yet.
- Selected places can be moved or duplicated into another of your lists via a
  target-list picker (move re-points collection_id; duplicate re-saves the place
  data, carrying description / category / notes / etc.).
- New strings across all 22 locales.

* style(dashboard): accent follows the user's theme instead of a fixed orange (#1081)

The .trek-dash scope (dashboard, collections, vacay, atlas) hardcoded an orange
accent, ignoring the appearance theme. Drop the override so --accent inherits the
theme tokens (index.css): monochrome black/white by default, coloured per
data-scheme / custom accent. --accent-ink/-soft now map onto --accent-on/-subtle,
and accent-filled elements use --accent-text for legible text on any scheme.
Category colours are set explicitly per element and stay untouched.

* fix(collections): saved-places picker height + list filter, all-saved first-load (#1081)

- Trip "Saved places" picker: drop the fixed 360px cap so the list fills the
  panel instead of stopping half-way, and add list + status filter dropdowns
  (filter by which collection the place is saved in).
- "All saved" showed nothing on first open: setActive(ALL_SAVED) unioned the
  lists from the store, but on first load those aren't fetched yet (loadAll still
  running). Load them first when empty so the union isn't blank.

* test(collections): unit-test the nest controller (branch coverage) (#1081)

The collections nest module had no controller test, dragging src/nest/** branch
coverage below the 80% gate. Cover the controller's branches: reorder/deleteMany
payload validation, owner-gated invite/cancel/remove/available-users, invite +
accept error surfacing, the cover demo-mode + no-file guards, and the x-socket-id
forwarding on the mutating endpoints.

* fix(collections): mobile polish — touch targets, safe-areas, overflow (#1081)

From a mobile UX audit of the collections page:
- Detail sheet: the read-mode footer no longer clips "Remove from list" (it wraps,
  drops the growing spacer) and clears the home indicator (safe-area padding,
  84dvh instead of 84vh).
- Bigger touch targets on phones (≥40px): view toggle, filter dropdowns, select-bar
  buttons, detail close/actions, drawer rail rows, and the interactive status badge
  (enlarged tap area via a pseudo-element, look unchanged).
- Select action bar breaks its bulk actions onto their own line instead of
  stranding them behind a growing spacer.
- Lists drawer honours device safe-areas and gets an explicit close button.
- Page honours the top safe-area and goes full-width on phones (drop the 95vw cap);
  filter popovers cap their width so long category names don't overflow.
- Add-place: Cancel/Add pinned in the modal footer (reachable without scrolling),
  status pills wrap.
- Drop dead hero mobile CSS left over from the hero refactor.

* feat(collections): per-member permission roles on shared lists (#1081)

The owner now assigns each member a role — viewer (read + copy-to-trip only),
editor (default: add + edit places) or admin (full incl. delete). The owner is
always full. Existing members default to editor via migration 152, so nothing
regresses.

- Server: role column on collection_members (migration 152 + schema); roleOf +
  assertCanEdit (save/update/status/list-meta) + assertCanDelete (delete) layered
  on assertAccess; sendInvite takes a role; new setMemberRole (owner-only) +
  POST members/role; members payload carries each role.
- Client: Share modal gains a role picker on invite and a per-member role select
  for the owner (read-only role badge for others); the page hides add / edit /
  status / move / delete for roles that can't perform them (server still enforces).
- Roles in all 22 locales; service + controller tests for the new gating.

* feat(collections): bulk-add selected trip places to a list (#1081)

Add a "Save to collection" action to the trip place list's selection bar (next to
bulk category + delete): it opens a list picker and copies every selected place
into the chosen list in one request, instead of one-by-one from each place.

- Server: saveFromTripPlaces (one access check + one WS notify), POST
  places/from-trip-many; dedups by name/coords, skips missing ids, honours force.
- Client: saveFromTripMany api + SaveTripPlacesToListModal; the selection-bar
  button is gated on the collections addon being enabled.
- Copy count / skipped-duplicates toast; strings in all 22 locales.
- Service + controller tests for the bulk path.

* style(collections): custom dropdown for the permission role pickers (#1081)

Swap the two native <select> role pickers in the share modal (invite + per-member)
for the app's CustomSelect (portal dropdown, size sm) so they match the rest of
the UI instead of the browser's native control.

* style(collections): widen the share modal (#1081)

* test(collections): client component tests + select in All saved, off the map (#1081)

- Add client tests for the new collections UI (80 tests): collectionsModel (incl.
  the undefined-entry guards that fix the white-screen regression), StatusBadge,
  CollectionFilterBar, CollectionList, CollectionPlaceDetail (permission gating),
  MoveToListModal.
- Offer the select toggle in "All saved" too (server enforces per-place rights).
- Drop the now-duplicate select button from the map controls (it lives in the
  filter row).

* docs(wiki): add Collections addon page (#1081)

New wiki/Collections.md in the style of the other addon pages (lists, status,
categories, adding/bulk-adding places, place detail, filters + bulk actions,
fusion sharing with member roles, dashboard widget). Add it to the Addons
overview table + the sidebar navigation.

* feat(date-picker): add month/year drill-down navigation and keyboard input trigger

- Add three-level calendar view (days → months → years) via clickable
  header label, allowing fast navigation to distant dates without
  repeated arrow clicks
- Replace double-click text input affordance with a visible keyboard
  icon button; compact/borderless variants show the icon in the
  calendar footer
- Pre-fill text input with locale-aware numeric date (DD.MM.YYYY)
  when a value is already selected
- Add aria-label and aria-pressed to all interactive calendar elements
  for screen reader support
- Update existing tests to reflect new two-button trigger layout
- Add FE-COMP-DATEPICKER-018 through 027 covering drill-down
  view transitions, prev/next behaviour per view, aria-pressed
  state, and keyboard icon trigger

* fix(date-picker): locale-aware keyboard input parsing and i18n control labels

- Replace fixed-order date parser with locale-aware implementation
  using Intl.DateTimeFormat.formatToParts to detect field order;
  adds swap fallback for unambiguous inputs (day > 12) to handle
  locale mismatches gracefully
- Pre-fill keyboard input with locale-formatted numeric date
  (e.g. 14.06.2026) instead of raw ISO value
- Replace all hardcoded English aria-labels and titles with t()
  calls; add new keys under common.datepicker.* namespace across
  all locale files
- Update FE-COMP-DATEPICKER-013 to use unambiguous day value (> 12)
  to avoid locale-dependent test failures

* fix(date-picker): add missing locale file and fix let-to-const lint error

- Add missing common.datepicker.* keys to overlooked locale file
- Change reassigned `let` to `const` where value is not mutated
  to satisfy lint rules

* chore(i18n): backfill datepicker keys for sv + vi locales added on dev

* fix: back-merge v3.1.4 hotfixes into dev (#1371)

Port the three main-only fixes onto dev's (post-rewrite) architecture:
- fix(backups): prevent recursion when the backup path sits inside the backed-up dir
- fix(share): convert budget items to the viewer's base currency instead of a flat EUR
- fix(files): surface the descriptive server error for unsupported upload types (#1363)

Cherry-picked from 819aa793 on main; the SharedTripPage and useTripPlanner
conflicts were resolved to keep dev's font-scaling and full import set while
taking the fixes' currency conversion and translateApiError wiring.

* fix: resolve a batch of reported bugs (planner, budget, atlas, bookings, mobile)

- #1394 planner: two transports on one day no longer draw a phantom airport→airport
  road route between them (a run is only a drive when it holds a real place); mirrored
  in the map hook and the sidebar's leg list, with a regression test.
- #1392 planner: the per-day Route button now points the selection at the tapped day
  before toggling, so on mobile it computes that day's route instead of the previously
  selected one, and only the selected day's button reads as active.
- #1372 planner: the "open in Google Maps" route now includes the day's hotel bookends,
  matching the drawn map route.
- #1375 planner: a multi-day accommodation no longer thrashes the plan scroll — the
  auto-scroll lock keys on the selection identity, not the per-day row.
- #1377 planner: the reset-orientation compass is now shown on small screens too.
- #1382 budget: settlement nets in the trip's canonical currency and converts to the
  display currency once, so balances no longer drift with live FX and no phantom
  third-party micro-flows appear (identity, hence unchanged, when they're the same).
- #1366 atlas: countries reached only by a transport booking (no lodging/place) now
  count as visited, on both the dashboard and the Atlas page.
- #1383 bookings: a hotel linked to an accommodation shows only its day-range, not a
  duplicate stamped date row, and the range stays correct after an edit.
- #1353 bookings: any non-hotel reservation can now link an existing trip place/activity.
- #1390 i18n: fix the Polish word for "buddies" (Towarzysze → Współpodróżnicy).
- #1265 planner: drag-and-drop of places now works on touch devices via a polyfill.

* feat(planner): add an "Open in OpenStreetMap" button to the place inspector

Next to the existing "Open in Google Maps" action, add an OpenStreetMap button that
opens the place on openstreetmap.org (a marker at its coordinates, or a name search
when it has none) — the same map source TREK already renders, and a jumping-off point
for OSM-based apps like OrganicMaps / CoMaps. Requested in discussion #880.

Strings across all 22 locales; a unit test for the URL builder.

* feat(planner): shorten the map-open button labels to "Google Maps" / "OpenStreetMap"

* feat(planner): show a day's route distances inline on mobile

Seeing the driving/walking distances between a day's places on mobile
meant tapping the day (which closes the plan sheet), reopening it, then
tapping Route. Now the per-day Route button in the mobile footer toggles
that day's leg distances in place, so the sheet stays open and you get the
distances between places without selecting the day first.

The leg computation runs for every route-toggled day instead of only the
selected one, and the leg/hotel-bookend maps are nested per day so several
toggled days can't overwrite each other's segments. Desktop is unchanged.

Discussion #1374

* feat(oidc): use the picture claim as avatar when none is uploaded

When a user signs in via OIDC and hasn't uploaded a custom avatar, their
`picture` claim is now used as their avatar. The users.avatar column holds
either an uploaded file name or an absolute https URL from the claim, and a
single resolver on each side (server avatarUrl, client avatarSrc) renders
both. An uploaded avatar always wins and is never overwritten; the picture
refreshes on each login otherwise. Only https URLs are stored, matching the
image CSP.

All the scattered /uploads/avatars/ builders now go through the resolvers,
which also fixes collection member avatars that were rendering a bare file
name.

Discussion #1399

* feat(trips): trip invite links + optional trip binding on admin invites

Trip invite links (#1143): each trip can have one rotating invite link in its
Share panel. An existing, logged-in user who opens /join/<token> is added to
the trip as a member; an anonymous visitor is sent to the login page and
returned to the invite afterwards — there is no registration from this link.
Reading, rotating or disabling the link all require the share_manage permission.

Admin invite trip binding (#1402): the admin create-invite dialog can now bind
a registration invite to a trip. Someone who registers via that link is
auto-added to the trip as a member (password and OIDC paths), inside the same
atomic step that consumes the invite.

Adds a trip_invite_tokens table and a nullable invite_tokens.trip_id, a shared
owner-safe/idempotent add-by-id helper, the manage + join endpoints, the
JoinTripPage and Share-panel section, the admin trip picker, and the new i18n
keys across every locale. Wiki updated.

Discussion #1143

* fix(join): extract JoinTripPage state into a useJoinTrip hook

The page container held useState/useEffect directly, tripping the CI
page-pattern check. Move the token preview + accept logic into a co-located
useJoinTrip() hook; the page is now a thin presentational shell.

* feat(costs): filter expenses by category and by a single day

Adds two filter dropdowns next to the Search Expenses field (height-matched
to it): one filters by expense category, the other narrows to a single day.
Selecting a day shows a prominent summary banner with that day's total, and
hides the now-redundant per-day header. Both filters work on the desktop and
mobile layouts and compose with the existing search + all/mine/owed filters.

New i18n keys (costs.filter.allCategories / allDays, costs.expensesCount)
across every locale.

* fix(admin): use TREK's CustomSelect for the invite trip picker

The "add to trip" dropdown in the admin create-invite dialog was a native
<select>; swap it for the shared CustomSelect so it matches the rest of the UI
(searchable once there are many trips).

* feat(planner): public transit routing via Transitous (#1065)

Each day header gets a transit button (replacing the rename pencil, which
moved next to the day name in the day detail panel). It opens a route search
backed by Transitous/MOTIS — free, open data, no paid provider: from/to stop
search with the day's own places as quick picks, depart/arrive time, mode
filters (train, subway, tram, bus, ferry, cable car) and ranking by best
route, fewer transfers or less walking. Results show local times, duration,
transfers, walking time and line badges in their official colors, with a
stop-by-stop breakdown per connection.

Adding a connection saves it as a regular transport reservation — typed by
its dominant leg, timed from the itinerary's wall-clock departure/arrival
converted to station-local time (tz-lookup), with the origin, transfer stops
and destination as endpoints and the compact legs in metadata.transit. It
slots into the day timeline by time and inherits editing, deletion and
drag-reordering from the existing transport machinery; the transport detail
view renders the full itinerary. Re-saving a transit transport through the
edit modal preserves the stored itinerary while the route is unchanged.

The server proxies the Transitous API (JWT-guarded, rate-limited, identifying
User-Agent, short response cache, strict mode whitelist); TRANSIT_API_URL
lets self-hosters use their own MOTIS instance. New i18n keys in every
locale, wiki page updated.

Discussion #1065

* fix(build): declare tz-lookup as a client dependency

It was present in the lockfile but undeclared, so the local install had it
while the Docker client build (npm ci --workspace=client) did not.

* test(maps): add buildUserAgent to the mapsService mock

transitService imports it at module load, and the full-app integration boot
now pulls the transit module in — the factory mock lacked the export.

* feat(planner): make transit journeys first-class entries (#1065)

A saved transit route is now its own reservation type instead of piggybacking
on train/bus: it gets a tram icon and its own color everywhere, and the day
timeline renders the itinerary inline — line badges in their official colors
with walk segments, plus the transfer count and walking time — instead of a
generic transport row.

Clicking the row opens the itinerary view (journey summary, stop-by-stop legs
with times, platforms, headsigns and operators) rather than the edit form;
editing stays reachable from an Edit action inside that view. The transit
type is registered across the timeline merge, transport modal, reservations
panel, file manager, map overlays and detail panels, with a translated type
label in every locale.

* feat(planner): integrate transit into the transport system as Automated mode

The add-transport dialog gains a Manual/Automated switch: Automated embeds the
public-transit search (day picker + from/to + modes + preferences + results)
right in the dialog, and the day header's tram button opens it directly in
that mode. The standalone search modal is gone.

Saved journeys get their own roomy journey view — the stop-by-stop itinerary
(times, platforms, lines, headsigns, operators) together with the editable
booking fields, delete, and a "Change route" action that re-runs the search
pre-seeded with the journey's origin/destination and replaces the itinerary on
save. The generic transport form no longer opens for transit entries, from the
timeline or from the Transports tab, where journeys now sit in their own
"Automated public transit" section with their line badges on the card.

New i18n keys in every locale; wiki updated.

* feat(planner): polish the transit journey UI and fix its tab placement

Transit entries were classified as bookings by the planner's transport-type
list and landed in the Bookings tab — they now sit in the Transports tab's
own section, rendered as proper journey cards (tram icon, arrow title, leg
chips, journey stats) instead of the generic booking card.

The journey modal got a redesign: the title renames inline in the header
with an icon arrow, the stats become three full-width tiles (duration /
transfers / walking, each with an icon), status and booking-code fields are
gone, and notes take the full width with a markdown write/preview toggle.
The Automated search mode gains a proper header (icon, hint, day picker)
and the day-plan row now shows walks with their minutes inside the chip
sequence (🚶 3 › U2 › 🚶 3) instead of a detached direct/walk summary.
"A → B" titles render with an arrow icon everywhere. The Transports tab's
add button is simply "Transport" now that the dialog covers both modes.

* test(nav): the bottom-nav add button is labelled Transport now

* feat(planner): markdown toolbar for journey notes + calmer transit search form

The journey notes gain a proper markdown toolbar (bold, italic, strike,
heading, list, checklist, link, code) that wraps the selection or prefixes
the current lines. The transit search options settle into one calm card:
depart/arrive + time + date and the ranking preference share the top row,
the mode filters and the search button share the bottom row, with the mode
chips restyled from heavy filled pills to quiet toggles. The day-plan row
drops the transfer count — the leg chips already tell the story.

* feat(planner): badge meta rows + inline itinerary expansion for transit

Dot-joined meta text becomes quiet badge chips everywhere transit facts are
listed: the journey modal's per-leg line (time, duration, stops, headsign
with an arrow icon, operator de-emphasised), the search results' leg details,
and the Transports-tab journey card (day, date, time span, duration — the
transfer count is gone from the card).

The day-plan transit row swaps the map-connections toggle for an expander:
the chevron folds the stop-by-stop itinerary out right inside the timeline —
times, line badges, stations with platform and stop counts — sized for the
sidebar.

* feat(planner): walk legs as centred dividers + journey-card note line

Walk segments in the journey modal and the day-plan inline itinerary
collapse from two lines into a single centred divider — dashed rules left
and right, the walk in the middle (foot icon, destination, minutes). Leg
meta badges sit tighter under their titles. The Transports-tab journey card
shows a dimmed first-line note preview, and the journey modal now reads the
reservation from the live store, so an update is visible the moment the
entry reopens.

* feat(map): draw transit journeys along their real rail and bus alignments

MOTIS leg geometry (encoded polylines) now travels through the proxy and is
stored per leg, so both map renderers draw the journey along the actual
tracks instead of a straight line: colored cores in each line's GTFS color
over a white casing, walks as dotted grey connectors. Transit journeys are
always visible on the map — they are part of the plan itself, not an opt-in
overlay — and the day route already anchors to their stations, so the
journey slots into the route computation end to end. Entries saved before
this keep the straight-line fallback.

Also: stronger dashes on the walk dividers, notes open rendered (preview
tab) when present, and MOTIS's START/END placeholders are replaced with the
places the user actually picked.

* fix(planner): elegant walk-divider hairlines + proven notes preview

The walk dividers switch from dashed borders to 1px hairlines that fade
towards the outer edges — strongest next to the walk text. A regression
test pins the journey modal opening existing notes on the rendered
markdown preview rather than the raw text.

* fix(map): transit polish — earlier label collapse, route-toggle coupling, md note preview

Station badges on transit journeys collapse to icon dots much earlier when
zooming out (label threshold 900px instead of 400). The drawn transit paths
now ride the day-route toggle: turning the route off hides them too, since
they are part of the computed route. The journey card's note preview renders
its first line as inline markdown instead of raw asterisks.

* fix(settings): booking route labels default to off

The map endpoint labels only render when the user explicitly enables them;
an unset preference now means hidden, matching the calmer default the
transit paths brought to the map.

* style(settings): TREK-styled text-size sliders

The appearance tab's native range inputs become proper TREK sliders: a thin
pill track filled up to the current value in the accent color, with a soft
round thumb that scales slightly on hover/drag.

* fix(planner): mobile layouts for the transit popups

The journey modal and the transit search now lay out properly on phones:
from/to stack vertically with the swap rotated between them, the ranking
segment and search button go full width, the day picker in the automated
header spans the row, the three stat tiles compress to centred mini tiles,
the itinerary tightens its gutters, and the footer wraps with an icon-only
delete. Desktop is unchanged.

* fix(planner): tighter mobile transit search + vertical journey itinerary

* fix(planner): wrap-safe mobile itinerary text — platform below the stop, minutes-first walks

* feat(plugins): plugin system scaffold — registry tables + admin panel

First slice of the plugin system. Lays down the data model and a read-only
admin surface; nothing executes yet.

- Migration 155: plugins, plugin_meta_migrations, plugin_error_log and
  plugin_settings_fields tables. Plugin data will live in a per-plugin sqlite
  file under /plugins-data, never in these tables.
- New Nest module server/src/nest/plugins with GET /api/admin/plugins
  (admin-gated, returns the installed list + the runtime-enabled flag).
- TREK_PLUGINS_ENABLED kill switch (config.pluginsEnabled), off by default.
- Admin → Plugins tab with a read-only panel: installed list, status badges,
  and a clear banner when the runtime is disabled by server config.
- i18n keys for the tab and panel across all locales.

Install, activation, the isolated runtime and the registry browser follow in
later slices.

* feat(plugins): isolated per-plugin runtime + capability RPC (M1)

Every plugin now runs in its own forked child process with a scrubbed env
(no JWT_SECRET, no db path, nothing inherited). It talks to TREK only over a
JSON-RPC channel, and the host's capability router registers ONLY the methods a
plugin's granted permissions unlock — so an ungranted call is unreachable, not
merely refused. The plugin's own data lives in a separate sqlite file it can
never open directly; core reads (trips/users) go through membership-checked,
column-projected host methods; ws broadcasts are force-namespaced.

- protocol/envelope: the wire types + method→permission map (pure, shared by
  host and the isolated child)
- host/rpc-host: the capability router = the enforcement point (dispatch,
  BAD_PARAMS / PERMISSION_DENIED / RESOURCE_FORBIDDEN / UNKNOWN_METHOD)
- host/plugin-data: the per-plugin sqlite file (db:own), guarded against
  ATTACH/PRAGMA escape, idempotent migrations
- host/create-rpc-host: wires the router to the real db/websocket (host-only)
- runtime/plugin-sdk + plugin-host-entry: the child bootstrap + definePlugin
  ctx; turns each ctx call into an RPC, never imports a privileged module
- supervisor: spawn on activate, heartbeat/reap, crash backoff + auto-disable,
  graceful shutdown — a plugin crash/OOM/hang can never reach the Nest loop
- paths: code/data layout, dist-vs-tsx child entry resolution

Nothing is wired into activation yet (that's the next slice); exercised by unit
tests for the router/sdk/data and an integration test that forks a real child.

* feat(plugins): activation, HTTP route proxy + instance settings (M2)

Wires the isolated runtime into TREK. Admins can now activate a plugin from the
panel and its HTTP routes work end to end, still behind the kill switch.

- PluginRuntimeService owns the supervisor: activate spawns the child with its
  granted permissions + decrypted instance config, deactivate kills it, status
  and errors are persisted to the plugins / plugin_error_log tables, and active
  plugins are booted on startup (OnModuleInit).
- Bidirectional RPC: the child now handles host→child invokes (routes/jobs) and
  reports its declared routes on load; the supervisor gained invoke()/routesOf().
- /api/plugins/:id/* proxy controller — a single static route that matches the
  plugin's declared routes, enforces per-route auth (auth:false routes are public
  for OAuth callbacks/webhooks), forwards only a whitelisted request view (never
  the session cookie), and strips unsafe response headers.
- Admin endpoints: POST :id/activate, POST :id/deactivate, GET/PUT :id/config —
  instance settings with secret fields encrypted (apiKeyCrypto) and masked.
- Kill switch moved to its own module so it never collides with test config mocks.

Photo/calendar hook consumers are deferred to a later slice.

* feat(plugins): sandboxed page/widget frames + trekBridge (M3)

Plugins can now render UI. Page plugins appear as a nav entry and open a
full-page sandboxed iframe; the frame talks to TREK only over the postMessage
bridge.

- Server serves plugin client assets at /plugin-frame/:id/* with a strict path
  guard and a locked-down, per-plugin CSP (default-src none; connect-src limited
  to declared outbound hosts; sandbox WITHOUT allow-same-origin -> opaque origin,
  so the frame can't read the session cookie or the parent DOM). Global CSP
  frameSrc relaxed from 'none' to 'self' for exactly these frames.
- GET /api/plugins feed lists active plugins for the client.
- Client: pluginStore + PluginFrame (the trekBridge host) authenticates every
  inbound message by SENDER WINDOW IDENTITY (event.source), not by a claimed id
  or origin; pushes context (theme/locale/tripId/userId), validates navigation,
  renders notifications as text, resizes widgets, and proxies trek:invoke to the
  plugin's own routes host-side (session cookie stays with the host).
- Page route /plugins/:id + Navbar nav injection for page plugins.

Dashboard widget slot and the trek:request core-data bridge are deferred to a
later slice.

* feat(plugins): secure installer — manifest, discovery, safe extract/fetch/scan (M4)

Plugins placed on the /plugins volume are now discovered, validated and registered
as inactive, ready to activate.

- manifest.ts: strict trek-plugin.json validation (id/version/type, known
  permissions only, egress required with http:outbound, native modules rejected).
- discovery.ts: scans the volume on startup + on demand (POST /api/admin/plugins/
  rescan), upserts rows INACTIVE, refreshes settings-field descriptors, and never
  downgrades or wipes an already-installed plugin's status / grants / config.
  Invalid or native-carrying plugins are skipped and logged.
- Activation now grants the DECLARED permissions (the consent gate) and persists
  them before spawning.
- install/ utilities for the registry installer (M5), each independently tested:
  - safe-fetch: host allowlist (GitHub only) + private-IP refusal + manual
    redirect following + size cap + sha256 (constant-time compare).
  - safe-extract: zip/tar-slip-safe extraction with its own minimal tar.gz + zip
    readers; rejects traversal, absolute paths, symlinks, oversized/too-many
    entries, and unsupported formats.
  - native-scan: refuses .node / binding.gyp / prebuilds, never follows symlinks.

* feat(plugins): TREK-side registry — browse + one-click install (M5)

Connects TREK to the static GitHub registry (mauriceboe/TREK-Plugins). The
registry repo + CI gates were already live; this is the server side.

- registry.service: fetches the single aggregated dist/index.json (never
  per-plugin GitHub API calls — the HACS rate-limit lesson), caches it 30 min,
  soft-fails to a stale/empty registry, and installs a pinned version through
  the M4 pipeline: safe download -> sha256 verify -> slip-safe extract ->
  manifest re-validate -> native re-scan -> atomic move -> discover (inactive),
  recording repo/commit/sha provenance. Handles the codeload {repo}-{sha}/
  wrapper directory.
- Admin endpoints: GET /api/admin/plugins/registry (browse metadata) and
  POST /api/admin/plugins/install { id, version }. Install never executes code;
  activation stays a separate, deliberate step.

* feat(plugins): trek-plugin-sdk package — types, mock host, scaffolder, validator (M6)

The author-facing SDK, a standalone dependency-free package (not wired into the
app workspaces, so it can't affect the app build).

- definePlugin + the full plugin type surface (PluginContext, PluginRoute,
  PluginJob, PhotoProvider, CalendarSource) mirroring what the isolated runtime
  injects; PLUGIN_API_VERSION.
- createMockHost (trek-plugin-sdk/testing): a PluginContext that enforces the
  SAME permission model + membership checks, so authors can unit-test that their
  plugin degrades gracefully — no running TREK needed.
- validateManifest: the exact rules the registry CI runs, so a local pass
  predicts a CI pass.
- CLIs: create-trek-plugin (scaffolds a working plugin + README + starter iframe)
  and trek-plugin validate (manifest + README sanity).

Consolidating the server loader to import this shared validator is a follow-up.

* docs(plugins): plugin wiki + reference plugin (M7)

- Wiki pages (sync to the GitHub wiki on push to main): Plugins overview + trust
  model, Plugin Development (SDK, definePlugin, ctx, routes/jobs, the client
  bridge, testing with the mock host), Plugin Permissions reference, and
  Publishing (registry PR + CI gates + provenance). Linked from the sidebar.
- Reference plugin plugin-sdk/examples/trip-countdown: a complete, minimal-
  permission widget (reads trip data through ctx, renders in the sandboxed
  iframe via the bridge, filled-in README). Validated in the SDK test suite so it
  passes the exact gate authors face.

* feat(plugins): lifecycle polish — uninstall, error log, egress guard, widget slot (M8)

- Uninstall with data disposition: POST /api/admin/plugins/:id/uninstall kills the
  plugin, removes its code + DB metadata, and (deleteData) drops its data dir,
  error log and per-user settings.
- Error log: GET/DELETE /api/admin/plugins/:id/errors — the plugin's own crash /
  request-failure log, surfaced in the admin panel.
- Egress guard: the isolated child wraps global fetch and refuses any outbound
  host not in the plugin's declared egress[]; with none declared, all outbound is
  blocked. Process-level defense in depth (the container runtime enforces it at
  the network layer in v2).
- Admin → Plugins is now actionable: activate / deactivate / uninstall, a
  registry browser (install), and per-plugin error log. i18n across all locales.
- Dashboard widget slot: active widget plugins render as sandboxed cards.

The trek:request core-data bridge + photo/calendar hook consumers remain follow-ups.

* docs(plugins): clarify the fork-and-PR publishing flow

* fix(plugins): allow GitHub's rotating release-asset host in the installer

GitHub 302-redirects release-asset downloads to a rotating *.githubusercontent.com
host (objects / github-releases / release-assets). The SSRF allowlist only had
objects.githubusercontent.com, so installs failed with 'host not allowlisted'.
Allow the whole *.githubusercontent.com suffix (plus github.com/codeload); the
private-IP check remains the SSRF backstop.

* fix(plugins): allow inline scripts in the sandboxed frame + fix server lint error

- Plugin frame CSP: the frame runs at an opaque origin (sandbox without
  allow-same-origin), so script-src 'self' matches nothing and the widget's own
  script never runs (stuck on 'Loading…'). Allow 'unsafe-inline' — the sandbox,
  not this directive, is the isolation boundary, and the plugin author controls
  the frame code either way.
- Fix a no-constant-binary-expression eslint error in registry.test.ts that was
  failing the server lint:check (eslint .) in CI.

* fix(plugins): exclude /plugin-frame/ from the service-worker navigate fallback

The PWA service worker's navigateFallback served the SPA shell for any
navigation not on its denylist. /plugin-frame/ wasn't listed, so the SW
intercepted the sandboxed opaque-origin plugin iframe navigation, which Chrome
reports as 'Unsafe attempt to load URL … from frame with URL …'. Denylist it so
plugin frames are served straight from the network.

* feat(plugins): pass the dashboard's spotlight trip id to widget plugins

Widget plugins now receive the current (spotlight) trip id in their bridge
context, so a widget like Trip Countdown can show a real countdown instead of
the empty state.

* fix(plugins): trips.getById returns the actual trip row, not the access check

canAccessTrip only returns { id, user_id } (it's a membership check), but the
rpc-host's trips.getById returned it verbatim — so plugins saw a trip with no
title/start_date/etc. Fetch the real row after the access check. Also fix the
reference plugin to read t.title (the trips column is 'title', not 'name').

* feat(plugins): persist enable-intent across restarts + redesign admin page

The deactivation-on-deploy bug: `status` conflated the admin's ON/OFF intent with
runtime health, so a boot crash flipped status to 'error' and the plugin never
rebooted after the next deploy. Migration 156 adds an `enabled` flag (admin
intent) separate from `status` (runtime health); boot now retries every enabled
plugin regardless of last status, and a crash no longer erases the intent.

Admin → Plugins redesign:
- ON/OFF is a ToggleSwitch bound to `enabled`; runtime health shows separately as
  a coloured status dot, with the last error inline when it crashed.
- "Update → vX" badge when the registry has a newer version (one click updates
  and reactivates).
- Reviewed/unreviewed trust badges, cleaner cards, nicer empty state, registry
  browser marks already-installed plugins. i18n across all locales.

* fix(plugins): backfill enabled for any plugin not explicitly deactivated

status at migration time can be error/stopped/starting after a crash or shutdown,
not just 'active' — so backfill enabled=1 for everything except 'inactive' (the
only status deactivate() sets).

* feat(plugins): hero widget slot + Koffi reference plugin

Widget plugins can now declare capabilities.widget.slot 'hero' to render as a
transparent, click-through overlay sitting on the boarding-pass bar's top edge
(migration 157 persists capabilities; manifest validation server+SDK, feed
exposes the slot, dashboard mounts hero frames above the pass). Sidebar stays
the default slot.

Replaces the trip-countdown example with Koffi, the TREK mascot: an animated
suitcase with a 14-state behavior engine driven by real trip data — walking,
waving, napping, trolley rolls, passport-stamp stickers, a split-flap luggage-
tag countdown under 7 days, and sunglasses while the trip runs. Validated by
the SDK suite like any author plugin; published as mauriceboe/trek-plugin-koffi
in the registry.

Migrations 156/157 follow the idempotent ALTER pattern (the reconciliation
test re-runs everything from v135, so duplicate-column must stay non-fatal).

* feat(plugins): richer admin panel + registry detail view

Admin list: flush-left header like Addons, type/reviewed badges, runtime
health as a dot on the icon tile (text badge only for problem states),
description + source-repo link on installed cards, manifest icon.

Browse: cards show the plugin screenshot (docs/screenshot.png at the pinned
commit) and open a detail dialog fed by GET /api/admin/plugins/registry/:id —
live-manifest permissions in plain language, egress hosts, setup preview,
repo/homepage links. Manifest fetched server-side through safeDownload at the
reviewed commit, cached per plugin for 30 min and only when a detail opens.

Also fixes the update flow (restart the running child around the install,
keep the admin's enabled intent instead of force-activating disabled
plugins), guards the icon lookup against Object.prototype names, reserves
ids that would shadow static admin routes, stops negative-caching failed
manifest fetches, and makes the version compare prerelease-safe.

* i18n: localize the plugins admin section across all locales

The admin.plugins block was still English filler in most locales; translate
it everywhere and add the new detail-view keys in all 22 languages.

* feat(plugins): denser browse grid + prominent install-risk disclaimer

Four cards per row on desktop with tighter card padding, and a full-width
warning banner above the browse grid: installs are at the admin's own risk,
a prior quick review does not rule out harmful content, inspect a plugin
yourself when in doubt — TREK accepts no responsibility. All 22 locales.

* feat(plugins): sandbox hardening — OS permission model, egress choke point, bound acting user, author signatures

Closes the four gaps the security review surfaced:

- OS permission model on the prod plugin child (Node --permission with
  fs-read scoped to the compiled server dir + the plugin's own code dir, no
  fs-write/child_process/worker/native). A plugin can no longer read trek.db
  or the .jwt_secret/.encryption_key files, nor shell out — the direct-fs and
  RCE escapes that bypassed the RPC layer. Opt-out via TREK_PLUGIN_PERMISSIONS=off.
- Egress guard extended from fetch to the net.Socket connect choke point, so
  node:http/https/net/tls obey the declared-egress allowlist too (no declared
  egress = no outbound). Under the permission model there is no clean escape to
  an unwrapped runtime. Kernel/network-namespace containment remains the
  container step.
- Trip reads are membership-checked against the acting user the HOST binds from
  the authenticated invocation, not an asUserId the plugin supplies; a job/onLoad
  (no user) can't read user-scoped trips.
- Optional minisign (Ed25519) author signatures verified offline, TOFU-pinned
  (migration 158). Unsigned plugins install on sha256 alone; a signed plugin
  can't silently drop its signature or swap its author key.

Server suite green (permission-model activation verified against the Koffi
reference plugin on dev1).

* fix(plugins): make the permission-model child load from the real plugin path

The prod data dir is a symlink (server/data -> volume), so resolving the plugin
under it tripped the permission model, and Node's module-type lookup walked up
into the (denied) data dir. Fork the child from the plugin's realpath and drop a
{"type":"commonjs"} package.json at its root so resolution stops there — trek.db
and the secret files stay unreadable, verified against Koffi.

* test(plugins): cover pluginRealCodeDir fallback + ensurePluginModuleType

* feat(plugins): zero-config L1 hardening — SSRF egress, RSS reaper, capability audit, no popups

Security that ships from the install itself, no self-hoster setup:

- Egress SSRF/rebinding backstop: the net.Socket connect guard now RESOLVES the
  destination and refuses private/loopback/link-local/metadata/CGNAT/ULA
  addresses, pinning the resolved IP (a declared host that re-resolves to an
  internal address is blocked). Pure policy in egress-policy.ts + tests.
  TREK_PLUGIN_ALLOW_PRIVATE_EGRESS=on opts back into internal targets.
- RSS memory reaper: the supervisor now kills a child that blows a real RSS
  ceiling (TREK_PLUGIN_MAX_RSS_MB, default 300) — --max-old-space-size only
  bounds the V8 heap, so Buffers could OOM the box under it.
- Hash-chained capability audit log (migration 159): every core-data / broadcast
  call is recorded at the RPC boundary with the host-bound acting user and a
  per-plugin hash chain, so wide grants stay attributable + tamper-evident.
  Admin endpoint GET /api/admin/plugins/:id/audit.
- Drop allow-popups from the plugin frame (sandbox + CSP): window.open ignores
  connect-src, so it was an egress/phishing bypass.

Server suite 207 green, client + migration reconciliation green.

* fix(plugins): close the UDP + DNS egress hole in the network guard

The egress guard only wrapped fetch and net.Socket.connect, so TCP and
HTTP were contained but two channels stayed wide open: a plugin could
send data out over UDP (node:dgram) or tunnel it inside DNS queries
(dns.resolveTxt & friends) to any host it never declared. Neither goes
through net.Socket.connect, so the allowlist never saw them.

Wrap both now against the same declared-host allowlist:
- dgram send/connect: the explicit destination is allowlisted and
  private-IP-checked like a TCP connect (a null address keeps the
  connected/localhost default, which the connect wrapper already vetted).
- the dns resolver family (module fns, dns.promises, Resolver.prototype):
  a forward lookup for an undeclared name is refused, which kills DNS
  tunnelling even when no socket is ever opened.

A plugin with no declared egress now really has no way out.

* feat(plugins): re-consent gate when an update wants new permissions

Updating a plugin used to just reinstall and reactivate, which silently
granted whatever the new version declared — so a plugin could quietly
widen its own rights on the next release.

Route updates through a new server-side update() that diffs the new
version's declared permissions against what the admin already granted:
- nothing new -> the plugin is restarted transparently on the new code.
- new permissions or a new outbound host -> the new code is installed
  but the plugin is left OFF, and the delta is handed back so the admin
  has to approve it before it turns on.

Install runs first, so a failed download/signature check leaves the
running plugin untouched. The client shows the delta in a consent dialog
and only then activates. An update can never widen a plugin behind your back.

* feat(plugins): honest security info in the admin panel + update consent UI

Reworks how the plugins panel talks about safety, since the old copy
oversold it. Drops the "install at your own risk" banner and the generic
trust note, and replaces them with:

- a collapsible security section that lays out plainly how a plugin is
  contained, what the permissions actually mean (a hard limit on what a
  plugin CAN do, not a promise of what it does), where the limits are,
  and what a hostile plugin could do at worst.
- a short note on what "Reviewed" means: a maintainer scanned it for
  malware each version, not for quality — not a guarantee it's harmless.
- the consent dialog for the update flow: when an update asks for rights
  you never granted, it lists the new permissions and outbound hosts and
  makes you approve before the plugin turns back on.

Full copy in all 22 locales.

* feat(plugins): redesign the admin plugins page — search, filters, cleaner cards

The panel was cramped and hard to scan. Rebuilt it as a proper management
surface:

- A segmented Installed/Discover switch with counts, and a real toolbar:
  search, filter by type, filter by status (active/off/update/error), and
  sort (name/recent/updates first).
- An "N updates available · Update all" bar.
- Installed rows are tidied up: a single health dot on the icon tile
  instead of a wall of badges, and capability chips underneath that show
  what each plugin can actually reach at a glance (reads your trips,
  dashboard widget, the hosts it talks to) — the reach is now visible
  without opening anything. Update, toggle and a ⋯ menu (restart, errors,
  source, uninstall) sit on the right.
- The registry browser is now an App-Store-style card grid: screenshot
  with the plugin's icon chip, a reviewed badge, consistent heights.
- The detail dialog gained "What it can access", "Connects to" and a
  details grid (version, size, requires, reviewed).

To feed the capability chips, the installed list now returns each plugin's
declared permissions and capabilities. New copy is in all 22 locales.

* feat(plugins): make the plugins admin page work on small screens

The redesign was built desktop-first. On a phone the toolbar wrapped into
a mess and the rows were too cramped. Reworked the responsive behaviour:

- The toolbar stacks on mobile — tabs + rescan on top, full-width search,
  then a right-aligned filter row — and collapses back into one row on
  sm+ (via display:contents), so the desktop layout is unchanged. Filter
  buttons drop their label on mobile and lead with an icon; their menus
  are capped to the viewport width so they never push the page sideways.
- Installed rows use tighter spacing on mobile and the update button
  shrinks to just its icon (full label from sm up).
- Horizontal padding, the discover grid and the detail dialog all get
  mobile-friendly spacing.

* fix(plugins): make the detail dialog screenshot fill the full width

aspect-[16/9] together with max-h-64 made the browser shrink the image
width to keep the ratio once the height was capped, leaving a grey strip
on the right. Drop the max-height so the header image spans the dialog.

* feat(plugin-sdk): one-command publishing — pack, entry, release

Publishing a plugin meant hand-building the zip, running shasum + stat,
resolving the tag's commit, and hand-writing the whole registry entry.
The SDK does all of it now:

- `trek-plugin pack` builds plugin.zip in the exact layout the installer
  reads (own tiny zip writer, so the SDK stays dependency-free and the
  format can't drift from the reader), enforces the same native-binary and
  size rules, and prints the sha256 + size. docs/ is left out — the store
  fetches the screenshot from the repo, so it doesn't belong in the install
  artifact (Koffi's went from 943 KB to 15 KB).
- `trek-plugin entry` emits the ready-to-PR registry entry from the manifest
  + the packed zip + the git tag: commitSha (deref'd), downloadUrl, sha256,
  size, and minTrekVersion derived from the manifest's trek range. `--merge`
  prepends a new version onto an existing entry for updates.
- `trek-plugin release` chains pack → gh release → entry.

Also: the scaffold now points the README at docs/screenshot.png (the path
the store actually fetches, was screenshot-1.png) with a size hint, and
stops hard-coding an MIT license — a plugin is the author's own code under
their own license. Round-tripped against the real server extractor; 18 tests.

* docs(plugins): rewrite the plugin wiki against the current code + tooling

The plugin wiki had drifted from the app and the SDK. Rewrote all four
pages, verifying every command, permission, field, path and UI behaviour
against source:

- Plugins: activation is a toggle (no separate consent screen); install is
  the Discover tab (no "Browse plugins" button); you review permissions in
  the detail modal before installing; documents update + re-consent, the ⋯
  menu, toolbar filters, capability chips and the health dot.
- Plugin-Development: full manifest reference; ws:broadcast:trip/:user (there
  is no ws:broadcast:*); onLoad + onUnload; the trek:error bridge message and
  full context payload; trips.* only work in a route handler; asUserId is
  accepted-but-ignored; integration hooks are declared but not yet wired.
- Plugin-Permissions: db:own also covers db.migrate; a host must appear as
  both an http:outbound:<host> permission and an egress[] entry or it's
  silently blocked; bare vs per-host outbound.
- Plugin-Publishing: the new one-command flow (validate → pack → release →
  entry), size is a required entry field, signing reconciled with the schema,
  no reserved namespaces, and the --merge update path.

* chore(plugin-sdk): make it npm-publishable so `npx` resolves for authors

The docs told authors to run `npx create-trek-plugin` / `npx trek-plugin`,
but nothing published under those names, so npx couldn't resolve them.

- Ship one package, `trek-plugin-sdk`, with a bin that matches the package
  name (`trek-plugin-sdk`) so `npx trek-plugin-sdk <command>` resolves with
  zero install. The dispatcher gained a `create` subcommand, so every step
  (create/validate/pack/entry/release) runs through that one entry point.
  The short `trek-plugin` / `create-trek-plugin` bins still work once
  installed.
- Package hardening for publish: repository+directory (monorepo subdir),
  homepage/bugs/author/engines, publishConfig public, a prepublishOnly that
  builds + tests, and a LICENSE file.
- A publish workflow: pushing a `plugin-sdk-v*` tag builds and publishes with
  the NPM_TOKEN repo secret.
- Docs (SDK README + the four wiki pages) now use `npx trek-plugin-sdk <cmd>`,
  the invocation that actually resolves.

* feat(plugin-sdk): dev server, preflight, auto-PR submit, signing, wizard

Round out the author experience so the loop is create -> dev -> release/submit
without hand-work or a round-trip through registry review.

- `dev`: run a plugin locally with a real request loop and hot reload — no full
  TREK. Injects a ctx that enforces the manifest's granted permissions (an
  ungranted call throws, so you catch a missing grant), backs db:own with a real
  SQLite file (node:sqlite), serves routes under /api and page/widget UI at /ui,
  and reloads on save. Dependency-free (node:http + built-ins).
- `preflight`: run the registry CI checks locally over the network (tag->commit,
  manifest parity, artifact sha256/size, native scan, README quality gate) so a
  green run predicts a green CI.
- `submit`: fork TREK-Plugins, branch off current main, write/merge the entry,
  push, and open the PR — the last manual publishing step, automated.
- `keygen`/`sign` + `--sign` on entry/release/submit: dependency-free Ed25519
  author signatures over the artifact bytes, verified 1:1 against the server's
  TOFU check. Fills authorPublicKey + signature and guards against a key change.
- `create` gains an interactive wizard (id/type/author/permissions) and flags.
- README + Development/Publishing/Permissions wikis document the new flow.

24 tests pass (sign round-trips through a server-shaped verifier; zip reader;
scaffold options; entry signing + key-change guard).

* feat(plugin-sdk): one-command `publish` (pack → release → preflight → PR)

Collapses the release into a single command: pack the artifact, tag + create the
GitHub release, run the registry CI checks locally (preflight), and open the
registry PR — stopping before it submits if preflight would fail, so a broken
entry never becomes a doomed PR. `--sign` signs it; `--no-preflight` skips the
gate. The individual pack/release/preflight/submit commands still exist.

README + the Development/Publishing/Permissions wikis lead with `publish` now.

* fix(plugins): security hardening from the PR #1415 audit

Remediates the findings from the adversarial audit (threat model: malicious
plugin author + malicious artifact). Highlights:

Critical
- proxy: force nosniff + Content-Disposition: attachment on every proxied reply
  and drop location/content-disposition + non-2xx from the passthrough, so a
  plugin can't serve an HTML document at TREK's origin (sandbox-escape → account
  takeover) or an open redirect.

High
- db:own runs synchronously in the host: cap the plugin DB (max_page_count) and
  row-cap query() via iterate() so a recursive CTE / huge blob can't stall the
  event loop, OOM, or exhaust the shared volume.
- supervisor: measure child RSS host-side (/proc/<pid>/statm) instead of trusting
  the spoofable heartbeat; add an activation timeout so a stuck onLoad can't hang
  activate() or peg a core unreaped.
- safe-extract: enforce entry-count + cumulative-size limits INSIDE readZip
  before inflating (decompression-bomb OOM).
- re-consent: activate() never widens granted permissions without explicit
  consent (409 CONSENT_REQUIRED); the row toggle + "Update All" route through the
  consent dialog, which now queues instead of overwriting.

Medium/low
- egress: gate dgram hostnames through the IP-vetting resolver; block the
  low-level socket escape (process.binding) + lock the wrapped prototypes;
  canonicalize IPv6 in isBlockedIp (hex-mapped/compressed metadata); reject
  degenerate `*.` / whole-TLD / spaced outbound hosts in the manifest + CSP.
- ws:broadcast is membership-gated to the acting user's trips / own connections;
  users.getById is scoped to users the acting user can see (no enumeration).
- safe-fetch streams + aborts at the byte cap (chunked codeload OOM); isPrivateIp
  reuses the canonicalizing check.
- native-scan throws instead of silently passing past its entry cap.
- SDK: dev serves binary assets as raw buffers + handles EADDRINUSE; manifest
  validator gains the reserved-id + outbound-host checks; wikis corrected.

Tests updated for the new membership-gated behaviour + regression tests added
(IPv6 canonicalization, wildcard hardening, outbound-host validation, ws/user
scoping). 234 plugin tests + 24 SDK tests green.

* fix(plugins): close the 4 PARTIAL findings + regressions from the fix-verify pass

A second adversarial pass over the first remediation found four findings only
partially closed and five issues the fixes themselves introduced. This closes
them:

Partial → closed
- re-consent gate keyed on `granted.length > 0`, so a plugin first activated with
  ZERO permissions (granted '[]') was treated as never-consented and a later
  widening was granted silently. Now discovery marks a never-consented plugin with
  granted_permissions '' and activate() gates on "ever consented" (any non-empty
  string, including '[]').
- db:own DoS: block WITH RECURSIVE outright (the one construct that spins the
  synchronous host unboundedly regardless of the size/row caps, via query OR exec).
- dgram: also wrap `new dgram.Socket(...)` (bypassed createSocket) to inject the
  IP-vetting lookup, and lock createSocket/Socket.
- frame self-navigation: documented as a bounded best-effort mitigation (inherent
  to sandboxed iframes; exposure is the plugin's own routes + already-held context,
  never the httpOnly cookie).

Regressions introduced by the first pass → fixed
- proxy: only real redirects (301/302/303/307/308) are gated, to a RELATIVE in-app
  Location (supports OAuth-callback bounce, blocks open redirect); 300/304 pass
  through; attachment only on non-redirects.
- supervisor: measure RSS via /proc/<pid>/status VmRSS (page-size independent);
  activation-timeout awaits kill() before disposing the db handle.
- manifest HOST_RE: allow single-label hosts (self-hoster sibling services) while
  keeping wildcards multi-label; mirrored in the SDK + frame CSP filter.

Regression tests added (re-consent incl. the '[]' case, WITH RECURSIVE + row cap,
single-label host). 236 plugin tests + 24 SDK tests green.

* docs: refresh README screenshots (8) + swap the second trip shot for Collections

Replaces all eight README gallery screenshots with current-UI captures and swaps
docs/screenshots/trip-iceland.png for collections.png (saved place lists).

* fix(plugin-sdk): make require('trek-plugin-sdk') actually resolve everywhere

A freshly scaffolded plugin could not load anywhere: the npm package is
ESM-only (no require condition in its exports map), so the scaffold's
require('trek-plugin-sdk') threw ERR_PACKAGE_PATH_NOT_EXPORTED under
`trek-plugin dev` - and the runtime injection the wiki promised for the
plugin child never existed, so a packed plugin (node_modules stripped)
crashed with MODULE_NOT_FOUND after a real install.

- plugin child: inject a frozen {definePlugin, PLUGIN_API_VERSION} shim
  for require('trek-plugin-sdk'); subpaths fail with a pointed error
- trek-plugin dev: inject the exact same shim, so a fresh scaffold runs
  with zero npm install and dev parity with production holds
- npm package: ship a real CommonJS build (dist/cjs + require export
  conditions) so the installed package also requires cleanly on Node 18+
- create: scaffold a package.json (type commonjs, SDK as devDependency,
  npx scripts); print resolvable `npx trek-plugin-sdk ...` hints
- wiki: package.json in the scaffold tree + publishing checklist, and
  document the zero-install dev flow

* fix(plugins): tolerate a UTF-8 BOM in trek-plugin.json

Windows editors love to prepend a BOM, and a bare JSON.parse then dies
with an "Unexpected token" pointing at an invisible character - in the
SDK CLIs (dev/validate/entry/submit) and, worse, server-side: a BOM in
an author repo travels through pack into the artifact and fails
discovery and registry install. Strip it at every manifest/JSON read
(readJsonFile in the SDK, parseJsonText in the installer).

* fix(plugin-sdk): dev db binds an args array like the real host, and a failed onLoad stops the routes

* ci(plugin-sdk): publish on Node 22; skip the dev-db bind test without node:sqlite

* docs(wiki): document AI booking import, guest members and packing sharing

Fill the gaps left after the 3.2.0 feature work:
- add an AI Booking Import page for the AI Parsing addon (providers,
  admin/per-user config, model pull, the review-before-save flow) and link
  it from Reservations & Bookings and the sidebar
- document guest members on Trip Members and Sharing (owner-only, what they
  can be assigned to, and the sign-in/notification/visibility limits)
- document the three packing sharing tiers and co-bringing on Packing Lists
- add TRANSIT_API_URL and the plugin variables to Environment Variables,
  and correct the language list to 22 (add Swedish and Vietnamese)
- list the airtrail and llm_parsing addons in the Addons overview

* feat(plugins): enable the plugin system by default

The runtime and the Admin -> Plugins panel are now available out of the box;
TREK_PLUGINS_ENABLED becomes an opt-out (set it to false to switch the whole
system off). Installed plugins are still registered inactive and have to be
activated one by one, so no third-party code runs until an admin turns a
specific plugin on.

Update the kill-switch default test and the plugin/env-var wiki pages to match.

* fix(costs): KGS is selectable as default/expense currency (#1400)

* fix(map): render date-line-crossing routes as one continuous arc (#1411)

The great-circle sampler normalizes longitudes to [-180,180], so a
transpacific leg jumped +-360 between neighbours and got split into two
polylines pinned to opposite map edges. Unwrap the longitudes instead
(shared flightGeodesy module for both renderers): Leaflet additionally
draws a +-360-shifted copy so both halves show in the standard view, GL
maps repeat world copies themselves.

* fix(map): clear the hover card on marker click and camera moves (#1404)

Clicking an off-center place recenters the map under a stationary
cursor, so mouseout/mouseleave never fires and the hover card sticks.
Clear it on marker click and on movestart, and suppress re-shows while
the camera is animating (marker rebuilds re-fire mouseenter mid-pan).

feat(map): long-press + plain right-click add-place on GL maps (#1398)

The GL providers only bound middle-click, so mobile had no way to add a
place at a position (and Macs have no middle button). Add a 600ms touch
long-press with move tolerance and the map contextmenu event - both GL
libs suppress it while the right-button rotate/pitch drag is active, so
the gesture keeps winning.

* fix(mcp): keep SSE streams alive and stop invalidating sessions on unrelated saves (#1414)

Three separate causes for the reconnect-per-tool-call pain:
- no keep-alive on the standalone GET stream, so reverse proxies with
  idle timeouts (nginx default 60s) killed it between calls - send an
  SSE comment ping every 25s (MCP_SSE_KEEPALIVE, 0 = off) and count an
  open stream as session activity
- the session TTL was hard-coded - MCP_SESSION_TTL (seconds, clamped to
  24h) now works as the issue expected
- every addon save invalidated ALL sessions: config-only saves, photo
  provider toggles and addons with no MCP surface included. Only a real
  enabled-flip of an MCP-relevant addon (or an actual collab-feature
  change) tears sessions down now.

* feat(api): OpenAPI/Swagger docs at /api/docs behind TREK_API_DOCS_ENABLED (#1412)

Swagger UI + raw spec (/api/docs-json, -yaml) over all controllers, with
a bearer button that works with a plain session JWT. Off by default -
the spec enumerates the whole surface incl. admin routes, so exposing
it is an explicit self-hoster decision (same kill-switch pattern as
TREK_PLUGINS_ENABLED).

Request bodies come from the Zod schemas the routes already validate
with: an enricher walks every controller, finds whole-body
ZodValidationPipe params and lifts their schema into the document via
zod v4's native z.toJSONSchema - nothing is annotated twice, and any
route that gains a Zod pipe is documented automatically.

* fix(map,mcp): review follow-ups for the issue-fix batch

- mapbox-gl (unlike maplibre) still emits the map contextmenu after a
  right-button rotate/pitch drag on Windows - guard it with the pressed
  position so ending a rotate can't open the Add-Place form (#1398)
- a long-press whose fire was deduped (or that never yields a click) no
  longer leaves suppressNextClick armed to swallow a later real tap
- MCP_SSE_KEEPALIVE=0 keeps the open-stream-counts-as-activity
  guarantee: the touch interval survives, only the pings stop (#1414)
- swagger-ui-dist ships @scarf/scarf install-time analytics - disabled
  via scarfSettings in the root package.json, TREK sends no telemetry
- Budget wiki currency list: 47 incl. KGS (#1400)

* feat(map): real road routes for car/bus/taxi/bicycle bookings instead of straight lines

Road-based transport bookings drew an as-the-crow-flies line; only
transit journeys (Transitous) showed the real path. A shared
useTransportRoutes hook now fetches the OSRM road geometry (driving for
car/bus/taxi, cycling for bicycle) — reusing the day-route router and
its cache — and both renderers draw it in place of the straight arc,
falling back to the straight line until it loads or if routing fails.
Trains/other keep their straight line (not road-routable); a 2000 km
sanity cap avoids hammering the public router on cross-continent quirks.

* feat(transport): multi-leg train bookings (#1150)

Long train trips are usually several trains under one booking. Trains
now get the same multi-leg editor flights have: an ordered chain of
stations (station search instead of the airport picker) with a per-leg
train number + platform, saved as from/stop/to endpoints + metadata.legs
— mirroring the flight leg contract, so the map draws the whole chain
and the day plan splits it into one row per leg (drag/reorder/position
persistence come for free from the shared __leg machinery). A single-leg
train saves exactly as before (flat metadata, no legs), and the flat
train-fields block is gone in favour of the per-leg inputs. Day sidebar,
shared trip view and the PDF render each train leg like a flight leg.

* feat(collections): per-collection custom labels

Each list can now define its own labels (e.g. Berlin, Hamburg, Ostsee in a
"Germany 2026" list) and organise its places by them:

- manage labels (create / rename / recolor / delete) from a label manager
- assign labels to a place from its detail sheet, or to many places at once
  from the selection toolbar
- filter the place list AND the map by label (multi-select, any-match)

Labels are scoped to a collection and shared by all its members. Managing and
assigning labels needs edit rights; filtering is available to everyone. Moving
a place to another list drops its labels, since they belong to the source list.

* test(collections): pass the required labels prop in CollectionPlaceDetail test

The per-collection labels feature (a5522e99) made `labels` a required prop
and renders `labels.filter(...)`, but the test's props cast to
Omit<DetailProps,'t'> hid the missing prop, so `labels` was undefined at
runtime and crashed the whole suite (Cannot read properties of undefined
reading 'filter'). Pass labels: [] like categories.

* docs(wiki): document collection labels, multi-leg trains and road-route overlays

- Collections: add a Custom labels section (manage / assign / filter), note the
  label filter + bulk assign, and the view-vs-edit permission split
- Transport: rewrite the train fields as the multi-leg route editor, correct the
  transport type list (nine types) and the map/day-plan behaviour
- Map Features: car/bus/taxi/bicycle overlays follow real roads; multi-leg trains
  draw their full station chain; date-line routes render as one continuous arc

---------

Co-authored-by: jubnl <jgunther021@gmail.com>
Co-authored-by: jufy111 <jeffturner93@gmail.com>
Co-authored-by: Azalea <noreply@aza.moe>
Co-authored-by: Zorth Thorch <jasper_goens@hotmail.com>
Co-authored-by: leeduc <lee.duc55@gmail.com>
Co-authored-by: yael-tramier <tramier.yael@gmail.com>
Co-authored-by: michael-bohr <mjbohr@gmail.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: Gio Cettuzzi <gio.cettuzzi@gmail.com>
Co-authored-by: mauriceboe <mauriceboe@users.noreply.github.com>
Co-authored-by: jubnl <66769052+jubnl@users.noreply.github.com>
This commit is contained in:
Maurice
2026-07-05 01:13:04 +02:00
committed by GitHub
parent 75e3bb3985
commit 7eabf6066f
1053 changed files with 61584 additions and 3393 deletions
+2
View File
@@ -8,6 +8,8 @@ export const ADDON_IDS = {
COLLAB: 'collab',
JOURNEY: 'journey',
AIRTRAIL: 'airtrail',
LLM_PARSING: 'llm_parsing',
COLLECTIONS: 'collections',
} as const;
export type AddonId = typeof ADDON_IDS[keyof typeof ADDON_IDS];
+5
View File
@@ -4,6 +4,8 @@ import type { INestApplication } from '@nestjs/common';
import { AppModule } from './nest/app.module';
import { applyGlobalMiddleware } from './middleware/globalMiddleware';
import { applyPlatformUploads, applyPlatformTransport, applyPlatformStatic } from './nest/platform/platform.routes';
import { apiDocsEnabled } from './nest/common/api-docs.kill-switch';
import { setupApiDocs } from './nest/platform/api-docs';
/**
* Builds the unified TREK NestJS application that serves the ENTIRE surface — the
@@ -27,6 +29,8 @@ import { applyPlatformUploads, applyPlatformTransport, applyPlatformStatic } fro
* metadata, the /mcp routes, the /oauth/consent COOP header.
* 4. applyPlatformStatic — the production built-client static assets (so a real
* asset request returns the file before the Nest router 404s it).
* 4b. setupApiDocs — Swagger UI/spec at /api/docs* when TREK_API_DOCS_ENABLED;
* also Express-level, so it must precede init for the same reason.
* 5. app.init() — registers every migrated /api domain (the Nest controllers).
*
* The SPA index.html fallback (unmatched GET → index.html in production) is the
@@ -40,6 +44,7 @@ export async function buildApp(): Promise<INestApplication> {
applyPlatformUploads(instance);
applyPlatformTransport(instance);
applyPlatformStatic(instance);
if (apiDocsEnabled()) setupApiDocs(app);
await app.init();
return app;
}
+348
View File
@@ -3071,6 +3071,354 @@ function runMigrations(db: Database.Database): void {
if (!err.message?.includes('duplicate column name')) throw err;
}
},
() => {
try {
db.exec('ALTER TABLE budget_item_members ADD COLUMN amount REAL');
} catch (err: any) {
if (!err.message?.includes('duplicate column name')) throw err;
}
},
// Calendar feed tokens — subscribable ICS links for per-trip and all-trips feeds
() => {
try {
db.exec('ALTER TABLE trips ADD COLUMN feed_token TEXT');
} catch (err: any) {
if (!err.message?.includes('duplicate column name')) throw err;
}
try {
db.exec('ALTER TABLE users ADD COLUMN feed_token TEXT');
} catch (err: any) {
if (!err.message?.includes('duplicate column name')) throw err;
}
db.exec('CREATE UNIQUE INDEX IF NOT EXISTS idx_trips_feed_token ON trips(feed_token) WHERE feed_token IS NOT NULL');
db.exec('CREATE UNIQUE INDEX IF NOT EXISTS idx_users_feed_token ON users(feed_token) WHERE feed_token IS NOT NULL');
},
// Optimistic-concurrency token for offline conflict detection (#1135).
// packing_items had only created_at, so an offline edit could not be checked
// against a concurrent server change. SQLite forbids a non-constant DEFAULT on
// ALTER ADD COLUMN, so add it nullable and backfill from created_at; new rows
// set it explicitly (packingService). Additive: a request without the
// X-Base-Updated-At header keeps the old last-write-wins behaviour.
() => {
try {
db.exec('ALTER TABLE packing_items ADD COLUMN updated_at DATETIME');
} catch (err: any) {
if (!err.message?.includes('duplicate column name')) throw err;
}
db.exec('UPDATE packing_items SET updated_at = COALESCE(updated_at, created_at, CURRENT_TIMESTAMP) WHERE updated_at IS NULL');
},
// Video support (#823): the trek_photos registry held only images. media_type
// discriminates image vs video so the gallery, lightbox and provider proxy can
// branch; duration_ms is optional metadata for the player. Additive — existing
// rows default to 'image'.
() => {
for (const stmt of [
"ALTER TABLE trek_photos ADD COLUMN media_type TEXT NOT NULL DEFAULT 'image'",
'ALTER TABLE trek_photos ADD COLUMN duration_ms INTEGER',
]) {
try {
db.exec(stmt);
} catch (err: any) {
if (!err.message?.includes('duplicate column name')) throw err;
}
}
},
// Dedicated booking URL (#935) — users previously stuffed links into notes.
// Additive nullable TEXT; existing rows default to NULL.
() => {
try {
db.exec('ALTER TABLE reservations ADD COLUMN url TEXT');
} catch (err: any) {
if (!err.message?.includes('duplicate column name')) throw err;
}
},
// Private packing items (#858): an item can be hidden from other trip members.
// is_private toggles the visibility; owner_id records who it belongs to so the
// listing can show it only to them. owner_id is NULL on legacy rows (shared).
() => {
for (const stmt of [
'ALTER TABLE packing_items ADD COLUMN is_private INTEGER NOT NULL DEFAULT 0',
'ALTER TABLE packing_items ADD COLUMN owner_id INTEGER REFERENCES users(id) ON DELETE SET NULL',
]) {
try {
db.exec(stmt);
} catch (err: any) {
if (!err.message?.includes('duplicate column name')) throw err;
}
}
},
// Guest members (#1362): people added to a trip without an account. A guest is a
// users row flagged is_guest=1 (no usable credentials) joined into trip_members,
// so it's assignable everywhere a member is — but must never authenticate or show
// up in the global user directory. The flag is the discriminator for those guards.
() => {
try {
db.exec('ALTER TABLE users ADD COLUMN is_guest INTEGER NOT NULL DEFAULT 0');
} catch (err: any) {
if (!err.message?.includes('duplicate column name')) throw err;
}
},
// Three-tier packing sharing (#858 follow-up): an item is Common (is_private=0,
// every existing item — non-breaking), Personal (is_private=1, owner only) or
// Shared-with-people (is_private=1 + recipient rows). owner_id is the "bringer".
// Contributors are extra people who said "I can bring that too" on a Common item
// (status 'pending' until the owner accepts).
() => {
db.exec(`
CREATE TABLE IF NOT EXISTS packing_item_recipients (
item_id INTEGER NOT NULL REFERENCES packing_items(id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
PRIMARY KEY (item_id, user_id)
);
CREATE INDEX IF NOT EXISTS idx_packing_item_recipients_user ON packing_item_recipients(user_id);
CREATE TABLE IF NOT EXISTS packing_item_contributors (
item_id INTEGER NOT NULL REFERENCES packing_items(id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
status TEXT NOT NULL DEFAULT 'accepted',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (item_id, user_id)
);
`);
},
// Migration 150: Collections addon — personal place library (#1081).
// Multi-list + per-place status (idea/want/visited) + fusion sharing.
// (150 = migrations.length of this array after appending — the runner uses
// migrations.length, not this comment; the label is cosmetic.)
() => {
db.prepare(
`
INSERT OR IGNORE INTO addons (id, name, description, type, icon, enabled, config, sort_order)
VALUES ('collections', 'Collections', 'Personal place library — save places across trips into named lists, copy into any trip, share with others', 'global', 'Bookmark', 0, '{}', 16)
`,
).run();
db.exec(`
CREATE TABLE IF NOT EXISTS collections (
id INTEGER PRIMARY KEY AUTOINCREMENT,
owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
name TEXT NOT NULL,
description TEXT,
color TEXT DEFAULT '#6366f1',
icon TEXT DEFAULT 'Bookmark',
cover_image TEXT,
sort_order INTEGER DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS collection_members (
id INTEGER PRIMARY KEY AUTOINCREMENT,
collection_id INTEGER NOT NULL REFERENCES collections(id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
status TEXT NOT NULL DEFAULT 'pending',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
UNIQUE(collection_id, user_id)
);
CREATE TABLE IF NOT EXISTS collection_places (
id INTEGER PRIMARY KEY AUTOINCREMENT,
collection_id INTEGER NOT NULL REFERENCES collections(id) ON DELETE CASCADE,
owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
saved_by INTEGER REFERENCES users(id) ON DELETE SET NULL,
name TEXT NOT NULL,
description TEXT,
lat REAL,
lng REAL,
address TEXT,
category_id INTEGER REFERENCES categories(id) ON DELETE SET NULL,
price REAL,
currency TEXT,
notes TEXT,
image_url TEXT,
google_place_id TEXT,
google_ftid TEXT,
osm_id TEXT,
website TEXT,
phone TEXT,
status TEXT NOT NULL DEFAULT 'idea',
source_trip_id INTEGER,
source_place_id INTEGER,
sort_order INTEGER DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS collection_place_tags (
collection_place_id INTEGER NOT NULL REFERENCES collection_places(id) ON DELETE CASCADE,
tag_id INTEGER NOT NULL REFERENCES tags(id) ON DELETE CASCADE,
PRIMARY KEY (collection_place_id, tag_id)
);
CREATE INDEX IF NOT EXISTS idx_collection_places_collection ON collection_places(collection_id);
CREATE INDEX IF NOT EXISTS idx_collection_members_user ON collection_members(user_id);
CREATE INDEX IF NOT EXISTS idx_collection_place_tags_place ON collection_place_tags(collection_place_id);
CREATE INDEX IF NOT EXISTS idx_collection_place_tags_tag ON collection_place_tags(tag_id);
`);
},
// Migration 151: user-added links on collections + saved places (JSON text)
() => {
try { db.exec('ALTER TABLE collections ADD COLUMN links TEXT'); } catch (err) { console.warn('[migrations] Non-fatal migration step failed:', err); }
try { db.exec('ALTER TABLE collection_places ADD COLUMN links TEXT'); } catch (err) { console.warn('[migrations] Non-fatal migration step failed:', err); }
},
// Migration 152: per-member permission role on a shared list. Existing
// accepted members default to 'editor' so nothing regresses.
() => {
try { db.exec("ALTER TABLE collection_members ADD COLUMN role TEXT NOT NULL DEFAULT 'editor'"); } catch (err) { console.warn('[migrations] Non-fatal migration step failed:', err); }
},
// Migration 153: per-trip invite links (#1143). One rotating token per trip;
// a logged-in existing user who opens the link joins the trip as a member.
// Deleting the trip drops the token (CASCADE); the creator is nulled if their
// account is removed so the link keeps working.
() => {
db.exec(`
CREATE TABLE IF NOT EXISTS trip_invite_tokens (
id INTEGER PRIMARY KEY AUTOINCREMENT,
trip_id INTEGER NOT NULL UNIQUE REFERENCES trips(id) ON DELETE CASCADE,
token TEXT UNIQUE NOT NULL,
created_by INTEGER REFERENCES users(id) ON DELETE SET NULL,
expires_at TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_trip_invite_tokens_token ON trip_invite_tokens(token);
`);
},
// Migration 154: optional trip binding on an admin invite link (#1402). A user
// who REGISTERS via the link is auto-added to the trip. Nullable for backward
// compatibility; ON DELETE SET NULL so removing the trip just unbinds the invite.
() => {
try { db.exec('ALTER TABLE invite_tokens ADD COLUMN trip_id INTEGER REFERENCES trips(id) ON DELETE SET NULL'); } catch (err) { console.warn('[migrations] Non-fatal migration step failed:', err); }
},
// Migration 155: plugin system scaffold (#plugins). A plugin is a row here;
// its code lives on the /plugins volume and (once the runtime lands) runs in
// an isolated child process. This migration only lays down the registry
// tables — nothing executes yet. Own data lives in a per-plugin sqlite file
// under /plugins-data, never in these tables.
() => {
db.exec(`
CREATE TABLE IF NOT EXISTS plugins (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
description TEXT,
type TEXT NOT NULL DEFAULT 'integration',
icon TEXT DEFAULT 'Blocks',
version TEXT,
api_version INTEGER DEFAULT 1,
min_trek_version TEXT,
permissions TEXT DEFAULT '[]',
granted_permissions TEXT DEFAULT '[]',
status TEXT NOT NULL DEFAULT 'inactive',
config TEXT DEFAULT '{}',
source_repo TEXT,
source_commit TEXT,
sha256 TEXT,
crash_count INTEGER NOT NULL DEFAULT 0,
last_error TEXT,
reviewed_at TEXT,
sort_order INTEGER NOT NULL DEFAULT 0,
installed_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS plugin_meta_migrations (
plugin_id TEXT NOT NULL,
migration_id TEXT NOT NULL,
applied_at DATETIME DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (plugin_id, migration_id)
);
CREATE TABLE IF NOT EXISTS plugin_error_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
plugin_id TEXT NOT NULL,
ts DATETIME DEFAULT CURRENT_TIMESTAMP,
level TEXT NOT NULL DEFAULT 'error',
message TEXT,
stack TEXT
);
CREATE INDEX IF NOT EXISTS idx_plugin_error_log_plugin ON plugin_error_log(plugin_id, ts);
CREATE TABLE IF NOT EXISTS plugin_settings_fields (
id INTEGER PRIMARY KEY AUTOINCREMENT,
plugin_id TEXT NOT NULL,
field_key TEXT NOT NULL,
label TEXT,
input_type TEXT NOT NULL DEFAULT 'text',
placeholder TEXT,
hint TEXT,
required INTEGER NOT NULL DEFAULT 0,
secret INTEGER NOT NULL DEFAULT 0,
scope TEXT NOT NULL DEFAULT 'instance',
options TEXT,
oauth_config TEXT,
sort_order INTEGER NOT NULL DEFAULT 0,
UNIQUE (plugin_id, field_key)
);
`);
},
// Migration 156: separate the admin's ON/OFF intent (`enabled`) from the
// runtime health (`status`). A crash used to flip status to 'error', which
// erased the "keep it on" intent, so the plugin never rebooted after a deploy.
// Boot now retries every enabled plugin regardless of last status.
() => {
try {
db.exec("ALTER TABLE plugins ADD COLUMN enabled INTEGER NOT NULL DEFAULT 0;");
// Anything not explicitly deactivated was meant to be on ('inactive' is the
// only status deactivate() sets; a crash/shutdown could leave error/stopped/starting).
db.exec("UPDATE plugins SET enabled = 1 WHERE status != 'inactive';");
} catch (err) { console.warn('[migrations] Non-fatal migration step failed:', err); }
},
// Migration 157: plugin capabilities (from trek-plugin.json) — the client
// needs them to place widgets (e.g. widget.slot 'hero' renders as an overlay
// on the boarding-pass bar instead of the dashboard sidebar).
() => {
try { db.exec("ALTER TABLE plugins ADD COLUMN capabilities TEXT NOT NULL DEFAULT '{}';"); } catch (err) { console.warn('[migrations] Non-fatal migration step failed:', err); }
},
// Migration 158: TOFU pin for a plugin's author signing key (#plugins, #4).
// Set on first install of a signed plugin; a later install whose registry key
// differs is a hard stop (author change / key rotation / attack) unless an
// admin re-trusts. NULL for unsigned plugins (signing is opt-in).
() => {
try { db.exec("ALTER TABLE plugins ADD COLUMN author_pubkey TEXT;"); } catch (err) { console.warn('[migrations] Non-fatal migration step failed:', err); }
},
// Migration 159: hash-chained capability audit log (#plugins, L1 hardening).
// Every host-mediated capability call the plugin makes is recorded at the RPC
// boundary (where the plugin provably can't reach) with the host-bound acting
// user and a per-plugin hash chain, so wide data grants stay attributable +
// tamper-evident + user-visible.
() => {
try {
db.exec(`CREATE TABLE IF NOT EXISTS plugin_capability_audit (
id INTEGER PRIMARY KEY AUTOINCREMENT,
plugin_id TEXT NOT NULL,
acting_user_id INTEGER,
method TEXT NOT NULL,
resource TEXT,
code TEXT NOT NULL,
ts TEXT NOT NULL DEFAULT (datetime('now')),
prev_hash TEXT,
hash TEXT NOT NULL
);`);
db.exec('CREATE INDEX IF NOT EXISTS idx_plugin_audit_plugin ON plugin_capability_audit (plugin_id, id);');
} catch (err) { console.warn('[migrations] Non-fatal migration step failed:', err); }
},
// Migration 160: per-collection custom labels (#collections). Each list owns
// its own label set (unlike the instance-wide `tags` table), and a place can
// carry several labels. Used for grouping + filtering places within a list.
() => {
db.exec(`CREATE TABLE IF NOT EXISTS collection_labels (
id INTEGER PRIMARY KEY AUTOINCREMENT,
collection_id INTEGER NOT NULL REFERENCES collections(id) ON DELETE CASCADE,
name TEXT NOT NULL,
color TEXT DEFAULT '#6366f1',
sort_order INTEGER DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);`);
db.exec(`CREATE TABLE IF NOT EXISTS collection_place_labels (
collection_place_id INTEGER NOT NULL REFERENCES collection_places(id) ON DELETE CASCADE,
label_id INTEGER NOT NULL REFERENCES collection_labels(id) ON DELETE CASCADE,
PRIMARY KEY (collection_place_id, label_id)
);`);
db.exec('CREATE INDEX IF NOT EXISTS idx_collection_labels_collection ON collection_labels(collection_id);');
db.exec('CREATE INDEX IF NOT EXISTS idx_collection_place_labels_place ON collection_place_labels(collection_place_id);');
db.exec('CREATE INDEX IF NOT EXISTS idx_collection_place_labels_label ON collection_place_labels(label_id);');
},
];
if (currentVersion < migrations.length) {
+89
View File
@@ -26,6 +26,8 @@ function createTables(db: Database.Database): void {
synology_sid TEXT,
must_change_password INTEGER DEFAULT 0,
password_version INTEGER NOT NULL DEFAULT 0,
feed_token TEXT,
is_guest INTEGER NOT NULL DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
@@ -87,6 +89,7 @@ function createTables(db: Database.Database): void {
cover_image TEXT,
is_archived INTEGER DEFAULT 0,
reminder_days INTEGER DEFAULT 3,
feed_token TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
@@ -368,6 +371,92 @@ function createTables(db: Database.Database): void {
sort_order INTEGER NOT NULL DEFAULT 0
);
-- Collections addon tables
CREATE TABLE IF NOT EXISTS collections (
id INTEGER PRIMARY KEY AUTOINCREMENT,
owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
name TEXT NOT NULL,
description TEXT,
color TEXT DEFAULT '#6366f1',
icon TEXT DEFAULT 'Bookmark',
cover_image TEXT,
links TEXT,
sort_order INTEGER DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS collection_members (
id INTEGER PRIMARY KEY AUTOINCREMENT,
collection_id INTEGER NOT NULL REFERENCES collections(id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
status TEXT NOT NULL DEFAULT 'pending',
role TEXT NOT NULL DEFAULT 'editor',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
UNIQUE(collection_id, user_id)
);
CREATE TABLE IF NOT EXISTS collection_places (
id INTEGER PRIMARY KEY AUTOINCREMENT,
collection_id INTEGER NOT NULL REFERENCES collections(id) ON DELETE CASCADE,
owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
saved_by INTEGER REFERENCES users(id) ON DELETE SET NULL,
name TEXT NOT NULL,
description TEXT,
lat REAL,
lng REAL,
address TEXT,
category_id INTEGER REFERENCES categories(id) ON DELETE SET NULL,
price REAL,
currency TEXT,
notes TEXT,
image_url TEXT,
google_place_id TEXT,
google_ftid TEXT,
osm_id TEXT,
website TEXT,
phone TEXT,
status TEXT NOT NULL DEFAULT 'idea',
source_trip_id INTEGER,
source_place_id INTEGER,
links TEXT,
sort_order INTEGER DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS collection_place_tags (
collection_place_id INTEGER NOT NULL REFERENCES collection_places(id) ON DELETE CASCADE,
tag_id INTEGER NOT NULL REFERENCES tags(id) ON DELETE CASCADE,
PRIMARY KEY (collection_place_id, tag_id)
);
CREATE INDEX IF NOT EXISTS idx_collection_places_collection ON collection_places(collection_id);
CREATE INDEX IF NOT EXISTS idx_collection_members_user ON collection_members(user_id);
CREATE INDEX IF NOT EXISTS idx_collection_place_tags_place ON collection_place_tags(collection_place_id);
CREATE INDEX IF NOT EXISTS idx_collection_place_tags_tag ON collection_place_tags(tag_id);
-- Per-collection custom labels (distinct from the instance-wide tags table):
-- each list defines its own labels and every place can carry several.
CREATE TABLE IF NOT EXISTS collection_labels (
id INTEGER PRIMARY KEY AUTOINCREMENT,
collection_id INTEGER NOT NULL REFERENCES collections(id) ON DELETE CASCADE,
name TEXT NOT NULL,
color TEXT DEFAULT '#6366f1',
sort_order INTEGER DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS collection_place_labels (
collection_place_id INTEGER NOT NULL REFERENCES collection_places(id) ON DELETE CASCADE,
label_id INTEGER NOT NULL REFERENCES collection_labels(id) ON DELETE CASCADE,
PRIMARY KEY (collection_place_id, label_id)
);
CREATE INDEX IF NOT EXISTS idx_collection_labels_collection ON collection_labels(collection_id);
CREATE INDEX IF NOT EXISTS idx_collection_place_labels_place ON collection_place_labels(collection_place_id);
CREATE INDEX IF NOT EXISTS idx_collection_place_labels_label ON collection_place_labels(label_id);
CREATE TABLE IF NOT EXISTS day_accommodations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+25 -7
View File
@@ -15,8 +15,21 @@ function isOidcOnlyConfigured(): boolean {
function seedAdminAccount(db: Database.Database): void {
try {
const env_admin_email = process.env.ADMIN_EMAIL;
const env_admin_pw = process.env.ADMIN_PASSWORD;
const adminEnvProvided = !!(env_admin_email || env_admin_pw);
const userCount = (db.prepare('SELECT COUNT(*) as count FROM users').get() as { count: number }).count;
if (userCount > 0) return;
if (userCount > 0) {
// ADMIN_EMAIL/ADMIN_PASSWORD only take effect on the first run (empty database). Once a
// user exists they are silently ignored — a common trip-up: people add the vars after the
// fact, restart, nothing changes, and there is no hint why. Say so instead of staying silent.
if (adminEnvProvided) {
console.warn('[admin] ADMIN_EMAIL/ADMIN_PASSWORD are set, but users already exist — these only apply on first run (empty database) and are being ignored.');
console.warn('[admin] Change an existing password from Settings after signing in, reset the admin (see the Troubleshooting wiki), or start with an empty data volume to re-run setup.');
}
return;
}
// Demo mode seeds its own admin (admin@trek.app, username 'admin') right after this.
// Creating a first-run admin here would grab username 'admin' first and make the demo
@@ -35,15 +48,18 @@ function seedAdminAccount(db: Database.Database): void {
const bcrypt = require('bcryptjs');
const env_admin_email = process.env.ADMIN_EMAIL;
const env_admin_pw = process.env.ADMIN_PASSWORD;
let password;
let email;
let password: string;
let email: string;
if (env_admin_email && env_admin_pw) {
password = env_admin_pw;
email = env_admin_email;
} else {
// A partial config (only one of the two) is an easy mistake: neither value is used and a
// generated password is created instead. Flag it so the chosen credentials silently not
// working isn't a surprise.
if (adminEnvProvided) {
console.warn('[admin] Only one of ADMIN_EMAIL/ADMIN_PASSWORD is set — both are required for a custom admin. Falling back to admin@trek.local with a generated password (shown below).');
}
password = crypto.randomBytes(12).toString('base64url');
email = 'admin@trek.local';
}
@@ -104,6 +120,8 @@ function seedAddons(db: Database.Database): void {
{ id: 'collab', name: 'Collab', description: 'Notes, polls, and live chat for trip collaboration', type: 'trip', icon: 'Users', enabled: 1, sort_order: 6 },
{ id: 'journey', name: 'Journey', description: 'Trip tracking & travel journal — check-ins, photos, daily stories', type: 'global', icon: 'Compass', enabled: 0, sort_order: 35 },
{ id: 'airtrail', name: 'AirTrail', description: 'Sync flights from your self-hosted AirTrail instance', type: 'integration', icon: 'Plane', enabled: 0, sort_order: 14 },
{ id: 'llm_parsing', name: 'AI Parsing', description: 'LLM fallback for booking imports kitinerary cannot read', type: 'integration', icon: 'Sparkles', enabled: 0, sort_order: 15 },
{ id: 'collections', name: 'Collections', description: 'Personal place library — save places across trips into named lists, copy into any trip, share with others', type: 'global', icon: 'Bookmark', enabled: 0, sort_order: 16 },
];
const insertAddon = db.prepare('INSERT OR IGNORE INTO addons (id, name, description, type, icon, enabled, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?)');
for (const a of defaultAddons) insertAddon.run(a.id, a.name, a.description, a.type, a.icon, a.enabled, a.sort_order);
@@ -154,4 +172,4 @@ function runSeeds(db: Database.Database): void {
seedAddons(db);
}
export { runSeeds };
export { runSeeds, seedAdminAccount };
+1 -1
View File
@@ -66,7 +66,7 @@ function seedExampleTrips(db: Database.Database, adminId: number, demoId: number
const insertDay = db.prepare('INSERT INTO days (trip_id, day_number, date) VALUES (?, ?, ?)');
const insertPlace = db.prepare('INSERT INTO places (trip_id, name, lat, lng, address, category_id, place_time, duration_minutes, notes, image_url, google_place_id, website, phone) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
const insertAssignment = db.prepare('INSERT INTO day_assignments (day_id, place_id, order_index) VALUES (?, ?, ?)');
const insertPacking = db.prepare('INSERT INTO packing_items (trip_id, name, checked, category, sort_order) VALUES (?, ?, ?, ?, ?)');
const insertPacking = db.prepare('INSERT INTO packing_items (trip_id, name, checked, category, sort_order, updated_at) VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)');
const insertBudget = db.prepare('INSERT INTO budget_items (trip_id, category, name, total_price, persons, note) VALUES (?, ?, ?, ?, ?, ?)');
const insertReservation = db.prepare('INSERT INTO reservations (trip_id, day_id, title, reservation_time, confirmation_number, status, type, location) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
const insertMember = db.prepare('INSERT OR IGNORE INTO trip_members (trip_id, user_id, invited_by) VALUES (?, ?, ?)');
+22
View File
@@ -0,0 +1,22 @@
/**
* MCP tuning knobs from the environment (#1414). Pure parsers, kept free of
* imports so units can test them without dragging in the MCP SDK.
*/
/**
* Session idle TTL in SECONDS via MCP_SESSION_TTL, default 1 hour, clamped to
* 24h so a milliseconds-value typo can't produce a 1000-hour session.
*/
export function resolveSessionTtlMs(raw: string | undefined): number {
const parsed = Number.parseInt(raw ?? "");
return Number.isFinite(parsed) && parsed > 0 ? Math.min(parsed, 24 * 60 * 60) * 1000 : 60 * 60 * 1000;
}
/**
* SSE keep-alive interval in SECONDS via MCP_SSE_KEEPALIVE, default 25s
* (below common proxy idle timeouts like nginx-ingress's 60s). 0 disables.
*/
export function resolveKeepaliveMs(raw: string | undefined): number {
const parsed = Number.parseInt(raw ?? "");
return Number.isFinite(parsed) && parsed >= 0 ? parsed * 1000 : 25_000;
}
+34 -1
View File
@@ -10,6 +10,7 @@ import { ADDON_IDS } from '../addons';
import { registerResources } from './resources';
import { registerTools } from './tools';
import { McpSession, sessions, revokeUserSessions, revokeUserSessionsForClient } from './sessionManager';
import { resolveSessionTtlMs, resolveKeepaliveMs } from './config';
import { writeAudit, getClientIp } from '../services/auditLog';
import { getMcpSafeUrl } from '../services/notifications';
@@ -95,9 +96,39 @@ const STATIC_TOKEN_DEPRECATION_NOTICE =
'Please migrate to OAuth 2.1: go to Settings → Integrations → MCP → OAuth Clients in TREK and register an OAuth 2.1 application." ' +
'The actual tool result follows — answer the user\'s question as well.';
const SESSION_TTL_MS = 60 * 60 * 1000; // 1 hour
// Configurable session TTL + SSE keep-alive cadence (#1414); see mcp/config.ts.
const SESSION_TTL_MS = resolveSessionTtlMs(process.env.MCP_SESSION_TTL);
const sessionParsed = Number.parseInt(process.env.MCP_MAX_SESSION_PER_USER ?? "");
const MAX_SESSIONS_PER_USER = Number.isFinite(sessionParsed) && sessionParsed > 0 ? sessionParsed : 20;
const KEEPALIVE_MS = resolveKeepaliveMs(process.env.MCP_SSE_KEEPALIVE);
/**
* Write SSE comment frames on an interval while the response is an open
* event stream. A no-op for JSON/error responses (content-type gate) and for
* per-POST streams that end quickly (writableEnded gate). `touch` refreshes
* the session's lastActivity so the sweep never evicts a session whose GET
* stream is still connected.
*/
function armSseKeepalive(res: Response, touch?: () => void): void {
// With pings disabled (MCP_SSE_KEEPALIVE=0) an open stream must STILL count
// as session activity, or the sweep would evict a live idle client — keep
// the interval for touch() and only skip the writes.
const writePings = KEEPALIVE_MS > 0;
if (!writePings && !touch) return;
const intervalMs = writePings ? KEEPALIVE_MS : 25_000;
const timer = setInterval(() => {
if (!res.headersSent) return;
const ct = String(res.getHeader('content-type') ?? '');
if (!ct.includes('text/event-stream') || res.writableEnded || res.destroyed) {
clearInterval(timer);
return;
}
if (writePings) res.write(': keepalive\n\n');
touch?.();
}, intervalMs);
timer.unref();
res.once('close', () => clearInterval(timer));
}
const RATE_LIMIT_WINDOW_MS = 60 * 1000; // 1 minute
const parsed = Number.parseInt(process.env.MCP_RATE_LIMIT ?? "");
const RATE_LIMIT_MAX = Number.isFinite(parsed) && parsed > 0 ? parsed : 300; // requests per minute per user
@@ -255,6 +286,7 @@ export async function mcpHandler(req: Request, res: Response): Promise<void> {
}
session.lastActivity = Date.now();
logToolCallAudit(req, user.id, clientId);
armSseKeepalive(res, () => { session.lastActivity = Date.now(); });
try {
await session.transport.handleRequest(req, res, req.body);
} catch (err) {
@@ -318,6 +350,7 @@ export async function mcpHandler(req: Request, res: Response): Promise<void> {
});
logToolCallAudit(req, user.id, clientId);
armSseKeepalive(res);
try {
await server.connect(transport);
await transport.handleRequest(req, res, req.body);
+2 -1
View File
@@ -127,7 +127,8 @@ export function registerResources(server: McpServer, userId: number, scopes: str
async (uri, { tripId }) => {
const id = parseId(tripId);
if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
const items = listPackingItems(id);
// Hide other members' private items (#858) from the requesting user.
const items = listPackingItems(id, userId);
return jsonContent(uri.href, items);
}
);
+2 -2
View File
@@ -44,7 +44,7 @@ export function registerPackingTools(server: McpServer, userId: number, scopes:
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
const item = createPackingItem(tripId, { name, category: category || 'General' });
const item = createPackingItem(tripId, { name, category: category || 'General' }, userId);
safeBroadcast(tripId, 'packing:created', { item });
return ok({ item });
}
@@ -386,7 +386,7 @@ export function registerPackingTools(server: McpServer, userId: number, scopes:
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
const created = bulkImport(tripId, items);
const created = bulkImport(tripId, items, userId);
for (const item of created) safeBroadcast(tripId, 'packing:created', { item });
return ok({ items: created, count: created.length });
}
+38 -1
View File
@@ -2,7 +2,7 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
import { z } from 'zod';
import { canAccessTrip, db } from '../../db/database';
import { isDemoUser } from '../../services/authService';
import { deletePlacesMany, importGoogleList, importNaverList, listPlaces, createPlace, updatePlace, deletePlace } from '../../services/placeService';
import { deletePlacesMany, updatePlacesMany, importGoogleList, importNaverList, listPlaces, createPlace, updatePlace, deletePlace } from '../../services/placeService';
import { createAssignment, dayExists } from '../../services/assignmentService';
import { onPlaceDeleted } from '../../services/journeyService';
import { listCategories } from '../../services/categoryService';
@@ -269,4 +269,41 @@ export function registerPlaceTools(server: McpServer, userId: number, scopes: st
return ok({ deleted, count: deleted.length });
}
);
if (W) server.registerTool(
'bulk_update_places',
{
description: 'Update many places in a trip at once, applying the SAME field values to every listed place. Use this for sweeping edits — e.g. re-categorising a batch of POIs (set category_id for 80 places) — in a single call instead of one update_place per place. Only the fields you set are changed; everything else on each place is preserved. Use list_categories for category_id.',
inputSchema: {
tripId: z.number().int().positive(),
placeIds: z.array(z.number().int().positive()).min(1).max(500).describe('IDs of the places to update (from list_places)'),
category_id: z.number().int().positive().optional().describe('Category ID — use list_categories'),
price: z.number().optional(),
currency: z.string().length(3).optional(),
transport_mode: z.enum(['walking', 'driving', 'cycling', 'transit', 'flight']).optional(),
place_time: z.string().max(50).optional().describe('Scheduled time (e.g. "09:00")'),
end_time: z.string().max(50).optional().describe('End time (e.g. "11:00")'),
duration_minutes: z.number().int().positive().optional(),
notes: z.string().max(2000).optional(),
website: z.string().max(500).optional(),
phone: z.string().max(50).optional(),
description: z.string().max(2000).optional(),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ tripId, placeIds, category_id, price, currency, transport_mode, place_time, end_time, duration_minutes, notes, website, phone, description }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('place_edit', tripId, userId)) return permissionDenied();
const fields = { category_id, price, currency, transport_mode, place_time, end_time, duration_minutes, notes, website, phone, description };
if (Object.values(fields).every(v => v === undefined)) {
return { content: [{ type: 'text' as const, text: 'Provide at least one field to update.' }], isError: true };
}
const updated = updatePlacesMany(String(tripId), placeIds, fields);
for (const place of updated) safeBroadcast(tripId, 'place:updated', { place });
return ok({ count: updated.length, updatedIds: updated.map(p => p.id), skipped: placeIds.length - updated.length });
}
);
}
+2 -1
View File
@@ -77,7 +77,8 @@ ${days?.map((d: any, i: number) => `Day ${i + 1} (${d.date}): ${d.assignments?.l
if (!canAccessTrip(tripId, userId)) {
return { messages: [{ role: 'user', content: { type: 'text', text: 'Trip not found or access denied.' } }] };
}
const items = listPackingItems(tripId);
// Hide other members' private items (#858) from the requesting user.
const items = listPackingItems(tripId, userId);
if (!items.length) {
return { messages: [{ role: 'user', content: { type: 'text', text: 'No packing items found for this trip.' } }] };
}
+4 -1
View File
@@ -123,7 +123,10 @@ export function applyGlobalMiddleware(
// 'self' so same-origin file previews can embed PDFs via <object>/<embed>
// (Firefox/Chrome enforce object-src; 'none' broke inline PDF previews there).
objectSrc: ["'self'"],
frameSrc: ["'none'"],
// 'self' so the app can embed same-origin, sandboxed plugin frames
// (/plugin-frame/*). Those frames are sandboxed WITHOUT allow-same-origin,
// so they run at an opaque origin and get their own locked-down CSP.
frameSrc: ["'self'"],
frameAncestors: ["'self'"],
// Restrict <form> submission targets (form-action has no default-src
// fallback, so it must be set explicitly).
+15 -6
View File
@@ -135,11 +135,15 @@ export class AdminController {
@Get('invites')
listInvites() { return { invites: this.admin.listInvites() }; }
// Trips an admin can optionally bind a registration invite to (#1402).
@Get('invites/trips')
listInviteTrips() { return { trips: this.admin.listTripsForInvite() }; }
@Post('invites')
@HttpCode(201)
createInvite(@CurrentUser() user: User, @Body() body: unknown, @Req() req: Request) {
const result = this.admin.createInvite(user.id, body);
writeAudit({ userId: user.id, action: 'admin.invite_create', resource: String(result.inviteId), ip: getClientIp(req), details: { max_uses: result.uses, expires_in_days: result.expiresInDays } });
writeAudit({ userId: user.id, action: 'admin.invite_create', resource: String(result.inviteId), ip: getClientIp(req), details: { max_uses: result.uses, expires_in_days: result.expiresInDays, trip_id: result.tripId } });
return { invite: result.invite };
}
@@ -199,10 +203,12 @@ export class AdminController {
@Put('collab-features')
updateCollabFeatures(@CurrentUser() user: User, @Body() body: unknown, @Req() req: Request) {
const result = this.admin.updateCollabFeatures(body);
this.admin.invalidateMcpSessions();
writeAudit({ userId: user.id, action: 'admin.collab_features', ip: getClientIp(req), details: result });
return result;
const { features, changed } = this.admin.updateCollabFeatures(body);
// Collab flags gate MCP registration, but a no-op save must not tear down
// every live MCP session (#1414).
if (changed) this.admin.invalidateMcpSessions();
writeAudit({ userId: user.id, action: 'admin.collab_features', ip: getClientIp(req), details: features });
return features;
}
// ── Packing templates ──
@@ -268,7 +274,10 @@ export class AdminController {
updateAddon(@CurrentUser() user: User, @Param('id') id: string, @Body() body: unknown, @Req() req: Request) {
const result = ok(this.admin.updateAddon(id, body));
writeAudit({ userId: user.id, action: 'admin.addon_update', resource: String(id), ip: getClientIp(req), details: result.auditDetails });
this.admin.invalidateMcpSessions();
// Sessions only need re-creating when the registered MCP surface can
// actually change — an enabled-flip of an MCP-relevant addon. Config-only
// saves and photo-provider toggles used to kill every session (#1414).
if (result.mcpAffected) this.admin.invalidateMcpSessions();
return { addon: result.addon };
}
+1
View File
@@ -34,6 +34,7 @@ export class AdminService {
// Invites
listInvites() { return svc.listInvites(); }
listTripsForInvite() { return svc.listTripsForInvite(); }
createInvite(userId: number, body: unknown) { return svc.createInvite(userId, body as Parameters<typeof svc.createInvite>[1]); }
deleteInvite(id: string) { return svc.deleteInvite(id); }
+7 -1
View File
@@ -4,6 +4,7 @@ import { DatabaseModule } from './database/database.module';
import { HealthController } from './health/health.controller';
import { HealthService } from './health/health.service';
import { WeatherModule } from './weather/weather.module';
import { HelpModule } from './help/help.module';
import { AirportsModule } from './airports/airports.module';
import { ConfigModule } from './config/config.module';
import { SystemNoticesModule } from './system-notices/system-notices.module';
@@ -27,7 +28,11 @@ import { PhotosModule } from './photos/photos.module';
import { MemoriesModule } from './memories/memories.module';
import { AirtrailModule } from './integrations/airtrail.module';
import { JourneyModule } from './journey/journey.module';
import { CollectionsModule } from './collections/collections.module';
import { ShareModule } from './share/share.module';
import { TripInviteModule } from './trip-invite/trip-invite.module';
import { TransitModule } from './transit/transit.module';
import { FeedsModule } from './feeds/feeds.module';
import { SettingsModule } from './settings/settings.module';
import { BackupModule } from './backup/backup.module';
import { BookingImportModule } from './booking-import/booking-import.module';
@@ -36,6 +41,7 @@ import { OidcModule } from './oidc/oidc.module';
import { OauthModule } from './oauth/oauth.module';
import { AdminModule } from './admin/admin.module';
import { AddonsModule } from './addons/addons.module';
import { PluginsModule } from './plugins/plugins.module';
import { TrekExceptionFilter } from './common/trek-exception.filter';
import { SpaFallbackFilter } from './platform/spa-fallback.filter';
import { IdempotencyInterceptor } from './common/idempotency.interceptor';
@@ -46,7 +52,7 @@ import { IdempotencyInterceptor } from './common/idempotency.interceptor';
* migrated.
*/
@Module({
imports: [DatabaseModule, WeatherModule, AirportsModule, ConfigModule, SystemNoticesModule, MapsModule, CategoriesModule, TagsModule, NotificationsModule, AtlasModule, VacayModule, PackingModule, TodoModule, BudgetModule, ReservationsModule, DaysModule, AssignmentsModule, PlacesModule, TripsModule, CollabModule, FilesModule, PhotosModule, MemoriesModule, AirtrailModule, JourneyModule, ShareModule, SettingsModule, BackupModule, AuthModule, OidcModule, OauthModule, AdminModule, AddonsModule, BookingImportModule],
imports: [DatabaseModule, WeatherModule, HelpModule, AirportsModule, ConfigModule, SystemNoticesModule, MapsModule, CategoriesModule, TagsModule, NotificationsModule, AtlasModule, VacayModule, PackingModule, TodoModule, BudgetModule, ReservationsModule, DaysModule, AssignmentsModule, PlacesModule, TripsModule, CollabModule, FilesModule, PhotosModule, MemoriesModule, AirtrailModule, JourneyModule, CollectionsModule, ShareModule, TripInviteModule, TransitModule, FeedsModule, SettingsModule, BackupModule, AuthModule, OidcModule, OauthModule, AdminModule, AddonsModule, PluginsModule, BookingImportModule],
controllers: [HealthController],
providers: [
HealthService,
@@ -4,6 +4,7 @@ import { AuthService } from './auth.service';
import { RateLimitService } from './rate-limit.service';
import { OptionalJwtGuard } from './optional-jwt.guard';
import { writeAudit, getClientIp } from '../../services/auditLog';
import { willDropSecureCookie } from '../../services/cookie';
import type { User } from '../../types';
const WINDOW = 15 * 60 * 1000;
@@ -88,7 +89,13 @@ export class AuthPublicController {
return { mfa_required: true, mfa_token: result.mfa_token };
}
this.auth.setAuthCookie(res, result.token!, req, result.remember);
return { token: result.token, user: result.user };
return {
token: result.token,
user: result.user,
// Surfaced so the client can explain the plain-HTTP cookie gotcha instead
// of the user hitting a bare "Access token required" on the next request.
...(willDropSecureCookie(req) ? { insecureCookie: true } : {}),
};
}
@Post('forgot-password')
@@ -1,6 +1,7 @@
import {
Controller,
Post,
Get,
Body,
Param,
Headers,
@@ -15,7 +16,9 @@ import type { User } from '../../types';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
import { BookingImportService } from './booking-import.service';
import type { BookingImportPreviewItem, BookingImportPreviewResponse, BookingImportConfirmResponse } from '@trek/shared';
import { ImportJobsService } from './import-jobs.service';
import { bookingImportModeSchema } from '@trek/shared';
import type { BookingImportPreviewItem, BookingImportPreviewResponse, BookingImportConfirmResponse, BookingImportMode } from '@trek/shared';
const ACCEPTED_EXTS = new Set(['.eml', '.pdf', '.pkpass', '.html', '.htm', '.txt']);
const MAX_FILE_BYTES = 10 * 1024 * 1024;
@@ -29,7 +32,10 @@ const UPLOAD = {
@Controller('api/trips/:tripId/reservations/import')
@UseGuards(JwtAuthGuard)
export class BookingImportController {
constructor(private readonly bookingImport: BookingImportService) {}
constructor(
private readonly bookingImport: BookingImportService,
private readonly importJobs: ImportJobsService,
) {}
private requireTrip(tripId: string, user: User) {
const trip = this.bookingImport.verifyTripAccess(tripId, user.id);
@@ -43,6 +49,31 @@ export class BookingImportController {
}
}
/** Shared validation for both the sync and async import endpoints; returns the parsed mode. */
private validateImport(tripId: string, user: User, files: Express.Multer.File[] | undefined, rawMode?: string): BookingImportMode {
const trip = this.requireTrip(tripId, user);
this.requireEdit(trip, user);
const modeResult = bookingImportModeSchema.safeParse(rawMode ?? 'no-ai');
if (!modeResult.success) throw new HttpException({ error: 'Invalid mode' }, 400);
const mode = modeResult.data;
if (mode === 'force-ai' && !this.bookingImport.aiAvailable(user.id)) {
throw new HttpException({ error: 'AI parsing is not configured' }, 409);
}
if (mode === 'no-ai' && !this.bookingImport.isAvailable()) {
throw new HttpException({ error: 'KItinerary extractor is not available on this server' }, 503);
}
if (!files || files.length === 0) throw new HttpException({ error: 'No files uploaded' }, 400);
for (const f of files) {
const ext = f.originalname.toLowerCase().slice(f.originalname.lastIndexOf('.'));
if (!ACCEPTED_EXTS.has(ext)) {
throw new HttpException({ error: `Unsupported file type: ${f.originalname}. Accepted: EML, PDF, PKPass, HTML, TXT` }, 400);
}
}
return mode;
}
/**
* POST /api/trips/:tripId/reservations/import/booking
* Accepts up to 5 booking confirmation files (EML, PDF, PKPass, HTML, TXT).
@@ -54,28 +85,42 @@ export class BookingImportController {
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@UploadedFiles() files: Express.Multer.File[] | undefined,
) {
const trip = this.requireTrip(tripId, user);
this.requireEdit(trip, user);
@Body('mode') rawMode?: string,
): Promise<BookingImportPreviewResponse> {
const mode = this.validateImport(tripId, user, files, rawMode);
return this.bookingImport.preview(files!, mode, user.id);
}
if (!this.bookingImport.isAvailable()) {
throw new HttpException({ error: 'KItinerary extractor is not available on this server' }, 503);
}
/**
* POST /api/trips/:tripId/reservations/import/booking/async
* Same input as /booking, but returns a job id immediately and parses in the
* background. Progress + completion are pushed over the user's WebSocket
* (import:progress / import:done / import:error). Lets the upload modal close at
* once and a background widget track the work while the user keeps navigating.
*/
@Post('booking/async')
@UseInterceptors(FilesInterceptor('files', MAX_FILES, UPLOAD))
async previewAsync(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@UploadedFiles() files: Express.Multer.File[] | undefined,
@Body('mode') rawMode?: string,
): Promise<{ jobId: string }> {
const mode = this.validateImport(tripId, user, files, rawMode);
const jobId = this.importJobs.start(tripId, files!, mode, user.id);
return { jobId };
}
if (!files || files.length === 0) {
throw new HttpException({ error: 'No files uploaded' }, 400);
}
// Validate extensions
for (const f of files) {
const ext = f.originalname.toLowerCase().slice(f.originalname.lastIndexOf('.'));
if (!ACCEPTED_EXTS.has(ext)) {
throw new HttpException({ error: `Unsupported file type: ${f.originalname}. Accepted: EML, PDF, PKPass, HTML, TXT` }, 400);
}
}
const result: BookingImportPreviewResponse = await this.bookingImport.preview(files);
return result;
/**
* GET /api/trips/:tripId/reservations/import/jobs/:jobId
* Poll a background import job — recovery path for a client that missed the
* WebSocket push (navigation, reconnect). 404 once the job has expired.
*/
@Get('jobs/:jobId')
async jobStatus(@CurrentUser() user: User, @Param('jobId') jobId: string) {
const job = this.importJobs.get(jobId, user.id);
if (!job) throw new HttpException({ error: 'Job not found' }, 404);
return { status: job.status, done: job.done, total: job.total, result: job.result, error: job.error };
}
/**
@@ -1,11 +1,14 @@
import { Module } from '@nestjs/common';
import { BookingImportController } from './booking-import.controller';
import { BookingImportService } from './booking-import.service';
import { ImportJobsService } from './import-jobs.service';
import { KitineraryExtractorService } from './kitinerary-extractor.service';
import { FeaturesController } from './features.controller';
import { LlmParseModule } from '../llm-parse/llm-parse.module';
@Module({
imports: [LlmParseModule],
controllers: [BookingImportController, FeaturesController],
providers: [BookingImportService, KitineraryExtractorService],
providers: [BookingImportService, KitineraryExtractorService, ImportJobsService],
})
export class BookingImportModule {}
@@ -4,30 +4,47 @@ import { checkPermission } from '../../services/permissions';
import { verifyTripAccess } from '../../services/tripAccess';
import { createReservation } from '../../services/reservationService';
import { createPlace } from '../../services/placeService';
import { createBudgetItem } from '../../services/budgetService';
import { isAddonEnabled } from '../../services/adminService';
import { ADDON_IDS } from '../../addons';
import { searchNominatim } from '../../services/mapsService';
import { db } from '../../db/database';
import type { User } from '../../types';
import { KitineraryExtractorService } from './kitinerary-extractor.service';
import { LlmParseService } from '../llm-parse/llm-parse.service';
import { mapReservations } from './kitinerary-mapper';
import type { BookingImportPreviewItem, BookingImportPreviewResponse, BookingImportConfirmResponse, Reservation } from '@trek/shared';
import type { ParsedBookingItem } from './kitinerary.types';
import { typeToCostCategory } from '@trek/shared';
import type { BookingImportPreviewItem, BookingImportPreviewResponse, BookingImportConfirmResponse, BookingImportMode, BookingImportFileReport, Reservation } from '@trek/shared';
import type { ParsedBookingItem, KiReservation } from './kitinerary.types';
function resolveDayId(tripId: string, iso: string | null | undefined): number | null {
if (!iso) return null;
const date = iso.slice(0, 10);
if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) return null;
const row = db.prepare('SELECT id FROM days WHERE trip_id = ? AND date = ? LIMIT 1').get(tripId, date) as { id: number } | undefined;
return row?.id ?? null;
const exact = db.prepare('SELECT id FROM days WHERE trip_id = ? AND date = ? LIMIT 1').get(tripId, date) as { id: number } | undefined;
if (exact) return exact.id;
// Clamp to the nearest trip day so an out-of-range / unmatched check-in still
// resolves and the accommodation row is inserted.
const nearest = db.prepare('SELECT id FROM days WHERE trip_id = ? ORDER BY ABS(JULIANDAY(date) - JULIANDAY(?)) ASC, date ASC LIMIT 1').get(tripId, date) as { id: number } | undefined;
return nearest?.id ?? null;
}
@Injectable()
export class BookingImportService {
constructor(private readonly extractor: KitineraryExtractorService) {}
constructor(
private readonly extractor: KitineraryExtractorService,
private readonly llmParse: LlmParseService,
) {}
isAvailable(): boolean {
return this.extractor.isAvailable();
}
/** True when the LLM fallback is enabled and configured for this user. */
aiAvailable(userId: number): boolean {
return this.llmParse.isAvailable(userId);
}
verifyTripAccess(tripId: string, userId: number) {
return verifyTripAccess(tripId, userId);
}
@@ -37,37 +54,69 @@ export class BookingImportService {
}
/**
* Parse uploaded files through kitinerary-extractor and return a preview list.
* Does NOT persist anything.
* Parse uploaded files and return a preview list. Does NOT persist anything.
* Runs kitinerary first; depending on `mode`, falls back to the LLM:
* - no-ai: kitinerary only
* - fallback-on-empty: LLM for files kitinerary returns nothing for
* - force-ai: LLM on every file (kitinerary skipped)
* LLM-derived items are flagged needs_review. Per-file AI usage is reported.
*/
async preview(files: Express.Multer.File[]): Promise<BookingImportPreviewResponse> {
if (!this.extractor.isAvailable()) {
async preview(
files: Express.Multer.File[],
mode: BookingImportMode,
userId: number,
onProgress?: (done: number, total: number, fileName: string) => void,
): Promise<BookingImportPreviewResponse> {
const kitineraryAvailable = this.extractor.isAvailable();
const aiAvailable = this.llmParse.isAvailable(userId);
if (!kitineraryAvailable && !aiAvailable) {
throw new HttpException({ error: 'KItinerary extractor is not available on this server' }, 503);
}
const allItems: ParsedBookingItem[] = [];
const allWarnings: string[] = [];
const fileReports: BookingImportFileReport[] = [];
let processed = 0;
for (const file of files) {
let kiItems;
try {
kiItems = await this.extractor.extract(file.buffer, file.originalname);
} catch (err) {
allWarnings.push(`${file.originalname}: extraction failed — ${err instanceof Error ? err.message : String(err)}`);
continue;
let kiItems: KiReservation[] = [];
let aiUsed = false;
// Stage 1: kitinerary (skipped entirely when forcing AI).
if (mode !== 'force-ai' && kitineraryAvailable) {
try {
kiItems = await this.extractor.extract(file.buffer, file.originalname);
} catch (err) {
allWarnings.push(`${file.originalname}: extraction failed — ${err instanceof Error ? err.message : String(err)}`);
}
}
// Stage 1b: LLM fallback.
const runLlm = aiAvailable && (mode === 'force-ai' || (mode === 'fallback-on-empty' && kiItems.length === 0));
if (runLlm) {
aiUsed = true;
const llm = await this.llmParse.parse({ buffer: file.buffer, originalName: file.originalname }, userId);
kiItems = llm.kiItems;
allWarnings.push(...llm.warnings);
}
fileReports.push({ fileName: file.originalname, aiAvailable, aiUsed });
if (kiItems.length === 0) {
allWarnings.push(`${file.originalname}: no reservations found`);
continue;
} else {
const { items, warnings } = mapReservations(kiItems, file.originalname);
// LLM extraction is less certain than kitinerary — always flag for review.
if (aiUsed) for (const it of items) it.needs_review = true;
allItems.push(...items);
allWarnings.push(...warnings);
}
const { items, warnings } = mapReservations(kiItems, file.originalname);
allItems.push(...items);
allWarnings.push(...warnings);
// Report per-file progress so a background import can drive a live widget.
onProgress?.(++processed, files.length, file.originalname);
}
return { items: allItems, warnings: allWarnings };
return { items: allItems, warnings: allWarnings, files: fileReports };
}
/**
@@ -126,6 +175,28 @@ export class BookingImportService {
broadcast(tripId, 'place:created', { place }, socketId);
}
// Geocode transport endpoints (stations/stops/terminals/rental desks) that
// arrived without coords, so the route draws and map pins appear. The LLM
// and kitinerary rarely supply geo for non-airport endpoints.
if (Array.isArray(reservationData.endpoints)) {
for (const ep of reservationData.endpoints) {
if ((ep.lat == null || ep.lng == null) && ep.name) {
try {
const hit = (await searchNominatim(ep.name))[0];
if (hit?.lat != null && hit?.lng != null) {
ep.lat = hit.lat;
ep.lng = hit.lng;
}
} catch {
// geocoding failure is non-fatal
}
}
}
// Persist only coord'd endpoints (reservation_endpoints needs lat/lng);
// ungeocodable ones still appeared in the preview's From→To.
reservationData.endpoints = reservationData.endpoints.filter((ep) => ep.lat != null && ep.lng != null);
}
// Build create_accommodation for hotel reservations.
// start_day_id / end_day_id are resolved from check-in/out ISO dates so
// the accommodation row is actually inserted (createReservation gates on them).
@@ -154,6 +225,33 @@ export class BookingImportService {
broadcast(tripId, 'accommodation:created', {}, socketId);
}
// Turn an extracted price into a real linked cost (Costs addon), so the
// booking shows up as an expense — not just a price in metadata.
if (isAddonEnabled(ADDON_IDS.BUDGET)) {
const meta =
reservationData.metadata && typeof reservationData.metadata === 'object'
? (reservationData.metadata as Record<string, unknown>)
: null;
const price = meta && meta.price != null ? Number(meta.price) : NaN;
if (Number.isFinite(price) && price > 0) {
try {
const budgetItem = createBudgetItem(tripId, {
category: typeToCostCategory(item.type),
name: item.title,
total_price: price,
currency: meta && typeof meta.priceCurrency === 'string' ? meta.priceCurrency : null,
reservation_id: reservation.id,
});
broadcast(tripId, 'budget:created', { item: budgetItem }, socketId);
} catch (err) {
console.error(
`[booking-import] Failed to create cost for "${item.title}":`,
err instanceof Error ? err.message : err,
);
}
}
}
created.push(reservation);
} catch (err) {
console.error(`[booking-import] Failed to create reservation "${item.title}":`, err instanceof Error ? err.message : err);
@@ -1,5 +1,7 @@
import { Controller, Get } from '@nestjs/common';
import { KitineraryExtractorService } from './kitinerary-extractor.service';
import { isAddonEnabled } from '../../services/adminService';
import { ADDON_IDS } from '../../addons';
/** Exposes server feature flags consumed by the frontend to show/hide optional UI. */
@Controller('api/health')
@@ -10,6 +12,9 @@ export class FeaturesController {
features() {
return {
bookingImport: this.extractor.isAvailable(),
// Addon-level flag (per-user config availability is reported per-file in
// the preview response). Drives whether the client shows AI affordances.
aiParsing: isAddonEnabled(ADDON_IDS.LLM_PARSING),
};
}
}
@@ -0,0 +1,85 @@
import { Injectable } from '@nestjs/common';
import { randomUUID } from 'node:crypto';
import { broadcastToUser } from '../../websocket';
import { BookingImportService } from './booking-import.service';
import type { BookingImportMode, BookingImportPreviewResponse } from '@trek/shared';
type JobStatus = 'running' | 'done' | 'error';
interface ImportJob {
id: string;
tripId: string;
userId: number;
status: JobStatus;
done: number;
total: number;
result?: BookingImportPreviewResponse;
error?: string;
createdAt: number;
}
// Keep a finished job around briefly so a client that missed the WebSocket push
// (navigation, reconnect) can still GET its result.
const JOB_TTL_MS = 10 * 60_000;
/**
* Runs a booking-import parse OFF the request: the controller returns a job id
* immediately, the parse continues here, and progress/completion are pushed to the
* user's sockets via `broadcastToUser` (which reaches them on ANY page, not just the
* trip room). This is what lets the upload modal close at once and a background widget
* track the work while the user keeps navigating. The actual parsing is the same
* `BookingImportService.preview` the synchronous endpoint uses.
*/
@Injectable()
export class ImportJobsService {
private readonly jobs = new Map<string, ImportJob>();
/** Tail of each user's job chain — parses run one at a time per user, not all at once. */
private readonly chains = new Map<number, Promise<void>>();
constructor(private readonly bookingImport: BookingImportService) {}
/** Create a job and queue it behind the user's other parses; returns the job id at once. */
start(tripId: string, files: Express.Multer.File[], mode: BookingImportMode, userId: number): string {
const id = randomUUID();
const job: ImportJob = { id, tripId, userId, status: 'running', done: 0, total: files.length, createdAt: Date.now() };
this.jobs.set(id, job);
// Chain onto the user's previous parse so they run sequentially (one CPU-heavy
// inference at a time), while the request returns immediately.
const prev = this.chains.get(userId) ?? Promise.resolve();
const next = prev.then(() => this.run(job, files, mode)).catch(() => {});
this.chains.set(userId, next);
void next.finally(() => {
if (this.chains.get(userId) === next) this.chains.delete(userId);
});
return id;
}
get(id: string, userId: number): ImportJob | undefined {
const job = this.jobs.get(id);
return job && job.userId === userId ? job : undefined;
}
private async run(job: ImportJob, files: Express.Multer.File[], mode: BookingImportMode): Promise<void> {
this.push(job, 'import:progress', { status: 'running', done: 0, total: job.total });
try {
const result = await this.bookingImport.preview(files, mode, job.userId, (done, total, fileName) => {
job.done = done;
this.push(job, 'import:progress', { status: 'running', done, total, fileName });
});
job.status = 'done';
job.result = result;
this.push(job, 'import:done', { result });
} catch (err) {
job.status = 'error';
job.error = err instanceof Error ? err.message : String(err);
this.push(job, 'import:error', { message: job.error });
} finally {
const id = job.id;
setTimeout(() => this.jobs.delete(id), JOB_TTL_MS).unref?.();
}
}
private push(job: ImportJob, type: string, payload: Record<string, unknown>): void {
broadcastToUser(job.userId, { type, jobId: job.id, tripId: job.tripId, ...payload });
}
}
@@ -189,8 +189,9 @@ function mapTrain(r: KiReservation, source: ParsedBookingItem['source']): Parsed
const endpoints: ParsedEndpoint[] = [];
const dc = coords(t.departureStation?.geo);
const ac = coords(t.arrivalStation?.geo);
if (dc) endpoints.push({ role: 'from', sequence: 0, name: depName, code: null, lat: dc.lat, lng: dc.lng, timezone: null, local_time: depTime, local_date: depDate });
if (ac) endpoints.push({ role: 'to', sequence: 1, name: arrName, code: null, lat: ac.lat, lng: ac.lng, timezone: null, local_time: arrTime, local_date: arrDate });
// Push named endpoints even without coords — confirm() geocodes them later.
if (t.departureStation?.name) endpoints.push({ role: 'from', sequence: 0, name: depName, code: null, lat: dc?.lat ?? null, lng: dc?.lng ?? null, timezone: null, local_time: depTime, local_date: depDate });
if (t.arrivalStation?.name) endpoints.push({ role: 'to', sequence: 1, name: arrName, code: null, lat: ac?.lat ?? null, lng: ac?.lng ?? null, timezone: null, local_time: arrTime, local_date: arrDate });
return {
type: 'train',
@@ -220,10 +221,10 @@ function mapBus(r: KiReservation, source: ParsedBookingItem['source']): ParsedBo
const endpoints: ParsedEndpoint[] = [];
const dc = coords(b.departureBusStop?.geo);
const ac = coords(b.arrivalBusStop?.geo);
if (dc) endpoints.push({ role: 'from', sequence: 0, name: depName, code: null, lat: dc.lat, lng: dc.lng, timezone: null, local_time: depTime, local_date: depDate });
if (ac) endpoints.push({ role: 'to', sequence: 1, name: arrName, code: null, lat: ac.lat, lng: ac.lng, timezone: null, local_time: arrTime, local_date: arrDate });
if (b.departureBusStop?.name) endpoints.push({ role: 'from', sequence: 0, name: depName, code: null, lat: dc?.lat ?? null, lng: dc?.lng ?? null, timezone: null, local_time: depTime, local_date: depDate });
if (b.arrivalBusStop?.name) endpoints.push({ role: 'to', sequence: 1, name: arrName, code: null, lat: ac?.lat ?? null, lng: ac?.lng ?? null, timezone: null, local_time: arrTime, local_date: arrDate });
return { type: 'train', title, reservation_time: toIsoString(b.departureTime), reservation_end_time: toIsoString(b.arrivalTime), confirmation_number: r.reservationNumber ?? null, endpoints, needs_review: endpoints.length < 2, source };
return { type: 'bus', title, reservation_time: toIsoString(b.departureTime), reservation_end_time: toIsoString(b.arrivalTime), confirmation_number: r.reservationNumber ?? null, metadata: busId ? { bus_number: busId } : undefined, endpoints, needs_review: endpoints.length < 2, source };
}
function mapBoat(r: KiReservation, source: ParsedBookingItem['source']): ParsedBookingItem | null {
@@ -240,10 +241,10 @@ function mapBoat(r: KiReservation, source: ParsedBookingItem['source']): ParsedB
const endpoints: ParsedEndpoint[] = [];
const dc = coords(b.departureBoatTerminal?.geo);
const ac = coords(b.arrivalBoatTerminal?.geo);
if (dc) endpoints.push({ role: 'from', sequence: 0, name: depName, code: null, lat: dc.lat, lng: dc.lng, timezone: null, local_time: depTime, local_date: depDate });
if (ac) endpoints.push({ role: 'to', sequence: 1, name: arrName, code: null, lat: ac.lat, lng: ac.lng, timezone: null, local_time: arrTime, local_date: arrDate });
if (b.departureBoatTerminal?.name) endpoints.push({ role: 'from', sequence: 0, name: depName, code: null, lat: dc?.lat ?? null, lng: dc?.lng ?? null, timezone: null, local_time: depTime, local_date: depDate });
if (b.arrivalBoatTerminal?.name) endpoints.push({ role: 'to', sequence: 1, name: arrName, code: null, lat: ac?.lat ?? null, lng: ac?.lng ?? null, timezone: null, local_time: arrTime, local_date: arrDate });
return { type: 'cruise', title, reservation_time: toIsoString(b.departureTime), reservation_end_time: toIsoString(b.arrivalTime), confirmation_number: r.reservationNumber ?? null, endpoints, source };
return { type: 'cruise', title, reservation_time: toIsoString(b.departureTime), reservation_end_time: toIsoString(b.arrivalTime), confirmation_number: r.reservationNumber ?? null, endpoints, needs_review: endpoints.length < 2, source };
}
function mapLodging(r: KiReservation, source: ParsedBookingItem['source']): ParsedBookingItem | null {
@@ -287,10 +288,31 @@ function mapRentalCar(r: KiReservation, source: ParsedBookingItem['source']): Pa
const title = [company, carName].filter(Boolean).join(' — ') || 'Rental Car';
const pickup = r.pickupLocation as KiReservation['pickupLocation'];
const dropoff = r.dropoffLocation as KiReservation['dropoffLocation'];
const pc = coords(pickup?.geo);
const drc = coords(dropoff?.geo);
const venue: ParsedVenue | undefined = pickup?.name ? { name: pickup.name, ...(pc ?? {}), address: formatAddress(pickup.address) ?? undefined } : undefined;
return { type: 'car', title, reservation_time: toIsoString(r.pickupTime), reservation_end_time: toIsoString(r.dropoffTime), confirmation_number: r.reservationNumber ?? null, ...(venue ? { _venue: venue } : {}), source };
// Pickup → return as from/to endpoints (coords optional; confirm() geocodes).
const { date: puDate, time: puTime } = splitIso(r.pickupTime);
const { date: doDate, time: doTime } = splitIso(r.dropoffTime);
const endpoints: ParsedEndpoint[] = [];
if (pickup?.name) endpoints.push({ role: 'from', sequence: 0, name: pickup.name, code: null, lat: pc?.lat ?? null, lng: pc?.lng ?? null, timezone: null, local_time: puTime, local_date: puDate });
if (dropoff?.name) endpoints.push({ role: 'to', sequence: 1, name: dropoff.name, code: null, lat: drc?.lat ?? null, lng: drc?.lng ?? null, timezone: null, local_time: doTime, local_date: doDate });
return {
type: 'car',
title,
reservation_time: toIsoString(r.pickupTime),
reservation_end_time: toIsoString(r.dropoffTime),
confirmation_number: r.reservationNumber ?? null,
location: formatAddress(pickup?.address) ?? pickup?.name ?? null,
...(company ? { metadata: { rental_company: company } } : {}),
endpoints,
needs_review: endpoints.length < 2,
...(venue ? { _venue: venue } : {}),
source,
};
}
function mapEvent(r: KiReservation, source: ParsedBookingItem['source']): ParsedBookingItem | null {
@@ -299,15 +321,42 @@ function mapEvent(r: KiReservation, source: ParsedBookingItem['source']): Parsed
const loc = e.location;
const c = coords(loc?.geo);
const venue: ParsedVenue | undefined = loc?.name ? { name: loc.name, ...(c ?? {}), address: formatAddress(loc.address) ?? undefined } : undefined;
const venue: ParsedVenue | undefined = loc?.name ? { name: loc.name, ...(c ?? {}), address: formatAddress(loc.address) ?? undefined, website: loc.url ?? undefined, phone: loc.telephone ?? undefined } : undefined;
return { type: 'event', title: e.name, reservation_time: toIsoString(e.startDate), reservation_end_time: toIsoString(e.endDate), confirmation_number: r.reservationNumber ?? null, location: loc ? (formatAddress(loc.address) ?? loc.name ?? null) : null, ...(venue ? { _venue: venue } : {}), source };
return { type: 'event', title: e.name, reservation_time: toIsoString(e.startDate ?? r.startTime), reservation_end_time: toIsoString(e.endDate ?? r.endTime), confirmation_number: r.reservationNumber ?? null, location: loc ? (formatAddress(loc.address) ?? loc.name ?? null) : null, ...(venue ? { _venue: venue } : {}), source };
}
// ---------------------------------------------------------------------------
// Public
// ---------------------------------------------------------------------------
/** Merge seat/class/platform/price into an item's metadata (type-agnostic).
* Models name these inconsistently and sometimes nest them under reservationFor,
* so check both levels and common aliases. The item's own metadata wins. */
function applyCommonMeta(item: ParsedBookingItem, r: KiReservation): ParsedBookingItem {
const rf = (r.reservationFor && typeof r.reservationFor === 'object' ? r.reservationFor : {}) as Record<string, unknown>;
const pick = (...keys: string[]): unknown => {
for (const k of keys) {
const v = (r as Record<string, unknown>)[k] ?? rf[k];
if (v != null && v !== '') return v;
}
return undefined;
};
const m: Record<string, unknown> = {};
const seat = pick('seat', 'seatNumber');
if (seat != null) m.seat = String(seat);
const cls = pick('class', 'bookingClass', 'fareClass', 'serviceClass', 'seatingType');
if (cls != null) m.class = String(cls);
const platform = pick('platform', 'departurePlatform');
if (platform != null) m.platform = String(platform);
const price = pick('price', 'priceAmount', 'totalPrice', 'total');
if (price != null) m.price = price;
const cur = pick('priceCurrency', 'priceCurrencyISO4217Code', 'currency');
if (cur != null) m.priceCurrency = String(cur);
if (Object.keys(m).length) item.metadata = { ...m, ...(item.metadata ?? {}) };
return item;
}
export function mapReservations(kiItems: KiReservation[], fileName: string): { items: ParsedBookingItem[]; warnings: string[] } {
const items: ParsedBookingItem[] = [];
const warnings: string[] = [];
@@ -331,7 +380,7 @@ export function mapReservations(kiItems: KiReservation[], fileName: string): { i
group.push(kiItems[++i]);
}
item = group.length > 1 ? mapFlightGroup(group, source) : mapFlight(r, source);
if (item) items.push(item);
if (item) items.push(applyCommonMeta(item, r));
continue;
}
@@ -348,7 +397,7 @@ export function mapReservations(kiItems: KiReservation[], fileName: string): { i
warnings.push(`Unknown type "${r['@type']}" in ${fileName}[${i}] — skipped`);
}
if (item) items.push(item);
if (item) items.push(applyCommonMeta(item, r));
}
return { items, warnings };
@@ -112,6 +112,8 @@ export interface KiEventVenue {
name?: string;
address?: string | KiAddress;
geo?: KiGeo;
telephone?: string;
url?: string;
}
export interface KiEvent {
@@ -134,6 +136,12 @@ export interface KiReservation {
endTime?: KiDateTimeish;
reservationFor?: Record<string, unknown>;
pickupLocation?: KiEventVenue;
dropoffLocation?: KiEventVenue;
seat?: string;
class?: string;
platform?: string;
price?: number | string;
priceCurrency?: string;
[key: string]: unknown;
}
@@ -143,8 +151,8 @@ export interface ParsedEndpoint {
sequence: number;
name: string;
code: string | null;
lat: number;
lng: number;
lat: number | null;
lng: number | null;
timezone: string | null;
local_time: string | null;
local_date: string | null;
@@ -0,0 +1,18 @@
import { CanActivate, HttpException, Injectable } from '@nestjs/common';
import { isAddonEnabled } from '../../services/adminService';
import { ADDON_IDS } from '../../addons';
/**
* Mirrors the addon mount gate: when the Collections addon is disabled the whole
* route group answers 404, regardless of auth. Declared before JwtAuthGuard so
* the addon check wins over the 401, exactly as the Journey addon guard does.
*/
@Injectable()
export class CollectionsAddonGuard implements CanActivate {
canActivate(): boolean {
if (!isAddonEnabled(ADDON_IDS.COLLECTIONS)) {
throw new HttpException({ error: 'Collections addon is not enabled' }, 404);
}
return true;
}
}
@@ -0,0 +1,356 @@
import {
Body,
Controller,
Delete,
Get,
Headers,
HttpCode,
HttpException,
Param,
Patch,
Post,
Query,
UploadedFile,
UseGuards,
UseInterceptors,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import type { Request } from 'express';
import { diskStorage } from 'multer';
import path from 'path';
import fs from 'fs';
import { v4 as uuidv4 } from 'uuid';
import type { User } from '../../types';
import { CollectionsService } from './collections.service';
import { CollectionsAddonGuard } from './collections-addon.guard';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
import { ZodValidationPipe } from '../common/zod-validation.pipe';
import { isDemoEmail } from '../../services/demo';
import {
collectionCreateRequestSchema,
collectionUpdateRequestSchema,
collectionSavePlaceRequestSchema,
collectionSaveFromTripRequestSchema,
collectionSaveFromTripManyRequestSchema,
collectionPlaceUpdateRequestSchema,
collectionSetStatusRequestSchema,
collectionCopyToTripRequestSchema,
collectionInviteRequestSchema,
collectionInviteActionRequestSchema,
collectionInviteCancelRequestSchema,
collectionRemoveMemberRequestSchema,
collectionSetMemberRoleRequestSchema,
collectionLabelCreateRequestSchema,
collectionLabelUpdateRequestSchema,
collectionLabelAssignRequestSchema,
type CollectionLabelCreateRequest,
type CollectionLabelUpdateRequest,
type CollectionLabelAssignRequest,
type CollectionCreateRequest,
type CollectionUpdateRequest,
type CollectionSavePlaceRequest,
type CollectionSaveFromTripRequest,
type CollectionSaveFromTripManyRequest,
type CollectionPlaceUpdateRequest,
type CollectionSetStatusRequest,
type CollectionCopyToTripRequest,
type CollectionInviteRequest,
type CollectionInviteActionRequest,
type CollectionInviteCancelRequest,
type CollectionRemoveMemberRequest,
type CollectionSetMemberRoleRequest,
} from '@trek/shared';
const MAX_COVER_SIZE = 20 * 1024 * 1024;
const coversDir = path.join(__dirname, '../../../uploads/covers');
const COVER_UPLOAD = {
storage: diskStorage({
destination: (_req, _file, cb) => {
if (!fs.existsSync(coversDir)) fs.mkdirSync(coversDir, { recursive: true });
cb(null, coversDir);
},
filename: (_req, file, cb) => cb(null, `${uuidv4()}${path.extname(file.originalname)}`),
}),
limits: { fileSize: MAX_COVER_SIZE },
fileFilter: (_req: Request, file: Express.Multer.File, cb: (err: Error | null, accept: boolean) => void) => {
const ext = path.extname(file.originalname).toLowerCase();
const allowed = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
if (file.mimetype.startsWith('image/') && !file.mimetype.includes('svg') && allowed.includes(ext)) cb(null, true);
else cb(new Error('Only jpg, png, gif, webp images allowed'), false);
},
};
/**
* /api/addons/collections — saved-place library (lists, places, fusion sharing).
*
* The addon guard (404) runs before JwtAuthGuard so a disabled addon answers 404
* regardless of auth. Access control lives in the service (assertAccess / isOwner
* throw 404/403/400). /invite, /invite/cancel and /:id/available-users add an
* explicit owner check in the controller so they cannot be used to enumerate.
* The X-Socket-Id header is forwarded to the service so the originating client is
* excluded from the WS broadcast.
*/
@Controller('api/addons/collections')
@UseGuards(CollectionsAddonGuard, JwtAuthGuard)
export class CollectionsController {
constructor(private readonly collections: CollectionsService) {}
// ── Lists ─────────────────────────────────────────────────────────────────
@Get()
list(@CurrentUser() user: User) {
return this.collections.listCollections(user.id);
}
@Post()
create(@CurrentUser() user: User, @Body(new ZodValidationPipe(collectionCreateRequestSchema)) body: CollectionCreateRequest) {
return this.collections.createCollection(user.id, body);
}
@Post('reorder')
@HttpCode(200)
reorder(@CurrentUser() user: User, @Body('orderedIds') orderedIds: unknown) {
if (!Array.isArray(orderedIds) || !orderedIds.every((v) => Number.isFinite(Number(v)))) {
throw new HttpException({ error: 'orderedIds must be an array of numbers' }, 400);
}
this.collections.reorderCollections(user.id, orderedIds.map(Number));
return { success: true };
}
// ── Places (static prefixes before /:id) ────────────────────────────────────
@Post('places')
@HttpCode(200)
savePlace(@CurrentUser() user: User, @Body(new ZodValidationPipe(collectionSavePlaceRequestSchema)) body: CollectionSavePlaceRequest, @Headers('x-socket-id') socketId?: string) {
return this.collections.savePlace(user.id, body, socketId);
}
@Post('places/from-trip')
@HttpCode(200)
saveFromTrip(@CurrentUser() user: User, @Body(new ZodValidationPipe(collectionSaveFromTripRequestSchema)) body: CollectionSaveFromTripRequest) {
return this.collections.saveFromTripPlace(user.id, body.collection_id, body.source_trip_id, body.source_place_id, body.force);
}
@Post('places/from-trip-many')
@HttpCode(200)
saveFromTripMany(@CurrentUser() user: User, @Body(new ZodValidationPipe(collectionSaveFromTripManyRequestSchema)) body: CollectionSaveFromTripManyRequest) {
return this.collections.saveFromTripPlaces(user.id, body.collection_id, body.source_trip_id, body.source_place_ids, body.force);
}
@Post('places/delete-many')
@HttpCode(200)
deleteMany(@CurrentUser() user: User, @Body('ids') ids: unknown, @Headers('x-socket-id') socketId?: string) {
if (!Array.isArray(ids) || !ids.every((v) => Number.isFinite(Number(v)))) {
throw new HttpException({ error: 'ids must be an array of numbers' }, 400);
}
return { deleted: this.collections.deletePlacesMany(user.id, ids.map(Number), socketId) };
}
@Patch('places/:pid')
updatePlace(
@CurrentUser() user: User,
@Param('pid') pid: string,
@Body(new ZodValidationPipe(collectionPlaceUpdateRequestSchema)) body: CollectionPlaceUpdateRequest,
@Headers('x-socket-id') socketId?: string,
) {
return this.collections.updatePlace(user.id, Number(pid), body, socketId);
}
@Post('places/:pid/status')
@HttpCode(200)
setStatus(
@CurrentUser() user: User,
@Param('pid') pid: string,
@Body(new ZodValidationPipe(collectionSetStatusRequestSchema)) body: CollectionSetStatusRequest,
@Headers('x-socket-id') socketId?: string,
) {
return this.collections.setStatus(user.id, Number(pid), body.status, socketId);
}
@Delete('places/:pid')
deletePlace(@CurrentUser() user: User, @Param('pid') pid: string, @Headers('x-socket-id') socketId?: string) {
this.collections.deletePlace(user.id, Number(pid), socketId);
return { success: true };
}
// ── Copy to trip ────────────────────────────────────────────────────────────
@Post('copy-to-trip')
@HttpCode(200)
copyToTrip(@CurrentUser() user: User, @Body(new ZodValidationPipe(collectionCopyToTripRequestSchema)) body: CollectionCopyToTripRequest) {
return this.collections.copyToTrip(user.id, body);
}
// ── Labels (per-collection custom labels; static prefixes before /:id) ───────
@Post('labels')
@HttpCode(200)
createLabel(
@CurrentUser() user: User,
@Body(new ZodValidationPipe(collectionLabelCreateRequestSchema)) body: CollectionLabelCreateRequest,
@Headers('x-socket-id') socketId?: string,
) {
return this.collections.createLabel(user.id, body.collection_id, body.name, body.color, socketId);
}
@Patch('labels/:lid')
updateLabel(
@CurrentUser() user: User,
@Param('lid') lid: string,
@Body(new ZodValidationPipe(collectionLabelUpdateRequestSchema)) body: CollectionLabelUpdateRequest,
@Headers('x-socket-id') socketId?: string,
) {
return this.collections.updateLabel(user.id, Number(lid), body, socketId);
}
@Delete('labels/:lid')
deleteLabel(@CurrentUser() user: User, @Param('lid') lid: string, @Headers('x-socket-id') socketId?: string) {
this.collections.deleteLabel(user.id, Number(lid), socketId);
return { success: true };
}
@Post('labels/assign')
@HttpCode(200)
assignLabels(
@CurrentUser() user: User,
@Body(new ZodValidationPipe(collectionLabelAssignRequestSchema)) body: CollectionLabelAssignRequest,
@Headers('x-socket-id') socketId?: string,
) {
return this.collections.assignLabels(user.id, body.label_ids, body.place_ids, false, socketId);
}
@Post('labels/unassign')
@HttpCode(200)
unassignLabels(
@CurrentUser() user: User,
@Body(new ZodValidationPipe(collectionLabelAssignRequestSchema)) body: CollectionLabelAssignRequest,
@Headers('x-socket-id') socketId?: string,
) {
return this.collections.assignLabels(user.id, body.label_ids, body.place_ids, true, socketId);
}
// ── Library-wide membership lookup ──────────────────────────────────────────
@Get('membership')
membership(
@CurrentUser() user: User,
@Query('google_place_id') googlePlaceId?: string,
@Query('google_ftid') googleFtid?: string,
@Query('name') name?: string,
@Query('lat') lat?: string,
@Query('lng') lng?: string,
) {
return this.collections.findMembership(user.id, {
google_place_id: googlePlaceId,
google_ftid: googleFtid,
name,
lat: lat != null && lat !== '' ? Number(lat) : undefined,
lng: lng != null && lng !== '' ? Number(lng) : undefined,
});
}
// ── Fusion invitations ──────────────────────────────────────────────────────
@Post('invite')
@HttpCode(200)
invite(@CurrentUser() user: User, @Body(new ZodValidationPipe(collectionInviteRequestSchema)) body: CollectionInviteRequest) {
this.collections.assertAccess(user.id, body.collection_id); // 404 if not visible (no enumeration)
if (!this.collections.isOwner(user.id, body.collection_id)) {
throw new HttpException({ error: 'Only the owner can invite' }, 403);
}
const result = this.collections.sendInvite(body.collection_id, user.id, user.username, user.email, body.user_id, body.role);
if (result.error) {
throw new HttpException({ error: result.error }, result.status!);
}
return { success: true };
}
@Post('invite/accept')
@HttpCode(200)
acceptInvite(@CurrentUser() user: User, @Body(new ZodValidationPipe(collectionInviteActionRequestSchema)) body: CollectionInviteActionRequest, @Headers('x-socket-id') socketId?: string) {
const result = this.collections.acceptInvite(user.id, body.collection_id, socketId);
if (result.error) {
throw new HttpException({ error: result.error }, result.status!);
}
return { success: true };
}
@Post('invite/decline')
@HttpCode(200)
declineInvite(@CurrentUser() user: User, @Body(new ZodValidationPipe(collectionInviteActionRequestSchema)) body: CollectionInviteActionRequest, @Headers('x-socket-id') socketId?: string) {
this.collections.declineInvite(user.id, body.collection_id, socketId);
return { success: true };
}
@Post('invite/cancel')
@HttpCode(200)
cancelInvite(@CurrentUser() user: User, @Body(new ZodValidationPipe(collectionInviteCancelRequestSchema)) body: CollectionInviteCancelRequest) {
this.collections.assertAccess(user.id, body.collection_id); // 404 if not visible
if (!this.collections.isOwner(user.id, body.collection_id)) {
throw new HttpException({ error: 'Only the owner can cancel invites' }, 403);
}
this.collections.cancelInvite(body.collection_id, user.id, body.user_id);
return { success: true };
}
@Post('leave')
@HttpCode(200)
leave(@CurrentUser() user: User, @Body(new ZodValidationPipe(collectionInviteActionRequestSchema)) body: CollectionInviteActionRequest, @Headers('x-socket-id') socketId?: string) {
this.collections.leaveCollection(user.id, body.collection_id, socketId);
return { success: true };
}
@Post('members/remove')
@HttpCode(200)
removeMember(@CurrentUser() user: User, @Body(new ZodValidationPipe(collectionRemoveMemberRequestSchema)) body: CollectionRemoveMemberRequest) {
this.collections.assertAccess(user.id, body.collection_id); // 404 if not visible
if (!this.collections.isOwner(user.id, body.collection_id)) {
throw new HttpException({ error: 'Only the owner can remove members' }, 403);
}
this.collections.removeMember(user.id, body.collection_id, body.user_id);
return { success: true };
}
@Post('members/role')
@HttpCode(200)
setMemberRole(@CurrentUser() user: User, @Body(new ZodValidationPipe(collectionSetMemberRoleRequestSchema)) body: CollectionSetMemberRoleRequest) {
this.collections.assertAccess(user.id, body.collection_id); // 404 if not visible
if (!this.collections.isOwner(user.id, body.collection_id)) {
throw new HttpException({ error: 'Only the owner can change member roles' }, 403);
}
this.collections.setMemberRole(user.id, body.collection_id, body.user_id, body.role);
return { success: true };
}
// ── /:id (declared last so static prefixes win) ─────────────────────────────
@Get(':id/available-users')
availableUsers(@CurrentUser() user: User, @Param('id') id: string) {
this.collections.assertAccess(user.id, Number(id)); // 404 if not visible (no enumeration)
if (!this.collections.isOwner(user.id, Number(id))) {
throw new HttpException({ error: 'Only the owner can manage members' }, 403);
}
return { users: this.collections.availableUsers(user.id, Number(id)) };
}
@Post(':id/cover')
@UseInterceptors(FileInterceptor('cover', COVER_UPLOAD))
uploadCover(@CurrentUser() user: User, @Param('id') id: string, @UploadedFile() file: Express.Multer.File | undefined, @Headers('x-socket-id') socketId?: string) {
if (process.env.DEMO_MODE?.toLowerCase() === 'true' && isDemoEmail(user.email)) {
throw new HttpException({ error: 'Uploads are disabled in demo mode. Self-host TREK for full functionality.' }, 403);
}
if (!file) throw new HttpException({ error: 'No image uploaded' }, 400);
const coverUrl = `/uploads/covers/${file.filename}`;
return this.collections.setCollectionCover(user.id, Number(id), coverUrl, socketId);
}
@Get(':id')
get(@CurrentUser() user: User, @Param('id') id: string) {
return this.collections.getCollection(user.id, Number(id));
}
@Patch(':id')
update(@CurrentUser() user: User, @Param('id') id: string, @Body(new ZodValidationPipe(collectionUpdateRequestSchema)) body: CollectionUpdateRequest, @Headers('x-socket-id') socketId?: string) {
return this.collections.updateCollection(user.id, Number(id), body, socketId);
}
@Delete(':id')
remove(@CurrentUser() user: User, @Param('id') id: string) {
this.collections.deleteCollection(user.id, Number(id));
return { success: true };
}
}
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { CollectionsController } from './collections.controller';
import { CollectionsService } from './collections.service';
import { CollectionsAddonGuard } from './collections-addon.guard';
@Module({
controllers: [CollectionsController],
providers: [CollectionsService, CollectionsAddonGuard],
})
export class CollectionsModule {}
@@ -0,0 +1,63 @@
import { Injectable } from '@nestjs/common';
import * as svc from '../../services/collectionsService';
import type {
CollectionCreateRequest,
CollectionUpdateRequest,
CollectionSavePlaceRequest,
CollectionPlaceUpdateRequest,
CollectionCopyToTripRequest,
CollectionStatus,
} from '@trek/shared';
/**
* Thin Nest wrapper around services/collectionsService. All access control lives
* in the legacy service (assertAccess / isOwner throw, fusion returns {error});
* this just re-exposes the functions one-to-one.
*/
@Injectable()
export class CollectionsService {
listCollections(userId: number) { return svc.listCollections(userId); }
getCollection(userId: number, id: number) { return svc.getCollection(userId, id); }
createCollection(userId: number, body: CollectionCreateRequest) { return svc.createCollection(userId, body); }
updateCollection(userId: number, id: number, body: CollectionUpdateRequest, socketId?: string) { return svc.updateCollection(userId, id, body, socketId); }
setCollectionCover(userId: number, id: number, coverUrl: string | null, socketId?: string) { return svc.setCollectionCover(userId, id, coverUrl, socketId); }
deleteCollection(userId: number, id: number) { return svc.deleteCollection(userId, id); }
reorderCollections(userId: number, orderedIds: number[]) { return svc.reorderCollections(userId, orderedIds); }
savePlace(userId: number, body: CollectionSavePlaceRequest, socketId?: string) { return svc.savePlace(userId, body, socketId); }
saveFromTripPlace(userId: number, collectionId: number, tripId: number, placeId: number, force?: boolean) {
return svc.saveFromTripPlace(userId, collectionId, tripId, placeId, force);
}
saveFromTripPlaces(userId: number, collectionId: number, tripId: number, placeIds: number[], force?: boolean) {
return svc.saveFromTripPlaces(userId, collectionId, tripId, placeIds, force);
}
updatePlace(userId: number, placeId: number, body: CollectionPlaceUpdateRequest, socketId?: string) { return svc.updatePlace(userId, placeId, body, socketId); }
setStatus(userId: number, placeId: number, status: CollectionStatus, socketId?: string) { return svc.setStatus(userId, placeId, status, socketId); }
deletePlace(userId: number, placeId: number, socketId?: string) { return svc.deletePlace(userId, placeId, socketId); }
deletePlacesMany(userId: number, ids: number[], socketId?: string) { return svc.deletePlacesMany(userId, ids, socketId); }
copyToTrip(userId: number, body: CollectionCopyToTripRequest) { return svc.copyToTrip(userId, body); }
findMembership(userId: number, query: { google_place_id?: string; google_ftid?: string; name?: string; lat?: number; lng?: number }) {
return svc.findMembership(userId, query);
}
createLabel(userId: number, collectionId: number, name: string, color: string | undefined, socketId?: string) { return svc.createLabel(userId, collectionId, name, color, socketId); }
updateLabel(userId: number, labelId: number, body: { name?: string; color?: string; sort_order?: number }, socketId?: string) { return svc.updateLabel(userId, labelId, body, socketId); }
deleteLabel(userId: number, labelId: number, socketId?: string) { return svc.deleteLabel(userId, labelId, socketId); }
assignLabels(userId: number, labelIds: number[], placeIds: number[], remove: boolean, socketId?: string) { return svc.assignLabels(userId, labelIds, placeIds, remove, socketId); }
// Access helpers used by the controller's owner guards.
assertAccess(userId: number, collectionId: number) { return svc.assertAccess(userId, collectionId); }
isOwner(userId: number, collectionId: number) { return svc.isOwner(userId, collectionId); }
sendInvite(collectionId: number, inviterId: number, inviterUsername: string, inviterEmail: string, targetUserId: number, role?: 'viewer' | 'editor' | 'admin') {
return svc.sendInvite(collectionId, inviterId, inviterUsername, inviterEmail, targetUserId, role);
}
acceptInvite(userId: number, collectionId: number, socketId?: string) { return svc.acceptInvite(userId, collectionId, socketId); }
declineInvite(userId: number, collectionId: number, socketId?: string) { return svc.declineInvite(userId, collectionId, socketId); }
cancelInvite(collectionId: number, ownerId: number, targetUserId: number) { return svc.cancelInvite(collectionId, ownerId, targetUserId); }
leaveCollection(userId: number, collectionId: number, socketId?: string) { return svc.leaveCollection(userId, collectionId, socketId); }
removeMember(ownerId: number, collectionId: number, targetUserId: number) { return svc.removeMember(ownerId, collectionId, targetUserId); }
setMemberRole(ownerId: number, collectionId: number, targetUserId: number, role: 'viewer' | 'editor' | 'admin') { return svc.setMemberRole(ownerId, collectionId, targetUserId, role); }
availableUsers(ownerId: number, collectionId: number) { return svc.availableUsers(ownerId, collectionId); }
}
@@ -0,0 +1,11 @@
/**
* API-docs kill switch (#1412). Deliberately NOT in src/config.ts: tests mock
* that module with partial exports, and reading the env at call time keeps the
* flag testable per-request (same pattern as plugins/kill-switch.ts).
*
* Off by default — the generated spec enumerates every route including the
* admin surface, so exposing it is an explicit self-hoster decision.
*/
export function apiDocsEnabled(): boolean {
return (process.env.TREK_API_DOCS_ENABLED || '').trim().toLowerCase() === 'true';
}
+87
View File
@@ -0,0 +1,87 @@
import type { INestApplication } from '@nestjs/common';
import { RequestMethod } from '@nestjs/common';
import { ModulesContainer } from '@nestjs/core';
import { PATH_METADATA, METHOD_METADATA, ROUTE_ARGS_METADATA } from '@nestjs/common/constants';
import { z, type ZodType } from 'zod';
import type { OpenAPIObject } from '@nestjs/swagger';
import { ZodValidationPipe } from './zod-validation.pipe';
/**
* Phase 2 of #1412: real request-body schemas without annotating anything
* twice. The API validates with Zod via `@Body(new ZodValidationPipe(schema))`
* — that pipe IS the schema source of truth, so this enricher walks every
* controller route, finds full-body Zod pipes, and writes the converted
* JSON schema into the generated OpenAPI document. Any route that gains a
* ZodValidationPipe is documented automatically from then on.
*/
/** Zod → OpenAPI 3.0 schema; degrades to a bare object for unrepresentable schemas. */
export function zodToOpenApi(schema: ZodType): Record<string, unknown> {
try {
return z.toJSONSchema(schema, { target: 'openapi-3.0', io: 'input', unrepresentable: 'any' }) as Record<string, unknown>;
} catch {
return { type: 'object' };
}
}
const HTTP_METHOD: Partial<Record<RequestMethod, string>> = {
[RequestMethod.GET]: 'get',
[RequestMethod.POST]: 'post',
[RequestMethod.PUT]: 'put',
[RequestMethod.PATCH]: 'patch',
[RequestMethod.DELETE]: 'delete',
};
// RouteParamtypes.BODY — the numeric key prefix @Body() writes into
// ROUTE_ARGS_METADATA ("<paramtype>:<index>"). The enum lives in a private
// @nestjs/common path, so the value is pinned here with a boot-time test.
const BODY_PARAMTYPE = '3';
function joinPath(base: string | undefined, sub: string | undefined): string {
const parts = `${base ?? ''}/${sub ?? ''}`.split('/').filter(Boolean);
// Express ":param" → OpenAPI "{param}"
return '/' + parts.map((p) => (p.startsWith(':') ? `{${p.slice(1)}}` : p)).join('/');
}
/** Find full-body Zod schemas per route and merge them into the document. */
export function attachZodBodySchemas(app: INestApplication, document: OpenAPIObject): void {
const modules = app.get(ModulesContainer, { strict: false });
for (const module of modules.values()) {
for (const wrapper of module.controllers.values()) {
const ctor = wrapper.metatype as (abstract new (...args: never[]) => unknown) | undefined;
if (!ctor || typeof ctor !== 'function') continue;
const basePath = Reflect.getMetadata(PATH_METADATA, ctor) as string | undefined;
if (basePath === undefined) continue;
for (const name of Object.getOwnPropertyNames(ctor.prototype)) {
if (name === 'constructor') continue;
const handler = (ctor.prototype as Record<string, unknown>)[name];
if (typeof handler !== 'function') continue;
const methodEnum = Reflect.getMetadata(METHOD_METADATA, handler) as RequestMethod | undefined;
const verb = methodEnum !== undefined ? HTTP_METHOD[methodEnum] : undefined;
if (!verb) continue;
const args = (Reflect.getMetadata(ROUTE_ARGS_METADATA, ctor, name) ?? {}) as Record<
string,
{ index: number; data?: unknown; pipes?: unknown[] }
>;
const bodyArg = Object.entries(args).find(([key, meta]) =>
key.startsWith(`${BODY_PARAMTYPE}:`)
// @Body('field') picks a sub-field — only whole-body pipes describe the request body
&& meta.data === undefined
&& (meta.pipes ?? []).some((p) => p instanceof ZodValidationPipe),
);
if (!bodyArg) continue;
const zodPipe = (bodyArg[1].pipes ?? []).find((p): p is ZodValidationPipe => p instanceof ZodValidationPipe)!;
const route = document.paths[joinPath(basePath, Reflect.getMetadata(PATH_METADATA, handler) as string | undefined)];
const operation = route?.[verb as 'get' | 'post' | 'put' | 'patch' | 'delete'];
if (!operation) continue;
operation.requestBody = {
required: true,
content: { 'application/json': { schema: zodToOpenApi(zodPipe.schema) } },
};
}
}
}
}
@@ -11,7 +11,9 @@ import type { ZodType } from 'zod';
*/
@Injectable()
export class ZodValidationPipe implements PipeTransform {
constructor(private readonly schema: ZodType) {}
// Public so the API-docs enricher can lift the schema into the OpenAPI
// document (#1412) — the pipe stays the single source of truth.
constructor(readonly schema: ZodType) {}
transform(value: unknown, _metadata: ArgumentMetadata): unknown {
const result = this.schema.safeParse(value);
+143
View File
@@ -0,0 +1,143 @@
import {
Controller,
Delete,
Get,
HttpException,
Param,
Post,
Put,
Req,
Res,
UseGuards,
} from '@nestjs/common';
import type { Request, Response } from 'express';
import { FeedsService } from './feeds.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
import type { User } from '../../types';
import { db } from '../../db/database';
// Resolve the public origin used to build feed URLs. APP_URL wins — it is the
// canonical externally-reachable URL behind a reverse proxy. When it is unset
// (the default on a plain `docker run`), fall back to the request's own host so
// the link is still absolute and copy-pasteable as webcal:// instead of a dead
// relative path.
function resolveFeedBase(req: Request): string {
const configured = (process.env.APP_URL || '').replace(/\/$/, '');
if (configured) return configured;
const host = req.get('host');
return host ? `${req.protocol}://${host}` : '';
}
/**
* Public subscribable ICS feed endpoints — no auth required.
* The secret token in the URL acts as the access credential.
*/
@Controller('api/feed')
export class FeedsPublicController {
constructor(private readonly feeds: FeedsService) {}
@Get('trip/:token.ics')
tripFeed(@Param('token') token: string, @Res() res: Response): void {
const result = this.feeds.buildTripIcs(token);
if (!result) {
res.status(404).json({ error: 'Feed not found' });
return;
}
res.setHeader('Content-Type', 'text/calendar; charset=utf-8');
res.setHeader('Content-Disposition', `inline; filename="${result.filename}"`);
res.setHeader('Cache-Control', 'no-cache, no-store');
res.setHeader('X-Published-TTL', 'PT1H');
res.send(result.ics);
}
@Get('user/:token.ics')
userFeed(@Param('token') token: string, @Res() res: Response): void {
const result = this.feeds.buildUserIcs(token);
if (!result) {
res.status(404).json({ error: 'Feed not found' });
return;
}
res.setHeader('Content-Type', 'text/calendar; charset=utf-8');
res.setHeader('Content-Disposition', `inline; filename="all-trips.ics"`);
res.setHeader('Cache-Control', 'no-cache, no-store');
res.setHeader('X-Published-TTL', 'PT1H');
res.send(result.ics);
}
}
/**
* Authenticated token management for a single trip's feed.
* POST = enable (mint a token, idempotent)
* PUT = rotate (new token, invalidates the old URL)
* DELETE = disable (clear the token, public URL stops resolving)
*/
@Controller('api/trips/:tripId/feed')
@UseGuards(JwtAuthGuard)
export class TripFeedTokenController {
constructor(private readonly feeds: FeedsService) {}
private assertAccess(tripId: string, userId: number): void {
const row = db
.prepare(
'SELECT id FROM trips WHERE id = ? AND (user_id = ? OR id IN (SELECT trip_id FROM trip_members WHERE user_id = ?))',
)
.get(tripId, userId, userId);
if (!row) throw new HttpException({ error: 'Trip not found' }, 404);
}
@Get('token')
get(@CurrentUser() user: User, @Param('tripId') tripId: string, @Req() req: Request) {
return this.feeds.getTripToken(tripId, user.id, resolveFeedBase(req));
}
@Post('token')
generate(@CurrentUser() user: User, @Param('tripId') tripId: string, @Req() req: Request) {
this.assertAccess(tripId, user.id);
return this.feeds.generateTripToken(tripId, user.id, resolveFeedBase(req));
}
@Put('token')
rotate(@CurrentUser() user: User, @Param('tripId') tripId: string, @Req() req: Request) {
this.assertAccess(tripId, user.id);
return this.feeds.rotateTripToken(tripId, resolveFeedBase(req));
}
@Delete('token')
disable(@CurrentUser() user: User, @Param('tripId') tripId: string) {
this.assertAccess(tripId, user.id);
this.feeds.disableTripToken(tripId);
return { feed_url: null };
}
}
/**
* Authenticated token management for the all-trips (per-user) feed.
* POST = enable PUT = rotate DELETE = disable
*/
@Controller('api/feed/user')
@UseGuards(JwtAuthGuard)
export class UserFeedTokenController {
constructor(private readonly feeds: FeedsService) {}
@Get('token')
get(@CurrentUser() user: User, @Req() req: Request) {
return this.feeds.getUserToken(user.id, resolveFeedBase(req));
}
@Post('token')
generate(@CurrentUser() user: User, @Req() req: Request) {
return this.feeds.generateUserToken(user.id, resolveFeedBase(req));
}
@Put('token')
rotate(@CurrentUser() user: User, @Req() req: Request) {
return this.feeds.rotateUserToken(user.id, resolveFeedBase(req));
}
@Delete('token')
disable(@CurrentUser() user: User) {
this.feeds.disableUserToken(user.id);
return { feed_url: null };
}
}
+9
View File
@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { FeedsService } from './feeds.service';
import { FeedsPublicController, TripFeedTokenController, UserFeedTokenController } from './feeds.controller';
@Module({
controllers: [FeedsPublicController, TripFeedTokenController, UserFeedTokenController],
providers: [FeedsService],
})
export class FeedsModule {}
+158
View File
@@ -0,0 +1,158 @@
import { Injectable } from '@nestjs/common';
import { randomUUID } from 'crypto';
import { db } from '../../db/database';
import { exportICS } from '../../services/tripService';
const ninetyDaysAgo = () => {
const d = new Date();
d.setDate(d.getDate() - 90);
return d.toISOString().slice(0, 10);
};
function feedUrl(token: string, scope: 'trip' | 'user', base: string): string {
return `${base.replace(/\/$/, '')}/api/feed/${scope}/${token}.ics`;
}
@Injectable()
export class FeedsService {
// ── Trip feed token ─────────────────────────────────────────────────────
private tripTokenRow(tripId: string, userId: number) {
return db
.prepare(
'SELECT feed_token FROM trips WHERE id = ? AND (user_id = ? OR id IN (SELECT trip_id FROM trip_members WHERE user_id = ?))',
)
.get(tripId, userId, userId) as { feed_token: string | null } | undefined;
}
getTripToken(tripId: string, userId: number, base: string): { feed_url: string | null } {
const row = this.tripTokenRow(tripId, userId);
return { feed_url: row?.feed_token ? feedUrl(row.feed_token, 'trip', base) : null };
}
/** Enable (idempotent): mint a token only if the trip has none yet. */
generateTripToken(tripId: string, userId: number, base: string): { feed_url: string } {
const row = this.tripTokenRow(tripId, userId);
if (row?.feed_token) return { feed_url: feedUrl(row.feed_token, 'trip', base) };
const token = randomUUID();
db.prepare('UPDATE trips SET feed_token = ? WHERE id = ?').run(token, tripId);
return { feed_url: feedUrl(token, 'trip', base) };
}
/** Rotate: always issue a fresh token, invalidating the previous URL. */
rotateTripToken(tripId: string, base: string): { feed_url: string } {
const token = randomUUID();
db.prepare('UPDATE trips SET feed_token = ? WHERE id = ?').run(token, tripId);
return { feed_url: feedUrl(token, 'trip', base) };
}
/** Disable: clear the token so the public URL stops resolving. */
disableTripToken(tripId: string): void {
db.prepare('UPDATE trips SET feed_token = NULL WHERE id = ?').run(tripId);
}
// ── User (all-trips) feed token ──────────────────────────────────────────
getUserToken(userId: number, base: string): { feed_url: string | null } {
const row = db.prepare('SELECT feed_token FROM users WHERE id = ?').get(userId) as
| { feed_token: string | null }
| undefined;
return { feed_url: row?.feed_token ? feedUrl(row.feed_token, 'user', base) : null };
}
generateUserToken(userId: number, base: string): { feed_url: string } {
const existing = this.getUserToken(userId, base);
if (existing.feed_url) return { feed_url: existing.feed_url };
const token = randomUUID();
db.prepare('UPDATE users SET feed_token = ? WHERE id = ?').run(token, userId);
return { feed_url: feedUrl(token, 'user', base) };
}
rotateUserToken(userId: number, base: string): { feed_url: string } {
const token = randomUUID();
db.prepare('UPDATE users SET feed_token = ? WHERE id = ?').run(token, userId);
return { feed_url: feedUrl(token, 'user', base) };
}
disableUserToken(userId: number): void {
db.prepare('UPDATE users SET feed_token = NULL WHERE id = ?').run(userId);
}
// ── ICS generation ───────────────────────────────────────────────────────
buildTripIcs(token: string): { ics: string; filename: string } | null {
const row = db.prepare('SELECT id FROM trips WHERE feed_token = ?').get(token) as
| { id: number }
| undefined;
if (!row) return null;
try {
const { ics, filename } = exportICS(row.id);
// Inject calendar-subscription refresh hints into the VCALENDAR header so
// clients re-fetch hourly. The one-time download path (exportICS) is left
// untouched; this is feed-only.
const withHints = ics.replace(
'METHOD:PUBLISH\r\n',
'METHOD:PUBLISH\r\nREFRESH-INTERVAL;VALUE=DURATION:PT1H\r\nX-PUBLISHED-TTL:PT1H\r\n',
);
return { ics: withHints, filename };
} catch {
return null;
}
}
buildUserIcs(token: string): { ics: string; calName: string } | null {
const user = db.prepare('SELECT id, username FROM users WHERE feed_token = ?').get(token) as
| { id: number; username: string }
| undefined;
if (!user) return null;
const cutoff = ninetyDaysAgo();
const trips = db
.prepare(
`SELECT id FROM trips
WHERE user_id = ?
AND is_archived = 0
AND (end_date IS NULL OR end_date >= ?)
ORDER BY start_date ASC`,
)
.all(user.id, cutoff) as { id: number }[];
const esc = (s: string) =>
s.replace(/\\/g, '\\\\').replace(/;/g, '\\;').replace(/,/g, '\\,').replace(/\r?\n/g, '\\n');
const calName = `${user.username} – All Trips`;
let combined =
'BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//TREK//Travel Planner//EN\r\nCALSCALE:GREGORIAN\r\nMETHOD:PUBLISH\r\n';
combined += `X-WR-CALNAME:${esc(calName)}\r\n`;
combined += 'REFRESH-INTERVAL;VALUE=DURATION:PT1H\r\nX-PUBLISHED-TTL:PT1H\r\n';
for (const { id } of trips) {
try {
const { ics } = exportICS(id);
combined += extractVEvents(ics);
} catch {
// skip failed trips
}
}
combined += 'END:VCALENDAR\r\n';
return { ics: combined, calName };
}
}
// Pull the VEVENT blocks out of a single-trip calendar by structural line
// scanning rather than a lazy regex on "END:VEVENT". User-supplied text (escaped
// onto a SUMMARY/DESCRIPTION line) can legitimately contain the literal
// "END:VEVENT", which a non-greedy regex would mistake for a terminator and
// truncate the event. Folded continuation lines always begin with a space, so a
// bare "BEGIN:VEVENT"/"END:VEVENT" only ever appears as a real delimiter.
function extractVEvents(ics: string): string {
let out = '';
let inside = false;
for (const line of ics.split('\r\n')) {
if (line === 'BEGIN:VEVENT') inside = true;
if (inside) out += line + '\r\n';
if (line === 'END:VEVENT') inside = false;
}
return out;
}
+35 -10
View File
@@ -24,7 +24,7 @@ import type { User } from '../../types';
import { FilesService } from './files.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
import { MAX_FILE_SIZE, BLOCKED_EXTENSIONS, filesDir, getAllowedExtensions } from '../../services/fileService';
import { MAX_FILE_SIZE, MAX_VIDEO_SIZE, BLOCKED_EXTENSIONS, filesDir, getAllowedExtensions, isVideoExtension } from '../../services/fileService';
import { isDemoEmail } from '../../services/demo';
const UPLOAD = {
@@ -32,7 +32,9 @@ const UPLOAD = {
destination: (_req, _file, cb) => { if (!fs.existsSync(filesDir)) fs.mkdirSync(filesDir, { recursive: true }); cb(null, filesDir); },
filename: (_req, file, cb) => cb(null, `${uuidv4()}${path.extname(file.originalname)}`),
}),
limits: { fileSize: MAX_FILE_SIZE },
// Allow up to the video cap; non-video files are still held to MAX_FILE_SIZE by
// the per-type guard in the upload handler (#823).
limits: { fileSize: MAX_VIDEO_SIZE },
defParamCharset: 'utf8', // parity with legacy routes/files.ts — preserve non-ASCII original filenames
fileFilter: (_req: unknown, file: Express.Multer.File, cb: (err: Error | null, accept: boolean) => void) => {
const ext = path.extname(file.originalname).toLowerCase();
@@ -45,7 +47,8 @@ const UPLOAD = {
if (BLOCKED_EXTENSIONS.includes(ext) || file.mimetype.includes('svg')) return reject();
const allowed = getAllowedExtensions().split(',').map((e) => e.trim().toLowerCase());
const fileExt = ext.replace('.', '');
if (allowed.includes(fileExt) || (allowed.includes('*') && !BLOCKED_EXTENSIONS.includes(ext))) return cb(null, true);
// Video is accepted as media regardless of the admin doc-types allowlist (#823).
if (allowed.includes(fileExt) || isVideoExtension(fileExt) || (allowed.includes('*') && !BLOCKED_EXTENSIONS.includes(ext))) return cb(null, true);
reject();
},
};
@@ -97,17 +100,39 @@ export class FilesController {
@Body() body: { place_id?: string; description?: string; reservation_id?: string },
@Headers('x-socket-id') socketId?: string,
) {
const trip = this.requireTrip(tripId, user);
if (process.env.DEMO_MODE?.toLowerCase() === 'true' && isDemoEmail(user.email)) {
throw new HttpException({ error: 'Uploads are disabled in demo mode. Self-host TREK for full functionality.' }, 403);
}
if (!this.files.can('file_upload', trip, user)) {
throw new HttpException({ error: 'No permission to upload files' }, 403);
// multer (diskStorage) has already written the upload by the time we get here,
// so every rejection below must remove the orphaned bytes — otherwise a 404/403
// leaves up to the 500 MB video cap on disk (#823).
const cleanup = () => { if (file?.path) { try { fs.unlinkSync(file.path); } catch { /* best-effort */ } } };
try {
const trip = this.requireTrip(tripId, user);
if (process.env.DEMO_MODE?.toLowerCase() === 'true' && isDemoEmail(user.email)) {
throw new HttpException({ error: 'Uploads are disabled in demo mode. Self-host TREK for full functionality.' }, 403);
}
if (!this.files.can('file_upload', trip, user)) {
throw new HttpException({ error: 'No permission to upload files' }, 403);
}
} catch (err) {
cleanup();
throw err;
}
if (!file) {
throw new HttpException({ error: 'No file uploaded' }, 400);
}
this.assertLinkTargets(tripId, { reservation_id: body.reservation_id, place_id: body.place_id });
// The per-type cap is keyed on the EXTENSION, matching how the fileFilter
// decides acceptance — so a real video labelled application/octet-stream isn't
// wrongly rejected, and the 500 MB cap only applies to actual video extensions.
const isVideoUpload = isVideoExtension(path.extname(file.originalname || ''));
if (!isVideoUpload && file.size > MAX_FILE_SIZE) {
cleanup();
throw new HttpException({ error: 'File is too large' }, 400);
}
try {
this.assertLinkTargets(tripId, { reservation_id: body.reservation_id, place_id: body.place_id });
} catch (err) {
cleanup();
throw err;
}
const created = this.files.createFile(tripId, file, user.id, {
place_id: body.place_id,
description: body.description,
+50
View File
@@ -0,0 +1,50 @@
import { Controller, Get, Param, Req, Res } from '@nestjs/common';
import type { Request, Response } from 'express';
import {
getWikiIndex,
getWikiPage,
getWikiAsset,
WikiNotFound,
type WikiPage,
type WikiNavSection,
} from '../../services/wikiService';
/**
* /api/help — embedded TREK wiki. Content is public docs (the wiki is public on
* GitHub), so these endpoints are unauthenticated; that also lets <img> tags load
* the proxied assets without sending credentials. All upstream calls go to the
* fixed TREK wiki path and are cached server-side.
*/
@Controller('api/help')
export class HelpController {
@Get('index')
index(): Promise<{ sections: WikiNavSection[] }> {
return getWikiIndex();
}
@Get('page/:slug')
async page(@Param('slug') slug: string, @Res() res: Response): Promise<void> {
try {
const page: WikiPage = await getWikiPage(slug);
res.json(page);
} catch (err) {
res.status(err instanceof WikiNotFound ? 404 : 502).json({ error: 'Help page unavailable' });
}
}
@Get('asset/*')
async asset(@Req() req: Request, @Res() res: Response): Promise<void> {
// Take everything after `/asset/` straight from the URL — the Express
// wildcard param isn't reliably populated through the Nest adapter.
const after = (req.originalUrl || req.url).split('/asset/')[1] ?? '';
const assetPath = decodeURIComponent(after.split('?')[0]);
try {
const { buf, type } = await getWikiAsset(assetPath);
res.setHeader('Content-Type', type);
res.setHeader('Cache-Control', 'public, max-age=3600');
res.end(buf);
} catch {
res.status(404).end();
}
}
}
+8
View File
@@ -0,0 +1,8 @@
import { Module } from '@nestjs/common';
import { HelpController } from './help.controller';
/** /api/help — embedded GitHub wiki (fetched + cached in wikiService). */
@Module({
controllers: [HelpController],
})
export class HelpModule {}
+84 -12
View File
@@ -15,7 +15,7 @@ import {
UseGuards,
UseInterceptors,
} from '@nestjs/common';
import { FileInterceptor, FilesInterceptor } from '@nestjs/platform-express';
import { FileInterceptor, FilesInterceptor, FileFieldsInterceptor } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import path from 'node:path';
import fs from 'node:fs';
@@ -25,7 +25,7 @@ import { JourneyService } from './journey.service';
import { JourneyAddonGuard } from './journey-addon.guard';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
import { getAllowedExtensions } from '../../services/fileService';
import { getAllowedExtensions, isVideoMime, isVideoExtension, MAX_VIDEO_SIZE } from '../../services/fileService';
const uploadsBase = path.join(__dirname, '../../../uploads/journey');
const IMAGE_UPLOAD = {
@@ -51,6 +51,41 @@ const IMAGE_UPLOAD = {
},
};
// Gallery video upload (#823): one video plus an optional client-captured poster
// image, written to the same uploads/journey store. Larger cap than images since
// phone clips are big; videos are stored as-is and streamed with HTTP Range.
const VIDEO_UPLOAD = {
storage: diskStorage({
destination: (_req, _file, cb) => { if (!fs.existsSync(uploadsBase)) fs.mkdirSync(uploadsBase, { recursive: true }); cb(null, uploadsBase); },
filename: (_req, file, cb) => {
// The poster is ALWAYS stored as .jpg, never the client-supplied extension:
// otherwise a poster declared image/* but named x.html / x.js would land on
// disk with that extension and be served inline same-origin (stored XSS,
// reachable via the public share proxy). The video extension is validated by
// the fileFilter, so it is safe to keep.
const ext = file.fieldname === 'poster' ? '.jpg' : (path.extname(file.originalname).toLowerCase() || '.mp4');
cb(null, `${crypto.randomUUID()}${ext}`);
},
}),
limits: { fileSize: MAX_VIDEO_SIZE },
fileFilter: (_req: unknown, file: Express.Multer.File, cb: (err: Error | null, accept: boolean) => void) => {
const reject = (msg: string) => {
const err: Error & { statusCode?: number } = new Error(msg);
err.statusCode = 400;
cb(err, false);
};
if (file.fieldname === 'poster') {
if (!file.mimetype.startsWith('image/') || file.mimetype.includes('svg')) return reject('Poster must be an image');
return cb(null, true);
}
// 'video' field
const ext = path.extname(file.originalname).toLowerCase().replace('.', '');
if (!isVideoMime(file.mimetype)) return reject('Only video files are allowed');
if (!isVideoExtension(ext)) return reject(`Video type .${ext} is not allowed`);
cb(null, true);
},
};
/**
* /api/journeys — cross-trip travel narrative (journeys, entries, photo gallery
* + provider mirroring, contributors, preferences, share links).
@@ -145,20 +180,21 @@ export class JourneyController {
}
@Post('entries/:entryId/provider-photos')
providerPhotos(@CurrentUser() user: User, @Param('entryId') entryId: string, @Body() body: { provider?: string; asset_id?: string; asset_ids?: unknown[]; caption?: string; passphrase?: string }) {
providerPhotos(@CurrentUser() user: User, @Param('entryId') entryId: string, @Body() body: { provider?: string; asset_id?: string; asset_ids?: unknown[]; caption?: string; passphrase?: string; media_type?: string; media_types?: unknown[] }) {
const pp = body.passphrase && typeof body.passphrase === 'string' ? body.passphrase : undefined;
if (Array.isArray(body.asset_ids) && body.provider) {
const added: unknown[] = [];
for (const id of body.asset_ids) {
const photo = this.journey.addProviderPhoto(Number(entryId), user.id, body.provider, String(id), body.caption, pp);
body.asset_ids.forEach((id, i) => {
const mt = Array.isArray(body.media_types) && body.media_types[i] === 'video' ? 'video' : 'image';
const photo = this.journey.addProviderPhoto(Number(entryId), user.id, body.provider!, String(id), body.caption, pp, mt);
if (photo) added.push(photo);
}
});
return { photos: added, added: added.length };
}
if (!body.provider || !body.asset_id) {
throw new HttpException({ error: 'provider and asset_id required' }, 400);
}
const photo = this.journey.addProviderPhoto(Number(entryId), user.id, body.provider, body.asset_id, body.caption, pp);
const photo = this.journey.addProviderPhoto(Number(entryId), user.id, body.provider, body.asset_id, body.caption, pp, body.media_type === 'video' ? 'video' : 'image');
if (!photo) {
throw new HttpException({ error: 'Not allowed or duplicate' }, 403);
}
@@ -222,21 +258,57 @@ export class JourneyController {
return { photos };
}
@Post(':id/gallery/video')
@UseInterceptors(FileFieldsInterceptor([{ name: 'video', maxCount: 1 }, { name: 'poster', maxCount: 1 }], VIDEO_UPLOAD))
uploadGalleryVideo(
@CurrentUser() user: User,
@Param('id') id: string,
@UploadedFiles() files: { video?: Express.Multer.File[]; poster?: Express.Multer.File[] } | undefined,
@Body() body: { duration_ms?: string },
) {
const video = files?.video?.[0];
const poster = files?.poster?.[0];
// multer already wrote both parts; clean them up on any rejection so a POST to
// a journey the user can't edit doesn't orphan a 500 MB clip on disk (#823).
const cleanup = () => {
for (const f of [video, poster]) {
if (f?.path) { try { fs.unlinkSync(f.path); } catch { /* best-effort */ } }
}
};
if (!video) {
cleanup();
throw new HttpException({ error: 'No video uploaded' }, 400);
}
const durationMs = body?.duration_ms != null ? Number(body.duration_ms) : null;
const photos = this.journey.uploadGalleryPhotos(Number(id), user.id, [{
path: `journey/${video.filename}`,
thumbnail: poster ? `journey/${poster.filename}` : undefined,
mediaType: 'video',
durationMs: durationMs != null && Number.isFinite(durationMs) ? durationMs : null,
}]);
if (!photos.length) {
cleanup();
throw new HttpException({ error: 'Not allowed' }, 403);
}
return { photos };
}
@Post(':id/gallery/provider-photos')
galleryProviderPhotos(@CurrentUser() user: User, @Param('id') id: string, @Body() body: { provider?: string; asset_id?: string; asset_ids?: unknown[]; passphrase?: string }) {
galleryProviderPhotos(@CurrentUser() user: User, @Param('id') id: string, @Body() body: { provider?: string; asset_id?: string; asset_ids?: unknown[]; passphrase?: string; media_type?: string; media_types?: unknown[] }) {
const pp = body.passphrase && typeof body.passphrase === 'string' ? body.passphrase : undefined;
if (Array.isArray(body.asset_ids) && body.provider) {
const added: unknown[] = [];
for (const aid of body.asset_ids) {
const photo = this.journey.addProviderPhotoToGallery(Number(id), user.id, body.provider, String(aid), undefined, pp);
body.asset_ids.forEach((aid, i) => {
const mt = Array.isArray(body.media_types) && body.media_types[i] === 'video' ? 'video' : 'image';
const photo = this.journey.addProviderPhotoToGallery(Number(id), user.id, body.provider!, String(aid), undefined, pp, mt);
if (photo) added.push(photo);
}
});
return { photos: added, added: added.length };
}
if (!body.provider || !body.asset_id) {
throw new HttpException({ error: 'provider and asset_id required' }, 400);
}
const photo = this.journey.addProviderPhotoToGallery(Number(id), user.id, body.provider, body.asset_id, undefined, pp);
const photo = this.journey.addProviderPhotoToGallery(Number(id), user.id, body.provider, body.asset_id, undefined, pp, body.media_type === 'video' ? 'video' : 'image');
if (!photo) {
throw new HttpException({ error: 'Not allowed or duplicate' }, 403);
}
+2 -2
View File
@@ -46,13 +46,13 @@ export class JourneyService {
// Photos
addPhoto(entryId: number, userId: number, filePath: string, thumbnailPath: string | undefined, caption: string | undefined) { return svc.addPhoto(entryId, userId, filePath, thumbnailPath, caption); }
setPhotoProvider(photoId: number, provider: string, assetId: string, ownerId: number) { return svc.setPhotoProvider(photoId, provider, assetId, ownerId); }
addProviderPhoto(entryId: number, userId: number, provider: string, assetId: string, caption?: string, passphrase?: string) { return svc.addProviderPhoto(entryId, userId, provider, assetId, caption, passphrase); }
addProviderPhoto(entryId: number, userId: number, provider: string, assetId: string, caption?: string, passphrase?: string, mediaType?: string) { return svc.addProviderPhoto(entryId, userId, provider, assetId, caption, passphrase, mediaType); }
linkPhotoToEntry(entryId: number, journeyPhotoId: number, userId: number) { return svc.linkPhotoToEntry(entryId, journeyPhotoId, userId); }
unlinkPhotoFromEntry(entryId: number, journeyPhotoId: number, userId: number) { return svc.unlinkPhotoFromEntry(entryId, journeyPhotoId, userId); }
updatePhoto(photoId: number, userId: number, data: Parameters<typeof svc.updatePhoto>[2]) { return svc.updatePhoto(photoId, userId, data); }
deletePhoto(photoId: number, userId: number) { return svc.deletePhoto(photoId, userId); }
uploadGalleryPhotos(id: number, userId: number, filePaths: Parameters<typeof svc.uploadGalleryPhotos>[2]) { return svc.uploadGalleryPhotos(id, userId, filePaths); }
addProviderPhotoToGallery(id: number, userId: number, provider: string, assetId: string, caption?: string, passphrase?: string) { return svc.addProviderPhotoToGallery(id, userId, provider, assetId, caption, passphrase); }
addProviderPhotoToGallery(id: number, userId: number, provider: string, assetId: string, caption?: string, passphrase?: string, mediaType?: string) { return svc.addProviderPhotoToGallery(id, userId, provider, assetId, caption, passphrase, mediaType); }
deleteGalleryPhoto(journeyPhotoId: number, userId: number) { return svc.deleteGalleryPhoto(journeyPhotoId, userId); }
// Contributors
@@ -0,0 +1,85 @@
import type { LlmExtractionClient, LlmExtractionInput } from '../llm-provider.interface';
const TIMEOUT_MS = 120_000;
const MAX_TOKENS = 8192;
const ANTHROPIC_VERSION = '2023-06-01';
const TOOL_NAME = 'emit_reservations';
/**
* Anthropic Messages API client. Structured output via forced tool-use: a single
* `emit_reservations` tool whose `input_schema` is the reservations schema, with
* `tool_choice` forcing it — the documented, reliable way to get structured JSON.
* PDFs go as native base64 `document` blocks (Anthropic reads scanned PDFs).
* Raw fetch (no SDK) to match the codebase's HTTP style.
*/
export class AnthropicClient implements LlmExtractionClient {
async extract(input: LlmExtractionInput): Promise<Record<string, unknown>[]> {
const base = (input.baseUrl ?? 'https://api.anthropic.com').replace(/\/+$/, '');
const url = `${base}/v1/messages`;
const content: unknown[] = [];
if (input.file) {
content.push({
type: 'document',
source: { type: 'base64', media_type: input.file.mimeType, data: input.file.data.toString('base64') },
});
}
content.push({
type: 'text',
text: input.text ? `${USER_TEXT}\n\n${input.text}` : USER_TEXT,
});
const body = {
model: input.model,
max_tokens: MAX_TOKENS,
system: input.prompt,
tools: [
{
name: TOOL_NAME,
description: 'Return the travel reservations extracted from the document.',
input_schema: input.jsonSchema,
},
],
tool_choice: { type: 'tool', name: TOOL_NAME },
messages: [{ role: 'user', content }],
};
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
let res: Response;
try {
res = await fetch(url, {
method: 'POST',
signal: controller.signal,
headers: {
'content-type': 'application/json',
'x-api-key': input.apiKey ?? '',
'anthropic-version': ANTHROPIC_VERSION,
},
body: JSON.stringify(body),
});
} finally {
clearTimeout(timer);
}
if (!res.ok) {
const detail = await res.text().catch(() => '');
throw new Error(`Anthropic request failed (${res.status}): ${detail.slice(0, 300)}`);
}
const data = (await res.json()) as {
stop_reason?: string;
content?: { type: string; name?: string; input?: { reservations?: unknown } }[];
};
if (data.stop_reason === 'refusal') {
throw new Error('Anthropic declined to process this document');
}
const toolUse = data.content?.find(b => b.type === 'tool_use' && b.name === TOOL_NAME);
const reservations = toolUse?.input?.reservations;
return Array.isArray(reservations) ? (reservations as Record<string, unknown>[]) : [];
}
}
const USER_TEXT = 'Extract every travel reservation from the following document as schema.org JSON-LD.';
@@ -0,0 +1,275 @@
/**
* NuExtract adapter for the OpenAI-compatible client.
*
* NuExtract (NuMind) is not an instruct model — it is fine-tuned to fill a JSON
* *template* whose leaf values are type tokens ("verbatim-string", "date-time",
* …). Fed a generic chat instruction it just echoes the schema back, which is
* why a plain prompt produces garbage. Run through Ollama/llama.cpp the template
* has to be embedded INLINE in the user message under a `# Template:` header
* (llama.cpp ignores vLLM's chat_template_kwargs), with temperature 0.
*
* Rather than ask NuExtract for the nested schema.org shape (its template format
* can't express per-@type conditional fields), we give it ONE flat union template
* — its sweet spot — and map the flat result back into the `KiReservation` shape
* the kitinerary mapper consumes, so the whole downstream pipeline is unchanged.
*/
/** Detect a NuExtract model id (e.g. `hf.co/numind/NuExtract-2.0-2B-GGUF`, `nuextract`). */
export function isNuExtractModel(model: string | undefined): boolean {
return !!model && /nuextract/i.test(model);
}
/**
* Flat union template covering every reservation type. NuExtract fills the
* relevant fields and returns the rest as null, so one template serves all docs.
*
* Deliberately flat (a single reservation, not an array). A small NuExtract (the
* 2B) returns an empty result when handed a nested `{ reservations: [ … ] }`
* array-of-objects template, but extracts reliably from a single flat object —
* so this path yields one reservation per document. Multi-segment itineraries
* (round trips) are left to the generic instruct path (qwen/cloud), which the
* system prompt already drives to emit every leg.
*/
export const NUEXTRACT_TEMPLATE = {
type: ['flight', 'train', 'bus', 'ferry', 'car', 'hotel', 'restaurant', 'event'],
name: 'verbatim-string',
booking_reference: 'verbatim-string',
operator: 'verbatim-string',
vehicle_number: 'verbatim-string',
// Departure/arrival double as a rental car's pick-up/return (place + time) — a
// separate pickup_location field only tempted the model to grab a nearby form
// label ("Location Terminal") instead of the actual depot.
from_name: 'verbatim-string',
from_code: 'verbatim-string',
to_name: 'verbatim-string',
to_code: 'verbatim-string',
departure_time: 'date-time',
arrival_time: 'date-time',
address: 'verbatim-string',
checkin_time: 'date-time',
checkout_time: 'date-time',
start_time: 'date-time',
end_time: 'date-time',
telephone: 'verbatim-string',
website: 'verbatim-string',
seat: 'verbatim-string',
travel_class: 'verbatim-string',
platform: 'verbatim-string',
// Verbatim so we parse the localized number ourselves — asking the model for a
// JSON number turns "1.580,22 €" (German thousands/decimal) into 1.49772.
price: 'verbatim-string',
currency: 'verbatim-string',
};
/**
* Build the NuExtract user-turn text: the template (pretty-printed with the
* indent the model cards use) followed by the document, under a `# Template:`
* header. This is the exact inline format the GGUF model cards document.
*/
export function buildNuExtractUserText(documentText: string): string {
return `# Template:\n${JSON.stringify(NUEXTRACT_TEMPLATE, null, 4)}\n${documentText}`;
}
/** NuExtract `type` token → schema.org reservation `@type`. */
const TYPE_MAP: Record<string, string> = {
flight: 'FlightReservation',
train: 'TrainReservation',
bus: 'BusReservation',
ferry: 'BoatReservation',
boat: 'BoatReservation',
cruise: 'BoatReservation',
car: 'RentalCarReservation',
hotel: 'LodgingReservation',
lodging: 'LodgingReservation',
restaurant: 'FoodEstablishmentReservation',
event: 'EventReservation',
};
/** Recursively drop null/undefined/blank leaves and the empty objects/arrays they leave behind. */
function clean(value: unknown): unknown {
if (Array.isArray(value)) {
const arr = value.map(clean).filter((v) => v !== undefined);
return arr.length ? arr : undefined;
}
if (value && typeof value === 'object') {
const out: Record<string, unknown> = {};
for (const [k, v] of Object.entries(value)) {
const c = clean(v);
if (c !== undefined) out[k] = c;
}
return Object.keys(out).length ? out : undefined;
}
if (value === null || value === undefined) return undefined;
if (typeof value === 'string' && value.trim() === '') return undefined;
return value;
}
/**
* Parse a localized money string into a plain number. Handles German
* ("1.580,22 €" → 1580.22) and English ("1,580.22"/"$89.00" → 89) grouping by
* treating the right-most separator as the decimal point. Returns null when there
* is no parseable amount.
*/
function parseAmount(raw: unknown): number | null {
if (typeof raw === 'number') return Number.isFinite(raw) ? raw : null;
if (typeof raw !== 'string') return null;
let s = raw.replace(/[^\d.,]/g, '');
if (!s) return null;
const lastComma = s.lastIndexOf(',');
const lastDot = s.lastIndexOf('.');
let decimal: ',' | '.' | null = null;
if (lastComma > -1 && lastDot > -1) {
decimal = lastComma > lastDot ? ',' : '.';
} else if (lastComma > -1) {
// A single comma with ≤2 trailing digits is a decimal point; otherwise grouping.
const parts = s.split(',');
decimal = parts.length === 2 && parts[1].length <= 2 ? ',' : null;
} else if (lastDot > -1) {
const parts = s.split('.');
decimal = parts.length === 2 && parts[1].length <= 2 ? '.' : null;
}
if (decimal) {
const grouping = decimal === ',' ? '.' : ',';
s = s.split(grouping).join('').replace(decimal, '.');
} else {
s = s.replace(/[.,]/g, '');
}
const n = Number(s);
return Number.isFinite(n) ? n : null;
}
/** Resolve an ISO 4217 currency from a symbol or code found in either field. */
function parseCurrency(...candidates: unknown[]): string | undefined {
for (const c of candidates) {
if (typeof c !== 'string') continue;
const s = c.toUpperCase();
if (s.includes('€') || /\bEUR\b/.test(s)) return 'EUR';
if (s.includes('£') || /\bGBP\b/.test(s)) return 'GBP';
if (s.includes('$') || /\bUSD\b/.test(s)) return 'USD';
if (s.includes('¥') || /\bJPY\b/.test(s)) return 'JPY';
const iso = s.match(/\b([A-Z]{3})\b/);
if (iso) return iso[1];
}
return undefined;
}
/** A venue's display name, falling back to the address (or a generic label) so a
* lodging/restaurant/event is never silently dropped when the model misses the name. */
function nameOrFallback(x: Record<string, unknown>, fallback: string): string {
const name = typeof x.name === 'string' ? x.name.trim() : '';
if (name) return name;
const address = typeof x.address === 'string' ? x.address.trim() : '';
if (address) return address.split(',')[0].trim();
return fallback;
}
/** Map one flat NuExtract reservation into a schema.org `KiReservation` node (or undefined). */
function buildNode(x: Record<string, unknown>): Record<string, unknown> | undefined {
const atType = TYPE_MAP[String(x.type ?? '').toLowerCase().trim()];
if (!atType) return undefined;
const node: Record<string, unknown> = {
'@type': atType,
reservationNumber: x.booking_reference,
seat: x.seat,
class: x.travel_class,
platform: x.platform,
price: parseAmount(x.price) ?? undefined,
priceCurrency: parseCurrency(x.currency, x.price),
};
switch (atType) {
case 'FlightReservation':
node.reservationFor = {
flightNumber: x.vehicle_number,
airline: x.operator ? { name: x.operator } : undefined,
departureAirport: { iataCode: x.from_code, name: x.from_name },
arrivalAirport: { iataCode: x.to_code, name: x.to_name },
departureTime: x.departure_time,
arrivalTime: x.arrival_time,
};
break;
case 'TrainReservation':
node.reservationFor = {
trainNumber: x.vehicle_number,
departureStation: { name: x.from_name },
arrivalStation: { name: x.to_name },
departureTime: x.departure_time,
arrivalTime: x.arrival_time,
};
break;
case 'BusReservation':
node.reservationFor = {
busNumber: x.vehicle_number,
departureBusStop: { name: x.from_name },
arrivalBusStop: { name: x.to_name },
departureTime: x.departure_time,
arrivalTime: x.arrival_time,
};
break;
case 'BoatReservation':
node.reservationFor = {
name: x.name ?? x.operator,
departureBoatTerminal: { name: x.from_name },
arrivalBoatTerminal: { name: x.to_name },
departureTime: x.departure_time,
arrivalTime: x.arrival_time,
};
break;
case 'LodgingReservation':
node.reservationFor = { name: nameOrFallback(x, 'Accommodation'), address: x.address, telephone: x.telephone, url: x.website };
node.checkinTime = x.checkin_time;
node.checkoutTime = x.checkout_time;
break;
case 'FoodEstablishmentReservation':
node.reservationFor = { name: nameOrFallback(x, 'Restaurant'), address: x.address, telephone: x.telephone, url: x.website };
node.startTime = x.start_time;
node.endTime = x.end_time;
break;
case 'RentalCarReservation':
// Pick-up / return ride the transport from/to fields (see template comment).
node.reservationFor = { name: x.name, rentalCompany: x.operator ? { name: x.operator } : undefined };
node.pickupTime = x.departure_time;
node.dropoffTime = x.arrival_time;
node.pickupLocation = { name: x.from_name, address: x.address };
node.dropoffLocation = { name: x.to_name };
break;
case 'EventReservation':
node.reservationFor = {
name: nameOrFallback(x, 'Event'),
startDate: x.start_time,
endDate: x.end_time,
location: { address: x.address, telephone: x.telephone, url: x.website },
};
node.startTime = x.start_time;
node.endTime = x.end_time;
break;
}
return clean(node) as Record<string, unknown> | undefined;
}
/**
* Convert a parsed NuExtract response into schema.org `KiReservation` nodes.
* Accepts the `{ reservations: [...] }` wrapper the template asks for, a bare
* array, or a single object. Unrecognized/empty entries are dropped.
*/
export function nuExtractToKiReservations(parsed: unknown): Record<string, unknown>[] {
const wrapped = (parsed as { reservations?: unknown })?.reservations;
const list = Array.isArray(wrapped)
? wrapped
: Array.isArray(parsed)
? parsed
: parsed && typeof parsed === 'object'
? [parsed]
: [];
const out: Record<string, unknown>[] = [];
for (const entry of list) {
if (entry && typeof entry === 'object') {
const node = buildNode(entry as Record<string, unknown>);
if (node) out.push(node);
}
}
return out;
}
@@ -0,0 +1,121 @@
import type { LlmExtractionClient, LlmExtractionInput } from '../llm-provider.interface';
import { isNuExtractModel, buildNuExtractUserText, nuExtractToKiReservations } from './nuextract';
// Generous: a local CPU model (Ollama, no GPU) may cold-load several GB and then
// take a few minutes on a longer document before the first token.
const TIMEOUT_MS = 300_000;
const MAX_TOKENS = 4096;
/**
* OpenAI-compatible chat-completions client. Covers both the "openai" cloud
* provider and the "local" provider (Ollama / vLLM / llama.cpp / LM Studio),
* which all expose `POST {baseUrl}/chat/completions`. Native binaries (PDF) are
* sent as an OpenAI `file` content part; text goes as a text part. Uses the
* global fetch (no SDK) to match the codebase's HTTP style.
*
* A NuExtract model (detected by id) takes a different request shape: the JSON
* template inlined in a single user message, no system prompt and no
* `response_format` (see ./nuextract.ts) — that's how the fine-tune expects to
* be driven; the generic instruct path applies to every other model.
*/
export class OpenAiCompatibleClient implements LlmExtractionClient {
async extract(input: LlmExtractionInput): Promise<Record<string, unknown>[]> {
const base = (input.baseUrl ?? 'https://api.openai.com/v1').replace(/\/+$/, '');
const url = `${base}/chat/completions`;
const nuextract = isNuExtractModel(input.model);
const userContent: unknown[] = nuextract
? [{ type: 'text', text: buildNuExtractUserText(input.text ?? '') }]
: [{ type: 'text', text: input.text ? `${USER_TEXT}\n\n${input.text}` : USER_TEXT }];
// Only genuine images go natively (as image_url) — OpenAI-compatible servers
// (notably Ollama) reject `file`/PDF content parts. PDFs reach this client as
// pre-extracted text (see llm-parse.service.ts), never as bytes.
if (!nuextract && input.file && input.file.mimeType.startsWith('image/')) {
const b64 = input.file.data.toString('base64');
userContent.push({
type: 'image_url',
image_url: { url: `data:${input.file.mimeType};base64,${b64}` },
});
}
const body = {
model: input.model,
max_tokens: MAX_TOKENS,
// Extraction is a deterministic task — Ollama defaults to 0.7, which makes
// small models (NuExtract) drop fields or return empty. Pin to 0.
temperature: 0,
// NuExtract wants the template (in the user turn) to be the only instruction
// — a system prompt or a json_schema grammar derails it.
messages: nuextract
? [{ role: 'user', content: userContent }]
: [
{ role: 'system', content: input.prompt },
{ role: 'user', content: userContent },
],
...(nuextract
? {}
: {
response_format: {
type: 'json_schema' as const,
json_schema: { name: 'reservations', schema: input.jsonSchema, strict: false },
},
}),
};
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
let res: Response;
try {
res = await fetch(url, {
method: 'POST',
signal: controller.signal,
headers: {
'content-type': 'application/json',
...(input.apiKey ? { authorization: `Bearer ${input.apiKey}` } : {}),
},
body: JSON.stringify(body),
});
} finally {
clearTimeout(timer);
}
if (!res.ok) {
const detail = await res.text().catch(() => '');
throw new Error(`LLM request failed (${res.status}): ${detail.slice(0, 300)}`);
}
const data = (await res.json()) as {
choices?: { message?: { content?: string } }[];
};
const content = data.choices?.[0]?.message?.content;
return nuextract ? parseNuExtract(content) : parseReservations(content);
}
}
/** Strip code fences and JSON.parse; `null` on failure. */
function parseJson(content: string | undefined | null): unknown {
if (!content) return null;
const stripped = content.trim().replace(/^```(?:json)?/i, '').replace(/```$/, '').trim();
try {
return JSON.parse(stripped);
} catch {
return null;
}
}
/** Parse a NuExtract response and map its flat template output to KiReservation nodes. */
function parseNuExtract(content: string | undefined | null): Record<string, unknown>[] {
return nuExtractToKiReservations(parseJson(content));
}
const USER_TEXT = 'Extract every travel reservation from the following document as schema.org JSON-LD.';
/** Tolerant parse: strip code fences, JSON.parse, pull `reservations`. `[]` on failure. */
function parseReservations(content: string | undefined | null): Record<string, unknown>[] {
const parsed = parseJson(content);
if (Array.isArray(parsed)) return parsed as Record<string, unknown>[];
if (parsed && typeof parsed === 'object' && Array.isArray((parsed as { reservations?: unknown }).reservations)) {
return (parsed as { reservations: Record<string, unknown>[] }).reservations;
}
return [];
}
@@ -0,0 +1,24 @@
import type { LlmExtractionClient } from './llm-provider.interface';
import type { ResolvedLlmConfig } from '../../services/llmConfig';
import { OpenAiCompatibleClient } from './clients/openai-compatible.client';
import { AnthropicClient } from './clients/anthropic.client';
/**
* Pick the provider client for a resolved config.
* - 'anthropic' → Anthropic Messages API client
* - 'openai' | 'local' → OpenAI-compatible client (cloud or local base URL)
*/
export function createLlmClient(config: ResolvedLlmConfig): LlmExtractionClient {
switch (config.provider) {
case 'anthropic':
return new AnthropicClient();
case 'openai':
case 'local':
return new OpenAiCompatibleClient();
// TODO(nuextract): add a NuExtract template adapter here (local vision model
// with its own template-fill API) once the OpenAI-compatible path proves
// insufficient for small local models — see the design seam in the plan.
default:
return new OpenAiCompatibleClient();
}
}
@@ -0,0 +1,55 @@
import { db } from '../../db/database';
import { ADDON_IDS } from '../../addons';
import { isAddonEnabled } from '../../services/adminService';
import { getUserSettings, getDecryptedUserSetting } from '../../services/settingsService';
import { decryptLlmApiKey, LLM_PROVIDERS, type LlmProvider, type ResolvedLlmConfig } from '../../services/llmConfig';
function asProvider(v: unknown): LlmProvider | null {
return typeof v === 'string' && (LLM_PROVIDERS as string[]).includes(v) ? (v as LlmProvider) : null;
}
function readInstanceConfig(): ResolvedLlmConfig | null {
const row = db.prepare('SELECT config FROM addons WHERE id = ?').get(ADDON_IDS.LLM_PARSING) as { config?: string } | undefined;
if (!row?.config) return null;
let cfg: Record<string, unknown>;
try {
cfg = JSON.parse(row.config || '{}');
} catch {
return null;
}
const provider = asProvider(cfg.provider);
const model = typeof cfg.model === 'string' ? cfg.model.trim() : '';
if (!provider || !model) return null;
return {
provider,
model,
baseUrl: typeof cfg.baseUrl === 'string' && cfg.baseUrl.trim() ? cfg.baseUrl.trim() : undefined,
apiKey: decryptLlmApiKey(cfg.apiKey),
multimodal: cfg.multimodal === true,
};
}
function readUserConfig(userId: number): ResolvedLlmConfig | null {
const settings = getUserSettings(userId);
const provider = asProvider(settings.llm_provider);
const model = typeof settings.llm_model === 'string' ? settings.llm_model.trim() : '';
if (!provider || !model) return null;
const apiKey = getDecryptedUserSetting(userId, 'llm_api_key') ?? undefined;
return {
provider,
model,
baseUrl: typeof settings.llm_base_url === 'string' && settings.llm_base_url.trim() ? settings.llm_base_url.trim() : undefined,
apiKey,
multimodal: settings.llm_multimodal === true,
};
}
/**
* Resolve the effective LLM config for a user, gated by the addon.
* Order: addon disabled → null; admin instance config wins; else per-user config;
* else null. This is the single place the API key is decrypted.
*/
export function resolveLlmConfig(userId: number): ResolvedLlmConfig | null {
if (!isAddonEnabled(ADDON_IDS.LLM_PARSING)) return null;
return readInstanceConfig() ?? readUserConfig(userId);
}
@@ -0,0 +1,45 @@
import { Controller, Get, Post, Query, Body, Res, UseGuards } from '@nestjs/common';
import type { Response } from 'express';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { AdminGuard } from '../auth/admin.guard';
import { LlmLocalService } from './llm-local.service';
/**
* Admin-only management of a local LLM server (Ollama): list installed models and
* pull new ones (e.g. NuExtract). Used by the AI-parsing addon config UI.
*/
@Controller('api/admin/llm/local')
@UseGuards(JwtAuthGuard, AdminGuard)
export class LlmLocalController {
constructor(private readonly local: LlmLocalService) {}
@Get('models')
models(@Query('baseUrl') baseUrl?: string) {
return this.local.listModels(baseUrl);
}
/**
* Stream a model pull. Proxies Ollama's NDJSON progress lines
* ({ status, total?, completed? }) straight to the client, which reads the
* response body to render a progress bar. Uses @Res() to stream manually.
*/
@Post('pull')
async pull(@Body() body: { baseUrl?: string; model?: string }, @Res() res: Response): Promise<void> {
const stream = await this.local.pull(body?.baseUrl, body?.model ?? '');
res.status(200);
res.setHeader('Content-Type', 'application/x-ndjson');
res.setHeader('Cache-Control', 'no-cache');
const reader = stream.getReader();
try {
for (;;) {
const { done, value } = await reader.read();
if (done) break;
res.write(Buffer.from(value));
}
} catch {
// Upstream dropped mid-pull — close the response; the client surfaces it.
} finally {
res.end();
}
}
}
@@ -0,0 +1,63 @@
import { Injectable, HttpException } from '@nestjs/common';
/**
* Admin helpers for managing a local OpenAI-compatible LLM server (Ollama).
* Talks to Ollama's *management* API (`/api/tags`, `/api/pull`), which lives at
* the server root — not the `/v1` OpenAI-compatible path the extraction client
* uses. Admin-only (guarded at the controller); the base URL is admin-supplied
* and typically points at a localhost Ollama, so SSRF guarding is intentionally
* not applied (it would block localhost) — we only validate the protocol.
*/
@Injectable()
export class LlmLocalService {
/** Derive the Ollama root from a configured base URL (strip a trailing /v1). */
ollamaRoot(baseUrl: string | undefined): string {
const raw = (baseUrl ?? 'http://localhost:11434').trim();
let url: URL;
try {
url = new URL(raw);
} catch {
throw new HttpException({ error: 'Invalid base URL' }, 400);
}
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
throw new HttpException({ error: 'Base URL must be http(s)' }, 400);
}
return raw.replace(/\/+$/, '').replace(/\/v1$/, '');
}
/** List models already pulled on the local server. */
async listModels(baseUrl: string | undefined): Promise<{ models: { name: string; size: number }[] }> {
const root = this.ollamaRoot(baseUrl);
let res: Response;
try {
res = await fetch(`${root}/api/tags`, { signal: AbortSignal.timeout(10_000) });
} catch {
throw new HttpException({ error: `Could not reach local LLM server at ${root}` }, 502);
}
if (!res.ok) throw new HttpException({ error: `Local LLM server error (${res.status})` }, 502);
const data = (await res.json()) as { models?: { name?: string; size?: number }[] };
const models = (data.models ?? []).map(m => ({ name: m.name ?? '', size: m.size ?? 0 })).filter(m => m.name);
return { models };
}
/**
* Start a streamed pull. Returns the upstream NDJSON body so the controller can
* pipe Ollama's progress lines straight to the client.
*/
async pull(baseUrl: string | undefined, model: string): Promise<ReadableStream<Uint8Array>> {
if (!model?.trim()) throw new HttpException({ error: 'model is required' }, 400);
const root = this.ollamaRoot(baseUrl);
let res: Response;
try {
res = await fetch(`${root}/api/pull`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ model: model.trim(), stream: true }),
});
} catch {
throw new HttpException({ error: `Could not reach local LLM server at ${root}` }, 502);
}
if (!res.ok || !res.body) throw new HttpException({ error: `Pull failed (${res.status})` }, 502);
return res.body;
}
}
@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { LlmParseService } from './llm-parse.service';
import { LlmLocalService } from './llm-local.service';
import { LlmLocalController } from './llm-local.controller';
/** Provides the LLM booking-import fallback; imported by BookingImportModule. */
@Module({
controllers: [LlmLocalController],
providers: [LlmParseService, LlmLocalService],
exports: [LlmParseService],
})
export class LlmParseModule {}
@@ -0,0 +1,163 @@
import type { KiReservation } from '../booking-import/kitinerary.types';
import { createLlmClient } from './llm-client.factory';
import { resolveLlmConfig } from './llm-config.resolver';
import { buildSystemPrompt, KI_RESERVATION_JSON_SCHEMA } from './llm-prompt';
import type { LlmExtractionInput } from './llm-provider.interface';
import { isPdf, extractText } from './text-extract';
import { routeExtraction, detectFlightNumbers } from './router/extraction-router';
import { Injectable } from '@nestjs/common';
import { kiReservationSchema } from '@trek/shared';
const MIME_BY_EXT: Record<string, string> = {
'.pdf': 'application/pdf',
};
export interface LlmParseResult {
kiItems: KiReservation[];
warnings: string[];
}
/**
* Orchestrates the LLM fallback: resolve config → pick client → build input
* (native bytes vs extracted text by the `multimodal` flag) → call provider →
* validate the response → return schema.org `KiReservation[]` for the shared
* mapper. Never throws for content/provider reasons — degrades to `[]` + a
* warning, mirroring the kitinerary extractor's tolerance.
*/
@Injectable()
export class LlmParseService {
/** True when the addon is enabled AND a usable config resolves for this user. */
isAvailable(userId: number): boolean {
return resolveLlmConfig(userId) !== null;
}
async parse(file: { buffer: Buffer; originalName: string }, userId: number): Promise<LlmParseResult> {
const config = resolveLlmConfig(userId);
if (!config) return { kiItems: [], warnings: ['AI parsing is not configured'] };
const warnings: string[] = [];
const input: LlmExtractionInput = {
prompt: buildSystemPrompt(),
jsonSchema: KI_RESERVATION_JSON_SCHEMA,
model: config.model,
baseUrl: config.baseUrl,
apiKey: config.apiKey,
};
// Native PDF only for Anthropic (its document block reads text AND scans).
// OpenAI-compatible servers (incl. Ollama/NuExtract) can't ingest PDFs/`file`
// parts, so every other provider gets extracted text.
try {
if (config.provider === 'anthropic' && isPdf(file.originalName)) {
input.file = { mimeType: MIME_BY_EXT['.pdf'], data: file.buffer };
console.debug(
`[DEBUG] Extracted (native PDF, ${file.buffer.length} bytes) sent to ${config.provider}: ${file.originalName}`,
);
} else {
input.text = await extractText(file.buffer, file.originalName);
// Cap the text fed to the model. A flight itinerary lists its legs throughout a long
// document, so it keeps a generous window; a single booking has the essentials up top,
// so cap it tighter to keep CPU prompt-eval fast (a 11-page rental voucher was ~200s at
// 16k, the booking data sits in the first ~2k). Cloud single-shot keeps the tight cap.
const MAX_EXTRACT_CHARS =
config.provider !== 'local' ? 4000 : detectFlightNumbers(input.text).length > 0 ? 16000 : 6000;
if (input.text.length > MAX_EXTRACT_CHARS) input.text = input.text.slice(0, MAX_EXTRACT_CHARS);
console.debug(`[DEBUG] Extracted text from ${file.originalName} (${input.text.length} chars):\n`, input.text);
if (!input.text.trim()) {
return {
kiItems: [],
warnings: [`${file.originalName}: no readable text found (a scanned PDF needs a cloud/vision provider)`],
};
}
}
} catch (err) {
return {
kiItems: [],
warnings: [`${file.originalName}: could not read file — ${err instanceof Error ? err.message : String(err)}`],
};
}
// Local provider (Ollama): go through the layered extraction router — vendor
// templates → decompose + grammar-enforced per-reservation extraction → validate
// + repair. Far more reliable on small CPU models than the single-shot path below
// (which stays for cloud providers, whose strong models handle one-shot well).
if (config.provider === 'local' && input.text) {
try {
const routed = await routeExtraction(input.text, {
baseUrl: config.baseUrl ?? 'http://localhost:11434/v1',
model: config.model,
apiKey: config.apiKey,
});
return { kiItems: routed.kiItems, warnings: [...warnings, ...routed.warnings] };
} catch (err) {
return {
kiItems: [],
warnings: [`${file.originalName}: AI parsing failed — ${err instanceof Error ? err.message : String(err)}`],
};
}
}
let raw: Record<string, unknown>[];
try {
raw = await createLlmClient(config).extract(input);
console.debug('[DEBUG] Raw LLM Response: ', raw);
} catch (err) {
return {
kiItems: [],
warnings: [`${file.originalName}: AI parsing failed — ${err instanceof Error ? err.message : String(err)}`],
};
}
const kiItems: KiReservation[] = [];
for (const node of raw) {
const result = kiReservationSchema.safeParse(node);
if (result.success) kiItems.push(normalizeNode(result.data) as unknown as KiReservation);
else warnings.push(`${file.originalName}: skipped an unrecognized AI result`);
}
return { kiItems, warnings };
}
}
/** Root-level keys in the schema.org reservation shape; everything else is trip-specific. */
const ROOT_KEYS = new Set([
'@type',
'reservationNumber',
'checkinTime',
'checkoutTime',
'pickupTime',
'dropoffTime',
'startTime',
'endTime',
'pickupLocation',
'dropoffLocation',
'seat',
'class',
'platform',
'price',
'priceCurrency',
'reservationFor',
]);
/**
* Small models often flatten the type-specific fields (flightNumber, airline,
* departureAirport, …) onto the reservation root instead of nesting them under
* `reservationFor`, which is where the kitinerary mapper reads them. When
* `reservationFor` is missing/empty, fold the non-root keys into it so the
* existing mappers work unchanged.
*/
function normalizeNode(node: Record<string, unknown>): Record<string, unknown> {
const rf = node.reservationFor;
if (rf && typeof rf === 'object' && Object.keys(rf as object).length > 0) return node;
const out: Record<string, unknown> = {};
const reservationFor: Record<string, unknown> = {};
for (const [k, v] of Object.entries(node)) {
if (ROOT_KEYS.has(k)) out[k] = v;
else reservationFor[k] = v;
}
// Nothing to fold (no flattened type fields) — leave the node as-is.
if (Object.keys(reservationFor).length === 0) return node;
out.reservationFor = reservationFor;
return out;
}
+36
View File
@@ -0,0 +1,36 @@
import { KI_RESERVATION_JSON_SCHEMA, KI_RESERVATION_TYPES } from '@trek/shared';
export { KI_RESERVATION_JSON_SCHEMA };
/**
* System instructions telling the model to emit schema.org reservation JSON-LD
* in exactly the shape the kitinerary binary produces — so the result feeds the
* same `mapReservations()` mapper. Pure (no I/O) so it's unit-testable.
*/
export function buildSystemPrompt(): string {
return [
'You extract travel reservations from a document (a booking confirmation, ticket, or itinerary).',
'Return ONLY a JSON object of the form { "reservations": [ ... ] } — no prose, no markdown.',
'Each reservation is a schema.org JSON-LD object whose "@type" is one of:',
KI_RESERVATION_TYPES.map((t) => ` - ${t}`).join('\n'),
'Put the booking/confirmation code in "reservationNumber" on each reservation.',
'All dates/times are plain ISO 8601 local strings, e.g. "2026-06-11T10:00:00" (no timezone wrapper objects).',
'IMPORTANT: nest the type-specific fields INSIDE a "reservationFor" object — do NOT place them at the top level of the reservation.',
'Populate "reservationFor" with the type-specific fields:',
' FlightReservation: { flightNumber, airline:{name,iataCode}, departureAirport:{iataCode,name,geo:{latitude,longitude}}, arrivalAirport:{...}, departureTime, arrivalTime }',
' TrainReservation: { trainNumber, trainName, departureStation:{name,geo}, arrivalStation:{name,geo}, departureTime, arrivalTime }',
' BusReservation: { busNumber, busName, departureBusStop:{name,geo}, arrivalBusStop:{name,geo}, departureTime, arrivalTime }',
' BoatReservation: { name, departureBoatTerminal:{name,geo}, arrivalBoatTerminal:{name,geo}, departureTime, arrivalTime }',
' LodgingReservation: { name, address, geo:{latitude,longitude}, telephone, url } — put check-in/out in root "checkinTime"/"checkoutTime"',
' FoodEstablishmentReservation: { name, address, geo, telephone, url } — put booking time in root "startTime"/"endTime"',
' RentalCarReservation: { name, model, make, rentalCompany:{name} } — put pickup/dropoff times in root "pickupTime"/"dropoffTime", and the pickup AND return stations in root "pickupLocation" and "dropoffLocation", each {name,address,geo:{latitude,longitude}}',
' EventReservation / TouristAttractionVisit: { name, startDate, endDate, location:{name,address,geo,telephone,url} }',
'When present, also include at the reservation ROOT: "seat", "class" (fare/cabin class), "platform" (trains/buses), and the total "price" (a number) with "priceCurrency" (ISO 4217 code, e.g. EUR).',
'Extract EVERY flight/segment in the document, including return legs — a round trip has TWO OR MORE flights, and each row of a flight table is a separate reservation. Do NOT stop after the first.',
"Each flight shares the booking's reservationNumber. Use the date shown for that specific flight as its departureTime; if a flight lists only one date (no separate arrival time), leave arrivalTime null — never reuse another flight's date.",
'If the document contains no recognizable reservation, return { "reservations": [] }.',
].join('\n');
}
/** Short user-turn instruction that accompanies the document content. */
export const USER_INSTRUCTION = 'Extract every travel reservation from the following document as schema.org JSON-LD.';
@@ -0,0 +1,30 @@
/** A single binary file (e.g. a PDF) sent natively to a multimodal provider. */
export interface LlmExtractionFile {
mimeType: string;
data: Buffer;
}
/** Everything a provider client needs to extract reservations from one document. */
export interface LlmExtractionInput {
/** System instructions enumerating the schema.org shape (see llm-prompt.ts). */
prompt: string;
/** JSON Schema describing `{ reservations: KiReservation[] }`. */
jsonSchema: object;
model: string;
baseUrl?: string;
apiKey?: string;
/** Pre-extracted text (text-like files, or text-only-model mode). */
text?: string;
/** Native binary (PDF) for multimodal providers. */
file?: LlmExtractionFile;
}
/**
* A provider client turns one document into raw schema.org reservation objects.
* It returns the parsed `reservations` array (best-effort: `[]` on a malformed or
* empty response, never throwing for content reasons). The caller validates and
* maps via the shared kitinerary mapper.
*/
export interface LlmExtractionClient {
extract(input: LlmExtractionInput): Promise<Record<string, unknown>[]>;
}
@@ -0,0 +1,232 @@
/**
* The extraction router — tuned for ONE model call per document.
*
* 1. exactly one grammar-ENFORCED call (Ollama native `format`):
* - flights → a flat ARRAY of legs in a single call (a capable model fills every
* leg at once — far faster than one call per leg);
* - otherwise → one flat single-reservation call, with a type-specific schema when the
* type is obvious from keywords (the common case), else a union schema the model picks;
* 2. booking-wide fields (PNR, total price, currency) and the overnight-arrival day are filled
* DETERMINISTICALLY from the text — the model isn't asked to reason about them, and the
* document's own currency symbol corrects the model where it misreads it.
*
* A capable instruct model (e.g. Qwen3-8B with thinking disabled) reads name/address/dates/
* legs reliably across formats, so there's no per-vendor template layer to drift or distort —
* the model handles the long tail and Schicht 2 backstops the money/reference fields. No per-leg
* fan-out and no repair round-trips: that 4–8× call count was the latency that made a multi-leg
* flight take minutes on a CPU host. The flat results map into the kitinerary pipeline via the
* existing `nuExtractToKiReservations` mapper, so nothing downstream changes.
*/
import type { KiReservation } from '../../booking-import/kitinerary.types';
import { nuExtractToKiReservations } from '../clients/nuextract';
import { FLAT_SCHEMA_BY_TYPE, FLIGHTS_ARRAY_SCHEMA, UNION_SINGLE_SCHEMA, type FlatType, type FlatLike } from './flat-schemas';
import { extractEnforced } from './ollama-format.client';
export interface RouterContext {
baseUrl: string;
model: string;
apiKey?: string;
}
const TRANSPORT_TYPES: FlatType[] = ['flight', 'train', 'bus', 'ferry'];
/** Per-type guidance for the single-reservation prompt. `price`/`currency` are the total
* paid and its currency on every type; `address` is the venue street address for stays/venues. */
const TYPE_HINT: Record<FlatType, string> = {
flight: 'flight. vehicle_number = flight number, from_code/to_code = IATA codes, times = full ISO, price/currency = total fare.',
train: 'train. from_name/to_name = stations, vehicle_number = train number, times = full ISO, price/currency = total fare.',
bus: 'bus. from_name/to_name = stops, times = full ISO, price/currency = total fare.',
ferry: 'ferry/cruise. from_name/to_name = terminals/ports, times = full ISO, price/currency = total fare.',
car: 'rental car. operator = the rental company, from_name = pick-up location, to_name = return location (may differ), departure_time = pick-up, arrival_time = return, price/currency = total rental cost.',
hotel: 'hotel stay. name = hotel name, address = the hotel street address, checkin_time/checkout_time = full ISO date-time, price/currency = total paid.',
restaurant: 'restaurant booking. name = the restaurant, address = its street address, start_time = the reservation date-time, price/currency = total if shown.',
event: 'event/attraction. name = the event/ticket, address = the venue, start_time/end_time = full ISO, price/currency = ticket price.',
};
/** Keyword → reservation type, so an obvious document skips the costlier union/strong path. */
const TYPE_KEYWORDS: [FlatType, RegExp][] = [
['car', /\b(sixt|europcar|hertz|avis|enterprise|mietwagen|rental\s*car|autovermietung|anmietung|r(?:ü|ue)ckgabe|pick-?up|drop-?off)\b/i],
['hotel', /\b(hotel|check-?in|check-?out|(?:ü|ue)bernachtung|zimmer|room\s*night|lodging|airbnb|b&b|hostel|pension)\b/i],
['train', /\b(deutsche\s*bahn|bahn|train|railway|\bice\b|\bzug\b|gleis|sncf|trenitalia|renfe)\b/i],
['bus', /\b(flixbus|\bbus\b|coach|omnibus)\b/i],
['ferry', /\b(f(?:ä|ae)hre|ferry|cruise|kreuzfahrt)\b/i],
['restaurant', /\b(restaurant|\btisch\b|table\s*for|men(?:ü|u)|gedeck)\b/i],
['event', /\b(ticket|concert|konzert|veranstaltung|eintritt|admission)\b/i],
];
function detectType(text: string): FlatType | null {
for (const [type, re] of TYPE_KEYWORDS) if (re.test(text)) return type;
return null;
}
/** Detect flight numbers (order-preserving, deduped) — also the "is this a flight doc" test. */
export function detectFlightNumbers(text: string): string[] {
const out: string[] = [];
for (const m of text.matchAll(/\b([A-Z]{2})\s?(\d{2,4})\b/g)) {
const fn = `${m[1]}${m[2]}`;
if (!out.includes(fn)) out.push(fn);
}
return out;
}
/**
* The booking/confirmation code, pulled once for the whole document. Covers the German
* "Bestätigungs-Code" (Airbnb) and "Reservation No." (rental brokers) on top of the PNR /
* Buchungsnummer / Confirmation forms. The match is left-most in the text, so a customer
* "Reservation No." that precedes a vendor "Supplier Reference" wins.
*/
export function extractBookingRef(text: string): string | undefined {
// The captured code must contain a digit: real PNRs/booking codes effectively always
// do, while the case-insensitive [A-Z0-9] class would otherwise grab a following prose
// word ("Confirmation\nThank you…" → "Thank") after a bare label.
const m = text.match(
/(?:PNR|Buchungs(?:code|nummer|referenz)|Booking\s*(?:reference|code|number)|Confirmation\s*(?:number|code)?|Reservierungsnummer|Reservation\s*(?:No\.?|Number|Nr\.?)|Best(?:ä|ae)tigungs[-\s]?(?:nummer|code)|(?:Expedia[-\s]*)?Reiseplan|Reference)\s*:?\s*((?=[A-Z0-9]*\d)[A-Z0-9]{5,})/i,
);
return m?.[1];
}
/** Currency symbol/code → ISO 4217, or undefined when none is recognised. */
export function normCurrency(token: string): string | undefined {
const u = token.toUpperCase();
if (u.includes('€')) return 'EUR';
if (u.includes('$')) return 'USD';
if (u.includes('£')) return 'GBP';
if (u.includes('¥')) return 'JPY';
return /^[A-Z]{3}$/.test(u) ? u : undefined;
}
/** The booking total, pulled deterministically (raw amount string + ISO currency). */
export function extractTotalPrice(text: string): { price: string; currency?: string } | null {
const strip = (s: string) => s.replace(/[€$£¥\s]/g, '');
// A labeled total: "Gesamtpreis: 1.234,56 €", "Total Amount 99 USD", "Bezahlter Betrag 651,86 €".
const labeled = text.match(
/(?:Gesamtpreis|Gesamtbetrag|Gesamtsumme|Total(?:\s*(?:price|amount))?|Amount|Summe|Betrag)\s*:?\s*([€$£¥]?\s*\d[\d.,]*)\s*(EUR|USD|GBP|CHF|JPY|€|\$|£|¥)?/i,
);
if (labeled) return { price: strip(labeled[1]), currency: normCurrency(labeled[2] ?? labeled[1]) };
// Fallback: a standalone amount carrying a currency symbol on its own line (e.g. a voucher's
// "¥9,400") — the price sits far from any label the pattern above can anchor to.
const symbol = text.match(/^\s*([€$£¥]\s?\d[\d.,]*)\b/m);
if (symbol) return { price: strip(symbol[1]), currency: normCurrency(symbol[1]) };
return null;
}
/**
* Derive a transport leg's arrival DATE deterministically: same day as departure, rolled to
* the next day only when the arrival clock time is earlier than departure (an overnight leg).
* The model reads clock times reliably but mishandles the day rollover.
*/
export function fixArrivalDate(flat: FlatLike): FlatLike {
if (!TRANSPORT_TYPES.includes(flat.type)) return flat;
const dep = /(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2})/.exec(String(flat.departure_time ?? ''));
const arr = /(\d{2}:\d{2})/.exec(String(flat.arrival_time ?? ''));
if (!dep || !arr) return flat;
const [, depDate, depTime] = dep;
const arrTime = arr[1];
const d = new Date(`${depDate}T00:00:00Z`);
if (arrTime < depTime) d.setUTCDate(d.getUTCDate() + 1);
flat.arrival_time = `${d.toISOString().slice(0, 10)}T${arrTime}:00`;
return flat;
}
const DATE_FIELDS = ['departure_time', 'arrival_time', 'checkin_time', 'checkout_time', 'start_time', 'end_time'] as const;
/**
* Coerce a date value to ISO 8601. Models occasionally ignore the format instruction and
* emit a natural-language date ("Aug 23 2025 13:30"), which the downstream `splitIso` then
* slices into garbage ("Aug 23 202"). Keep already-ISO values untouched; otherwise parse and
* reformat. (The server runs in UTC, so the components line up.)
*/
function toIso(value: unknown): unknown {
if (typeof value !== 'string' || !value.trim()) return value;
if (/^\d{4}-\d{2}-\d{2}/.test(value)) return value;
const t = Date.parse(value);
if (Number.isNaN(t)) return value;
const d = new Date(t);
const p = (n: number) => String(n).padStart(2, '0');
return `${d.getUTCFullYear()}-${p(d.getUTCMonth() + 1)}-${p(d.getUTCDate())}T${p(d.getUTCHours())}:${p(d.getUTCMinutes())}:00`;
}
/** Normalize every date-ish field on a flat reservation to ISO before mapping. */
function normalizeDates(flat: FlatLike): FlatLike {
for (const f of DATE_FIELDS) if (f in flat) (flat as Record<string, unknown>)[f] = toIso((flat as Record<string, unknown>)[f]);
return flat;
}
/** One enforced call extracting every flight leg as a flat array. */
async function extractFlights(text: string, ctx: RouterContext): Promise<FlatLike[]> {
const system =
'Extract EVERY flight segment in the document (each flight number is one segment; a round trip has the ' +
'outbound AND the return legs). vehicle_number = the flight number, from_code/to_code = 3-letter IATA codes, ' +
"departure_time/arrival_time = full ISO 'YYYY-MM-DDTHH:MM:00' using the date of the section heading each flight is listed under.";
const out = await extractEnforced({ baseUrl: ctx.baseUrl, model: ctx.model, apiKey: ctx.apiKey, system, user: `Document:\n${text}`, schema: FLIGHTS_ARRAY_SCHEMA, numPredict: 900 });
const legs = Array.isArray((out as { flights?: unknown })?.flights) ? (out as { flights: Record<string, unknown>[] }).flights : [];
return legs.map((leg) => fixArrivalDate(normalizeDates({ ...leg, type: 'flight' as FlatType })));
}
/** One enforced call for a single reservation — a type-specific schema when the type is
* obvious from keywords, else a union schema the model fills with the type it picks. */
async function extractSingle(text: string, ctx: RouterContext): Promise<FlatLike> {
const known = detectType(text);
const call = (schema: Record<string, unknown>, hint: string) =>
extractEnforced({
baseUrl: ctx.baseUrl, model: ctx.model, apiKey: ctx.apiKey,
system: `Extract the single reservation from the document into the flat fields. ${hint} Omit any field that is truly absent.`,
user: `Document:\n${text}`,
schema,
});
if (known) {
const out = (await call(FLAT_SCHEMA_BY_TYPE[known], `It is a ${TYPE_HINT[known]}`)) ?? {};
return fixArrivalDate(normalizeDates({ ...out, type: known }));
}
const out = (await call(UNION_SINGLE_SCHEMA, 'Pick the correct "type".')) ?? {};
const type = (typeof out.type === 'string' ? out.type : 'hotel') as FlatType;
return fixArrivalDate(normalizeDates({ ...out, type }));
}
/**
* Schicht 2 — fill the booking-wide fields the per-reservation model call doesn't reliably
* carry: the confirmation/PNR and the booking total + its currency. The confirmation and a
* missing price are filled from the document; the currency is taken from the document's own
* symbol/code (authoritative — small models misread it), correcting the model where needed.
*/
function fillBookingWideFields(flats: Record<string, unknown>[], text: string): void {
const ref = extractBookingRef(text);
const total = extractTotalPrice(text);
// A small model sometimes emits an empty string for a price it didn't find, which is
// not `null` — treat blank/whitespace as "no price" so the deterministic total still wins.
const priceMissing = (v: unknown) => v == null || (typeof v === 'string' && v.trim() === '');
flats.forEach((f, i) => {
if (!f.booking_reference && ref) f.booking_reference = ref;
// The total belongs to the booking, so handle it once (the first item).
if (i === 0 && total) {
if (priceMissing(f.price)) f.price = total.price;
// The document's own currency symbol/code is authoritative; let it override the
// model's guess (small models misread "¥" as "$").
if (total.currency) f.currency = total.currency;
}
});
}
/**
* Run the router on extracted document text and return schema.org KiReservation nodes.
* Returns `[]` (never throws for content reasons) so the caller degrades gracefully.
*/
export async function routeExtraction(text: string, ctx: RouterContext): Promise<{ kiItems: KiReservation[]; warnings: string[] }> {
const warnings: string[] = [];
// Schicht 1 — exactly one model call.
let flats: FlatLike[];
try {
flats = detectFlightNumbers(text).length > 0 ? await extractFlights(text, ctx) : [await extractSingle(text, ctx)];
} catch (err) {
return { kiItems: [], warnings: [`AI parsing failed — ${err instanceof Error ? err.message : String(err)}`] };
}
// Schicht 2 — deterministic booking-wide fields the per-call schema doesn't carry.
fillBookingWideFields(flats, text);
const kiItems = nuExtractToKiReservations(flats as unknown as Record<string, unknown>[]) as unknown as KiReservation[];
return { kiItems, warnings };
}
@@ -0,0 +1,132 @@
/**
* Type-specific FLAT JSON Schemas for the extraction router.
*
* The router drives a local model with a small, flat, single-reservation schema and
* lets Ollama's native `format` parameter constrain sampling to it (grammar-level —
* see ollama-format.client.ts). Two findings shape this:
* - Enforcing the big nested `{reservations:[union of 8 types]}` schema makes small
* local models collapse (grammar compliance falls off a cliff on deep schemas), so
* we never enforce the monolith — only one flat object at a time.
* - A flat schema whose key fields are `required` forces the model to actually fill
* flightNumber / from / to / dates instead of leaving them null, which is the single
* biggest reliability win for a small model.
*
* The flat field names match NUEXTRACT_TEMPLATE so the existing flat→schema.org mapper
* (`nuExtractToKiReservations`) maps the result straight into the kitinerary pipeline.
*/
export type FlatType = 'flight' | 'train' | 'bus' | 'ferry' | 'car' | 'hotel' | 'restaurant' | 'event';
export const FLAT_TYPES: FlatType[] = ['flight', 'train', 'bus', 'ferry', 'car', 'hotel', 'restaurant', 'event'];
/** A flat reservation as the model emits it, before mapping to schema.org. The named fields
* are the ones the router reads directly; the index signature carries the rest unchanged. */
export interface FlatLike {
type: FlatType;
booking_reference?: string;
vehicle_number?: string;
from_code?: string;
to_code?: string;
from_name?: string;
to_name?: string;
departure_time?: string;
arrival_time?: string;
checkin_time?: string;
checkout_time?: string;
[k: string]: unknown;
}
type JsonSchema = Record<string, unknown>;
const STR = { type: 'string' } as const;
/** Build a flat object schema from a field list, marking `required` the ones enforcement must guarantee. */
function flat(fields: string[], required: string[]): JsonSchema {
const properties: Record<string, typeof STR> = {};
for (const f of fields) properties[f] = STR;
return { type: 'object', properties, required };
}
/**
* One schema per reservation type. `required` names the fields the model MUST emit;
* everything else is optional. The router knows the type up-front (from the classifier),
* so the type token itself is not part of the extraction schema — it's set afterwards.
*/
export const FLAT_SCHEMA_BY_TYPE: Record<FlatType, JsonSchema> = {
flight: flat(
['booking_reference', 'operator', 'vehicle_number', 'from_code', 'from_name', 'to_code', 'to_name', 'departure_time', 'arrival_time', 'seat', 'travel_class', 'price', 'currency'],
// booking_reference (PNR) is REQUIRED: the mapper groups legs into one booking by
// shared reservationNumber, so a missing PNR would split a round-trip into loose legs.
// Enforcing it makes the small model actually copy it instead of leaving it null.
['vehicle_number', 'from_code', 'to_code', 'departure_time', 'booking_reference'],
),
train: flat(
['booking_reference', 'operator', 'vehicle_number', 'from_name', 'to_name', 'departure_time', 'arrival_time', 'seat', 'travel_class', 'platform', 'price', 'currency'],
['from_name', 'to_name', 'departure_time'],
),
bus: flat(
['booking_reference', 'operator', 'vehicle_number', 'from_name', 'to_name', 'departure_time', 'arrival_time', 'seat', 'price', 'currency'],
['from_name', 'to_name', 'departure_time'],
),
ferry: flat(
['booking_reference', 'operator', 'name', 'from_name', 'to_name', 'departure_time', 'arrival_time', 'price', 'currency'],
['from_name', 'to_name', 'departure_time'],
),
car: flat(
['booking_reference', 'operator', 'name', 'from_name', 'to_name', 'departure_time', 'arrival_time', 'price', 'currency'],
// `operator` (rental company) is REQUIRED so the booking gets a real title instead of the
// generic "Rental Car" fallback.
['operator', 'from_name', 'departure_time', 'arrival_time'],
),
hotel: flat(
['name', 'booking_reference', 'address', 'checkin_time', 'checkout_time', 'telephone', 'website', 'price', 'currency'],
// `address` is REQUIRED so the model actually emits the (often unlabeled) street address line
// — without it small models skip it and the booking loses its location/place.
['name', 'address', 'checkin_time', 'checkout_time'],
),
restaurant: flat(
['name', 'booking_reference', 'address', 'start_time', 'end_time', 'telephone', 'website', 'price', 'currency'],
['name'],
),
event: flat(
['name', 'booking_reference', 'address', 'start_time', 'end_time', 'telephone', 'website', 'price', 'currency'],
['name'],
),
};
/**
* All flight legs of a document in ONE shot: a flat array. A capable model (7b) fills
* every leg reliably in a single call — far faster than one call per leg — and the
* booking-wide fields (PNR, total price) are recovered deterministically afterwards.
*/
export const FLIGHTS_ARRAY_SCHEMA: JsonSchema = {
type: 'object',
properties: {
flights: {
type: 'array',
items: flat(
['vehicle_number', 'operator', 'from_code', 'from_name', 'to_code', 'to_name', 'departure_time', 'arrival_time', 'seat', 'travel_class'],
['vehicle_number', 'from_code', 'to_code', 'departure_time'],
),
},
},
required: ['flights'],
};
/**
* Single-reservation fallback when the document type isn't obvious from keywords:
* one flat object the model fills, choosing the `type` itself. Used on the strong
* model so the type pick is reliable.
*/
export const UNION_SINGLE_SCHEMA: JsonSchema = {
type: 'object',
properties: {
type: { type: 'string', enum: FLAT_TYPES },
name: STR, booking_reference: STR, operator: STR, vehicle_number: STR,
from_name: STR, from_code: STR, to_name: STR, to_code: STR,
departure_time: STR, arrival_time: STR, address: STR,
checkin_time: STR, checkout_time: STR, start_time: STR, end_time: STR,
telephone: STR, website: STR, price: STR, currency: STR,
},
required: ['type'],
};
@@ -0,0 +1,95 @@
/**
* Minimal Ollama native-API client used by the extraction router.
*
* Why not the OpenAI-compatible `/v1/chat/completions` path the rest of llm-parse uses?
* Ollama's `/v1` endpoint does NOT faithfully honour OpenAI's `response_format:{json_schema,strict}`
* (it's passed through loosely — the schema and `strict` flag are effectively ignored).
* Ollama's OWN `/api/chat` endpoint with a top-level `format: <jsonSchema>` is the path that
* actually compiles the schema to a GBNF grammar and constrains token sampling. That hard
* guarantee — valid, type-correct, all-required-fields JSON — is the router's foundation,
* so the router talks to `/api/chat` directly. (Cloud providers enforce via their own strict
* tool/response_format and keep using the existing clients.)
*/
const TIMEOUT_MS = 300_000;
export interface EnforcedExtractInput {
/** Ollama base URL — accepts the addon's `…/v1` form; the `/v1` suffix is stripped. */
baseUrl: string;
model: string;
system: string;
user: string;
/** JSON Schema the output is constrained to (grammar-level). */
schema: Record<string, unknown>;
apiKey?: string;
numPredict?: number;
/** Context window. 8192 fits a typical multi-section booking; raise for long itineraries. */
numCtx?: number;
}
/** Resolve the native API base from a config base URL that may end in `/v1`. */
export function toNativeBase(baseUrl: string): string {
return baseUrl.replace(/\/+$/, '').replace(/\/v1$/, '');
}
/** Strip code fences and JSON.parse; returns null on failure. */
function parseJson(content: string | undefined | null): unknown {
if (!content) return null;
const stripped = content.trim().replace(/^```(?:json)?/i, '').replace(/```$/, '').trim();
try {
return JSON.parse(stripped);
} catch {
return null;
}
}
/**
* Run one schema-constrained chat completion against Ollama's native `/api/chat`.
* Returns the parsed JSON object (constrained to `schema`), or null if the request
* failed or produced unparseable output.
*/
export async function extractEnforced(input: EnforcedExtractInput): Promise<Record<string, unknown> | null> {
const url = `${toNativeBase(input.baseUrl)}/api/chat`;
const body = {
model: input.model,
stream: false,
format: input.schema,
// Disable "thinking" for hybrid/reasoning models (Qwen3, etc.): the reasoning tokens
// collide with the format-grammar constraint here — they produce unparseable output and
// blow the latency budget on CPU. Ollama ignores this for non-thinking models, so it's safe.
think: false,
// Keep the model resident a while so back-to-back imports don't pay the cold load.
keep_alive: '30m',
options: { temperature: 0, num_predict: input.numPredict ?? 512, num_ctx: input.numCtx ?? 8192 },
messages: [
{ role: 'system', content: input.system },
{ role: 'user', content: input.user },
],
};
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
let res: Response;
try {
res = await fetch(url, {
method: 'POST',
signal: controller.signal,
headers: {
'content-type': 'application/json',
...(input.apiKey ? { authorization: `Bearer ${input.apiKey}` } : {}),
},
body: JSON.stringify(body),
});
} finally {
clearTimeout(timer);
}
if (!res.ok) {
const detail = await res.text().catch(() => '');
throw new Error(`Ollama /api/chat failed (${res.status}): ${detail.slice(0, 200)}`);
}
const data = (await res.json()) as { message?: { content?: string } };
const parsed = parseJson(data.message?.content);
return parsed && typeof parsed === 'object' ? (parsed as Record<string, unknown>) : null;
}
+71
View File
@@ -0,0 +1,71 @@
import { extname } from 'node:path';
import { PDFParse } from 'pdf-parse';
/** File extensions whose bytes are inherently text and can be decoded directly. */
const TEXT_LIKE = new Set(['.txt', '.html', '.htm', '.eml']);
export function isTextLike(fileName: string): boolean {
return TEXT_LIKE.has(extname(fileName).toLowerCase());
}
export function isPdf(fileName: string): boolean {
return extname(fileName).toLowerCase() === '.pdf';
}
/** Strip HTML/XML tags and collapse whitespace for a cleaner LLM prompt. */
function stripMarkup(s: string): string {
return s
.replace(/<script[\s\S]*?<\/script>/gi, ' ')
.replace(/<style[\s\S]*?<\/style>/gi, ' ')
.replace(/<[^>]+>/g, ' ')
.replace(/&nbsp;/gi, ' ')
.replace(/[ \t]+/g, ' ')
.replace(/\n{3,}/g, '\n\n')
.trim();
}
/** Extract the embedded text layer from a PDF (empty for scanned/image-only PDFs). */
async function extractPdfText(buffer: Buffer): Promise<string> {
const parser = new PDFParse({ data: new Uint8Array(buffer) });
try {
// Space (not tab) between same-line items reads more naturally for the LLM.
const res = await parser.getText({ cellSeparator: ' ' });
return cleanPdfText(res.text ?? '');
} finally {
await parser.destroy?.();
}
}
/**
* Clean up pdf-parse output for the LLM:
* - strip `-- N of M --` page markers
* - normalize whitespace/tabs
* - collapse letter-spaced UPPERCASE runs ("A M S T E R D A M" → "AMSTERDAM"),
* a common PDF kerning artifact that otherwise hides booking fields
*/
function cleanPdfText(text: string): string {
return text
.replace(/^\s*-+\s*\d+\s+of\s+\d+\s*-+\s*$/gim, '')
.replace(/[ \t]+/g, ' ')
.replace(/\b(?:[A-Z] ){2,}[A-Z]\b/g, m => m.replace(/ /g, ''))
.replace(/ *\n */g, '\n')
.replace(/\n{3,}/g, '\n\n')
.trim();
}
/**
* Extract text from a booking file for the OpenAI-compatible/local LLM path
* (Ollama can't ingest PDFs or `file` parts, so everything becomes text).
* - txt/html/htm/eml → decoded (markup stripped)
* - pdf → embedded text layer via pdf-parse
* - anything else → best-effort UTF-8 decode
* A scanned/image-only PDF yields empty text — that case needs a vision provider
* (Anthropic reads PDFs natively).
*/
export async function extractText(buffer: Buffer, fileName: string): Promise<string> {
const ext = extname(fileName).toLowerCase();
if (isPdf(fileName)) return extractPdfText(buffer);
const raw = buffer.toString('utf8');
if (ext === '.html' || ext === '.htm' || ext === '.eml') return stripMarkup(raw);
return raw.trim();
}
+6
View File
@@ -128,6 +128,12 @@ export class OidcController {
return f('/login?oidc_error=subject_mismatch');
}
// Some IdPs put `picture` only in the id_token, not the userinfo response —
// fall back to it so the avatar (#1399) still populates.
if (!userInfo.picture && typeof idVerify.claims.picture === 'string') {
userInfo.picture = idVerify.claims.picture;
}
const result = this.oidc.findOrCreateUser(userInfo, config, pending.inviteToken);
if ('error' in result) return f('/login?oidc_error=' + result.error);
+152 -11
View File
@@ -13,9 +13,13 @@ import {
} from '@nestjs/common';
import type { User } from '../../types';
import { PackingService } from './packing.service';
import { isUpdateConflict } from '../../services/conflictResult';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
/** A packing item row carrying the privacy fields (#858) used to scope broadcasts. */
type PackingItemRow = { is_private?: number; owner_id?: number | null; recipients?: { user_id: number }[]; [key: string]: unknown };
/**
* /api/trips/:tripId/packing — trip-scoped packing list (items, bags, templates,
* assignees).
@@ -50,7 +54,8 @@ export class PackingController {
@Get()
list(@CurrentUser() user: User, @Param('tripId') tripId: string) {
this.requireTrip(tripId, user);
return { items: this.packing.listItems(tripId) };
// Pass the viewer so private items (#858) owned by other members are hidden.
return { items: this.packing.listItems(tripId, user.id) };
}
@Post('import')
@@ -65,9 +70,9 @@ export class PackingController {
if (!Array.isArray(items) || items.length === 0) {
throw new HttpException({ error: 'items must be a non-empty array' }, 400);
}
const created = this.packing.bulkImport(tripId, items);
const created = this.packing.bulkImport(tripId, items, user.id);
for (const item of created) {
this.packing.broadcast(tripId, 'packing:created', { item }, socketId);
this.packing.broadcastItem(tripId, 'packing:created', { item }, item, socketId);
}
return { items: created, count: created.length };
}
@@ -76,7 +81,7 @@ export class PackingController {
create(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@Body() body: { name?: string; category?: string; checked?: boolean },
@Body() body: { name?: string; category?: string; checked?: boolean; is_private?: boolean; visibility?: 'common' | 'personal' | 'shared'; recipient_ids?: number[] },
@Headers('x-socket-id') socketId?: string,
) {
const trip = this.requireTrip(tripId, user);
@@ -84,11 +89,22 @@ export class PackingController {
if (!body.name) {
throw new HttpException({ error: 'Item name is required' }, 400);
}
const item = this.packing.createItem(tripId, { name: body.name, category: body.category, checked: body.checked });
this.packing.broadcast(tripId, 'packing:created', { item }, socketId);
const item = this.packing.createItem(tripId, { name: body.name, category: body.category, checked: body.checked, is_private: body.is_private, visibility: body.visibility, recipient_ids: body.recipient_ids }, user.id);
this.emitToViewers(tripId, 'packing:created', { item }, item, socketId);
return { item };
}
/** Deliver an item event to exactly the people who can see it (#858): the whole
* room for a Common item, or owner + recipients for a restricted one. */
private emitToViewers(tripId: string, event: string, payload: Record<string, unknown>, item: PackingItemRow, socketId: string | undefined): void {
const viewers = this.packing.viewersOf(item);
if (viewers === null) {
this.packing.broadcast(tripId, event, payload, socketId);
} else {
this.packing.broadcastToViewers(tripId, event, payload, viewers, socketId);
}
}
@Put('reorder')
reorder(
@CurrentUser() user: User,
@@ -109,18 +125,57 @@ export class PackingController {
@Param('id') id: string,
@Body() body: Record<string, unknown>,
@Headers('x-socket-id') socketId?: string,
@Headers('x-base-updated-at') ifMatch?: string,
) {
const trip = this.requireTrip(tripId, user);
this.requireEdit(trip, user);
const { name, checked, category, weight_grams, bag_id, quantity } = body as Record<string, never>;
const updated = this.packing.updateItem(tripId, id, { name, checked, category, weight_grams, bag_id, quantity }, Object.keys(body));
// Privacy state before the change, so a public↔private toggle (#858) can route
// the broadcast correctly instead of leaking a freshly-privatized item.
const before = this.packing.getItemPrivacy(tripId, id);
const { name, checked, category, weight_grams, bag_id, quantity, is_private } = body as Record<string, never>;
const updated = this.packing.updateItem(tripId, id, { name, checked, category, weight_grams, bag_id, quantity, is_private }, Object.keys(body), ifMatch, user.id);
if (!updated) {
throw new HttpException({ error: 'Item not found' }, 404);
}
this.packing.broadcast(tripId, 'packing:updated', { item: updated }, socketId);
// Stale offline overwrite — surface the conflict for client-side resolution (#1135).
if (isUpdateConflict(updated)) {
throw new HttpException({ error: 'conflict', server: updated.server }, 409);
}
this.broadcastUpdate(tripId, id, updated as PackingItemRow, !!before?.is_private, socketId);
return { item: updated };
}
/**
* Routes a packing-item update over WebSocket so private items (#858) stay
* scoped to their owner across the four public↔private transitions:
* - stays private → owner-only update
* - public→private → drop it from the whole room, re-add for the owner
* - private→public → create for members who lacked it, then update for all
* - stays public → plain update to all
*/
private broadcastUpdate(
tripId: string,
id: string,
item: PackingItemRow,
wasPrivate: boolean,
socketId: string | undefined,
): void {
const nowPrivate = !!item.is_private;
if (nowPrivate) {
if (wasPrivate) {
this.packing.broadcastItem(tripId, 'packing:updated', { item }, item, socketId);
} else {
this.packing.broadcast(tripId, 'packing:deleted', { itemId: Number(id) }, socketId);
this.packing.broadcastItem(tripId, 'packing:created', { item }, item, socketId);
}
} else {
if (wasPrivate) {
this.packing.broadcast(tripId, 'packing:created', { item }, socketId);
}
this.packing.broadcast(tripId, 'packing:updated', { item }, socketId);
}
}
@Delete(':id')
remove(
@CurrentUser() user: User,
@@ -130,13 +185,99 @@ export class PackingController {
) {
const trip = this.requireTrip(tripId, user);
this.requireEdit(trip, user);
if (!this.packing.deleteItem(tripId, id)) {
const deleted = this.packing.deleteItem(tripId, id);
if (!deleted) {
throw new HttpException({ error: 'Item not found' }, 404);
}
this.packing.broadcast(tripId, 'packing:deleted', { itemId: Number(id) }, socketId);
// Scope the delete to the people who could see it (owner + recipients, #858).
this.emitToViewers(tripId, 'packing:deleted', { itemId: Number(id) }, deleted as PackingItemRow, socketId);
return { success: true };
}
@Put(':id/sharing')
setSharing(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@Param('id') id: string,
@Body() body: { visibility?: 'common' | 'personal' | 'shared'; recipient_ids?: number[] },
@Headers('x-socket-id') socketId?: string,
) {
const trip = this.requireTrip(tripId, user);
this.requireEdit(trip, user);
if (body.visibility !== 'common' && body.visibility !== 'personal' && body.visibility !== 'shared') {
throw new HttpException({ error: 'Invalid visibility' }, 400);
}
const updated = this.packing.setItemSharing(tripId, id, user.id, body.visibility, Array.isArray(body.recipient_ids) ? body.recipient_ids : []);
if (!updated) {
throw new HttpException({ error: 'Item not found' }, 404);
}
if ((updated as { forbidden?: boolean }).forbidden) {
throw new HttpException({ error: 'Only the owner can change sharing' }, 403);
}
// The viewer set just changed: drop the item from the whole room, then re-add
// it for whoever can now see it (owner + recipients, or everyone if Common).
this.packing.broadcast(tripId, 'packing:deleted', { itemId: Number(id) }, socketId);
this.emitToViewers(tripId, 'packing:created', { item: updated }, updated as PackingItemRow, socketId);
return { item: updated };
}
@Post(':id/clone')
@HttpCode(201)
clone(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@Param('id') id: string,
@Headers('x-socket-id') socketId?: string,
) {
const trip = this.requireTrip(tripId, user);
this.requireEdit(trip, user);
const item = this.packing.cloneItem(tripId, id, user.id);
if (!item) {
throw new HttpException({ error: 'Item not found' }, 404);
}
// The clone is personal to the caller — only their sockets need it.
this.emitToViewers(tripId, 'packing:created', { item }, item, socketId);
return { item };
}
@Post(':id/contributors')
addContributor(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@Param('id') id: string,
@Headers('x-socket-id') socketId?: string,
) {
const trip = this.requireTrip(tripId, user);
this.requireEdit(trip, user);
const item = this.packing.addContributor(tripId, id, user.id);
if (!item) {
throw new HttpException({ error: 'Item not found or not a shared list item' }, 404);
}
// Common item — visible to all, so the contributor change broadcasts to the room.
this.packing.broadcast(tripId, 'packing:updated', { item }, socketId);
return { item };
}
@Delete(':id/contributors/:userId')
removeContributor(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@Param('id') id: string,
@Param('userId') userId: string,
@Headers('x-socket-id') socketId?: string,
) {
const trip = this.requireTrip(tripId, user);
this.requireEdit(trip, user);
// You can drop your own pledge; the owner can remove anyone's.
const target = parseInt(userId);
const item = this.packing.removeContributor(tripId, id, target);
if (!item) {
throw new HttpException({ error: 'Item not found' }, 404);
}
this.packing.broadcast(tripId, 'packing:updated', { item }, socketId);
return { item };
}
@Get('bags')
listBags(@CurrentUser() user: User, @Param('tripId') tripId: string) {
this.requireTrip(tripId, user);
+60 -9
View File
@@ -5,6 +5,9 @@ import { checkPermission } from '../../services/permissions';
import type { User } from '../../types';
import * as svc from '../../services/packingService';
/** Privacy fields stamped on a packing item (#858). */
type PrivacyFields = { is_private?: number; owner_id?: number | null };
type Trip = NonNullable<ReturnType<typeof svc.verifyTripAccess>>;
/**
@@ -27,24 +30,72 @@ export class PackingService {
broadcast(tripId, event, payload, socketId);
}
listItems(tripId: string) {
return svc.listItems(tripId);
/**
* Broadcast an item event, but keep private items (#858) off other members'
* screens: when the item is private the event is delivered only to its owner's
* sockets. Shared items broadcast to the whole trip room as before.
*/
broadcastItem(tripId: string, event: string, payload: Record<string, unknown>, item: PrivacyFields | null | undefined, socketId: string | undefined): void {
const onlyUserId = item?.is_private && item.owner_id != null ? item.owner_id : undefined;
broadcast(tripId, event, payload, socketId, onlyUserId);
}
createItem(tripId: string, data: { name: string; category?: string; checked?: boolean }) {
return svc.createItem(tripId, data);
/** Deliver an item event to a specific set of viewers (#858 shared items) — the
* owner plus the recipients it was shared with — without leaking to the room. */
broadcastToViewers(tripId: string, event: string, payload: Record<string, unknown>, viewerIds: number[], socketId: string | undefined): void {
for (const uid of new Set(viewerIds)) {
if (uid != null) broadcast(tripId, event, payload, socketId, uid);
}
}
updateItem(tripId: string, id: string, data: Parameters<typeof svc.updateItem>[2], changedKeys: string[]) {
return svc.updateItem(tripId, id, data, changedKeys);
/** The users who can currently see an item: everyone (null) for Common, or
* owner + recipients for a restricted item. */
viewersOf(item: { is_private?: number; owner_id?: number | null; recipients?: { user_id: number }[] } | null | undefined): number[] | null {
if (!item || !item.is_private) return null; // Common — visible to the whole room
const ids = [item.owner_id, ...(item.recipients || []).map(r => r.user_id)].filter((x): x is number => x != null);
return ids;
}
deleteItem(tripId: string, id: string): boolean {
listItems(tripId: string, userId?: number) {
return svc.listItems(tripId, userId);
}
/** Reads an item's current privacy fields (#858) before an update, so the
* controller can detect a public↔private transition and route the broadcast. */
getItemPrivacy(tripId: string, id: string): PrivacyFields | undefined {
return db.prepare('SELECT is_private, owner_id FROM packing_items WHERE id = ? AND trip_id = ?').get(id, tripId) as PrivacyFields | undefined;
}
createItem(tripId: string, data: Parameters<typeof svc.createItem>[1], ownerId?: number) {
return svc.createItem(tripId, data, ownerId);
}
setItemSharing(tripId: string, id: string, actingUserId: number, visibility: svc.PackingVisibility, recipientIds: number[]) {
return svc.setItemSharing(tripId, id, actingUserId, visibility, recipientIds);
}
addContributor(tripId: string, id: string, userId: number) {
return svc.addContributor(tripId, id, userId);
}
removeContributor(tripId: string, id: string, userId: number) {
return svc.removeContributor(tripId, id, userId);
}
cloneItem(tripId: string, id: string, userId: number) {
return svc.cloneItem(tripId, id, userId);
}
updateItem(tripId: string, id: string, data: Parameters<typeof svc.updateItem>[2], changedKeys: string[], ifMatch?: string, actingUserId?: number) {
return svc.updateItem(tripId, id, data, changedKeys, ifMatch, actingUserId);
}
deleteItem(tripId: string, id: string) {
return svc.deleteItem(tripId, id);
}
bulkImport(tripId: string, items: Parameters<typeof svc.bulkImport>[1]) {
return svc.bulkImport(tripId, items);
bulkImport(tripId: string, items: Parameters<typeof svc.bulkImport>[1], ownerId?: number) {
return svc.bulkImport(tripId, items, ownerId);
}
reorderItems(tripId: string, orderedIds: Parameters<typeof svc.reorderItems>[1]): void {
+3 -3
View File
@@ -1,4 +1,4 @@
import { Controller, Get, HttpException, Param, Res, UseGuards } from '@nestjs/common';
import { Controller, Get, Headers, HttpException, Param, Res, UseGuards } from '@nestjs/common';
import type { Response } from 'express';
import type { User } from '../../types';
import { PhotosService } from './photos.service';
@@ -37,9 +37,9 @@ export class PhotosController {
}
@Get(':id/original')
async original(@CurrentUser() user: User, @Param('id') id: string, @Res() res: Response): Promise<void> {
async original(@CurrentUser() user: User, @Param('id') id: string, @Res() res: Response, @Headers('range') range?: string): Promise<void> {
const photoId = this.requireAccess(user, id);
await this.photos.stream(res, user.id, photoId, 'original');
await this.photos.stream(res, user.id, photoId, 'original', range);
}
@Get(':id/info')
+2 -2
View File
@@ -14,8 +14,8 @@ export class PhotosService {
return canAccessTrekPhoto(userId, photoId);
}
stream(res: Response, userId: number, photoId: number, kind: 'thumbnail' | 'original') {
return streamPhoto(res, userId, photoId, kind);
stream(res: Response, userId: number, photoId: number, kind: 'thumbnail' | 'original', range?: string) {
return streamPhoto(res, userId, photoId, kind, range);
}
info(userId: number, photoId: number) {
+40 -2
View File
@@ -18,6 +18,7 @@ import { FileInterceptor } from '@nestjs/platform-express';
import { memoryStorage } from 'multer';
import type { User } from '../../types';
import { PlacesService } from './places.service';
import { isUpdateConflict } from '../../services/conflictResult';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
@@ -225,6 +226,36 @@ export class PlacesController {
return { deleted, count: deleted.length };
}
@Post('bulk-update')
@HttpCode(200)
bulkUpdate(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@Body() body: { ids?: unknown; category_id?: unknown },
@Headers('x-socket-id') socketId?: string,
) {
const trip = this.requireTrip(tripId, user);
this.requireEdit(trip, user);
const { ids } = body;
if (!Array.isArray(ids) || ids.some((v) => typeof v !== 'number')) {
throw new HttpException({ error: 'ids must be an array of numbers' }, 400);
}
if (ids.length === 0) {
return { updated: [], count: 0 };
}
// `category_id` may be a number or null (null clears it), so key presence —
// not truthiness — is what signals there's something to change.
if (!('category_id' in body)) {
throw new HttpException({ error: 'Provide at least one field to update' }, 400);
}
const updated = this.places.updateMany(tripId, ids, { category_id: body.category_id as number | null });
for (const place of updated) {
this.places.broadcast(tripId, 'place:updated', { place }, socketId);
this.places.onUpdated(place.id);
}
return { updated: updated.map((p) => p.id), count: updated.length };
}
@Get(':id')
get(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string) {
this.requireTrip(tripId, user);
@@ -258,14 +289,21 @@ export class PlacesController {
@Param('id') id: string,
@Body() body: Record<string, unknown>,
@Headers('x-socket-id') socketId?: string,
@Headers('x-base-updated-at') ifMatch?: string,
) {
const trip = this.requireTrip(tripId, user);
validateLengths(body);
this.requireEdit(trip, user);
const place = this.places.update(tripId, id, body as never);
if (!place) {
const result = this.places.update(tripId, id, body as never, ifMatch);
if (!result) {
throw new HttpException({ error: 'Place not found' }, 404);
}
// The offline edit was based on a now-stale version — let the client resolve
// it (#1135) instead of silently overwriting the newer server state.
if (isUpdateConflict(result)) {
throw new HttpException({ error: 'conflict', server: result.server }, 409);
}
const place = result;
this.places.broadcast(tripId, 'place:updated', { place }, socketId);
this.places.onUpdated(place.id);
return { place };
+6 -2
View File
@@ -40,8 +40,8 @@ export class PlacesService {
return svc.createPlace(tripId, data);
}
update(tripId: string, id: string, data: Parameters<typeof svc.updatePlace>[2]) {
return svc.updatePlace(tripId, id, data);
update(tripId: string, id: string, data: Parameters<typeof svc.updatePlace>[2], ifMatch?: string) {
return svc.updatePlace(tripId, id, data, ifMatch);
}
remove(tripId: string, id: string): boolean {
@@ -52,6 +52,10 @@ export class PlacesService {
return svc.deletePlacesMany(tripId, ids);
}
updateMany(tripId: string, ids: number[], data: Parameters<typeof svc.updatePlacesMany>[2]) {
return svc.updatePlacesMany(tripId, ids, data);
}
importGpx(
tripId: string,
buffer: Buffer,
+40
View File
@@ -0,0 +1,40 @@
import type { INestApplication } from '@nestjs/common';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { attachZodBodySchemas } from '../common/api-zod';
/**
* Swagger UI + OpenAPI spec for the REST API (#1412), gated behind
* TREK_API_DOCS_ENABLED. Must run BEFORE app.init() — SwaggerModule.setup
* registers Express-level routes, and a post-init Express route is
* unreachable behind the Nest router (see bootstrap.ts).
*
* /api/docs Swagger UI (all controllers, try-it-out, auth button)
* /api/docs-json raw OpenAPI 3 document (generated clients, Postman)
* /api/docs-yaml same, as YAML
*
* The bearer button works with a plain TREK session JWT: extractToken
* accepts `Authorization: Bearer` everywhere as the cookie fallback.
*/
export function setupApiDocs(app: INestApplication): void {
const version: string = process.env.APP_VERSION || (require('../../../package.json') as { version: string }).version;
const config = new DocumentBuilder()
.setTitle('TREK API')
.setDescription(
'The REST API the TREK web app itself runs on. Authenticate with a session JWT — '
+ 'either the `trek_session` cookie (same browser) or an `Authorization: Bearer <jwt>` header.',
)
.setVersion(version)
.addBearerAuth({ type: 'http', scheme: 'bearer', bearerFormat: 'JWT' }, 'session')
.addCookieAuth('trek_session')
.addSecurityRequirements('session')
.build();
const document = SwaggerModule.createDocument(app, config);
// Lift the Zod schemas the routes already validate with into the document —
// no double annotation, every ZodValidationPipe body is documented.
attachZodBodySchemas(app, document);
SwaggerModule.setup('api/docs', app, document, {
jsonDocumentUrl: 'api/docs-json',
yamlDocumentUrl: 'api/docs-yaml',
swaggerOptions: { persistAuthorization: true },
});
}
@@ -0,0 +1,51 @@
import { db, canAccessTrip } from '../../../db/database';
import { broadcast, broadcastToUser } from '../../../websocket';
import { PluginDataDb } from './plugin-data.service';
import { PluginRpcHost } from './rpc-host';
import { appendAudit } from './plugin-audit';
/**
* Wires a plugin's capability host to the REAL privileged modules (#plugins,
* M1). This is the ONLY plugin file that imports db/websocket — it runs in the
* host (parent), never in the child. Broadcasts are force-namespaced to
* `plugin:{id}:{event}` so a plugin can't forge a core event.
*/
const dataDbs = new Map<string, PluginDataDb>();
export function getPluginDataDb(id: string): PluginDataDb {
let d = dataDbs.get(id);
if (!d) {
d = new PluginDataDb(id);
dataDbs.set(id, d);
}
return d;
}
export function closePluginDataDb(id: string): void {
dataDbs.get(id)?.close();
dataDbs.delete(id);
}
export function createRealRpcHost(id: string, granted: ReadonlySet<string>): PluginRpcHost {
return new PluginRpcHost(id, granted, {
data: getPluginDataDb(id),
db,
canAccessTrip: (tripId, userId) => canAccessTrip(tripId, userId),
// Two users "share a trip" when both are owner-or-member of the same trip.
canSeeUser: (actingUserId, targetUserId) =>
!!db
.prepare(
`SELECT 1 FROM trips t
LEFT JOIN trip_members m1 ON m1.trip_id = t.id AND m1.user_id = ?
LEFT JOIN trip_members m2 ON m2.trip_id = t.id AND m2.user_id = ?
WHERE (t.user_id = ? OR m1.user_id IS NOT NULL)
AND (t.user_id = ? OR m2.user_id IS NOT NULL)
LIMIT 1`,
)
.get(actingUserId, targetUserId, actingUserId, targetUserId),
broadcastToTrip: (tripId, event, payload) => broadcast(tripId, `plugin:${id}:${event}`, payload),
broadcastToUser: (userId, payload) => broadcastToUser(userId, { type: `plugin:${id}`, ...payload }),
audit: (entry) => appendAudit(db, entry),
});
}
@@ -0,0 +1,63 @@
import crypto from 'node:crypto';
/**
* Host-side, hash-chained capability audit (#plugins, L1 hardening).
*
* Every host-mediated core-data / broadcast call a plugin makes is recorded at
* the RPC boundary — the one place the plugin provably can't reach — with the
* HOST-bound acting user (not a value the plugin supplies) and a per-plugin hash
* chain (hash = sha256(prev_hash + row)). That makes wide data grants
* attributable, tamper-evident, and user-visible, which is exactly what lets
* TREK grant broad reads to large addons without raising risk.
*/
interface AuditDb {
prepare(sql: string): {
get(...args: unknown[]): unknown;
run(...args: unknown[]): unknown;
all(...args: unknown[]): unknown[];
};
}
export interface AuditEntry {
pluginId: string;
actingUserId?: number;
method: string;
resource?: string | null;
code: string;
}
/** The methods worth auditing: core-data reads + broadcasts, not own-db noise. */
export function auditResource(method: string, params: Record<string, unknown>): string | null {
if (method.startsWith('trips.')) return `trip:${params.tripId ?? '?'}`;
if (method === 'users.getById') return `user:${params.id ?? '?'}`;
if (method === 'ws.broadcastToTrip') return `trip:${params.tripId ?? '?'}`;
if (method === 'ws.broadcastToUser') return `user:${params.userId ?? '?'}`;
return null;
}
/** True for calls we record (core data + ws); a plugin's own-db calls are skipped. */
export function isAuditable(method: string): boolean {
return method.startsWith('trips.') || method.startsWith('users.') || method.startsWith('ws.');
}
/** Append one entry to the per-plugin hash chain. Synchronous (better-sqlite3). */
export function appendAudit(db: AuditDb, e: AuditEntry): void {
const prev =
(db.prepare('SELECT hash FROM plugin_capability_audit WHERE plugin_id = ? ORDER BY id DESC LIMIT 1').get(e.pluginId) as
| { hash: string }
| undefined)?.hash ?? '';
const ts = new Date().toISOString();
const row = JSON.stringify([e.pluginId, e.actingUserId ?? null, e.method, e.resource ?? null, e.code, ts]);
const hash = crypto.createHash('sha256').update(prev + row).digest('hex');
db.prepare(
'INSERT INTO plugin_capability_audit (plugin_id, acting_user_id, method, resource, code, ts, prev_hash, hash) VALUES (?,?,?,?,?,?,?,?)',
).run(e.pluginId, e.actingUserId ?? null, e.method, e.resource ?? null, e.code, ts, prev || null, hash);
}
/** Read the most recent audit rows for a plugin (admin view). */
export function readAudit(db: AuditDb, pluginId: string, limit = 200): unknown[] {
return db
.prepare('SELECT ts, acting_user_id, method, resource, code FROM plugin_capability_audit WHERE plugin_id = ? ORDER BY id DESC LIMIT ?')
.all(pluginId, limit);
}
@@ -0,0 +1,105 @@
import fs from 'node:fs';
import Database from 'better-sqlite3';
import type { Database as Db } from 'better-sqlite3';
import { pluginDataDir, pluginDbFile } from '../paths';
/**
* A plugin's own sqlite database (#plugins, db:own). The HOST owns the handle;
* the plugin child never gets a path or a connection — it can only reach this
* through RPC (db.exec / db.query / db.migrate). Because it is a SEPARATE FILE,
* containment is a filesystem fact: the plugin physically cannot read trek.db,
* and we don't have to police table-name prefixes in its SQL.
*
* A thin guard still rejects statements that would let a plugin escape its file
* (ATTACH another db, VACUUM INTO elsewhere, PRAGMA fiddling) or DoS via
* oversize SQL.
*/
const MAX_SQL_LENGTH = 100_000;
// RECURSIVE is the one construct that generates unbounded rows/CPU independent of
// the (capped) data size — a `WITH RECURSIVE …` can spin the synchronous host
// forever even with an empty database, which neither the size quota nor the
// result-row cap can stop (an aggregate over it never yields a first row). Refuse
// it outright; the row/size caps below bound everything else.
const FORBIDDEN = /\b(ATTACH|DETACH|VACUUM|PRAGMA|RECURSIVE)\b/i;
// Per-plugin on-disk quota. better-sqlite3 is synchronous and runs in the HOST
// process, so an unbounded plugin DB is both a disk-exhaustion DoS on the shared
// trek.db volume and (via a huge scan) an event-loop stall. max_page_count caps
// the file (writes past it fail SQLITE_FULL, contained to the plugin) and bounds
// the worst-case scan cost. Result sets are additionally row-capped below so a
// recursive CTE / cartesian product can't materialize an unbounded array.
const QUOTA_BYTES = 256 * 1024 * 1024;
const MAX_ROWS = 100_000;
export class PluginDataDb {
private db: Db;
constructor(pluginId: string) {
fs.mkdirSync(pluginDataDir(pluginId), { recursive: true });
this.db = new Database(pluginDbFile(pluginId));
this.db.pragma('journal_mode = WAL');
this.db.pragma('foreign_keys = ON');
// Cap the file size (per-connection; not persisted, so set on every open).
const pageSize = Number(this.db.pragma('page_size', { simple: true })) || 4096;
this.db.pragma(`max_page_count = ${Math.max(1, Math.floor(QUOTA_BYTES / pageSize))}`);
// Track applied migrations so db.migrate is idempotent per (plugin, id).
this.db.exec(
`CREATE TABLE IF NOT EXISTS _plugin_migrations (id TEXT PRIMARY KEY, applied_at INTEGER)`,
);
}
private guard(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.test(sql)) throw new Error('statement type not allowed for plugin databases');
}
/** Read query — returns rows up to MAX_ROWS. Single statement only. */
query(sql: string, args: unknown[] = []): unknown[] {
this.guard(sql);
// iterate() pulls one row at a time, so a recursive CTE that would yield
// unboundedly is halted at the cap instead of materializing via all().
const rows: unknown[] = [];
for (const row of this.db.prepare(sql).iterate(...(args as never[]))) {
rows.push(row);
if (rows.length > MAX_ROWS) throw new Error(`query returned more than ${MAX_ROWS} rows`);
}
return rows;
}
/** Write statement(s). exec() allows multiple statements (e.g. a small setup script). */
exec(sql: string, args: unknown[] = []): { changes: number } {
this.guard(sql);
if (args.length > 0) {
const info = this.db.prepare(sql).run(...(args as never[]));
return { changes: info.changes };
}
this.db.exec(sql);
return { changes: 0 };
}
/** Run a migration once, keyed by id. Re-running with the same id is a no-op. */
migrate(id: string, sql: string): { applied: boolean } {
this.guard(sql);
const seen = this.db.prepare('SELECT 1 FROM _plugin_migrations WHERE id = ?').get(id);
if (seen) return { applied: false };
this.db.transaction(() => {
this.db.exec(sql);
this.db.prepare('INSERT INTO _plugin_migrations (id, applied_at) VALUES (?, ?)').run(id, Date.now());
})();
return { applied: true };
}
close(): void {
try {
this.db.close();
} catch {
/* already closed */
}
}
}
/** Delete a plugin's data directory (uninstall "delete data"). */
export function removePluginData(pluginId: string): void {
fs.rmSync(pluginDataDir(pluginId), { recursive: true, force: true });
}
+212
View File
@@ -0,0 +1,212 @@
import {
KNOWN_METHODS,
type KnownMethod,
type RpcError,
type RpcRequest,
type RpcResponse,
} from '../protocol/envelope';
import type { PluginDataDb } from './plugin-data.service';
import { auditResource, isAuditable } from './plugin-audit';
/**
* The per-plugin capability router (#plugins, M1) — the ENFORCEMENT POINT.
*
* Built from the plugin's GRANTED permission set. Only the methods a permission
* unlocks are registered; an ungranted method is simply never in the map, so the
* plugin cannot "call it anyway" — there is no shared object, only messages, and
* the host is the sole holder of the trek.db handle and the broadcast fns.
*
* Runs in the HOST (parent) process.
*/
/** Thrown by a handler when the acting user may not touch the requested resource. */
export class ForbiddenResource extends Error {}
interface CoreDb {
prepare(sql: string): {
all(...args: unknown[]): unknown[];
get(...args: unknown[]): unknown;
};
}
export interface HostDeps {
/** The plugin's own sqlite (db:own). */
data: PluginDataDb;
/** Read-only handle to the core trek.db, used ONLY through the typed readers here. */
db: CoreDb;
/** Returns the trip row if the user may access it, else undefined. */
canAccessTrip(tripId: number, userId: number): unknown;
/** True if the target user is the acting user or co-members a trip with them. */
canSeeUser(actingUserId: number, targetUserId: number): boolean;
/** Namespaced trip broadcast (host forces the plugin:{id}:{event} event type). */
broadcastToTrip(tripId: number, eventType: string, payload: Record<string, unknown>): void;
/** Namespaced per-user broadcast. */
broadcastToUser(userId: number, payload: Record<string, unknown>): void;
/** Optional sink for the capability audit log (host-side, hash-chained). */
audit?(entry: { pluginId: string; actingUserId?: number; method: string; resource: string | null; code: string }): void;
}
type Handler = (params: Record<string, unknown>, actingUserId: number | undefined) => unknown;
const num = (v: unknown, name: string): number => {
const n = typeof v === 'string' ? Number(v) : v;
if (typeof n !== 'number' || !Number.isFinite(n)) throw new BadParams(`${name} must be a number`);
return n;
};
const str = (v: unknown, name: string): string => {
if (typeof v !== 'string') throw new BadParams(`${name} must be a string`);
return v;
};
class BadParams extends Error {}
export class PluginRpcHost {
private methods = new Map<string, Handler>();
constructor(
private readonly pluginId: string,
granted: ReadonlySet<string>,
private readonly deps: HostDeps,
) {
const has = (p: string) => granted.has(p);
if (has('db:own')) {
this.methods.set('db.query', (p) => deps.data.query(str(p.sql, 'sql'), asArgs(p.args)));
this.methods.set('db.exec', (p) => deps.data.exec(str(p.sql, 'sql'), asArgs(p.args)));
this.methods.set('db.migrate', (p) => deps.data.migrate(str(p.id, 'id'), str(p.sql, 'sql')));
}
if (has('db:read:trips')) {
this.methods.set('trips.getById', (p, uid) =>
this.tripRead(p, uid, () => deps.db.prepare('SELECT * FROM trips WHERE id = ?').get(num(p.tripId, 'tripId'))),
);
this.methods.set('trips.getPlaces', (p, uid) =>
this.tripRead(p, uid, () => deps.db.prepare('SELECT * FROM places WHERE trip_id = ? ORDER BY day_id, position').all(num(p.tripId, 'tripId'))),
);
this.methods.set('trips.getReservations', (p, uid) =>
this.tripRead(p, uid, () => deps.db.prepare('SELECT * FROM reservations WHERE trip_id = ? ORDER BY reservation_time').all(num(p.tripId, 'tripId'))),
);
}
if (has('db:read:users')) {
// Scope to people the acting user can actually see (self or a trip they
// share) so a plugin can't enumerate every account's profile by looping ids.
this.methods.set('users.getById', (p, uid) => {
const id = num(p.id, 'id');
if (uid === undefined) throw new ForbiddenResource('user reads require an authenticated user context');
if (id !== uid && !this.deps.canSeeUser(uid, id)) throw new ForbiddenResource(`no access to user ${id}`);
return deps.db.prepare('SELECT id, username, display_name, avatar FROM users WHERE id = ?').get(id);
});
}
if (has('ws:broadcast:trip')) {
// Gate the TARGET the same way reads are gated: a plugin may only push to a
// trip room the acting user is a member of — never an arbitrary/other-tenant
// trip. (Event-type namespacing alone doesn't cross the membership boundary.)
this.methods.set('ws.broadcastToTrip', (p, uid) => {
const tripId = num(p.tripId, 'tripId');
if (uid === undefined) throw new ForbiddenResource('broadcasts require an authenticated user context');
if (!this.deps.canAccessTrip(tripId, uid)) throw new ForbiddenResource(`no access to trip ${tripId}`);
deps.broadcastToTrip(tripId, str(p.event, 'event'), asPayload(p.data));
return { ok: true };
});
}
if (has('ws:broadcast:user')) {
// Restrict to the acting user's own connections — a plugin may not push to
// an arbitrary user it has no relationship to.
this.methods.set('ws.broadcastToUser', (p, uid) => {
const userId = num(p.userId, 'userId');
if (uid === undefined || userId !== uid) {
throw new ForbiddenResource('a plugin may only broadcast to the acting user');
}
deps.broadcastToUser(userId, { event: str(p.event, 'event'), ...asPayload(p.data) });
return { ok: true };
});
}
}
/**
* Membership-check every trip read against the acting user. The acting user is
* bound by the HOST from the authenticated invocation (see the supervisor's
* invocation map) — NOT taken from a plugin-supplied `asUserId`, which a plugin
* could set to any id to read another user's trips. If no acting user is bound
* (a job / onLoad, or a forged call), the read is forbidden.
*/
private tripRead(p: Record<string, unknown>, actingUserId: number | undefined, read: () => unknown): unknown {
const tripId = num(p.tripId, 'tripId');
if (actingUserId === undefined) {
throw new ForbiddenResource('trip reads require an authenticated user context');
}
if (!this.deps.canAccessTrip(tripId, actingUserId)) {
throw new ForbiddenResource(`no access to trip ${tripId}`);
}
return read();
}
async dispatch(req: RpcRequest, actingUserId?: number): Promise<RpcResponse | RpcError> {
const params = (req.params ?? {}) as Record<string, unknown>;
const res = await this.handle(req, params, actingUserId);
// Audit the core-data / broadcast surface (incl. denials) at the boundary.
if (this.deps.audit && isAuditable(req.method)) {
try {
this.deps.audit({
pluginId: this.pluginId,
actingUserId,
method: req.method,
resource: auditResource(req.method, params),
code: res.ok ? 'ok' : (res as RpcError).error.code,
});
} catch {
/* auditing must never break a call */
}
}
return res;
}
private async handle(
req: RpcRequest,
params: Record<string, unknown>,
actingUserId?: number,
): Promise<RpcResponse | RpcError> {
const handler = this.methods.get(req.method);
if (!handler) {
const known = (KNOWN_METHODS as readonly string[]).includes(req.method as KnownMethod);
return this.err(
req.id,
known ? 'PERMISSION_DENIED' : 'UNKNOWN_METHOD',
known
? `${req.method} requires a permission "${this.pluginId}" was not granted`
: `unknown method ${req.method}`,
);
}
try {
const result = await handler(params, actingUserId);
return { k: 'res', id: req.id, ok: true, result };
} catch (e) {
if (e instanceof BadParams) return this.err(req.id, 'BAD_PARAMS', e.message);
if (e instanceof ForbiddenResource) return this.err(req.id, 'RESOURCE_FORBIDDEN', e.message);
return this.err(req.id, 'HOST_ERROR', e instanceof Error ? e.message : 'internal error');
}
}
private err(id: string, code: RpcError['error']['code'], message: string): RpcError {
return { k: 'res', id, ok: false, error: { code, message } };
}
/** Release host-held resources (the plugin's own db handle) on terminal stop. */
dispose(): void {
try {
this.deps.data.close();
} catch {
/* already closed */
}
}
}
function asArgs(v: unknown): unknown[] {
if (v == null) return [];
if (Array.isArray(v)) return v;
throw new BadParams('args must be an array');
}
function asPayload(v: unknown): Record<string, unknown> {
return v && typeof v === 'object' ? (v as Record<string, unknown>) : { value: v };
}
@@ -0,0 +1,81 @@
import fs from 'node:fs';
import path from 'node:path';
import type BetterSqlite3 from 'better-sqlite3';
import { pluginsCodeRoot, pluginCodeDir } from '../paths';
import { parseJsonText, parseManifest, type PluginManifest } from './manifest';
import { scanForNativeBinaries } from './native-scan';
/**
* Discover plugins placed on the /plugins volume (#plugins, M4, "install from
* disk"). Reads each subdir's trek-plugin.json and upserts a registry row as
* INACTIVE — an existing plugin keeps its status / granted permissions / config,
* so re-discovery never silently re-activates or wipes settings. A plugin whose
* manifest is invalid or that ships native binaries is skipped (recorded to its
* error log if it already existed).
*/
export function discoverPlugins(db: BetterSqlite3.Database): { discovered: string[]; skipped: string[] } {
const root = pluginsCodeRoot();
const discovered: string[] = [];
const skipped: string[] = [];
if (!fs.existsSync(root)) return { discovered, skipped };
for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
if (!entry.isDirectory() || entry.name.startsWith('.')) continue;
const dir = pluginCodeDir(entry.name);
const manifestPath = path.join(dir, 'trek-plugin.json');
if (!fs.existsSync(manifestPath)) continue;
try {
const manifest = parseManifest(parseJsonText(fs.readFileSync(manifestPath, 'utf8')));
if (manifest.id !== entry.name) throw new Error(`manifest id "${manifest.id}" != directory "${entry.name}"`);
if (scanForNativeBinaries(dir).length) throw new Error('directory contains native binaries');
upsert(db, manifest);
discovered.push(manifest.id);
} catch (e) {
skipped.push(entry.name);
const msg = e instanceof Error ? e.message : 'invalid plugin';
db.prepare('INSERT INTO plugin_error_log (plugin_id, level, message) VALUES (?, ?, ?)').run(entry.name, 'error', `discovery: ${msg}`);
}
}
return { discovered, skipped };
}
function upsert(db: BetterSqlite3.Database, m: PluginManifest): void {
const existing = db.prepare('SELECT id FROM plugins WHERE id = ?').get(m.id) as { id: string } | undefined;
if (existing) {
db.prepare(
`UPDATE plugins SET name = ?, description = ?, type = ?, icon = ?, version = ?, api_version = ?,
min_trek_version = ?, permissions = ?, capabilities = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?`,
).run(m.name, m.description ?? null, m.type, m.icon ?? 'Blocks', m.version, m.apiVersion, m.minTrekVersion ?? null, JSON.stringify(m.permissions), JSON.stringify(m.capabilities), m.id);
} else {
db.prepare(
// granted_permissions '' (empty, not '[]') marks "never consented" so the
// first activation is distinguishable from a plugin consented to zero perms.
`INSERT INTO plugins (id, name, description, type, icon, version, api_version, min_trek_version, permissions, capabilities, granted_permissions, status)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '', 'inactive')`,
).run(m.id, m.name, m.description ?? null, m.type, m.icon ?? 'Blocks', m.version, m.apiVersion, m.minTrekVersion ?? null, JSON.stringify(m.permissions), JSON.stringify(m.capabilities));
}
// Refresh the settings-field descriptors from the manifest.
db.prepare('DELETE FROM plugin_settings_fields WHERE plugin_id = ?').run(m.id);
const insert = db.prepare(
`INSERT INTO plugin_settings_fields (plugin_id, field_key, label, input_type, placeholder, hint, required, secret, scope, options, oauth_config, sort_order)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
);
m.settings.forEach((f, i) => {
insert.run(
m.id,
f.key,
f.label ?? f.key,
f.input_type ?? 'text',
f.placeholder ?? null,
f.hint ?? null,
f.required ? 1 : 0,
f.secret ? 1 : 0,
f.scope ?? 'instance',
f.options ? JSON.stringify(f.options) : null,
f.oauth ? JSON.stringify(f.oauth) : null,
i,
);
});
}
+173
View File
@@ -0,0 +1,173 @@
import { isKnownPermission } from '../protocol/envelope';
/**
* Parse + validate a plugin's trek-plugin.json (#plugins, M4). Kept deliberately
* strict: unknown permissions, missing required fields, or a declared native
* module all fail here, before a plugin is ever registered. (The published SDK's
* shared Zod schema will supersede this in M6; the checks stay identical.)
*/
export interface ManifestSettingField {
key: string;
label?: string;
input_type?: string;
placeholder?: string;
hint?: string;
required?: boolean;
secret?: boolean;
scope?: 'instance' | 'user';
options?: Array<{ value: string; label: string }>;
oauth?: { initPath?: string; callbackPath?: string };
}
export interface WidgetCapability {
title?: string;
defaultSize?: string;
/** Where the widget mounts: dashboard sidebar (default) or as a hero-bar overlay. */
slot?: 'sidebar' | 'hero';
}
export interface PluginCapabilities {
widget?: WidgetCapability;
}
export interface PluginManifest {
id: string;
name: string;
version: string;
apiVersion: number;
author?: string;
description?: string;
homepage?: string;
icon?: string;
type: 'integration' | 'page' | 'widget';
trek?: string;
minTrekVersion?: string;
nativeModules: boolean;
permissions: string[];
egress: string[];
settings: ManifestSettingField[];
capabilities: PluginCapabilities;
}
const ID_RE = /^[a-z][a-z0-9-]{2,39}$/;
// An outbound host: an exact hostname (single-label like a `redis` sibling
// service, or a dotted FQDN) OR a `*.`-prefixed wildcard that MUST have a real
// multi-label suffix. Rejects `*`, `*.`, whole-TLD `*.com`, schemes, and any
// embedded space — all of which would otherwise widen egress or inject a CSP
// source token when the host is interpolated into connect-src.
const HOST_RE = /^(\*\.[a-z0-9-]+(\.[a-z0-9-]+)+|[a-z0-9-]+(\.[a-z0-9-]+)*)$/i;
// Static path segments under /api/admin/plugins — a plugin id must never shadow them
// (id "registry" would collide with GET registry/:id vs :id/errors routing).
const RESERVED_IDS = new Set(['registry', 'install', 'rescan']);
const SEMVER_RE = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
const TYPES = new Set(['integration', 'page', 'widget']);
export class ManifestError extends Error {}
/** JSON.parse that tolerates a UTF-8 BOM (0xFEFF) — manifests written on Windows often carry one. */
export function parseJsonText(text: string): unknown {
return JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text);
}
export function parseManifest(raw: unknown): PluginManifest {
if (!raw || typeof raw !== 'object') throw new ManifestError('manifest is not an object');
const m = raw as Record<string, unknown>;
const id = str(m.id, 'id');
if (!ID_RE.test(id)) throw new ManifestError(`invalid id "${id}" (lowercase slug, 3–40 chars)`);
if (RESERVED_IDS.has(id)) throw new ManifestError(`reserved id "${id}"`);
const version = str(m.version, 'version');
if (!SEMVER_RE.test(version)) throw new ManifestError(`invalid version "${version}"`);
const type = str(m.type, 'type');
if (!TYPES.has(type)) throw new ManifestError(`invalid type "${type}"`);
if (m.nativeModules === true) throw new ManifestError('native modules are not allowed');
const permissions = arr(m.permissions).map(String);
const unknown = permissions.filter((p) => !isKnownPermission(p));
if (unknown.length) throw new ManifestError(`unknown permission(s): ${unknown.join(', ')}`);
// Validate the host portion of every per-host outbound permission: this is the
// string the runtime egress guard AND the iframe CSP connect-src are built from.
const badOutbound = permissions
.filter((p) => p.startsWith('http:outbound:'))
.map((p) => p.slice('http:outbound:'.length))
.find((h) => !HOST_RE.test(h));
if (badOutbound !== undefined) throw new ManifestError(`invalid http:outbound host "${badOutbound}"`);
const egress = arr(m.egress).map(String);
if (permissions.some((p) => p === 'http:outbound' || p.startsWith('http:outbound:')) && egress.length === 0) {
throw new ManifestError('http:outbound declared but egress[] is empty');
}
if (egress.includes('*')) throw new ManifestError('egress[] must not contain a bare "*"');
const badEgress = egress.find((h) => !HOST_RE.test(h));
if (badEgress !== undefined) throw new ManifestError(`invalid egress host "${badEgress}"`);
const trek = optStr(m.trek);
return {
id,
name: str(m.name, 'name'),
version,
apiVersion: typeof m.apiVersion === 'number' ? m.apiVersion : 1,
author: optStr(m.author),
description: optStr(m.description),
homepage: optStr(m.homepage),
icon: optStr(m.icon) ?? 'Blocks',
type: type as PluginManifest['type'],
trek,
minTrekVersion: trek ? (trek.match(/(\d+\.\d+\.\d+)/)?.[1] ?? undefined) : undefined,
nativeModules: false,
permissions,
egress,
settings: parseSettings(m.settings),
capabilities: parseCapabilities(m.capabilities),
};
}
function parseCapabilities(raw: unknown): PluginCapabilities {
if (!raw || typeof raw !== 'object') return {};
const c = raw as Record<string, unknown>;
const out: PluginCapabilities = {};
if (c.widget && typeof c.widget === 'object') {
const w = c.widget as Record<string, unknown>;
const slot = optStr(w.slot);
if (slot && slot !== 'sidebar' && slot !== 'hero') throw new ManifestError(`invalid widget slot "${slot}"`);
out.widget = {
title: optStr(w.title),
defaultSize: optStr(w.defaultSize),
slot: (slot as WidgetCapability['slot']) ?? 'sidebar',
};
}
return out;
}
function parseSettings(raw: unknown): ManifestSettingField[] {
if (!Array.isArray(raw)) return [];
return raw
.filter((s): s is Record<string, unknown> => !!s && typeof s === 'object')
.map((s): ManifestSettingField => ({
key: String(s.key ?? ''),
label: optStr(s.label),
input_type: optStr(s.input_type) ?? 'text',
placeholder: optStr(s.placeholder),
hint: optStr(s.hint),
required: !!s.required,
secret: !!s.secret,
scope: s.scope === 'user' ? 'user' : 'instance',
options: Array.isArray(s.options) ? (s.options as Array<{ value: string; label: string }>) : undefined,
oauth: s.oauth && typeof s.oauth === 'object' ? (s.oauth as { initPath?: string; callbackPath?: string }) : undefined,
}))
.filter((s) => s.key);
}
function str(v: unknown, name: string): string {
if (typeof v !== 'string' || !v) throw new ManifestError(`missing/invalid "${name}"`);
return v;
}
function optStr(v: unknown): string | undefined {
return typeof v === 'string' && v ? v : undefined;
}
function arr(v: unknown): unknown[] {
return Array.isArray(v) ? v : [];
}
@@ -0,0 +1,39 @@
import fs from 'node:fs';
import path from 'node:path';
/**
* Scan a plugin directory for native binaries / build artifacts (#plugins, M4).
* Native modules (.node) are forbidden in v1 — a native addon in a fork() child
* is arbitrary native code at the plugin uid, which would defeat any future
* sandbox. Returns the offending relative paths (empty = clean).
*/
const OFFENDERS = /\.node$|(^|[\\/])binding\.gyp$|(^|[\\/])prebuilds?[\\/]/i;
const MAX_ENTRIES = 20_000;
export function scanForNativeBinaries(dir: string): string[] {
const hits: string[] = [];
let seen = 0;
const walk = (d: string, rel: string) => {
let entries: fs.Dirent[];
try {
entries = fs.readdirSync(d, { withFileTypes: true });
} catch {
return;
}
for (const e of entries) {
// Never silently stop scanning — an artifact padded past the cap must be
// rejected, not passed clean (it could hide a .node past the limit).
if (++seen > MAX_ENTRIES) throw new Error('artifact has too many files to scan for native binaries');
const childRel = rel ? `${rel}/${e.name}` : e.name;
if (e.isSymbolicLink()) continue; // never follow symlinks
if (e.isDirectory()) {
if (OFFENDERS.test(childRel + '/')) hits.push(childRel);
else walk(path.join(d, e.name), childRel);
} else if (OFFENDERS.test(childRel)) {
hits.push(childRel);
}
}
};
walk(dir, '');
return hits;
}
@@ -0,0 +1,148 @@
import fs from 'node:fs';
import path from 'node:path';
import zlib from 'node:zlib';
/**
* Zip/tar-slip-safe extraction (#plugins, M4). Extracts an artifact into a fresh
* directory, refusing anything that would escape it: absolute paths, ".."
* segments, symlinks/hardlinks, non-regular entries, and oversized / too-many /
* high-ratio (zip-bomb) archives. The containment check is the same idiom the
* platform routes use for uploads.
*
* v1 supports gzip'd tar (codeload archives) and stored/deflated ZIP (release
* assets) via a minimal reader — no third-party unpacker in the trust path.
*/
export interface ExtractLimits {
maxTotalBytes?: number; // uncompressed
maxEntries?: number;
maxFileBytes?: number;
}
const DEFAULTS: Required<ExtractLimits> = {
maxTotalBytes: 50 * 1024 * 1024,
maxEntries: 4000,
maxFileBytes: 25 * 1024 * 1024,
};
export class ExtractError extends Error {}
/** Assert a member path stays within dest; return the safe absolute path. */
export function safeJoin(dest: string, name: string): string {
const norm = name.replace(/\\/g, '/');
if (norm.startsWith('/') || /^[a-zA-Z]:/.test(norm)) throw new ExtractError(`absolute path rejected: ${name}`);
if (norm.split('/').some((seg) => seg === '..')) throw new ExtractError(`path traversal rejected: ${name}`);
const resolved = path.resolve(dest, norm);
const root = path.resolve(dest);
if (resolved !== root && !resolved.startsWith(root + path.sep)) throw new ExtractError(`escapes destination: ${name}`);
return resolved;
}
interface Member {
name: string;
type: 'file' | 'dir' | 'other';
data?: Buffer;
}
export function extractArchive(buf: Buffer, dest: string, limits: ExtractLimits = {}): number {
const lim = { ...DEFAULTS, ...limits };
const isGzip = buf[0] === 0x1f && buf[1] === 0x8b;
const isZip = buf[0] === 0x50 && buf[1] === 0x4b;
const members = isGzip ? readTarGz(buf, lim) : isZip ? readZip(buf, lim) : null;
if (!members) throw new ExtractError('unsupported archive format (expected .tar.gz or .zip)');
let total = 0;
let count = 0;
fs.mkdirSync(dest, { recursive: true });
for (const m of members) {
if (++count > lim.maxEntries) throw new ExtractError('too many entries');
if (m.type === 'other') throw new ExtractError(`non-regular entry rejected: ${m.name}`); // symlink/device/etc
const target = safeJoin(dest, m.name);
if (m.type === 'dir') {
fs.mkdirSync(target, { recursive: true });
continue;
}
const size = m.data?.length ?? 0;
if (size > lim.maxFileBytes) throw new ExtractError(`file too large: ${m.name}`);
total += size;
if (total > lim.maxTotalBytes) throw new ExtractError('archive exceeds size limit');
fs.mkdirSync(path.dirname(target), { recursive: true });
fs.writeFileSync(target, m.data ?? Buffer.alloc(0));
}
return total;
}
// ── minimal tar.gz reader ────────────────────────────────────────────────────
function readTarGz(buf: Buffer, lim: Required<ExtractLimits>): Member[] {
const tar = zlib.gunzipSync(buf, { maxOutputLength: lim.maxTotalBytes + 1024 * 1024 });
const members: Member[] = [];
let off = 0;
while (off + 512 <= tar.length) {
const block = tar.subarray(off, off + 512);
if (block.every((b) => b === 0)) break;
let name = block.subarray(0, 100).toString('utf8').replace(/\0.*$/, '');
const prefix = block.subarray(345, 500).toString('utf8').replace(/\0.*$/, '');
if (prefix) name = `${prefix}/${name}`;
const size = parseInt(block.subarray(124, 136).toString('utf8').replace(/\0.*$/, '').trim() || '0', 8);
const typeflag = String.fromCharCode(block[156]);
off += 512;
const data = tar.subarray(off, off + size);
off += Math.ceil(size / 512) * 512;
if (!name || name.endsWith('/PaxHeader/') || typeflag === 'x' || typeflag === 'g') continue;
if (typeflag === '5') members.push({ name, type: 'dir' });
else if (typeflag === '0' || typeflag === '\0' || typeflag === '') members.push({ name, type: 'file', data: Buffer.from(data) });
else members.push({ name, type: 'other' }); // links (1,2), devices, fifo
}
return members;
}
// ── minimal ZIP reader (central directory) ───────────────────────────────────
function readZip(buf: Buffer, lim: Required<ExtractLimits>): Member[] {
// Find End Of Central Directory.
let eocd = -1;
for (let i = buf.length - 22; i >= 0 && i > buf.length - 22 - 65536; i--) {
if (buf.readUInt32LE(i) === 0x06054b50) { eocd = i; break; }
}
if (eocd < 0) throw new ExtractError('invalid zip (no EOCD)');
const count = buf.readUInt16LE(eocd + 10);
// Bound the entry count from the EOCD (up to 65535) BEFORE inflating anything.
if (count > lim.maxEntries) throw new ExtractError('too many entries');
let p = buf.readUInt32LE(eocd + 16); // central dir offset
const members: Member[] = [];
// Enforce the cumulative uncompressed budget AS WE GO, so a decompression bomb
// (many entries each inflating to ~maxFileBytes) can't materialize gigabytes in
// memory before the caller's write loop ever runs.
let total = 0;
for (let i = 0; i < count; i++) {
if (buf.readUInt32LE(p) !== 0x02014b50) throw new ExtractError('invalid zip (central header)');
const method = buf.readUInt16LE(p + 10);
const compSize = buf.readUInt32LE(p + 20);
const nameLen = buf.readUInt16LE(p + 28);
const extraLen = buf.readUInt16LE(p + 30);
const commentLen = buf.readUInt16LE(p + 32);
const extAttr = buf.readUInt32LE(p + 38); // unix mode in high 16 bits
const lho = buf.readUInt32LE(p + 42);
const name = buf.subarray(p + 46, p + 46 + nameLen).toString('utf8');
const unixMode = (extAttr >>> 16) & 0xffff;
const isSymlink = (unixMode & 0xf000) === 0xa000;
// local header: recompute data start
const lhNameLen = buf.readUInt16LE(lho + 26);
const lhExtraLen = buf.readUInt16LE(lho + 28);
const dataStart = lho + 30 + lhNameLen + lhExtraLen;
const comp = buf.subarray(dataStart, dataStart + compSize);
p += 46 + nameLen + extraLen + commentLen;
if (isSymlink) { members.push({ name, type: 'other' }); continue; }
if (name.endsWith('/')) { members.push({ name, type: 'dir' }); continue; }
let data: Buffer;
if (method === 0) {
if (compSize > lim.maxFileBytes) throw new ExtractError(`file too large: ${name}`);
data = Buffer.from(comp);
} else if (method === 8) {
data = zlib.inflateRawSync(comp, { maxOutputLength: lim.maxFileBytes + 1024 });
} else throw new ExtractError(`unsupported zip compression method ${method}`);
total += data.length;
if (total > lim.maxTotalBytes) throw new ExtractError('archive exceeds size limit');
members.push({ name, type: 'file', data });
}
return members;
}
@@ -0,0 +1,104 @@
import { createHash } from 'node:crypto';
import dns from 'node:dns/promises';
import { isBlockedIp } from '../runtime/egress-policy';
/**
* SSRF-hardened download for the plugin installer (#plugins, M4). The primary
* control is a host allowlist (only GitHub delivery hosts); as defense in depth
* we resolve each hop and refuse private/loopback/link-local IPs, and we follow
* redirects manually so a 3xx to an internal address can't slip through. Returns
* the bytes + their sha256; the caller verifies the hash against the registry
* pin before anything is written to a plugin location.
*/
const MAX_REDIRECTS = 5;
const MAX_BYTES = 50 * 1024 * 1024;
export class DownloadError extends Error {}
/**
* GitHub delivery hosts only. Release-asset downloads 302 through a rotating
* `*.githubusercontent.com` host (objects / github-releases / release-assets …),
* so we allow that whole suffix plus github.com and codeload. The private-IP
* check below is the SSRF backstop regardless of host.
*/
function isAllowedHost(hostname: string): boolean {
const h = hostname.toLowerCase();
return h === 'github.com' || h === 'codeload.github.com' || h.endsWith('.githubusercontent.com');
}
export function isPrivateIp(ip: string): boolean {
// Reuse the egress guard's canonicalizing check so non-canonical IPv6 forms
// (hex IPv4-mapped, compressed) and CGNAT/multicast are all covered here too.
return isBlockedIp(ip);
}
async function assertSafeHost(urlStr: string): Promise<void> {
let url: URL;
try {
url = new URL(urlStr);
} catch {
throw new DownloadError(`invalid url: ${urlStr}`);
}
if (url.protocol !== 'https:') throw new DownloadError('only https downloads are allowed');
if (!isAllowedHost(url.hostname)) throw new DownloadError(`host not allowlisted: ${url.hostname}`);
const addrs = await dns.lookup(url.hostname, { all: true }).catch(() => []);
if (addrs.length === 0) throw new DownloadError(`could not resolve ${url.hostname}`);
for (const a of addrs) {
if (isPrivateIp(a.address)) throw new DownloadError(`refusing private address for ${url.hostname}`);
}
}
export async function safeDownload(urlStr: string, maxBytes = MAX_BYTES): Promise<{ bytes: Buffer; sha256: string }> {
let current = urlStr;
for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
await assertSafeHost(current);
const resp = await fetch(current, { redirect: 'manual', headers: { 'User-Agent': 'TREK-Server' } });
if (resp.status >= 300 && resp.status < 400) {
const loc = resp.headers.get('location');
if (!loc) throw new DownloadError('redirect without a location');
current = new URL(loc, current).toString();
continue;
}
if (!resp.ok) throw new DownloadError(`download failed: ${resp.status}`);
const declared = Number(resp.headers.get('content-length') || 0);
if (declared && declared > maxBytes) throw new DownloadError('artifact exceeds size limit');
// Stream the body and abort the moment it crosses the cap — a chunked response
// (e.g. codeload archives) carries no content-length, so buffering the whole
// body first (arrayBuffer) could OOM the server before any post-check fires.
const bytes = await readCapped(resp, maxBytes);
return { bytes, sha256: createHash('sha256').update(bytes).digest('hex') };
}
throw new DownloadError('too many redirects');
}
/** Read a response body into a Buffer, throwing once it exceeds maxBytes. */
async function readCapped(resp: Response, maxBytes: number): Promise<Buffer> {
const reader = resp.body?.getReader();
if (!reader) {
const b = Buffer.from(await resp.arrayBuffer());
if (b.length > maxBytes) throw new DownloadError('artifact exceeds size limit');
return b;
}
const chunks: Buffer[] = [];
let received = 0;
for (;;) {
const { done, value } = await reader.read();
if (done) break;
received += value.length;
if (received > maxBytes) {
await reader.cancel().catch(() => {});
throw new DownloadError('artifact exceeds size limit');
}
chunks.push(Buffer.from(value));
}
return Buffer.concat(chunks);
}
/** Constant-time compare of two hex digests. */
export function sha256Matches(actual: string, expected: string): boolean {
if (actual.length !== expected.length) return false;
let diff = 0;
for (let i = 0; i < actual.length; i++) diff |= actual.charCodeAt(i) ^ expected.charCodeAt(i);
return diff === 0;
}
@@ -0,0 +1,87 @@
import crypto from 'node:crypto';
/**
* Author-signature verification for the plugin installer (#plugins, #4).
*
* sha256 pinning proves the bytes match what the REGISTRY vouches for; a whoever
* controls the registry repo controls that. A minisign (Ed25519) author
* signature proves the bytes were signed by the holder of the plugin AUTHOR's
* private key — so a compromised registry cannot ship attacker code under an
* author's name without also stealing that key. TREK verifies offline with
* node:crypto (no Fulcio/Rekor phone-home), consistent with the "no telemetry
* beyond the update check" stance.
*
* Signing is OPT-IN: an entry without an author key + signature installs exactly
* as before (sha256 only). When both are present, verification is mandatory and
* a mismatch aborts the install.
*/
// SPKI DER prefix for a raw 32-byte Ed25519 public key (RFC 8410).
const ED25519_SPKI_PREFIX = Buffer.from('302a300506032b6570032100', 'hex');
export class SignatureError extends Error {}
/** Wrap a raw 32-byte Ed25519 public key as a node KeyObject. */
function ed25519KeyFromRaw(raw: Buffer): crypto.KeyObject {
if (raw.length !== 32) throw new SignatureError('public key is not a 32-byte Ed25519 key');
return crypto.createPublicKey({ key: Buffer.concat([ED25519_SPKI_PREFIX, raw]), format: 'der', type: 'spki' });
}
/**
* Parse a minisign public key. Accepts either the two-line minisign format
* (comment line + base64 payload) or a bare base64 payload. The 10-byte payload
* header is `Ed` + an 8-byte key id; the trailing 32 bytes are the Ed25519 key.
* A bare 32-byte base64 key (44 chars) is also accepted for simple deployments.
*/
function parseMinisignPubKey(pub: string): { key: crypto.KeyObject; keyId: Buffer | null } {
const line = pub.trim().split(/\r?\n/).map((l) => l.trim()).filter((l) => l && !l.startsWith('untrusted comment')).pop();
if (!line) throw new SignatureError('empty public key');
const buf = Buffer.from(line, 'base64');
if (buf.length === 32) return { key: ed25519KeyFromRaw(buf), keyId: null };
if (buf.length === 42 && buf.subarray(0, 2).toString('latin1') === 'Ed') {
return { key: ed25519KeyFromRaw(buf.subarray(10)), keyId: buf.subarray(2, 10) };
}
throw new SignatureError('unrecognized public key format');
}
/**
* Parse a minisign signature (.minisig). The relevant line is the first base64
* payload: 2-byte algorithm (`Ed` legacy | `ED` prehashed) + 8-byte key id +
* 64-byte Ed25519 signature. A bare 64-byte base64 signature (legacy over the
* raw bytes) is also accepted.
*/
function parseMinisignSignature(sig: string): { algo: 'Ed' | 'ED' | 'raw'; keyId: Buffer | null; signature: Buffer } {
const line = sig.trim().split(/\r?\n/).map((l) => l.trim()).filter((l) => l && !l.startsWith('untrusted comment')).shift();
if (!line) throw new SignatureError('empty signature');
const buf = Buffer.from(line, 'base64');
if (buf.length === 64) return { algo: 'raw', keyId: null, signature: buf };
if (buf.length === 74) {
const algo = buf.subarray(0, 2).toString('latin1');
if (algo !== 'Ed' && algo !== 'ED') throw new SignatureError(`unsupported signature algorithm ${algo}`);
return { algo, keyId: buf.subarray(2, 10), signature: buf.subarray(10) };
}
throw new SignatureError('unrecognized signature format');
}
/**
* Verify that `bytes` were signed by the holder of `publicKeyB64`'s private key.
* Supports minisign legacy (`Ed`, signs the raw file) and prehashed (`ED`, signs
* BLAKE2b-512 of the file), plus bare raw Ed25519 over the file bytes. Returns
* true on a valid signature, throws SignatureError on a malformed input, and
* returns false on a well-formed but non-matching signature.
*/
export function verifyAuthorSignature(bytes: Buffer, signatureB64: string, publicKeyB64: string): boolean {
const { key, keyId } = parseMinisignPubKey(publicKeyB64);
const { algo, keyId: sigKeyId, signature } = parseMinisignSignature(signatureB64);
// If both carry a key id, they must match the same key (catches a wrong-key mixup).
if (keyId && sigKeyId && !keyId.equals(sigKeyId)) return false;
const message =
algo === 'ED' ? crypto.createHash('blake2b512').update(bytes).digest() : bytes;
try {
return crypto.verify(null, message, key, signature);
} catch {
return false;
}
}
+15
View File
@@ -0,0 +1,15 @@
/**
* Plugin-system kill switch (#plugins). On by default — the runtime and the
* Admin → Plugins panel are available out of the box, but installed plugins
* still have to be activated one by one, so no third-party code runs until an
* admin turns a specific plugin on. Set TREK_PLUGINS_ENABLED=false to switch the
* whole system off (installed plugins stay on disk, deactivated). Lives in its
* own module (not config.ts) so the many tests that mock config with a partial
* export set don't have to know about it: the plugin runtime reads the env
* directly here. Read at call time so tests and runtime env changes take effect
* immediately.
*/
export function pluginsEnabled(): boolean {
const v = (process.env.TREK_PLUGINS_ENABLED || '').trim().toLowerCase();
return !['false', '0', 'off', 'no'].includes(v);
}
+126
View File
@@ -0,0 +1,126 @@
import fs from 'node:fs';
import path from 'node:path';
/**
* Filesystem layout for the plugin system (#plugins). Code and data are two
* separate trees so the child can be given a read-only view of its code and a
* read-write view of only its own data (M1 sets the env; the container runtime
* in v2 enforces the mounts).
*
* Defaults sit under the persisted data dir (server/data), overridable by env
* so a Docker deployment can point them at dedicated volumes.
*/
const DATA_ROOT = path.resolve(__dirname, '../../../data');
// Read lazily so a deployment (or a test) can point these at dedicated volumes
// via env without import-order surprises.
export function pluginsCodeRoot(): string {
return process.env.TREK_PLUGINS_DIR || path.join(DATA_ROOT, 'plugins');
}
export function pluginsDataRoot(): string {
return process.env.TREK_PLUGINS_DATA_DIR || path.join(DATA_ROOT, 'plugins-data');
}
/** A plugin's installed code directory (contains trek-plugin.json + server/index.js). */
export function pluginCodeDir(id: string): string {
return path.join(pluginsCodeRoot(), id);
}
/**
* The plugin code dir with symlinks resolved. The data root is often a symlink
* (Docker mounts `server/data` -> a volume), and the OS permission model checks
* REAL paths — forking the child from the real path keeps path resolution from
* ever touching the symlinked parent (which would need a broad read grant).
* Falls back to the lexical path if the dir does not exist yet.
*/
export function pluginRealCodeDir(id: string): string {
try {
return fs.realpathSync(pluginCodeDir(id));
} catch {
return pluginCodeDir(id);
}
}
/**
* Give a plugin its own `package.json` (only if it ships none) so Node resolves
* the child's module type AT the plugin root and never walks up into the data
* dir — which, under the permission model, is denied (that's the whole point).
* Defaults to CommonJS, matching the plain `module.exports` plugins ship.
*/
export function ensurePluginModuleType(codeDir: string): void {
try {
const pkg = path.join(codeDir, 'package.json');
if (!fs.existsSync(pkg)) fs.writeFileSync(pkg, '{"type":"commonjs"}\n');
} catch {
/* best effort — a missing package.json only matters under --permission */
}
}
/** A plugin's writable data directory (its own sqlite file + any blobs). */
export function pluginDataDir(id: string): string {
return path.join(pluginsDataRoot(), id);
}
/** The plugin's own sqlite file — opened by the HOST, reached by the plugin only via RPC. */
export function pluginDbFile(id: string): string {
return path.join(pluginDataDir(id), 'plugin.db');
}
/**
* The child bootstrap entry + the execArgv to fork it with.
*
* Prod/dev run the tsc output, so the sibling `runtime/plugin-host-entry.js`
* exists and forks as plain node. Under vitest the code runs from `src` as TS,
* so no `.js` sibling exists — fall back to the `.ts` source loaded via tsx (a
* prod dependency). This keeps the fork path identical in tests and production.
*/
export function resolveChildEntry(): { entry: string; execArgv: string[]; forkCwd?: string; jsMode: boolean } {
const js = path.join(__dirname, 'runtime', 'plugin-host-entry.js');
const ts = path.join(__dirname, 'runtime', 'plugin-host-entry.ts');
if (!fs.existsSync(js) && fs.existsSync(ts)) {
// tsx (dev/test only) is resolved relative to the child's cwd, so the child
// must run from a dir where `tsx` is on the node_modules chain (the server
// root) — NOT the plugin dir. The plugin itself is still loaded by absolute
// path via createRequire, so this doesn't weaken the prod isolation, where
// the .js branch below keeps cwd at the plugin dir. tsx compiles TS on the
// fly and walks node_modules, so the OS-level permission model can't be
// applied here — it is a prod-only hardening (jsMode).
return { entry: ts, execArgv: ['--import', 'tsx'], forkCwd: process.cwd(), jsMode: false };
}
return { entry: js, execArgv: ['--max-old-space-size=192'], jsMode: true };
}
/**
* The compiled server code root (…/dist), computed from this module's location.
* The plugin child needs read access to it to load its bootstrap + SDK; it must
* NOT be granted the data root (trek.db, .jwt_secret, .encryption_key live there).
*/
export function serverCodeRoot(): string {
// __dirname = …/dist/nest/plugins → …/dist
return path.resolve(__dirname, '../..');
}
/**
* Node OS-level permission-model flags for a plugin child (#plugins, #2 security
* hardening). `--permission` denies filesystem write, child_process, worker
* threads and native addons outright; `--allow-fs-read` is scoped to exactly the
* code the child must load (the compiled server dir + this plugin's own code
* dir). Result: the child can no longer read trek.db / the secret files or shell
* out, closing the direct-filesystem and RCE escapes that bypass the RPC layer.
* Empty (opt-out) when TREK_PLUGIN_PERMISSIONS=off.
*/
export function pluginPermissionArgs(pluginId: string): string[] {
if ((process.env.TREK_PLUGIN_PERMISSIONS ?? 'on').toLowerCase() === 'off') return [];
const codeRoot = serverCodeRoot();
return [
'--permission',
`--allow-fs-read=${codeRoot}`,
// The server package.json sits one level above dist and Node reads it to
// resolve the child's module type. Grant just that file — never its dir,
// which also holds the `data` symlink to trek.db and the secret files.
`--allow-fs-read=${path.join(codeRoot, '..', 'package.json')}`,
// The plugin's own code, by REAL path (see pluginRealCodeDir).
`--allow-fs-read=${pluginRealCodeDir(pluginId)}`,
];
}
@@ -0,0 +1,97 @@
import { Controller, Get, Param, Req, Res } from '@nestjs/common';
import type { Request, Response } from 'express';
import fs from 'node:fs';
import path from 'node:path';
import { pluginsEnabled } from './kill-switch';
import { PluginRuntimeService } from './plugin-runtime.service';
import { pluginCodeDir } from './paths';
/**
* Serves a page/widget plugin's static client from /plugin-frame/:id/* (#plugins,
* M3). The document is embedded in a sandbox WITHOUT allow-same-origin, so it
* runs at an OPAQUE origin: it cannot read the trek_session cookie, cannot reach
* the parent DOM, and its only channel to TREK is the postMessage bridge.
*
* Each response gets a locked-down, per-plugin CSP (default-src none; own scripts
* only; connect-src limited to declared outbound hosts) and a strict path guard
* so a plugin can only serve files under its own client/ directory.
*/
const MIME: Record<string, string> = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.mjs': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.webp': 'image/webp',
'.woff2': 'font/woff2',
'.ico': 'image/x-icon',
};
@Controller('plugin-frame/:pluginId')
export class PluginFrameController {
constructor(private readonly runtime: PluginRuntimeService) {}
@Get('*path')
serve(@Param('pluginId') pluginId: string, @Req() req: Request, @Res() res: Response): void {
if (!pluginsEnabled() || !this.runtime.isActive(pluginId)) {
res.status(404).send('Plugin not available');
return;
}
const rest = (req.params as Record<string, unknown>).path ?? (req.params as Record<string, unknown>)[0] ?? '';
const rel = (Array.isArray(rest) ? rest.join('/') : String(rest)).replace(/^\/+/, '') || 'index.html';
const clientDir = path.join(pluginCodeDir(pluginId), 'client');
const resolved = path.resolve(clientDir, rel);
// Containment: never escape the plugin's own client/ dir.
if (!resolved.startsWith(path.resolve(clientDir) + path.sep) && resolved !== path.resolve(clientDir)) {
res.status(403).send('Forbidden');
return;
}
if (!fs.existsSync(resolved) || !fs.statSync(resolved).isFile()) {
res.status(404).send('Not found');
return;
}
const ext = path.extname(resolved).toLowerCase();
res.setHeader('Content-Type', MIME[ext] ?? 'application/octet-stream');
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('Content-Security-Policy', this.frameCsp(pluginId));
res.sendFile(resolved);
}
/** Per-plugin, locked-down CSP for the sandboxed frame document. */
private frameCsp(pluginId: string): string {
// Defense in depth: the manifest validator already constrains these hosts, but
// never interpolate anything that isn't a clean host/wildcard into connect-src
// (a stray space or `*` would inject an extra CSP source token).
const outbound = this.runtime
.outboundHostsOf(pluginId)
.filter((h) => /^(\*\.[a-z0-9-]+(\.[a-z0-9-]+)+|[a-z0-9-]+(\.[a-z0-9-]+)*)$/i.test(h));
const connect = ["'self'", ...outbound.map((h) => `https://${h}`)].join(' ');
return [
"default-src 'none'",
// The frame runs at an OPAQUE origin (sandbox without allow-same-origin),
// so 'self' matches nothing — inline is the only way its own script can run.
// Safe here: the sandbox (not this script-src) is the isolation boundary,
// and the plugin author controls the frame's code either way.
"script-src 'self' 'unsafe-inline'",
"style-src 'self' 'unsafe-inline'",
"img-src 'self' data: blob:",
"font-src 'self' data:",
`connect-src ${connect}`,
"frame-ancestors 'self'",
"base-uri 'none'",
"form-action 'self'",
// No allow-popups: window.open() ignores connect-src, so it would be an
// egress/phishing bypass (open any URL / a fake full-page login). A future
// OAuth-popup addon can re-request it as an explicit capability.
'sandbox allow-scripts allow-forms',
].join('; ');
}
}
@@ -0,0 +1,230 @@
import { Injectable, type OnModuleInit, type OnModuleDestroy } from '@nestjs/common';
import { db } from '../../db/database';
import { pluginsEnabled } from './kill-switch';
import { decrypt_api_key } from '../../services/apiKeyCrypto';
import { PluginSupervisor, type PluginRouteInfo } from './supervisor/plugin-supervisor';
import fs from 'node:fs';
import { createRealRpcHost, closePluginDataDb } from './host/create-rpc-host';
import { removePluginData } from './host/plugin-data.service';
import { isKnownPermission } from './protocol/envelope';
import { discoverPlugins } from './install/discovery';
import { pluginCodeDir } from './paths';
import { PluginRegistryService } from './registry/registry.service';
const HTTP_OUTBOUND = 'http:outbound:';
/** Thrown when (re-)activating would grant permissions the admin hasn't consented to. */
export class PluginConsentRequired extends Error {
constructor(message: string, readonly newPermissions: string[] = [], readonly newEgress: string[] = []) {
super(message);
}
}
/**
* Owns the isolated-plugin runtime lifecycle inside NestJS (#plugins, M2).
* Bridges the DB registry (`plugins` rows) to the process supervisor: activate
* spawns the child with its granted permissions + decrypted instance config,
* deactivate kills it, and status/errors are persisted back to the DB. Boots all
* `active` plugins on startup when the runtime is enabled.
*/
interface PluginRow {
id: string;
status: string;
permissions: string;
granted_permissions: string;
config: string;
}
@Injectable()
export class PluginRuntimeService implements OnModuleInit, OnModuleDestroy {
private readonly supervisor = new PluginSupervisor(createRealRpcHost, {
onStatus: (id, status, error) => {
db.prepare('UPDATE plugins SET status = ?, last_error = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?').run(
status,
error ?? null,
id,
);
},
onLog: (id, level, msg) => {
if (level === 'error' || level === 'warn') {
db.prepare('INSERT INTO plugin_error_log (plugin_id, level, message) VALUES (?, ?, ?)').run(id, level, msg);
}
},
});
// Optional at the type level so tests can `new PluginRuntimeService()` without a
// registry; Nest always injects the real one (the provider is in the module).
constructor(private readonly registry?: PluginRegistryService) {}
onModuleInit(): void {
if (!pluginsEnabled()) return;
// Discover plugins placed on the volume (registers new ones inactive), then
// boot the ones an admin had already activated.
try {
discoverPlugins(db);
} catch {
/* discovery must never block boot */
}
// Boot everything the admin left ENABLED, regardless of the last runtime
// status — a crash or a bad deploy set status='error' but must not silently
// keep the plugin down forever.
const enabled = db.prepare('SELECT id FROM plugins WHERE enabled = 1').all() as Array<{ id: string }>;
for (const { id } of enabled) {
this.activate(id).catch(() => {
/* status is persisted as error by the supervisor hook */
});
}
}
/** Re-scan the plugins volume on demand (admin action). */
rescan(): { discovered: string[]; skipped: string[] } {
return discoverPlugins(db);
}
async onModuleDestroy(): Promise<void> {
await this.supervisor.shutdownAll();
}
/**
* Spawn a plugin from its DB row (granted permissions + decrypted config).
*
* A plain activate may NEVER widen what the admin already consented to — that is
* what stops a plugin left off pending an update's re-consent from silently
* gaining the new rights via the row's enable toggle. The FIRST activation of a
* freshly-installed plugin (no prior grant) is itself the consent for its
* declared set; widening an already-consented set requires `consentWiden` (the
* update consent dialog), and otherwise throws PluginConsentRequired.
*/
async activate(id: string, consentWiden = false): Promise<void> {
const row = db.prepare('SELECT id, status, permissions, granted_permissions, config FROM plugins WHERE id = ?').get(id) as
| PluginRow
| undefined;
if (!row) throw new Error(`plugin ${id} not found`);
const declared = parseArray(row.permissions).filter(isKnownPermission);
const granted = parseArray(row.granted_permissions);
const newGrants = declared.filter((p) => !granted.includes(p));
// "Ever consented" is a non-empty granted_permissions string (even '[]' — the
// consent to zero perms). Only the very first activation (marker '') may grant
// the declared set without an explicit consent; any later widening needs one.
const everConsented = !!row.granted_permissions;
if (everConsented && newGrants.length > 0 && !consentWiden) {
const newEgress = newGrants.filter((p) => p.startsWith(HTTP_OUTBOUND)).map((p) => p.slice(HTTP_OUTBOUND.length)).filter(Boolean);
const newPermissions = newGrants.filter((p) => !p.startsWith(HTTP_OUTBOUND));
throw new PluginConsentRequired(`plugin ${id} requests new permissions; explicit re-consent is required`, newPermissions, newEgress);
}
// Mark it enabled (admin intent) so it reboots after restarts/crashes.
db.prepare('UPDATE plugins SET granted_permissions = ?, enabled = 1 WHERE id = ?').run(JSON.stringify(declared), id);
const config = decryptConfig(parseObject(row.config));
const egress = declared.filter((p) => p.startsWith('http:outbound:')).map((p) => p.slice('http:outbound:'.length));
await this.supervisor.activate(id, new Set(declared), config, egress);
}
async deactivate(id: string): Promise<void> {
await this.supervisor.disable(id);
closePluginDataDb(id);
db.prepare("UPDATE plugins SET status = 'inactive', enabled = 0, updated_at = CURRENT_TIMESTAMP WHERE id = ?").run(id);
}
/**
* Update a plugin to the registry's latest version with a re-consent gate: the
* new version's declared permissions are diffed against what the admin already
* granted. Nothing new → the plugin is transparently restarted on the new code.
* Anything new (a permission or an outbound host) → the plugin is left INACTIVE
* and the delta is returned, so the caller can show it and only re-activate on
* an explicit admin click. An update never silently widens what a plugin may do.
*
* Install runs first so a failed download/signature/integrity check leaves the
* currently-running child untouched (it keeps serving the old code from memory).
*/
async update(id: string): Promise<{ version: string; activated: boolean; newPermissions: string[]; newEgress: string[] }> {
const before = db.prepare('SELECT enabled, granted_permissions FROM plugins WHERE id = ?').get(id) as
| { enabled: number; granted_permissions: string }
| undefined;
if (!before) throw new Error(`plugin ${id} not found`);
if (!this.registry) throw new Error('registry service unavailable');
const wasEnabled = before.enabled === 1;
const granted = new Set(parseArray(before.granted_permissions));
const res = await this.registry.install(id); // swaps code + refreshes declared permissions; keeps granted
const declared = parseArray(
(db.prepare('SELECT permissions FROM plugins WHERE id = ?').get(id) as { permissions: string }).permissions,
).filter(isKnownPermission);
const newGrants = declared.filter((p) => !granted.has(p));
const newEgress = newGrants.filter((p) => p.startsWith(HTTP_OUTBOUND)).map((p) => p.slice(HTTP_OUTBOUND.length)).filter(Boolean);
const newPermissions = newGrants.filter((p) => !p.startsWith(HTTP_OUTBOUND));
if (wasEnabled) await this.deactivate(id); // stop the old child now that new code is in place
if (newGrants.length === 0 && wasEnabled) {
await this.activate(id); // no wider rights → transparent restart on the new code
return { version: res.version, activated: true, newPermissions, newEgress };
}
// New rights requested (or it was already disabled): leave it inactive until
// an admin explicitly consents by activating it.
return { version: res.version, activated: false, newPermissions, newEgress };
}
/** Stop the plugin, remove its code, and optionally delete all its data. */
async uninstall(id: string, deleteData: boolean): Promise<void> {
await this.supervisor.disable(id);
closePluginDataDb(id);
// Code always goes; the DB metadata + fields go so it disappears from the UI.
fs.rmSync(pluginCodeDir(id), { recursive: true, force: true });
db.prepare('DELETE FROM plugins WHERE id = ?').run(id);
db.prepare('DELETE FROM plugin_settings_fields WHERE plugin_id = ?').run(id);
if (deleteData) {
removePluginData(id);
db.prepare('DELETE FROM plugin_error_log WHERE plugin_id = ?').run(id);
db.prepare("DELETE FROM settings WHERE key LIKE ?").run(`plugin:${id}:%`);
}
}
isActive(id: string): boolean {
return this.supervisor.isActive(id);
}
/** Declared outbound hosts (from http:outbound:<host> grants) for the frame CSP. */
outboundHostsOf(id: string): string[] {
const row = db.prepare('SELECT granted_permissions FROM plugins WHERE id = ?').get(id) as
| { granted_permissions: string }
| undefined;
if (!row) return [];
return parseArray(row.granted_permissions)
.filter((p) => p.startsWith('http:outbound:'))
.map((p) => p.slice('http:outbound:'.length))
.filter(Boolean);
}
routesOf(id: string): PluginRouteInfo[] {
return this.supervisor.routesOf(id);
}
invoke(id: string, method: string, params: Record<string, unknown>, actingUserId?: number): Promise<unknown> {
return this.supervisor.invoke(id, method, params, { actingUserId });
}
}
function parseArray(json: string): string[] {
try {
const v = JSON.parse(json || '[]');
return Array.isArray(v) ? v.map(String) : [];
} catch {
return [];
}
}
function parseObject(json: string): Record<string, unknown> {
try {
const v = JSON.parse(json || '{}');
return v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : {};
} catch {
return {};
}
}
/** Decrypt secret config values transparently (decrypt_api_key passes plaintext through). */
function decryptConfig(config: Record<string, unknown>): Record<string, unknown> {
const out: Record<string, unknown> = {};
for (const [k, v] of Object.entries(config)) {
out[k] = typeof v === 'string' ? decrypt_api_key(v) : v;
}
return out;
}
@@ -0,0 +1,42 @@
import { Controller, Get, UseGuards } from '@nestjs/common';
import { db } from '../../db/database';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { pluginsEnabled } from './kill-switch';
/**
* GET /api/plugins — the authenticated feed of ACTIVE plugins the client renders
* (#plugins, M3): page plugins become nav entries, widget plugins become
* dashboard widgets. Empty when the runtime is disabled. Distinct from the
* admin surface (/api/admin/plugins) and the per-plugin proxy
* (/api/plugins/:id/*) — this is the exact /api/plugins path.
*/
interface ActivePlugin {
id: string;
name: string;
type: string;
icon: string | null;
slot: 'sidebar' | 'hero';
}
@Controller('api/plugins')
@UseGuards(JwtAuthGuard)
export class PluginsFeedController {
@Get()
list(): { plugins: ActivePlugin[] } {
if (!pluginsEnabled()) return { plugins: [] };
const rows = db
.prepare("SELECT id, name, type, icon, capabilities FROM plugins WHERE status = 'active' ORDER BY sort_order, name")
.all() as Array<Omit<ActivePlugin, 'slot'> & { capabilities: string }>;
const plugins = rows.map(({ capabilities, ...p }) => ({ ...p, slot: slotOf(capabilities) }));
return { plugins };
}
}
function slotOf(capabilities: string): 'sidebar' | 'hero' {
try {
const c = JSON.parse(capabilities || '{}') as { widget?: { slot?: string } };
return c.widget?.slot === 'hero' ? 'hero' : 'sidebar';
} catch {
return 'sidebar';
}
}
@@ -0,0 +1,105 @@
import { All, Controller, Param, Req, Res } from '@nestjs/common';
import type { Request, Response } from 'express';
import { extractToken, verifyJwtAndLoadUser } from '../../middleware/auth';
import { pluginsEnabled } from './kill-switch';
import { PluginRuntimeService } from './plugin-runtime.service';
/**
* Proxies a plugin's own HTTP routes at /api/plugins/:id/* (#plugins, M2).
*
* This is a SINGLE static Nest route — it never registers per-plugin routes at
* runtime. It matches the request against the plugin's declared routes, enforces
* per-route auth (routes with `auth:false` — OAuth callbacks/webhooks — skip the
* session check), and forwards a minimal, whitelisted request view to the
* isolated child over RPC. The plugin never sees raw headers or the session
* cookie, so it cannot replay the user's credentials.
*/
// A plugin fully controls the reply's content-type + body, and this route is on
// TREK's REAL origin, so we must never let the browser RENDER it as a document
// (that would run plugin script at our origin, outside the iframe sandbox) nor
// follow a plugin-chosen redirect. `location` / `content-disposition` are NOT
// passthrough; every reply is forced to nosniff + attachment below. fetch-based
// consumers (the plugin's own client) are unaffected — fetch ignores both.
const SAFE_RESPONSE_HEADERS = new Set(['content-type', 'cache-control']);
@Controller('api/plugins/:pluginId')
export class PluginsProxyController {
constructor(private readonly runtime: PluginRuntimeService) {}
@All('*path')
async proxy(@Param('pluginId') pluginId: string, @Req() req: Request, @Res() res: Response): Promise<void> {
if (!pluginsEnabled() || !this.runtime.isActive(pluginId)) {
res.status(404).json({ error: 'Plugin not found' });
return;
}
const rest = (req.params as Record<string, unknown>).path ?? (req.params as Record<string, unknown>)[0] ?? '';
const sub = '/' + (Array.isArray(rest) ? rest.join('/') : String(rest)).replace(/^\/+/, '');
const route = this.runtime.routesOf(pluginId).find((r) => r.method === req.method && r.path === sub);
if (!route) {
res.status(404).json({ error: 'Not found' });
return;
}
// Per-route auth: default-on; `auth:false` routes are public (OAuth cb/webhook).
let user: { id: number; username: string; is_admin?: boolean } | null = null;
if (route.auth) {
const token = extractToken(req);
const loaded = token ? verifyJwtAndLoadUser(token) : null;
if (!loaded) {
res.status(401).json({ error: 'Access token required', code: 'AUTH_REQUIRED' });
return;
}
user = loaded;
}
try {
const reply = (await this.runtime.invoke(
pluginId,
'invoke.route',
{
routeId: route.i,
req: {
method: req.method,
path: sub,
query: req.query,
body: req.body ?? null,
user: user ? { id: user.id, username: user.username, isAdmin: !!user.is_admin } : null,
},
},
// Bind the authenticated session user as the acting user for any trip
// reads this invocation makes — the plugin cannot override it.
user?.id,
)) as { status?: number; headers?: Record<string, string>; body?: unknown };
const status = reply?.status ?? 200;
const headers = reply?.headers ?? {};
res.setHeader('X-Content-Type-Options', 'nosniff');
// A genuine redirect (301/302/303/307/308) may only target a RELATIVE in-app
// path — never an external URL (open redirect / phishing). This still lets an
// OAuth-callback route bounce the user back into the app. 300/304 aren't
// redirects and fall through to the normal path.
if ([301, 302, 303, 307, 308].includes(status)) {
const loc = Object.entries(headers).find(([k]) => k.toLowerCase() === 'location')?.[1];
if (typeof loc !== 'string' || !/^\/(?!\/)/.test(loc)) {
res.status(502).json({ error: 'Plugin error', detail: 'unsafe redirect target' });
return;
}
res.status(status).setHeader('Location', loc);
res.end();
return;
}
for (const [k, v] of Object.entries(headers)) {
if (SAFE_RESPONSE_HEADERS.has(k.toLowerCase())) res.setHeader(k, v);
}
// Never let a non-redirect reply render as a document at TREK's origin
// (that would run plugin script at our real origin, outside the sandbox).
res.setHeader('Content-Disposition', 'attachment');
res.status(status).send(reply?.body ?? '');
} catch (e) {
res.status(502).json({ error: 'Plugin error', detail: e instanceof Error ? e.message : 'unknown' });
}
}
}
@@ -0,0 +1,131 @@
import { Body, Controller, Delete, Get, HttpCode, HttpException, Param, Post, Put, UseGuards } from '@nestjs/common';
import { PluginsService } from './plugins.service';
import { PluginRuntimeService, PluginConsentRequired } from './plugin-runtime.service';
import { PluginRegistryService } from './registry/registry.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { AdminGuard } from '../auth/admin.guard';
import { pluginsEnabled } from './kill-switch';
/**
* /api/admin/plugins — admin-only plugin control surface (#plugins).
*
* M0: read-only listing + the runtime-enabled flag.
* M2: activate / deactivate (spawns/kills the isolated child) + instance config.
* Admin-gated like the rest of /api/admin. The proxy namespace /api/plugins/:id
* is a separate controller.
*/
@Controller('api/admin/plugins')
@UseGuards(JwtAuthGuard, AdminGuard)
export class PluginsController {
constructor(
private readonly plugins: PluginsService,
private readonly runtime: PluginRuntimeService,
private readonly registry: PluginRegistryService,
) {}
@Get()
list() {
return this.plugins.list();
}
@Get('registry')
browse() {
return this.registry.browse();
}
@Get('registry/:id')
async registryDetail(@Param('id') id: string) {
try {
return await this.registry.detail(id);
} catch (e) {
throw new HttpException({ error: e instanceof Error ? e.message : 'not found' }, 404);
}
}
@Post('install')
@HttpCode(200)
async install(@Body() body: { id?: string; version?: string }) {
if (!pluginsEnabled()) throw new HttpException({ error: 'Plugins are disabled by server configuration' }, 503);
if (!body?.id) throw new HttpException({ error: 'id is required' }, 400);
try {
return await this.registry.install(body.id, body.version);
} catch (e) {
throw new HttpException({ error: e instanceof Error ? e.message : 'install failed' }, 400);
}
}
@Get(':id/config')
getConfig(@Param('id') id: string) {
return { config: this.plugins.getInstanceConfig(id) };
}
@Put(':id/config')
updateConfig(@Param('id') id: string, @Body() body: Record<string, unknown>) {
return { config: this.plugins.updateInstanceConfig(id, body || {}) };
}
@Post(':id/activate')
@HttpCode(200)
async activate(@Param('id') id: string, @Body() body: { consent?: boolean } = {}) {
if (!pluginsEnabled()) throw new HttpException({ error: 'Plugins are disabled by server configuration' }, 503);
try {
await this.runtime.activate(id, !!body?.consent);
} catch (e) {
// Re-enabling a plugin whose update widened its permissions must NOT grant
// them silently — surface a distinct code so the UI opens the consent dialog.
if (e instanceof PluginConsentRequired) {
throw new HttpException({ error: e.message, code: 'CONSENT_REQUIRED', newPermissions: e.newPermissions, newEgress: e.newEgress }, 409);
}
throw new HttpException({ error: e instanceof Error ? e.message : 'activation failed' }, 400);
}
return { status: this.runtime.isActive(id) ? 'active' : 'error' };
}
@Post(':id/deactivate')
@HttpCode(200)
async deactivate(@Param('id') id: string) {
await this.runtime.deactivate(id);
return { status: 'inactive' };
}
@Post(':id/update')
@HttpCode(200)
async update(@Param('id') id: string) {
if (!pluginsEnabled()) throw new HttpException({ error: 'Plugins are disabled by server configuration' }, 503);
try {
return await this.runtime.update(id);
} catch (e) {
throw new HttpException({ error: e instanceof Error ? e.message : 'update failed' }, 400);
}
}
@Post(':id/uninstall')
@HttpCode(200)
async uninstall(@Param('id') id: string, @Body() body: { deleteData?: boolean }) {
await this.runtime.uninstall(id, !!body?.deleteData);
return { status: 'uninstalled' };
}
@Get(':id/errors')
errors(@Param('id') id: string) {
return { errors: this.plugins.errors(id) };
}
@Get(':id/audit')
audit(@Param('id') id: string) {
return { audit: this.plugins.auditLog(id) };
}
@Delete(':id/errors')
clearErrors(@Param('id') id: string) {
this.plugins.clearErrors(id);
return { ok: true };
}
@Post('rescan')
@HttpCode(200)
rescan() {
if (!pluginsEnabled()) throw new HttpException({ error: 'Plugins are disabled by server configuration' }, 503);
return this.runtime.rescan();
}
}
+21
View File
@@ -0,0 +1,21 @@
import { Module } from '@nestjs/common';
import { PluginsController } from './plugins.controller';
import { PluginsFeedController } from './plugins-feed.controller';
import { PluginsProxyController } from './plugins-proxy.controller';
import { PluginFrameController } from './plugin-frame.controller';
import { PluginsService } from './plugins.service';
import { PluginRuntimeService } from './plugin-runtime.service';
import { PluginRegistryService } from './registry/registry.service';
/**
* Plugin system (#plugins). M0 read side + M2 isolated runtime + M3 frontend:
* the runtime service owns the process supervisor and boots active plugins on
* startup; the proxy forwards /api/plugins/:id/* to the child; the feed lists
* active plugins for the client; the frame controller serves sandboxed page/
* widget assets at /plugin-frame/:id/*.
*/
@Module({
controllers: [PluginsController, PluginsFeedController, PluginsProxyController, PluginFrameController],
providers: [PluginsService, PluginRuntimeService, PluginRegistryService],
})
export class PluginsModule {}
+123
View File
@@ -0,0 +1,123 @@
import { Injectable } from '@nestjs/common';
import { db } from '../../db/database';
import { pluginsEnabled } from './kill-switch';
import { maybe_encrypt_api_key } from '../../services/apiKeyCrypto';
import { readAudit } from './host/plugin-audit';
const SECRET_MASK = '••••••••';
/**
* Read side of the plugin system (#plugins), M0 scaffold. Lists installed
* plugins from the `plugins` registry table and reports whether the runtime is
* enabled (TREK_PLUGINS_ENABLED). No execution here — the isolated runtime,
* install pipeline and registry fetch land in later milestones.
*/
export interface PluginListItem {
id: string;
name: string;
description: string | null;
type: string;
icon: string | null;
version: string | null;
status: string;
enabled: number;
last_error: string | null;
reviewed_at: string | null;
source_repo: string | null;
/** Declared permissions (JSON string) — drives the "what this can access" chips. */
permissions: string;
/** Declared capabilities (JSON string) — e.g. widget slot. */
capabilities: string;
}
@Injectable()
export class PluginsService {
list(): { enabled: boolean; plugins: PluginListItem[] } {
const plugins = db
.prepare(
`SELECT id, name, description, type, icon, version, status, enabled, last_error, reviewed_at, source_repo,
permissions, capabilities
FROM plugins
ORDER BY sort_order, name`,
)
.all() as PluginListItem[];
return { enabled: pluginsEnabled(), plugins };
}
/**
* Merge instance-scope settings into the plugin's config, encrypting fields
* declared secret (unless the value is the unchanged mask sentinel). Returns
* the config with secrets masked for the client.
*/
updateInstanceConfig(id: string, patch: Record<string, unknown>): Record<string, unknown> {
const row = db.prepare('SELECT config FROM plugins WHERE id = ?').get(id) as { config: string } | undefined;
if (!row) throw new Error(`plugin ${id} not found`);
const secretKeys = new Set(
(
db
.prepare("SELECT field_key FROM plugin_settings_fields WHERE plugin_id = ? AND scope = 'instance' AND secret = 1")
.all(id) as Array<{ field_key: string }>
).map((r) => r.field_key),
);
const config = safeParse(row.config);
for (const [k, v] of Object.entries(patch)) {
if (secretKeys.has(k)) {
if (v === SECRET_MASK) continue; // unchanged secret — keep stored ciphertext
config[k] = maybe_encrypt_api_key(v);
} else {
config[k] = v;
}
}
db.prepare('UPDATE plugins SET config = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?').run(JSON.stringify(config), id);
return maskSecrets(config, secretKeys);
}
/** A plugin's error log, newest first. */
errors(id: string): Array<{ ts: string; level: string; message: string }> {
return db
.prepare('SELECT ts, level, message FROM plugin_error_log WHERE plugin_id = ? ORDER BY ts DESC, id DESC LIMIT 200')
.all(id) as Array<{ ts: string; level: string; message: string }>;
}
clearErrors(id: string): void {
db.prepare('DELETE FROM plugin_error_log WHERE plugin_id = ?').run(id);
}
/** A plugin's hash-chained capability audit log, newest first. */
auditLog(id: string): unknown[] {
return readAudit(db, id);
}
/** Read the instance config with secret fields masked. */
getInstanceConfig(id: string): Record<string, unknown> {
const row = db.prepare('SELECT config FROM plugins WHERE id = ?').get(id) as { config: string } | undefined;
if (!row) throw new Error(`plugin ${id} not found`);
const secretKeys = new Set(
(
db
.prepare("SELECT field_key FROM plugin_settings_fields WHERE plugin_id = ? AND scope = 'instance' AND secret = 1")
.all(id) as Array<{ field_key: string }>
).map((r) => r.field_key),
);
return maskSecrets(safeParse(row.config), secretKeys);
}
}
function safeParse(json: string): Record<string, unknown> {
try {
const v = JSON.parse(json || '{}');
return v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : {};
} catch {
return {};
}
}
function maskSecrets(config: Record<string, unknown>, secretKeys: Set<string>): Record<string, unknown> {
const out: Record<string, unknown> = {};
for (const [k, v] of Object.entries(config)) {
out[k] = secretKeys.has(k) && v ? SECRET_MASK : v;
}
return out;
}
@@ -0,0 +1,89 @@
/**
* The host <-> plugin JSON-RPC wire protocol (#plugins, M1).
*
* PURE TYPES ONLY — this file must never import anything with runtime side
* effects. It is loaded by BOTH the privileged host (parent process) and the
* isolated plugin child, and the child must not transitively pull in db, config
* or the websocket server. Keep it dependency-free.
*/
export type PluginErrCode =
| 'PERMISSION_DENIED' // a real method the plugin was not granted
| 'UNKNOWN_METHOD' // not a method the host exposes at all
| 'BAD_PARAMS' // params failed validation
| 'RESOURCE_FORBIDDEN' // granted, but the acting user can't touch this resource
| 'TIMEOUT'
| 'PLUGIN_ERROR'
| 'HOST_ERROR';
export interface RpcRequest {
k: 'req';
id: string;
method: string;
params: unknown;
}
export interface RpcResponse {
k: 'res';
id: string;
ok: true;
result: unknown;
}
export interface RpcError {
k: 'res';
id: string;
ok: false;
error: { code: PluginErrCode; message: string };
}
export interface RpcEvent {
k: 'evt';
topic: string;
data: unknown;
}
export type Envelope = RpcRequest | RpcResponse | RpcError | RpcEvent;
/**
* Every method the host CAN expose. The capability router registers only the
* subset a plugin was granted; anything here but ungranted resolves to
* PERMISSION_DENIED, anything not here at all resolves to UNKNOWN_METHOD.
*/
export const KNOWN_METHODS = [
'db.exec',
'db.query',
'db.migrate',
'trips.getById',
'trips.getPlaces',
'trips.getReservations',
'users.getById',
'ws.broadcastToTrip',
'ws.broadcastToUser',
] as const;
export type KnownMethod = (typeof KNOWN_METHODS)[number];
/** Which permission unlocks which method(s). The single source for the router. */
export const METHOD_PERMISSION: Record<KnownMethod, string> = {
'db.exec': 'db:own',
'db.query': 'db:own',
'db.migrate': 'db:own',
'trips.getById': 'db:read:trips',
'trips.getPlaces': 'db:read:trips',
'trips.getReservations': 'db:read:trips',
'users.getById': 'db:read:users',
'ws.broadcastToTrip': 'ws:broadcast:trip',
'ws.broadcastToUser': 'ws:broadcast:user',
};
/** All permission strings the host understands (unknown ones are rejected at activation). */
export const KNOWN_PERMISSIONS = [
'db:own',
'db:read:trips',
'db:read:users',
'ws:broadcast:trip',
'ws:broadcast:user',
'hook:photo-provider',
'hook:calendar-source',
'http:outbound',
] as const;
export function isKnownPermission(p: string): boolean {
return (KNOWN_PERMISSIONS as readonly string[]).includes(p) || p.startsWith('http:outbound:');
}
@@ -0,0 +1,281 @@
import { Injectable } from '@nestjs/common';
import fs from 'node:fs';
import path from 'node:path';
import { db } from '../../../db/database';
import { pluginCodeDir, pluginsCodeRoot, pluginsDataRoot } from '../paths';
import { safeDownload, sha256Matches } from '../install/safe-fetch';
import { verifyAuthorSignature } from '../install/verify-signature';
import { extractArchive } from '../install/safe-extract';
import { scanForNativeBinaries } from '../install/native-scan';
import { parseJsonText, parseManifest } from '../install/manifest';
import { discoverPlugins } from '../install/discovery';
/**
* TREK-side of the plugin registry (#plugins, M5). Fetches the single aggregated
* dist/index.json (never per-plugin GitHub API calls — the HACS rate-limit
* lesson), caches it briefly + soft-fails, and installs a pinned version through
* the M4 pipeline: SSRF-safe download -> sha256 verify -> zip/tar-slip-safe
* extract -> manifest re-validate -> native re-scan -> atomic move -> discover
* (registers INACTIVE). Nothing executes on install; activation is separate.
*/
const REGISTRY_URL =
process.env.TREK_PLUGIN_REGISTRY_URL ||
'https://raw.githubusercontent.com/mauriceboe/TREK-Plugins/main/dist/index.json';
const CACHE_TTL = 30 * 60 * 1000;
const MANIFEST_MAX_BYTES = 256 * 1024;
interface RegistryVersion {
version: string;
gitTag: string;
commitSha: string;
downloadUrl: string;
sha256: string;
minTrekVersion: string;
maxTrekVersion?: string | null;
size?: number;
apiVersion?: number;
nativeModules?: boolean;
publishedAt?: string;
/** base64 minisign signature (.minisig payload) over the artifact bytes. */
signature?: string;
}
export interface RegistryEntry {
id: string;
name: string;
author: string;
description: string;
repo: string;
homepage?: string;
tags?: string[];
type: string;
reviewedAt?: string | null;
/** base64 minisign author public key — stable across versions, TOFU-pinned. */
authorPublicKey?: string;
versions: RegistryVersion[];
}
interface Registry {
schemaVersion: number;
generatedAt?: string;
plugins: RegistryEntry[];
}
/** Anzeige-only preview of a plugin's live manifest (fetched at the reviewed commit). */
export interface ManifestPreview {
permissions: string[];
egress: string[];
settings: Array<{ key: string; label: string; inputType: string; scope: string; required: boolean }>;
license: string | null;
icon: string | null;
}
let _cache: { data: Registry; expiresAt: number } | null = null;
const _detailCache = new Map<string, { data: unknown; expiresAt: number }>();
/** Test hook: drop the in-memory registry cache. */
export function __clearRegistryCacheForTests(): void {
_cache = null;
_detailCache.clear();
}
export class RegistryError extends Error {}
@Injectable()
export class PluginRegistryService {
/** Fetch the aggregated registry (cached, soft-fail, stale-serve). */
async fetchRegistry(): Promise<Registry> {
if (_cache && Date.now() < _cache.expiresAt) return _cache.data;
try {
const resp = await fetch(REGISTRY_URL, { headers: { 'User-Agent': 'TREK-Server' } });
if (!resp.ok) throw new Error(`registry ${resp.status}`);
const data = (await resp.json()) as Registry;
if (!data || !Array.isArray(data.plugins)) throw new Error('malformed registry');
_cache = { data, expiresAt: Date.now() + CACHE_TTL };
return data;
} catch {
return _cache?.data ?? { schemaVersion: 1, plugins: [] };
}
}
/** The browse list the admin UI renders (metadata only, no code). */
async browse(): Promise<Array<Omit<RegistryEntry, 'versions'> & { latest: string | null; minTrekVersion: string | null; screenshotUrl: string | null }>> {
const reg = await this.fetchRegistry();
return reg.plugins.map((p) => {
const latest = p.versions[0] ?? null;
return {
id: p.id, name: p.name, author: p.author, description: p.description, repo: p.repo,
homepage: p.homepage, tags: p.tags, type: p.type, reviewedAt: p.reviewedAt ?? null,
latest: latest?.version ?? null, minTrekVersion: latest?.minTrekVersion ?? null,
screenshotUrl: latest ? rawFileUrl(p.repo, latest.commitSha, 'docs/screenshot.png') : null,
};
});
}
/**
* Everything the browse detail view shows for one plugin: the registry entry
* plus a preview of its live manifest (permissions, egress, settings) fetched
* from the author repo at the pinned/reviewed commit. Display-only — the
* install pipeline re-validates the manifest inside the downloaded artifact.
* Cached per plugin (30 min) and only fetched when a detail view opens, never
* for the whole grid (the HACS rate-limit lesson).
*/
async detail(id: string): Promise<Record<string, unknown>> {
const hit = _detailCache.get(id);
if (hit && Date.now() < hit.expiresAt) return hit.data as Record<string, unknown>;
const reg = await this.fetchRegistry();
const entry = reg.plugins.find((p) => p.id === id);
if (!entry) throw new RegistryError(`plugin ${id} not in registry`);
const latest = entry.versions[0] ?? null;
let manifest: ManifestPreview | null = null;
if (latest) {
try {
const { bytes } = await safeDownload(rawFileUrl(entry.repo, latest.commitSha, 'trek-plugin.json'), MANIFEST_MAX_BYTES);
manifest = previewManifest(parseJsonText(bytes.toString('utf8')));
} catch {
// Soft-fail: the detail view still renders from registry metadata alone.
}
}
const data = {
id: entry.id, name: entry.name, author: entry.author, description: entry.description,
repo: entry.repo, homepage: entry.homepage ?? null, tags: entry.tags ?? [], type: entry.type,
reviewedAt: entry.reviewedAt ?? null,
latest: latest?.version ?? null, minTrekVersion: latest?.minTrekVersion ?? null,
size: latest?.size ?? null, publishedAt: latest?.publishedAt ?? null,
screenshotUrl: latest ? rawFileUrl(entry.repo, latest.commitSha, 'docs/screenshot.png') : null,
manifest,
};
// Don't negative-cache a transiently failed manifest fetch — the next
// detail open should retry instead of hiding the preview for 30 minutes.
if (manifest || !latest) _detailCache.set(id, { data, expiresAt: Date.now() + CACHE_TTL });
return data;
}
/** Install a pinned version from the registry. Returns the installed plugin id. */
async install(id: string, version?: string): Promise<{ id: string; version: string }> {
const reg = await this.fetchRegistry();
const entry = reg.plugins.find((p) => p.id === id);
if (!entry) throw new RegistryError(`plugin ${id} not in registry`);
const ver = version ? entry.versions.find((v) => v.version === version) : entry.versions[0];
if (!ver) throw new RegistryError(`version ${version ?? 'latest'} not found for ${id}`);
// 1. SSRF-safe download + 2. sha256 verify
const { bytes, sha256 } = await safeDownload(ver.downloadUrl, (ver.size ?? 50 * 1024 * 1024) + 4096);
if (!sha256Matches(sha256, ver.sha256)) throw new RegistryError('integrity check failed (sha256 mismatch)');
// 2b. author signature (opt-in) + TOFU key pin. Unsigned plugins skip this
// and install on sha256 alone (unchanged behaviour); a signed plugin must
// verify, and its author key must match the one pinned on first install.
this.verifySignatureAndTofu(id, bytes, entry, ver);
// 3. zip/tar-slip-safe extract to staging
const staging = path.join(pluginsDataRoot(), '.staging', `${id}-${ver.version}-${Date.now()}`);
try {
extractArchive(bytes, staging);
const pluginRoot = locateManifestDir(staging);
if (!pluginRoot) throw new RegistryError('archive contains no trek-plugin.json');
// 4. re-validate the bundled manifest + 5. native re-scan
const manifest = parseManifest(parseJsonText(fs.readFileSync(path.join(pluginRoot, 'trek-plugin.json'), 'utf8')));
if (manifest.id !== id) throw new RegistryError(`manifest id "${manifest.id}" != "${id}"`);
if (scanForNativeBinaries(pluginRoot).length) throw new RegistryError('artifact contains native binaries');
// 6. atomic move into place
const dest = pluginCodeDir(id);
fs.mkdirSync(pluginsCodeRoot(), { recursive: true });
fs.rmSync(dest, { recursive: true, force: true });
fs.renameSync(pluginRoot, dest);
// 7. register INACTIVE (record provenance)
discoverPlugins(db);
db.prepare('UPDATE plugins SET source_repo = ?, source_commit = ?, sha256 = ?, reviewed_at = ? WHERE id = ?').run(
entry.repo, ver.commitSha, ver.sha256, entry.reviewedAt ?? null, id,
);
// Pin the author key on first successful install of a signed plugin (TOFU).
if (entry.authorPublicKey) {
db.prepare('UPDATE plugins SET author_pubkey = ? WHERE id = ?').run(entry.authorPublicKey, id);
}
return { id, version: ver.version };
} finally {
fs.rmSync(staging, { recursive: true, force: true });
}
}
/**
* Verify the author signature (if the entry declares a key + the version a
* signature) and enforce Trust-On-First-Use on the author key.
*
* - Neither key nor signature → unsigned plugin, skip (opt-in).
* - Key present but no signature (or vice versa) → hard stop; a half-signed
* entry is a misconfiguration we refuse rather than silently downgrade.
* - Signature invalid → hard stop.
* - Registry key differs from the key pinned on a prior install → hard stop
* (author change / rotation / attack; needs an explicit admin re-trust).
*/
private verifySignatureAndTofu(id: string, bytes: Buffer, entry: RegistryEntry, ver: RegistryVersion): void {
const pinned = (db.prepare('SELECT author_pubkey FROM plugins WHERE id = ?').get(id) as { author_pubkey?: string } | undefined)?.author_pubkey ?? null;
if (!entry.authorPublicKey && !ver.signature) {
if (pinned) throw new RegistryError('this plugin was signed before but the update is unsigned — refusing');
return; // unsigned throughout: sha256 is the only pin
}
if (!entry.authorPublicKey || !ver.signature) {
throw new RegistryError('incomplete signature: an author key and a version signature must both be present');
}
if (pinned && pinned !== entry.authorPublicKey) {
throw new RegistryError("the plugin's author signing key changed since it was installed — re-trust it explicitly to continue");
}
if (!verifyAuthorSignature(bytes, ver.signature, entry.authorPublicKey)) {
throw new RegistryError('author signature verification failed');
}
}
}
function rawFileUrl(repo: string, commitSha: string, file: string): string {
return `https://raw.githubusercontent.com/${repo}/${commitSha}/${file}`;
}
/**
* Tolerant projection of a live manifest for display. Unknown shapes degrade to
* empty lists instead of throwing — a future manifest field must never break
* browsing (strict validation happens against the downloaded artifact instead).
*/
function previewManifest(raw: unknown): ManifestPreview {
const m = (raw && typeof raw === 'object' ? raw : {}) as Record<string, unknown>;
const strings = (v: unknown): string[] =>
Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : [];
const settings = Array.isArray(m.settings)
? m.settings
.filter((s): s is Record<string, unknown> => !!s && typeof s === 'object')
.map((s) => ({
key: typeof s.key === 'string' ? s.key : '',
label: typeof s.label === 'string' ? s.label : typeof s.key === 'string' ? s.key : '',
inputType: typeof s.input_type === 'string' ? s.input_type : 'text',
scope: s.scope === 'user' ? 'user' : 'instance',
required: s.required === true,
}))
.filter((s) => s.key)
: [];
return {
permissions: strings(m.permissions),
egress: strings(m.egress),
settings,
license: typeof m.license === 'string' ? m.license : null,
icon: typeof m.icon === 'string' ? m.icon : null,
};
}
/** The extracted plugin root: staging itself, or its single wrapper subdir (codeload archives wrap in {repo}-{sha}/). */
function locateManifestDir(staging: string): string | null {
if (fs.existsSync(path.join(staging, 'trek-plugin.json'))) return staging;
const subs = fs.existsSync(staging)
? fs.readdirSync(staging, { withFileTypes: true }).filter((d) => d.isDirectory())
: [];
for (const s of subs) {
const p = path.join(staging, s.name);
if (fs.existsSync(path.join(p, 'trek-plugin.json'))) return p;
}
return null;
}
@@ -0,0 +1,130 @@
/**
* Pure egress-policy helpers for the plugin child's network guard (#plugins, L1
* hardening). Kept dependency-free so the isolated child can import them without
* pulling in any privileged server module, and so they are unit-testable on
* their own (the guard that uses them lives in plugin-host-entry, which is
* excluded from coverage as a subprocess entry).
*/
/**
* Block outbound connections to loopback / private / link-local / ULA / carrier-
* grade-NAT / cloud-metadata / multicast / reserved destinations. This is the
* SSRF backstop: even a declared host that (re)resolves to one of these is
* refused, so a plugin can't pivot to trek.db's host, the 169.254.169.254
* metadata IP, the local docker network, or other internal services.
*/
export function isBlockedIp(ip: string): boolean {
const v4 = ip.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
if (v4) {
const a = Number(v4[1]);
const b = Number(v4[2]);
return (
a === 0 ||
a === 10 ||
a === 127 ||
(a === 172 && b >= 16 && b <= 31) ||
(a === 192 && b === 168) ||
(a === 169 && b === 254) || // link-local, incl. 169.254.169.254 metadata
(a === 100 && b >= 64 && b <= 127) || // CGNAT 100.64/10
a >= 224 // multicast + reserved
);
}
// IPv6: expand to 8 hextets so EVERY spelling is checked (compressed `::`,
// hex IPv4-mapped `::ffff:a9fe:a9fe`, dotted `::ffff:169.254.169.254`, `0::1`).
const g = expandV6(ip.replace(/^\[/, '').replace(/\]$/, ''));
if (g) {
if (g.every((x) => x === 0)) return true; // :: (unspecified)
// IPv4-mapped (::ffff:x) and IPv4-compatible (::x) → check the embedded IPv4.
if (g.slice(0, 5).every((x) => x === 0) && (g[5] === 0xffff || g[5] === 0)) {
return isBlockedIp(`${g[6] >> 8}.${g[6] & 0xff}.${g[7] >> 8}.${g[7] & 0xff}`);
}
if ((g[0] & 0xffc0) === 0xfe80) return true; // fe80::/10 link-local
if ((g[0] & 0xfe00) === 0xfc00) return true; // fc00::/7 ULA
}
return false;
}
/** Expand an IPv6 literal into its 8 numeric hextets, or null if not a valid IPv6. */
function expandV6(ip: string): number[] | null {
let h = ip.toLowerCase().replace(/%.*$/, '');
if (!h.includes(':')) return null;
const dotted = h.match(/^(.*:)(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/);
if (dotted) {
const v4 = dotted[2].split('.').map(Number);
if (v4.some((n) => n > 255)) return null;
h = dotted[1] + ((v4[0] << 8) | v4[1]).toString(16) + ':' + ((v4[2] << 8) | v4[3]).toString(16);
}
const halves = h.split('::');
if (halves.length > 2) return null;
const head = halves[0] ? halves[0].split(':') : [];
const tail = halves.length === 2 && halves[1] ? halves[1].split(':') : [];
const groups =
halves.length === 2 ? [...head, ...Array(8 - head.length - tail.length).fill('0'), ...tail] : head;
if (groups.length !== 8) return null;
const nums = groups.map((x) => (x === '' ? NaN : parseInt(x, 16)));
return nums.some((n) => !Number.isInteger(n) || n < 0 || n > 0xffff) ? null : nums;
}
/** Build a declared-egress host matcher (exact host or `*.suffix` wildcard). */
export function makeHostAllow(egress: string[]): (host: string) => boolean {
const patterns = egress
.map((h) => h.trim().toLowerCase().replace(/\.$/, '')) // drop a trailing dot (FQDN trick)
.filter((p) => p && p !== '*')
// A wildcard must have a real multi-label suffix — reject the degenerate
// `*.` (matched any trailing-dot host = allow-all) and whole-TLD `*.com`.
.filter((p) => !p.startsWith('*.') || p.slice(2).includes('.'));
return (host: string) => {
const h = host.toLowerCase().replace(/\.$/, '');
return patterns.some((p) => (p.startsWith('*.') ? h === p.slice(2) || h.endsWith(p.slice(1)) : h === p));
};
}
export interface ConnectTarget {
kind: 'local' | 'literal-ip' | 'hostname';
host: string;
}
/**
* Destination host of a `dgram.Socket.send(msg[, offset, length], port[, address][, cb])`
* call, or null when no explicit address is given (Node then uses the socket's
* connected remote or the localhost default — the connect() wrapper already
* vetted that, and a localhost default is not an exfil vector). Only an explicit
* address string is a target we must allowlist. Mirrors both send() overloads:
* the (offset, length) form pushes port/address two slots right.
*/
export function dgramSendTarget(args: unknown[]): string | null {
const offsetForm = typeof args[1] === 'number' && typeof args[2] === 'number';
const address = args[offsetForm ? 4 : 2];
return typeof address === 'string' ? address : null;
}
/**
* Destination host of a `dgram.Socket.connect(port[, address][, cb])` call, or
* null when no address is given (localhost default — not an exfil vector).
*/
export function dgramConnectTarget(args: unknown[]): string | null {
return typeof args[1] === 'string' ? (args[1] as string) : null;
}
/**
* Classify a `net.Socket.connect(...)` argument list into what we must check:
* a unix-socket/pipe (local, allowed), a literal IP (checked synchronously), or
* a hostname (allowlist + a DNS-resolving guard). Mirrors Node's connect
* overloads: connect(options[,cb]) | connect(port[,host][,cb]) | connect(path[,cb]).
*/
export function classifyConnect(args: unknown[], isIP: (s: string) => boolean): ConnectTarget {
const first = args[0];
if (first && typeof first === 'object') {
const o = first as { host?: string; path?: string };
if (o.path) return { kind: 'local', host: o.path };
const host = o.host ?? 'localhost';
return { kind: isIP(host) ? 'literal-ip' : 'hostname', host };
}
if (typeof first === 'string' && !/^\d+$/.test(first)) {
// a bare string that isn't a port number is an IPC path
return { kind: 'local', host: first };
}
// connect(port[, host][, cb])
const host = typeof args[1] === 'string' ? (args[1] as string) : 'localhost';
return { kind: isIP(host) ? 'literal-ip' : 'hostname', host };
}
@@ -0,0 +1,388 @@
/**
* The isolated plugin child bootstrap (#plugins, M1).
*
* Runs as a forked node process (`dist/nest/plugins/runtime/plugin-host-entry.js`)
* with a scrubbed env — NO JWT_SECRET, NO db path, NO inherited process.env. It
* loads the plugin's own code and turns every ctx call into an RPC message to
* the parent, which is the only side holding real capabilities.
*
* MUST NOT import any privileged server module (db, config, websocket). Its only
* imports are the pure protocol + SDK.
*/
import path from 'node:path';
import net from 'node:net';
import dns from 'node:dns';
import dgram from 'node:dgram';
import { createRequire } from 'node:module';
import { createPluginContext, definePlugin, PLUGIN_API_VERSION, type ChildTransport, type PluginContext, type PluginDefinition } from './plugin-sdk';
import { isBlockedIp, makeHostAllow, classifyConnect, dgramSendTarget, dgramConnectTarget } from './egress-policy';
import type { Envelope, RpcError } from '../protocol/envelope';
const pluginId = process.argv[2] || process.env.TREK_PLUGIN_ID || 'unknown';
const pluginDir = process.argv[3] || '';
let pluginConfig: Record<string, unknown> = {};
const pending = new Map<string, { resolve: (v: unknown) => void; reject: (e: Error) => void }>();
let seq = 0;
function send(msg: Envelope): void {
process.send?.(msg);
}
const transport: ChildTransport = {
rpc(method, params) {
return new Promise((resolve, reject) => {
const id = `${++seq}`;
pending.set(id, { resolve, reject });
send({ k: 'req', id, method, params });
});
},
emit(topic, data) {
send({ k: 'evt', topic, data });
},
};
let def: PluginDefinition | null = null;
let ctx: PluginContext | null = null;
/**
* Make `require('trek-plugin-sdk')` resolve inside the child WITHOUT the plugin
* vendoring the package: the shim below is served from memory for every require
* of that name, anywhere in the plugin's module graph. This is what lets `pack`
* strip node_modules and still keep the scaffold's
* `const { definePlugin } = require('trek-plugin-sdk')` working in production.
* Subpaths (`trek-plugin-sdk/testing`) are build/test-time tools and fail with a
* pointed message instead of a confusing MODULE_NOT_FOUND.
*/
function installSdkInjection(requirePlugin: NodeJS.Require): void {
const nodeModule = requirePlugin('node:module') as {
_load: (request: string, parent: unknown, isMain: boolean) => unknown;
};
const realLoad = nodeModule._load;
const shim = Object.freeze({ definePlugin, PLUGIN_API_VERSION });
nodeModule._load = function (request: string, parent: unknown, isMain: boolean): unknown {
if (request === 'trek-plugin-sdk') return shim;
if (request.startsWith('trek-plugin-sdk/')) {
throw new Error(`${request} is a build/test-time module — only 'trek-plugin-sdk' itself is injected inside TREK`);
}
return realLoad.call(this, request, parent, isMain);
};
}
async function boot(config: Record<string, unknown>): Promise<void> {
try {
// createRequire works whether this bootstrap runs as CJS (prod dist) or ESM
// (tsx in tests), so `require` being undefined in ESM never bites us.
const entry = path.join(pluginDir, 'server', 'index.js');
const requirePlugin = createRequire(entry);
installSdkInjection(requirePlugin);
const mod = requirePlugin(entry);
def = mod && mod.default ? (mod.default as PluginDefinition) : (mod as PluginDefinition);
ctx = createPluginContext(pluginId, config, transport);
if (typeof def.onLoad === 'function') await def.onLoad(ctx);
// Report the declared routes (with their index = routeId) and job ids so the
// host can proxy HTTP and schedule jobs without re-parsing the manifest.
const routes = (def.routes ?? []).map((r, i) => ({ i, method: r.method, path: r.path, auth: r.auth !== false }));
const jobs = (def.jobs ?? []).map((j) => j.id);
send({ k: 'evt', topic: 'loaded', data: { routes, jobs } });
// An immediate first heartbeat confirms liveness without waiting a full interval.
send({ k: 'evt', topic: 'heartbeat', data: { rss: process.memoryUsage().rss } });
} catch (e) {
send({ k: 'evt', topic: 'load-error', data: { message: errMsg(e), stack: errStack(e) } });
}
}
/** Handle a host→child request: run a declared route or job with the plugin ctx. */
async function handleInvoke(req: { id: string; method: string; params: Record<string, unknown> }): Promise<void> {
const respond = (ok: boolean, payload: unknown) =>
send(
ok
? { k: 'res', id: req.id, ok: true, result: payload }
: { k: 'res', id: req.id, ok: false, error: { code: 'PLUGIN_ERROR', message: String(payload) } },
);
try {
if (!def || !ctx) throw new Error('plugin not loaded');
// A per-invocation ctx tagged with this invoke's id, so the host binds trip
// reads to the invocation's authenticated user (routes) / refuses them (jobs).
const invCtx = createPluginContext(pluginId, pluginConfig, transport, req.id);
if (req.method === 'invoke.route') {
const routeId = req.params.routeId as number;
const route = def.routes?.[routeId];
if (!route) throw new Error(`no route ${routeId}`);
const pluginReq = req.params.req as Parameters<NonNullable<typeof route.handler>>[0];
const result = await route.handler(pluginReq, invCtx);
respond(true, result);
} else if (req.method === 'invoke.job') {
const jobId = req.params.jobId as string;
const job = def.jobs?.find((j) => j.id === jobId);
if (!job) throw new Error(`no job ${jobId}`);
await job.handler(invCtx);
respond(true, { ok: true });
} else {
respond(false, `unknown invoke ${req.method}`);
}
} catch (e) {
respond(false, errMsg(e));
}
}
async function shutdown(): Promise<void> {
try {
if (def && typeof def.onUnload === 'function' && ctx) await def.onUnload(ctx);
} catch {
/* best effort */
}
clearInterval(heartbeat);
process.exit(0);
}
process.on('message', (raw: unknown) => {
const msg = raw as Envelope;
if (!msg || typeof msg !== 'object') return;
if (msg.k === 'req') {
// A host→child invoke (route / job).
void handleInvoke({ id: msg.id, method: msg.method, params: (msg.params ?? {}) as Record<string, unknown> });
return;
}
if (msg.k === 'res') {
const p = pending.get(msg.id);
if (!p) return;
pending.delete(msg.id);
if (msg.ok) {
p.resolve(msg.result);
} else {
const em = (msg as RpcError).error;
p.reject(new Error(`${em.code}: ${em.message}`));
}
return;
}
if (msg.k === 'evt') {
if (msg.topic === 'init') {
const d = msg.data as { config?: Record<string, unknown>; egress?: string[] };
pluginConfig = d.config ?? {};
installEgressGuard(d.egress ?? []);
void boot(pluginConfig);
} else if (msg.topic === 'shutdown') void shutdown();
}
});
/**
* Restrict the plugin's outbound network to its declared egress hosts. With no
* declared egress, ALL outbound is blocked. Wildcards like `*.host` match any
* subdomain.
*
* Four channels are covered, so a plugin can't sidestep one with another:
* 1. `globalThis.fetch` is wrapped (early hostname reject).
* 2. `net.Socket.prototype.connect` is wrapped — the single TCP choke point that
* node:http / node:https / node:net / node:tls AND undici/fetch all funnel
* through. Here we additionally RESOLVE the destination and refuse any
* private/loopback/link-local/metadata/CGNAT/ULA address (SSRF + DNS-rebinding
* backstop), pinning the resolved IP into the connect so the name can't flip
* to an internal address between check and connect.
* 3. `dgram.Socket` send/connect (UDP) — TCP-only wrappers would leave UDP open
* as a data-exfiltration channel; the explicit destination is allowlisted +
* private-IP-checked like a TCP connect.
* 4. The `dns` resolver family (module fns, `dns.promises`, `Resolver.prototype`)
* — a plugin could otherwise tunnel data out inside DNS queries to a name it
* never declared (dns.resolveTxt('secret.attacker.com')); every forward lookup
* is rejected unless the queried name is a declared host.
*
* Under the OS permission model the child also cannot spawn a fresh process or
* load a native addon to escape these wrappers. A kernel/network-namespace
* guarantee still belongs to the container runtime. Set
* TREK_PLUGIN_ALLOW_PRIVATE_EGRESS=on to permit private/internal targets (e.g. a
* self-hoster's sibling service) — default is the secure, block-private policy.
*/
function installEgressGuard(egress: string[]): void {
const allowed = makeHostAllow(egress);
const blockPrivate = (process.env.TREK_PLUGIN_ALLOW_PRIVATE_EGRESS ?? '').toLowerCase() !== 'on';
// The wrappers below are the ONLY egress choke point (the OS --permission model
// does not restrict the network). Deny the low-level escape hatch a plugin could
// use to build a raw socket handle BELOW those wrappers. node:net/dns/dgram/http
// are already imported above, so they keep their captured bindings; only fresh
// access via process.binding is cut off.
for (const name of ['binding', '_linkedBinding'] as const) {
try {
Object.defineProperty(process, name, {
value: () => { throw new Error(`egress: process.${name} is disabled for plugins`); },
writable: false, configurable: false,
});
} catch { /* already locked / non-configurable */ }
}
const realFetch = globalThis.fetch;
if (typeof realFetch === 'function') {
globalThis.fetch = ((input: unknown, init?: unknown) => {
const url = typeof input === 'string' ? input : (input as { url?: string })?.url ?? String(input);
let host: string;
try {
host = new URL(url).hostname.replace(/^\[/, '').replace(/\]$/, '');
} catch {
return Promise.reject(new Error('egress: invalid url'));
}
if (!allowed(host)) return Promise.reject(new Error(`egress: ${host} is not in the plugin's declared hosts`));
return (realFetch as (i: unknown, n: unknown) => Promise<unknown>)(input, init);
}) as typeof fetch;
}
// Capture the real resolvers before we patch the dns module below, so the
// connect guard keeps resolving even though direct dns.* calls get gated.
const realLookup = dns.lookup.bind(dns);
// A DNS lookup that refuses to resolve a name to a blocked address; injected
// into every hostname connect so the socket only ever reaches a vetted IP.
const guardedLookup = (
hostname: string,
options: unknown,
cb: (err: Error | null, address?: unknown, family?: number) => void,
): void => {
const opts = typeof options === 'function' ? {} : options;
if (typeof options === 'function') cb = options as typeof cb;
realLookup(hostname, opts as dns.LookupOptions, (err, address, family) => {
if (err) return cb(err, address as unknown, family);
const list = Array.isArray(address) ? address : [{ address: address as string }];
for (const a of list) {
if (blockPrivate && isBlockedIp((a as { address: string }).address)) {
return cb(new Error(`egress: ${hostname} resolves to a blocked address (${(a as { address: string }).address})`));
}
}
cb(null, address as unknown, family);
});
};
const proto = net.Socket.prototype as unknown as { connect: (...a: unknown[]) => unknown };
const realConnect = proto.connect;
proto.connect = function (this: unknown, ...args: unknown[]): unknown {
const target = classifyConnect(args, (s) => net.isIP(s) !== 0);
if (target.kind === 'local') return realConnect.apply(this, args); // unix socket / pipe
if (!allowed(target.host)) {
throw new Error(`egress: ${target.host} is not in the plugin's declared hosts`);
}
if (target.kind === 'literal-ip') {
if (blockPrivate && isBlockedIp(target.host)) {
throw new Error(`egress: ${target.host} is a blocked address`);
}
return realConnect.apply(this, args);
}
// Hostname: inject the resolving guard. Preserve an existing lookup by
// wrapping the args' options object.
const first = args[0];
const options = first && typeof first === 'object' ? { ...(first as object) } : { host: target.host, port: args[0] };
(options as { lookup?: unknown }).lookup = guardedLookup;
const rest = first && typeof first === 'object' ? args.slice(1) : args.slice(typeof args[1] === 'string' ? 2 : 1);
return realConnect.call(this, options, ...rest);
};
// Refuse an outbound UDP target the plugin never declared, or a private one.
// A null target means "no explicit address" (connected remote / localhost
// default) — the connect wrapper below already vetted connected sockets.
const guardDatagram = (host: string | null): void => {
if (host === null) return;
if (!allowed(host)) throw new Error(`egress: ${host} is not in the plugin's declared hosts`);
if (blockPrivate && net.isIP(host) !== 0 && isBlockedIp(host)) {
throw new Error(`egress: ${host} is a blocked address`);
}
};
const dgramProto = dgram.Socket.prototype as unknown as {
send: (...a: unknown[]) => unknown;
connect: (...a: unknown[]) => unknown;
};
const realSend = dgramProto.send;
dgramProto.send = function (this: unknown, ...args: unknown[]): unknown {
guardDatagram(dgramSendTarget(args));
return realSend.apply(this, args);
};
const realDgramConnect = dgramProto.connect;
dgramProto.connect = function (this: unknown, ...args: unknown[]): unknown {
guardDatagram(dgramConnectTarget(args));
return realDgramConnect.apply(this, args);
};
// A dgram HOSTNAME target is resolved via the socket's `lookup` before the packet
// is sent; force the IP-vetting guardedLookup so a declared name that resolves to
// a private/metadata address is refused (the TCP path's rebind backstop, for UDP).
const injectLookup = (arg: unknown): { type?: unknown; lookup: unknown } =>
typeof arg === 'string' ? { type: arg, lookup: guardedLookup } : { ...(arg as object), lookup: guardedLookup };
const dgramApi = dgram as unknown as { createSocket: (...a: unknown[]) => unknown; Socket: new (o?: unknown, cb?: unknown) => unknown };
const realCreateSocket = dgramApi.createSocket;
dgramApi.createSocket = function (this: unknown, ...args: unknown[]): unknown {
args[0] = injectLookup(args[0]);
return realCreateSocket.apply(this, args);
};
// Also cover `new dgram.Socket(...)`, which bypasses createSocket entirely.
const RealDgramSocket = dgramApi.Socket;
const GuardedDgramSocket = function (options?: unknown, cb?: unknown): unknown {
return new RealDgramSocket(injectLookup(options), cb);
} as unknown as new (o?: unknown, cb?: unknown) => unknown;
(GuardedDgramSocket as unknown as { prototype: unknown }).prototype = RealDgramSocket.prototype;
// Lock the wrapped choke points so a plugin can't restore the originals.
const lock = (obj: object, key: string, value: unknown) => {
try { Object.defineProperty(obj, key, { value, writable: false, configurable: false }); } catch { /* noop */ }
};
lock(proto, 'connect', proto.connect);
lock(dgramProto, 'send', dgramProto.send);
lock(dgramProto, 'connect', dgramProto.connect);
lock(dgramApi as unknown as object, 'createSocket', dgramApi.createSocket);
lock(dgramApi as unknown as object, 'Socket', GuardedDgramSocket);
// Gate the dns resolver family: a forward lookup for an undeclared name is a
// DNS-tunnel exfiltration channel even when no socket is ever opened. The name
// itself must be a declared host. Covers the callback module fns, the promise
// API, and per-Resolver instances (which share Resolver.prototype).
const DNS_METHODS = [
'lookup', 'resolve', 'resolve4', 'resolve6', 'resolveAny', 'resolveCaa', 'resolveCname',
'resolveMx', 'resolveNaptr', 'resolveNs', 'resolvePtr', 'resolveSoa', 'resolveSrv', 'resolveTxt',
];
const gateDnsMethods = (obj: Record<string, unknown> | undefined): void => {
if (!obj) return;
for (const name of DNS_METHODS) {
const real = obj[name];
if (typeof real !== 'function') continue;
obj[name] = function (this: unknown, hostname: unknown, ...rest: unknown[]): unknown {
if (typeof hostname === 'string' && !allowed(hostname)) {
const err = new Error(`egress: DNS lookup for ${hostname} is not in the plugin's declared hosts`);
const cb = rest.find((a) => typeof a === 'function') as ((e: Error) => void) | undefined;
if (cb) return cb(err); // callback API
return Promise.reject(err); // promise API (dns.promises / Resolver)
}
return (real as (...a: unknown[]) => unknown).call(this, hostname, ...rest);
};
}
};
gateDnsMethods(dns as unknown as Record<string, unknown>);
gateDnsMethods(dns.promises as unknown as Record<string, unknown>);
const resolverProto = (dns as unknown as { Resolver?: { prototype: Record<string, unknown> } }).Resolver?.prototype;
gateDnsMethods(resolverProto);
const promisesResolverProto = (dns.promises as unknown as { Resolver?: { prototype: Record<string, unknown> } })?.Resolver?.prototype;
gateDnsMethods(promisesResolverProto);
}
// Ask the host for the init payload (instance config), then wait for it.
send({ k: 'evt', topic: 'hello', data: {} });
// Liveness — unref so it never keeps the process alive on its own.
const heartbeat = setInterval(() => {
send({ k: 'evt', topic: 'heartbeat', data: { rss: process.memoryUsage().rss } });
}, 5000);
heartbeat.unref?.();
// A plugin that throws asynchronously must not take the host down — it only
// crashes THIS child, which the supervisor detects and restarts/disables.
process.on('uncaughtException', (e) => {
send({ k: 'evt', topic: 'load-error', data: { message: errMsg(e), stack: errStack(e) } });
process.exit(1);
});
process.on('unhandledRejection', (e) => {
send({ k: 'evt', topic: 'load-error', data: { message: errMsg(e), stack: errStack(e) } });
process.exit(1);
});
function errMsg(e: unknown): string {
return e instanceof Error ? e.message : String(e);
}
function errStack(e: unknown): string | undefined {
return e instanceof Error ? e.stack : undefined;
}
@@ -0,0 +1,131 @@
/**
* The plugin-author-facing SDK surface (#plugins, M1) — the minimal in-repo
* version. The published `@trek/plugin-sdk` (M6) will re-export these types; for
* now the runtime ships its own copy so the child has zero external deps.
*
* PURE — no server imports. This runs inside the isolated child. Every ctx
* method is plumbing that turns a call into an RPC message to the host; the
* child holds no db handle, no secrets, no network by default.
*/
/** Mirrors the published package's constant — bumped on any breaking API change. */
export const PLUGIN_API_VERSION = 1 as const;
export interface PluginContext {
readonly id: string;
readonly config: Readonly<Record<string, 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 }>;
};
trips: {
// `asUserId` is accepted for source compatibility but IGNORED by the host —
// trip reads are always membership-checked against the authenticated user of
// the current invocation (the request's `req.user`), which the plugin cannot
// override. Only reachable from a route handler (a user context); a job has
// no user and its trip reads are refused.
getById(tripId: number, asUserId?: number): Promise<unknown>;
getPlaces(tripId: number, asUserId?: number): Promise<unknown[]>;
getReservations(tripId: number, asUserId?: number): Promise<unknown[]>;
};
users: {
getById(id: number): Promise<unknown>;
};
ws: {
broadcastToTrip(tripId: number, event: string, data: Record<string, unknown>): Promise<void>;
broadcastToUser(userId: number, event: string, data: Record<string, unknown>): Promise<void>;
};
log: {
info(msg: string, meta?: Record<string, unknown>): void;
warn(msg: string, meta?: Record<string, unknown>): void;
error(msg: string, meta?: Record<string, unknown>): void;
};
}
export interface PluginRequest {
method: string;
path: string;
query: Record<string, unknown>;
body: unknown;
user: { id: number; username: string; isAdmin: boolean } | null;
}
export interface PluginResponse {
status: number;
headers?: Record<string, string>;
body?: unknown;
}
export interface PluginRoute {
method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
path: string;
auth?: boolean;
handler(req: PluginRequest, ctx: PluginContext): Promise<PluginResponse>;
}
export interface PluginJob {
id: string;
schedule: string;
handler(ctx: PluginContext): Promise<void>;
}
export interface PluginDefinition {
onLoad?(ctx: PluginContext): Promise<void> | void;
onUnload?(ctx: PluginContext): Promise<void> | void;
routes?: PluginRoute[];
jobs?: PluginJob[];
// hooks (photo/calendar) land in M2
}
/** Identity helper: gives authors types + a stable shape. A plain object works too. */
export function definePlugin(def: PluginDefinition): PluginDefinition {
return def;
}
/** Transport the child entry wires to process.send / message correlation. */
export interface ChildTransport {
rpc(method: string, params: Record<string, unknown>): Promise<unknown>;
emit(topic: string, data: unknown): void;
}
/**
* Build the ctx the plugin's handlers receive — every method is an RPC call.
* `invocationId` (the host's reqId for the route/job currently being handled) is
* attached to trip reads as `_inv` so the host can bind the acting user to THIS
* invocation. It is undefined for the load-time ctx (onLoad), where trip reads
* have no user and are refused.
*/
export function createPluginContext(
id: string,
config: Record<string, unknown>,
t: ChildTransport,
invocationId?: string,
): PluginContext {
return {
id,
config: Object.freeze({ ...config }),
db: {
query: (sql, ...args) => t.rpc('db.query', { sql, args }) as Promise<never[]>,
exec: (sql, ...args) => t.rpc('db.exec', { sql, args }) as Promise<{ changes: number }>,
migrate: (mid, sql) => t.rpc('db.migrate', { id: mid, sql }) as Promise<{ applied: boolean }>,
},
trips: {
getById: (tripId) => t.rpc('trips.getById', { tripId, _inv: invocationId }),
getPlaces: (tripId) => t.rpc('trips.getPlaces', { tripId, _inv: invocationId }) as Promise<unknown[]>,
getReservations: (tripId) => t.rpc('trips.getReservations', { tripId, _inv: invocationId }) as Promise<unknown[]>,
},
users: {
getById: (uid) => t.rpc('users.getById', { id: uid }),
},
ws: {
broadcastToTrip: async (tripId, event, data) => {
await t.rpc('ws.broadcastToTrip', { tripId, event, data });
},
broadcastToUser: async (userId, event, data) => {
await t.rpc('ws.broadcastToUser', { userId, event, data });
},
},
log: {
info: (msg, meta) => t.emit('log', { level: 'info', msg, meta }),
warn: (msg, meta) => t.emit('log', { level: 'warn', msg, meta }),
error: (msg, meta) => t.emit('log', { level: 'error', msg, meta }),
},
};
}
@@ -0,0 +1,420 @@
import fs from 'node:fs';
import { randomUUID } from 'node:crypto';
import { fork, type ChildProcess } from 'node:child_process';
import { resolveChildEntry, pluginCodeDir, pluginRealCodeDir, pluginPermissionArgs, ensurePluginModuleType } from '../paths';
import type { Envelope, RpcError, RpcRequest } from '../protocol/envelope';
import type { PluginRpcHost } from '../host/rpc-host';
export interface PluginRouteInfo {
i: number;
method: string;
path: string;
auth: boolean;
}
/**
* Owns the lifecycle of every running plugin child (#plugins, M1): spawn on
* activate, route RPC between the child and its capability host, watch
* heartbeats, and restart-with-backoff / auto-disable on crashes. A child dying
* — segfault, throw, OOM, infinite loop — only ever kills the child; the Nest
* event loop never hiccups. That is what finally makes "a plugin can't crash
* TREK" true.
*/
export type PluginStatus = 'starting' | 'active' | 'error' | 'stopped';
export interface SupervisorHooks {
onStatus?(id: string, status: PluginStatus, error?: string): void;
onLog?(id: string, level: string, msg: string, meta?: unknown): void;
/** Any non-lifecycle event the child emits (e.g. a plugin's own signals). */
onEvent?(id: string, topic: string, data: unknown): void;
}
interface Pending {
resolve: (v: unknown) => void;
reject: (e: Error) => void;
timer: ReturnType<typeof setTimeout>;
}
interface Supervised {
id: string;
granted: ReadonlySet<string>;
config: Record<string, unknown>;
egress: string[];
rpcHost: PluginRpcHost;
child: ChildProcess | null;
status: PluginStatus;
crashes: number[]; // crash timestamps (ms)
lastBeat: number;
lastRss: number; // last reported resident set size (bytes)
routes: PluginRouteInfo[];
jobs: string[];
pending: Map<string, Pending>; // host→child invokes awaiting a response
invocations: Map<string, number | undefined>; // reqId -> acting user of that invoke (undefined = no user, e.g. a job)
activation?: { resolve: () => void; reject: (e: Error) => void };
activationTimer?: ReturnType<typeof setTimeout>; // deadline for the plugin to reach 'active'
}
export interface SupervisorTuning {
heartbeatTimeoutMs?: number;
crashWindowMs?: number;
crashLimit?: number;
backoffCapMs?: number;
killGraceMs?: number;
maxRssBytes?: number;
activationTimeoutMs?: number;
}
const DEFAULTS: Required<SupervisorTuning> = {
heartbeatTimeoutMs: 20_000, // 3–4 missed 5s beats
crashWindowMs: 5 * 60_000,
crashLimit: 5,
backoffCapMs: 30_000,
killGraceMs: 3000,
// A plugin that never reaches 'loaded' (e.g. a synchronous infinite loop in
// onLoad) must not hang the admin's activate() forever nor peg a core unreaped.
activationTimeoutMs: 30_000,
// Hard RSS ceiling — the real memory cap. --max-old-space-size only bounds the
// V8 heap; Buffers/ArrayBuffers/native allocations sail past it, so a plugin
// could OOM the box while staying "under" the heap limit. Overridable via env.
maxRssBytes: (Number(process.env.TREK_PLUGIN_MAX_RSS_MB) || 300) * 1024 * 1024,
};
export class PluginSupervisor {
private running = new Map<string, Supervised>();
private sweep: ReturnType<typeof setInterval> | null = null;
private readonly tuning: Required<SupervisorTuning>;
constructor(
private readonly createRpcHost: (id: string, granted: ReadonlySet<string>) => PluginRpcHost,
private readonly hooks: SupervisorHooks = {},
tuning: SupervisorTuning = {},
) {
this.tuning = { ...DEFAULTS, ...tuning };
}
/** Spawn a plugin and resolve once it reports `loaded` (or reject on load error). */
activate(id: string, granted: ReadonlySet<string>, config: Record<string, unknown> = {}, egress: string[] = []): Promise<void> {
if (this.running.has(id)) return Promise.resolve();
const sup: Supervised = {
id,
granted,
config,
egress,
rpcHost: this.createRpcHost(id, granted),
child: null,
status: 'starting',
crashes: [],
lastBeat: Date.now(),
lastRss: 0,
routes: [],
jobs: [],
pending: new Map(),
invocations: new Map(),
};
this.running.set(id, sup);
this.ensureSweep();
return new Promise<void>((resolve, reject) => {
sup.activation = { resolve, reject };
// Deadline: if the plugin never reports 'loaded' (stuck onLoad), reject the
// activation and kill the child rather than hanging + leaking a busy core.
sup.activationTimer = setTimeout(async () => {
if (sup.status === 'active') return;
this.hooks.onLog?.(sup.id, 'error', 'activation timed out; killing');
this.setStatus(sup, 'error', 'activation timed out');
sup.activation?.reject(new Error('plugin did not finish loading in time'));
sup.activation = undefined;
this.running.delete(sup.id);
// await the kill (SIGTERM grace) before closing the plugin db, so a ctx.*
// RPC from the dying child can't hit an already-disposed handle.
await this.kill(sup);
sup.rpcHost.dispose();
}, this.tuning.activationTimeoutMs);
sup.activationTimer.unref?.();
this.spawn(sup);
});
}
private clearActivationTimer(sup: Supervised): void {
if (sup.activationTimer) {
clearTimeout(sup.activationTimer);
sup.activationTimer = undefined;
}
}
/** Stop a plugin: ask it to unload, then kill. Idempotent. */
async disable(id: string): Promise<void> {
const sup = this.running.get(id);
if (!sup) return;
this.running.delete(id);
this.clearActivationTimer(sup);
this.setStatus(sup, 'stopped');
await this.kill(sup);
sup.rpcHost.dispose();
}
isActive(id: string): boolean {
return this.running.get(id)?.status === 'active';
}
statusOf(id: string): PluginStatus | null {
return this.running.get(id)?.status ?? null;
}
/** The plugin's declared HTTP routes (populated once it reports `loaded`). */
routesOf(id: string): PluginRouteInfo[] {
return this.running.get(id)?.routes ?? [];
}
/**
* Send a host→child request (invoke a route or job) and await its response.
* `actingUserId` binds the authenticated user of this invocation on the HOST
* side: any trip read the child makes while handling it is membership-checked
* against THIS user, never against an id the plugin passes. A job carries no
* user (undefined) and therefore cannot read user-scoped data.
*/
invoke(
id: string,
method: string,
params: Record<string, unknown>,
opts: { timeoutMs?: number; actingUserId?: number } = {},
): Promise<unknown> {
const { timeoutMs = 30_000, actingUserId } = opts;
const sup = this.running.get(id);
if (!sup || sup.status !== 'active' || !sup.child) {
return Promise.reject(new Error(`plugin ${id} is not active`));
}
return new Promise((resolve, reject) => {
const reqId = randomUUID();
const timer = setTimeout(() => {
sup.pending.delete(reqId);
sup.invocations.delete(reqId);
reject(new Error('plugin invoke timed out'));
}, timeoutMs);
timer.unref?.();
sup.pending.set(reqId, { resolve, reject, timer });
// The child echoes this reqId as `_inv` on its trip reads; the host resolves
// the acting user from here, so the plugin cannot name an arbitrary user.
sup.invocations.set(reqId, actingUserId);
sup.child!.send({ k: 'req', id: reqId, method, params: { ...params, _inv: reqId } } satisfies Envelope);
});
}
async shutdownAll(): Promise<void> {
if (this.sweep) clearInterval(this.sweep);
this.sweep = null;
const all = [...this.running.values()];
await Promise.all(all.map((s) => this.kill(s)));
for (const s of all) s.rpcHost.dispose();
this.running.clear();
}
// ── internals ──────────────────────────────────────────────────────────────
private spawn(sup: Supervised): void {
const { entry, execArgv, forkCwd, jsMode } = resolveChildEntry();
// Prod (compiled) children get the OS permission model — a real kernel-level
// fs/child_process/native jail on top of the env scrub and RPC boundary.
// Use the plugin's REAL path + ensure it has a package.json so the sandboxed
// child can resolve its own module type without a broad read grant.
const codeDir = jsMode ? pluginRealCodeDir(sup.id) : pluginCodeDir(sup.id);
if (jsMode) ensurePluginModuleType(codeDir);
const argv = jsMode ? [...execArgv, ...pluginPermissionArgs(sup.id)] : execArgv;
const child = fork(entry, [sup.id, codeDir], {
cwd: forkCwd ?? codeDir,
execArgv: argv,
stdio: ['ignore', 'pipe', 'pipe', 'ipc'],
// Whitelist env — nothing inherited. No JWT_SECRET, no DB creds, no PATH-leaked secrets.
env: {
NODE_ENV: process.env.NODE_ENV ?? 'production',
TZ: process.env.TZ ?? '',
PATH: process.env.PATH ?? '',
TREK_PLUGIN_ID: sup.id,
},
});
sup.child = child;
sup.lastBeat = Date.now();
child.on('message', (raw: unknown) => this.onMessage(sup, raw as Envelope));
child.on('exit', (code, signal) => this.onExit(sup, code, signal));
child.on('error', (e) => this.hooks.onLog?.(sup.id, 'error', `child error: ${e.message}`));
child.stdout?.on('data', (b) => this.hooks.onLog?.(sup.id, 'info', String(b).trimEnd()));
child.stderr?.on('data', (b) => this.hooks.onLog?.(sup.id, 'error', String(b).trimEnd()));
}
private async onMessage(sup: Supervised, msg: Envelope): Promise<void> {
if (!msg || typeof msg !== 'object') return;
if (msg.k === 'req') {
// A ctx.* call from the plugin — dispatch through its capability host. The
// acting user comes from the invocation the child is currently handling
// (its `_inv` reqId → our invocation map), NOT from anything the plugin can
// set in the call params.
const inv = (msg as RpcRequest).params as { _inv?: unknown } | undefined;
const actingUserId = typeof inv?._inv === 'string' ? sup.invocations.get(inv._inv) : undefined;
const res = await sup.rpcHost.dispatch(msg as RpcRequest, actingUserId);
sup.child?.send(res);
return;
}
if (msg.k === 'res') {
// A response to a host→child invoke (route/job).
const p = sup.pending.get(msg.id);
if (!p) return;
sup.pending.delete(msg.id);
sup.invocations.delete(msg.id);
clearTimeout(p.timer);
if (msg.ok) p.resolve(msg.result);
else p.reject(new Error((msg as RpcError).error.message));
return;
}
if (msg.k === 'evt') {
switch (msg.topic) {
case 'hello':
sup.child?.send({ k: 'evt', topic: 'init', data: { config: sup.config, egress: sup.egress } } satisfies Envelope);
break;
case 'heartbeat': {
sup.lastBeat = Date.now();
const rss = (msg.data as { rss?: number })?.rss;
if (typeof rss === 'number') sup.lastRss = rss;
break;
}
case 'loaded': {
sup.lastBeat = Date.now();
const d = msg.data as { routes?: PluginRouteInfo[]; jobs?: string[] };
sup.routes = d.routes ?? [];
sup.jobs = d.jobs ?? [];
this.clearActivationTimer(sup);
this.setStatus(sup, 'active');
sup.activation?.resolve();
sup.activation = undefined;
break;
}
case 'load-error': {
const message = (msg.data as { message?: string })?.message || 'plugin load failed';
this.clearActivationTimer(sup);
this.setStatus(sup, 'error', message);
sup.activation?.reject(new Error(message));
sup.activation = undefined;
await this.kill(sup);
sup.rpcHost.dispose();
break;
}
case 'log': {
const d = msg.data as { level?: string; msg?: string; meta?: unknown };
this.hooks.onLog?.(sup.id, d.level || 'info', d.msg || '', d.meta);
break;
}
default:
this.hooks.onEvent?.(sup.id, msg.topic, msg.data);
}
}
}
private rejectPending(sup: Supervised, reason: string): void {
for (const p of sup.pending.values()) {
clearTimeout(p.timer);
p.reject(new Error(reason));
}
sup.pending.clear();
sup.invocations.clear();
}
private onExit(sup: Supervised, code: number | null, signal: string | null): void {
sup.child = null;
// In-flight host→child invokes can never complete now.
this.rejectPending(sup, 'plugin exited');
// A clean stop we asked for isn't a crash.
if (sup.status === 'stopped' || sup.status === 'error') return;
if (!this.running.has(sup.id)) return;
sup.crashes.push(Date.now());
const recent = sup.crashes.filter((t) => t > Date.now() - this.tuning.crashWindowMs);
if (recent.length >= this.tuning.crashLimit) {
this.clearActivationTimer(sup);
this.setStatus(sup, 'error', `auto-disabled after ${recent.length} crashes`);
sup.activation?.reject(new Error('plugin crashed repeatedly'));
sup.activation = undefined;
sup.rpcHost.dispose();
return;
}
const delay = Math.min(this.tuning.backoffCapMs, 1000 * 2 ** (recent.length - 1));
this.hooks.onLog?.(sup.id, 'warn', `crashed (code=${code} sig=${signal}); restarting in ${delay}ms`);
this.setStatus(sup, 'starting');
const timer = setTimeout(() => {
if (this.running.has(sup.id)) this.spawn(sup);
}, delay);
timer.unref?.();
}
private ensureSweep(): void {
if (this.sweep) return;
this.sweep = setInterval(() => this.reapStale(), 5000);
this.sweep.unref?.();
}
/**
* Kill any active plugin that has stopped sending heartbeats OR blown its RSS
* ceiling (drives the crash/backoff path, so a repeat offender auto-disables).
*/
reapStale(now = Date.now()): void {
for (const sup of this.running.values()) {
if (sup.status !== 'active') continue;
const rss = this.childRss(sup);
if (now - sup.lastBeat > this.tuning.heartbeatTimeoutMs) {
this.hooks.onLog?.(sup.id, 'warn', 'missed heartbeats; killing');
sup.child?.kill('SIGKILL');
} else if (rss > this.tuning.maxRssBytes) {
this.hooks.onLog?.(
sup.id,
'warn',
`exceeded memory ceiling (${Math.round(rss / 1048576)}MB > ${Math.round(this.tuning.maxRssBytes / 1048576)}MB); killing`,
);
sup.child?.kill('SIGKILL');
}
}
}
/**
* Resident memory of the child, measured HOST-side from the OS — never trusting
* the child's self-reported heartbeat rss (a malicious plugin can spoof it).
* On Linux (prod runs in a Linux container) this reads /proc/<pid>/statm; where
* that isn't available (dev on win/mac) it falls back to the reported value.
*/
private childRss(sup: Supervised): number {
const pid = sup.child?.pid;
if (pid) {
try {
// VmRSS is reported in kB and is page-size-independent (statm pages would
// undercount on 16K/64K-page kernels, loosening the cap).
const m = fs.readFileSync(`/proc/${pid}/status`, 'utf8').match(/^VmRSS:\s+(\d+)\s+kB/m);
if (m) return Number(m[1]) * 1024;
} catch {
/* not Linux / process gone — fall back */
}
}
return sup.lastRss;
}
private async kill(sup: Supervised): Promise<void> {
const child = sup.child;
if (!child) return;
sup.child = null;
child.send?.({ k: 'evt', topic: 'shutdown', data: {} } satisfies Envelope);
await new Promise<void>((resolve) => {
const t = setTimeout(() => {
child.kill('SIGKILL');
resolve();
}, this.tuning.killGraceMs);
t.unref?.();
child.once('exit', () => {
clearTimeout(t);
resolve();
});
});
}
private setStatus(sup: Supervised, status: PluginStatus, error?: string): void {
sup.status = status;
this.hooks.onStatus?.(sup.id, status, error);
}
}
@@ -0,0 +1,67 @@
import { Controller, Get, HttpException, Query, Req, UseGuards } from '@nestjs/common';
import type { Request } from 'express';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { RateLimitService } from '../auth/rate-limit.service';
import * as transit from '../../services/transitService';
const RL_WINDOW = 15 * 60 * 1000;
/**
* /api/transit — public transit routing (#1065) proxied through Transitous
* (or a self-hosted MOTIS via TRANSIT_API_URL). JWT-guarded and rate-limited:
* the Transitous usage policy asks integrators to keep expensive routing
* traffic reasonable, so planning gets a tighter bucket than geocoding.
*/
@Controller('api/transit')
@UseGuards(JwtAuthGuard)
export class TransitController {
constructor(private readonly rl: RateLimitService) {}
private limit(bucket: string, req: Request, max: number): void {
if (!this.rl.check(bucket, req.ip || 'unknown', max, RL_WINDOW, Date.now())) {
throw new HttpException({ error: 'Too many requests. Please try again later.' }, 429);
}
}
private rethrow(err: unknown): never {
const status = (err as { status?: number }).status || 502;
const message = err instanceof Error ? err.message : 'Transit provider error';
throw new HttpException({ error: message }, status);
}
@Get('geocode')
async geocode(
@Query('q') q: string | undefined,
@Query('lang') lang: string | undefined,
@Query('near') near: string | undefined,
@Req() req: Request,
) {
this.limit('transit_geocode', req, 300);
try {
return await transit.geocode(q || '', lang, near);
} catch (err) { this.rethrow(err); }
}
@Get('plan')
async plan(
@Query('from') from: string | undefined,
@Query('to') to: string | undefined,
@Query('time') time: string | undefined,
@Query('arriveBy') arriveBy: string | undefined,
@Query('modes') modes: string | undefined,
@Query('maxTransfers') maxTransfers: string | undefined,
@Req() req: Request,
) {
this.limit('transit_plan', req, 60);
try {
return await transit.plan({
from: from || '',
to: to || '',
time,
arriveBy: arriveBy === 'true' || arriveBy === '1',
modes,
maxTransfers: maxTransfers !== undefined && maxTransfers !== '' ? Number(maxTransfers) : undefined,
});
} catch (err) { this.rethrow(err); }
}
}
@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { TransitController } from './transit.controller';
import { RateLimitService } from '../auth/rate-limit.service';
@Module({
controllers: [TransitController],
providers: [RateLimitService],
})
export class TransitModule {}
@@ -0,0 +1,100 @@
import { Body, Controller, Delete, Get, HttpCode, HttpException, Param, Post, Req, UseGuards } from '@nestjs/common';
import type { Request } from 'express';
import type { User } from '../../types';
import { TripInviteService } from './trip-invite.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
import { RateLimitService } from '../auth/rate-limit.service';
import { writeAudit, getClientIp } from '../../services/auditLog';
const RL_WINDOW = 15 * 60 * 1000;
/**
* /api/trips/:tripId/invite-link — manage a trip's invite link (#1143).
*
* Mirrors the public share link: trip access (404) + the 'share_manage'
* permission (403). Unlike the share link this one is not public — see
* TripInviteController for the login-required join.
*/
@Controller('api/trips/:tripId/invite-link')
@UseGuards(JwtAuthGuard)
export class TripInviteLinkController {
constructor(private readonly invites: TripInviteService) {}
private requireManage(tripId: string, user: User) {
const trip = this.invites.verifyTripAccess(tripId, user.id);
if (!trip) throw new HttpException({ error: 'Trip not found' }, 404);
if (!this.invites.canManage(trip, user)) throw new HttpException({ error: 'No permission' }, 403);
}
@Get()
get(@CurrentUser() user: User, @Param('tripId') tripId: string) {
// The token grants trip membership, so reading it needs the same
// share_manage permission as creating/rotating it — not just trip access.
this.requireManage(tripId, user);
const info = this.invites.get(tripId);
return info ? info : { token: null };
}
@Post()
create(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@Body() body: { expires_in_days?: number | string | null },
@Req() req: Request,
) {
this.requireManage(tripId, user);
const days = body?.expires_in_days != null && String(body.expires_in_days).trim() !== ''
? parseInt(String(body.expires_in_days))
: null;
const info = this.invites.createOrRotate(tripId, user.id, Number.isFinite(days as number) ? days : null);
writeAudit({ userId: user.id, action: 'trip.invite_link_create', resource: tripId, ip: getClientIp(req), details: { expires_in_days: days } });
return info;
}
@Delete()
remove(@CurrentUser() user: User, @Param('tripId') tripId: string, @Req() req: Request) {
this.requireManage(tripId, user);
this.invites.remove(tripId);
writeAudit({ userId: user.id, action: 'trip.invite_link_delete', resource: tripId, ip: getClientIp(req) });
return { success: true };
}
}
/**
* /api/trip-invites/:token — resolve + accept a trip invite as an existing,
* logged-in user. JWT-guarded: an anonymous visitor is redirected to /login by
* the client (never registration). Rate-limited to blunt any token probing even
* though the tokens are 192-bit and unguessable. The join is idempotent and
* owner-safe (see joinTripAsMember).
*/
@Controller('api/trip-invites')
@UseGuards(JwtAuthGuard)
export class TripInviteController {
constructor(private readonly invites: TripInviteService, private readonly rl: RateLimitService) {}
private limit(req: Request, max: number): void {
if (!this.rl.check('trip_invite', req.ip || 'unknown', max, RL_WINDOW, Date.now())) {
throw new HttpException({ error: 'Too many attempts. Please try again later.' }, 429);
}
}
@Get(':token')
preview(@Param('token') token: string, @Req() req: Request) {
this.limit(req, 30);
const resolved = this.invites.resolve(token);
if (!resolved) throw new HttpException({ error: 'Invalid or expired invite link' }, 404);
return { trip_id: resolved.trip_id, title: resolved.title };
}
@Post(':token/accept')
@HttpCode(200)
accept(@CurrentUser() user: User, @Param('token') token: string, @Req() req: Request) {
this.limit(req, 20);
const resolved = this.invites.resolve(token);
if (!resolved) throw new HttpException({ error: 'Invalid or expired invite link' }, 404);
const result = this.invites.join(resolved.trip_id, user.id);
writeAudit({ userId: user.id, action: 'trip.invite_link_join', resource: String(resolved.trip_id), ip: getClientIp(req), details: { joined: result.joined } });
return { trip_id: resolved.trip_id, joined: result.joined };
}
}
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { TripInviteLinkController, TripInviteController } from './trip-invite.controller';
import { TripInviteService } from './trip-invite.service';
import { RateLimitService } from '../auth/rate-limit.service';
@Module({
controllers: [TripInviteLinkController, TripInviteController],
providers: [TripInviteService, RateLimitService],
})
export class TripInviteModule {}
@@ -0,0 +1,35 @@
import { Injectable } from '@nestjs/common';
import { canAccessTrip } from '../../db/database';
import { checkPermission } from '../../services/permissions';
import { joinTripAsMember } from '../../services/tripMembership';
import type { User } from '../../types';
import * as svc from '../../services/tripInviteService';
type Trip = NonNullable<ReturnType<typeof canAccessTrip>>;
/**
* Thin Nest wrapper around the trip invite-link service. Trip access and the
* 'share_manage' permission mirror the public share link exactly (the invite
* link lives next to it in the Share area).
*/
@Injectable()
export class TripInviteService {
verifyTripAccess(tripId: string, userId: number) {
return canAccessTrip(tripId, userId);
}
canManage(trip: Trip, user: User): boolean {
return checkPermission('share_manage', user.role, trip.user_id, user.id, trip.user_id !== user.id);
}
get(tripId: string) { return svc.getTripInviteLink(tripId); }
createOrRotate(tripId: string, userId: number, expiresInDays?: number | null) {
return svc.createOrRotateTripInviteLink(tripId, userId, expiresInDays ?? null);
}
remove(tripId: string) { return svc.deleteTripInviteLink(tripId); }
resolve(token: string) { return svc.resolveTripInvite(token); }
/** Join the resolved trip as the current (authenticated, non-guest) user.
* invited_by is null — they joined via a link, not a personal invite. */
join(tripId: number, userId: number) { return joinTripAsMember(tripId, userId, null); }
}
+123 -1
View File
@@ -29,6 +29,7 @@ import { CurrentUser } from '../auth/current-user.decorator';
import { writeAudit, getClientIp, logInfo } from '../../services/auditLog';
import { isDemoEmail } from '../../services/demo';
import { NotFoundError, ValidationError } from '../../services/tripService';
import { saveUnsplashCover, isUnsplashCoverUrl } from '../../services/unsplashService';
const MAX_COVER_SIZE = 20 * 1024 * 1024;
const coversDir = path.join(__dirname, '../../../uploads/covers');
@@ -71,6 +72,21 @@ export class TripsController {
return { trips: this.trips.list(user.id, archived === '1' ? 1 : 0) };
}
@Get('cover-images/search')
async coverImages(@Query('query') query?: string) {
try {
const result = await this.trips.searchCoverImages(query || '');
if ('error' in result) {
throw new HttpException({ error: result.error }, result.status);
}
return { photos: result.photos };
} catch (err: unknown) {
if (err instanceof HttpException) throw err;
console.error('Unsplash cover image error:', err);
throw new HttpException({ error: 'Error searching for cover images' }, 500);
}
}
@Post()
@HttpCode(201)
create(@CurrentUser() user: User, @Body() body: Record<string, unknown>, @Req() req: Request) {
@@ -105,7 +121,7 @@ export class TripsController {
}
@Put(':id')
update(@CurrentUser() user: User, @Param('id') id: string, @Body() body: Record<string, unknown>, @Req() req: Request, @Headers('x-socket-id') socketId?: string) {
async update(@CurrentUser() user: User, @Param('id') id: string, @Body() body: Record<string, unknown>, @Req() req: Request, @Headers('x-socket-id') socketId?: string) {
const access = this.trips.canAccessTrip(id, user.id);
if (!access) {
throw new HttpException({ error: 'Trip not found' }, 404);
@@ -122,8 +138,25 @@ export class TripsController {
if (editFields.some((f) => body[f] !== undefined) && !this.trips.can('trip_edit', user.role, ownerId, user.id, isMember)) {
throw new HttpException({ error: 'No permission to edit this trip' }, 403);
}
// A chosen Unsplash cover arrives as an images.unsplash.com hot-link; download
// it into uploads/covers so the cover survives offline + CDN link-rot (#1277).
if (isUnsplashCoverUrl(body.cover_image)) {
try {
const filename = await saveUnsplashCover(body.cover_image, coversDir);
body.cover_image = `/uploads/covers/${filename}`;
} catch (e) {
console.error('Unsplash cover download failed:', e);
throw new HttpException({ error: 'Could not save the selected cover image' }, 502);
}
}
const oldCover = body.cover_image !== undefined
? (this.trips.getRaw(id) as { cover_image: string | null } | undefined)?.cover_image
: undefined;
try {
const result = this.trips.update(id, user.id, body, user.role);
if (body.cover_image !== undefined && body.cover_image !== oldCover) {
this.trips.deleteOldCover(oldCover);
}
if (Object.keys(result.changes).length > 0) {
writeAudit({ userId: user.id, action: 'trip.update', ip: getClientIp(req), details: { tripId: Number(id), trip: result.newTitle, ...(result.ownerEmail ? { owner: result.ownerEmail } : {}), ...result.changes } });
if (result.isAdminEdit && result.ownerEmail) logInfo(`Admin ${user.email} edited trip "${result.newTitle}" owned by ${result.ownerEmail}`);
@@ -246,6 +279,95 @@ export class TripsController {
return { success: true };
}
@Post(':id/transfer')
transferOwnership(
@CurrentUser() user: User,
@Param('id') id: string,
@Body('newOwnerId') newOwnerId: unknown,
@Req() req: Request,
@Headers('x-socket-id') socketId?: string,
) {
const access = this.trips.canAccessTrip(id, user.id);
if (!access) {
throw new HttpException({ error: 'Trip not found' }, 404);
}
// Owner-only: handing over a trip is reserved for its actual owner, not just
// anyone who can manage members.
if (access.user_id !== user.id) {
throw new HttpException({ error: 'Only the owner can transfer ownership' }, 403);
}
if (typeof newOwnerId !== 'number') {
throw new HttpException({ error: 'newOwnerId is required' }, 400);
}
try {
const result = this.trips.transferOwnership(id, newOwnerId, user.id);
writeAudit({ userId: user.id, action: 'trip.transfer_ownership', ip: getClientIp(req), details: { tripId: Number(id), trip: result.tripTitle, from: result.fromEmail, to: result.toEmail } });
// Nudge everyone viewing the trip to re-read it so the new ownership and the
// recomputed permissions take effect live.
const updatedTrip = this.trips.get(id, user.id);
this.trips.broadcast(id, 'trip:updated', { trip: updatedTrip }, socketId);
return { success: true };
} catch (e: unknown) {
if (e instanceof NotFoundError) throw new HttpException({ error: e.message }, 404);
if (e instanceof ValidationError) throw new HttpException({ error: e.message }, 400);
throw e;
}
}
/** Loads the trip or throws 404, then asserts the caller is its owner (guest CRUD, #1362). */
private requireOwner(id: string, user: User): void {
const access = this.trips.canAccessTrip(id, user.id);
if (!access) {
throw new HttpException({ error: 'Trip not found' }, 404);
}
if (access.user_id !== user.id) {
throw new HttpException({ error: 'Only the owner can manage guests' }, 403);
}
}
@Post(':id/guests')
@HttpCode(201)
createGuest(@CurrentUser() user: User, @Param('id') id: string, @Body('name') name: unknown) {
this.requireOwner(id, user);
if (typeof name !== 'string' || !name.trim()) {
throw new HttpException({ error: 'Guest name is required' }, 400);
}
try {
// No notifyInvite: a guest has no inbox.
return this.trips.createGuest(id, name, user.id);
} catch (e: unknown) {
if (e instanceof ValidationError) throw new HttpException({ error: e.message }, 400);
throw e;
}
}
@Put(':id/guests/:userId')
renameGuest(@CurrentUser() user: User, @Param('id') id: string, @Param('userId') userId: string, @Body('name') name: unknown) {
this.requireOwner(id, user);
if (typeof name !== 'string' || !name.trim()) {
throw new HttpException({ error: 'Guest name is required' }, 400);
}
try {
if (!this.trips.renameGuest(id, parseInt(userId), name)) {
throw new HttpException({ error: 'Guest not found' }, 404);
}
return { success: true };
} catch (e: unknown) {
if (e instanceof HttpException) throw e;
if (e instanceof ValidationError) throw new HttpException({ error: e.message }, 400);
throw e;
}
}
@Delete(':id/guests/:userId')
deleteGuest(@CurrentUser() user: User, @Param('id') id: string, @Param('userId') userId: string) {
this.requireOwner(id, user);
if (!this.trips.deleteGuest(id, parseInt(userId))) {
throw new HttpException({ error: 'Guest not found' }, 404);
}
return { success: true };
}
@Get(':id/bundle')
bundle(@CurrentUser() user: User, @Param('id') id: string) {
const trip = this.trips.get(id, user.id) as { user_id: number } | undefined;
+21
View File
@@ -11,6 +11,7 @@ import { listItems as listTodoItems } from '../../services/todoService';
import { listBudgetItems } from '../../services/budgetService';
import { listReservations } from '../../services/reservationService';
import { listFiles } from '../../services/fileService';
import { searchUnsplashPhotos } from '../../services/unsplashService';
/**
* Thin Nest wrapper around the existing trip service + the per-domain list
@@ -49,6 +50,10 @@ export class TripsService {
return tripSvc.getTripRaw(tripId);
}
searchCoverImages(query: string) {
return searchUnsplashPhotos(query, 9);
}
getOwner(tripId: string) {
return tripSvc.getTripOwner(tripId);
}
@@ -90,6 +95,22 @@ export class TripsService {
tripSvc.removeMember(tripId, targetId);
}
transferOwnership(tripId: string, newOwnerId: number, currentOwnerId: number) {
return tripSvc.transferOwnership(tripId, newOwnerId, currentOwnerId);
}
createGuest(tripId: string, name: string, invitedBy: number) {
return tripSvc.createGuest(tripId, name, invitedBy);
}
renameGuest(tripId: string, guestUserId: number, name: string): boolean {
return tripSvc.renameGuest(tripId, guestUserId, name);
}
deleteGuest(tripId: string, guestUserId: number): boolean {
return tripSvc.deleteGuest(tripId, guestUserId);
}
exportICS(tripId: string) {
return tripSvc.exportICS(tripId);
}
+76 -17
View File
@@ -1,4 +1,5 @@
import bcrypt from 'bcryptjs';
import { avatarUrl } from './avatarUrl';
import crypto from 'crypto';
import path from 'path';
import fs from 'fs';
@@ -11,6 +12,8 @@ import { revokeUserSessions, revokeUserSessionsForClient } from '../mcp';
import { deleteUserCompletely } from './userCleanupService';
import { validatePassword } from './passwordPolicy';
import { getPhotoProviderConfig } from './memories/helpersService';
import { ADDON_IDS } from '../addons';
import { prepareLlmAddonConfigForWrite, maskLlmAddonConfig } from './llmConfig';
import { send as sendNotification } from './notificationService';
import { resolveAuthToggles } from './authService';
@@ -57,8 +60,10 @@ export const isDocker = (() => {
// ── User CRUD ──────────────────────────────────────────────────────────────
export function listUsers() {
// Guests (#1362) are accountless trip participants, not real users — keep them out
// of admin user management entirely.
const users = db.prepare(
'SELECT id, username, email, role, avatar, created_at, updated_at, last_login FROM users ORDER BY created_at DESC'
'SELECT id, username, email, role, avatar, created_at, updated_at, last_login FROM users WHERE COALESCE(is_guest, 0) = 0 ORDER BY created_at DESC'
).all() as (Pick<User, 'id' | 'username' | 'email' | 'role' | 'created_at' | 'updated_at' | 'last_login'> & { avatar?: string | null })[];
let onlineUserIds = new Set<number>();
try {
@@ -67,7 +72,7 @@ export function listUsers() {
} catch { /* */ }
return users.map(u => ({
...u,
avatar_url: u.avatar ? `/uploads/avatars/${u.avatar}` : null,
avatar_url: avatarUrl(u),
created_at: utcSuffix(u.created_at),
updated_at: utcSuffix(u.updated_at as string),
last_login: utcSuffix(u.last_login),
@@ -91,10 +96,11 @@ export function createUser(data: { username: string; email: string; password: st
return { error: 'Invalid role', status: 400 };
}
const existingUsername = db.prepare('SELECT id FROM users WHERE username = ?').get(username);
// Guests (#1362) live in a reserved synthetic namespace; never let one block a real account.
const existingUsername = db.prepare('SELECT id FROM users WHERE username = ? AND COALESCE(is_guest, 0) = 0').get(username);
if (existingUsername) return { error: 'Username already taken', status: 409 };
const existingEmail = db.prepare('SELECT id FROM users WHERE email = ?').get(email);
const existingEmail = db.prepare('SELECT id FROM users WHERE email = ? AND COALESCE(is_guest, 0) = 0').get(email);
if (existingEmail) return { error: 'Email already taken', status: 409 };
const passwordHash = bcrypt.hashSync(password, BCRYPT_COST);
@@ -127,11 +133,11 @@ export function updateUser(id: string, data: { username?: string; email?: string
}
if (username && username !== user.username) {
const conflict = db.prepare('SELECT id FROM users WHERE username = ? AND id != ?').get(username, id);
const conflict = db.prepare('SELECT id FROM users WHERE username = ? AND id != ? AND COALESCE(is_guest, 0) = 0').get(username, id);
if (conflict) return { error: 'Username already taken', status: 409 };
}
if (email && email !== user.email) {
const conflict = db.prepare('SELECT id FROM users WHERE email = ? AND id != ?').get(email, id);
const conflict = db.prepare('SELECT id FROM users WHERE email = ? AND id != ? AND COALESCE(is_guest, 0) = 0').get(email, id);
if (conflict) return { error: 'Email already taken', status: 409 };
}
@@ -193,7 +199,7 @@ export function deleteUser(id: string, currentUserId: number) {
// ── Stats ──────────────────────────────────────────────────────────────────
export function getStats() {
const totalUsers = (db.prepare('SELECT COUNT(*) as count FROM users').get() as { count: number }).count;
const totalUsers = (db.prepare('SELECT COUNT(*) as count FROM users WHERE COALESCE(is_guest, 0) = 0').get() as { count: number }).count;
const totalTrips = (db.prepare('SELECT COUNT(*) as count FROM trips').get() as { count: number }).count;
const totalPlaces = (db.prepare('SELECT COUNT(*) as count FROM places').get() as { count: number }).count;
const totalFiles = (db.prepare('SELECT COUNT(*) as count FROM trip_files').get() as { count: number }).count;
@@ -426,14 +432,20 @@ export async function checkAndNotifyVersion(): Promise<void> {
export function listInvites() {
return db.prepare(`
SELECT i.*, u.username as created_by_name
SELECT i.*, u.username as created_by_name, t.title as trip_title
FROM invite_tokens i
JOIN users u ON i.created_by = u.id
LEFT JOIN trips t ON i.trip_id = t.id
ORDER BY i.created_at DESC
`).all();
}
export function createInvite(createdBy: number, data: { max_uses?: string | number; expires_in_days?: string | number }) {
/** Trips an admin can bind an invite to — id + title only, for the picker (#1402). */
export function listTripsForInvite() {
return db.prepare('SELECT id, title FROM trips ORDER BY title COLLATE NOCASE ASC').all();
}
export function createInvite(createdBy: number, data: { max_uses?: string | number; expires_in_days?: string | number; trip_id?: string | number | null }) {
const rawUses = parseInt(String(data.max_uses));
const uses = rawUses === 0 ? 0 : Math.min(Math.max(rawUses || 1, 1), 5);
const token = crypto.randomBytes(16).toString('hex');
@@ -441,19 +453,30 @@ export function createInvite(createdBy: number, data: { max_uses?: string | numb
? new Date(Date.now() + parseInt(String(data.expires_in_days)) * 86400000).toISOString()
: null;
// Optional trip binding: only persist a trip that actually exists, so a stale
// or forged id can never bind (and never auto-adds anyone on registration).
let tripId: number | null = null;
if (data.trip_id != null && String(data.trip_id).trim() !== '') {
const parsed = parseInt(String(data.trip_id));
if (Number.isInteger(parsed) && db.prepare('SELECT id FROM trips WHERE id = ?').get(parsed)) {
tripId = parsed;
}
}
const ins = db.prepare(
'INSERT INTO invite_tokens (token, max_uses, expires_at, created_by) VALUES (?, ?, ?, ?)'
).run(token, uses, expiresAt, createdBy);
'INSERT INTO invite_tokens (token, max_uses, expires_at, created_by, trip_id) VALUES (?, ?, ?, ?, ?)'
).run(token, uses, expiresAt, createdBy, tripId);
const inviteId = Number(ins.lastInsertRowid);
const invite = db.prepare(`
SELECT i.*, u.username as created_by_name
SELECT i.*, u.username as created_by_name, t.title as trip_title
FROM invite_tokens i
JOIN users u ON i.created_by = u.id
LEFT JOIN trips t ON i.trip_id = t.id
WHERE i.id = ?
`).get(inviteId);
return { invite, inviteId, uses, expiresInDays: data.expires_in_days ?? null };
return { invite, inviteId, uses, expiresInDays: data.expires_in_days ?? null, tripId };
}
export function deleteInvite(id: string) {
@@ -529,11 +552,17 @@ export function getCollabFeatures() {
export function updateCollabFeatures(features: { chat?: boolean; notes?: boolean; polls?: boolean; whatsnext?: boolean }) {
const mapping: Record<string, string> = { chat: 'collab_chat_enabled', notes: 'collab_notes_enabled', polls: 'collab_polls_enabled', whatsnext: 'collab_whatsnext_enabled' };
const before = getCollabFeatures();
const stmt = db.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)");
for (const [feat, key] of Object.entries(mapping)) {
if (features[feat] !== undefined) stmt.run(key, features[feat] ? 'true' : 'false');
}
return getCollabFeatures();
const after = getCollabFeatures();
// Collab flags gate MCP tool/resource registration, so callers must know
// whether anything actually flipped — a no-op save must not tear down every
// live MCP session (#1414).
const changed = (Object.keys(after) as Array<keyof typeof after>).some(k => after[k] !== before[k]);
return { features: after, changed };
}
// ── Packing Templates ──────────────────────────────────────────────────────
@@ -670,7 +699,13 @@ export function listAddons() {
}
return [
...addons.map(a => ({ ...a, enabled: !!a.enabled, config: JSON.parse(a.config || '{}') })),
...addons.map(a => ({
...a,
enabled: !!a.enabled,
config: a.id === ADDON_IDS.LLM_PARSING
? maskLlmAddonConfig(JSON.parse(a.config || '{}'))
: JSON.parse(a.config || '{}'),
})),
...providers.map(p => ({
id: p.id,
name: p.name,
@@ -702,7 +737,14 @@ export function updateAddon(id: string, data: { enabled?: boolean; config?: Reco
if (addon) {
if (data.enabled !== undefined) db.prepare('UPDATE addons SET enabled = ? WHERE id = ?').run(data.enabled ? 1 : 0, id);
if (data.config !== undefined) db.prepare('UPDATE addons SET config = ? WHERE id = ?').run(JSON.stringify(data.config), id);
if (data.config !== undefined) {
// The AI-parsing addon holds an API key — encrypt it at rest and preserve
// the stored key when the client echoes the mask sentinel (see llmConfig.ts).
const configToStore = id === ADDON_IDS.LLM_PARSING
? prepareLlmAddonConfigForWrite(data.config, JSON.parse(addon.config || '{}'))
: data.config;
db.prepare('UPDATE addons SET config = ? WHERE id = ?').run(JSON.stringify(configToStore), id);
}
} else {
if (data.enabled !== undefined) db.prepare('UPDATE photo_providers SET enabled = ? WHERE id = ?').run(data.enabled ? 1 : 0, id);
}
@@ -710,7 +752,13 @@ export function updateAddon(id: string, data: { enabled?: boolean; config?: Reco
const updatedAddon = db.prepare('SELECT * FROM addons WHERE id = ?').get(id) as Addon | undefined;
const updatedProvider = db.prepare('SELECT * FROM photo_providers WHERE id = ?').get(id) as { id: string; name: string; description?: string | null; icon: string; enabled: number; sort_order: number } | undefined;
const updated = updatedAddon
? { ...updatedAddon, enabled: !!updatedAddon.enabled, config: JSON.parse(updatedAddon.config || '{}') }
? {
...updatedAddon,
enabled: !!updatedAddon.enabled,
config: updatedAddon.id === ADDON_IDS.LLM_PARSING
? maskLlmAddonConfig(JSON.parse(updatedAddon.config || '{}'))
: JSON.parse(updatedAddon.config || '{}'),
}
: updatedProvider
? {
id: updatedProvider.id,
@@ -724,8 +772,19 @@ export function updateAddon(id: string, data: { enabled?: boolean; config?: Reco
}
: null;
// Only these addons gate MCP tool/resource/prompt registration (see
// registerTools/registerResources) — and only a real enabled-flip changes
// what a session would register. Config-only saves, photo providers and
// MCP-irrelevant addons must not tear down every live session (#1414).
const MCP_RELEVANT_ADDONS = new Set<string>([
ADDON_IDS.MCP, ADDON_IDS.PACKING, ADDON_IDS.BUDGET, ADDON_IDS.COLLAB,
ADDON_IDS.ATLAS, ADDON_IDS.VACAY, ADDON_IDS.JOURNEY,
]);
const enabledChanged = !!addon && data.enabled !== undefined && (data.enabled ? 1 : 0) !== addon.enabled;
return {
addon: updated,
mcpAffected: enabledChanged && MCP_RELEVANT_ADDONS.has(id),
auditDetails: { enabled: data.enabled !== undefined ? !!data.enabled : undefined, config_changed: data.config !== undefined },
};
}
+15 -9
View File
@@ -64,8 +64,8 @@ export function normalizeFlight(raw: AirtrailFlightRaw): AirtrailFlight {
toCode: airportCode(raw.to),
toName: raw.to?.name ?? null,
date: raw.date ?? null,
departure: raw.departureScheduled ?? null,
arrival: raw.arrivalScheduled ?? null,
departure: raw.departureScheduled ?? raw.departure ?? null,
arrival: raw.arrivalScheduled ?? raw.arrival ?? null,
airline: entityName(raw.airline),
flightNumber: raw.flightNumber ?? null,
aircraft: entityCode(raw.aircraft),
@@ -103,11 +103,14 @@ function hasCoords(a: AirtrailAirport | null): a is AirtrailAirport & { lat: num
/** Raw AirTrail flight → the data createReservation() expects (type:'flight'). */
export function mapFlightToReservation(raw: AirtrailFlightRaw): MappedReservation {
// Read the SCHEDULED times only — TREK plans against the scheduled (booked) time,
// not the actual/estimated `departure`/`arrival`. When a flight has no scheduled
// time, the clock is left blank (date preserved) rather than fabricated.
const dep = localParts(raw.departureScheduled, raw.from?.tz ?? null);
const arr = localParts(raw.arrivalScheduled, raw.to?.tz ?? null);
// Prefer the scheduled (booked) time TREK plans against, but fall back to the
// primary departure/arrival instant when AirTrail has no scheduled time. Manually
// entered flights only set `departure`/`arrival` (the `*Scheduled` columns stay
// null), so reading scheduled alone dropped the clock — and the whole arrival —
// for the common case (#1336). Only when neither exists is the clock left blank
// (date preserved) rather than fabricated.
const dep = localParts(raw.departureScheduled ?? raw.departure, raw.from?.tz ?? null);
const arr = localParts(raw.arrivalScheduled ?? raw.arrival, raw.to?.tz ?? null);
const fromCode = airportCode(raw.from);
const toCode = airportCode(raw.to);
@@ -194,8 +197,11 @@ export function canonicalHash(raw: AirtrailFlightRaw): string {
to: airportCode(raw.to),
date: raw.date ?? null,
datePrecision: raw.datePrecision ?? 'day',
departureScheduled: raw.departureScheduled ?? null,
arrivalScheduled: raw.arrivalScheduled ?? null,
// Hash the same instant the import uses (scheduled, else primary) so a change to
// whichever time TREK actually shows triggers a re-sync — and existing flights
// imported without a scheduled time re-sync once to pick up their clock (#1336).
departureScheduled: raw.departureScheduled ?? raw.departure ?? null,
arrivalScheduled: raw.arrivalScheduled ?? raw.arrival ?? null,
airline: entityCode(raw.airline),
flightNumber: raw.flightNumber ?? null,
aircraft: entityCode(raw.aircraft),
+16
View File
@@ -444,6 +444,22 @@ export async function getStats(userId: number) {
}
}
// Merge countries reached only by a transport booking. Those store geocoded from/to
// coordinates in reservation_endpoints but create no place row, so they never show up
// via resolvePlaceCountries above and would otherwise be missed (#1366).
const endpoints = db.prepare(`
SELECT DISTINCT e.lat, e.lng
FROM reservation_endpoints e
JOIN reservations r ON e.reservation_id = r.id
WHERE r.trip_id IN (${tripIds.map(() => '?').join(',')})
`).all(...tripIds) as { lat: number; lng: number }[];
for (const e of endpoints) {
const code = getCountryFromCoords(e.lat, e.lng);
if (code && !countries.find(c => c.code === code)) {
countries.push({ code, placeCount: 0, tripCount: 0, firstVisit: null, lastVisit: null });
}
}
const mostVisited = countries.length > 0 ? countries.reduce((a, b) => a.placeCount > b.placeCount ? a : b) : null;
const continents: Record<string, number> = {};
+43 -10
View File
@@ -17,10 +17,12 @@ import { revokeUserSessions } from '../mcp';
import { startTripReminders } from '../scheduler';
import { deleteUserCompletely } from './userCleanupService';
import { getFlightDistanceKm } from './distanceService';
import { getCountryFromCoords } from './atlasService';
import { verifyJwtAndLoadUser } from '../middleware/auth';
import { User } from '../types';
import { DEMO_EMAIL_PRIMARY, isDemoEmail } from './demo';
import { avatarUrl } from './avatarUrl';
import { joinTripAsMember } from './tripMembership';
import { isPasskeyConfigured } from './webauthnConfig';
export { avatarUrl };
@@ -277,7 +279,7 @@ export function getPendingMfaSecret(userId: number): string | null {
// ---------------------------------------------------------------------------
export function getAppConfig(authenticatedUser: { id: number } | null) {
const userCount = (db.prepare('SELECT COUNT(*) as count FROM users').get() as { count: number }).count;
const userCount = (db.prepare('SELECT COUNT(*) as count FROM users WHERE COALESCE(is_guest, 0) = 0').get() as { count: number }).count;
const isDemo = process.env.DEMO_MODE?.toLowerCase() === 'true';
const toggles = resolveAuthToggles();
const version: string = process.env.APP_VERSION ?? require('../../package.json').version;
@@ -378,7 +380,7 @@ export function registerUser(body: {
const email = typeof body.email === 'string' ? body.email.trim() : '';
const { password, invite_token } = body;
const userCount = (db.prepare('SELECT COUNT(*) as count FROM users').get() as { count: number }).count;
const userCount = (db.prepare('SELECT COUNT(*) as count FROM users WHERE COALESCE(is_guest, 0) = 0').get() as { count: number }).count;
let validInvite: any = null;
if (invite_token) {
@@ -406,7 +408,8 @@ export function registerUser(body: {
return { error: 'Invalid email format', status: 400 };
}
const existingUser = db.prepare('SELECT id FROM users WHERE LOWER(email) = LOWER(?) OR LOWER(username) = LOWER(?)').get(email, username);
// Ignore guests (#1362): their synthetic username/email must never block a real signup.
const existingUser = db.prepare('SELECT id FROM users WHERE (LOWER(email) = LOWER(?) OR LOWER(username) = LOWER(?)) AND COALESCE(is_guest, 0) = 0').get(email, username);
if (existingUser) {
return { error: 'Registration failed. Please try different credentials.', status: 409 };
}
@@ -430,6 +433,11 @@ export function registerUser(body: {
if (!updated) {
console.warn(`[Auth] Invite token ${validInvite.token.slice(0, 8)}... exceeded max_uses due to race condition`);
}
// Trip-bound invite (#1402): auto-add the freshly registered user to the
// trip. Idempotent + owner-safe; no-ops if the bound trip was since deleted.
if (validInvite.trip_id) {
joinTripAsMember(Number(validInvite.trip_id), Number(result.lastInsertRowid), validInvite.created_by ?? null);
}
}
return {
@@ -469,7 +477,9 @@ export function loginUser(body: {
return { error: 'Email and password are required', status: 400 };
}
const user = db.prepare('SELECT * FROM users WHERE LOWER(email) = LOWER(?)').get(email) as User | undefined;
// Guests (#1362) carry a synthetic email but must never authenticate — treat a
// matched guest row exactly like an unknown email (dummy-hash timing preserved).
const user = db.prepare('SELECT * FROM users WHERE LOWER(email) = LOWER(?) AND COALESCE(is_guest, 0) = 0').get(email) as User | undefined;
// Always run bcrypt — even for unknown/OIDC-only users — so response time
// does not reveal whether the email exists in the database (CWE-203/208).
@@ -649,7 +659,7 @@ export function updateSettings(
if (!/^[a-zA-Z0-9_.-]+$/.test(trimmed)) {
return { error: 'Username can only contain letters, numbers, underscores, dots and hyphens', status: 400 };
}
const conflict = db.prepare('SELECT id FROM users WHERE LOWER(username) = LOWER(?) AND id != ?').get(trimmed, userId);
const conflict = db.prepare('SELECT id FROM users WHERE LOWER(username) = LOWER(?) AND id != ? AND COALESCE(is_guest, 0) = 0').get(trimmed, userId);
if (conflict) return { error: 'Username already taken', status: 409 };
}
@@ -658,7 +668,7 @@ export function updateSettings(
if (!trimmed || !EMAIL_REGEX.test(trimmed)) {
return { error: 'Invalid email format', status: 400 };
}
const conflict = db.prepare('SELECT id FROM users WHERE LOWER(email) = LOWER(?) AND id != ?').get(trimmed, userId);
const conflict = db.prepare('SELECT id FROM users WHERE LOWER(email) = LOWER(?) AND id != ? AND COALESCE(is_guest, 0) = 0').get(trimmed, userId);
if (conflict) return { error: 'Email already taken', status: 409 };
}
@@ -707,7 +717,9 @@ export function getSettings(userId: number): { error?: string; status?: number;
export async function saveAvatar(userId: number, filename: string) {
const current = db.prepare('SELECT avatar FROM users WHERE id = ?').get(userId) as { avatar: string | null } | undefined;
if (current && current.avatar) {
// Only a locally uploaded file has something to clean up. An OIDC picture URL
// (#1399) has no file on disk, so skip the rm — path.join on a URL is meaningless.
if (current?.avatar && !/^https:\/\//i.test(current.avatar)) {
// Fire-and-forget: leftover files are harmless; the DB update is
// the source of truth for which avatar is current.
const oldPath = path.join(avatarDir, current.avatar);
@@ -722,7 +734,8 @@ export async function saveAvatar(userId: number, filename: string) {
export async function deleteAvatar(userId: number) {
const current = db.prepare('SELECT avatar FROM users WHERE id = ?').get(userId) as { avatar: string | null } | undefined;
if (current && current.avatar) {
// An OIDC picture URL (#1399) has no local file — only rm an uploaded one.
if (current?.avatar && !/^https:\/\//i.test(current.avatar)) {
const filePath = path.join(avatarDir, current.avatar);
await fs.promises.rm(filePath, { force: true }).catch(() => {});
}
@@ -735,8 +748,10 @@ export async function deleteAvatar(userId: number) {
// ---------------------------------------------------------------------------
export function listUsers(excludeUserId: number) {
// The global user directory feeds the trip member-add / contributor pickers —
// guests (#1362) are trip-scoped and must never be selectable here.
const users = db.prepare(
'SELECT id, username, avatar FROM users WHERE id != ? ORDER BY username ASC'
'SELECT id, username, avatar FROM users WHERE id != ? AND COALESCE(is_guest, 0) = 0 ORDER BY username ASC'
).all(excludeUserId) as Pick<User, 'id' | 'username' | 'avatar'>[];
return users.map(u => ({ ...u, avatar_url: avatarUrl(u) }));
}
@@ -977,6 +992,23 @@ export function getTravelStats(userId: number) {
`).all(userId, userId) as { country_code: string }[];
placeRegionCodes.forEach(r => { if (r.country_code) countryCodes.add(r.country_code.toUpperCase()); });
// Transport bookings don't create a place row, so their geocoded endpoints never
// reached place_regions — a country reached only by a flight/train (no lodging or
// planned place there) was never counted as visited (#1366). Resolve each endpoint
// coordinate to a country and fold it in too.
const endpoints = db.prepare(`
SELECT DISTINCT e.lat, e.lng
FROM reservation_endpoints e
JOIN reservations r ON e.reservation_id = r.id
JOIN trips t ON r.trip_id = t.id
LEFT JOIN trip_members tm ON t.id = tm.trip_id
WHERE (t.user_id = ? OR tm.user_id = ?)
`).all(userId, userId) as { lat: number; lng: number }[];
for (const e of endpoints) {
const code = getCountryFromCoords(e.lat, e.lng);
if (code) countryCodes.add(code.toUpperCase());
}
return {
countries: [...countryCodes],
cities: [...cities],
@@ -1201,7 +1233,8 @@ export function requestPasswordReset(rawEmail: string, createdIp: string | null)
return { tokenForDelivery: null, userId: null, userEmail: null, reason: 'no_user' };
}
const user = db.prepare('SELECT id, email, password_hash, oidc_sub FROM users WHERE email = ?').get(email) as
// A guest (#1362) must never receive a reset link — treat its synthetic email as unknown.
const user = db.prepare('SELECT id, email, password_hash, oidc_sub FROM users WHERE email = ? AND COALESCE(is_guest, 0) = 0').get(email) as
| { id: number; email: string; password_hash: string | null; oidc_sub: string | null }
| undefined;
+10 -1
View File
@@ -1,3 +1,12 @@
/**
* Resolve a user's stored avatar reference to a renderable URL.
*
* The value is either an uploaded file name (served from /uploads/avatars) or,
* for SSO users who never uploaded one, an absolute https URL taken from their
* OIDC `picture` claim (#1399) — that one is passed through untouched.
*/
export function avatarUrl(user: { avatar?: string | null }): string | null {
return user.avatar ? `/uploads/avatars/${user.avatar}` : null;
if (!user.avatar) return null;
if (/^https:\/\//i.test(user.avatar)) return user.avatar;
return `/uploads/avatars/${user.avatar}`;
}
+81 -36
View File
@@ -11,7 +11,7 @@ export { verifyTripAccess } from './tripAccess';
function loadItemMembers(itemId: number | string) {
const rows = db.prepare(`
SELECT bm.user_id, bm.paid, u.username, u.avatar
SELECT bm.user_id, bm.paid, bm.amount, u.username, u.avatar
FROM budget_item_members bm
JOIN users u ON bm.user_id = u.id
WHERE bm.budget_item_id = ?
@@ -60,7 +60,7 @@ export function listBudgetItems(tripId: string | number) {
if (itemIds.length > 0) {
const allMembers = db.prepare(`
SELECT bm.budget_item_id, bm.user_id, bm.paid, u.username, u.avatar
SELECT bm.budget_item_id, bm.user_id, bm.paid, bm.amount, u.username, u.avatar
FROM budget_item_members bm
JOIN users u ON bm.user_id = u.id
WHERE bm.budget_item_id IN (${itemIds.map(() => '?').join(',')})
@@ -69,7 +69,7 @@ export function listBudgetItems(tripId: string | number) {
for (const m of allMembers) {
if (!membersByItem[m.budget_item_id]) membersByItem[m.budget_item_id] = [];
membersByItem[m.budget_item_id].push({
user_id: m.user_id, paid: m.paid, username: m.username, avatar_url: avatarUrl(m),
user_id: m.user_id, paid: m.paid, username: m.username, avatar_url: avatarUrl(m), amount: m.amount,
});
}
}
@@ -104,6 +104,7 @@ export function createBudgetItem(
category?: string; name: string; total_price?: number;
currency?: string | null; exchange_rate?: number;
payers?: { user_id: number; amount: number }[]; member_ids?: number[];
members?: { user_id: number; amount?: number | null }[];
persons?: number | null; days?: number | null; note?: string | null; expense_date?: string | null;
reservation_id?: number | null;
},
@@ -147,8 +148,11 @@ export function createBudgetItem(
const itemId = result.lastInsertRowid as number;
if (data.payers && data.payers.length > 0) writeItemPayers(itemId, data.payers);
if (data.member_ids && data.member_ids.length > 0) {
const insert = db.prepare('INSERT OR IGNORE INTO budget_item_members (budget_item_id, user_id, paid) VALUES (?, ?, 0)');
if (data.members && data.members.length > 0) {
const insert = db.prepare('INSERT OR IGNORE INTO budget_item_members (budget_item_id, user_id, paid, amount) VALUES (?, ?, 0, ?)');
for (const m of data.members) insert.run(itemId, m.user_id, m.amount !== undefined && m.amount !== null ? m.amount : null);
} else if (data.member_ids && data.member_ids.length > 0) {
const insert = db.prepare('INSERT OR IGNORE INTO budget_item_members (budget_item_id, user_id, paid, amount) VALUES (?, ?, 0, NULL)');
for (const uid of data.member_ids) insert.run(itemId, uid);
}
@@ -185,6 +189,7 @@ export function updateBudgetItem(
category?: string; name?: string; total_price?: number;
currency?: string | null; exchange_rate?: number;
payers?: { user_id: number; amount: number }[]; member_ids?: number[];
members?: { user_id: number; amount?: number | null }[];
persons?: number | null; days?: number | null; note?: string | null; sort_order?: number; expense_date?: string | null;
},
) {
@@ -228,9 +233,14 @@ export function updateBudgetItem(
db.prepare('UPDATE budget_items SET total_price = ? WHERE id = ?').run(data.total_price, id);
}
}
if (data.member_ids !== undefined) {
if (data.members !== undefined) {
db.prepare('DELETE FROM budget_item_members WHERE budget_item_id = ?').run(id);
const insert = db.prepare('INSERT OR IGNORE INTO budget_item_members (budget_item_id, user_id, paid) VALUES (?, ?, 0)');
const insert = db.prepare('INSERT OR IGNORE INTO budget_item_members (budget_item_id, user_id, paid, amount) VALUES (?, ?, 0, ?)');
for (const m of data.members) insert.run(id, m.user_id, m.amount !== undefined && m.amount !== null ? m.amount : null);
db.prepare('UPDATE budget_items SET persons = ? WHERE id = ?').run(data.members.length || null, id);
} else if (data.member_ids !== undefined) {
db.prepare('DELETE FROM budget_item_members WHERE budget_item_id = ?').run(id);
const insert = db.prepare('INSERT OR IGNORE INTO budget_item_members (budget_item_id, user_id, paid, amount) VALUES (?, ?, 0, NULL)');
for (const uid of data.member_ids) insert.run(id, uid);
db.prepare('UPDATE budget_items SET persons = ? WHERE id = ?').run(data.member_ids.length || null, id);
}
@@ -323,8 +333,8 @@ export function toggleMemberPaid(id: string | number, tripId: string | number, u
export function getPerPersonSummary(tripId: string | number) {
const summary = db.prepare(`
SELECT bm.user_id, u.username, u.avatar,
SUM(bi.total_price * 1.0 / (SELECT COUNT(*) FROM budget_item_members WHERE budget_item_id = bi.id)) as total_assigned,
SUM(CASE WHEN bm.paid = 1 THEN bi.total_price * 1.0 / (SELECT COUNT(*) FROM budget_item_members WHERE budget_item_id = bi.id) ELSE 0 END) as total_paid,
SUM(COALESCE(bm.amount, bi.total_price * 1.0 / (SELECT COUNT(*) FROM budget_item_members WHERE budget_item_id = bi.id))) as total_assigned,
SUM(CASE WHEN bm.paid = 1 THEN COALESCE(bm.amount, bi.total_price * 1.0 / (SELECT COUNT(*) FROM budget_item_members WHERE budget_item_id = bi.id)) ELSE 0 END) as total_paid,
COUNT(bi.id) as items_count
FROM budget_item_members bm
JOIN budget_items bi ON bm.budget_item_id = bi.id
@@ -336,9 +346,26 @@ export function getPerPersonSummary(tripId: string | number) {
return summary.map(s => ({ ...s, avatar_url: avatarUrl(s) }));
}
// ---------------------------------------------------------------------------
// Settlement calculation (greedy debt matching)
// ---------------------------------------------------------------------------
export function splitEqualShares(total: number, members: { user_id: number }[], itemId: number): Record<number, number> {
const n = members.length;
if (n === 0) return {};
const totalCents = Math.round(total * 100);
const baseCents = Math.floor(totalCents / n);
const remainder = totalCents % n;
const shares: Record<number, number> = {};
const sortedMembers = [...members].sort((a, b) => a.user_id - b.user_id);
const startIndex = itemId % n;
for (let i = 0; i < n; i++) {
const member = sortedMembers[i];
const hasExtraCent = ((i - startIndex + n) % n) < remainder;
shares[member.user_id] = (baseCents + (hasExtraCent ? 1 : 0)) / 100;
}
return shares;
}
export function calculateSettlement(
tripId: string | number,
@@ -347,22 +374,34 @@ export function calculateSettlement(
const base = (opts.base || opts.tripCurrency || 'EUR').toUpperCase();
const tripCurrency = (opts.tripCurrency || base).toUpperCase();
const rates = opts.rates ?? null;
// Amount in some currency → base. Pre-rework rows store currency = NULL, which
// means "the trip's own currency". rates[X] = units of X per 1 base.
const toBase = (amount: number, itemCurrency: string | null | undefined, itemRate?: number | null): number => {
// Net the whole settlement in the trip's canonical currency and convert the final
// totals to the display currency once, instead of netting in the (moving) display
// currency. Otherwise per-expense rounding shifts as live FX drifts and the greedy
// debt-simplifier reshuffles it into phantom third-party micro-flows (#1382). When
// the display currency IS the trip currency (the common case) every conversion below
// is the identity, so behaviour is unchanged.
// rates[X] = units of X per 1 base; the frozen exchange_rate is units of item-currency
// per 1 trip-currency. Pre-rework rows store currency = NULL = "the trip's own currency".
const toTrip = (amount: number, itemCurrency: string | null | undefined, itemRate?: number | null): number => {
const cur = (itemCurrency || tripCurrency).toUpperCase();
if (cur === base) return amount;
// Prefer the FX rate frozen at entry time (#1335): a settled expense keeps the rate it
// was booked at, so a later live-rate drift doesn't re-open it with a few-cent residual.
// The stored rate is units of item-currency per 1 trip-currency, so it only applies when
// converting to the trip's own currency; otherwise (and for legacy rows) use live rates.
if (base === tripCurrency && itemRate != null && itemRate > 0 && itemRate !== 1) {
return amount / itemRate;
}
if (cur === tripCurrency) return amount;
// Prefer the FX rate frozen at entry time (#1335): a settled expense keeps the rate
// it was booked at, so a later live-rate drift doesn't re-open it with a residual.
if (itemRate != null && itemRate > 0 && itemRate !== 1) return amount / itemRate;
// Legacy rows without a frozen rate: convert via base with live rates.
if (!rates) return amount;
const r = rates[cur];
return r && r > 0 ? amount / r : amount;
const rCur = rates[cur];
const rTrip = rates[tripCurrency];
if (rCur && rCur > 0 && rTrip && rTrip > 0) return (amount / rCur) * rTrip;
return amount;
};
// trip-currency → display currency, applied once to the final netted totals.
const toDisplay = (v: number): number =>
base === tripCurrency ? v : (rates && rates[tripCurrency] > 0 ? v / rates[tripCurrency] : v);
// A recorded settle-up amount is entered in whatever display currency the payer was
// viewing (the table has no currency column), so bring it into trip currency to net.
const settleToTrip = (v: number): number =>
base === tripCurrency ? v : (rates && rates[tripCurrency] > 0 ? v * rates[tripCurrency] : v);
const items = db.prepare('SELECT * FROM budget_items WHERE trip_id = ?').all(tripId) as BudgetItem[];
const allMembers = db.prepare(`
@@ -392,13 +431,19 @@ export function calculateSettlement(
const payers = allPayers.filter(p => p.budget_item_id === item.id);
if (members.length === 0) continue; // planning-only entry → doesn't affect balances
const paidBase = payers.reduce((a, p) => a + toBase(p.amount > 0 ? p.amount : 0, item.currency, item.exchange_rate), 0);
const sharePerMember = paidBase / members.length;
// Payers are credited what they actually paid (converted to base)…
for (const p of payers) ensure(p.user_id, p).balance += toBase(p.amount > 0 ? p.amount : 0, item.currency, item.exchange_rate);
// …and every split participant owes an equal share of the base total.
for (const m of members) ensure(m.user_id, m).balance -= sharePerMember;
// Payers are credited what they actually paid (converted to trip currency with
// the item's stored exchange rate)…
for (const p of payers) ensure(p.user_id, p).balance += toTrip(p.amount > 0 ? p.amount : 0, item.currency, item.exchange_rate);
// …and each split participant owes their share — a custom per-member amount
// when one is set, otherwise an equal share of the expense total.
const hasCustomSplit = members.some(m => m.amount !== null && m.amount !== undefined);
const equalShares = !hasCustomSplit ? splitEqualShares(item.total_price, members, item.id) : {};
for (const m of members) {
const memberShare = hasCustomSplit && m.amount !== null && m.amount !== undefined
? toTrip(m.amount, item.currency, item.exchange_rate)
: toTrip(equalShares[m.user_id] || 0, item.currency, item.exchange_rate);
ensure(m.user_id, m).balance -= memberShare;
}
}
// Persisted settle-up transfers already moved money: the payer's debt shrinks,
@@ -412,8 +457,8 @@ export function calculateSettlement(
return balances[id];
};
for (const s of settlements) {
ensureSettled(s.from_user_id, s.from_username, s.from_avatar_url).balance += s.amount;
ensureSettled(s.to_user_id, s.to_username, s.to_avatar_url).balance -= s.amount;
ensureSettled(s.from_user_id, s.from_username, s.from_avatar_url).balance += settleToTrip(s.amount);
ensureSettled(s.to_user_id, s.to_username, s.to_avatar_url).balance -= settleToTrip(s.amount);
}
// Calculate optimized payment flows (greedy algorithm)
@@ -434,7 +479,7 @@ export function calculateSettlement(
flows.push({
from: { user_id: debtors[di].user_id, username: debtors[di].username, avatar_url: debtors[di].avatar_url },
to: { user_id: creditors[ci].user_id, username: creditors[ci].username, avatar_url: creditors[ci].avatar_url },
amount: Math.round(transfer * 100) / 100,
amount: Math.round(toDisplay(transfer) * 100) / 100,
});
}
debtors[di].amount -= transfer;
@@ -444,7 +489,7 @@ export function calculateSettlement(
}
return {
balances: Object.values(balances).map(b => ({ ...b, balance: Math.round(b.balance * 100) / 100 })),
balances: Object.values(balances).map(b => ({ ...b, balance: Math.round(toDisplay(b.balance) * 100) / 100 })),
flows,
settlements,
};

Some files were not shown because too many files have changed in this diff Show More