mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-04 01:44:13 +00:00
Feat/orm : mikroorm (#2416)
* base entities
* update deps
* fix date as string
* rename entities
* migrations + seeders
* feat(db): DbTimestampType keeps DATETIME columns as the CURRENT_TIMESTAMP text
* feat(db): discover entities from an explicit list instead of a glob
* test(db): createTestOrm binds an ORM to a suite's own SQLite handle
* feat(db): dialect helper is the one place SQL functions are spelled
* test(db): dialect helper refuses malformed column references and day counts
* feat(db): snake_case entity shape and the first three repositories (Days, DayNotes, Trips)
* fix(db): repositories mirror the statement's column set and guard their row types
* feat(db): request-context and unit-of-work helpers for the ORM, with concurrency tests
* test(server): integration suites boot on the migrated schema snapshot
* test(server): snapshot harness keeps the legacy id semantics
* fix(test): route MikroORM's dynamic imports through vitest from the setup file, not the ORM config
* test(db): coverage ratchet entries for the ORM foundation
* test(server): websocket suites boot on the migrated schema snapshot
* test(server): coverage's uncovered-file pass goes through the SWC transform
* fix(db): dialect helpers dispatch on the platform; lint gate for the repository layer
* test(server): ORM suites open the schema snapshot; RESET_TABLES derived from the schema
* chore(server): promise safety net and sweep tooling for the async migration
* refactor(realtime, systemNotices, addons, airports, audit, categories, permissions, query-helpers, tags, transit, trip-membership): async DB-touching methods; transactions through UnitOfWork
* fix(server): observe every promise the async sweep left unobserved (timer, handshake, plugin-runtime test)
* test(doc-sync): unit suites await the methods the async sweep made async
* refactor(atlas, school-holidays, settings): async DB-touching methods; transactions through UnitOfWork
* chore(server): lint rule refusing a Promise used as a plain value, and the misses it found
* test(server): suites await the methods Task 1's forced edits made async
* refactor(budget, common, day-notes, days): async DB-touching methods; transactions through UnitOfWork
* test(oauth): controller suite awaits the async service
* chore(server): db-call-graph --unawaited lists calls to async methods whose result is used without await
* refactor(llm-parse, mcp-shared, oauth, place-shadow, route-usage, storage, todo, trip-invite): async DB-touching methods; transactions through UnitOfWork
* refactor(plugins): async DB-touching methods; transactions through UnitOfWork
* chore(server): db-call-graph --sync stops its transitive walk at an async callee
* chore(plugins): drop gate-only asyncs; observe the scheduler's rejection; async event-sink stub
* refactor(notifications, place-photos, backup): async DB-touching methods; transactions through UnitOfWork
* refactor(auth, files): async DB-touching methods; transactions through UnitOfWork
* test(server): suites await the methods earlier sweep groups made async
* refactor(tokens): async DB-touching methods; the auth token handlers await them
* test(files): upload filters fail closed on an excluded or unresolvable type
* refactor(collab, collections, maps): async DB-touching methods; transactions through UnitOfWork
* refactor(memories, photos, packing, share): async DB-touching methods; transactions through UnitOfWork
* chore(server): lint rule also refuses a Promise handed to expect() without resolves/rejects
* refactor(vacay, admin, doc-sync): async DB-touching methods; transactions through UnitOfWork
* fix(vacay): type the loop accumulators the async sweep introduced
* refactor(journey, oidc, place-enrichment, tokens, trip-members): async DB-touching methods; transactions through UnitOfWork
* fix(server): the journey hooks are awaited by their callers, not detached
* refactor(assignments, public-api, accommodations, places): async DB-touching methods; transactions through UnitOfWork
* refactor(trips): rewrite AccommodationsService.createAccommodation .bind alias
Recipe R4 trap named in the Task 12 brief: a .bind alias of an
AssignmentsService/AccommodationsService method is typed any and hides a
missing await from tsc and the promise lint rules. createAccommodation
belongs to this task's group, so rewritten as an arrow forwarding to the
method instead of a bound reference.
* refactor(assignments): drop the unused Trip type alias
* refactor(reservations, booking-import, calendar, integrations, roadtrip): async DB-touching methods; transactions through UnitOfWork
* refactor(roadtrip, reservations): return await on transactional; document the single-flight promises
* refactor(trip-read-model, trips, feeds): async DB-touching methods; transactions through UnitOfWork
* refactor(server): remove DatabaseService.transaction — every transaction runs through UnitOfWork
* refactor(trips, feeds): drop added return annotations; no double await on the feed guard
* fix(server): phase 1 review follow-ups — awaited returns, logged upload-filter rejections, covered handshake/notice branches, call-graph gate in CI, dead test imports
* fix(server): upload filters answer multer once on a throwing callback; positive call-graph gate test
* test(db): entity metadata must match the migrated schema; fix the four drifts it found
* feat(db): primary-relation entities proven (BudgetCategoryOrder, VacayUserSettings)
* test(db): parity gate also holds declared pivot entities; per-field column types; missing-set ratchets both ways
* test(db): numeric ids for the primary-relation spike
* feat(db): re-runnable entity generator encoding the snake_case/DbTimestampType rules
* fix(db): generator guard rails — validation cannot mask hidden()/index loss; typed JSON; loud failures
* fix(db): generator keeps NOT NULL boolean defaults; fails if a JSON interface import survives
* refactor(db): every entity in the snake_case shape; document-sync entities added; one repository per entity
* fix(db): no NaN class-field initialisers; entity generator --check gate in CI; parity normaliser keeps literal case
* chore(db): entity --check reports stray files; class-field census is a ratchet; migrate-encryption typechecked
* feat(db): AppSettings and Users repositories; forFeature wiring pattern
* refactor(permissions): permission flags through AppSettingsRepository
* fix(server): boot-time settings read runs inside an explicit ORM request context
* refactor(audit): audit log writes through AuditLogRepository
* fix(db): PK reads refresh past the identity map; typed owned-lookup generics; e2e ORM module mirrors production config
* docs(db): owned-lookup call-site convention; refresh side effect; e2e ORM module spread notes
* fix(audit): audit rows are native inserts, not a unit-of-work flush; closed test ORMs
* fix(server): non-HTTP entrypoints run inside an ORM request context; permission loads fail closed on context errors
* refactor(categories, tags): repositories replace raw SQL
* refactor(addons): addon catalog and photo providers through repositories
* fix(db): generator captures inline UNIQUE constraints
SqliteSchemaHelper.getIndexes() drops every unnamed sqlite_autoindex_
entry before entity-generator ever sees it, so a table-level
UNIQUE(...) constraint with no separate named CREATE UNIQUE INDEX
(settings' UNIQUE(user_id, key) among ~40 others) never reached the
generated entity's uniques: metadata. Adds a general
RULE9_addImplicitUniqueConstraints (skips a column set identical to
the table's own primary key — AppSettings.key/Addons.id noise) fed by
a PRAGMA index_list/index_info scan, and regenerates every entity.
* chore(addons): well-known gate wraps only the addon read in a request context; drop unused test factories
* fix(platform): well-known gate tolerates a synchronous addon read from the context helper
* fix(db): PK lookups inside patch refresh past the identity map; corrected identity-map notes
* refactor(settings): user and instance settings through repositories
SettingsRepository (getForUser/upsertForUser/getOne/deleteForUser) replaces
the per-user settings table's raw SQL; SettingsService drops DatabaseService
entirely. instance-api-keys.ts's readInstanceApiKey/writeInstanceApiKey/
resolveApiKey take an explicit AppSettingsRepository/UsersRepository instead
of a raw connection.
An earlier version resolved those two repositories itself from the active
MikroORM request context, so none of its six callers needed to change. That
worked in production and e2e (always inside a real request) but broke
service construction in plain unit tests across every calling domain
(addons, auth x2, maps, transit, unsplash - 185 failures on a full run),
since none of them wrap a request context. Each of those six services now
injects its own AppSettingsRepository/UsersRepository and passes them
through explicitly, matching how every other converted repository in this
migration is consumed; their own SQL is untouched (outside Plan 3a).
* test(server): harness constructors follow the Task 5 repository signatures; one test ORM per handle in the plugin host
* fix(db): generator names relation properties in captured UNIQUE constraints
* fix(settings): drop dead wiring and the speculative deleteForUser; strict row assertions
* fix(server): plan 3a review follow-ups — fail closed without an ORM at every choke point; seam and D5 ratchet tests; dead method and DDL copies removed
* fix(server): plan 3a re-review follow-ups — plugin boot activation and the airports backfill inside a request context; the supervisor answers the child before failing closed; BOOT-SWEEP-001 drives the real boot hooks; ws adapter seam pinned
* feat(db): generated entities declare their repository type; test casts dropped
* fix(server): plan 3a re-review 2 follow-ups — absent-ORM boot branch pinned; airports boot hook never rejects; BOOT-SWEEP-001 asserts the seven routes; duplicate comment removed
* feat(server): pre-init photo route and WS handshake run in a request context; InviteTokensRepository
* refactor(auth): users table through UsersRepository; JWT and MFA lookups repository-backed
* refactor(tokens): MCP and API tokens through McpTokensRepository
* refactor(auth): passkeys and registration invites through repositories
* fix(db): row-out repository reads bypass the identity map — stale write-back over nativeUpdate at flush; insertUser via em.insert; settings round-trip pinned
* fix(server): non-numeric route ids answer the legacy not-found, never NaN (tokens, categories, tags); mint path back to two statements; identity-map regression pinned
* refactor(oauth): OAuth server tables through repositories
OauthClientsRepository/OauthTokensRepository/OauthConsentsRepository
replace OauthService's raw SQL (OA1-OA33). revokeChain's recursive CTE
and the oauth_clients join (its FK actually targets client_id, not the
row id the generated relation assumes) go through em.getKysely();
OA19's chain revoke is one nativeUpdate($in); OA12's consent grant is
em.upsert on the (client, user) unique key. revokeAllForUser built now
for Task 5. Every row-out read is disableIdentityMap: true; inserts go
through em.insert.
* fix(auth): non-numeric passkey and invite ids answer the legacy 404, never NaN; invite join type pinned
* fix(db): generator emits the referenced column for non-PK foreign keys; OAuth client joins through the relation; FK parity un-skipped
* refactor(db): TrekRepository base — every repository path validates the request context and reads bypass the identity map by default
* refactor(auth): AuthService and account cleanup through repositories
* refactor(oidc): OIDC identities and settings through repositories
* fix(auth): invite validation keeps expires_at null on the wire; password transaction scopes and reset-token burn pinned
* fix(server): plan 3b close-out — case folding on both sides for identifier lookups (non-ASCII login regression); coverage ratchet restored; repository scaffold and instanceof ratchet on TrekRepository; D-shape tests load-bearing
* refactor(server): trip-access primitives async at every caller
* refactor(trips): trip access through TripsRepository; demo seed in a request context; dialect helpers for the trips cluster
* refactor(days): days and day notes through repositories
* refactor(assignments): day assignments through repositories
* refactor(server): trip-membership, place-shadow, place-enrichment, place-photos and query helpers through repositories
* refactor(trip-members): membership, guests and the trip read model through repositories
* refactor(places): places, tags, ratings and place images through repositories
* fix(server): place-shadow source counts ordered in SQL; identity-map ratchets load-bearing; photo-cache race pinned
* refactor(places): import paths through repositories
* refactor(trips): trips through repositories
* fix(server): trip ids parsed once at the gate for places and assignments; NUL-safe value quoting on the SQLite platform; places parity tests completed
* refactor(trips): trip copy through repositories for the owned tables
* fix(server): plan 3c close-out — non-finite ids bound as NULL, trip id parsed once at every places/days/ws gate
Platform: NulSafeSqlitePlatform now renders a bound NaN as NULL and
+/-Infinity as 9e999/-9e999, matching better-sqlite3's own legacy binding
(rule 22 extension) — the program-wide fail-safe for any caller that still
passes an unguarded Number(untrusted) into a converted statement.
PlacesService.verifyTripAccess and RealtimeGateway.handleJoin stop doing
that: verifyTripAccess parses once with toRowId and threads the parsed id
through create/import/bulk/rating/export.gpx (deleting the seven
toRowId(tripId) ?? -1 sites), and handleJoin gets a Number.isFinite guard.
DaysService gets the same treatment across list/create/getDay/reorder/
insert/resyncAccommodationDays, closing the gap where a hex-spelled trip id
could renumber a real trip's days while the raw-bind inverted-accommodation
guard silently matched nothing.
DatabaseService.getTripTitle is deleted; PlacesService injects
TripsRepository directly and calls getTitle itself.
Template/cheap-item cleanup: DayAssignmentsRepository.listForTimeSort uses
$castTo instead of an unknown bridge; the duplicated TagRow interface in
Places.repository.ts is now imported from Tags.repository.ts;
AssignmentWithPlaceRow extends the guarded DayAssignmentRow instead of
restating its columns; PlaceShadowPicksRepository.totals drops its
unreachable ??-fallback branch; Places.repository.ts's updatePlace types
the NOT NULL name column as string; trip-members.service.ts's
transferOwnership threads one parsed trip id through all three writes and
corrects two stale "raw-bind seam" docstrings that were actually Number()
seams; a dead canAccessTrip mock is removed from reservations.e2e.test.ts.
Tests: the 23 new no-explicit-any warnings in TRIP-SVC-069 are typed
(lint back to 2416); HTTP and WS regression coverage for the non-finite
and non-canonical id shapes across places/days routes, mutation-proved;
TRIP-JOIN-005 asserts the exact concurrent-join settlement instead of
>= 1; a new tests/unit/db/transaction-yield.test.ts pins rule 24's
measured transaction-yield/dirty-read/nested-BEGIN behaviour.
* test(server): plan 3c close-out — copy-source full-row parity, Kysely rollback proofs, identity-map relabels, trips e2e on the snapshot DB
* fix(server): plan 3c close-out — days create/insert answer the guard 404 for non-canonical trip ids instead of 500; exact settlement and cross-request yield ratchets
* feat(server): plan 3d groundwork — dialect helpers, visibility predicate, feed and cron context ratchets
* refactor(roadtrip): roadtrip tables through repositories
* refactor(reservations): reservations, endpoints and travelers through repositories
* refactor(feeds): ICS feed tokens and anonymous feeds through repositories
* refactor(accommodations): stays through repositories inside the existing transactions
* test(server): plan 3d — MCP test helper constructors follow the accommodations and days services
* refactor(trips): trip copy through repositories for the roadtrip, accommodation and reservation tables
* refactor(calendar): calendar reads and reservation visibility through one predicate
* feat(server): plan 3e groundwork — packing visibility predicate, memories access-gate audit
* fix(server): plan 3d close-out — legacy text shape for stored accommodation ids restores the date-change restamp; reservation ids parsed once at the gate; parity tests for the reservation repositories
* refactor(photos): trek photos, memories access and cache sweeps through repositories
* refactor(files): trip files and file links through repositories, with transactions added
* test(server): plan 3e — hand-built FilesService, FilesRpc and AllowedFileTypesService calls follow the repository constructors
* refactor(memories): unified, immich and synology photo sync through repositories
* refactor(collab): notes, polls, messages and links through repositories
* refactor(budget): budget items, members, payers and settlements through repositories
* refactor(todo): todo items through repositories
* refactor(packing): packing items, bags and templates through repositories
* feat(server): plan 3f groundwork — systemNotices DI shape, TRAVELER_OWNS predicate, ntfy/storage-health specs, composite-PK pins
* refactor(school-holidays): country and region catalog through repositories
* refactor(notifications): in-app notifications and channel preferences through repositories
* refactor(notifications): reminder crons, mailer, ntfy and webhook transports through repositories
* fix(server): plan 3e close-out — repository registrations restore the boot; packing assignee and bag updates parse and no-op as legacy; coverage and scoping ratchets for the budget, packing and collab repositories
* refactor(vacay): vacation plans, entries, shares and holiday calendars through repositories
* refactor(system-notices): notice dismissals through a Nest provider and repository
* refactor(atlas): visited countries, regions and bucket list through repositories
* feat(server): plan 3g groundwork — GALLERY_CHRONOLOGICAL_ORDER Kysely ordering, unixEpochToIsoKysely helper, composite-PK DDL pins, JB5/R7 confirmations
* refactor(journey): journey and trip access control, CRUD and the trip-sync engine through repositories
* feat(server): plan 3h groundwork — date-offset dialect helpers, entity/repository fitness confirmations, pre-init and encryption pattern confirmations, survivor re-grep
* fix(server): plan 3f close-out — ntfy operator-scope test on the live send path; vacay date-offset and shift-order parity; todo reminder window; coverage and parity ratchets for the atlas and vacay repositories
* refactor(journey): journey stats, entries, photos, contributors and suggestions through repositories
* refactor(journey): public share links, TREK Studio books and the journal facades through repositories
* refactor(collections): access model, hydration, export/import and list CRUD through repositories
* refactor(server): journey-table survivors in trips, photos, memories, auth-cleanup and plugin-contributions through repositories
* refactor(integrations): dawarich connection, sync, tracks and review-flow through repositories
* refactor(collections): saved places, copy-to-trip, labels and invitations through repositories
* refactor(integrations,booking-import,airports,maps,route-usage): airtrail, booking import, airport backfill, maps cache and route-usage counters through repositories
* refactor(doc-sync): connections, reconciler and controller-SQL relocation through repositories
* test(integrations): add AirTrail saveSettings tx-asymmetry ratchet (Plan 3h Task 4 addendum)
* fix(server): plan 3g close-out — transactional book first-save, skeleton reconcile and share-link create; unknown-key entry patches are no-ops again; parity and authorization pins for the journey repositories
* feat(server): plan 3i groundwork — AuditLogRepository's reserved methods, the demo connection-swap spike, repository-fitness confirmations
* feat(server): plan 3j groundwork — scheduler onto CronRegistrarService, SDK-contract confirmation, repository fitness
* refactor(storage): backend/category config and usage stats through AppSettingsRepository; fix the seed-file test race and the shared-replica migration-flip gap
* refactor(share): public share links, the pre-init photo fallback, and collection-places survivors through repositories
* feat(server): plan 3j — the withCamelCase utility, unwired, pending a contract decision
* refactor(admin): user CRUD, stats, audit log, version check and addon config through repositories
* test(admin): pin createUser's pre-existing non-transactional uniqueness-check race (AD2-4)
* refactor(plugins): the trip-write role gate through a repository, in isolation
* refactor(demo,backup): seed and reset through DemoRepository, live-connection backup statements through MaintenanceRepository, isDemoUserId through an injected DemoService
* fix(server): plan 3h close-out — new-value-wins COALESCE restores stay/reservation propagation; doc-sync state filter truthiness; request-context and parity ratchets for share, doc-sync and the integrations
* refactor(plugins): runtime lifecycle, config CRUD and the uninstall cascade through repositories
* fix(server): plan 3i close-out — DemoModule imported where its service is consumed (e2e restored); admin addons list selects the provider relation; saveDemoBaseline awaited; backup tests on the maintenance repository
* refactor(plugins): outbound OAuth tokens and per-user plugin settings through repositories
* refactor(plugins): install-time gates, the capability-audit hash chain and the registry through repositories
* refactor(plugins): contribution-hook controllers, the small plugin controllers and the plugins-table survivors through repositories
* test(server): plan 4 — collapse mcp tool test harnesses onto the ORM snapshot
* test(server): plan 4 — collapse nest service test harnesses onto the ORM snapshot
* fix(server): plan 3j close-out — serialized audit-chain appends, atomic metadata and scheduler limits, rollback and race proofs for the plugin repositories
* refactor(server): plan 4 — convert the program's orphaned raw-SQL callers
* fix(server): plan 4 — un-skip PARITY-009 (FK deleteRule and index-name parity)
* refactor(server): plan 4 — inline canAccessTrip/isOwner off DatabaseService (trip-domain services)
* refactor(server): plan 4 — inline canAccessTrip/isOwner off DatabaseService (plugins + MCP surfaces)
* fix(server): plan 4 — RULE12 paren-count scanner ignores string literals
The entity generator's RULE12_fixGarbledCheckExpressions CHECK-expression
paren-balance scanner counted every `(`/`)` character regardless of
whether it fell inside a single-quoted SQL string literal. A CHECK
expression like `status IN ('confirmed)', 'tentative')` has a literal `)`
inside its first string value; the scanner would hit depth 0 at that
in-string character and truncate the expression, losing its own real
closing paren. The scanner now tracks single-quote string state (handling
the doubled `''` SQLite escape) and skips parens while inside one.
Latent-bug fix — no shipped entity's CHECK expression has hit this shape
yet (3d's ledger: "nothing affected today").
* refactor(server): plan 4 — unify the trip-access predicate's Kysely copies
TripsRepository.findForViewer/listForUser/activeTrip each hand-wrote the
identical trip-access boolean (t.user_id = ? OR m.user_id IS NOT NULL)
through the Kysely expression builder. Task 7's security review (M1)
evaluated a shared helper and set it aside for time, falling back to the
TRIPREPO-041 cross-method parity test as a regression guard instead.
Extracted the boolean into one generic helper, tripAccessExpr
(_shared/trip-access.ts), following the reservation-visibility.ts
publicReservationExpr precedent: fully generic over <DB, TB> since the
predicate has no correlated subquery, so it composes across
TripSelectKyselyDB and ActiveTripKyselyDB without needing a narrower
fixed-alias shape. The LEFT JOIN itself stays hand-written at each call
site — tripSelectQuery's own docstring already explains why a shared join
helper can't be typed across these differently-joined outer queries.
feeds.service.ts and memories-access.service.ts no longer duplicate this
predicate at all (Task 2's facade-inline sweep already converted both onto
TripsRepository.findAccessible/getFeedTokenIfReachable/
listReachableActiveTrips, which read through the canonical MikroORM
QueryBuilder form, accessibleTripsQuery) — the remaining duplication this
task closes is the three Kysely copies inside this file.
TRIPREPO-041 (64/64 in the file) stays green as the unification's own
regression guard.
* fix(server): plan 4 — trek_photo_cache_meta.cache_key NOT NULL
The column was a bare TEXT PRIMARY KEY, which SQLite does not implicitly
make NOT NULL (unlike an INTEGER PRIMARY KEY rowid alias). Every writer
(TrekPhotoCacheMetaRepository.upsertMeta, the table's only INSERT path)
has always bound a real string — 3e's R5 confirmed this. Appends a new
migration rebuilding the table with cache_key NOT NULL (SQLite has no
ALTER COLUMN, so this follows the same rebuild recipe
Migration20200101020000 uses in the opposite direction) and updates the
entity/generated metadata to match. Schema tightening, not a behaviour
change.
* refactor(server): plan 4 — retire the safely-convertible string-form where conditions (rule 23)
Places.repository.ts's existsInTrip/findInTrip/findRaw/reclaimInputs/
listByTripAndIds and Trips.repository.ts's findPublicForShare all took a
raw `.where('col = ?', [v])` string condition even though their id/trip_id
parameters were already plain `number` (or, for findPublicForShare,
narrowed to `number` here after confirming its one caller,
share.service.ts#getSharedTripData, only ever passes a number sourced
from a Kysely-typed share_tokens row, never an unconverted URL param) —
converted all six to MikroORM's typed `.where({...})` filter object.
The remaining raw string-form conditions in src/db/repositories/** are
NOT converted here: they are the `number | string` raw-bind seam
findAccessible/isOwner's own docstrings describe (trip_id/id threaded
through unconverted from req.params), which structurally requires the
deferred guard-level single toRowId parse to land first — narrowing any
of those methods' signatures now would either break the '0x10'/'007' id
parity those docstrings warn about, or duplicate the deferred item's own
work ahead of it landing.
* refactor(server): plan 4 — trek-photos.repository.ts finishes its rename
3e Task 6 renamed the CLASS (TrekPhotosRepository -> TrekPhotoRegistrationService,
since the name collided with the generated ORM TrekPhotos.repository.ts) but
left the FILE and its test file's names unchanged. Renames both to
trek-photo-registration.service.ts / .test.ts.
The old path is kept as a thin re-export stub (the src/websocket.ts shape)
rather than repointed at every one of its ~20 importers in this pass: several
of those files sit in two sibling tasks' exclusively-owned windows on this
shared branch (Task 3's budget/packing/todo/accommodations/places ripple,
reached through tests/helpers/plugin-host.ts and mcp-test-controllers.ts;
Task 5c's held-back tests/unit/services/{trekPhotoMedia,conflictUpdate}.test.ts)
and are off limits here. Flagged for a follow-up once those tasks land: delete
the stub and repoint every remaining importer at ./trek-photo-registration.service.
* fix(server): plan 4 — plugin discovery's delete+reinsert pairs are atomic
install/discovery.ts#upsert refreshed a plugin's actions and settings-field
descriptors as two independent delete-then-reinsert pairs (DI5-DI8) with no
transaction spanning either pair, let alone both: a crash between a delete
and its own reinsert left that plugin with an EMPTY actions or
settings-field set until the next discovery run, instead of its previous
still-valid rows. Wraps both pairs in one uow.transactional, so a discovery
refresh for a plugin's descriptors is now all-or-nothing.
Deliberate behaviour change, named for the user per the task brief.
DiscoveryRepos grows a UnitOfWork; PluginRegistryService (the other
production caller, registry.service.ts) picks it up the same @Optional()
way PluginRuntimeService already does, with the same guard-throw. Updates
the two hand-constructed test call sites that actually exercise discovery
(discovery.test.ts, registry.test.ts) to pass a real UnitOfWork.
* refactor(server): plan 4 — facade inline sweep part B (rosterUserIds/getPlaceWithTags)
Inline DatabaseService.rosterUserIds onto TripMembersRepository.rosterUserIds
directly in budget.service.ts, budget.mcp.ts and todo.service.ts, and
DatabaseService.getPlaceWithTags onto PlacesRepository.findWithTagsAndRatings
in accommodations.service.ts (placesRepo was already injected there).
BudgetService/BudgetMcp/TodoService collapse their constructors, dropping
the now-fully-unused DatabaseService param (budget.module.ts/todo.module.ts
register TripMembers on forFeature). PackingService keeps DatabaseService as
a vestigial param behind an optional TripMembersRepository with a fallback
in tripRosterIds: an in-flight Task 5c file
(tests/unit/services/conflictUpdate.test.ts) hand-constructs PackingService
positionally without the new repository, so its arity cannot change this
task; the fallback keeps that file's DatabaseService.rosterUserIds spy
working until Task 4 drops the param with the class itself.
* test(server): plan 4 — constructor ripple for the rosterUserIds/getPlaceWithTags inline
Hand-built BudgetService/BudgetMcp/TodoService call sites drop the removed
DatabaseService constructor arg (budgetRepoArgs() now appends a
TripMembersRepository so most spread call sites need no other change);
budget.service.test.ts's rosterHas() helper and svc() factory move from a
spied DatabaseService to a stubbed TripMembersRepository. The
AccommodationsService helper (tests/helpers/accommodations-service.ts) and
its two direct callers drop the same arg. PackingService call sites are
untouched (its new param is optional, so every existing hand-built instance
still resolves rosterUserIds through the DatabaseService fallback).
* fix(server): plan 4 — thread the discovery UnitOfWork through PluginRuntimeService too
Complements the just-landed discovery atomicity fix (DiscoveryRepos.uow):
PluginRuntimeService's own discoveryRepos getter still built the bundle
without a uow field. Threads its already-injected, @Optional() uow through
so its own onApplicationBootstrap/reload/dev-link discovery calls also get
the transactional DI5-DI8 refresh, not just PluginRegistryService's.
No throwing guard here, unlike PluginRegistryService's: several hand-built
partial-DI-graph test instances of this class (boot-registry-order.test.ts,
in a sibling task's held file window) construct it with uow omitted and
exercise onApplicationBootstrap's discovery call directly. Discovery must
never refuse outright just because a test built a partial graph, so it
degrades to the pre-existing untransacted sequence when uow is absent
(DiscoveryRepos.uow's own docstring covers this), the same "boot must
never block app init" defensiveness this file already applies elsewhere.
* fix(server): plan 4 — guard-level single parse: verify + correct the overclaiming verifyTripAccess docstring (L-2)
TripAccessGuard/TripOwnerGuard already parse :tripId exactly once
(Number(), guarded by Number.isFinite) and hand the resolved TripAccess
row to the handler via request[TRIP_REQUEST_KEY], TripOwnerGuard reusing
TripAccessGuard's own lookup when both are on the same route rather than
re-querying — verified by reading both guards directly, no change needed
there.
PlacesService.verifyTripAccess's own docstring separately claimed its
returned `tid` gets "returned... for every downstream call to reuse
(never re-parsing)" (3c's Task 9 review, L-2, carried to Plan 4). Reading
every call site (not assumed) shows this is false: `.tid` has exactly one
reader (PlacesController.requireTrip itself), which discards it — none of
requireTrip's 13 callers read `.tid` off the trip it returns; each passes
the original raw tripId string on to the write/read method it calls next,
which toRowId-parses it again itself. That second parse cannot be
eliminated by this gate alone: the same service methods are called
directly by places.mcp.ts too, an entry point with no requireTrip gate at
all (its own numeric tripId is re-stringified, String(tripId), to call
them), so each method owns its own id validation regardless of entry
point. Threading `tid` all the way through would mean giving every one of
~15 methods a second, number-only call shape for the REST path alone to
use — a real refactor, out of this docstring fix's own scope. Corrected
the docstring to say so plainly instead of repeating the false claim.
* refactor(server): plan 4 — relocate JS7/10/13/14 off the journey-share fallback stub
JourneyShareTokensRepository's own JS7/JS10/JS13/JS14 Kysely reads were a
3g Task 3 fallback (Task 2's JourneyPhotosRepository/JourneyEntriesRepository/
JourneyEntryPhotosRepository were still mid-flight). Now that those
repositories are stable, relocate: JS7/JS10 (photo/asset validation joins)
onto JourneyPhotosRepository (already injected into JourneyShareService as
photosRepo, no constructor change); JS13 (public entry list) onto
JourneyEntriesRepository.listPublicEntries; JS14 (public per-entry photo
read) onto JourneyEntryPhotosRepository.listForPublicJourney, deduped
against that repository's own JP_COLUMNS select list instead of a
hand-duplicated copy. JourneyShareService gains two new @InjectRepository
params (both already registered in journey-domain.module.ts's forFeature),
rippled through mcp-test-controllers.ts and journey-share.service.test.ts
(P04/P05 parity tests now pin the new homes).
* refactor(server): plan 4 — document unreachable ?? default arms after single-row aggregates
3f Task 7's fix wave flagged a cluster of `row?.x ?? default` arms after
unqualified, ungrouped aggregate reads (MAX/COUNT/COALESCE(SUM,0)) as
"same class as OauthClients:147" but left them unexamined per-site. Decided
per site: document, don't delete — TypeScript still types
executeTakeFirst()'s result as `| undefined` even though SQL guarantees
exactly one row for these unqualified aggregates, so the optional chain
can't be removed without a non-null assertion (worse, not safer). Six
sites: JourneyEntries.repository.ts (maxSortOrderForDate JG42,
countStatsPlaces JG67), JourneyEntryPhotos.repository.ts
(maxSortOrderForEntry JG91), JourneyPhotos.repository.ts (maxSortOrder
JG88/JG99), VacayEntries.repository.ts (sumFraction VC1, sumCompFraction
VC2). No behavior change — comments only.
* refactor(server): plan 4 — unify the two user-data-erasure enqueue paths
UserCleanupService.erasePluginUserData (the account-deletion transaction's
own UC2/UC3 enqueue) and PluginRuntimeService.enqueueUserErasure (the
emitUserDeleted sink's post-commit enqueue) independently walked the
identical SELECT id, permissions FROM plugins + JSON.parse + hook:user-data
filter + INSERT OR IGNORE — and both genuinely run for every account
deletion, since every emitUserDeleted call site (auth.service.ts,
admin.service.ts, trip-members.service.ts's guest removal) fires
immediately after deleteUserCompletely.
Extracted the shared filter into enqueueHookUserDataErasures
(nest/plugins/user-erasure-enqueue.ts) and pointed both call sites at it.
UC2/UC3 also come off DatabaseService onto PluginsRepository/
PluginUserErasureQueueRepository in the same change (they were the last
raw statements standing in the way of sharing one implementation) — this
narrows the Plan 3b Task 5 "stays raw, owned by Plan 3j" ruling to UC1
only (plugin_user_config/plugin_oauth_tokens/plugin_oauth_state), which
still stays raw, unaffected. UserCleanupService's orphan-data-directory
scan (a plugin uninstalled with data retained) has no equivalent on the
enqueueUserErasure side and stays there, now via the same repository.
Both enqueue calls still run per deletion (INSERT OR IGNORE keeps this
idempotent) — this unifies the IMPLEMENTATION, not the call count; not
touching the emitUserDeleted event-sink wiring itself was a deliberate,
smaller-blast-radius choice for this task.
* refactor(server): plan 4 — narrow TripMembersRepository.remove/TripsRepository.setOwner to number
Both accepted trip_id: number | string per 3c's carry note (their "stays
loose for other callers" reasoning), pending the guard-level single parse
landing first. Re-checked every caller directly: setOwner's one production
caller (trip-members.service.ts#transferOwnership) already passes trip.id,
a real number resolved earlier in the same transaction; remove's callers
are trips.rpc.ts (num(), already a validated number), trips.mcp.ts (Zod-
typed tool input, already a number) and TripMembersController.removeMember
(the one genuine raw-string caller, :id off the route with no class-level
TripAccessGuard on this controller by design).
TripMembersController.removeMember now parses :id once (toRowId, not
Number() — rule 15's NaN-into-SQL trap) and threads the parsed number to
both its own access check and removeMember, instead of passing the raw
string through twice. TripMembersService.removeMember and both repository
methods narrow to number accordingly; setOwner's WHERE also moves off its
raw-bind escape hatch onto nativeUpdate now that trip_id is typed, and
remove's trip_id half moves onto a typed .where({ trip: trip_id }) filter
(user_id keeps its own raw bind — a different, still-live NaN-safety seam,
unrelated to this narrowing).
TRIPREPO-018 and TMEMREPO-023, which pinned the retired string-bind seam
on setOwner/remove, no longer typecheck against the narrowed signatures
and are removed with an explanatory comment in their place.
* refactor(server): plan 4 — U6 gate-level id parsing for todo item ids
Rule 21's carry from 3e Task 8's review: TodoController.update/.remove
passed the raw :id route string all the way to TodoItemsRepository,
relying on SQLite's column-affinity CAST to match it instead of a typed
filter. Parse :id ONCE at the controller (toRowId, matching Task 8a's
TripAccessGuard/removeMember shape), 404 on a non-canonical id, and thread
the number down through TodoService.updateItem/deleteItem into
TodoItemsRepository.findInTrip/existsInTrip/update/deleteById, all
narrowed from number | string to number. todo.rpc.ts's num()-derived
todoId no longer needs its String() wrapper. tripId stays string | number
— a separate, already-accepted carry (23c292f2f). Two new e2e tests pin
the non-numeric-id 404 at the gate.
* test(server): plan 4 — full-key parity tests for ShareTokensRepository (3h L4)
3h L4's carry: ShareTokensRepository (SH1-SH6/SH17/UC6) had zero tests.
17 cases pinning every read against the legacy statement run raw on the
same connection — findRawByTrip/findTokenByTrip with every nullable
column both null and set, findValidByToken/findTripAndShareMapByToken/
findTripIdByToken's shared token+expiry predicate (valid, future-expiry,
past-expiry, unknown token), plus insertNew/updateFlagsByTrip/deleteByTrip/
deleteByCreator's write correctness (deleteByCreator's cross-trip erasure
kept distinct from deleteByTrip's single-trip scope, per the repository's
own docstring). The listPublicForShare family (the other half of 3h L4)
is a separate, larger carry — not in this file.
* test(server): plan 4 — full-key parity for Reservations share/public-api reads (3d carry)
Task 8b-2 item 1 (partial): the 8 share.service.ts/public-api.service.ts
reads on ReservationsRepository flagged by the 3d Task 7 review as having
no repository-level toEqual(<legacy raw>) coverage (listEndpointsForShare,
listDayPositionsForShare, listPublicForShare, listPublicAccommodationsForShare,
listScheduledForPublicApi, listUnscheduledForPublicApi,
listAccommodationsForPublicApi, listUnplannedPlacesForPublicApi). 12 new
cases against the legacy statement run raw on the same connection.
* test(server): plan 4 — concurrency pins for boundaries-upsert and token-mint races (3d carry)
Task 8b-2 item 2: R7's two remaining un-transacted-statement races flagged
by the 3d Task 7 review (L4) but never pinned — RoadtripDayBoundariesService
.save's belongs-check-then-upsert, and FeedsService.generateTripToken's
read-then-write. Both tests pin today's actual outcome (an atomic ON
CONFLICT upsert survives cleanly; the token mint has a last-write-wins
loser) with the same concurrent-request-shape Promise.all/allSettled
pattern roadtrip.service.test.ts's existing R7 vias pin uses. Not a fix.
* test(server): plan 4 — full-key parity for Days/DayAssignments/Places roadtrip reads (3d carry)
Task 8b-2 item 1 (remainder): the 3 non-share/public-api reads from the 3d
Task 7 review's missing-parity list — DaysRepository.listPlanDays (RPL1),
DayAssignmentsRepository.listRoadtripVisits (RPL2, the correlated-subquery
LEFT JOIN), and PlacesRepository.isTrackInTrip (RT13, the review's
"findTrackInTrip" — the actual method name). Completes the 11-file carry
together with 434113937's 8 share/public-api reads.
* test(server): plan 4 — dedupe overlapping listPlanDays/isTrackInTrip parity blocks
235f03665 landed two versions of the same DaysRepository.listPlanDays and
PlacesRepository.isTrackInTrip parity coverage side by side (a merge
artifact from concurrent work on the same carry item). Keeps one block per
method, drops the duplicate describe/it blocks and their colliding test ids.
* test(server): plan 4 — budget calc suite onto real repositories (3e carry)
* test(server): plan 4 — at-rest encryption pins for AirTrail/doc-sync/webhook secrets (3h L3)
Task 8b-2 item 4: the three credential columns the 3h Task 7 review flagged
as having no at-rest pin — users.airtrail_api_key (AirtrailService#saveSettings),
document_connections.secrets (DocSyncConfigService's whole-secret-map
column), and trip_document_links.webhook_secret (createLink's per-binding
mint). Each test saves through the real service, reads the raw column via
better-sqlite3, asserts it is enc:v1:-prefixed ciphertext that never
contains the plaintext, and asserts the service's own decrypt path rounds
it back to the original value.
* test(server): plan 4 — at-rest encryption pins for AirTrail/doc-sync secrets (3h L3 carry)
Task 8b-2 item 4: the 3h Task 7 review's L3 finding ("users.airtrail_api_key
has no at-rest pin", "document_connections.secrets ... has no enc:v1: check",
"trip_document_links.webhook_secret - no at-rest pin"). Three targets, each
proven by reading the raw column and asserting the stored value is
enc:v1:-prefixed ciphertext that round-trips, never the plaintext:
UsersRepository.setAirtrailSettingsWithKey/getAirtrailConnRow at the
repository layer, AirtrailService.saveSettings/getAirtrailCredentials at the
service layer, and DocSyncConfigService's connection secrets map plus
createLink's webhook secret.
* test(server): plan 4 — drop duplicate AirTrail encryption repository test
Task 8b-2 item 4 follow-up: 6965869dd already covers
UsersRepository.setAirtrailSettingsWithKey/getAirtrailConnRow's at-rest
ciphertext at the service layer (airtrail.service.test.ts's
AIRTRAIL-SVC-ENC-001/002) plus the doc-sync secrets/webhook pins
(DOCSYNC-ENC-001/002); this repository-level file duplicated the same
AirTrail assertion a second time.
* test(server): plan 4 — atlas read-model parity remainder (3f L6 carry)
Task 8b-2 item 3 (atlas half): full-key toEqual(<legacy raw>) coverage for
the atlas read models the 3f Task 7 review's L6 finding listed as missing
(minus AT1/TRAVELER_OWNS-consumer, already landed) — AT2 (Places.
listForTripIds), AT3/AT28 (PlaceRegions.listCountryCodesForPlaceIds/
listForPlaceIds), AT5/AT10/AT43 (VisitedCountries.listCodesForUser/
listForUser), AT21/AT24/AT25 (VisitedRegions.listForUser/
listRegionCodesForCountry/findCountryCode), AT22 (HiddenRegions.listForUser),
AT23/AT40/AT44 (PlaceRegions.listDistinctRegionCodesForCountryAndPlaces/
countPlacesByCountryForTrip/listVisitedCountryCodesForUser), AT30/33/34
(BucketList.listForUser/findById/findForUser), AT41 (Places.
listAddressesForUser), AT42 (Trips.countTripsAndDaysForUser). New standalone
files for HiddenRegions/VisitedCountries/VisitedRegions/PlaceRegions, which
had none. AT6/45/46 (the TRAVELER_OWNS endpoint reads) are proven on ids
only by the existing consumer test — full-row parity for those three is
NOT done here (carried forward, same as the review's own open item).
* test(server): plan 4 — vacay read-model parity remainder (3f L6 carry)
Task 8b-2 item 3 (vacay half): full-key toEqual(<legacy raw>) coverage for
the vacay read models the 3f Task 7 review's L6 finding listed as missing
(minus VC81/82, already landed) — VacayPlans.findByOwner/findById (the
getPlanData/getStats composite's own plan read), VacayYears.listForPlan
(listYears), VacayCompanyHolidays.listForPlan (the company-holidays list),
VacayHolidayCalendars.listForPlan/findById (holiday-calendar reads),
VacayUserSettings.findForUser (user year settings), VacayUserYears.
findForYear (getStats rows, including the NULL vacation_days case the
review named explicitly), and VacayPlanMembers.listAvailableForFusion/
listPendingForPlan/listPendingForUser (the fusion and share pickers). Seven
new standalone files — only VacayShares had a repository-level test before
this. getSharedCalendars itself is a service-level composite over these
same reads plus VacayCompanyHolidays.listDatesForRange (already exercised
elsewhere); its own dedicated test is NOT added here.
* test(server): plan 4 — full-key parity for PackingItemsRepository.listPublicForShare (3h L4)
Task 8b-4a: no repository-level toEqual(<legacy raw>) coverage existed for
the share.service.ts SH13 read. Seeds Common items with every nullable
column both null and set, plus Personal and Shared-with-people items on
both sides of the is_private/owner/recipient predicate, and proves only
the Common tier surfaces.
* test(server): plan 4 — full-key parity for BudgetItemsRepository.listPublicForShare (3h L4)
Task 8b-4a: no repository-level toEqual(<legacy raw>) coverage existed for
the share.service.ts SH14 read. Seeds two items — every nullable column
set and every nullable column null — plus a foreign-trip item, and proves
the ORDER BY category ASC shape (unlike BG72's listAllForTrip, which has
none).
* test(server): plan 4 — full-key parity for CollabMessagesRepository.listPublicForShare (3h L4)
Task 8b-4a: no repository-level toEqual(<legacy raw>) coverage existed for
the share.service.ts SH16 read. Seeds a root message, a reply (reply_to
set), a deleted message (must be excluded) and a foreign-trip message, and
proves the narrower username/avatar-only join shape (no reply_text/
reply_username, unlike joinedQuery).
* test(server): plan 4 — full-key parity for PlacesRepository.listPublicForShare (3h L4)
Task 8b-4a: no repository-level toEqual(<legacy raw>) coverage existed for
the share.service.ts SH12 read. Seeds a categorised place with every
nullable column set and an uncategorised place with every nullable column
null, plus a foreign-trip place, and proves the named 20-column allow-list
never leaks an owner-only column (reservation_status, google_place_id,
…).
* test(server): plan 4 — full-key parity for DayAssignmentsRepository.listPublicForShare (3h L4)
Task 8b-4a: no repository-level toEqual(<legacy raw>) coverage existed for
the SH9 read. Seeds assignments across multiple days (one excluded day_id
never leaks in), every nullable place/assignment column both null and
set, and proves the six owner-only columns SharePublicAssignmentRow omits
(google_place_id, google_ftid, osm_id, amap_poi_id, stop_type,
fill_percent) never appear on the row at all.
* test(server): plan 4 — collapse remaining test harnesses; triage legacy migration tests
* test(server): plan 4 — todo controller test expects the gate-parsed item id (U6 follow-up)
* fix(server): add the missing numbered migration for the booked-night reseat step (#242)
reseatBookedNights (legacy step 242) was never invoked from any shipped
MikroORM migration -- only from the retired db/migrations.ts array --
so an install upgrading through the numbered chain never got the
one-time reorder. Adds Migration20200101040300, which calls the frozen
function through the native better-sqlite3 handle so it runs inside
the migration's own transaction.
orm-driver.ts's BoundSqliteConnection now also captures that handle
onto the field SqliteConnection.getNativeClient() reads, which its
createKyselyDialect() override previously left unset -- needed for
this migration (and any future one) to reach it in production, not
just under the bare test driver.
RESEAT-009 moves off the legacy createTables+runMigrations builder
onto the real Migrator via tests/helpers/migration-step.ts, plus a
new fresh-install guard (RESEAT-011).
* test(server): plan 4 — swap 4 of 5 straggler nest test harnesses off legacy schema builder
day-notes.service.test.ts, public-api-scopes.test.ts,
registration-invites.service.test.ts, trip-invite.service.test.ts onto
createSnapshotTestDb() via the async vi.mock idiom (5a/5b/5c precedent),
dropping their own hand-rolled createTables()+runMigrations() harness.
trip-invite.service.test.ts and registration-invites.service.test.ts
also drop their now-redundant DatabaseService wrapper (its .connection
was always just the same test db handle). expect( assertions unchanged.
user-cleanup.service.test.ts held back: its constructor call was
updated to match UserCleanupService's new EntityManager-based shape,
but deleteUserCompletely() now deadlocks against a real UnitOfWork
(reproduced in isolation, independent of this test file -- see the
report), which looks like a genuine bug in erasePluginUserData's new
MaintenanceRepository(em) call versus UnitOfWork.transactional(), not
a test-harness problem.
* test(server): plan 4 — move auto-backup.test.ts and demo-reset-path.test.ts off createTestDb()
Both build a schema db while 'fs'/'node:fs' are mocked (wholesale in
auto-backup.test.ts, selectively spied in demo-reset-path.test.ts) for
their own archiver/filesystem assertions, which broke
createSnapshotTestDb()'s read of the schema snapshot through
schema-snapshot.ts's own fs import.
auto-backup.test.ts: fs is mocked wholesale, so the snapshot db is now
built via a small helper that points fsMock's three calls at the real
filesystem (fetched through vi.importActual, bypassing the mock) just
long enough to build the db, before the test installs its own
existsSync stub -- never touching schema-snapshot.ts itself.
demo-reset-path.test.ts: fs.existsSync is selectively spied to answer
only for the baseline path, so the db is now built before that spy is
installed instead of after.
* test(server): plan 4 — retire the legacy-runner-only migration hygiene checks
migration-hygiene.test.ts deleted outright: every block in it (the
destructive-op allowlist, the empty-catch guard, the full-chain smoke)
scans or runs the legacy db/migrations.ts array being deleted this
plan, never the numbered src/db/migrations/*.ts chain, so there is
nothing in it to carry forward.
leg-mode-incoming.test.ts: deleted its first describe block (the
legacy-runner column-add + replay-safety smoke, also against
db/migrations.ts); the read-path parity block, already on the modern
createSnapshotTestDb() harness, is untouched.
* chore(server): delete the legacy schema/migration/seed builders
MikroORM's migrations are the only schema source now, including for
tests: src/db/schema.ts, src/db/migrations.ts and src/db/seeds.ts are
gone, along with tests/unit/db/schema-parity.test.ts (the parity gate
that guarded them, already red on 8a's cache_key NOT NULL) and
createTestDb() + its now-dead imports out of tests/helpers/test-db.ts
(its last two callers moved onto createSnapshotTestDb() this plan).
Their three entries drop from eslint.config.mjs's better-sqlite3
allow-list -- the files they exempted no longer exist.
Ruling 7's frozen files (migration-utils.ts, reseat-booked-nights.ts,
document-provider-seed.ts) and every numbered migration in
src/db/migrations/ are untouched.
Precondition grep (server/tests + server/src, from the task brief) is
now empty:
grep -rlE "from ['\"].*db/schema['\"]|from ['\"].*db/migrations['\"]|from ['\"].*db/seeds['\"]" server/tests server/src --include="*.ts"
* docs: plan 4 — the repository layer is the only data access path
DatabaseService/DatabaseModule are gone; queries go through repositories
(server/src/db/repositories/) and UnitOfWork (server/src/nest/database/
unit-of-work.ts) for transactions. MikroORM's migrations are the only
schema source, including for tests — the hand-kept schema.ts/migrations.ts/
seeds.ts test builders and their parity test are deleted. Documents the
db/database.ts (connection only) / db/orm-driver.ts (bound driver) /
UnitOfWork / repository shape, withRequestContext for non-HTTP entrypoints,
the better-sqlite3 ESLint restriction, and the entity generator (gen:entities/
check:entities) as the schema-parity guard. Corrects two stale nest/README.md
mentions (realtime.gateway.ts's now-repository constructor, the BE-Phase 1
trip-access bullet) and marks the legacy src/services/ migration recipe as a
historical changelog rather than current guidance.
* refactor(server): plan 4 — drop the 13 vestigial DatabaseService params/getters
Removes the now-dead DatabaseService injection (or private get db() getter)
from addons.service.ts, trips.service.ts, trip-invite.mcp.ts,
place-photo-cache.service.ts, trek-photo-registration.service.ts,
categories.mcp.ts, journey-domain.service.ts, plugins.service.ts,
plugin-runtime.service.ts, plugin-mcp-tools.service.ts, places.service.ts
and packing.service.ts — every one of them was fully repository-backed
already (Task 2/3's facade inline sweep), just still carrying the param.
PackingService's TripMembersRepository is required now (the
this.db.rosterUserIds fallback is gone with it) and PluginRuntimeService's
uow is no longer @Optional() — both moved ahead of the optional
registry?/hostFactory? params, since TypeScript refuses a required
parameter after an optional one; install/discovery.ts's DiscoveryRepos.uow
is required to match, and its upsert() always runs the descriptor
refresh inside one transaction instead of falling back to an
un-transacted sequence.
user-cleanup.service.ts's UC1 (the one genuinely live raw site, Plan 3b's
"stays raw" plugin-table trio) moves off DatabaseService onto a new
MaintenanceRepository.deletePluginUserData method — the rule-4-permitted
connection.execute() home, built from a directly-injected EntityManager.
Threads the active UnitOfWork.transactional's transaction context through
execute()'s ctx param: without it, a raw connection.execute() call issued
from inside deleteUserCompletely's open transaction contends for the same
single-connection checkout the transaction already holds and deadlocks
(never released, since the transaction is itself awaiting the call).
tests/unit/db/transaction-yield.test.ts's probe B already pinned this
exact hazard class for a raw better-sqlite3 statement; this is the same
mechanism reached through the ORM's connection pool instead.
nest/photos/trek-photos.repository.ts (the Plan 4 Task 8a re-export shim)
is deleted, with every importer repointed to trek-photo-registration.service
directly. The ~7 files that only imported the TripAccess/PlaceWithTags
type re-export from database.service.ts now import them from
Trips.repository.ts/Places.repository.ts directly, the actual single source.
* refactor(server): plan 4 — delete DatabaseService, DatabaseModule and database.tokens.ts
Grep gate confirmed zero src/ importers of DatabaseService left outside
these three files (Task 1/2/3's earlier conversions + this task's own
vestigial-param sweep). Deletes database.service.ts, database.module.ts
and database.tokens.ts, drops DatabaseModule from app.module.ts's imports
and the five other modules that still listed it
(accommodations/calendar/doc-sync/feeds/trip-members) — none of them had
a live DatabaseService injection left, so the import was already dead.
OrmModule is the module that survives DatabaseModule's deletion, per the
Phase 0 ledger's own ruling; untouched.
db/database.ts's `db` Proxy export itself stays, deliberately: ~190 test
files' vi.mock('…/db/database', …) factories return a { db: <mock
handle>, … } shape, and their own `import { db as testDb } from
'…/db/database'` is typed against this file's real exports regardless of
the runtime mock — vi.mock swaps the module at runtime, but tsc resolves
the import statically. Deleting the export would fail typecheck:tests
across the whole suite for a test-harness idiom this task's file set
doesn't own (Track B's territory). src/ has zero remaining importers, so
the ESLint no-restricted-imports gate this task also shrinks still holds
this file to its permanent allow-list entry either way.
* test(server): plan 4 — repoint the test suite off the deleted DatabaseService/DatabaseModule
Mechanical follow-through of the previous two commits across ~110 test
files:
- The 41 tests/e2e/*.e2e.test.ts suites composed DatabaseModule into their
partial Test.createTestingModule graphs; the import and the array entry
are dropped (nothing in any composed domain module injected
DatabaseService any more, so the entry was already dead weight).
- The shared test helpers (mcp-test-controllers.ts, plugin-host.ts,
accommodations-service.ts, notifications.ts, test-addons.ts,
test-uow.ts) each held a DatabaseService/DatabaseService-shaped param
used only for its raw better-sqlite3 handle; every one now takes that
handle directly, and every constructor call site the helpers make
(PackingService, PlacesService, JourneyDomainService,
PlacePhotoCacheService, TrekPhotoRegistrationService, TripsService,
UserCleanupService, AddonsService, PluginsService, PluginRuntimeService)
drops the removed param and, where PluginRuntimeService's uow is
involved, reorders it ahead of the optional registry?/hostFactory?
params to match the real constructor.
- ~60 further unit/integration test files hand-constructed one or more of
those same services directly; same fix, file by file. Four of them
(memories-access.service.test.ts, places.directions.test.ts,
places.service.test.ts, unified-memories.service.test.ts) also drop a
vi.spyOn(DatabaseService.prototype | instance, 'canAccessTrip' | 'isOwner'
| 'rosterUserIds' | 'getPlaceWithTags') spy left over from when those
methods delegated through DatabaseService — dead now that the services
read the owning repository directly.
- database-service.test.ts and database-service.delegation.test.ts tested
DatabaseService directly and are deleted with it.
- tests/unit/db/transaction-yield.test.ts's probe B, which pinned a raw
DatabaseService statement's dirty-read behaviour inside an open
transaction (rule 24), now issues the same raw better-sqlite3
statement directly against the shared test handle — the exact shape
DatabaseService.get/run used to wrap (this.conn.prepare(sql).get/run(),
bypassing MikroORM/Kysely entirely) — so the hazard it documents is
unchanged. Verified still green.
No expect(...) assertion changed in any file; only construction/import
plumbing. typecheck, typecheck:tests and the full touched-file run
(101 files / 2668 tests) are green, plus the compiled boot
(bootstrap.test.ts + boot-sweeps-request-context.test.ts) and one real
e2e boot file (trips.e2e.test.ts).
tests/unit/nest/user-cleanup.service.test.ts is deliberately NOT in this
commit — see the next one.
* test(server): plan 4 — finish user-cleanup.service.test.ts's harness swap; regression-test the UC1 transactional deadlock fix
This file arrived already modified and unstaged in the shared tree —
Task 6 (the parallel legacy-schema-deletion task) had swapped its DB
harness onto createSnapshotTestDb() and updated the UserCleanupService
construction to this task's new EntityManager-first shape while landing
its own commits. Finished here: USER-CLEANUP-005 ("survives a slim
schema without the plugin tables") passed a fake `{} as unknown as
EntityManager`, which doesn't reach the real UC1 path any more (the
previous raw DatabaseService.run swallowed everything in a try/catch
regardless); it now builds a real EntityManager bound to the slim
handle via sharedTestOrm(slim), so the per-statement query against the
missing plugin_user_config/plugin_oauth_tokens/plugin_oauth_state
tables is what's actually being proven caught, not a construction-time
throw.
USER-CLEANUP-006 through -010 (deleteUserCompletely, all of them
exercising UC1 inside the real uow.transactional wrap) are the
regression test for the previous commit's deadlock fix in
user-cleanup.service.ts/MaintenanceRepository.ts: before that fix, every
one of these hung and timed out. Green now, verified directly.
* chore(server): plan 4 — shrink the better-sqlite3 ESLint allow-list
Per ruling 6: database.service.ts's entry comes off (the file is
deleted). The five plugin entries (plugin-route-normalize.ts,
plugin-host-state.ts, install/discovery.ts, settings-defaults.ts,
signature-status.ts) come off too — re-verified none of the five import
better-sqlite3 or DatabaseService any more (3j's own conversion). The
src/demo/** blanket entry was already gone (3i's own task landed it).
reseat-booked-nights.ts and document-provider-seed.ts stay, with the
`// TODO(plan 4)` comment corrected: they're frozen forever (ruling 7),
invoked from inside numbered, already-shipped MikroORM migrations, never
Plan 4's or any future plan's to touch.
Permanent allow-list after this commit: src/db/database.ts,
src/db/orm-driver.ts, src/db/durability.ts (the driver homes),
src/nest/plugins/host/plugin-data.service.ts (3j's R-out-of-scope — a
plugin's own sqlite file is never TREK's schema), src/nest/backup/backup.impl.ts
(3i's R1, exactly the untrusted-upload-file probe), src/db/reseat-booked-nights.ts
and src/db/document-provider-seed.ts (frozen forever). src/db/{schema,migrations,seeds}.ts
entries were already removed by Task 6 when it deleted those files.
0 new lint errors; warning count unchanged at 2123 (well under the 2247
lean-gate ceiling) — every file the shrink touches was already fully
converted.
* refactor(server): plan 4 — U6 gate-level id parsing for budget item/settlement ids
Rule 21's 3e carry, same discipline 218f75d0f applied to todo: every
:id/:settlementId/:userId route param in BudgetController is parsed ONCE at
the gate with toRowId, matching the legacy affinity-seam "not found" outcome
for a malformed id on each route (404 'Budget item not found'/'Settlement
not found', except toggleMemberPaid — the one legacy handler that never
404'd an unknown item/member either, so a malformed id there skips the write
and keeps the same 200 { member } + Number(id)/Number(userId) broadcast
shape it always had).
The parsed numbers thread down through BudgetService's update/updateMembers/
setPayers/toggleMemberPaid/remove/updateSettlement/deleteSettlement (and
their updateBudgetItem/deleteBudgetItem/setItemPayers/getBudgetItem/
applySettlementUpdate/getSettlement internals) into BudgetItemsRepository's
getCurrency/findInTrip/existsInTrip/findForDelete/findById/update/deleteById
and BudgetSettlementsRepository's findWithUsers/findGuard/update/deleteById,
all narrowed from number | string to number; trip_id stays loose, a
separate, already-accepted carry. costs.rpc.ts's num()-derived itemId no
longer needs its String() wrapper on the update/delete calls; budget.mcp.ts
was already Zod-typed to number throughout. Two new e2e tests pin the
non-numeric-id 404 at the gate; controller/service unit tests cover the
narrowed call args and the toggleMemberPaid malformed-id parity case.
* refactor(server): plan 4 — U6 gate-level id parsing for packing item/bag/template ids
Rule 21's 3e carry, same discipline 218f75d0f applied to todo: every
:id/:bagId/:templateId/:userId route param in PackingController is parsed
ONCE at the gate with toRowId, matching the legacy affinity-seam "not found"
outcome for a malformed id on the routes with a pre-ORM Express precedent
(update/remove -> 'Item not found', updateBag/deleteBag/setBagMembers ->
'Bag not found', applyTemplate -> 'Template not found or empty').
#858's sharing/contributors routes (setSharing/clone/addContributor/
removeContributor) are native Nest code with no pre-ORM precedent (landed in
7eabf6066, after the migration) — a malformed id there just 404s the same
way an unknown one already does. removeContributor's :userId used to reach
contributorsRepo.deleteOne through a bare Number.parseInt(), the exact
NaN-into-SQL trap row-id.ts documents; it now parses through toRowId too.
The parsed numbers thread down through PackingService's updateItem/
setItemSharing/addContributor/removeContributor/cloneItem/deleteItem/
getItemPrivacy/updateBag/deleteBag/setBagMembers/applyTemplate, all narrowed
from number | string to number; tripId stays loose, a separate,
already-accepted carry. PackingItemsRepository's getPrivacy/findVisibleInTrip/
update/updateSharing/delete/findById, PackingBagsRepository's findInTrip/
update/findWithAssignee/delete and PackingTemplateItemsRepository.listForApply
narrow the same way. packing.rpc.ts's num()-derived itemId/bagId no longer
need their String() wrappers on the update/delete/updateBag/deleteBag/
setBagMembers calls; packing.mcp.ts was already Zod-typed to number
throughout. Two new e2e tests pin the non-numeric-id 404 at the gate;
controller/rpc unit tests cover the narrowed call args and the
removeContributor malformed-userId parity case.
AdminPackingTemplatesController (/api/admin/packing-templates) is out of
scope — a separate admin-gated surface with its own string-typed template
CRUD, not part of this trip-scoped controller's :id chain.
* test(server): plan 4 review — three pins catch up with the gate-parsed ids and the cache_key NOT NULL (M1–M3)
* fix(server): boot baselines legacy-runner installs before running MikroORM migrations (B1)
An install the retired positional runner migrated has a schema_version row
and no mikro_orm_migrations rows, so its first boot on this branch replayed
all 244 migrations over an already-migrated schema: eight refuse the boot,
and the replay-safe ones overwrite user data (step 26 rewrites every
day_assignments.assignment_time).
runSchemaBootstrap now records the baseline plus every migration whose
"Legacy migration step N" docstring is <= schema_version as executed, in one
transaction through the migrator's own storage, before the ordinary run
applies the rest. The step map is derived from the discovered migrations'
source, never hand-kept, and anything unmappable (a newer or malformed
schema_version, a duplicated, missing or out-of-order step) refuses the boot.
* test(server): boot the app on three legacy-runner fixtures to pin the B1 baseline
SQL dumps of databases the retired runner itself built: schema_version 205
(main at fa406b708), 242 (417d0445b, the runner's last commit) and 82
(v2.9.14, so seven of the eight non-replay-safe migrations still lie ahead
and run for the first time). Each gets canary rows: user-set assignment
times and a booked night.
buildApp() on each asserts the baseline and the applied rest in order, the
assignment times untouched, the booked-night reseat run exactly once on 205
and 82 and not at all on 242, schema_version kept, no half-built *_new
table, a schema identical to a fresh install's, and an idempotent re-run.
* refactor(server): demo-reset reads the live path off getRawConnection, not the db Proxy (m1)
demo-reset.ts was the one src/ consumer of the db Proxy left, reached
through a runtime require that a grep on `from` misses. It now imports
closeDb/getRawConnection/reinitialize statically, the way backup.impl.ts
does, so the Proxy genuinely has no src/ importer (the claim in database.ts
and server/CLAUDE.md now holds). The path test mocks the module with vi.mock
instead of teaching Node's require loader to answer for a .ts file.
* test(server): renumber the duplicate ASSIGNREPO/PLACEREPO test ids Plan 4 introduced (m3)
ASSIGNREPO-031/032 (the legacy-statement parity pair) become 034/035, and
the later PLACEREPO-030..038 block becomes 053..061, the next free ids, so
each id names one test again. No test body changes.
* refactor(server): derive the two restated public row types instead of copying their columns (m4)
JourneyPublicEntryPhotoRow restated JourneyPublicGalleryRow's nineteen
columns with only the parent key changed; it is now that row with
journey_id swapped for entry_id. PublicApiAssignedPlaceRow and its Kysely
table shape restated PlaceRow's columns; both now Pick them off PlaceRow.
Types only. The review's CPD method over Plan 4's new src lines drops from
about 3.4% to 0.64%.
* test(server): full-key parity for TripsRepository.findPublicForShare and VacaySharesRepository.listAvailableForShare (m5)
Neither read had any test reference. Each is now pinned with
toEqual(<legacy statement run raw on the same connection>), the
listPublicForShare family shape: SH7 on a filled and a NULL-heavy trip plus
a missing id (TRIPREPO-067/068), and VC90 over one world exercising every
exclusion (caller, guest, existing share, plan owner, accepted member) and
a missing plan.
* fix(server): the legacy baseline runs createTables() instead of marking it, atomically with the run (N1)
The legacy runner ran the running release's createTables() on every boot
before its pending steps, and about 30 tables exist only there. Marking the
baseline migration as executed left installs older than those tables (below
legacy step 68) failing with "no such table: photo_provider_fields" and, since
the rows were committed before the run, stuck half-baselined for every later
boot.
Only steps 1..N are recorded now, so the baseline's IF NOT EXISTS DDL runs
first, as the legacy boot did. The rows are logged inside the same
transaction as migrator.up({ transaction }), so a failed first boot records
nothing and the next boot baselines again.
A v66 fixture (the runner at 5be2e9b26) boots: 66 recorded, 178 applied,
canaries kept. Its two schema differences from a fresh install
(users.immich_access_token, reservations.accommodation_id INTEGER) come
from the legacy chain itself and are pinned as carried.
* fix(deps): sync the lockfiles with the bumped manifests and follow lucide's icon renames
feat/orm raised react to ^19.3.0 and several plugin-sdk dependencies without
regenerating the lockfiles, so npm ci failed on every CI job. The root
overrides now pin react 19.3.0, both lockfiles are regenerated with npm 11,
and the tests that select lucide icons by their old class names use the
current ones. Two tests cover the Immich prefs reads and the boot restore
branch that the coverage thresholds were missing.
* ci: give the server lint step an 8 GB heap for the type-aware rules
* test(server): keep the no-promise-as-value rule tester out of single-run mode on CI
With CI=true typescript-eslint infers single-run mode, builds the program
from the fixture file on disk and ignores the code each case passes in, so
all 24 invalid cases reported nothing on the runner. Both testers now set
disallowAutomaticSingleRunInference.
* refactor(server): name the new migrations after the first seven words of their purpose, like the rest
* fix(server): keep tsx a production dependency so image key rotation can load it
* test(server): re-pin the repositories branch floor at the measured 89.83%
* test(planner): keep the sidebar fixtures on past dates so the jump to today never fires in jsdom
* test(server): keep console output for failing tests only and teach Nest's logger LOG_LEVEL
* test(client): keep console output for failing tests only and answer the health probe
* test(client): drop the health handler, it races the admin page's first load
* chore(sonar): assert explicitly in two e2e cases, Number.NaN, and ignore S2187 on the legacy-upgrade fixtures
---------
Co-authored-by: Maurice <mauriceboe@icloud.com>
This commit is contained in:
@@ -16,9 +16,10 @@ import { BucketItemExistsError } from '../../../src/nest/atlas/atlas.service';
|
||||
import { VacayRpc } from '../../../src/nest/vacay/vacay.rpc';
|
||||
import { JournalRpc } from '../../../src/nest/journey/journal.rpc';
|
||||
import { CollectionsRpc } from '../../../src/nest/collections/collections.rpc';
|
||||
import type { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
import type { TripsRepository } from '../../../src/db/repositories/Trips.repository';
|
||||
import type { PermissionsService } from '../../../src/nest/permissions/permissions.service';
|
||||
import type { AddonsService } from '../../../src/nest/addons/addons.service';
|
||||
import type { UsersRepository } from '../../../src/db/repositories/Users.repository';
|
||||
import type { RpcRequest, RpcError } from '../../../src/nest/plugins/protocol/envelope';
|
||||
import { makeDeps } from '../../helpers/rpc-host-deps';
|
||||
|
||||
@@ -38,13 +39,14 @@ function build(overrides: {
|
||||
collections?: Record<string, unknown>;
|
||||
} = {}) {
|
||||
const db = {
|
||||
canAccessTrip: vi.fn(() => ({ id: 1, user_id: 42 })),
|
||||
findAccessible: vi.fn(async () => ({ id: 1, user_id: 42 })),
|
||||
prepare: vi.fn(() => ({ get: () => ({ role: 'user' }), all: () => [] })),
|
||||
} as unknown as DatabaseService;
|
||||
} as unknown as TripsRepository;
|
||||
const guards = new PluginGuards(
|
||||
db,
|
||||
{ checkPermission: vi.fn(() => true) } as unknown as PermissionsService,
|
||||
{ isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService,
|
||||
{ getRole: vi.fn(async () => 'user') } as unknown as UsersRepository,
|
||||
);
|
||||
const realtime = { broadcast: vi.fn() } as never;
|
||||
const registry = createTestPluginRegistry([
|
||||
|
||||
@@ -20,9 +20,10 @@ import { VacayRpc } from '../../../src/nest/vacay/vacay.rpc';
|
||||
import { JournalRpc } from '../../../src/nest/journey/journal.rpc';
|
||||
import { CollectionsRpc } from '../../../src/nest/collections/collections.rpc';
|
||||
import { CostsRpc } from '../../../src/nest/budget/costs.rpc';
|
||||
import type { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
import type { TripsRepository } from '../../../src/db/repositories/Trips.repository';
|
||||
import type { PermissionsService } from '../../../src/nest/permissions/permissions.service';
|
||||
import type { AddonsService } from '../../../src/nest/addons/addons.service';
|
||||
import type { UsersRepository } from '../../../src/db/repositories/Users.repository';
|
||||
import type { RpcRequest, RpcError } from '../../../src/nest/plugins/protocol/envelope';
|
||||
import { makeDeps } from '../../helpers/rpc-host-deps';
|
||||
|
||||
@@ -58,13 +59,14 @@ function spyService(calls: string[], name: string) {
|
||||
function build(addonOn: boolean) {
|
||||
const calls: string[] = [];
|
||||
const db = {
|
||||
canAccessTrip: vi.fn(() => ({ id: 1, user_id: 42 })),
|
||||
findAccessible: vi.fn(async () => ({ id: 1, user_id: 42 })),
|
||||
prepare: vi.fn(() => ({ get: () => ({ role: 'user' }), all: () => [] })),
|
||||
} as unknown as DatabaseService;
|
||||
} as unknown as TripsRepository;
|
||||
const guards = new PluginGuards(
|
||||
db,
|
||||
{ checkPermission: vi.fn(() => true) } as unknown as PermissionsService,
|
||||
{ isAddonEnabled: vi.fn(() => addonOn) } as unknown as AddonsService,
|
||||
{ getRole: vi.fn(async () => 'user') } as unknown as UsersRepository,
|
||||
);
|
||||
const registry = createTestPluginRegistry([
|
||||
new CollabRpc(spyService(calls, 'collab'), { broadcast: vi.fn() } as never, guards),
|
||||
@@ -76,7 +78,8 @@ function build(addonOn: boolean) {
|
||||
{ put: async () => undefined, delete: async () => undefined } as never,
|
||||
{ get: () => '*' } as never,
|
||||
{ scheduleUpload: () => undefined } as never,
|
||||
{ prepare: () => ({ get: () => ({ email: 'u@example.test' }) }) } as never),
|
||||
// SV8 — Plan 3i: DemoService.isDemoUserId, the shared demo-gate primitive.
|
||||
{ isDemoUserId: async () => false } as never),
|
||||
new CollectionsRpc(spyService(calls, 'collections'), guards),
|
||||
new CostsRpc(spyService(calls, 'budget'), db, { broadcast: vi.fn() } as never, guards, spyService(calls, 'membership')),
|
||||
]);
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
const { canAccessTrip, pluginsEnabled, tripDays } = vi.hoisted(() => ({
|
||||
canAccessTrip: vi.fn((tripId: number, userId: number) => (tripId === 1 && userId === 5 ? { id: 1 } : undefined)),
|
||||
canAccessTrip: vi.fn(async (tripId: number, userId: number) => (tripId === 1 && userId === 5 ? { id: 1 } : undefined)),
|
||||
pluginsEnabled: vi.fn(() => true),
|
||||
tripDays: { value: [{ id: 10 }, { id: 11 }] as Array<{ id: number }> },
|
||||
}));
|
||||
@@ -16,12 +16,12 @@ vi.mock('../../../src/db/database', () => ({
|
||||
db: { prepare: () => ({ all: () => tripDays.value }) },
|
||||
canAccessTrip,
|
||||
}));
|
||||
import { db as dbConn } from '../../../src/db/database';
|
||||
import { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
import type { TripsRepository } from '../../../src/db/repositories/Trips.repository';
|
||||
vi.mock('../../../src/nest/plugins/kill-switch', () => ({ pluginsEnabled }));
|
||||
|
||||
import { DayScheduleController } from '../../../src/nest/plugins/contributions/day-schedule.controller';
|
||||
import type { PluginHooks } from '../../../src/nest/plugins/plugin-hooks.service';
|
||||
import type { DaysRepository } from '../../../src/db/repositories/Days.repository';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const req = (id?: number) => ({ user: id === undefined ? undefined : { id } }) as any;
|
||||
@@ -30,12 +30,14 @@ function controller(invoke: (id: string) => unknown, providers = ['p1']) {
|
||||
providersOf: vi.fn(() => providers),
|
||||
daySchedule: vi.fn(async (id: string) => invoke(id)),
|
||||
} as unknown as PluginHooks;
|
||||
return { c: new DayScheduleController(runtime, new DatabaseService(dbConn)), runtime };
|
||||
// CT1 (Plan 3j Task 5) — the day-id-set read is now DaysRepository.listIdsByTrip.
|
||||
const days = { listIdsByTrip: vi.fn(async () => tripDays.value.map((d) => d.id)) } as unknown as DaysRepository;
|
||||
return { c: new DayScheduleController(runtime, { findAccessible: canAccessTrip } as unknown as TripsRepository, days), runtime };
|
||||
}
|
||||
const item = (over: Record<string, unknown> = {}) => ({ id: 's1', dayId: 10, label: 'Charging', ...over });
|
||||
|
||||
describe('DayScheduleController', () => {
|
||||
beforeEach(() => { pluginsEnabled.mockReturnValue(true); canAccessTrip.mockReturnValue({ id: 1 } as never); });
|
||||
beforeEach(() => { pluginsEnabled.mockReturnValue(true); canAccessTrip.mockResolvedValue({ id: 1 } as never); });
|
||||
|
||||
it('gates: disabled / no user / non-member all return [] (no plugin calls on the first)', async () => {
|
||||
pluginsEnabled.mockReturnValue(false);
|
||||
@@ -45,7 +47,7 @@ describe('DayScheduleController', () => {
|
||||
pluginsEnabled.mockReturnValue(true);
|
||||
|
||||
expect((await controller(() => [item()]).c.get('1', req(undefined))).items).toEqual([]);
|
||||
canAccessTrip.mockReturnValue(undefined as never);
|
||||
canAccessTrip.mockResolvedValue(undefined as never);
|
||||
expect((await controller(() => [item()]).c.get('1', req(5))).items).toEqual([]);
|
||||
});
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
const { canAccessTrip, pluginsEnabled, tripDays } = vi.hoisted(() => ({
|
||||
canAccessTrip: vi.fn((tripId: number, userId: number) => (tripId === 1 && userId === 5 ? { id: 1 } : undefined)),
|
||||
canAccessTrip: vi.fn(async (tripId: number, userId: number) => (tripId === 1 && userId === 5 ? { id: 1 } : undefined)),
|
||||
pluginsEnabled: vi.fn(() => true),
|
||||
tripDays: { value: [{ id: 10 }, { id: 11 }] as Array<{ id: number }> },
|
||||
}));
|
||||
@@ -16,12 +16,12 @@ vi.mock('../../../src/db/database', () => ({
|
||||
db: { prepare: () => ({ all: () => tripDays.value }) },
|
||||
canAccessTrip,
|
||||
}));
|
||||
import { db as dbConn } from '../../../src/db/database';
|
||||
import { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
import type { TripsRepository } from '../../../src/db/repositories/Trips.repository';
|
||||
vi.mock('../../../src/nest/plugins/kill-switch', () => ({ pluginsEnabled }));
|
||||
|
||||
import { DayTintsController } from '../../../src/nest/plugins/contributions/day-tints.controller';
|
||||
import type { PluginHooks } from '../../../src/nest/plugins/plugin-hooks.service';
|
||||
import type { DaysRepository } from '../../../src/db/repositories/Days.repository';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const req = (id?: number) => ({ user: id === undefined ? undefined : { id } }) as any;
|
||||
@@ -30,12 +30,14 @@ function controller(invoke: (id: string) => unknown, providers = ['p1']) {
|
||||
providersOf: vi.fn(() => providers),
|
||||
dayTints: vi.fn(async (id: string) => invoke(id)),
|
||||
} as unknown as PluginHooks;
|
||||
return { c: new DayTintsController(runtime, new DatabaseService(dbConn)), runtime };
|
||||
// CT2 (Plan 3j Task 5) — the day-id-set read is now DaysRepository.listIdsByTrip.
|
||||
const days = { listIdsByTrip: vi.fn(async () => tripDays.value.map((d) => d.id)) } as unknown as DaysRepository;
|
||||
return { c: new DayTintsController(runtime, { findAccessible: canAccessTrip } as unknown as TripsRepository, days), runtime };
|
||||
}
|
||||
const tint = (over: Record<string, unknown> = {}) => ({ dayId: 10, tone: 'success', ...over });
|
||||
|
||||
describe('DayTintsController', () => {
|
||||
beforeEach(() => { pluginsEnabled.mockReturnValue(true); canAccessTrip.mockReturnValue({ id: 1 } as never); });
|
||||
beforeEach(() => { pluginsEnabled.mockReturnValue(true); canAccessTrip.mockResolvedValue({ id: 1 } as never); });
|
||||
|
||||
it('gates: disabled / no user / non-member all return [] (no plugin calls on the first)', async () => {
|
||||
pluginsEnabled.mockReturnValue(false);
|
||||
@@ -45,7 +47,7 @@ describe('DayTintsController', () => {
|
||||
pluginsEnabled.mockReturnValue(true);
|
||||
|
||||
expect((await controller(() => [tint()]).c.get('1', req(undefined))).tints).toEqual([]);
|
||||
canAccessTrip.mockReturnValue(undefined as never);
|
||||
canAccessTrip.mockResolvedValue(undefined as never);
|
||||
expect((await controller(() => [tint()]).c.get('1', req(5))).tints).toEqual([]);
|
||||
});
|
||||
|
||||
|
||||
@@ -36,10 +36,10 @@ describe('parseDependencies', () => {
|
||||
});
|
||||
|
||||
describe('disabledRequiredAddons', () => {
|
||||
it('lists only the disabled required addons', () => {
|
||||
it('lists only the disabled required addons', async () => {
|
||||
const deps = parseDependencies(JSON.stringify({ requiredAddons: ['budget', 'journey'], pluginDependencies: [] }));
|
||||
expect(disabledRequiredAddons(deps, (a) => a === 'budget')).toEqual(['journey']);
|
||||
expect(disabledRequiredAddons(deps, () => true)).toEqual([]);
|
||||
expect(await disabledRequiredAddons(deps, (a) => Promise.resolve(a === 'budget'))).toEqual(['journey']);
|
||||
expect(await disabledRequiredAddons(deps, () => Promise.resolve(true))).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -2,15 +2,29 @@
|
||||
* Plugin discovery (#plugins, M4, install-from-disk): scans the volume, upserts
|
||||
* rows as inactive, refreshes settings fields, keeps an existing plugin's status,
|
||||
* and skips invalid or native-carrying plugins (logging the reason).
|
||||
*
|
||||
* Plan 3j Task 3 — converted onto `PluginsRepository`/`PluginActionsRepository`/
|
||||
* `PluginSettingsFieldsRepository`/`PluginErrorLogRepository` (a `DiscoveryRepos`
|
||||
* bundle), via a real MikroORM over the full migrated schema (`createSnapshotTestDb`
|
||||
* + `createTestOrm`) rather than a hand-rolled `:memory:` table set.
|
||||
*/
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import Database from 'better-sqlite3';
|
||||
import { describe, it, expect, beforeAll, beforeEach, afterAll, afterEach } from 'vitest';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { discoverPlugins } from '../../../src/nest/plugins/install/discovery';
|
||||
import { createSnapshotTestDb } from '../../helpers/db-mock';
|
||||
import { resetTestDb } from '../../helpers/test-db';
|
||||
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
|
||||
import { Plugins } from '../../../src/db/entities/Plugins.entity';
|
||||
import { PluginActions } from '../../../src/db/entities/PluginActions.entity';
|
||||
import { PluginSettingsFields } from '../../../src/db/entities/PluginSettingsFields.entity';
|
||||
import { PluginErrorLog } from '../../../src/db/entities/PluginErrorLog.entity';
|
||||
import { discoverPlugins, type DiscoveryRepos } from '../../../src/nest/plugins/install/discovery';
|
||||
import { UnitOfWork } from '../../../src/nest/database/unit-of-work';
|
||||
|
||||
let db: Database.Database;
|
||||
const testDb = createSnapshotTestDb();
|
||||
let t: TestOrm;
|
||||
let repos: DiscoveryRepos;
|
||||
let codeRoot: string;
|
||||
|
||||
function writePlugin(id: string, manifest: Record<string, unknown>, extra?: () => void) {
|
||||
@@ -21,27 +35,24 @@ function writePlugin(id: string, manifest: Record<string, unknown>, extra?: () =
|
||||
extra?.()
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestOrm(testDb);
|
||||
repos = { plugins: t.repo(Plugins), actions: t.repo(PluginActions), settingsFields: t.repo(PluginSettingsFields), errorLog: t.repo(PluginErrorLog), uow: new UnitOfWork(t.em) };
|
||||
});
|
||||
beforeEach(() => {
|
||||
resetTestDb(testDb);
|
||||
t.clear();
|
||||
codeRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'disc-'));
|
||||
process.env.TREK_PLUGINS_DIR = codeRoot;
|
||||
db = new Database(':memory:');
|
||||
db.exec(`
|
||||
CREATE TABLE plugins (id TEXT PRIMARY KEY, name TEXT, description TEXT, type TEXT, icon TEXT, version TEXT,
|
||||
api_version INTEGER, min_trek_version TEXT, trek_range TEXT, permissions TEXT, capabilities TEXT DEFAULT '{}', dependencies TEXT DEFAULT '{}', operator_egress INTEGER DEFAULT 0, granted_permissions TEXT, status TEXT, config TEXT, updated_at TEXT);
|
||||
CREATE TABLE plugin_settings_fields (plugin_id TEXT, field_key TEXT, label TEXT, input_type TEXT, placeholder TEXT, hint TEXT,
|
||||
required INTEGER, secret INTEGER, scope TEXT, options TEXT, oauth_config TEXT, default_value TEXT, sort_order INTEGER);
|
||||
CREATE TABLE plugin_actions (plugin_id TEXT, action_key TEXT, label TEXT, hint TEXT, danger INTEGER, scope TEXT NOT NULL DEFAULT 'user', sort_order INTEGER,
|
||||
PRIMARY KEY (plugin_id, action_key));
|
||||
CREATE TABLE plugin_error_log (id INTEGER PRIMARY KEY AUTOINCREMENT, plugin_id TEXT, level TEXT, message TEXT, ts TEXT);`);
|
||||
});
|
||||
afterEach(() => {
|
||||
delete process.env.TREK_PLUGINS_DIR;
|
||||
db.close();
|
||||
fs.rmSync(codeRoot, { recursive: true, force: true });
|
||||
});
|
||||
afterAll(async () => { await t.close(); testDb.close(); });
|
||||
|
||||
describe('discoverPlugins', () => {
|
||||
it('registers a new plugin inactive with its settings fields', () => {
|
||||
it('registers a new plugin inactive with its settings fields', async () => {
|
||||
writePlugin('flight-tracker', {
|
||||
name: 'Flight',
|
||||
type: 'widget',
|
||||
@@ -52,64 +63,64 @@ describe('discoverPlugins', () => {
|
||||
{ key: 'oauth', input_type: 'oauth', scope: 'user', oauth: { initPath: '/o/start', callbackPath: '/o/cb' } },
|
||||
],
|
||||
});
|
||||
const res = discoverPlugins(db);
|
||||
const res = await discoverPlugins(repos);
|
||||
expect(res.discovered).toEqual(['flight-tracker']);
|
||||
|
||||
const row = db.prepare("SELECT status, type, permissions FROM plugins WHERE id='flight-tracker'").get() as { status: string; type: string; permissions: string };
|
||||
const row = testDb.prepare("SELECT status, type, permissions FROM plugins WHERE id='flight-tracker'").get() as { status: string; type: string; permissions: string };
|
||||
expect(row.status).toBe('inactive');
|
||||
expect(row.type).toBe('widget');
|
||||
expect(JSON.parse(row.permissions)).toEqual(['db:own']);
|
||||
|
||||
const field = db.prepare("SELECT field_key, secret FROM plugin_settings_fields WHERE plugin_id='flight-tracker'").get() as { field_key: string; secret: number };
|
||||
const field = testDb.prepare("SELECT field_key, secret FROM plugin_settings_fields WHERE plugin_id='flight-tracker'").get() as { field_key: string; secret: number };
|
||||
expect(field).toMatchObject({ field_key: 'api_key', secret: 1 });
|
||||
});
|
||||
|
||||
it('persists each action with its scope', () => {
|
||||
it('persists each action with its scope', async () => {
|
||||
writePlugin('acts', {
|
||||
name: 'Acts', type: 'integration', permissions: [],
|
||||
actions: [{ key: 'ping', label: 'Ping' }, { key: 'purge', label: 'Purge', scope: 'instance', danger: true }],
|
||||
});
|
||||
discoverPlugins(db);
|
||||
const rows = db.prepare("SELECT action_key, scope, danger FROM plugin_actions WHERE plugin_id='acts' ORDER BY sort_order").all();
|
||||
await discoverPlugins(repos);
|
||||
const rows = testDb.prepare("SELECT action_key, scope, danger FROM plugin_actions WHERE plugin_id='acts' ORDER BY sort_order").all();
|
||||
expect(rows).toEqual([
|
||||
{ action_key: 'ping', scope: 'user', danger: 0 },
|
||||
{ action_key: 'purge', scope: 'instance', danger: 1 },
|
||||
]);
|
||||
});
|
||||
|
||||
it('keeps an existing plugin status + granted permissions on re-discovery', () => {
|
||||
db.prepare("INSERT INTO plugins (id, name, type, status, granted_permissions) VALUES ('keep','Keep','page','active','[\"db:own\"]')").run();
|
||||
it('keeps an existing plugin status + granted permissions on re-discovery', async () => {
|
||||
testDb.prepare("INSERT INTO plugins (id, name, type, status, granted_permissions) VALUES ('keep','Keep','page','active','[\"db:own\"]')").run();
|
||||
writePlugin('keep', { name: 'Keep v2', type: 'page', version: '2.0.0' });
|
||||
discoverPlugins(db);
|
||||
const row = db.prepare("SELECT status, version, granted_permissions FROM plugins WHERE id='keep'").get() as { status: string; version: string; granted_permissions: string };
|
||||
await discoverPlugins(repos);
|
||||
const row = testDb.prepare("SELECT status, version, granted_permissions FROM plugins WHERE id='keep'").get() as { status: string; version: string; granted_permissions: string };
|
||||
expect(row.status).toBe('active'); // not downgraded
|
||||
expect(row.version).toBe('2.0.0'); // metadata refreshed
|
||||
expect(JSON.parse(row.granted_permissions)).toEqual(['db:own']); // grants preserved
|
||||
});
|
||||
|
||||
it('tolerates a UTF-8 BOM in trek-plugin.json (Windows-authored plugins)', () => {
|
||||
it('tolerates a UTF-8 BOM in trek-plugin.json (Windows-authored plugins)', async () => {
|
||||
writePlugin('bom-plug', { type: 'integration' });
|
||||
const mp = path.join(codeRoot, 'bom-plug', 'trek-plugin.json');
|
||||
fs.writeFileSync(mp, '\uFEFF' + fs.readFileSync(mp, 'utf8'));
|
||||
expect(discoverPlugins(db).discovered).toEqual(['bom-plug']);
|
||||
fs.writeFileSync(mp, '' + fs.readFileSync(mp, 'utf8'));
|
||||
expect((await discoverPlugins(repos)).discovered).toEqual(['bom-plug']);
|
||||
});
|
||||
|
||||
it('skips an invalid manifest and logs the reason', () => {
|
||||
it('skips an invalid manifest and logs the reason', async () => {
|
||||
writePlugin('bad', { type: 'not-a-type' });
|
||||
const res = discoverPlugins(db);
|
||||
const res = await discoverPlugins(repos);
|
||||
expect(res.skipped).toEqual(['bad']);
|
||||
expect(db.prepare("SELECT COUNT(*) c FROM plugins WHERE id='bad'").get()).toMatchObject({ c: 0 });
|
||||
expect((db.prepare("SELECT message FROM plugin_error_log WHERE plugin_id='bad'").get() as { message: string }).message).toContain('discovery');
|
||||
expect(testDb.prepare("SELECT COUNT(*) c FROM plugins WHERE id='bad'").get()).toMatchObject({ c: 0 });
|
||||
expect((testDb.prepare("SELECT message FROM plugin_error_log WHERE plugin_id='bad'").get() as { message: string }).message).toContain('discovery');
|
||||
});
|
||||
|
||||
it('skips a plugin that ships native binaries', () => {
|
||||
it('skips a plugin that ships native binaries', async () => {
|
||||
writePlugin('native', { type: 'integration' }, () => {
|
||||
fs.writeFileSync(path.join(codeRoot, 'native', 'server', 'addon.node'), '\0');
|
||||
});
|
||||
expect(discoverPlugins(db).skipped).toEqual(['native']);
|
||||
expect((await discoverPlugins(repos)).skipped).toEqual(['native']);
|
||||
});
|
||||
|
||||
it('follows a symlinked dev-link plugin only when dev-link mode is on', () => {
|
||||
it('follows a symlinked dev-link plugin only when dev-link mode is on', async () => {
|
||||
const srcRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'disc-src-'));
|
||||
const prev = process.env.TREK_PLUGINS_DEV_LINK;
|
||||
try {
|
||||
@@ -121,48 +132,48 @@ describe('discoverPlugins', () => {
|
||||
|
||||
// Off (default): a stale dev-link symlink is not discovered or registered.
|
||||
delete process.env.TREK_PLUGINS_DEV_LINK;
|
||||
expect(discoverPlugins(db).discovered).toEqual([]);
|
||||
expect(db.prepare("SELECT status FROM plugins WHERE id='linked'").get()).toBeUndefined();
|
||||
expect((await discoverPlugins(repos)).discovered).toEqual([]);
|
||||
expect(testDb.prepare("SELECT status FROM plugins WHERE id='linked'").get()).toBeUndefined();
|
||||
|
||||
// On: the dev-link is followed and registered inactive.
|
||||
process.env.TREK_PLUGINS_DEV_LINK = '1';
|
||||
expect(discoverPlugins(db).discovered).toEqual(['linked']);
|
||||
expect(db.prepare("SELECT status FROM plugins WHERE id='linked'").get()).toMatchObject({ status: 'inactive' });
|
||||
expect((await discoverPlugins(repos)).discovered).toEqual(['linked']);
|
||||
expect(testDb.prepare("SELECT status FROM plugins WHERE id='linked'").get()).toMatchObject({ status: 'inactive' });
|
||||
} finally {
|
||||
if (prev === undefined) delete process.env.TREK_PLUGINS_DEV_LINK; else process.env.TREK_PLUGINS_DEV_LINK = prev;
|
||||
fs.rmSync(srcRoot, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('is a no-op when the plugins dir is absent', () => {
|
||||
it('is a no-op when the plugins dir is absent', async () => {
|
||||
process.env.TREK_PLUGINS_DIR = path.join(codeRoot, 'does-not-exist');
|
||||
expect(discoverPlugins(db)).toEqual({ discovered: [], skipped: [] });
|
||||
expect(await discoverPlugins(repos)).toEqual({ discovered: [], skipped: [] });
|
||||
});
|
||||
|
||||
describe('the TREK range', () => {
|
||||
it('persists the range and its lower bound', () => {
|
||||
it('persists the range and its lower bound', async () => {
|
||||
writePlugin('ranged', { trek: '>=3.2.0 <4.0.0' });
|
||||
discoverPlugins(db);
|
||||
expect(db.prepare("SELECT trek_range, min_trek_version FROM plugins WHERE id='ranged'").get())
|
||||
await discoverPlugins(repos);
|
||||
expect(testDb.prepare("SELECT trek_range, min_trek_version FROM plugins WHERE id='ranged'").get())
|
||||
.toMatchObject({ trek_range: '>=3.2.0 <4.0.0', min_trek_version: '3.2.0' });
|
||||
});
|
||||
|
||||
it('still registers a plugin that declares NO range — it must not vanish', () => {
|
||||
it('still registers a plugin that declares NO range — it must not vanish', async () => {
|
||||
// Discovery is a reconciler, not a gate: it only logs and skips on a throw and never
|
||||
// touches the plugins row, so refusing here would leave an existing plugin's stale
|
||||
// enabled=1 row to be spawned by the next boot — invisible AND running. The row is
|
||||
// registered with a null range and the activation gate refuses it (TREK_VERSION_UNKNOWN).
|
||||
writePlugin('rangeless', {});
|
||||
expect(discoverPlugins(db).discovered).toEqual(['rangeless']);
|
||||
expect(db.prepare("SELECT trek_range FROM plugins WHERE id='rangeless'").get()).toMatchObject({ trek_range: null });
|
||||
expect((await discoverPlugins(repos)).discovered).toEqual(['rangeless']);
|
||||
expect(testDb.prepare("SELECT trek_range FROM plugins WHERE id='rangeless'").get()).toMatchObject({ trek_range: null });
|
||||
});
|
||||
|
||||
it('refreshes the range on re-discovery, so a plugin that narrowed its support is caught', () => {
|
||||
it('refreshes the range on re-discovery, so a plugin that narrowed its support is caught', async () => {
|
||||
writePlugin('shrink', { trek: '>=3.0.0' });
|
||||
discoverPlugins(db);
|
||||
await discoverPlugins(repos);
|
||||
writePlugin('shrink', { trek: '>=3.0.0 <3.1.0' });
|
||||
discoverPlugins(db);
|
||||
expect(db.prepare("SELECT trek_range FROM plugins WHERE id='shrink'").get()).toMatchObject({ trek_range: '>=3.0.0 <3.1.0' });
|
||||
await discoverPlugins(repos);
|
||||
expect(testDb.prepare("SELECT trek_range FROM plugins WHERE id='shrink'").get()).toMatchObject({ trek_range: '>=3.0.0 <3.1.0' });
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -63,19 +63,28 @@ import { MetaRpc } from '../../../src/nest/plugins/host/rpc/meta.rpc';
|
||||
import { HostSurfaceRpc } from '../../../src/nest/plugins/host/rpc/host-surface.rpc';
|
||||
import { UnreadableLlmResponse } from '../../../src/nest/llm-parse/clients/openai-compatible.client';
|
||||
import { getPluginDataDb, closePluginDataDb } from '../../../src/nest/plugins/host/plugin-host-state';
|
||||
import { verifyChain } from '../../../src/nest/plugins/host/plugin-audit';
|
||||
import { db as mockDb } from '../../../src/db/database';
|
||||
import { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
|
||||
import type { PermissionsService } from '../../../src/nest/permissions/permissions.service';
|
||||
import type { AddonsService } from '../../../src/nest/addons/addons.service';
|
||||
import type { UsersRepository } from '../../../src/db/repositories/Users.repository';
|
||||
import type { NotificationsService } from '../../../src/nest/notifications/notifications.service';
|
||||
import type { LlmConfigResolver } from '../../../src/nest/llm-parse/llm-config.resolver';
|
||||
import type { PluginOAuthService } from '../../../src/nest/plugins/oauth/plugin-oauth.service';
|
||||
import type { RpcError, RpcResponse } from '../../../src/nest/plugins/protocol/envelope';
|
||||
import type { PluginCapabilityAuditRepository } from '../../../src/db/repositories/PluginCapabilityAudit.repository';
|
||||
import type { TripsRepository } from '../../../src/db/repositories/Trips.repository';
|
||||
import type { PlacesRepository } from '../../../src/db/repositories/Places.repository';
|
||||
import type { DaysRepository } from '../../../src/db/repositories/Days.repository';
|
||||
import type { ReservationsRepository } from '../../../src/db/repositories/Reservations.repository';
|
||||
import type { DayAccommodationsRepository } from '../../../src/db/repositories/DayAccommodations.repository';
|
||||
import type { PluginEntityMetadataRepository } from '../../../src/db/repositories/PluginEntityMetadata.repository';
|
||||
import type { PluginScheduledTasksRepository } from '../../../src/db/repositories/PluginScheduledTasks.repository';
|
||||
|
||||
// Typed from the real method rather than from the always-true body below, so a case that
|
||||
// swaps in an implementation reading the action key (HOSTRPC-015) still type-checks.
|
||||
const checkPermission = vi.fn<PermissionsService['checkPermission']>(() => true);
|
||||
const checkPermission = vi.fn<PermissionsService['checkPermission']>(() => Promise.resolve(true));
|
||||
const permissions = { checkPermission } as unknown as PermissionsService;
|
||||
const addons = { isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService;
|
||||
const notifications = { send: notifySend } as unknown as NotificationsService;
|
||||
@@ -95,15 +104,223 @@ const userSettings = {
|
||||
readOne: vi.fn((_pid: string, uid: number, key: string) => (uid === 5 && key === 'apiKey' ? 'k-5' : undefined)),
|
||||
} as unknown as PluginUserSettingsService;
|
||||
|
||||
const dbs = new DatabaseService(mockDb);
|
||||
const guards = new PluginGuards(dbs, permissions, addons);
|
||||
// Plan 3j Task 3: `budgetFor`/`appendAudit` now take `PluginCapabilityAuditRepository`,
|
||||
// not a raw connection. `plugin_capability_audit`'s hand-rolled table above (unlike
|
||||
// `trips`/`users`) matches the real entity's full column set, so a real MikroORM
|
||||
// repository would work here too — but every other cross-cutting dependency in this
|
||||
// file (`canAccessTrip`, `getRole`) is a synchronous stub against this same `mockDb`
|
||||
// for the same reason (no top-level await in this file), so this stays consistent:
|
||||
// real raw SQL against `mockDb`, wrapped in the repository's own method shapes.
|
||||
// HOSTRPC-031 seeds real rows through `mockDb.prepare(...)` and reads them back
|
||||
// through `budgetSeed`, so this must be backed by the real table, not a canned stub.
|
||||
const pluginAuditRepo = {
|
||||
async budgetSeed(pluginId: string, since: string) {
|
||||
return (mockDb as unknown as { prepare(s: string): { all(...a: unknown[]): unknown[] } })
|
||||
.prepare(
|
||||
"SELECT method, COUNT(*) AS n FROM plugin_capability_audit WHERE plugin_id = ? AND code = 'ok' AND ts >= ? AND method IN ('ai.complete','ai.extract','notify.send') GROUP BY method",
|
||||
)
|
||||
.all(pluginId, since) as Array<{ method: string; n: number }>;
|
||||
},
|
||||
async lastHash(pluginId: string) {
|
||||
const row = (mockDb as unknown as { prepare(s: string): { get(...a: unknown[]): unknown } })
|
||||
.prepare('SELECT hash FROM plugin_capability_audit WHERE plugin_id = ? ORDER BY id DESC LIMIT 1')
|
||||
.get(pluginId) as { hash: string } | undefined;
|
||||
return row?.hash ?? null;
|
||||
},
|
||||
async insertRow(entry: { plugin_id: string; acting_user_id: number | null; method: string; resource: string | null; code: string; ts: string; prev_hash: string | null; hash: string }) {
|
||||
(mockDb as unknown as { prepare(s: string): { run(...a: unknown[]): unknown } })
|
||||
.prepare('INSERT INTO plugin_capability_audit (plugin_id, acting_user_id, method, resource, code, ts, prev_hash, hash) VALUES (?,?,?,?,?,?,?,?)')
|
||||
.run(entry.plugin_id, entry.acting_user_id, entry.method, entry.resource, entry.code, entry.ts, entry.prev_hash, entry.hash);
|
||||
},
|
||||
async pruneKeepingNewest() {
|
||||
// Not exercised in this suite (PRUNE_EVERY = 500 appends/plugin) — a no-op stub.
|
||||
},
|
||||
} as unknown as PluginCapabilityAuditRepository;
|
||||
|
||||
/**
|
||||
* Plan 3j Task 5: `MetaRpc`/`HostSurfaceRpc`'s own repository conversions
|
||||
* (MR#/HR#). Same reasoning as `pluginAuditRepo` above — this file's
|
||||
* hand-trimmed `:memory:` schema (no top-level await here) means a real
|
||||
* MikroORM repository isn't reachable, so every converted method is
|
||||
* reproduced as real raw SQL against `mockDb`, wrapped in the repository's
|
||||
* own method shape, rather than a canned stub — HOSTRPC-014/028/029/030
|
||||
* read the real table state back out through `mockDb.prepare(...)`
|
||||
* directly, so this HAS to be the real table.
|
||||
*/
|
||||
type RawDb = {
|
||||
prepare(sql: string): { get(...a: unknown[]): unknown; all(...a: unknown[]): unknown[]; run(...a: unknown[]): { changes: number } };
|
||||
};
|
||||
const raw = mockDb as unknown as RawDb;
|
||||
|
||||
const tripsRepo = {
|
||||
// Plan 4 Task 2 — PluginGuards' own canAccessTrip delegate is now this
|
||||
// repository's findAccessible directly (same access rule the old
|
||||
// `db/database` mock factory above encoded: trip 1 belongs to user 5,
|
||||
// user 6 is a member).
|
||||
async findAccessible(tripId: number | string, userId: number) {
|
||||
return Number(tripId) === 1 && (userId === 5 || userId === 6) ? { id: 1, user_id: 5, currency: null } : undefined;
|
||||
},
|
||||
async sharesTripWith(userIdA: number, userIdB: number) {
|
||||
return !!raw
|
||||
.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(userIdA, userIdB, userIdA, userIdB);
|
||||
},
|
||||
async existsById(id: number) {
|
||||
return !!raw.prepare('SELECT id FROM trips WHERE id = ?').get(id);
|
||||
},
|
||||
} as unknown as TripsRepository;
|
||||
|
||||
const placesRepo = {
|
||||
async findTripId(id: number) {
|
||||
return (raw.prepare('SELECT trip_id FROM places WHERE id = ?').get(id) as { trip_id: number } | undefined)?.trip_id;
|
||||
},
|
||||
} as unknown as PlacesRepository;
|
||||
|
||||
const daysRepo = {
|
||||
async findTripId(id: number) {
|
||||
return (raw.prepare('SELECT trip_id FROM days WHERE id = ?').get(id) as { trip_id: number } | undefined)?.trip_id;
|
||||
},
|
||||
} as unknown as DaysRepository;
|
||||
|
||||
const reservationsRepo = {
|
||||
async findTripId(id: number) {
|
||||
return (raw.prepare('SELECT trip_id FROM reservations WHERE id = ?').get(id) as { trip_id: number } | undefined)?.trip_id;
|
||||
},
|
||||
} as unknown as ReservationsRepository;
|
||||
|
||||
const dayAccommodationsRepo = {
|
||||
async getTripId(id: number) {
|
||||
return (raw.prepare('SELECT trip_id FROM day_accommodations WHERE id = ?').get(id) as { trip_id: number } | undefined)?.trip_id;
|
||||
},
|
||||
} as unknown as DayAccommodationsRepository;
|
||||
|
||||
const metaRepo = {
|
||||
async findValue(pluginId: string, entityType: string, entityId: number, key: string) {
|
||||
const row = raw
|
||||
.prepare('SELECT value FROM plugin_entity_metadata WHERE plugin_id=? AND entity_type=? AND entity_id=? AND key=?')
|
||||
.get(pluginId, entityType, entityId, key) as { value: string } | undefined;
|
||||
return row?.value ?? null;
|
||||
},
|
||||
async countForEntity(pluginId: string, entityType: string, entityId: number) {
|
||||
return (
|
||||
raw
|
||||
.prepare('SELECT COUNT(*) AS n FROM plugin_entity_metadata WHERE plugin_id=? AND entity_type=? AND entity_id=?')
|
||||
.get(pluginId, entityType, entityId) as { n: number }
|
||||
).n;
|
||||
},
|
||||
async upsertValue(pluginId: string, entityType: string, entityId: number, key: string, value: string) {
|
||||
raw
|
||||
.prepare(
|
||||
`INSERT INTO plugin_entity_metadata (plugin_id, entity_type, entity_id, key, value, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, datetime('now'))
|
||||
ON CONFLICT(plugin_id, entity_type, entity_id, key)
|
||||
DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`,
|
||||
)
|
||||
.run(pluginId, entityType, entityId, key, value);
|
||||
},
|
||||
async listForEntity(pluginId: string, entityType: string, entityId: number) {
|
||||
return raw
|
||||
.prepare('SELECT key, value FROM plugin_entity_metadata WHERE plugin_id=? AND entity_type=? AND entity_id=? ORDER BY key')
|
||||
.all(pluginId, entityType, entityId) as Array<{ key: string; value: string }>;
|
||||
},
|
||||
async deleteValue(pluginId: string, entityType: string, entityId: number, key: string) {
|
||||
return raw.prepare('DELETE FROM plugin_entity_metadata WHERE plugin_id=? AND entity_type=? AND entity_id=? AND key=?').run(pluginId, entityType, entityId, key).changes > 0;
|
||||
},
|
||||
// Plan 3j Task 7 fix (must-land 2) — `meta.rpc.ts#set` now calls this ONE method
|
||||
// instead of `findValue`+`countForEntity`+`upsertValue` separately. One synchronous
|
||||
// better-sqlite3 statement (no `await` gap between the cap check and the write),
|
||||
// the same atomicity property the real `PluginEntityMetadataRepository
|
||||
// .upsertValueCapped` gets from `getEntityManager().transactional`.
|
||||
async upsertValueCapped(pluginId: string, entityType: string, entityId: number, key: string, value: string, maxKeys: number) {
|
||||
const result = raw
|
||||
.prepare(
|
||||
`INSERT INTO plugin_entity_metadata (plugin_id, entity_type, entity_id, key, value, updated_at)
|
||||
SELECT ?, ?, ?, ?, ?, datetime('now')
|
||||
WHERE EXISTS (SELECT 1 FROM plugin_entity_metadata WHERE plugin_id=? AND entity_type=? AND entity_id=? AND key=?)
|
||||
OR (SELECT COUNT(*) FROM plugin_entity_metadata WHERE plugin_id=? AND entity_type=? AND entity_id=?) < ?
|
||||
ON CONFLICT(plugin_id, entity_type, entity_id, key)
|
||||
DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`,
|
||||
)
|
||||
.run(pluginId, entityType, entityId, key, value, pluginId, entityType, entityId, key, pluginId, entityType, entityId, maxKeys);
|
||||
return result.changes > 0;
|
||||
},
|
||||
} as unknown as PluginEntityMetadataRepository;
|
||||
|
||||
const scheduledTasksRepo = {
|
||||
async existsForPluginAndName(pluginId: string, name: string) {
|
||||
return !!raw.prepare('SELECT id FROM plugin_scheduled_tasks WHERE plugin_id = ? AND name = ?').get(pluginId, name);
|
||||
},
|
||||
async countForPlugin(pluginId: string) {
|
||||
return (raw.prepare('SELECT COUNT(*) AS c FROM plugin_scheduled_tasks WHERE plugin_id = ?').get(pluginId) as { c: number }).c;
|
||||
},
|
||||
async upsertTask(input: { plugin_id: string; name: string; due_at: number; payload: string; every_ms: number | null }) {
|
||||
raw
|
||||
.prepare(
|
||||
`INSERT INTO plugin_scheduled_tasks (plugin_id, name, due_at, payload, every_ms) VALUES (?, ?, ?, ?, ?)
|
||||
ON CONFLICT (plugin_id, name) DO UPDATE SET due_at = excluded.due_at, payload = excluded.payload, every_ms = excluded.every_ms`,
|
||||
)
|
||||
.run(input.plugin_id, input.name, input.due_at, input.payload, input.every_ms);
|
||||
},
|
||||
async deleteByPluginAndName(pluginId: string, name: string) {
|
||||
return raw.prepare('DELETE FROM plugin_scheduled_tasks WHERE plugin_id = ? AND name = ?').run(pluginId, name).changes > 0;
|
||||
},
|
||||
// Plan 3j Task 7 fix (must-land 3) — `host-surface.rpc.ts#schedulerSet` now calls
|
||||
// this ONE method instead of `existsForPluginAndName`+`countForPlugin`+`upsertTask`
|
||||
// separately. Same one-statement atomicity shape as `metaRepo.upsertValueCapped`
|
||||
// above, mirroring the real `PluginScheduledTasksRepository.upsertTaskCapped`.
|
||||
async upsertTaskCapped(input: { plugin_id: string; name: string; due_at: number; payload: string; every_ms: number | null }, maxTasks: number) {
|
||||
const result = raw
|
||||
.prepare(
|
||||
`INSERT INTO plugin_scheduled_tasks (plugin_id, name, due_at, payload, every_ms)
|
||||
SELECT ?, ?, ?, ?, ?
|
||||
WHERE EXISTS (SELECT 1 FROM plugin_scheduled_tasks WHERE plugin_id=? AND name=?)
|
||||
OR (SELECT COUNT(*) FROM plugin_scheduled_tasks WHERE plugin_id=?) < ?
|
||||
ON CONFLICT (plugin_id, name) DO UPDATE SET due_at = excluded.due_at, payload = excluded.payload, every_ms = excluded.every_ms`,
|
||||
)
|
||||
.run(input.plugin_id, input.name, input.due_at, input.payload, input.every_ms, input.plugin_id, input.name, input.plugin_id, maxTasks);
|
||||
return result.changes > 0;
|
||||
},
|
||||
} as unknown as PluginScheduledTasksRepository;
|
||||
|
||||
// Plan 3j Task 1: PluginGuards' own role lookup (PG3/PG4) now goes through
|
||||
// UsersRepository.getRole, not `dbs.prepare(...)`. Same reasoning as the
|
||||
// canAccessTrip spy above — a real UsersRepository would need a real
|
||||
// MikroORM over this file's hand-trimmed `:memory:` schema (async init, no
|
||||
// top-level await here) for no benefit: checkPermission is a blanket stub
|
||||
// in this file, so no case depends on which role value flows through it.
|
||||
// Stubbed against the exact seeded rows (users.ts INSERTs above) so it stays
|
||||
// accurate if a future case ever does start asserting on the role argument.
|
||||
const seededRoles: Record<number, string> = { 5: 'trip_owner', 6: 'user', 9: 'user' };
|
||||
const usersRepo = {
|
||||
getRole: vi.fn(async (id: number) => seededRoles[id] ?? null),
|
||||
// HR1 (Plan 3j Task 5) — same "real SQL against mockDb" reasoning as the
|
||||
// repository stubs above; HOSTRPC-019 asserts the exact returned shape.
|
||||
async findPublicIdentity(id: number) {
|
||||
return (
|
||||
(raw.prepare('SELECT id, username, display_name, avatar FROM users WHERE id = ?').get(id) as
|
||||
| { id: number; username: string; display_name: string | null; avatar: string | null }
|
||||
| undefined) ?? null
|
||||
);
|
||||
},
|
||||
} as unknown as UsersRepository;
|
||||
// Plan 4 Task 2 — PluginGuards'/MetaRpc's/HostSurfaceRpc's own DatabaseService
|
||||
// params are gone: canAccessTrip now reads through the TripsRepository each
|
||||
// already injects (`tripsRepo` above, findAccessible-only).
|
||||
const guards = new PluginGuards(tripsRepo, permissions, addons, usersRepo);
|
||||
const registry = createTestPluginRegistry([
|
||||
new DbRpc(userSettings),
|
||||
new MetaRpc(dbs, guards),
|
||||
new HostSurfaceRpc(dbs, new RealtimeService(), notifications, llmConfig, oauth, guards),
|
||||
new MetaRpc(guards, metaRepo, tripsRepo, placesRepo, daysRepo, reservationsRepo, dayAccommodationsRepo),
|
||||
new HostSurfaceRpc(new RealtimeService(), notifications, llmConfig, oauth, guards, pluginAuditRepo, usersRepo, tripsRepo, scheduledTasksRepo),
|
||||
]);
|
||||
const factory = new PluginRpcHostFactory(dbs, registry as unknown as PluginRpcRegistryService);
|
||||
const stubRouter: PluginCallRouter = { callPlugin: async () => undefined, emitPluginEvent: () => {} };
|
||||
const factory = new PluginRpcHostFactory(pluginAuditRepo, registry as unknown as PluginRpcRegistryService);
|
||||
const stubRouter: PluginCallRouter = { callPlugin: async () => undefined, emitPluginEvent: async () => {} };
|
||||
const makeHost = (id: string, ...perms: string[]) => factory.create(id, new Set(perms), stubRouter);
|
||||
/**
|
||||
* A response read loosely, on purpose.
|
||||
@@ -224,7 +441,7 @@ describe('DbRpc — the unconditional three', () => {
|
||||
calls.push({ callerId, targetId, fn, args, uid });
|
||||
return { echoed: true };
|
||||
},
|
||||
emitPluginEvent: (sourceId, event, payload) => {
|
||||
emitPluginEvent: async (sourceId, event, payload) => {
|
||||
emits.push({ sourceId, event, payload });
|
||||
},
|
||||
};
|
||||
@@ -255,7 +472,7 @@ describe('DbRpc — the unconditional three', () => {
|
||||
describe('MetaRpc — namespaced entity metadata', () => {
|
||||
beforeEach(() => {
|
||||
checkPermission.mockReset();
|
||||
checkPermission.mockReturnValue(true);
|
||||
checkPermission.mockResolvedValue(true);
|
||||
});
|
||||
afterAll(() => closePluginDataDb('meta'));
|
||||
|
||||
@@ -315,7 +532,7 @@ describe('MetaRpc — namespaced entity metadata', () => {
|
||||
const seen: string[] = [];
|
||||
checkPermission.mockImplementation((action) => {
|
||||
seen.push(action);
|
||||
return true;
|
||||
return Promise.resolve(true);
|
||||
});
|
||||
for (const [entityType, entityId] of [['trip', 1], ['place', 7], ['day', 3], ['reservation', 40], ['accommodation', 11]] as const) {
|
||||
expect((await call(host, 'meta.set', { entityType, entityId, key: 'k', value: 1 })).ok).toBe(true);
|
||||
@@ -323,7 +540,7 @@ describe('MetaRpc — namespaced entity metadata', () => {
|
||||
// Accommodations deliberately ride on day_edit, like the accommodation write path.
|
||||
expect(seen).toEqual(['trip_edit', 'place_edit', 'day_edit', 'reservation_edit', 'day_edit']);
|
||||
|
||||
checkPermission.mockReturnValue(false);
|
||||
checkPermission.mockResolvedValue(false);
|
||||
const write = await call(host, 'meta.set', { entityType: 'trip', entityId: 1, key: 'k', value: 2 });
|
||||
expect(write.error?.code).toBe('RESOURCE_FORBIDDEN');
|
||||
// …but a READ is only access-gated, so it still works for the same user.
|
||||
@@ -359,7 +576,7 @@ describe('MetaRpc — namespaced entity metadata', () => {
|
||||
describe('HostSurfaceRpc — users, broadcasts, notify, ai, oauth, scheduler', () => {
|
||||
beforeEach(() => {
|
||||
checkPermission.mockReset();
|
||||
checkPermission.mockReturnValue(true);
|
||||
checkPermission.mockResolvedValue(true);
|
||||
notifySend.mockClear();
|
||||
llmExtract.mockClear();
|
||||
broadcast.mockClear();
|
||||
@@ -378,6 +595,30 @@ describe('HostSurfaceRpc — users, broadcasts, notify, ai, oauth, scheduler', (
|
||||
expect((await call(host, 'users.getById', { id: 6 }, undefined)).error?.code).toBe('RESOURCE_FORBIDDEN');
|
||||
});
|
||||
|
||||
it('HOSTRPC-033 a burst of concurrent auditable RPC calls for the SAME plugin never forks the capability-audit hash chain (Plan 3j Task 7 fix, must-land 1)', async () => {
|
||||
// The REAL production path, not a direct `appendAudit` unit call: `dispatch()`
|
||||
// audits every `isAuditable` method AFTER computing its answer (`users.getById`
|
||||
// here, permission `db:read:users` != `db:own`), through the SAME per-plugin
|
||||
// promise-tail `appendAudit` now serializes on — task-7-review.md's SDK default of
|
||||
// 16 in-flight RPCs is what made this reachable live.
|
||||
const host = makeHost('auditburst', 'db:read:users');
|
||||
const N = 20;
|
||||
const results = await Promise.all(Array.from({ length: N }, () => call(host, 'users.getById', { id: 5 }, 5)));
|
||||
expect(results.every((r) => r.ok)).toBe(true);
|
||||
const rows = (
|
||||
mockDb as unknown as {
|
||||
prepare(s: string): { all(...a: unknown[]): Array<{ plugin_id: string; acting_user_id: number | null; method: string; resource: string | null; code: string; ts: string; prev_hash: string | null; hash: string }> };
|
||||
}
|
||||
)
|
||||
.prepare("SELECT plugin_id, acting_user_id, method, resource, code, ts, prev_hash, hash FROM plugin_capability_audit WHERE plugin_id = 'auditburst' ORDER BY id ASC")
|
||||
.all();
|
||||
expect(rows).toHaveLength(N);
|
||||
expect(verifyChain(rows)).toBe(true);
|
||||
const prevHashes = rows.map((r) => r.prev_hash ?? '');
|
||||
expect(new Set(prevHashes).size).toBe(prevHashes.length); // no two rows read the same "previous" tip
|
||||
closePluginDataDb('auditburst');
|
||||
});
|
||||
|
||||
it('HOSTRPC-020 trip broadcasts are force-namespaced and membership-gated', async () => {
|
||||
const host = makeHost('surface', 'ws:broadcast:trip');
|
||||
expect((await call(host, 'ws.broadcastToTrip', { tripId: 1, event: 'ping', data: { a: 1 } }, 5)).ok).toBe(true);
|
||||
|
||||
@@ -8,18 +8,13 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
const { entryJourney, canAccessJourney, isAddonEnabled, pluginsEnabled } = vi.hoisted(() => ({
|
||||
entryJourney: vi.fn((entryId: number) => (entryId === 7 ? { journey_id: 3 } : undefined)),
|
||||
entryJourney: vi.fn((entryId: number) => (entryId === 7 ? { journey_id: 3 } : null)),
|
||||
canAccessJourney: vi.fn((journeyId: number, userId: number) => (journeyId === 3 && userId === 5 ? { id: 3 } : null)),
|
||||
isAddonEnabled: vi.fn(() => true),
|
||||
pluginsEnabled: vi.fn(() => true),
|
||||
}));
|
||||
vi.mock('../../../src/db/database', () => ({
|
||||
db: { prepare: () => ({ get: (entryId: number) => entryJourney(entryId) }) },
|
||||
canAccessTrip: vi.fn(),
|
||||
}));
|
||||
import { db as dbConn } from '../../../src/db/database';
|
||||
import { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
import type { JourneyDomainService } from '../../../src/nest/journey/journey-domain.service';
|
||||
import type { JourneyEntriesRepository } from '../../../src/db/repositories/JourneyEntries.repository';
|
||||
vi.mock('../../../src/nest/plugins/kill-switch', () => ({ pluginsEnabled }));
|
||||
|
||||
import { JournalEntryRowsController } from '../../../src/nest/plugins/contributions/journal-entry-rows.controller';
|
||||
@@ -27,6 +22,10 @@ import type { PluginHooks } from '../../../src/nest/plugins/plugin-hooks.service
|
||||
import type { AddonsService } from '../../../src/nest/addons/addons.service';
|
||||
|
||||
const addonsStub = { isAddonEnabled } as unknown as AddonsService;
|
||||
// JEC1 (Plan 3g Task 4) — `JournalEntryRowsController` now injects
|
||||
// `JourneyEntriesRepository` instead of the raw `DatabaseService`/`db.prepare`
|
||||
// stub this test used to mock; `findById` stands in for the converted read.
|
||||
const journeyEntriesStub = { findById: vi.fn((entryId: number) => entryJourney(entryId)) } as unknown as JourneyEntriesRepository;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const req = (id?: number) => ({ user: id === undefined ? undefined : { id } }) as any;
|
||||
@@ -35,7 +34,7 @@ function controller(invoke: (id: string) => unknown, providers = ['p1']) {
|
||||
providersOf: vi.fn(() => providers),
|
||||
journalRows: vi.fn(async (id: string) => invoke(id)),
|
||||
} as unknown as PluginHooks;
|
||||
return { c: new JournalEntryRowsController(runtime, new DatabaseService(dbConn), addonsStub, { canAccessJourney } as unknown as JourneyDomainService), runtime };
|
||||
return { c: new JournalEntryRowsController(runtime, journeyEntriesStub, addonsStub, { canAccessJourney } as unknown as JourneyDomainService), runtime };
|
||||
}
|
||||
const row = (over: Record<string, unknown> = {}) => ({ label: 'Distance', value: '12 km', ...over });
|
||||
|
||||
|
||||
@@ -5,19 +5,8 @@
|
||||
* to link and no provider asset. These cases pin what the handler refuses before
|
||||
* it writes anything, and that a refused write leaves no object behind.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
// vi.mock is hoisted above the imports, so the flag it reads has to be too.
|
||||
// Only readEnv().demo is overridden: the module is shared, and replacing it
|
||||
// wholesale takes defaultLanguage and the rest of the env with it.
|
||||
const { demo } = vi.hoisted(() => ({ demo: { enabled: false } }));
|
||||
vi.mock('../../../src/app-config', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../../src/app-config')>();
|
||||
return { ...actual, readEnv: () => ({ ...actual.readEnv(), demo }) };
|
||||
});
|
||||
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { JournalRpc } from '../../../src/nest/journey/journal.rpc';
|
||||
import { DEMO_EMAIL_PRIMARY } from '../../../src/nest/common/demo';
|
||||
|
||||
const ACTOR = { actingUserId: 7 } as never;
|
||||
const PNG = Buffer.from('89504e470d0a1a0a', 'hex').toString('base64');
|
||||
@@ -25,8 +14,10 @@ const PNG = Buffer.from('89504e470d0a1a0a', 'hex').toString('base64');
|
||||
function build(overrides: {
|
||||
addPhoto?: unknown;
|
||||
allowed?: string;
|
||||
demoEnabled?: boolean;
|
||||
email?: string;
|
||||
/** SV8 (Plan 3i, R-survivors) — JournalRpc now delegates the whole demo-mode
|
||||
* check (env-enabled + email match) to `DemoService.isDemoUserId`, so the
|
||||
* test double only needs to say whether that call refuses. */
|
||||
demoBlocked?: boolean;
|
||||
} = {}) {
|
||||
// Typed parameters so the assertions below can index mock.calls.
|
||||
const put = vi.fn(async (_category: string, _filename: string, _body?: unknown, _opts?: unknown) => undefined);
|
||||
@@ -36,25 +27,20 @@ function build(overrides: {
|
||||
? () => ({ id: 5, photo_id: 42 })
|
||||
: () => overrides.addPhoto);
|
||||
|
||||
demo.enabled = overrides.demoEnabled ?? false;
|
||||
|
||||
const rpc = new JournalRpc(
|
||||
{ addPhoto } as never,
|
||||
{ requireAddon: vi.fn() } as never,
|
||||
{ put, delete: del } as never,
|
||||
{ get: () => overrides.allowed ?? '*' } as never,
|
||||
{ scheduleUpload } as never,
|
||||
{ prepare: () => ({ get: () => ({ email: overrides.email ?? 'user@example.test' }) }) } as never,
|
||||
// SV8 — Plan 3i: DemoService.isDemoUserId, the shared demo-gate primitive.
|
||||
{ isDemoUserId: async () => overrides.demoBlocked ?? false } as never,
|
||||
);
|
||||
return { rpc, put, del, scheduleUpload, addPhoto };
|
||||
}
|
||||
|
||||
const input = (over: Record<string, unknown> = {}) => ({ name: 'photo.jpg', content_base64: PNG, ...over });
|
||||
|
||||
beforeEach(() => {
|
||||
demo.enabled = false;
|
||||
});
|
||||
|
||||
describe('journal.addEntryPhoto', () => {
|
||||
it('JPHOTO-001: stores the bytes under a name of its own, then links the photo', async () => {
|
||||
const { rpc, put, scheduleUpload, addPhoto } = build();
|
||||
@@ -129,7 +115,7 @@ describe('journal.addEntryPhoto', () => {
|
||||
});
|
||||
|
||||
it('JPHOTO-007: refuses to write bytes for a demo user, exactly as the REST upload does', async () => {
|
||||
const { rpc, put } = build({ demoEnabled: true, email: DEMO_EMAIL_PRIMARY });
|
||||
const { rpc, put } = build({ demoBlocked: true });
|
||||
|
||||
await expect(rpc.addEntryPhoto({ entryId: 3, input: input() }, ACTOR)).rejects.toThrow(/disabled in demo mode/);
|
||||
expect(put).not.toHaveBeenCalled();
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
const { canAccessTrip, pluginsEnabled } = vi.hoisted(() => ({
|
||||
canAccessTrip: vi.fn((tripId: number, userId: number) => (tripId === 1 && userId === 5 ? { id: 1 } : undefined)),
|
||||
canAccessTrip: vi.fn(async (tripId: number, userId: number) => (tripId === 1 && userId === 5 ? { id: 1 } : undefined)),
|
||||
pluginsEnabled: vi.fn(() => true),
|
||||
}));
|
||||
vi.mock('../../../src/db/database', () => ({ db: { prepare: () => ({ get: () => undefined }) }, canAccessTrip }));
|
||||
@@ -16,7 +16,7 @@ vi.mock('../../../src/nest/plugins/kill-switch', () => ({ pluginsEnabled }));
|
||||
|
||||
import { MapLayersController } from '../../../src/nest/plugins/contributions/map-layers.controller';
|
||||
import type { PluginHooks } from '../../../src/nest/plugins/plugin-hooks.service';
|
||||
import type { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
import type { TripsRepository } from '../../../src/db/repositories/Trips.repository';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const req = (id?: number) => ({ user: id === undefined ? undefined : { id } }) as any;
|
||||
@@ -25,7 +25,7 @@ function controller(invoke: (id: string) => unknown, providers = ['p1']) {
|
||||
providersOf: vi.fn(() => providers),
|
||||
mapLayers: vi.fn(async (id: string) => invoke(id)),
|
||||
} as unknown as PluginHooks;
|
||||
return { c: new MapLayersController(runtime, { canAccessTrip } as unknown as DatabaseService), runtime };
|
||||
return { c: new MapLayersController(runtime, { findAccessible: canAccessTrip } as unknown as TripsRepository), runtime };
|
||||
}
|
||||
const line = (n = 3, over: Record<string, unknown> = {}) => ({
|
||||
type: 'polyline',
|
||||
@@ -35,7 +35,7 @@ const line = (n = 3, over: Record<string, unknown> = {}) => ({
|
||||
const layer = (features: unknown[], over: Record<string, unknown> = {}) => ({ id: 'l1', features, ...over });
|
||||
|
||||
describe('MapLayersController', () => {
|
||||
beforeEach(() => { pluginsEnabled.mockReturnValue(true); canAccessTrip.mockReturnValue({ id: 1 } as never); });
|
||||
beforeEach(() => { pluginsEnabled.mockReturnValue(true); canAccessTrip.mockResolvedValue({ id: 1 } as never); });
|
||||
|
||||
it('gates: disabled / no user / non-member all return [] (no plugin calls on the first)', async () => {
|
||||
pluginsEnabled.mockReturnValue(false);
|
||||
@@ -45,7 +45,7 @@ describe('MapLayersController', () => {
|
||||
pluginsEnabled.mockReturnValue(true);
|
||||
|
||||
expect((await controller(() => [layer([line()])]).c.get('1', req(undefined))).layers).toEqual([]);
|
||||
canAccessTrip.mockReturnValue(undefined as never);
|
||||
canAccessTrip.mockResolvedValue(undefined as never);
|
||||
expect((await controller(() => [layer([line()])]).c.get('1', req(5))).layers).toEqual([]);
|
||||
});
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
const { canAccessTrip, pluginsEnabled } = vi.hoisted(() => ({
|
||||
canAccessTrip: vi.fn((tripId: number, userId: number) => (tripId === 1 && userId === 5 ? { id: 1 } : undefined)),
|
||||
canAccessTrip: vi.fn(async (tripId: number, userId: number) => (tripId === 1 && userId === 5 ? { id: 1 } : undefined)),
|
||||
pluginsEnabled: vi.fn(() => true),
|
||||
}));
|
||||
vi.mock('../../../src/db/database', () => ({ db: { prepare: () => ({ get: () => undefined }) }, canAccessTrip }));
|
||||
@@ -15,7 +15,7 @@ vi.mock('../../../src/nest/plugins/kill-switch', () => ({ pluginsEnabled }));
|
||||
|
||||
import { MapMarkersController } from '../../../src/nest/plugins/contributions/map-markers.controller';
|
||||
import type { PluginHooks } from '../../../src/nest/plugins/plugin-hooks.service';
|
||||
import type { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
import type { TripsRepository } from '../../../src/db/repositories/Trips.repository';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const req = (id?: number) => ({ user: id === undefined ? undefined : { id } }) as any;
|
||||
@@ -24,12 +24,12 @@ function controller(invoke: (id: string) => unknown, providers = ['p1']) {
|
||||
providersOf: vi.fn(() => providers),
|
||||
mapMarkers: vi.fn(async (id: string) => invoke(id)),
|
||||
} as unknown as PluginHooks;
|
||||
return { c: new MapMarkersController(runtime, { canAccessTrip } as unknown as DatabaseService), runtime };
|
||||
return { c: new MapMarkersController(runtime, { findAccessible: canAccessTrip } as unknown as TripsRepository), runtime };
|
||||
}
|
||||
const mk = (over: Record<string, unknown> = {}) => ({ id: 'm1', lat: 48.85, lng: 2.35, ...over });
|
||||
|
||||
describe('MapMarkersController', () => {
|
||||
beforeEach(() => { pluginsEnabled.mockReturnValue(true); canAccessTrip.mockReturnValue({ id: 1 } as never); });
|
||||
beforeEach(() => { pluginsEnabled.mockReturnValue(true); canAccessTrip.mockResolvedValue({ id: 1 } as never); });
|
||||
|
||||
it('gates: disabled / no user / non-member all return [] (no plugin calls on the first)', async () => {
|
||||
pluginsEnabled.mockReturnValue(false);
|
||||
@@ -39,7 +39,7 @@ describe('MapMarkersController', () => {
|
||||
pluginsEnabled.mockReturnValue(true);
|
||||
|
||||
expect((await controller(() => [mk()]).c.get('1', req(undefined))).markers).toEqual([]);
|
||||
canAccessTrip.mockReturnValue(undefined as never);
|
||||
canAccessTrip.mockResolvedValue(undefined as never);
|
||||
expect((await controller(() => [mk()]).c.get('1', req(5))).markers).toEqual([]);
|
||||
});
|
||||
|
||||
|
||||
@@ -47,30 +47,30 @@ describe('setPluginMcpToolSource', () => {
|
||||
});
|
||||
|
||||
describe('registerTools wiring', () => {
|
||||
it('MCPSINK-003: passes no dynamic source when none is registered', () => {
|
||||
it('MCPSINK-003: passes no dynamic source when none is registered', async () => {
|
||||
const { attach, registry } = spyRegistry();
|
||||
|
||||
registerTools(registry, new McpServer({ name: 't', version: '1' }), 1, null);
|
||||
await registerTools(registry, new McpServer({ name: 't', version: '1' }), 1, null);
|
||||
|
||||
expect(attach.mock.calls[0][2]).toEqual({ onInvoke: undefined, dynamicTools: undefined });
|
||||
});
|
||||
|
||||
it('MCPSINK-004: passes the registered source through to attach', () => {
|
||||
it('MCPSINK-004: passes the registered source through to attach', async () => {
|
||||
const source = (_ctx: McpContext) => [echo];
|
||||
setPluginMcpToolSource(source);
|
||||
const { attach, registry } = spyRegistry();
|
||||
|
||||
registerTools(registry, new McpServer({ name: 't', version: '1' }), 1, null);
|
||||
await registerTools(registry, new McpServer({ name: 't', version: '1' }), 1, null);
|
||||
|
||||
expect(attach.mock.calls[0][2].dynamicTools).toBe(source);
|
||||
});
|
||||
|
||||
it('MCPSINK-005: an explicit argument wins over the process-level source', () => {
|
||||
it('MCPSINK-005: an explicit argument wins over the process-level source', async () => {
|
||||
setPluginMcpToolSource(() => [echo]);
|
||||
const explicit = () => [];
|
||||
const { attach, registry } = spyRegistry();
|
||||
|
||||
registerTools(registry, new McpServer({ name: 't', version: '1' }), 1, null, false, undefined, undefined, explicit);
|
||||
await registerTools(registry, new McpServer({ name: 't', version: '1' }), 1, null, false, undefined, undefined, explicit);
|
||||
|
||||
expect(attach.mock.calls[0][2].dynamicTools).toBe(explicit);
|
||||
});
|
||||
|
||||
@@ -12,25 +12,29 @@
|
||||
* - it is always the ADMIN, never an end user, who widens it;
|
||||
* - changing the set RE-SPAWNS the plugin, because the child's guard is install-once.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest';
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
const { testDb, dbMock } = vi.hoisted(() => {
|
||||
const Database = require('better-sqlite3');
|
||||
const db = new Database(':memory:');
|
||||
return { testDb: db, dbMock: { db, closeDb: () => {}, reinitialize: () => {}, canAccessTrip: () => null } };
|
||||
vi.mock('../../../src/db/database', async () => {
|
||||
const { createSnapshotTestDb } = await import('../../helpers/db-mock');
|
||||
const db = createSnapshotTestDb();
|
||||
return { db, closeDb: () => {}, reinitialize: () => {}, canAccessTrip: async () => null };
|
||||
});
|
||||
vi.mock('../../../src/db/database', () => dbMock);
|
||||
import { db as dbConn } from '../../../src/db/database';
|
||||
import { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
import { db as testDb } from '../../../src/db/database';
|
||||
vi.mock('../../../src/config', () => ({ JWT_SECRET: 'x'.repeat(40), ENCRYPTION_KEY: 'a'.repeat(64), updateJwtSecret: () => {} }));
|
||||
|
||||
import { createTables } from '../../../src/db/schema';
|
||||
import { runMigrations } from '../../../src/db/migrations';
|
||||
import { PluginRuntimeService } from '../../../src/nest/plugins/plugin-runtime.service';
|
||||
import { createPluginRuntime } from '../../helpers/plugin-host';
|
||||
import { parseManifest, ManifestError } from '../../../src/nest/plugins/install/manifest';
|
||||
import { makeHostAllow } from '../../../src/nest/plugins/runtime/egress-policy';
|
||||
import { AddonsService } from '../../../src/nest/addons/addons.service';
|
||||
import { createTestAddonsService } from '../../helpers/test-addons';
|
||||
import { sharedTestOrm } from '../../helpers/test-uow';
|
||||
import { Plugins } from '../../../src/db/entities/Plugins.entity';
|
||||
import { PluginErrorLog } from '../../../src/db/entities/PluginErrorLog.entity';
|
||||
import { PluginEgressHosts } from '../../../src/db/entities/PluginEgressHosts.entity';
|
||||
import { PluginSettingsFields } from '../../../src/db/entities/PluginSettingsFields.entity';
|
||||
import { PluginActions } from '../../../src/db/entities/PluginActions.entity';
|
||||
import { PluginUserConfig } from '../../../src/db/entities/PluginUserConfig.entity';
|
||||
import { PluginCapabilityAudit } from '../../../src/db/entities/PluginCapabilityAudit.entity';
|
||||
|
||||
function install(id: string, operatorEgress: boolean, perms: string[] = ['http:outbound:gotify.net']) {
|
||||
testDb.prepare(
|
||||
@@ -41,29 +45,28 @@ function install(id: string, operatorEgress: boolean, perms: string[] = ['http:o
|
||||
|
||||
let rt: PluginRuntimeService;
|
||||
|
||||
beforeAll(() => { createTables(testDb); runMigrations(testDb); });
|
||||
beforeEach(() => {
|
||||
beforeEach(async () => {
|
||||
testDb.prepare('DELETE FROM plugins').run();
|
||||
testDb.prepare('DELETE FROM plugin_egress_hosts').run();
|
||||
testDb.prepare('DELETE FROM plugin_actions').run();
|
||||
rt = createPluginRuntime(new DatabaseService(dbConn));
|
||||
rt = await createPluginRuntime(testDb);
|
||||
});
|
||||
|
||||
describe('operator-supplied egress hosts', () => {
|
||||
it('OEG-001 — an admin can add hosts to a plugin that declared operatorEgress', async () => {
|
||||
install('gotify', true);
|
||||
expect(rt.wantsOperatorEgress('gotify')).toBe(true);
|
||||
expect(await rt.wantsOperatorEgress('gotify')).toBe(true);
|
||||
expect(await rt.setOperatorEgressHosts('gotify', ['gotify.mydomain.com'])).toEqual(['gotify.mydomain.com']);
|
||||
expect(rt.operatorEgressHosts('gotify')).toEqual(['gotify.mydomain.com']);
|
||||
expect(await rt.operatorEgressHosts('gotify')).toEqual(['gotify.mydomain.com']);
|
||||
});
|
||||
|
||||
it('OEG-002 — a plugin that did NOT declare it can never have hosts added', async () => {
|
||||
install('sneaky', false);
|
||||
expect(rt.wantsOperatorEgress('sneaky')).toBe(false);
|
||||
expect(await rt.wantsOperatorEgress('sneaky')).toBe(false);
|
||||
// This is the load-bearing check: without it an admin could silently widen egress for
|
||||
// ANY plugin, and the install-time consent would stop bounding what's possible.
|
||||
await expect(rt.setOperatorEgressHosts('sneaky', ['evil.example.com'])).rejects.toThrow(/did not declare operatorEgress/);
|
||||
expect(rt.operatorEgressHosts('sneaky')).toEqual([]);
|
||||
expect(await rt.operatorEgressHosts('sneaky')).toEqual([]);
|
||||
});
|
||||
|
||||
it('OEG-003 — hosts are validated exactly like manifest egress', async () => {
|
||||
@@ -86,7 +89,7 @@ describe('operator-supplied egress hosts', () => {
|
||||
install('gotify', true);
|
||||
await rt.setOperatorEgressHosts('gotify', ['a.example.com', 'b.example.com']);
|
||||
await rt.setOperatorEgressHosts('gotify', ['b.example.com']);
|
||||
expect(rt.operatorEgressHosts('gotify')).toEqual(['b.example.com']);
|
||||
expect(await rt.operatorEgressHosts('gotify')).toEqual(['b.example.com']);
|
||||
});
|
||||
|
||||
it('OEG-006 — the manifest rejects operatorEgress without an outbound permission', () => {
|
||||
@@ -113,7 +116,7 @@ describe('operator-supplied egress hosts', () => {
|
||||
// It ACTIVATES (it may have useful offline features), but the child's allow-list is the
|
||||
// union of its http:outbound:<host> grants and the admin's hosts — both empty here.
|
||||
install('gotify', true, ['http:outbound']);
|
||||
expect(rt.operatorEgressHosts('gotify')).toEqual([]);
|
||||
expect(await rt.operatorEgressHosts('gotify')).toEqual([]);
|
||||
expect(makeHostAllow([])('gotify.mydomain.com')).toBe(false);
|
||||
});
|
||||
|
||||
@@ -122,7 +125,7 @@ describe('operator-supplied egress hosts', () => {
|
||||
await rt.setOperatorEgressHosts('gotify', ['gotify.mydomain.com']);
|
||||
await rt.uninstall('gotify', false);
|
||||
// A LATER plugin reusing this id must not silently inherit hosts approved for another.
|
||||
expect(rt.operatorEgressHosts('gotify')).toEqual([]);
|
||||
expect(await rt.operatorEgressHosts('gotify')).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -132,12 +135,12 @@ describe('settings-page actions (runtime)', () => {
|
||||
.run(id, key, key, scope);
|
||||
}
|
||||
|
||||
it('ACT-001 — actionsOf returns the declared descriptors of ONE scope', () => {
|
||||
it('ACT-001 — actionsOf returns the declared descriptors of ONE scope', async () => {
|
||||
install('p', false);
|
||||
declareAction('p', 'testConnection');
|
||||
declareAction('p', 'purge', 'instance');
|
||||
expect(rt.actionsOf('p', 'user')).toEqual([{ key: 'testConnection', label: 'testConnection', hint: undefined, danger: false, scope: 'user' }]);
|
||||
expect(rt.actionsOf('p', 'instance')).toEqual([{ key: 'purge', label: 'purge', hint: undefined, danger: false, scope: 'instance' }]);
|
||||
expect(await rt.actionsOf('p', 'user')).toEqual([{ key: 'testConnection', label: 'testConnection', hint: undefined, danger: false, scope: 'user' }]);
|
||||
expect(await rt.actionsOf('p', 'instance')).toEqual([{ key: 'purge', label: 'purge', hint: undefined, danger: false, scope: 'instance' }]);
|
||||
});
|
||||
|
||||
it('ACT-002 — invoking an action the plugin never declared is REFUSED', async () => {
|
||||
@@ -172,18 +175,28 @@ describe('the admin list surfaces operator egress (so the chip can be shown)', (
|
||||
|
||||
// list() resolves required-addon dependencies through AddonsService, so it gets a real
|
||||
// one over the same DB. These fixtures declare no dependencies, so it is never consulted.
|
||||
const listPlugins = () => {
|
||||
const dbs = new DatabaseService(dbConn);
|
||||
return new PluginsService(dbs, new AddonsService(dbs)).list().plugins;
|
||||
const listPlugins = async () => {
|
||||
const orm = await sharedTestOrm(testDb);
|
||||
const service = new PluginsService(
|
||||
await createTestAddonsService(testDb),
|
||||
orm.repo(Plugins),
|
||||
orm.repo(PluginEgressHosts),
|
||||
orm.repo(PluginSettingsFields),
|
||||
orm.repo(PluginActions),
|
||||
orm.repo(PluginUserConfig),
|
||||
orm.repo(PluginErrorLog),
|
||||
orm.repo(PluginCapabilityAudit),
|
||||
);
|
||||
return (await service.list()).plugins;
|
||||
};
|
||||
|
||||
const before = listPlugins();
|
||||
const before = await listPlugins();
|
||||
expect(before.find(p => p.id === 'gotify')).toMatchObject({ operatorEgress: true, egressHostCount: 0 });
|
||||
// A plugin that never asked for it must never invite the admin to add hosts.
|
||||
expect(before.find(p => p.id === 'plain')).toMatchObject({ operatorEgress: false, egressHostCount: 0 });
|
||||
|
||||
await rt.setOperatorEgressHosts('gotify', ['a.example.com', 'b.example.com']);
|
||||
const after = listPlugins();
|
||||
const after = await listPlugins();
|
||||
expect(after.find(p => p.id === 'gotify')!.egressHostCount).toBe(2);
|
||||
delete process.env.TREK_PLUGINS_ENABLED;
|
||||
});
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
const { canAccessTrip, pluginsEnabled } = vi.hoisted(() => ({
|
||||
canAccessTrip: vi.fn((tripId: number, userId: number) => (tripId === 1 && userId === 5 ? { id: 1 } : undefined)),
|
||||
canAccessTrip: vi.fn(async (tripId: number, userId: number) => (tripId === 1 && userId === 5 ? { id: 1 } : undefined)),
|
||||
pluginsEnabled: vi.fn(() => true),
|
||||
}));
|
||||
vi.mock('../../../src/db/database', () => ({ db: { prepare: () => ({ get: () => undefined }) }, canAccessTrip }));
|
||||
@@ -16,7 +16,7 @@ vi.mock('../../../src/nest/plugins/kill-switch', () => ({ pluginsEnabled }));
|
||||
|
||||
import { PdfSectionsController } from '../../../src/nest/plugins/contributions/pdf-sections.controller';
|
||||
import type { PluginHooks } from '../../../src/nest/plugins/plugin-hooks.service';
|
||||
import type { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
import type { TripsRepository } from '../../../src/db/repositories/Trips.repository';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const req = (id?: number) => ({ user: id === undefined ? undefined : { id } }) as any;
|
||||
@@ -25,12 +25,12 @@ function controller(invoke: (id: string) => unknown, providers = ['p1']) {
|
||||
providersOf: vi.fn(() => providers),
|
||||
pdfSections: vi.fn(async (id: string) => invoke(id)),
|
||||
} as unknown as PluginHooks;
|
||||
return { c: new PdfSectionsController(runtime, { canAccessTrip } as unknown as DatabaseService), runtime };
|
||||
return { c: new PdfSectionsController(runtime, { findAccessible: canAccessTrip } as unknown as TripsRepository), runtime };
|
||||
}
|
||||
const sec = (over: Record<string, unknown> = {}) => ({ title: 'Weather', ...over });
|
||||
|
||||
describe('PdfSectionsController', () => {
|
||||
beforeEach(() => { pluginsEnabled.mockReturnValue(true); canAccessTrip.mockReturnValue({ id: 1 } as never); });
|
||||
beforeEach(() => { pluginsEnabled.mockReturnValue(true); canAccessTrip.mockResolvedValue({ id: 1 } as never); });
|
||||
|
||||
it('gates: disabled / bad tripId / no user / non-member all return [] (no plugin calls on the first)', async () => {
|
||||
pluginsEnabled.mockReturnValue(false);
|
||||
@@ -41,7 +41,7 @@ describe('PdfSectionsController', () => {
|
||||
|
||||
expect((await controller(() => [sec()]).c.get('abc', req(5))).sections).toEqual([]);
|
||||
expect((await controller(() => [sec()]).c.get('1', req(undefined))).sections).toEqual([]);
|
||||
canAccessTrip.mockReturnValue(undefined as never);
|
||||
canAccessTrip.mockResolvedValue(undefined as never);
|
||||
expect((await controller(() => [sec()]).c.get('1', req(5))).sections).toEqual([]);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
const { canAccessTrip, placeTrip, pluginsEnabled } = vi.hoisted(() => ({
|
||||
canAccessTrip: vi.fn((tripId: number, userId: number) => (tripId === 1 && userId === 5 ? { id: 1 } : undefined)),
|
||||
canAccessTrip: vi.fn(async (tripId: number, userId: number) => (tripId === 1 && userId === 5 ? { id: 1 } : undefined)),
|
||||
placeTrip: vi.fn((placeId: number) => (placeId === 7 ? { trip_id: 1 } : undefined)),
|
||||
pluginsEnabled: vi.fn(() => true),
|
||||
}));
|
||||
@@ -9,12 +9,12 @@ vi.mock('../../../src/db/database', () => ({
|
||||
db: { prepare: () => ({ get: (placeId: number) => placeTrip(placeId) }) },
|
||||
canAccessTrip,
|
||||
}));
|
||||
import { db as dbConn } from '../../../src/db/database';
|
||||
import { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
import type { TripsRepository } from '../../../src/db/repositories/Trips.repository';
|
||||
vi.mock('../../../src/nest/plugins/kill-switch', () => ({ pluginsEnabled }));
|
||||
|
||||
import { PlaceDetailsController } from '../../../src/nest/plugins/contributions/place-details.controller';
|
||||
import type { PluginHooks } from '../../../src/nest/plugins/plugin-hooks.service';
|
||||
import type { PlacesRepository } from '../../../src/db/repositories/Places.repository';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const req = (id?: number) => ({ user: id === undefined ? undefined : { id } }) as any;
|
||||
@@ -24,11 +24,13 @@ function controller(over: Partial<PluginHooks> = {}) {
|
||||
placeDetails: vi.fn(async (id: string) => (id === 'p2' ? [{ label: 'Rating', value: '4.5' }] : [{ label: 'Reviews', value: '12', url: 'https://x' }])),
|
||||
...over,
|
||||
} as unknown as PluginHooks;
|
||||
return { c: new PlaceDetailsController(runtime, new DatabaseService(dbConn)), runtime };
|
||||
// CT7 (Plan 3j Task 5) — the place's owning trip id is now Places.repository.ts#findTripId.
|
||||
const places = { findTripId: vi.fn(async (placeId: number) => placeTrip(placeId)?.trip_id) } as unknown as PlacesRepository;
|
||||
return { c: new PlaceDetailsController(runtime, { findAccessible: canAccessTrip } as unknown as TripsRepository, places), runtime };
|
||||
}
|
||||
|
||||
describe('PlaceDetailsController', () => {
|
||||
beforeEach(() => { pluginsEnabled.mockReturnValue(true); canAccessTrip.mockReturnValue({ id: 1 } as never); });
|
||||
beforeEach(() => { pluginsEnabled.mockReturnValue(true); canAccessTrip.mockResolvedValue({ id: 1 } as never); });
|
||||
|
||||
it('returns [] when the runtime is disabled (no plugin calls)', async () => {
|
||||
pluginsEnabled.mockReturnValue(false);
|
||||
@@ -40,7 +42,7 @@ describe('PlaceDetailsController', () => {
|
||||
it('returns [] for an unknown place or a place the caller cannot access', async () => {
|
||||
const { c } = controller();
|
||||
expect(await c.get('999', req(5))).toEqual({ providers: [] }); // place not found
|
||||
canAccessTrip.mockReturnValue(undefined as never);
|
||||
canAccessTrip.mockResolvedValue(undefined as never);
|
||||
expect(await c.get('7', req(5))).toEqual({ providers: [] }); // no access
|
||||
});
|
||||
|
||||
|
||||
@@ -1,18 +1,59 @@
|
||||
/**
|
||||
* Host-side capability audit log (#plugins, L1 hardening): resource projection,
|
||||
* which methods are auditable, and the per-plugin hash chain.
|
||||
*
|
||||
* Plan 3j Task 3 — converted onto `PluginCapabilityAuditRepository`. R-hash-chain:
|
||||
* `legacyAppendAudit` below is a byte-for-byte replica of the PRE-CONVERSION
|
||||
* `appendAudit` body (a raw `better-sqlite3` INSERT, the exact hash construction
|
||||
* this task's `plugin-audit.ts` now reproduces through the repository) — it exists
|
||||
* SOLELY so these tests can produce a "legacy-written" chain to replay against the
|
||||
* converted code, without keeping a second, unused copy of the production function
|
||||
* around.
|
||||
*/
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import Database from 'better-sqlite3';
|
||||
import { appendAudit, readAudit, readAuditForUser, auditResource, isAuditable, pruneAudit } from '../../../src/nest/plugins/host/plugin-audit';
|
||||
import { describe, it, expect, beforeAll, beforeEach, afterAll } from 'vitest';
|
||||
import crypto from 'node:crypto';
|
||||
import { createSnapshotTestDb } from '../../helpers/db-mock';
|
||||
import { resetTestDb } from '../../helpers/test-db';
|
||||
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
|
||||
import { PluginCapabilityAudit } from '../../../src/db/entities/PluginCapabilityAudit.entity';
|
||||
import type { PluginCapabilityAuditRepository } from '../../../src/db/repositories/PluginCapabilityAudit.repository';
|
||||
import { appendAudit, readAudit, readAuditForUser, auditResource, isAuditable, pruneAudit, verifyChain } from '../../../src/nest/plugins/host/plugin-audit';
|
||||
|
||||
function makeDb() {
|
||||
const db = new Database(':memory:');
|
||||
db.exec(`CREATE TABLE 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,
|
||||
prev_hash TEXT, hash TEXT NOT NULL);`);
|
||||
return db;
|
||||
const testDb = createSnapshotTestDb();
|
||||
let t: TestOrm;
|
||||
let audit: PluginCapabilityAuditRepository;
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestOrm(testDb);
|
||||
audit = t.repo(PluginCapabilityAudit);
|
||||
});
|
||||
beforeEach(() => { resetTestDb(testDb); t.clear(); });
|
||||
afterAll(async () => { await t.close(); testDb.close(); });
|
||||
|
||||
interface LegacyEntry {
|
||||
pluginId: string;
|
||||
actingUserId?: number;
|
||||
method: string;
|
||||
resource?: string | null;
|
||||
code: string;
|
||||
}
|
||||
|
||||
/** The pre-conversion `appendAudit` body, verbatim, against a raw connection. */
|
||||
function legacyAppendAudit(prevHash: string, e: LegacyEntry): { ts: string; hash: string } {
|
||||
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(prevHash + row).digest('hex');
|
||||
testDb
|
||||
.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, prevHash || null, hash);
|
||||
return { ts, hash };
|
||||
}
|
||||
|
||||
/** Every row for a plugin, oldest first — the shape `verifyChain` needs. */
|
||||
function chainRows(pluginId: string) {
|
||||
return testDb
|
||||
.prepare('SELECT plugin_id, acting_user_id, method, resource, code, ts, prev_hash, hash FROM plugin_capability_audit WHERE plugin_id = ? ORDER BY id ASC')
|
||||
.all(pluginId) as Array<{ plugin_id: string; acting_user_id: number | null; method: string; resource: string | null; code: string; ts: string; prev_hash: string | null; hash: string }>;
|
||||
}
|
||||
|
||||
describe('auditResource + isAuditable', () => {
|
||||
@@ -40,67 +81,134 @@ describe('auditResource + isAuditable', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('appendAudit hash chain', () => {
|
||||
let db: ReturnType<typeof makeDb>;
|
||||
beforeEach(() => { db = makeDb(); });
|
||||
|
||||
it('chains each entry off the previous hash (per plugin)', () => {
|
||||
appendAudit(db, { pluginId: 'p', actingUserId: 42, method: 'trips.getById', resource: 'trip:1', code: 'ok' });
|
||||
appendAudit(db, { pluginId: 'p', actingUserId: 42, method: 'trips.getById', resource: 'trip:2', code: 'ok' });
|
||||
const rows = db.prepare('SELECT prev_hash, hash FROM plugin_capability_audit ORDER BY id').all() as Array<{ prev_hash: string | null; hash: string }>;
|
||||
describe('appendAudit hash chain (converted, through PluginCapabilityAuditRepository)', () => {
|
||||
it('chains each entry off the previous hash (per plugin)', async () => {
|
||||
await appendAudit(audit, { pluginId: 'p', actingUserId: 42, method: 'trips.getById', resource: 'trip:1', code: 'ok' });
|
||||
await appendAudit(audit, { pluginId: 'p', actingUserId: 42, method: 'trips.getById', resource: 'trip:2', code: 'ok' });
|
||||
const rows = testDb.prepare('SELECT prev_hash, hash FROM plugin_capability_audit ORDER BY id').all() as Array<{ prev_hash: string | null; hash: string }>;
|
||||
expect(rows).toHaveLength(2);
|
||||
expect(rows[0].prev_hash).toBeNull();
|
||||
expect(rows[1].prev_hash).toBe(rows[0].hash); // chain links
|
||||
expect(rows[1].hash).not.toBe(rows[0].hash);
|
||||
});
|
||||
|
||||
it('keeps separate chains per plugin', () => {
|
||||
appendAudit(db, { pluginId: 'a', method: 'trips.getById', resource: 'trip:1', code: 'ok' });
|
||||
appendAudit(db, { pluginId: 'b', method: 'trips.getById', resource: 'trip:1', code: 'ok' });
|
||||
const a = db.prepare("SELECT prev_hash FROM plugin_capability_audit WHERE plugin_id='b'").get() as { prev_hash: string | null };
|
||||
expect(a.prev_hash).toBeNull(); // b's first entry doesn't chain off a's
|
||||
it('keeps separate chains per plugin', async () => {
|
||||
await appendAudit(audit, { pluginId: 'a', method: 'trips.getById', resource: 'trip:1', code: 'ok' });
|
||||
await appendAudit(audit, { pluginId: 'b', method: 'trips.getById', resource: 'trip:1', code: 'ok' });
|
||||
const b = testDb.prepare("SELECT prev_hash FROM plugin_capability_audit WHERE plugin_id='b'").get() as { prev_hash: string | null };
|
||||
expect(b.prev_hash).toBeNull(); // b's first entry doesn't chain off a's
|
||||
});
|
||||
|
||||
it('records denials too (code is the error code)', () => {
|
||||
appendAudit(db, { pluginId: 'p', actingUserId: 99, method: 'trips.getById', resource: 'trip:1', code: 'RESOURCE_FORBIDDEN' });
|
||||
const row = readAudit(db, 'p')[0] as { code: string; method: string };
|
||||
it('records denials too (code is the error code)', async () => {
|
||||
await appendAudit(audit, { pluginId: 'p', actingUserId: 99, method: 'trips.getById', resource: 'trip:1', code: 'RESOURCE_FORBIDDEN' });
|
||||
const row = (await readAudit(audit, 'p'))[0];
|
||||
expect(row.code).toBe('RESOURCE_FORBIDDEN');
|
||||
});
|
||||
|
||||
it('readAuditForUser returns one user\'s actions across ALL plugins, newest first, with the plugin name', () => {
|
||||
db.exec("CREATE TABLE plugins (id TEXT PRIMARY KEY, name TEXT)");
|
||||
db.prepare("INSERT INTO plugins (id, name) VALUES ('koffi','Koffi'), ('flight','Flight Tracker')").run();
|
||||
appendAudit(db, { pluginId: 'koffi', actingUserId: 42, method: 'trips.getById', resource: 'trip:1', code: 'ok' });
|
||||
appendAudit(db, { pluginId: 'flight', actingUserId: 42, method: 'reservations.create', resource: 'trip:1', code: 'ok' });
|
||||
appendAudit(db, { pluginId: 'koffi', actingUserId: 99, method: 'trips.getById', resource: 'trip:2', code: 'ok' }); // another user
|
||||
const mine = readAuditForUser(db, 42) as Array<{ plugin_id: string; plugin_name: string; method: string }>;
|
||||
expect(mine).toHaveLength(2); // only user 42's rows, across both plugins
|
||||
it("readAuditForUser returns one user's actions across ALL plugins, newest first, with the plugin name", async () => {
|
||||
testDb.prepare("INSERT INTO plugins (id, name) VALUES ('koffi','Koffi'), ('flight','Flight Tracker')").run();
|
||||
await appendAudit(audit, { pluginId: 'koffi', actingUserId: 42, method: 'trips.getById', resource: 'trip:1', code: 'ok' });
|
||||
await appendAudit(audit, { pluginId: 'flight', actingUserId: 42, method: 'reservations.create', resource: 'trip:1', code: 'ok' });
|
||||
await appendAudit(audit, { pluginId: 'koffi', actingUserId: 99, method: 'trips.getById', resource: 'trip:2', code: 'ok' }); // another user
|
||||
const mine = await readAuditForUser(audit, 42);
|
||||
expect(mine).toHaveLength(2); // only user 42's rows, across both plugins
|
||||
expect(mine[0]).toMatchObject({ plugin_id: 'flight', plugin_name: 'Flight Tracker', method: 'reservations.create' }); // newest first
|
||||
expect(mine[1]).toMatchObject({ plugin_id: 'koffi', plugin_name: 'Koffi' });
|
||||
expect(mine.some((r) => r.plugin_id === 'koffi' && r.method === 'trips.getById' && (r as { resource?: string }).resource === 'trip:2')).toBe(false); // never another user's
|
||||
expect(mine.some((r) => r.plugin_id === 'koffi' && r.method === 'trips.getById' && r.resource === 'trip:2')).toBe(false); // never another user's
|
||||
});
|
||||
|
||||
it('readAudit returns newest first with the projected fields only', () => {
|
||||
appendAudit(db, { pluginId: 'p', actingUserId: 42, method: 'trips.getById', resource: 'trip:1', code: 'ok' });
|
||||
const rows = readAudit(db, 'p') as Array<Record<string, unknown>>;
|
||||
it('readAudit returns newest first with the projected fields only', async () => {
|
||||
await appendAudit(audit, { pluginId: 'p', actingUserId: 42, method: 'trips.getById', resource: 'trip:1', code: 'ok' });
|
||||
const rows = await readAudit(audit, 'p');
|
||||
expect(rows[0]).toHaveProperty('method', 'trips.getById');
|
||||
expect(rows[0]).not.toHaveProperty('prev_hash'); // internal chain fields not exposed
|
||||
});
|
||||
|
||||
it('pruneAudit keeps only the newest N rows per plugin, leaving the retained window chain-consistent', () => {
|
||||
for (let i = 0; i < 50; i++) appendAudit(db, { pluginId: 'p', actingUserId: 1, method: 'trips.getById', resource: `trip:${i}`, code: 'ok' });
|
||||
appendAudit(db, { pluginId: 'other', actingUserId: 1, method: 'trips.getById', resource: 'trip:x', code: 'ok' });
|
||||
pruneAudit(db, 'p', 10);
|
||||
const rows = db.prepare("SELECT resource, prev_hash, hash FROM plugin_capability_audit WHERE plugin_id = 'p' ORDER BY id ASC").all() as Array<{ resource: string; prev_hash: string | null; hash: string }>;
|
||||
it('pruneAudit keeps only the newest N rows per plugin, leaving the retained window chain-consistent', async () => {
|
||||
for (let i = 0; i < 50; i++) await appendAudit(audit, { pluginId: 'p', actingUserId: 1, method: 'trips.getById', resource: `trip:${i}`, code: 'ok' });
|
||||
await appendAudit(audit, { pluginId: 'other', actingUserId: 1, method: 'trips.getById', resource: 'trip:x', code: 'ok' });
|
||||
await pruneAudit(audit, 'p', 10);
|
||||
const rows = testDb.prepare("SELECT resource, prev_hash, hash FROM plugin_capability_audit WHERE plugin_id = 'p' ORDER BY id ASC").all() as Array<{ resource: string; prev_hash: string | null; hash: string }>;
|
||||
expect(rows).toHaveLength(10);
|
||||
expect(rows[rows.length - 1].resource).toBe('trip:49'); // newest kept
|
||||
// each retained row is still self-consistent: hash === sha256(prev_hash + row-content)
|
||||
// (proven by re-appending on top — the chain continues from the surviving tip)
|
||||
appendAudit(db, { pluginId: 'p', actingUserId: 1, method: 'trips.getById', resource: 'trip:new', code: 'ok' });
|
||||
expect(db.prepare("SELECT COUNT(*) c FROM plugin_capability_audit WHERE plugin_id='p'").get()).toMatchObject({ c: 11 });
|
||||
await appendAudit(audit, { pluginId: 'p', actingUserId: 1, method: 'trips.getById', resource: 'trip:new', code: 'ok' });
|
||||
expect(testDb.prepare("SELECT COUNT(*) c FROM plugin_capability_audit WHERE plugin_id='p'").get()).toMatchObject({ c: 11 });
|
||||
// pruning one plugin never touches another's rows
|
||||
expect(db.prepare("SELECT COUNT(*) c FROM plugin_capability_audit WHERE plugin_id='other'").get()).toMatchObject({ c: 1 });
|
||||
expect(() => pruneAudit(db, 'p', 0)).not.toThrow(); // 0 = disabled, no-op
|
||||
expect(db.prepare("SELECT COUNT(*) c FROM plugin_capability_audit WHERE plugin_id='p'").get()).toMatchObject({ c: 11 });
|
||||
expect(testDb.prepare("SELECT COUNT(*) c FROM plugin_capability_audit WHERE plugin_id='other'").get()).toMatchObject({ c: 1 });
|
||||
await expect(pruneAudit(audit, 'p', 0)).resolves.toBeUndefined(); // 0 = disabled, no-op
|
||||
expect(testDb.prepare("SELECT COUNT(*) c FROM plugin_capability_audit WHERE plugin_id='p'").get()).toMatchObject({ c: 11 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('R-hash-chain: concurrency (Plan 3j Task 7 fix wave, must-land 1)', () => {
|
||||
it('R3J-CHAIN-002: 10 concurrent appendAudit calls for the SAME plugin produce a linear, gap-free chain (red without the per-plugin serialization fix)', async () => {
|
||||
// The exact real code path production uses: `appendAudit`, racing N callers, not a
|
||||
// sequential loop — task-7-review.md's own live 40-way burst found 108 of 120 rows
|
||||
// unlinked (108 duplicate prev_hash values) before this fix; 9 of 10 broken in an
|
||||
// earlier, in-process 10-way version of this same test.
|
||||
await Promise.all(
|
||||
Array.from({ length: 10 }, (_, i) =>
|
||||
appendAudit(audit, { pluginId: 'burst', actingUserId: 1, method: 'trips.getById', resource: `trip:${i}`, code: 'ok' }),
|
||||
),
|
||||
);
|
||||
const rows = chainRows('burst');
|
||||
expect(rows).toHaveLength(10);
|
||||
expect(verifyChain(rows)).toBe(true); // every row's prev_hash === the previous row's hash
|
||||
// No two rows share a prev_hash — the exact shape a forked chain (two racers reading
|
||||
// the SAME "previous" tip) would produce.
|
||||
const prevHashes = rows.map((r) => r.prev_hash ?? '');
|
||||
expect(new Set(prevHashes).size).toBe(prevHashes.length);
|
||||
// Exactly one row has no predecessor (the genesis of this plugin's chain).
|
||||
expect(prevHashes.filter((h) => h === '').length).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('R-hash-chain: replay, extension, mutation', () => {
|
||||
it('AUDITCHAIN-001 REPLAY+EXTENSION: verifies a legacy-produced chain, then extends it through the converted appendAudit and the WHOLE chain stays consistent', async () => {
|
||||
// 1. Write three rows the way the PRE-CONVERSION code did: raw SQL, no repository.
|
||||
let prev = '';
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const { hash } = legacyAppendAudit(prev, { pluginId: 'legacy-p', actingUserId: 7, method: 'trips.getById', resource: `trip:${i}`, code: 'ok' });
|
||||
prev = hash;
|
||||
}
|
||||
// 2. REPLAY: the converted verification logic (verifyChain) accepts the legacy-written rows.
|
||||
expect(verifyChain(chainRows('legacy-p'))).toBe(true);
|
||||
|
||||
// 3. EXTENSION: append two more rows through the CONVERTED appendAudit, on top of the
|
||||
// legacy tip — the repository reads the legacy row's hash as its own prev_hash.
|
||||
await appendAudit(audit, { pluginId: 'legacy-p', actingUserId: 7, method: 'trips.getById', resource: 'trip:3', code: 'ok' });
|
||||
await appendAudit(audit, { pluginId: 'legacy-p', actingUserId: 7, method: 'trips.getById', resource: 'trip:4', code: 'ok' });
|
||||
|
||||
const rows = chainRows('legacy-p');
|
||||
expect(rows).toHaveLength(5);
|
||||
expect(rows[3].prev_hash).toBe(rows[2].hash); // the converted append linked onto the legacy tip
|
||||
// 4. The WHOLE chain (3 legacy rows + 2 converted rows) verifies end to end.
|
||||
expect(verifyChain(rows)).toBe(true);
|
||||
});
|
||||
|
||||
it('AUDITCHAIN-002 MUTATION: a row whose stored hash omits one field from the hash input fails verification', async () => {
|
||||
// A row constructed EXACTLY like appendAudit's real one, except `resource` is
|
||||
// dropped from the JSON array fed to sha256 — the drift R-hash-chain warns
|
||||
// never errors anywhere on write, only on a verification pass.
|
||||
const pluginId = 'mutant';
|
||||
const actingUserId = 1;
|
||||
const method = 'trips.getById';
|
||||
const resource = 'trip:1';
|
||||
const code = 'ok';
|
||||
const ts = new Date().toISOString();
|
||||
const mutatedRow = JSON.stringify([pluginId, actingUserId, method, code, ts]); // resource OMITTED
|
||||
const mutatedHash = crypto.createHash('sha256').update('' + mutatedRow).digest('hex');
|
||||
testDb
|
||||
.prepare('INSERT INTO plugin_capability_audit (plugin_id, acting_user_id, method, resource, code, ts, prev_hash, hash) VALUES (?,?,?,?,?,?,?,?)')
|
||||
.run(pluginId, actingUserId, method, resource, code, ts, null, mutatedHash);
|
||||
|
||||
expect(verifyChain(chainRows(pluginId))).toBe(false);
|
||||
|
||||
// Control: the same row, hashed with the REAL (resource-included) construction, verifies.
|
||||
testDb.prepare('DELETE FROM plugin_capability_audit WHERE plugin_id = ?').run(pluginId);
|
||||
legacyAppendAudit('', { pluginId, actingUserId, method, resource, code });
|
||||
expect(verifyChain(chainRows(pluginId))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -70,15 +70,15 @@ const req = (p: string, host?: string) => ({ params: { path: p }, get: (h: strin
|
||||
function runtime(active = true, hosts: string[] = [], operatorHosts: string[] = []): PluginRuntimeService {
|
||||
return {
|
||||
isActive: vi.fn(() => active),
|
||||
outboundHostsOf: vi.fn(() => hosts),
|
||||
operatorEgressHosts: vi.fn(() => operatorHosts),
|
||||
outboundHostsOf: vi.fn(async () => hosts),
|
||||
operatorEgressHosts: vi.fn(async () => operatorHosts),
|
||||
} as unknown as PluginRuntimeService;
|
||||
}
|
||||
|
||||
describe('PluginFrameController', () => {
|
||||
it('serves index.html with the opaque-frame CSP + sandbox', () => {
|
||||
it('serves index.html with the opaque-frame CSP + sandbox', async () => {
|
||||
const res = fakeRes();
|
||||
new PluginFrameController(runtime(true, ['api.weather.com'])).serve('widget', req(''), res as never);
|
||||
await new PluginFrameController(runtime(true, ['api.weather.com'])).serve('widget', req(''), res as never);
|
||||
expect(res.filePath).toContain(path.join('widget', 'client', 'index.html'));
|
||||
const csp = res.headers['Content-Security-Policy'];
|
||||
expect(csp).toContain("default-src 'none'");
|
||||
@@ -91,53 +91,53 @@ describe('PluginFrameController', () => {
|
||||
|
||||
// Under the Nest ExpressAdapter, res.sendFile(absolutePath) resolves against the
|
||||
// rewritten req.url and 404s spuriously — files must go out root-relative.
|
||||
it('serves files with an explicit root, not an absolute path', () => {
|
||||
it('serves files with an explicit root, not an absolute path', async () => {
|
||||
const res = fakeRes();
|
||||
new PluginFrameController(runtime(true)).serve('widget', req(''), res as never);
|
||||
await new PluginFrameController(runtime(true)).serve('widget', req(''), res as never);
|
||||
expect(res.fileRoot).toBe(path.join(codeRoot, 'widget', 'client'));
|
||||
});
|
||||
|
||||
// The frame document runs at an opaque origin, so its own <script src> loads are
|
||||
// cross-origin fetches; helmet's CORP: same-origin makes the browser drop them
|
||||
// and a multi-file client dies on boot.
|
||||
it('marks responses cross-origin loadable for the opaque frame', () => {
|
||||
it('marks responses cross-origin loadable for the opaque frame', async () => {
|
||||
const res = fakeRes();
|
||||
new PluginFrameController(runtime(true)).serve('widget', req(''), res as never);
|
||||
await new PluginFrameController(runtime(true)).serve('widget', req(''), res as never);
|
||||
expect(res.headers['Cross-Origin-Resource-Policy']).toBe('cross-origin');
|
||||
});
|
||||
|
||||
// An operatorEgress plugin's hosts are supplied by the ADMIN after install, so they are not
|
||||
// in the manifest grants. activate() unions them into the child's egress guard; the frame
|
||||
// must match, or a plugin with a UI can call the host from its server but not its iframe.
|
||||
it('includes admin-supplied operatorEgress hosts in connect-src', () => {
|
||||
it('includes admin-supplied operatorEgress hosts in connect-src', async () => {
|
||||
const res = fakeRes();
|
||||
new PluginFrameController(runtime(true, ['api.weather.com'], ['gotify.home.lan'])).serve('widget', req(''), res as never);
|
||||
await new PluginFrameController(runtime(true, ['api.weather.com'], ['gotify.home.lan'])).serve('widget', req(''), res as never);
|
||||
const csp = res.headers['Content-Security-Policy'];
|
||||
expect(csp).toContain('https://api.weather.com');
|
||||
expect(csp).toContain('https://gotify.home.lan');
|
||||
});
|
||||
|
||||
it('does not duplicate a host granted in the manifest AND added by the admin', () => {
|
||||
it('does not duplicate a host granted in the manifest AND added by the admin', async () => {
|
||||
const res = fakeRes();
|
||||
new PluginFrameController(runtime(true, ['ntfy.sh'], ['ntfy.sh'])).serve('widget', req(''), res as never);
|
||||
await new PluginFrameController(runtime(true, ['ntfy.sh'], ['ntfy.sh'])).serve('widget', req(''), res as never);
|
||||
const csp = res.headers['Content-Security-Policy'];
|
||||
expect(csp.match(/https:\/\/ntfy\.sh/g)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('refuses to interpolate a malformed operator host into the CSP', () => {
|
||||
it('refuses to interpolate a malformed operator host into the CSP', async () => {
|
||||
const res = fakeRes();
|
||||
// The admin writer validates hosts, but connect-src is the last line of defence: a token
|
||||
// with a space or a bare * would widen the whole policy.
|
||||
new PluginFrameController(runtime(true, [], ['evil.com https://*', '*'])).serve('widget', req(''), res as never);
|
||||
await new PluginFrameController(runtime(true, [], ['evil.com https://*', '*'])).serve('widget', req(''), res as never);
|
||||
const csp = res.headers['Content-Security-Policy'];
|
||||
expect(csp).toContain("connect-src 'self'");
|
||||
expect(csp).not.toContain('evil.com');
|
||||
expect(csp).not.toContain('*');
|
||||
});
|
||||
|
||||
it('allows the plugin its own static assets when the Host header is clean', () => {
|
||||
it('allows the plugin its own static assets when the Host header is clean', async () => {
|
||||
const res = fakeRes();
|
||||
new PluginFrameController(runtime(true)).serve('widget', req('', 'trek.example.com:8443'), res as never);
|
||||
await new PluginFrameController(runtime(true)).serve('widget', req('', 'trek.example.com:8443'), res as never);
|
||||
const csp = res.headers['Content-Security-Policy'];
|
||||
// Scheme-less on purpose: matches the frame's own http AND https documents.
|
||||
expect(csp).toContain("script-src 'self' 'unsafe-inline' trek.example.com:8443/plugin-frame/widget/");
|
||||
@@ -145,54 +145,54 @@ describe('PluginFrameController', () => {
|
||||
expect(csp).toContain("connect-src 'self' trek.example.com:8443/plugin-frame/widget/");
|
||||
});
|
||||
|
||||
it('drops the own-assets source on a malformed Host header instead of widening the policy', () => {
|
||||
it('drops the own-assets source on a malformed Host header instead of widening the policy', async () => {
|
||||
const res = fakeRes();
|
||||
new PluginFrameController(runtime(true)).serve('widget', req('', 'evil.com *'), res as never);
|
||||
await new PluginFrameController(runtime(true)).serve('widget', req('', 'evil.com *'), res as never);
|
||||
const csp = res.headers['Content-Security-Policy'];
|
||||
expect(csp).toContain("script-src 'self' 'unsafe-inline';");
|
||||
expect(csp).not.toContain('evil.com');
|
||||
});
|
||||
|
||||
it('404 when the plugin is inactive', () => {
|
||||
it('404 when the plugin is inactive', async () => {
|
||||
const res = fakeRes();
|
||||
new PluginFrameController(runtime(false)).serve('widget', req(''), res as never);
|
||||
await new PluginFrameController(runtime(false)).serve('widget', req(''), res as never);
|
||||
expect(res.statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it('404 when the runtime is disabled', () => {
|
||||
it('404 when the runtime is disabled', async () => {
|
||||
pluginsEnabledMock.mockReturnValueOnce(false);
|
||||
const res = fakeRes();
|
||||
new PluginFrameController(runtime(true)).serve('widget', req(''), res as never);
|
||||
await new PluginFrameController(runtime(true)).serve('widget', req(''), res as never);
|
||||
expect(res.statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it('403 on a path-traversal attempt', () => {
|
||||
it('403 on a path-traversal attempt', async () => {
|
||||
const res = fakeRes();
|
||||
new PluginFrameController(runtime(true)).serve('widget', req('../../../etc/passwd'), res as never);
|
||||
await new PluginFrameController(runtime(true)).serve('widget', req('../../../etc/passwd'), res as never);
|
||||
expect(res.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it('404 for a missing file', () => {
|
||||
it('404 for a missing file', async () => {
|
||||
const res = fakeRes();
|
||||
new PluginFrameController(runtime(true)).serve('widget', req('missing.js'), res as never);
|
||||
await new PluginFrameController(runtime(true)).serve('widget', req('missing.js'), res as never);
|
||||
expect(res.statusCode).toBe(404);
|
||||
});
|
||||
|
||||
// The lexical guard above cannot see through a link, and statSync follows one.
|
||||
it('403 on a symlink inside client/ that points out of the plugin', () => {
|
||||
it('403 on a symlink inside client/ that points out of the plugin', async () => {
|
||||
if (!symlinksAvailable) return;
|
||||
const res = fakeRes();
|
||||
new PluginFrameController(runtime(true)).serve('widget', req('esc/leak.js'), res as never);
|
||||
await new PluginFrameController(runtime(true)).serve('widget', req('esc/leak.js'), res as never);
|
||||
expect(res.statusCode).toBe(403);
|
||||
expect(res.filePath).toBeUndefined();
|
||||
});
|
||||
|
||||
// Dev-link mode: the plugin directory itself is a link, so the containment
|
||||
// check has to resolve BOTH sides or local development stops working.
|
||||
it('still serves a dev-linked plugin whose whole tree is a symlink', () => {
|
||||
it('still serves a dev-linked plugin whose whole tree is a symlink', async () => {
|
||||
if (!symlinksAvailable) return;
|
||||
const res = fakeRes();
|
||||
new PluginFrameController(runtime(true)).serve('linked', req(''), res as never);
|
||||
await new PluginFrameController(runtime(true)).serve('linked', req(''), res as never);
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.filePath).toContain('index.html');
|
||||
});
|
||||
|
||||
@@ -4,13 +4,20 @@
|
||||
* the legacy router, because rpc-host.test.ts asserts them and shipped plugins read
|
||||
* them, so these tests pin the exact strings rather than just the refusal.
|
||||
*/
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { PluginGuards } from '../../../src/nest/plugins/host/plugin-guards.service';
|
||||
import { BadParams, ForbiddenResource } from '../../../src/nest/plugins/host/rpc-errors';
|
||||
import type { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
import type { PermissionsService } from '../../../src/nest/permissions/permissions.service';
|
||||
import type { TripsRepository } from '../../../src/db/repositories/Trips.repository';
|
||||
import { PermissionsService } from '../../../src/nest/permissions/permissions.service';
|
||||
import type { AddonsService } from '../../../src/nest/addons/addons.service';
|
||||
import type { UsersRepository } from '../../../src/db/repositories/Users.repository';
|
||||
import type { PluginRpcContext } from '../../../src/nest/plugins/host/rpc-kit/types';
|
||||
import { UnitOfWork } from '../../../src/nest/database/unit-of-work';
|
||||
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
|
||||
import { createSnapshotTestDb } from '../../helpers/db-mock';
|
||||
import { createUser } from '../../helpers/factories';
|
||||
import { AppSettings } from '../../../src/db/entities/AppSettings.entity';
|
||||
import { Users } from '../../../src/db/entities/Users.entity';
|
||||
|
||||
/**
|
||||
* The guards read `actingUserId` and nothing else off the context, so the two per-host
|
||||
@@ -27,59 +34,69 @@ const ctx = (actingUserId: number | undefined): PluginRpcContext => ({
|
||||
},
|
||||
});
|
||||
|
||||
/** Trip 1 belongs to user 42 and only user 42 may reach it, mirroring rpc-host.test.ts. */
|
||||
function build(overrides: { role?: string | undefined; allow?: boolean; addonOn?: boolean } = {}) {
|
||||
/**
|
||||
* Trip 1 belongs to user 42 and only user 42 may reach it, mirroring rpc-host.test.ts.
|
||||
*
|
||||
* `overrides.role` drives the stubbed `UsersRepository.getRole` (PG3/PG4, Plan 3j
|
||||
* Task 1) the same way it used to drive `db.prepare(...).get()`: omitted means a
|
||||
* normal row with role 'user'; explicitly `undefined` (or `null`) means "no row",
|
||||
* which `getRole`'s own `string | null` contract folds into a single `null` — the
|
||||
* `users` column is `NOT NULL DEFAULT 'user'`, so a present row can never actually
|
||||
* carry a null role, and `getRole` has no way to tell "row absent" from "row present,
|
||||
* role null" apart even if it could.
|
||||
*/
|
||||
function build(overrides: { role?: string | null; allow?: boolean; addonOn?: boolean } = {}) {
|
||||
const db = {
|
||||
canAccessTrip: vi.fn((tripId: number, userId: number) =>
|
||||
findAccessible: vi.fn(async (tripId: number, userId: number) =>
|
||||
tripId === 1 && userId === 42 ? { id: 1, user_id: 42 } : undefined,
|
||||
),
|
||||
prepare: vi.fn(() => ({
|
||||
get: () => ('role' in overrides ? (overrides.role === undefined ? undefined : { role: overrides.role }) : { role: 'user' }),
|
||||
})),
|
||||
} as unknown as DatabaseService;
|
||||
} as unknown as TripsRepository;
|
||||
const users = {
|
||||
getRole: vi.fn(async () => ('role' in overrides ? (overrides.role ?? null) : 'user')),
|
||||
} as unknown as UsersRepository;
|
||||
const permissions = {
|
||||
checkPermission: vi.fn(() => overrides.allow ?? true),
|
||||
} as unknown as PermissionsService;
|
||||
const addons = {
|
||||
isAddonEnabled: vi.fn(() => overrides.addonOn ?? true),
|
||||
} as unknown as AddonsService;
|
||||
return { guards: new PluginGuards(db, permissions, addons), db, permissions, addons };
|
||||
return { guards: new PluginGuards(db, permissions, addons, users), db, users, permissions, addons };
|
||||
}
|
||||
|
||||
describe('PluginGuards — tripRead', () => {
|
||||
it('PGUARD-001 runs the read for a member and hands it the acting user', () => {
|
||||
it('PGUARD-001 runs the read for a member and hands it the acting user', async () => {
|
||||
const { guards } = build();
|
||||
const read = vi.fn((userId: number) => ({ seenBy: userId }));
|
||||
expect(guards.tripRead({ tripId: 1 }, ctx(42), read)).toEqual({ seenBy: 42 });
|
||||
expect(await guards.tripRead({ tripId: 1 }, ctx(42), read)).toEqual({ seenBy: 42 });
|
||||
expect(read).toHaveBeenCalledWith(42);
|
||||
});
|
||||
|
||||
it('PGUARD-002 a userless context is refused before the read runs', () => {
|
||||
it('PGUARD-002 a userless context is refused before the read runs', async () => {
|
||||
const { guards } = build();
|
||||
const read = vi.fn();
|
||||
expect(() => guards.tripRead({ tripId: 1 }, ctx(undefined), read)).toThrow(
|
||||
await expect(guards.tripRead({ tripId: 1 }, ctx(undefined), read)).rejects.toThrow(
|
||||
new ForbiddenResource('trip reads require an authenticated user context'),
|
||||
);
|
||||
expect(read).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('PGUARD-003 a non-member is refused, naming the trip', () => {
|
||||
it('PGUARD-003 a non-member is refused, naming the trip', async () => {
|
||||
const { guards } = build();
|
||||
const read = vi.fn();
|
||||
expect(() => guards.tripRead({ tripId: 2 }, ctx(42), read)).toThrow(
|
||||
await expect(guards.tripRead({ tripId: 2 }, ctx(42), read)).rejects.toThrow(
|
||||
new ForbiddenResource('no access to trip 2'),
|
||||
);
|
||||
expect(read).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('PGUARD-004 a missing tripId is BAD_PARAMS, not a refusal', () => {
|
||||
it('PGUARD-004 a missing tripId is BAD_PARAMS, not a refusal', async () => {
|
||||
const { guards } = build();
|
||||
expect(() => guards.tripRead({}, ctx(42), vi.fn())).toThrow(new BadParams('tripId must be a number'));
|
||||
await expect(guards.tripRead({}, ctx(42), vi.fn())).rejects.toThrow(new BadParams('tripId must be a number'));
|
||||
});
|
||||
|
||||
it('PGUARD-005 a numeric string tripId is accepted, as the wire contract allows', () => {
|
||||
it('PGUARD-005 a numeric string tripId is accepted, as the wire contract allows', async () => {
|
||||
const { guards } = build();
|
||||
expect(guards.tripRead({ tripId: '1' }, ctx(42), (u) => u)).toBe(42);
|
||||
expect(await guards.tripRead({ tripId: '1' }, ctx(42), (u) => u)).toBe(42);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -96,61 +113,136 @@ describe('PluginGuards — requireActor', () => {
|
||||
});
|
||||
|
||||
describe('PluginGuards — requireTripEdit and canEditAs', () => {
|
||||
it('PGUARD-008 passes when the user may access and edit', () => {
|
||||
it('PGUARD-008 passes when the user may access and edit', async () => {
|
||||
const { guards, permissions } = build({ allow: true });
|
||||
expect(() => guards.requireTripEdit(1, 42, 'trip_edit')).not.toThrow();
|
||||
await expect(guards.requireTripEdit(1, 42, 'trip_edit')).resolves.not.toThrow();
|
||||
expect(permissions.checkPermission).toHaveBeenCalledWith('trip_edit', 'user', 42, 42, false);
|
||||
});
|
||||
|
||||
it('PGUARD-009 no access wins over no permission, and names the trip', () => {
|
||||
it('PGUARD-009 no access wins over no permission, and names the trip', async () => {
|
||||
const { guards } = build({ allow: false });
|
||||
expect(() => guards.requireTripEdit(2, 42, 'trip_edit')).toThrow(
|
||||
new ForbiddenResource('no access to trip 2'),
|
||||
);
|
||||
await expect(guards.requireTripEdit(2, 42, 'trip_edit')).rejects.toThrow(new ForbiddenResource('no access to trip 2'));
|
||||
});
|
||||
|
||||
it('PGUARD-010 access without the edit permission is a different message', () => {
|
||||
it('PGUARD-010 access without the edit permission is a different message', async () => {
|
||||
const { guards } = build({ allow: false });
|
||||
expect(() => guards.requireTripEdit(1, 42, 'trip_edit')).toThrow(
|
||||
new ForbiddenResource('no permission to edit trip 1'),
|
||||
);
|
||||
await expect(guards.requireTripEdit(1, 42, 'trip_edit')).rejects.toThrow(new ForbiddenResource('no permission to edit trip 1'));
|
||||
});
|
||||
|
||||
it('PGUARD-011 canEditAs returns false rather than throwing when there is no access', () => {
|
||||
expect(build().guards.canEditAs('trip_edit', 2, 42)).toBe(false);
|
||||
it('PGUARD-011 canEditAs returns false rather than throwing when there is no access', async () => {
|
||||
expect(await build().guards.canEditAs('trip_edit', 2, 42)).toBe(false);
|
||||
});
|
||||
|
||||
it('PGUARD-012 canEditAs returns false when the user row is gone', () => {
|
||||
expect(build({ role: undefined }).guards.canEditAs('trip_edit', 1, 42)).toBe(false);
|
||||
it('PGUARD-012 canEditAs returns false when the user row is gone', async () => {
|
||||
expect(await build({ role: undefined }).guards.canEditAs('trip_edit', 1, 42)).toBe(false);
|
||||
});
|
||||
|
||||
it('PGUARD-013 a missing role column falls back to "user"', () => {
|
||||
const { guards, permissions } = build({ role: null as unknown as string });
|
||||
guards.canEditAs('trip_edit', 1, 42);
|
||||
expect(permissions.checkPermission).toHaveBeenCalledWith('trip_edit', 'user', 42, 42, false);
|
||||
it('PGUARD-013 the repository role read actually drives the permission check — mutation proof: flipping the returned role flips the argument checkPermission sees', async () => {
|
||||
const { guards, permissions } = build({ role: 'admin' });
|
||||
await guards.canEditAs('trip_edit', 1, 42);
|
||||
// Seeded row is 'user' by default (see build()'s docstring); forcing the
|
||||
// double to return 'admin' and seeing THAT value reach checkPermission
|
||||
// proves canEditAs is reading through PluginGuards' own UsersRepository
|
||||
// call, not a cached or hard-coded role.
|
||||
expect(permissions.checkPermission).toHaveBeenCalledWith('trip_edit', 'admin', 42, 42, false);
|
||||
});
|
||||
|
||||
it('PGUARD-014 a non-owner member is flagged as shared', () => {
|
||||
it('PGUARD-014 a non-owner member is flagged as shared', async () => {
|
||||
const db = {
|
||||
canAccessTrip: vi.fn(() => ({ id: 1, user_id: 7 })),
|
||||
prepare: vi.fn(() => ({ get: () => ({ role: 'user' }) })),
|
||||
} as unknown as DatabaseService;
|
||||
findAccessible: vi.fn(async () => ({ id: 1, user_id: 7 })),
|
||||
} as unknown as TripsRepository;
|
||||
const users = { getRole: vi.fn(async () => 'user') } as unknown as UsersRepository;
|
||||
const permissions = { checkPermission: vi.fn(() => true) } as unknown as PermissionsService;
|
||||
const guards = new PluginGuards(db, permissions, {} as AddonsService);
|
||||
guards.canEditAs('trip_edit', 1, 42);
|
||||
const guards = new PluginGuards(db, permissions, {} as AddonsService, users);
|
||||
await guards.canEditAs('trip_edit', 1, 42);
|
||||
expect(permissions.checkPermission).toHaveBeenCalledWith('trip_edit', 'user', 7, 42, true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('PluginGuards — requireAddon', () => {
|
||||
it('PGUARD-015 an enabled addon passes', () => {
|
||||
expect(() => build({ addonOn: true }).guards.requireAddon('budget', 'costs')).not.toThrow();
|
||||
describe('PluginGuards — canCreateAs', () => {
|
||||
it('PGUARD-021 passes the looked-up role through with no trip-access check at all', async () => {
|
||||
const { guards, permissions } = build({ role: 'admin', allow: true });
|
||||
expect(await guards.canCreateAs('trip_create', 42)).toBe(true);
|
||||
expect(permissions.checkPermission).toHaveBeenCalledWith('trip_create', 'admin', null, 42, false);
|
||||
});
|
||||
|
||||
it('PGUARD-016 a disabled addon is refused with the noun in the message', () => {
|
||||
expect(() => build({ addonOn: false }).guards.requireAddon('budget', 'costs')).toThrow(
|
||||
new ForbiddenResource('the costs addon is disabled'),
|
||||
);
|
||||
it('PGUARD-022 a user id with no matching row never throws and falls back to role "user", unchanged from the legacy user?.role ?? "user" branch (no early refusal exists here, unlike canEditAs)', async () => {
|
||||
const { guards, permissions } = build({ role: undefined });
|
||||
await expect(guards.canCreateAs('trip_create', 999)).resolves.not.toThrow();
|
||||
expect(permissions.checkPermission).toHaveBeenCalledWith('trip_create', 'user', null, 999, false);
|
||||
});
|
||||
|
||||
it('PGUARD-023 mutation proof: flipping the returned role flips the argument checkPermission sees', async () => {
|
||||
const { guards, permissions } = build({ role: 'admin' });
|
||||
await guards.canCreateAs('trip_create', 42);
|
||||
expect(permissions.checkPermission).toHaveBeenCalledWith('trip_create', 'admin', null, 42, false);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* The role×action×ownership matrix the sql-inventory calls for (§3), run through the
|
||||
* REAL UsersRepository (a real MikroORM repository, default allowGlobalContext: true —
|
||||
* these are direct, unwrapped calls, same TRAP-list allowance test-orm.ts documents)
|
||||
* and the REAL PermissionsService (default in-memory permission levels, no stored
|
||||
* overrides), not the stubbed doubles `build()` uses above. This is what actually
|
||||
* proves PG3/PG4's conversion didn't change plugin-write authorization: a role that
|
||||
* should fail a check still fails it, a role that should pass still passes, and
|
||||
* physically changing the STORED row (not a test double) flips the result.
|
||||
*/
|
||||
describe('PluginGuards — canEditAs/canCreateAs against a real UsersRepository + PermissionsService', () => {
|
||||
let testDb: ReturnType<typeof createSnapshotTestDb>;
|
||||
let orm: TestOrm;
|
||||
let guards: PluginGuards;
|
||||
let memberId: number;
|
||||
const ownerId = 1;
|
||||
|
||||
beforeEach(async () => {
|
||||
testDb = createSnapshotTestDb();
|
||||
orm = await createTestOrm(testDb);
|
||||
const permissions = new PermissionsService(orm.repo(AppSettings), new UnitOfWork(orm.em));
|
||||
const db = {
|
||||
findAccessible: vi.fn(async (tripId: number) => (tripId === 1 ? { id: 1, user_id: ownerId } : undefined)),
|
||||
} as unknown as TripsRepository;
|
||||
// The permissions cache is module-scoped (permissions-cache.ts), not
|
||||
// per-instance — invalidate before every case so a stored override from
|
||||
// another describe block in this same worker can't leak in.
|
||||
permissions.invalidatePermissionsCache();
|
||||
guards = new PluginGuards(db, permissions, {} as AddonsService, orm.repo(Users));
|
||||
createUser(testDb, { role: 'user' }); // id 1, the trip owner — unused by these cases directly
|
||||
memberId = createUser(testDb, { role: 'user' }).user.id; // id 2, a non-owner trip member
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await orm.close();
|
||||
testDb.close();
|
||||
});
|
||||
|
||||
it('PGUARD-024 a member whose role lacks trip_delete (trip_owner-only by default) is refused', async () => {
|
||||
expect(await guards.canEditAs('trip_delete', 1, memberId)).toBe(false);
|
||||
});
|
||||
|
||||
it('PGUARD-025 mutation proof: promoting that SAME member to admin in the real users table flips PGUARD-024 to pass', async () => {
|
||||
testDb.prepare('UPDATE users SET role = ? WHERE id = ?').run('admin', memberId);
|
||||
expect(await guards.canEditAs('trip_delete', 1, memberId)).toBe(true);
|
||||
});
|
||||
|
||||
it('PGUARD-026 a non-member is refused regardless of role (trip access is checked first)', async () => {
|
||||
expect(await guards.canEditAs('trip_delete', 999, memberId)).toBe(false);
|
||||
});
|
||||
|
||||
it('PGUARD-027 canCreateAs: a real user id with no matching row never throws, and trip_create\'s "everybody" default lets it through — the legacy fallback preserved, not a new refusal', async () => {
|
||||
const vanishedId = memberId + 1000;
|
||||
await expect(guards.canCreateAs('trip_create', vanishedId)).resolves.toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('PluginGuards — requireAddon', () => {
|
||||
it('PGUARD-015 an enabled addon passes', async () => {
|
||||
await expect(build({ addonOn: true }).guards.requireAddon('budget', 'costs')).resolves.not.toThrow();
|
||||
});
|
||||
|
||||
it('PGUARD-016 a disabled addon is refused with the noun in the message', async () => {
|
||||
await expect(build({ addonOn: false }).guards.requireAddon('budget', 'costs')).rejects.toThrow(new ForbiddenResource('the costs addon is disabled'));
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* HS1 (`plugin-host-state.ts#budgetFor`'s seed read) — Plan 3j Task 3. Converted
|
||||
* from a raw `better-sqlite3` connection to `PluginCapabilityAuditRepository`;
|
||||
* this covers the seed's grouping (ai.complete + ai.extract vs notify.send),
|
||||
* the UTC-day floor, and the `code = 'ok'` filter (a denied call never counts
|
||||
* against the budget).
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, beforeEach, afterAll, afterEach, vi } from 'vitest';
|
||||
import { createSnapshotTestDb } from '../../helpers/db-mock';
|
||||
import { resetTestDb } from '../../helpers/test-db';
|
||||
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
|
||||
import { PluginCapabilityAudit } from '../../../src/db/entities/PluginCapabilityAudit.entity';
|
||||
import type { PluginCapabilityAuditRepository } from '../../../src/db/repositories/PluginCapabilityAudit.repository';
|
||||
import { appendAudit } from '../../../src/nest/plugins/host/plugin-audit';
|
||||
import { budgetFor, pluginBudgetUsage } from '../../../src/nest/plugins/host/plugin-host-state';
|
||||
|
||||
const testDb = createSnapshotTestDb();
|
||||
let t: TestOrm;
|
||||
let audit: PluginCapabilityAuditRepository;
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestOrm(testDb);
|
||||
audit = t.repo(PluginCapabilityAudit);
|
||||
});
|
||||
beforeEach(() => { resetTestDb(testDb); t.clear(); });
|
||||
afterEach(() => { vi.restoreAllMocks(); });
|
||||
afterAll(async () => { await t.close(); testDb.close(); });
|
||||
|
||||
// `budgetFor`'s `budgets` Map is deliberately module-level (see plugin-host-state.ts's
|
||||
// class docstring) — it is NOT reset by `resetTestDb`/`t.clear()`, so each test below
|
||||
// uses its own plugin id to avoid one test's seed being served (cached) to the next.
|
||||
describe('budgetFor / pluginBudgetUsage seed read', () => {
|
||||
it('HS-001: seeds ai (ai.complete + ai.extract) and notify counts separately from today\'s already-audited rows', async () => {
|
||||
await appendAudit(audit, { pluginId: 'hs1', actingUserId: 1, method: 'ai.complete', resource: null, code: 'ok' });
|
||||
await appendAudit(audit, { pluginId: 'hs1', actingUserId: 1, method: 'ai.extract', resource: null, code: 'ok' });
|
||||
await appendAudit(audit, { pluginId: 'hs1', actingUserId: 1, method: 'notify.send', resource: null, code: 'ok' });
|
||||
// A denied call must not count against the budget.
|
||||
await appendAudit(audit, { pluginId: 'hs1', actingUserId: 1, method: 'ai.complete', resource: null, code: 'RESOURCE_FORBIDDEN' });
|
||||
// A different plugin's calls must not bleed into this one's budget.
|
||||
await appendAudit(audit, { pluginId: 'hs1-other', actingUserId: 1, method: 'ai.complete', resource: null, code: 'ok' });
|
||||
|
||||
const usage = await pluginBudgetUsage('hs1', audit);
|
||||
expect(usage.ai).toBe(2);
|
||||
expect(usage.notify).toBe(1);
|
||||
});
|
||||
|
||||
it('HS-002: seeded only once per plugin per process lifetime — a later append is NOT re-counted on a second read', async () => {
|
||||
await appendAudit(audit, { pluginId: 'hs2', actingUserId: 1, method: 'ai.complete', resource: null, code: 'ok' });
|
||||
const first = await budgetFor('hs2', audit);
|
||||
expect(first.used(Date.now()).ai).toBe(1);
|
||||
// A direct .take() call (what a real dispatch does) advances the in-memory
|
||||
// counter; the seed read itself is not re-run.
|
||||
await appendAudit(audit, { pluginId: 'hs2', actingUserId: 1, method: 'ai.complete', resource: null, code: 'ok' });
|
||||
const second = await budgetFor('hs2', audit);
|
||||
expect(second).toBe(first); // same cached DailyBudget instance — no re-seed
|
||||
expect(second.used(Date.now()).ai).toBe(1); // still 1: the second append was never taken through the budget
|
||||
});
|
||||
|
||||
it("HS-003: ignores yesterday's rows — only today's UTC window seeds the count", async () => {
|
||||
await appendAudit(audit, { pluginId: 'hs3', actingUserId: 1, method: 'ai.complete', resource: null, code: 'ok' });
|
||||
// Backdate the row to yesterday, bypassing the repository (simulating a
|
||||
// real prior day's audit history already on disk).
|
||||
const yesterday = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString();
|
||||
testDb.prepare("UPDATE plugin_capability_audit SET ts = ? WHERE plugin_id = 'hs3'").run(yesterday);
|
||||
|
||||
const usage = await pluginBudgetUsage('hs3', audit);
|
||||
expect(usage.ai).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -13,26 +13,38 @@ import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import type { Request } from 'express';
|
||||
|
||||
const { testDb, dbMock } = vi.hoisted(() => {
|
||||
const Database = require('better-sqlite3');
|
||||
const db = new Database(':memory:');
|
||||
return { testDb: db, dbMock: { db, closeDb: () => {}, reinitialize: () => {}, canAccessTrip: () => null } };
|
||||
vi.mock('../../../src/db/database', async () => {
|
||||
const { createSnapshotTestDb } = await import('../../helpers/db-mock');
|
||||
const db = createSnapshotTestDb();
|
||||
return { db, closeDb: () => {}, reinitialize: () => {}, canAccessTrip: async () => null };
|
||||
});
|
||||
vi.mock('../../../src/db/database', () => dbMock);
|
||||
import { db as dbConn } from '../../../src/db/database';
|
||||
import { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
import { db as testDb } from '../../../src/db/database';
|
||||
vi.mock('../../../src/config', () => ({ JWT_SECRET: 'x'.repeat(40), ENCRYPTION_KEY: 'a'.repeat(64), updateJwtSecret: () => {} }));
|
||||
|
||||
import { createTables } from '../../../src/db/schema';
|
||||
import { runMigrations } from '../../../src/db/migrations';
|
||||
import { PluginsService } from '../../../src/nest/plugins/plugins.service';
|
||||
import { PluginsController } from '../../../src/nest/plugins/plugins.controller';
|
||||
import { PluginConsentRequired, type PluginRuntimeService } from '../../../src/nest/plugins/plugin-runtime.service';
|
||||
import type { PluginRegistryService } from '../../../src/nest/plugins/registry/registry.service';
|
||||
import type { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service';
|
||||
import { AddonsService } from '../../../src/nest/addons/addons.service';
|
||||
import type { AddonsService } from '../../../src/nest/addons/addons.service';
|
||||
import { createTestAddonsService } from '../../helpers/test-addons';
|
||||
import { createPluginRuntime } from '../../helpers/plugin-host';
|
||||
import { discoverPlugins } from '../../../src/nest/plugins/install/discovery';
|
||||
import { sharedTestOrm, createTestUnitOfWork } from '../../helpers/test-uow';
|
||||
import { Plugins } from '../../../src/db/entities/Plugins.entity';
|
||||
import { PluginErrorLog } from '../../../src/db/entities/PluginErrorLog.entity';
|
||||
import { PluginEgressHosts } from '../../../src/db/entities/PluginEgressHosts.entity';
|
||||
import { PluginSettingsFields } from '../../../src/db/entities/PluginSettingsFields.entity';
|
||||
import { PluginActions } from '../../../src/db/entities/PluginActions.entity';
|
||||
import { PluginUserConfig } from '../../../src/db/entities/PluginUserConfig.entity';
|
||||
import { PluginCapabilityAudit } from '../../../src/db/entities/PluginCapabilityAudit.entity';
|
||||
import type { PluginsRepository } from '../../../src/db/repositories/Plugins.repository';
|
||||
import type { PluginEgressHostsRepository } from '../../../src/db/repositories/PluginEgressHosts.repository';
|
||||
import type { PluginSettingsFieldsRepository } from '../../../src/db/repositories/PluginSettingsFields.repository';
|
||||
import type { PluginActionsRepository } from '../../../src/db/repositories/PluginActions.repository';
|
||||
import type { PluginUserConfigRepository } from '../../../src/db/repositories/PluginUserConfig.repository';
|
||||
import type { PluginErrorLogRepository } from '../../../src/db/repositories/PluginErrorLog.repository';
|
||||
import type { PluginCapabilityAuditRepository } from '../../../src/db/repositories/PluginCapabilityAudit.repository';
|
||||
|
||||
function install(id: string) {
|
||||
testDb
|
||||
@@ -52,10 +64,28 @@ function declareField(pluginId: string, key: string, scope: 'instance' | 'user',
|
||||
.run(pluginId, key, key, opts.required ? 1 : 0, opts.secret ? 1 : 0, scope, opts.options ?? null, opts.sortOrder ?? 0);
|
||||
}
|
||||
|
||||
const svc = () => {
|
||||
const dbs = new DatabaseService(dbConn);
|
||||
return new PluginsService(dbs, new AddonsService(dbs));
|
||||
};
|
||||
let addonsService: AddonsService;
|
||||
// Plan 3j Task 2 — PluginsService's own six repositories, resolved ONCE in `beforeAll`
|
||||
// (the file's `testDb` is fixed for the whole suite) so `svc()` below can stay a plain
|
||||
// synchronous factory — every one of its ~20 call sites below chains straight off it.
|
||||
let pluginsRepo: PluginsRepository;
|
||||
let pluginEgressHostsRepo: PluginEgressHostsRepository;
|
||||
let pluginSettingsFieldsRepo: PluginSettingsFieldsRepository;
|
||||
let pluginActionsRepo: PluginActionsRepository;
|
||||
let pluginUserConfigRepo: PluginUserConfigRepository;
|
||||
let pluginErrorLogRepo: PluginErrorLogRepository;
|
||||
let pluginCapabilityAuditRepo: PluginCapabilityAuditRepository;
|
||||
const svc = () =>
|
||||
new PluginsService(
|
||||
addonsService,
|
||||
pluginsRepo,
|
||||
pluginEgressHostsRepo,
|
||||
pluginSettingsFieldsRepo,
|
||||
pluginActionsRepo,
|
||||
pluginUserConfigRepo,
|
||||
pluginErrorLogRepo,
|
||||
pluginCapabilityAuditRepo,
|
||||
);
|
||||
|
||||
/**
|
||||
* Installs a real plugin through the manifest -> discovery pipeline (not a direct
|
||||
@@ -63,7 +93,7 @@ const svc = () => {
|
||||
* `parseSettingDefault` in manifest.ts, not just the settingsFields() read path.
|
||||
*/
|
||||
let codeRoot: string;
|
||||
function installFixturePlugin(opts: { settings: Array<Record<string, unknown>> }) {
|
||||
async function installFixturePlugin(opts: { settings: Array<Record<string, unknown>> }) {
|
||||
const dir = path.join(codeRoot, 'fixture-id', 'server');
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(
|
||||
@@ -71,12 +101,22 @@ function installFixturePlugin(opts: { settings: Array<Record<string, unknown>> }
|
||||
JSON.stringify({ id: 'fixture-id', name: 'Fixture', version: '1.0.0', type: 'integration', trek: '>=4.0.0 <5.0.0', settings: opts.settings }),
|
||||
);
|
||||
fs.writeFileSync(path.join(dir, 'index.js'), 'module.exports={}');
|
||||
discoverPlugins(testDb);
|
||||
// Plan 3j Task 3: `discoverPlugins` takes a `DiscoveryRepos` bundle now, not a raw
|
||||
// connection — the same repositories this file already resolves via `sharedTestOrm`.
|
||||
// Plan 4 Task 4: `uow` is no longer optional in that bundle.
|
||||
await discoverPlugins({ plugins: pluginsRepo, actions: pluginActionsRepo, settingsFields: pluginSettingsFieldsRepo, errorLog: pluginErrorLogRepo, uow: await createTestUnitOfWork(testDb) });
|
||||
}
|
||||
|
||||
beforeAll(() => {
|
||||
createTables(testDb);
|
||||
runMigrations(testDb);
|
||||
beforeAll(async () => {
|
||||
addonsService = await createTestAddonsService(testDb);
|
||||
const orm = await sharedTestOrm(testDb);
|
||||
pluginsRepo = orm.repo(Plugins);
|
||||
pluginEgressHostsRepo = orm.repo(PluginEgressHosts);
|
||||
pluginSettingsFieldsRepo = orm.repo(PluginSettingsFields);
|
||||
pluginActionsRepo = orm.repo(PluginActions);
|
||||
pluginUserConfigRepo = orm.repo(PluginUserConfig);
|
||||
pluginErrorLogRepo = orm.repo(PluginErrorLog);
|
||||
pluginCapabilityAuditRepo = orm.repo(PluginCapabilityAudit);
|
||||
});
|
||||
beforeEach(() => {
|
||||
testDb.prepare('DELETE FROM plugins').run();
|
||||
@@ -91,37 +131,37 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe('instance settings fields', () => {
|
||||
it('INS-001 — lists only the instance-scope fields, in declared order, with form metadata', () => {
|
||||
it('INS-001 — lists only the instance-scope fields, in declared order, with form metadata', async () => {
|
||||
install('p');
|
||||
declareField('p', 'apiUrl', 'instance', { required: true, sortOrder: 1 });
|
||||
declareField('p', 'apiKey', 'instance', { secret: true, sortOrder: 0 });
|
||||
declareField('p', 'units', 'user', { sortOrder: 2 }); // must never leak into the admin form
|
||||
|
||||
const fields = svc().instanceSettingsFields('p');
|
||||
const fields = await svc().instanceSettingsFields('p');
|
||||
expect(fields.map((f) => f.key)).toEqual(['apiKey', 'apiUrl']);
|
||||
expect(fields[0]).toMatchObject({ secret: true, required: false, input_type: 'text' });
|
||||
expect(fields[1]).toMatchObject({ secret: false, required: true });
|
||||
});
|
||||
|
||||
it('INS-002 — parses select options like the user form does', () => {
|
||||
it('INS-002 — parses select options like the user form does', async () => {
|
||||
install('p');
|
||||
declareField('p', 'mode', 'instance', { options: '["fast","slow"]' });
|
||||
expect(svc().instanceSettingsFields('p')[0].options).toEqual(['fast', 'slow']);
|
||||
expect((await svc().instanceSettingsFields('p'))[0].options).toEqual(['fast', 'slow']);
|
||||
});
|
||||
|
||||
it('INS-003 — the admin list carries the instance-field count (gates the menu item)', () => {
|
||||
it('INS-003 — the admin list carries the instance-field count (gates the menu item)', async () => {
|
||||
install('with-fields');
|
||||
install('plain');
|
||||
declareField('with-fields', 'apiKey', 'instance', { secret: true });
|
||||
declareField('with-fields', 'apiUrl', 'instance');
|
||||
declareField('with-fields', 'units', 'user'); // user fields must not count
|
||||
|
||||
const plugins = svc().list().plugins;
|
||||
const plugins = (await svc().list()).plugins;
|
||||
expect(plugins.find((p) => p.id === 'with-fields')).toMatchObject({ instanceSettingsCount: 2 });
|
||||
expect(plugins.find((p) => p.id === 'plain')).toMatchObject({ instanceSettingsCount: 0 });
|
||||
});
|
||||
|
||||
it('INS-004 — the admin list carries the instance-action count (gates the menu item even with no settings fields)', () => {
|
||||
it('INS-004 — the admin list carries the instance-action count (gates the menu item even with no settings fields)', async () => {
|
||||
install('with-action');
|
||||
install('plain');
|
||||
testDb
|
||||
@@ -131,20 +171,20 @@ describe('instance settings fields', () => {
|
||||
.prepare('INSERT INTO plugin_actions (plugin_id, action_key, label, hint, danger, scope, sort_order) VALUES (?, ?, ?, NULL, 0, ?, 0)')
|
||||
.run('with-action', 'notify', 'Notify', 'user'); // user-scope actions must not count
|
||||
|
||||
const plugins = svc().list().plugins;
|
||||
const plugins = (await svc().list()).plugins;
|
||||
expect(plugins.find((p) => p.id === 'with-action')).toMatchObject({ instanceSettingsCount: 0, instanceActionsCount: 1 });
|
||||
expect(plugins.find((p) => p.id === 'plain')).toMatchObject({ instanceSettingsCount: 0, instanceActionsCount: 0 });
|
||||
testDb.prepare("DELETE FROM plugin_actions WHERE plugin_id = 'with-action'").run();
|
||||
});
|
||||
|
||||
it('INS-010 — persists a settings-field default and serves it on the fields list', () => {
|
||||
installFixturePlugin({ settings: [{ key: 'oauth_authorize_url', required: true, default: 'https://auth.openbnb.org/authorize' }] });
|
||||
const fields = svc().instanceSettingsFields('fixture-id');
|
||||
it('INS-010 — persists a settings-field default and serves it on the fields list', async () => {
|
||||
await installFixturePlugin({ settings: [{ key: 'oauth_authorize_url', required: true, default: 'https://auth.openbnb.org/authorize' }] });
|
||||
const fields = await svc().instanceSettingsFields('fixture-id');
|
||||
expect(fields[0].default).toBe('https://auth.openbnb.org/authorize');
|
||||
});
|
||||
|
||||
it('INS-013 — drops a default the field cannot take: non-boolean on a checkbox, or not one of the select options', () => {
|
||||
installFixturePlugin({
|
||||
it('INS-013 — drops a default the field cannot take: non-boolean on a checkbox, or not one of the select options', async () => {
|
||||
await installFixturePlugin({
|
||||
settings: [
|
||||
{ key: 'on', input_type: 'checkbox', default: 'true' },
|
||||
{ key: 'mode', input_type: 'select', options: ['fast', 'slow'], default: 'warp' },
|
||||
@@ -152,73 +192,73 @@ describe('instance settings fields', () => {
|
||||
{ key: 'on_ok', input_type: 'checkbox', default: true },
|
||||
],
|
||||
});
|
||||
const byKey = Object.fromEntries(svc().instanceSettingsFields('fixture-id').map((f) => [f.key, f.default]));
|
||||
const byKey = Object.fromEntries((await svc().instanceSettingsFields('fixture-id')).map((f) => [f.key, f.default]));
|
||||
expect(byKey).toEqual({ on: undefined, mode: undefined, mode_ok: 'a', on_ok: true });
|
||||
});
|
||||
|
||||
it('INS-011 — drops a default on a secret field at parse time', () => {
|
||||
installFixturePlugin({ settings: [{ key: 'token', secret: true, default: 'leak' }] });
|
||||
expect(svc().instanceSettingsFields('fixture-id')[0].default).toBeUndefined();
|
||||
it('INS-011 — drops a default on a secret field at parse time', async () => {
|
||||
await installFixturePlugin({ settings: [{ key: 'token', secret: true, default: 'leak' }] });
|
||||
expect((await svc().instanceSettingsFields('fixture-id'))[0].default).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('required settings are enforced on save', () => {
|
||||
it('refuses a save that leaves a required instance field empty', () => {
|
||||
installFixturePlugin({ settings: [{ key: 'client_id', required: true }] });
|
||||
expect(() => svc().updateInstanceConfig('fixture-id', { client_id: ' ' })).toThrow(/Missing required setting "client_id"/);
|
||||
it('refuses a save that leaves a required instance field empty', async () => {
|
||||
await installFixturePlugin({ settings: [{ key: 'client_id', required: true }] });
|
||||
await expect(svc().updateInstanceConfig('fixture-id', { client_id: ' ' })).rejects.toThrow(/Missing required setting "client_id"/);
|
||||
});
|
||||
|
||||
it('accepts a partial patch when the required field is already stored', () => {
|
||||
installFixturePlugin({ settings: [{ key: 'client_id', required: true }, { key: 'note', required: false }] });
|
||||
it('accepts a partial patch when the required field is already stored', async () => {
|
||||
await installFixturePlugin({ settings: [{ key: 'client_id', required: true }, { key: 'note', required: false }] });
|
||||
const s = svc();
|
||||
s.updateInstanceConfig('fixture-id', { client_id: 'abc' });
|
||||
expect(() => s.updateInstanceConfig('fixture-id', { note: 'hi' })).not.toThrow();
|
||||
await s.updateInstanceConfig('fixture-id', { client_id: 'abc' });
|
||||
await expect(s.updateInstanceConfig('fixture-id', { note: 'hi' })).resolves.toBeDefined();
|
||||
});
|
||||
|
||||
it('accepts a user-scope partial patch when the required user field is already stored', () => {
|
||||
installFixturePlugin({ settings: [{ key: 'api_key', scope: 'user', required: true }, { key: 'units', scope: 'user' }] });
|
||||
it('accepts a user-scope partial patch when the required user field is already stored', async () => {
|
||||
await installFixturePlugin({ settings: [{ key: 'api_key', scope: 'user', required: true }, { key: 'units', scope: 'user' }] });
|
||||
const s = svc();
|
||||
s.updateUserConfig('fixture-id', 1, { api_key: 'sk-1' });
|
||||
expect(() => s.updateUserConfig('fixture-id', 1, { units: 'metric' })).not.toThrow();
|
||||
await s.updateUserConfig('fixture-id', 1, { api_key: 'sk-1' });
|
||||
await expect(s.updateUserConfig('fixture-id', 1, { units: 'metric' })).resolves.toBeDefined();
|
||||
});
|
||||
|
||||
it('refuses a user-settings save that leaves a required user field empty', () => {
|
||||
installFixturePlugin({ settings: [{ key: 'api_key', scope: 'user', required: true }] });
|
||||
expect(() => svc().updateUserConfig('fixture-id', 1, { api_key: '' })).toThrow(/Missing required setting "api_key"/);
|
||||
it('refuses a user-settings save that leaves a required user field empty', async () => {
|
||||
await installFixturePlugin({ settings: [{ key: 'api_key', scope: 'user', required: true }] });
|
||||
await expect(svc().updateUserConfig('fixture-id', 1, { api_key: '' })).rejects.toThrow(/Missing required setting "api_key"/);
|
||||
});
|
||||
|
||||
it('exempts checkbox fields from required enforcement (consent, not a settings field)', () => {
|
||||
installFixturePlugin({ settings: [{ key: 'accept_terms', input_type: 'checkbox', required: true }, { key: 'note', required: false }] });
|
||||
it('exempts checkbox fields from required enforcement (consent, not a settings field)', async () => {
|
||||
await installFixturePlugin({ settings: [{ key: 'accept_terms', input_type: 'checkbox', required: true }, { key: 'note', required: false }] });
|
||||
// accept_terms is left entirely unset (never patched, nothing stored) — a
|
||||
// non-checkbox required field in this state would throw.
|
||||
expect(() => svc().updateInstanceConfig('fixture-id', { note: 'hi' })).not.toThrow();
|
||||
await expect(svc().updateInstanceConfig('fixture-id', { note: 'hi' })).resolves.toBeDefined();
|
||||
});
|
||||
|
||||
it('a required field with a manifest default is satisfied by the default', () => {
|
||||
installFixturePlugin({ settings: [{ key: 'region', required: true, default: 'eu' }, { key: 'note', required: false }] });
|
||||
it('a required field with a manifest default is satisfied by the default', async () => {
|
||||
await installFixturePlugin({ settings: [{ key: 'region', required: true, default: 'eu' }, { key: 'note', required: false }] });
|
||||
// region is never patched and nothing is stored — the runtime will see the default,
|
||||
// so refusing the save here would contradict what the child actually gets.
|
||||
expect(() => svc().updateInstanceConfig('fixture-id', { note: 'hi' })).not.toThrow();
|
||||
await expect(svc().updateInstanceConfig('fixture-id', { note: 'hi' })).resolves.toBeDefined();
|
||||
});
|
||||
|
||||
it('a stored secret (non-empty ciphertext) counts as filled on a later partial patch', () => {
|
||||
installFixturePlugin({ settings: [{ key: 'api_key', secret: true, required: true }, { key: 'note', required: false }] });
|
||||
it('a stored secret (non-empty ciphertext) counts as filled on a later partial patch', async () => {
|
||||
await installFixturePlugin({ settings: [{ key: 'api_key', secret: true, required: true }, { key: 'note', required: false }] });
|
||||
const s = svc();
|
||||
s.updateInstanceConfig('fixture-id', { api_key: 'sk-real' });
|
||||
expect(() => s.updateInstanceConfig('fixture-id', { api_key: '••••••••', note: 'hi' })).not.toThrow();
|
||||
await s.updateInstanceConfig('fixture-id', { api_key: 'sk-real' });
|
||||
await expect(s.updateInstanceConfig('fixture-id', { api_key: '••••••••', note: 'hi' })).resolves.toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('respawn on save (runtime)', () => {
|
||||
it('INS-004 — an inactive plugin is left alone (no respawn, reports false)', async () => {
|
||||
install('p');
|
||||
const rt = createPluginRuntime(new DatabaseService(dbConn));
|
||||
const rt = await createPluginRuntime(testDb);
|
||||
await expect(rt.respawnIfActive('p')).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it('INS-005 — an active plugin is stopped and re-activated so the child re-reads config', async () => {
|
||||
install('p');
|
||||
const rt = createPluginRuntime(new DatabaseService(dbConn));
|
||||
const rt = await createPluginRuntime(testDb);
|
||||
const calls: string[] = [];
|
||||
vi.spyOn(rt, 'isActive').mockReturnValue(true);
|
||||
vi.spyOn(rt, 'activate').mockImplementation(async () => { calls.push('activate'); });
|
||||
@@ -239,12 +279,12 @@ describe('admin config endpoints (controller)', () => {
|
||||
{ isManaged: () => false } as unknown as RuntimeEnvService,
|
||||
);
|
||||
|
||||
it('INS-006 — GET :id/config returns the fields alongside the (masked) values', () => {
|
||||
it('INS-006 — GET :id/config returns the fields alongside the (masked) values', async () => {
|
||||
install('p');
|
||||
declareField('p', 'apiUrl', 'instance');
|
||||
testDb.prepare("UPDATE plugins SET config = '{\"apiUrl\":\"https://x.example\"}' WHERE id = 'p'").run();
|
||||
|
||||
const out = controllerWith({ actionsOf: () => [] }).getConfig('p');
|
||||
const out = await controllerWith({ actionsOf: async () => [] }).getConfig('p');
|
||||
expect(out.config).toEqual({ apiUrl: 'https://x.example' });
|
||||
expect(out.fields.map((f: Record<string, unknown>) => f.key)).toEqual(['apiUrl']);
|
||||
});
|
||||
@@ -292,7 +332,7 @@ describe('admin config endpoints (controller)', () => {
|
||||
expect(failed?.getStatus()).toBe(503);
|
||||
// The respawn is a spawn: it must not run while the whole plugin system is off.
|
||||
expect(respawnIfActive).not.toHaveBeenCalled();
|
||||
expect(svc().getInstanceConfig('p')).toEqual({});
|
||||
expect(await svc().getInstanceConfig('p')).toEqual({});
|
||||
});
|
||||
|
||||
it('INS-011: a respawn that fails reports the save that DID happen, and stops claiming the plugin runs', async () => {
|
||||
@@ -315,7 +355,7 @@ describe('admin config endpoints (controller)', () => {
|
||||
config: { apiUrl: 'https://y.example' },
|
||||
error: expect.stringMatching(/Settings saved.*db:read:trips/),
|
||||
});
|
||||
expect(svc().getInstanceConfig('p')).toEqual({ apiUrl: 'https://y.example' });
|
||||
expect(await svc().getInstanceConfig('p')).toEqual({ apiUrl: 'https://y.example' });
|
||||
// disable() leaves the row enabled, so the admin list would keep showing a plugin
|
||||
// that no longer has a child. The enable toggle is where the reason is offered.
|
||||
expect(deactivate).toHaveBeenCalledWith('p');
|
||||
@@ -324,7 +364,7 @@ describe('admin config endpoints (controller)', () => {
|
||||
|
||||
describe('defaults reach the child at spawn', () => {
|
||||
it('INS-012 — an unset instance field is handed to the child as its manifest default; a stored value wins', async () => {
|
||||
installFixturePlugin({
|
||||
await installFixturePlugin({
|
||||
settings: [
|
||||
{ key: 'api_url', default: 'https://api.example' },
|
||||
{ key: 'retries', input_type: 'number', default: 3 },
|
||||
@@ -332,9 +372,9 @@ describe('defaults reach the child at spawn', () => {
|
||||
],
|
||||
});
|
||||
const s = svc();
|
||||
s.updateInstanceConfig('fixture-id', { api_url: 'https://mine.example' });
|
||||
await s.updateInstanceConfig('fixture-id', { api_url: 'https://mine.example' });
|
||||
|
||||
const rt = createPluginRuntime(new DatabaseService(dbConn));
|
||||
const rt = await createPluginRuntime(testDb);
|
||||
const sup = (rt as unknown as { supervisor: { activate: (...a: unknown[]) => Promise<void> } }).supervisor;
|
||||
const activate = vi.spyOn(sup, 'activate').mockResolvedValue(undefined);
|
||||
|
||||
@@ -362,8 +402,8 @@ describe('instance-scope actions (admin)', () => {
|
||||
.run(pluginId, key, key, scope);
|
||||
}
|
||||
const adminReq = { user: { id: 42 } } as unknown as Request;
|
||||
function controller(invoke = vi.fn(async () => ({ ok: true, message: 'pong' }))) {
|
||||
const rt = createPluginRuntime(new DatabaseService(dbConn));
|
||||
async function controller(invoke = vi.fn(async () => ({ ok: true, message: 'pong' }))) {
|
||||
const rt = await createPluginRuntime(testDb);
|
||||
// isActive normally reflects the supervisor's live child map, which nothing here
|
||||
// spawns — so it's stubbed to read the same DB status the test itself flips,
|
||||
// mirroring what an actually-activated plugin would report.
|
||||
@@ -375,25 +415,25 @@ describe('instance-scope actions (admin)', () => {
|
||||
|
||||
beforeEach(() => { testDb.prepare('DELETE FROM plugin_actions').run(); });
|
||||
|
||||
it('ACT-ADM-001 — GET config lists the instance actions and none of the user ones', () => {
|
||||
it('ACT-ADM-001 — GET config lists the instance actions and none of the user ones', async () => {
|
||||
install('p');
|
||||
declareAction('p', 'purge', 'instance');
|
||||
declareAction('p', 'testConnection', 'user');
|
||||
const { c } = controller();
|
||||
expect(c.getConfig('p').actions).toEqual([{ key: 'purge', label: 'purge', hint: undefined, danger: false, scope: 'instance' }]);
|
||||
const { c } = await controller();
|
||||
expect((await c.getConfig('p')).actions).toEqual([{ key: 'purge', label: 'purge', hint: undefined, danger: false, scope: 'instance' }]);
|
||||
});
|
||||
|
||||
it('ACT-ADM-002 — POST runs the action as the clicking admin in the instance scope', async () => {
|
||||
install('p');
|
||||
testDb.prepare("UPDATE plugins SET status = 'active', enabled = 1 WHERE id = 'p'").run();
|
||||
const { c, invoke } = controller();
|
||||
const { c, invoke } = await controller();
|
||||
expect(await c.runAction('p', 'purge', adminReq)).toEqual({ ok: true, message: 'pong' });
|
||||
expect(invoke).toHaveBeenCalledWith('p', 'purge', 42, 'instance');
|
||||
});
|
||||
|
||||
it('ACT-ADM-003 — an inactive plugin answers 404 like the user route', async () => {
|
||||
install('p');
|
||||
const { c, invoke } = controller();
|
||||
const { c, invoke } = await controller();
|
||||
await expect(c.runAction('p', 'purge', adminReq)).rejects.toMatchObject({ status: 404, response: { error: 'Plugin is not active' } });
|
||||
expect(invoke).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -401,7 +441,7 @@ describe('instance-scope actions (admin)', () => {
|
||||
it('ACT-ADM-004 — a refused key is a failed RESULT, not a server error', async () => {
|
||||
install('p');
|
||||
testDb.prepare("UPDATE plugins SET status = 'active', enabled = 1 WHERE id = 'p'").run();
|
||||
const { c } = controller(vi.fn(async () => { throw new Error('plugin p did not declare action "x" in scope instance'); }));
|
||||
const { c } = await controller(vi.fn(async () => { throw new Error('plugin p did not declare action "x" in scope instance'); }));
|
||||
expect(await c.runAction('p', 'x', adminReq)).toEqual({ ok: false, message: 'plugin p did not declare action "x" in scope instance' });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -41,8 +41,11 @@ function makeService(w: Wiring = {}) {
|
||||
grantsOf: vi.fn((id: string) => new Set((w.grants ?? {})[id] ?? [])),
|
||||
};
|
||||
const env = {} as never;
|
||||
const dbs = {} as never;
|
||||
const svc = new PluginMcpToolsService(hooks as never, runtime as never, env, dbs);
|
||||
// Plan 3i Task 3: DemoService, stubbed the same shape the removed
|
||||
// vi.mock('.../common/demo-write', ...) provided — isDemoUserId() reads
|
||||
// the module-level `demoUser` flag at call time.
|
||||
const demo = { isDemoUserId: () => Promise.resolve(demoUser) } as never;
|
||||
const svc = new PluginMcpToolsService(hooks as never, runtime as never, env, demo);
|
||||
return { svc, hooks, runtime, callTool };
|
||||
}
|
||||
|
||||
@@ -50,7 +53,6 @@ let pluginsOn = true;
|
||||
let demoUser = false;
|
||||
|
||||
vi.mock('../../../src/nest/plugins/kill-switch', () => ({ pluginsEnabled: () => pluginsOn }));
|
||||
vi.mock('../../../src/nest/common/demo-write', () => ({ isDemoUserId: () => demoUser }));
|
||||
|
||||
beforeEach(() => {
|
||||
pluginsOn = true;
|
||||
@@ -61,9 +63,9 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe('the advertised surface', () => {
|
||||
it('MCPTOOLS-001: advertises a declared and implemented tool under the prefixed name', () => {
|
||||
it('MCPTOOLS-001: advertises a declared and implemented tool under the prefixed name', async () => {
|
||||
const { svc } = makeService();
|
||||
const tools = svc.mcpTools(ctx);
|
||||
const tools = await svc.mcpTools(ctx);
|
||||
|
||||
expect(tools).toHaveLength(1);
|
||||
expect(tools[0].options.name).toBe('plugin_weather_forecast');
|
||||
@@ -71,32 +73,32 @@ describe('the advertised surface', () => {
|
||||
expect(tools[0].options.access).toEqual({ group: 'plugins', mode: 'use' });
|
||||
});
|
||||
|
||||
it('MCPTOOLS-002: drops a tool the manifest declares but the build does not implement', () => {
|
||||
it('MCPTOOLS-002: drops a tool the manifest declares but the build does not implement', async () => {
|
||||
const { svc } = makeService({ implemented: { weather: [] } });
|
||||
expect(svc.mcpTools(ctx)).toEqual([]);
|
||||
expect(await svc.mcpTools(ctx)).toEqual([]);
|
||||
});
|
||||
|
||||
it('MCPTOOLS-003: drops a tool the build reports but the manifest never declared', () => {
|
||||
it('MCPTOOLS-003: drops a tool the build reports but the manifest never declared', async () => {
|
||||
// The manifest is signed and re-consented; the loaded report is neither.
|
||||
const { svc } = makeService({ declared: { weather: [] }, implemented: { weather: ['sneaky'] } });
|
||||
expect(svc.mcpTools(ctx)).toEqual([]);
|
||||
expect(await svc.mcpTools(ctx)).toEqual([]);
|
||||
});
|
||||
|
||||
it('MCPTOOLS-004: a plugin without the grant never reaches the surface', () => {
|
||||
it('MCPTOOLS-004: a plugin without the grant never reaches the surface', async () => {
|
||||
// providersOf already filters on active AND reported AND granted.
|
||||
const { svc, hooks } = makeService({ providers: [] });
|
||||
expect(svc.mcpTools(ctx)).toEqual([]);
|
||||
expect(await svc.mcpTools(ctx)).toEqual([]);
|
||||
expect(hooks.providersOf).toHaveBeenCalledWith('mcpToolProvider');
|
||||
});
|
||||
|
||||
it('MCPTOOLS-005: the kill switch empties the surface', () => {
|
||||
it('MCPTOOLS-005: the kill switch empties the surface', async () => {
|
||||
pluginsOn = false;
|
||||
const { svc, hooks } = makeService();
|
||||
expect(svc.mcpTools(ctx)).toEqual([]);
|
||||
expect(await svc.mcpTools(ctx)).toEqual([]);
|
||||
expect(hooks.providersOf).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('MCPTOOLS-006: one failing plugin costs only its own tools', () => {
|
||||
it('MCPTOOLS-006: one failing plugin costs only its own tools', async () => {
|
||||
const { svc } = makeService({
|
||||
providers: ['broken', 'weather'],
|
||||
declared: {
|
||||
@@ -106,20 +108,20 @@ describe('the advertised surface', () => {
|
||||
implemented: { weather: ['forecast'], broken: ['x'] },
|
||||
});
|
||||
|
||||
const tools = svc.mcpTools(ctx);
|
||||
const tools = await svc.mcpTools(ctx);
|
||||
expect(tools.map((t) => t.options.name)).toEqual(['plugin_weather_forecast']);
|
||||
});
|
||||
|
||||
it('MCPTOOLS-007: caps the tools one plugin may contribute', () => {
|
||||
it('MCPTOOLS-007: caps the tools one plugin may contribute', async () => {
|
||||
const many = Array.from({ length: 12 }, (_, i) => ({ ...weatherTool, name: `t${i}` }));
|
||||
const { svc } = makeService({
|
||||
declared: { weather: many },
|
||||
implemented: { weather: many.map((t) => t.name) },
|
||||
});
|
||||
expect(svc.mcpTools(ctx)).toHaveLength(8);
|
||||
expect(await svc.mcpTools(ctx)).toHaveLength(8);
|
||||
});
|
||||
|
||||
it('MCPTOOLS-008: caps the whole surface and says so rather than truncating silently', () => {
|
||||
it('MCPTOOLS-008: caps the whole surface and says so rather than truncating silently', async () => {
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
const eight = Array.from({ length: 8 }, (_, i) => ({ ...weatherTool, name: `t${i}` }));
|
||||
const providers = ['p1', 'p2', 'p3', 'p4', 'p5'];
|
||||
@@ -131,22 +133,22 @@ describe('the advertised surface', () => {
|
||||
}
|
||||
|
||||
const { svc } = makeService({ providers, declared, implemented });
|
||||
expect(svc.mcpTools(ctx)).toHaveLength(32);
|
||||
expect(await svc.mcpTools(ctx)).toHaveLength(32);
|
||||
expect(warn).toHaveBeenCalledWith(expect.stringContaining('dropped'));
|
||||
});
|
||||
|
||||
it('MCPTOOLS-009: clamps annotations against the grants the plugin actually holds', () => {
|
||||
it('MCPTOOLS-009: clamps annotations against the grants the plugin actually holds', async () => {
|
||||
const claiming = [{ ...weatherTool, annotations: { readOnlyHint: true } }];
|
||||
const { svc } = makeService({
|
||||
declared: { weather: claiming },
|
||||
grants: { weather: ['db:write:trips'] },
|
||||
});
|
||||
expect(svc.mcpTools(ctx)[0].options.annotations).toMatchObject({ readOnlyHint: false });
|
||||
expect((await svc.mcpTools(ctx))[0].options.annotations).toMatchObject({ readOnlyHint: false });
|
||||
});
|
||||
|
||||
it('MCPTOOLS-010: never advertises _meta or an outputSchema', () => {
|
||||
it('MCPTOOLS-010: never advertises _meta or an outputSchema', async () => {
|
||||
const { svc } = makeService({ declared: { weather: [{ ...weatherTool, _meta: { x: 1 } }] } });
|
||||
const options = svc.mcpTools(ctx)[0].options;
|
||||
const options = (await svc.mcpTools(ctx))[0].options;
|
||||
expect(options._meta).toBeUndefined();
|
||||
expect(options.outputSchema).toBeUndefined();
|
||||
});
|
||||
@@ -154,7 +156,7 @@ describe('the advertised surface', () => {
|
||||
|
||||
describe('invoking a tool', () => {
|
||||
const invoke = async (svc: PluginMcpToolsService, args: unknown = { city: 'Lisbon' }) => {
|
||||
const tool = svc.mcpTools(ctx)[0];
|
||||
const tool = (await svc.mcpTools(ctx))[0];
|
||||
return (await tool.handler(args, ctx)) as { content: Array<{ text: string }>; isError?: boolean };
|
||||
};
|
||||
|
||||
@@ -181,17 +183,18 @@ describe('invoking a tool', () => {
|
||||
expect(res.content[0].text).toContain('upstream 503');
|
||||
});
|
||||
|
||||
it('MCPTOOLS-014: refuses in demo mode without ever reaching the plugin', async () => {
|
||||
it('MCPTOOLS-014: refuses in demo mode without ever reaching the plugin, via the injected DemoService (Plan 3i Task 3 survivor site), with the exact canned refusal body', async () => {
|
||||
demoUser = true;
|
||||
const { svc, callTool } = makeService();
|
||||
const res = await invoke(svc);
|
||||
expect(res.isError).toBe(true);
|
||||
expect(res.content).toEqual([{ type: 'text', text: 'Write operations are disabled in demo mode.' }]);
|
||||
expect(callTool).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('MCPTOOLS-015: refuses once the kill switch goes off mid-session', async () => {
|
||||
const { svc, callTool } = makeService();
|
||||
const tool = svc.mcpTools(ctx)[0];
|
||||
const tool = (await svc.mcpTools(ctx))[0];
|
||||
pluginsOn = false;
|
||||
const res = (await tool.handler({}, ctx)) as { isError?: boolean };
|
||||
expect(res.isError).toBe(true);
|
||||
@@ -200,29 +203,29 @@ describe('invoking a tool', () => {
|
||||
});
|
||||
|
||||
describe('toMcpTextResult', () => {
|
||||
it('MCPTOOLS-016: preserves a well-formed result, isError included', () => {
|
||||
it('MCPTOOLS-016: preserves a well-formed result, isError included', async () => {
|
||||
const given = { content: [{ type: 'text', text: 'hi' }], isError: true };
|
||||
expect(toMcpTextResult(given)).toEqual(given);
|
||||
});
|
||||
|
||||
it('MCPTOOLS-017: wraps a bare string', () => {
|
||||
it('MCPTOOLS-017: wraps a bare string', async () => {
|
||||
expect(toMcpTextResult('hello')).toEqual({ content: [{ type: 'text', text: 'hello' }] });
|
||||
});
|
||||
|
||||
it('MCPTOOLS-018: survives a value that cannot be serialised', () => {
|
||||
it('MCPTOOLS-018: survives a value that cannot be serialised', async () => {
|
||||
const cyclic: Record<string, unknown> = {};
|
||||
cyclic.self = cyclic;
|
||||
const res = toMcpTextResult(cyclic) as { isError?: boolean };
|
||||
expect(res.isError).toBe(true);
|
||||
});
|
||||
|
||||
it('MCPTOOLS-019: caps a flood so a plugin cannot fill the assistant context', () => {
|
||||
it('MCPTOOLS-019: caps a flood so a plugin cannot fill the assistant context', async () => {
|
||||
const huge = 'x'.repeat(200_000);
|
||||
const res = toMcpTextResult(huge);
|
||||
expect(res.content[0].text.length).toBeLessThanOrEqual(64 * 1024);
|
||||
});
|
||||
|
||||
it('MCPTOOLS-020: the budget covers the WHOLE result, not each block', () => {
|
||||
it('MCPTOOLS-020: the budget covers the WHOLE result, not each block', async () => {
|
||||
// Per-block slicing is not a limit: 100 blocks of the maximum size is 100
|
||||
// times the maximum. This shape produced 6.5M characters before the fix.
|
||||
const many = { content: Array.from({ length: 100 }, () => ({ type: 'text', text: 'x'.repeat(200_000) })) };
|
||||
@@ -231,14 +234,14 @@ describe('toMcpTextResult', () => {
|
||||
expect(total).toBeLessThan(70 * 1024);
|
||||
});
|
||||
|
||||
it('MCPTOOLS-021: caps the number of content blocks and says it truncated', () => {
|
||||
it('MCPTOOLS-021: caps the number of content blocks and says it truncated', async () => {
|
||||
const many = { content: Array.from({ length: 500 }, (_, i) => ({ type: 'text', text: `b${i}` })) };
|
||||
const res = toMcpTextResult(many);
|
||||
expect(res.content.length).toBeLessThanOrEqual(33);
|
||||
expect(res.content[res.content.length - 1].text).toContain('truncated');
|
||||
});
|
||||
|
||||
it('MCPTOOLS-022: bounds a huge object without serialising it whole first', () => {
|
||||
it('MCPTOOLS-022: bounds a huge object without serialising it whole first', async () => {
|
||||
const fat = { rows: Array.from({ length: 20_000 }, (_, i) => ({ i, blob: 'y'.repeat(500) })) };
|
||||
const res = toMcpTextResult(fat);
|
||||
const total = res.content.reduce((n, c) => n + c.text.length, 0);
|
||||
|
||||
@@ -11,12 +11,10 @@ const { pluginsEnabled, getMock } = vi.hoisted(() => ({
|
||||
getMock: vi.fn(() => ({ 1: 1 })), // plugin is active by default
|
||||
}));
|
||||
vi.mock('../../../src/nest/plugins/kill-switch', () => ({ pluginsEnabled }));
|
||||
vi.mock('../../../src/db/database', () => ({ db: { prepare: () => ({ get: getMock }) } }));
|
||||
import { db as dbConn } from '../../../src/db/database';
|
||||
import { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
|
||||
import { PluginOAuthController } from '../../../src/nest/plugins/oauth/plugin-oauth.controller';
|
||||
import type { PluginOAuthService } from '../../../src/nest/plugins/oauth/plugin-oauth.service';
|
||||
import type { PluginsRepository } from '../../../src/db/repositories/Plugins.repository';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const req = (id?: number) => ({ user: id === undefined ? undefined : { id } }) as any;
|
||||
@@ -26,31 +24,33 @@ function fakeRes() {
|
||||
}
|
||||
function ctrl(over: Partial<PluginOAuthService> = {}) {
|
||||
const svc = {
|
||||
status: vi.fn(() => ({ configured: true, connected: false })),
|
||||
startConnect: vi.fn(() => 'https://provider.example/auth?state=s'),
|
||||
status: vi.fn(async () => ({ configured: true, connected: false })),
|
||||
startConnect: vi.fn(async () => 'https://provider.example/auth?state=s'),
|
||||
completeCallback: vi.fn(async () => undefined),
|
||||
disconnect: vi.fn(),
|
||||
disconnect: vi.fn(async () => undefined),
|
||||
...over,
|
||||
} as unknown as PluginOAuthService;
|
||||
return { c: new PluginOAuthController(svc, new DatabaseService(dbConn)), svc };
|
||||
// POC1 (Plan 3j Task 5) — the active-plugin guard is now Plugins.repository.ts#existsActive.
|
||||
const plugins = { existsActive: vi.fn(async () => !!getMock()) } as unknown as PluginsRepository;
|
||||
return { c: new PluginOAuthController(svc, plugins), svc };
|
||||
}
|
||||
|
||||
describe('PluginOAuthController', () => {
|
||||
beforeEach(() => { pluginsEnabled.mockReturnValue(true); getMock.mockReturnValue({ 1: 1 }); });
|
||||
|
||||
it('status is gated: runtime off / no user / inactive → not configured', () => {
|
||||
expect(ctrl().c.status('p', req(5))).toEqual({ configured: true, connected: false });
|
||||
it('status is gated: runtime off / no user / inactive → not configured', async () => {
|
||||
expect(await ctrl().c.status('p', req(5))).toEqual({ configured: true, connected: false });
|
||||
pluginsEnabled.mockReturnValue(false);
|
||||
expect(ctrl().c.status('p', req(5))).toEqual({ configured: false, connected: false });
|
||||
expect(await ctrl().c.status('p', req(5))).toEqual({ configured: false, connected: false });
|
||||
pluginsEnabled.mockReturnValue(true);
|
||||
expect(ctrl().c.status('p', req(undefined))).toEqual({ configured: false, connected: false });
|
||||
expect(await ctrl().c.status('p', req(undefined))).toEqual({ configured: false, connected: false });
|
||||
getMock.mockReturnValue(undefined as never); // inactive
|
||||
expect(ctrl().c.status('p', req(5))).toEqual({ configured: false, connected: false });
|
||||
expect(await ctrl().c.status('p', req(5))).toEqual({ configured: false, connected: false });
|
||||
});
|
||||
|
||||
it('connect returns the authorize URL for a bound user', () => {
|
||||
it('connect returns the authorize URL for a bound user', async () => {
|
||||
const { c, svc } = ctrl();
|
||||
expect(c.connect('p', req(5))).toEqual({ authorizeUrl: 'https://provider.example/auth?state=s' });
|
||||
expect(await c.connect('p', req(5))).toEqual({ authorizeUrl: 'https://provider.example/auth?state=s' });
|
||||
expect(svc.startConnect).toHaveBeenCalledWith('p', 5, expect.any(Number));
|
||||
});
|
||||
|
||||
@@ -68,9 +68,9 @@ describe('PluginOAuthController', () => {
|
||||
expect(denyRes.redirectedTo).toBe('/settings?oauth=p:denied');
|
||||
});
|
||||
|
||||
it('disconnect delegates for a bound user', () => {
|
||||
it('disconnect delegates for a bound user', async () => {
|
||||
const { c, svc } = ctrl();
|
||||
expect(c.disconnect('p', req(5))).toEqual({ connected: false });
|
||||
expect(await c.disconnect('p', req(5))).toEqual({ connected: false });
|
||||
expect(svc.disconnect).toHaveBeenCalledWith('p', 5);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -16,9 +16,11 @@ vi.mock('../../../src/app-config', async (importOriginal) => {
|
||||
});
|
||||
|
||||
const { getDb } = vi.hoisted(() => ({ getDb: { current: null as unknown } }));
|
||||
// The mock stays even though nothing in this file imports `db` directly any more
|
||||
// (the service dropped its last raw-connection use) — a transitive importer of
|
||||
// `src/db/database` elsewhere in the module graph would otherwise try to open a
|
||||
// real connection at import time.
|
||||
vi.mock('../../../src/db/database', () => ({ get db() { return getDb.current; } }));
|
||||
import { db as dbConn } from '../../../src/db/database';
|
||||
import { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
|
||||
// The token POST now runs through the SSRF guard (ssrfGuard.safeFetchLlm), which
|
||||
// resolves the host before fetching. Stub DNS so the fake provider.example host
|
||||
@@ -30,7 +32,13 @@ vi.mock('node:dns/promises', () => {
|
||||
});
|
||||
|
||||
import Database from 'better-sqlite3';
|
||||
import { createSnapshotTestDb } from '../../helpers/db-mock';
|
||||
import { PluginOAuthService } from '../../../src/nest/plugins/oauth/plugin-oauth.service';
|
||||
import { sharedTestOrm } from '../../helpers/test-uow';
|
||||
import { Plugins } from '../../../src/db/entities/Plugins.entity';
|
||||
import { PluginOauthTokens } from '../../../src/db/entities/PluginOauthTokens.entity';
|
||||
import { PluginOauthState } from '../../../src/db/entities/PluginOauthState.entity';
|
||||
import { PluginSettingsFields } from '../../../src/db/entities/PluginSettingsFields.entity';
|
||||
|
||||
const CFG = {
|
||||
oauth_authorize_url: 'https://provider.example/authorize',
|
||||
@@ -41,30 +49,35 @@ const CFG = {
|
||||
};
|
||||
|
||||
function freshDb(cfg: Record<string, unknown> = CFG) {
|
||||
const d = new Database(':memory:');
|
||||
d.exec(`
|
||||
CREATE TABLE plugins (id TEXT PRIMARY KEY, config TEXT, status TEXT);
|
||||
CREATE TABLE plugin_settings_fields (plugin_id TEXT, field_key TEXT, scope TEXT, secret INTEGER, default_value TEXT);
|
||||
CREATE TABLE plugin_oauth_tokens (plugin_id TEXT, user_id INTEGER, access_token TEXT, refresh_token TEXT, expires_at INTEGER, scope TEXT, updated_at TEXT, PRIMARY KEY (plugin_id, user_id));
|
||||
CREATE TABLE plugin_oauth_state (state TEXT PRIMARY KEY, plugin_id TEXT, user_id INTEGER, verifier TEXT, created_at INTEGER);
|
||||
`);
|
||||
d.prepare("INSERT INTO plugins (id, config, status) VALUES ('p', ?, 'active')").run(JSON.stringify(cfg));
|
||||
const d = createSnapshotTestDb();
|
||||
d.prepare("INSERT INTO plugins (id, name, config, status) VALUES ('p', 'p', ?, 'active')").run(JSON.stringify(cfg));
|
||||
return d;
|
||||
}
|
||||
|
||||
const NOW = 1_700_000_000_000;
|
||||
|
||||
/**
|
||||
* `PluginOAuthService`, built with real repositories over whichever fresh
|
||||
* `getDb.current` the caller just set — `sharedTestOrm` is memoized per db HANDLE,
|
||||
* and every test below assigns a brand-new `:memory:` db, so each call here gets
|
||||
* its own ORM, matching the pattern `plugin-user-settings.test.ts` established.
|
||||
*/
|
||||
async function makeOauthService(): Promise<PluginOAuthService> {
|
||||
const orm = await sharedTestOrm(getDb.current as Database.Database);
|
||||
return new PluginOAuthService(orm.repo(Plugins), orm.repo(PluginOauthTokens), orm.repo(PluginOauthState), orm.repo(PluginSettingsFields));
|
||||
}
|
||||
|
||||
describe('PluginOAuthService', () => {
|
||||
let svc: PluginOAuthService;
|
||||
beforeEach(() => { getDb.current = freshDb(); svc = new PluginOAuthService(new DatabaseService(dbConn)); vi.restoreAllMocks(); dnsState.address = '93.184.216.34'; dnsState.family = 4; });
|
||||
beforeEach(async () => { getDb.current = freshDb(); svc = await makeOauthService(); vi.restoreAllMocks(); dnsState.address = '93.184.216.34'; dnsState.family = 4; });
|
||||
|
||||
it('providerConfig returns null unless every piece is present, decrypting the secrets', () => {
|
||||
expect(svc.providerConfig('p')).toMatchObject({ clientId: 'client-123', clientSecret: 'secret-abc', scopes: 'read write' });
|
||||
it('providerConfig returns null unless every piece is present, decrypting the secrets', async () => {
|
||||
expect(await svc.providerConfig('p')).toMatchObject({ clientId: 'client-123', clientSecret: 'secret-abc', scopes: 'read write' });
|
||||
getDb.current = freshDb({ ...CFG, oauth_client_secret: '' });
|
||||
expect(new PluginOAuthService(new DatabaseService(dbConn)).providerConfig('p')).toBeNull();
|
||||
expect(await (await makeOauthService()).providerConfig('p')).toBeNull();
|
||||
});
|
||||
|
||||
it('providerConfig falls back to the manifest defaults for the endpoints the admin left unset', () => {
|
||||
it('providerConfig falls back to the manifest defaults for the endpoints the admin left unset', async () => {
|
||||
// A provider plugin ships its authorize/token URLs as defaults; the admin only ever
|
||||
// types the client id/secret. Those two are secrets and can never carry a default.
|
||||
const { oauth_authorize_url: _a, oauth_token_url: _t, oauth_scopes: _s, ...stored } = CFG;
|
||||
@@ -74,8 +87,8 @@ describe('PluginOAuthService', () => {
|
||||
ins.run('oauth_authorize_url', JSON.stringify('https://provider.example/authorize'));
|
||||
ins.run('oauth_token_url', JSON.stringify('https://provider.example/token'));
|
||||
ins.run('oauth_scopes', JSON.stringify('read'));
|
||||
svc = new PluginOAuthService(new DatabaseService(dbConn));
|
||||
expect(svc.providerConfig('p')).toEqual({
|
||||
svc = (await makeOauthService());
|
||||
expect(await svc.providerConfig('p')).toEqual({
|
||||
authorizeUrl: 'https://provider.example/authorize',
|
||||
tokenUrl: 'https://provider.example/token',
|
||||
scopes: 'read',
|
||||
@@ -84,8 +97,8 @@ describe('PluginOAuthService', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('startConnect builds a PKCE authorize URL + persists a single fresh state per user', () => {
|
||||
const url = new URL(svc.startConnect('p', 42, NOW));
|
||||
it('startConnect builds a PKCE authorize URL + persists a single fresh state per user', async () => {
|
||||
const url = new URL(await svc.startConnect('p', 42, NOW));
|
||||
expect(url.origin + url.pathname).toBe('https://provider.example/authorize');
|
||||
expect(url.searchParams.get('code_challenge_method')).toBe('S256');
|
||||
expect(url.searchParams.get('client_id')).toBe('client-123');
|
||||
@@ -96,28 +109,28 @@ describe('PluginOAuthService', () => {
|
||||
const stored = rows.prepare('SELECT verifier, user_id FROM plugin_oauth_state WHERE state = ?').get(state) as { verifier: string; user_id: number };
|
||||
expect(stored.user_id).toBe(42);
|
||||
// a second connect replaces the first (one live state per user)
|
||||
svc.startConnect('p', 42, NOW);
|
||||
await svc.startConnect('p', 42, NOW);
|
||||
expect((rows.prepare('SELECT COUNT(*) c FROM plugin_oauth_state WHERE user_id = 42').get() as { c: number }).c).toBe(1);
|
||||
});
|
||||
|
||||
it('rejects a non-https / loopback / metadata / internal authorize endpoint', () => {
|
||||
it('rejects a non-https / loopback / metadata / internal authorize endpoint', async () => {
|
||||
getDb.current = freshDb({ ...CFG, oauth_authorize_url: 'http://provider.example/authorize' });
|
||||
expect(() => new PluginOAuthService(new DatabaseService(dbConn)).startConnect('p', 42, NOW)).toThrow(/https/);
|
||||
await expect((await makeOauthService()).startConnect('p', 42, NOW)).rejects.toThrow(/https/);
|
||||
getDb.current = freshDb({ ...CFG, oauth_token_url: 'https://127.0.0.1/token' });
|
||||
expect(() => new PluginOAuthService(new DatabaseService(dbConn)).startConnect('p', 42, NOW)).toThrow(/loopback|private/);
|
||||
await expect((await makeOauthService()).startConnect('p', 42, NOW)).rejects.toThrow(/loopback|private/);
|
||||
// IPv6-literal loopback must not slip past the fast-fail
|
||||
getDb.current = freshDb({ ...CFG, oauth_token_url: 'https://[::1]/token' });
|
||||
expect(() => new PluginOAuthService(new DatabaseService(dbConn)).startConnect('p', 42, NOW)).toThrow(/loopback/);
|
||||
await expect((await makeOauthService()).startConnect('p', 42, NOW)).rejects.toThrow(/loopback/);
|
||||
// cloud-metadata by literal is refused too
|
||||
getDb.current = freshDb({ ...CFG, oauth_token_url: 'https://169.254.169.254/token' });
|
||||
expect(() => new PluginOAuthService(new DatabaseService(dbConn)).startConnect('p', 42, NOW)).toThrow(/loopback|metadata/);
|
||||
await expect((await makeOauthService()).startConnect('p', 42, NOW)).rejects.toThrow(/loopback|metadata/);
|
||||
// an internal name suffix is refused
|
||||
getDb.current = freshDb({ ...CFG, oauth_token_url: 'https://idp.internal/token' });
|
||||
expect(() => new PluginOAuthService(new DatabaseService(dbConn)).startConnect('p', 42, NOW)).toThrow(/local/);
|
||||
await expect((await makeOauthService()).startConnect('p', 42, NOW)).rejects.toThrow(/local/);
|
||||
});
|
||||
|
||||
it('completeCallback verifies state (single-use, user-bound, TTL), exchanges the code, encrypts tokens', async () => {
|
||||
const url = new URL(svc.startConnect('p', 42, NOW));
|
||||
const url = new URL(await svc.startConnect('p', 42, NOW));
|
||||
const state = url.searchParams.get('state')!;
|
||||
const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue({
|
||||
ok: true, json: async () => ({ access_token: 'AT', refresh_token: 'RT', expires_in: 3600, scope: 'read' }),
|
||||
@@ -134,15 +147,15 @@ describe('PluginOAuthService', () => {
|
||||
const tok = rows.prepare('SELECT access_token, refresh_token FROM plugin_oauth_tokens WHERE plugin_id = ? AND user_id = 42').get('p') as { access_token: string; refresh_token: string };
|
||||
expect(tok.access_token).toBe('enc:AT'); // encrypted at rest
|
||||
expect(tok.refresh_token).toBe('enc:RT');
|
||||
expect(svc.status('p', 42)).toMatchObject({ configured: true, connected: true });
|
||||
expect(await svc.status('p', 42)).toMatchObject({ configured: true, connected: true });
|
||||
// state is single-use — replaying it fails
|
||||
await expect(svc.completeCallback('p', 42, 'the-code', state, NOW + 2000)).rejects.toThrow(/state/);
|
||||
});
|
||||
|
||||
it('rejects a foreign or expired state', async () => {
|
||||
const state = new URL(svc.startConnect('p', 42, NOW)).searchParams.get('state')!;
|
||||
const state = new URL(await svc.startConnect('p', 42, NOW)).searchParams.get('state')!;
|
||||
await expect(svc.completeCallback('p', 99, 'code', state, NOW + 1000)).rejects.toThrow(/state/); // wrong user
|
||||
const state2 = new URL(svc.startConnect('p', 42, NOW)).searchParams.get('state')!;
|
||||
const state2 = new URL(await svc.startConnect('p', 42, NOW)).searchParams.get('state')!;
|
||||
await expect(svc.completeCallback('p', 42, 'code', state2, NOW + 20 * 60 * 1000)).rejects.toThrow(/state/); // > 10 min
|
||||
});
|
||||
|
||||
@@ -166,7 +179,7 @@ describe('PluginOAuthService', () => {
|
||||
});
|
||||
|
||||
it('routes the token exchange through the SSRF guard — a token_url resolving to cloud metadata is refused', async () => {
|
||||
const state = new URL(svc.startConnect('p', 42, NOW)).searchParams.get('state')!;
|
||||
const state = new URL(await svc.startConnect('p', 42, NOW)).searchParams.get('state')!;
|
||||
const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue({ ok: true, json: async () => ({ access_token: 'AT' }) } as Response);
|
||||
// The provider's token_url now resolves to the cloud-metadata address.
|
||||
dnsState.address = '169.254.169.254';
|
||||
@@ -177,7 +190,58 @@ describe('PluginOAuthService', () => {
|
||||
it('disconnect drops the user\'s tokens', async () => {
|
||||
const rows = getDb.current as unknown as InstanceType<typeof Database>;
|
||||
rows.prepare('INSERT INTO plugin_oauth_tokens (plugin_id, user_id, access_token) VALUES (?,?,?)').run('p', 42, 'enc:X');
|
||||
svc.disconnect('p', 42);
|
||||
expect(svc.status('p', 42).connected).toBe(false);
|
||||
await svc.disconnect('p', 42);
|
||||
expect((await svc.status('p', 42)).connected).toBe(false);
|
||||
});
|
||||
|
||||
/**
|
||||
* PO5+PO6+PO7 — single-use is enforced by `consumeByState`'s ONE atomic
|
||||
* delete, on EVERY path out of `completeCallback`: the expired/foreign-state
|
||||
* refusal and the success path both leave the row gone, not just the
|
||||
* success one.
|
||||
*/
|
||||
it('single-use: the state row is gone after EITHER the refused path or the success path', async () => {
|
||||
const rows = getDb.current as unknown as InstanceType<typeof Database>;
|
||||
|
||||
// Refused path: wrong user — the row is still consumed.
|
||||
const stateA = new URL(await svc.startConnect('p', 42, NOW)).searchParams.get('state')!;
|
||||
expect(rows.prepare('SELECT 1 FROM plugin_oauth_state WHERE state = ?').get(stateA)).toBeTruthy();
|
||||
await expect(svc.completeCallback('p', 99, 'code', stateA, NOW + 1000)).rejects.toThrow(/state/);
|
||||
expect(rows.prepare('SELECT 1 FROM plugin_oauth_state WHERE state = ?').get(stateA)).toBeUndefined();
|
||||
|
||||
// Success path.
|
||||
const stateB = new URL(await svc.startConnect('p', 42, NOW)).searchParams.get('state')!;
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValue({ ok: true, json: async () => ({ access_token: 'AT' }) } as Response);
|
||||
await svc.completeCallback('p', 42, 'code', stateB, NOW + 1000);
|
||||
expect(rows.prepare('SELECT 1 FROM plugin_oauth_state WHERE state = ?').get(stateB)).toBeUndefined();
|
||||
});
|
||||
|
||||
/**
|
||||
* R-oauth-upsert's TRAP: the state consume is a check-then-act primitive.
|
||||
* `consumeByState`'s atomic `DELETE ... RETURNING` (PluginOauthState.repository.ts)
|
||||
* exists specifically so two concurrent `completeCallback` calls for the SAME
|
||||
* state cannot both see a live row — racing them here is the proof, matching
|
||||
* the legacy synchronous-JS outcome (exactly one consumer wins, the token
|
||||
* exchange fires exactly once).
|
||||
*/
|
||||
it('the state consume race: two concurrent completeCallback calls for the SAME state — exactly one wins', async () => {
|
||||
const state = new URL(await svc.startConnect('p', 42, NOW)).searchParams.get('state')!;
|
||||
const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue({
|
||||
ok: true, json: async () => ({ access_token: 'AT', refresh_token: 'RT', expires_in: 3600 }),
|
||||
} as Response);
|
||||
|
||||
const results = await Promise.allSettled([
|
||||
svc.completeCallback('p', 42, 'code', state, NOW + 1000),
|
||||
svc.completeCallback('p', 42, 'code', state, NOW + 1000),
|
||||
]);
|
||||
const fulfilled = results.filter((r) => r.status === 'fulfilled');
|
||||
const rejected = results.filter((r) => r.status === 'rejected');
|
||||
expect(fulfilled).toHaveLength(1); // exactly one consumer wins the state
|
||||
expect(rejected).toHaveLength(1);
|
||||
expect((rejected[0] as PromiseRejectedResult).reason as Error).toMatchObject({ message: expect.stringMatching(/state/) });
|
||||
// The token exchange fired exactly once — the loser never reached it.
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
const rows = getDb.current as unknown as InstanceType<typeof Database>;
|
||||
expect(rows.prepare('SELECT 1 FROM plugin_oauth_state WHERE state = ?').get(state)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -8,14 +8,20 @@
|
||||
* namespaced, and styled by the HOST's copy of the declaration, never the plugin's
|
||||
* answer, because the colour and icon end up inside marker markup.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import Database from 'better-sqlite3';
|
||||
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
|
||||
import { HttpException } from '@nestjs/common';
|
||||
|
||||
const { pluginsEnabled } = vi.hoisted(() => ({ pluginsEnabled: vi.fn(() => true) }));
|
||||
vi.mock('../../../src/nest/plugins/kill-switch', () => ({ pluginsEnabled }));
|
||||
vi.mock('../../../src/db/database', async () => {
|
||||
const { createSnapshotTestDb } = await import('../../helpers/db-mock');
|
||||
const db = createSnapshotTestDb();
|
||||
return { db, closeDb: () => {}, reinitialize: () => {}, getPlaceWithTags: () => null, canAccessTrip: () => null, isOwner: () => false };
|
||||
});
|
||||
|
||||
import { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
import { db as testDb } from '../../../src/db/database';
|
||||
import type { PluginsRepository } from '../../../src/db/repositories/Plugins.repository';
|
||||
import { createTestPluginsRepo } from '../../helpers/share-repos';
|
||||
import type { PluginHooks } from '../../../src/nest/plugins/plugin-hooks.service';
|
||||
import { PluginPoisService } from '../../../src/nest/plugins/contributions/plugin-pois.service';
|
||||
import { PluginPoisController, parsePluginPoiQuery } from '../../../src/nest/plugins/contributions/plugin-pois.controller';
|
||||
@@ -31,22 +37,27 @@ const trailheads: PluginPoiCategory = { id: 'trailheads', label: 'Trailheads', l
|
||||
const bounds = { south: 47, west: 11, north: 47.5, east: 11.5 };
|
||||
const hit = (over: Record<string, unknown> = {}) => ({ id: 'th-1', name: 'Trailhead', lat: 47.2, lng: 11.2, ...over });
|
||||
|
||||
function makeDb(): DatabaseService {
|
||||
const conn = new Database(':memory:');
|
||||
conn.exec("CREATE TABLE plugins (id TEXT PRIMARY KEY, name TEXT, status TEXT, sort_order INTEGER DEFAULT 0, capabilities TEXT)");
|
||||
const insert = conn.prepare('INSERT INTO plugins (id, name, status, sort_order, capabilities) VALUES (?, ?, ?, ?, ?)');
|
||||
// The plugin rows every case reads, re-seeded before each one on the migrated
|
||||
// snapshot the ORM repository is bound to.
|
||||
function seedPlugins(): void {
|
||||
testDb.prepare('DELETE FROM plugins').run();
|
||||
const insert = testDb.prepare('INSERT INTO plugins (id, name, status, sort_order, capabilities) VALUES (?, ?, ?, ?, ?)');
|
||||
insert.run('trail-finder', 'Trail Finder', 'active', 1, JSON.stringify({ poiCategories: [trailheads, { ...trailheads, id: 'huts', label: 'Huts', labels: undefined, icon: 'Tent' }] }));
|
||||
insert.run('water-map', 'Water Map', 'active', 0, JSON.stringify({ poiCategories: [{ id: 'taps', label: 'Taps', icon: 'Droplet', color: '#2b6cb0' }] }));
|
||||
insert.run('quiet', 'Quiet', 'active', 2, JSON.stringify({ poiCategories: [{ id: 'benches', label: 'Benches', icon: 'Info', color: '#000000' }] }));
|
||||
return new DatabaseService(conn);
|
||||
}
|
||||
|
||||
function makeService(answer: () => unknown, providers = ['trail-finder', 'water-map'], db = makeDb()) {
|
||||
let pluginsRepo: PluginsRepository;
|
||||
beforeAll(async () => { pluginsRepo = await createTestPluginsRepo(testDb); });
|
||||
beforeEach(() => seedPlugins());
|
||||
afterAll(() => { testDb.close(); });
|
||||
|
||||
function makeService(answer: () => unknown, providers = ['trail-finder', 'water-map']) {
|
||||
const hooks = {
|
||||
providersOf: vi.fn(() => providers),
|
||||
categoryPois: vi.fn(async () => answer()),
|
||||
} as unknown as PluginHooks & { providersOf: ReturnType<typeof vi.fn>; categoryPois: ReturnType<typeof vi.fn> };
|
||||
return { service: new PluginPoisService(hooks, db), hooks };
|
||||
return { service: new PluginPoisService(hooks, pluginsRepo), hooks };
|
||||
}
|
||||
|
||||
beforeEach(() => pluginsEnabled.mockReturnValue(true));
|
||||
@@ -204,24 +215,23 @@ describe('PluginPoisService', () => {
|
||||
.toEqual({ ok: false, status: 502, error: 'The plugin sent an invalid answer' });
|
||||
});
|
||||
|
||||
it('PLUGPOI-012: lists the live categories in feed order with the label for the language', () => {
|
||||
it('PLUGPOI-012: lists the live categories in feed order with the label for the language', async () => {
|
||||
const { service } = makeService(() => []);
|
||||
expect(service.available('de')).toEqual([
|
||||
expect(await service.available('de')).toEqual([
|
||||
{ key: 'plugin:water-map/taps', pluginId: 'water-map', pluginName: 'Water Map', id: 'taps', label: 'Taps', icon: 'Droplet', color: '#2b6cb0' },
|
||||
{ key: 'plugin:trail-finder/trailheads', pluginId: 'trail-finder', pluginName: 'Trail Finder', id: 'trailheads', label: 'Wanderparkplätze', icon: 'Signpost', color: '#2f855a' },
|
||||
{ key: 'plugin:trail-finder/huts', pluginId: 'trail-finder', pluginName: 'Trail Finder', id: 'huts', label: 'Huts', icon: 'Tent', color: '#2f855a' },
|
||||
]);
|
||||
expect(service.available().find((c) => c.id === 'trailheads')?.label).toBe('Trailheads');
|
||||
expect(makeService(() => [], []).service.available()).toEqual([]);
|
||||
expect((await service.available()).find((c) => c.id === 'trailheads')?.label).toBe('Trailheads');
|
||||
expect(await makeService(() => [], []).service.available()).toEqual([]);
|
||||
pluginsEnabled.mockReturnValue(false);
|
||||
expect(service.available()).toEqual([]);
|
||||
expect(await service.available()).toEqual([]);
|
||||
});
|
||||
|
||||
it('PLUGPOI-016: flattens and caps the plugin name an assistant reads, and falls back to the id', () => {
|
||||
const db = makeDb();
|
||||
db.run('UPDATE plugins SET name = ? WHERE id = ?', `Trails\u202E\n\n## System ${'x'.repeat(4000)}`, 'trail-finder');
|
||||
db.run('UPDATE plugins SET name = ? WHERE id = ?', '\u0007\u2028\u2066', 'water-map');
|
||||
const names = makeService(() => [], undefined, db).service.available().map((c) => [c.id, c.pluginName]);
|
||||
it('PLUGPOI-016: flattens and caps the plugin name an assistant reads, and falls back to the id', async () => {
|
||||
testDb.prepare('UPDATE plugins SET name = ? WHERE id = ?').run(`Trails\u202E\n\n## System ${'x'.repeat(4000)}`, 'trail-finder');
|
||||
testDb.prepare('UPDATE plugins SET name = ? WHERE id = ?').run('\u0007\u2028\u2066', 'water-map');
|
||||
const names = (await makeService(() => []).service.available()).map((c) => [c.id, c.pluginName]);
|
||||
const trails = names.find(([id]) => id === 'trailheads')?.[1] ?? '';
|
||||
expect(trails.startsWith('Trails ## System xxx')).toBe(true);
|
||||
expect(trails).toHaveLength(80);
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
/**
|
||||
* Real-SQL parity tests for the plugin-adjacent repository methods Plan 3j Task 5
|
||||
* converted but never covered against raw SQL (task-7-review.md, must-land 4c): the
|
||||
* "Reviewer's full-seed parity" fixture (`r3j-parity.test.ts`, run in-process under the
|
||||
* review's own isolated `r3j-mut` export, 5/5 green there) — ported here per the fix
|
||||
* brief ("donate it, never import from the scratchpad"), not merely referenced.
|
||||
*
|
||||
* Each assertion below compares the converted repository method's result against the
|
||||
* SAME statement run directly on the raw better-sqlite3 handle — the shape that catches
|
||||
* M14 (`findPublicIdentity`'s miss returning `null` instead of `undefined`), M15 (its
|
||||
* key order), M16 (`sharesTripWith` always `true`, a security gate) and M17
|
||||
* (`existsById` ignored) from the review's mutation table, none of which any other
|
||||
* suite killed.
|
||||
*/
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { createSnapshotTestDb } from '../../helpers/db-mock';
|
||||
import { resetTestDb } from '../../helpers/test-db';
|
||||
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
|
||||
import { Trips } from '../../../src/db/entities/Trips.entity';
|
||||
import { Users } from '../../../src/db/entities/Users.entity';
|
||||
import { Days } from '../../../src/db/entities/Days.entity';
|
||||
import { PluginEntityMetadata } from '../../../src/db/entities/PluginEntityMetadata.entity';
|
||||
import { PluginScheduledTasks } from '../../../src/db/entities/PluginScheduledTasks.entity';
|
||||
|
||||
const testDb = createSnapshotTestDb();
|
||||
let t: TestOrm;
|
||||
beforeAll(async () => {
|
||||
t = await createTestOrm(testDb);
|
||||
});
|
||||
beforeEach(() => {
|
||||
resetTestDb(testDb);
|
||||
t.clear();
|
||||
});
|
||||
afterAll(async () => {
|
||||
await t.close();
|
||||
testDb.close();
|
||||
});
|
||||
|
||||
function seed() {
|
||||
for (let i = 1; i <= 6; i++) {
|
||||
testDb
|
||||
.prepare("INSERT INTO users (id, username, email, password_hash, display_name, avatar) VALUES (?, ?, ?, 'x', ?, ?)")
|
||||
.run(i, 'u' + i, `u${i}@x`, i % 2 ? 'D' + i : null, i === 3 ? 'a.png' : null);
|
||||
}
|
||||
const trips: Array<[number, number]> = [
|
||||
[1, 1],
|
||||
[2, 2],
|
||||
[3, 1],
|
||||
[4, 5],
|
||||
];
|
||||
for (const [id, owner] of trips) testDb.prepare('INSERT INTO trips (id, user_id, title) VALUES (?, ?, ?)').run(id, owner, 't');
|
||||
for (const [trip, user] of [
|
||||
[1, 2],
|
||||
[1, 3],
|
||||
[2, 3],
|
||||
[3, 4],
|
||||
[4, 1],
|
||||
]) {
|
||||
testDb.prepare('INSERT INTO trip_members (trip_id, user_id) VALUES (?, ?)').run(trip, user);
|
||||
}
|
||||
for (let d = 1; d <= 5; d++) testDb.prepare('INSERT INTO days (id, trip_id, day_number) VALUES (?, ?, ?)').run(10 + d, d % 2 ? 1 : 2, d);
|
||||
}
|
||||
|
||||
describe('R3J-PARITY (Plan 3j Task 7 fix wave, must-land 4c)', () => {
|
||||
it('HR9 Trips.sharesTripWith == legacy bilateral SQL for every ordered user pair (incl. missing users)', async () => {
|
||||
seed();
|
||||
const repo = t.repo(Trips);
|
||||
const legacy = testDb.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`);
|
||||
const diffs: string[] = [];
|
||||
for (let a = 1; a <= 7; a++) {
|
||||
for (let b = 1; b <= 7; b++) {
|
||||
const legacyResult = !!legacy.get(a, b, a, b);
|
||||
const converted = await repo.sharesTripWith(a, b);
|
||||
if (legacyResult !== converted) diffs.push(`${a},${b}: legacy=${legacyResult} new=${converted}`);
|
||||
}
|
||||
}
|
||||
expect(diffs).toEqual([]);
|
||||
});
|
||||
|
||||
it('Trips.existsById == legacy row-exists SQL, including a miss', async () => {
|
||||
seed();
|
||||
const repo = t.repo(Trips);
|
||||
for (const id of [1, 2, 3, 4, 99]) {
|
||||
const legacy = !!testDb.prepare('SELECT 1 FROM trips WHERE id = ?').get(id);
|
||||
expect(await repo.existsById(id)).toBe(legacy);
|
||||
}
|
||||
});
|
||||
|
||||
it('HR1 Users.findPublicIdentity == legacy row (full key, key order) and miss', async () => {
|
||||
seed();
|
||||
const repo = t.repo(Users);
|
||||
for (let i = 1; i <= 7; i++) {
|
||||
const legacy = testDb.prepare('SELECT id, username, display_name, avatar FROM users WHERE id = ?').get(i);
|
||||
const converted = (await repo.findPublicIdentity(i)) ?? undefined;
|
||||
// JSON.stringify: same keys, same order, same values — catches M15 (key order)
|
||||
// as well as a value drift a plain `toEqual` on two possibly-undefined objects
|
||||
// would not distinguish from M14 (miss shape) below.
|
||||
expect(JSON.stringify(converted)).toBe(JSON.stringify(legacy));
|
||||
}
|
||||
// M14: a miss returns `null` (this repository's own convention, see
|
||||
// `host-surface.rpc.ts#getUser`'s `?? undefined` docstring) — the CALLER maps
|
||||
// that to `undefined` to match the legacy `better-sqlite3` `.get()` shape, which
|
||||
// the `JSON.stringify` comparison above already exercises for id 7 (a miss).
|
||||
expect(await repo.findPublicIdentity(999)).toBeNull();
|
||||
});
|
||||
|
||||
it('CT1/CT2 Days.listIdsByTrip + MR9 Days.findTripId == legacy', async () => {
|
||||
seed();
|
||||
const repo = t.repo(Days);
|
||||
for (const trip of [1, 2, 3, 99]) {
|
||||
const legacy = (testDb.prepare('SELECT id FROM days WHERE trip_id = ?').all(trip) as Array<{ id: number }>).map((r) => r.id);
|
||||
expect(await repo.listIdsByTrip(trip)).toEqual(legacy);
|
||||
}
|
||||
for (const id of [11, 12, 99]) {
|
||||
const legacy = (testDb.prepare('SELECT trip_id FROM days WHERE id = ?').get(id) as { trip_id: number } | undefined)?.trip_id;
|
||||
expect(await repo.findTripId(id)).toEqual(legacy);
|
||||
}
|
||||
});
|
||||
|
||||
it('MR1-MR6 PluginEntityMetadata repository == legacy statements', async () => {
|
||||
seed();
|
||||
const repo = t.repo(PluginEntityMetadata);
|
||||
await repo.upsertValue('p', 'trip', 1, 'b', '"1"');
|
||||
await repo.upsertValue('p', 'trip', 1, 'a', '"2"');
|
||||
await repo.upsertValue('q', 'trip', 1, 'a', '"x"');
|
||||
const before = testDb.prepare("SELECT updated_at FROM plugin_entity_metadata WHERE plugin_id='p' AND key='b'").get() as { updated_at: string };
|
||||
testDb.prepare("UPDATE plugin_entity_metadata SET updated_at='2000-01-01 00:00:00' WHERE plugin_id='p' AND key='b'").run();
|
||||
await repo.upsertValue('p', 'trip', 1, 'b', '"3"');
|
||||
const after = testDb.prepare("SELECT id, value, updated_at FROM plugin_entity_metadata WHERE plugin_id='p' AND key='b'").get() as {
|
||||
id: number;
|
||||
value: string;
|
||||
updated_at: string;
|
||||
};
|
||||
expect(after.value).toBe('"3"'); // MR4: upsert replaces the value
|
||||
expect(after.updated_at).not.toBe('2000-01-01 00:00:00'); // MR4: updated_at refreshed on conflict
|
||||
expect(after.updated_at).toMatch(/^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d$/);
|
||||
expect(before.updated_at).toMatch(/^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d$/);
|
||||
expect(await repo.findValue('p', 'trip', 1, 'b')).toBe('"3"'); // MR1
|
||||
expect(await repo.findValue('p', 'trip', 1, 'zz')).toBeNull(); // MR1 miss
|
||||
expect(await repo.countForEntity('p', 'trip', 1)).toBe(2); // MR3
|
||||
expect(await repo.listForEntity('p', 'trip', 1)).toEqual(
|
||||
testDb.prepare("SELECT key, value FROM plugin_entity_metadata WHERE plugin_id=? AND entity_type=? AND entity_id=? ORDER BY key").all('p', 'trip', 1),
|
||||
); // MR5, ORDER BY key
|
||||
expect(await repo.deleteValue('p', 'trip', 1, 'a')).toBe(true); // MR6
|
||||
expect(await repo.deleteValue('p', 'trip', 1, 'a')).toBe(false); // MR6, already gone
|
||||
expect(testDb.prepare('SELECT COUNT(*) c FROM plugin_entity_metadata').get()).toEqual({ c: 2 }); // 'p'/'b' + 'q'/'a' survive
|
||||
});
|
||||
|
||||
it('HR5-HR8 PluginScheduledTasks repository == legacy statements (upsert keeps id, replaces fields)', async () => {
|
||||
const repo = t.repo(PluginScheduledTasks);
|
||||
await repo.upsertTask({ plugin_id: 'p', name: 'n', due_at: 5, payload: '1', every_ms: null });
|
||||
const id1 = (testDb.prepare("SELECT id FROM plugin_scheduled_tasks WHERE name='n'").get() as { id: number }).id;
|
||||
await repo.upsertTask({ plugin_id: 'p', name: 'n', due_at: 9, payload: '2', every_ms: 60000 });
|
||||
expect(testDb.prepare('SELECT id, plugin_id, name, due_at, payload, every_ms FROM plugin_scheduled_tasks').all()).toEqual([
|
||||
{ id: id1, plugin_id: 'p', name: 'n', due_at: 9, payload: '2', every_ms: 60000 },
|
||||
]); // HR7: same id, replaced fields — an upsert, not a delete+insert
|
||||
expect(await repo.existsForPluginAndName('p', 'n')).toBeTruthy(); // HR5
|
||||
expect(await repo.existsForPluginAndName('p', 'x')).toBeFalsy(); // HR5 miss
|
||||
expect(await repo.countForPlugin('p')).toBe(1); // HR6
|
||||
expect(await repo.deleteByPluginAndName('p', 'n')).toBe(true); // HR8
|
||||
expect(await repo.deleteByPluginAndName('p', 'n')).toBe(false); // HR8, already gone
|
||||
});
|
||||
|
||||
it("HR5-HR7 re-arm's claim guard: rearm only claims a row whose due_at is still <= the claimed-from time", async () => {
|
||||
const repo = t.repo(PluginScheduledTasks);
|
||||
const now = Date.now();
|
||||
await repo.upsertTask({ plugin_id: 'p', name: 'claim', due_at: now - 1000, payload: '1', every_ms: 60000 });
|
||||
const id = (testDb.prepare("SELECT id FROM plugin_scheduled_tasks WHERE name='claim'").get() as { id: number }).id;
|
||||
// The winning claim: due_at <= claimedFromDueAt (the row's own current due_at).
|
||||
expect(await repo.rearm(id, now + 60000, now - 1000)).toBe(true);
|
||||
// A second, losing claim against the SAME stale claimedFromDueAt now fails — the
|
||||
// row's due_at already moved forward past it (RACE-SCHED-001/002's guard).
|
||||
expect(await repo.rearm(id, now + 120000, now - 1000)).toBe(false);
|
||||
const row = testDb.prepare('SELECT due_at FROM plugin_scheduled_tasks WHERE id = ?').get(id) as { due_at: number };
|
||||
expect(row.due_at).toBe(now + 60000); // the losing rearm never wrote
|
||||
// deleteById carries the identical guard shape for the one-shot branch.
|
||||
expect(await repo.deleteById(id, now - 1000)).toBe(false); // stale claim, no-op
|
||||
expect(await repo.deleteById(id, now + 60000)).toBe(true); // current due_at, claims + deletes
|
||||
});
|
||||
|
||||
it('must-land 2: 130 concurrent PluginEntityMetadata.upsertValueCapped calls for the SAME (plugin, entity), 130 DIFFERENT new keys, never exceed the 100 cap', async () => {
|
||||
// The REAL repository method, raced through Promise.all — not a sequential loop —
|
||||
// so the exists+count+write really overlaps (task-7-review.md: live, 130 rows landed
|
||||
// on a 100 cap before this fix). Red without `upsertValueCapped`'s
|
||||
// `getEntityManager().transactional` wrap: the old three-separately-awaited-calls
|
||||
// shape let every racer's stale `count < 100` read pass before any of their writes
|
||||
// landed.
|
||||
const repo = t.repo(PluginEntityMetadata);
|
||||
const results = await Promise.all(
|
||||
Array.from({ length: 130 }, (_, i) => repo.upsertValueCapped('capbomb', 'trip', 1, `k${i}`, String(i), 100)),
|
||||
);
|
||||
expect(results.filter(Boolean).length).toBe(100); // exactly 100 writes accepted
|
||||
expect(await repo.countForEntity('capbomb', 'trip', 1)).toBe(100); // never more than 100 rows
|
||||
expect(testDb.prepare("SELECT COUNT(*) c FROM plugin_entity_metadata WHERE plugin_id='capbomb'").get()).toEqual({ c: 100 });
|
||||
});
|
||||
|
||||
it('must-land 3: 130 concurrent PluginScheduledTasks.upsertTaskCapped calls for the SAME plugin, 130 DIFFERENT new names, never exceed the 100 cap', async () => {
|
||||
const repo = t.repo(PluginScheduledTasks);
|
||||
const due = Date.now() + 60_000;
|
||||
const results = await Promise.all(
|
||||
Array.from({ length: 130 }, (_, i) => repo.upsertTaskCapped({ plugin_id: 'schedbomb', name: `t${i}`, due_at: due, payload: '1', every_ms: null }, 100)),
|
||||
);
|
||||
expect(results.filter(Boolean).length).toBe(100); // exactly 100 writes accepted
|
||||
expect(await repo.countForPlugin('schedbomb')).toBe(100); // never more than 100 rows
|
||||
expect(testDb.prepare("SELECT COUNT(*) c FROM plugin_scheduled_tasks WHERE plugin_id='schedbomb'").get()).toEqual({ c: 100 });
|
||||
});
|
||||
});
|
||||
@@ -13,7 +13,7 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { HttpException, type ArgumentsHost } from '@nestjs/common';
|
||||
|
||||
vi.mock('../../../src/db/database', () => ({ db: {}, canAccessTrip: () => undefined }));
|
||||
vi.mock('../../../src/db/database', () => ({ db: {}, canAccessTrip: async () => undefined }));
|
||||
|
||||
import { PluginsController } from '../../../src/nest/plugins/plugins.controller';
|
||||
import { PluginRuntimeService } from '../../../src/nest/plugins/plugin-runtime.service';
|
||||
@@ -55,7 +55,7 @@ beforeEach(() => {
|
||||
process.env.TREK_PLUGINS_ENABLED = 'true';
|
||||
runtime = { update: vi.fn(), retrust: vi.fn() } as unknown as PluginRuntimeService;
|
||||
registry = { install: vi.fn(), installWithDependencies: vi.fn(), recomputeUpdateHold: vi.fn() } as unknown as PluginRegistryService;
|
||||
plugins = { resumeUpdates: vi.fn(() => true) } as unknown as PluginsService;
|
||||
plugins = { resumeUpdates: vi.fn(async () => true) } as unknown as PluginsService;
|
||||
controller = new PluginsController(plugins, runtime, registry, { isManaged: () => false } as unknown as RuntimeEnvService);
|
||||
});
|
||||
|
||||
@@ -175,7 +175,7 @@ describe('update hold wiring', () => {
|
||||
});
|
||||
|
||||
it('POST :id/resume-updates is a 404 for an unknown plugin', async () => {
|
||||
vi.mocked(plugins.resumeUpdates).mockReturnValue(false);
|
||||
vi.mocked(plugins.resumeUpdates).mockResolvedValue(false);
|
||||
|
||||
const { status } = await wireFailure(async () => controller.resumeUpdates('ghost'));
|
||||
expect(status).toBe(404);
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* SV4 (R-survivors) — `declaredProfiles`, Plan 3j Task 3's conversion of the one
|
||||
* literal `SELECT capabilities FROM plugins WHERE id = ?` backing all three
|
||||
* external callers (`roadtrip-router.service.ts`'s RRT1/RRT2,
|
||||
* `plugin-routes.controller.ts`), now via `PluginsRepository#findCapabilities`
|
||||
* (PR52/PR53 — the same method `plugin-runtime.service.ts`'s
|
||||
* `capabilityList`/`mcpToolCapabilities` use for the same column).
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, beforeEach, afterAll } from 'vitest';
|
||||
import { createSnapshotTestDb } from '../../helpers/db-mock';
|
||||
import { resetTestDb } from '../../helpers/test-db';
|
||||
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
|
||||
import { Plugins } from '../../../src/db/entities/Plugins.entity';
|
||||
import type { PluginsRepository } from '../../../src/db/repositories/Plugins.repository';
|
||||
import { declaredProfiles } from '../../../src/nest/plugins/contributions/plugin-route-normalize';
|
||||
|
||||
const testDb = createSnapshotTestDb();
|
||||
let t: TestOrm;
|
||||
let plugins: PluginsRepository;
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestOrm(testDb);
|
||||
plugins = t.repo(Plugins);
|
||||
});
|
||||
beforeEach(() => { resetTestDb(testDb); t.clear(); });
|
||||
afterAll(async () => { await t.close(); testDb.close(); });
|
||||
|
||||
function seedPlugin(id: string, capabilities: unknown): void {
|
||||
testDb.prepare('INSERT INTO plugins (id, name, capabilities) VALUES (?, ?, ?)').run(id, id, JSON.stringify(capabilities));
|
||||
}
|
||||
|
||||
describe('declaredProfiles', () => {
|
||||
it('RN-001: returns the declared routeProfiles ids, filtered to the safe id pattern', async () => {
|
||||
seedPlugin('roadtrip-plugin', { routeProfiles: [{ id: 'eco' }, { id: 'fast-ev' }, { id: 'BAD ID' }, { id: '' }] });
|
||||
expect(await declaredProfiles(plugins, 'roadtrip-plugin')).toEqual(['eco', 'fast-ev']);
|
||||
});
|
||||
|
||||
it('RN-002: no routeProfiles capability → empty list', async () => {
|
||||
seedPlugin('no-routes', { widget: { slot: 'sidebar' } });
|
||||
expect(await declaredProfiles(plugins, 'no-routes')).toEqual([]);
|
||||
});
|
||||
|
||||
it('RN-003: a missing plugin row → empty list, never throws', async () => {
|
||||
expect(await declaredProfiles(plugins, 'does-not-exist')).toEqual([]);
|
||||
});
|
||||
|
||||
it('RN-004: malformed capabilities JSON → empty list, never throws', async () => {
|
||||
testDb.prepare('INSERT INTO plugins (id, name, capabilities) VALUES (?, ?, ?)').run('bad-json', 'bad-json', 'not json');
|
||||
expect(await declaredProfiles(plugins, 'bad-json')).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -8,7 +8,7 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
const { canAccessTrip, pluginsEnabled, capabilitiesRow } = vi.hoisted(() => ({
|
||||
canAccessTrip: vi.fn((tripId: number, userId: number) => (tripId === 1 && userId === 5 ? { id: 1 } : undefined)),
|
||||
canAccessTrip: vi.fn(async (tripId: number, userId: number) => (tripId === 1 && userId === 5 ? { id: 1 } : undefined)),
|
||||
pluginsEnabled: vi.fn(() => true),
|
||||
capabilitiesRow: { value: JSON.stringify({ routeProfiles: [{ id: 'ev', label: 'EV' }] }) as string | undefined },
|
||||
}));
|
||||
@@ -16,12 +16,12 @@ vi.mock('../../../src/db/database', () => ({
|
||||
db: { prepare: () => ({ get: () => (capabilitiesRow.value === undefined ? undefined : { capabilities: capabilitiesRow.value }) }) },
|
||||
canAccessTrip,
|
||||
}));
|
||||
import { db as dbConn } from '../../../src/db/database';
|
||||
import { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
import type { TripsRepository } from '../../../src/db/repositories/Trips.repository';
|
||||
vi.mock('../../../src/nest/plugins/kill-switch', () => ({ pluginsEnabled }));
|
||||
|
||||
import { PluginRoutesController } from '../../../src/nest/plugins/contributions/plugin-routes.controller';
|
||||
import type { PluginHooks } from '../../../src/nest/plugins/plugin-hooks.service';
|
||||
import type { PluginsRepository } from '../../../src/db/repositories/Plugins.repository';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const req = (id?: number) => ({ user: id === undefined ? undefined : { id } }) as any;
|
||||
@@ -30,7 +30,13 @@ function controller(invoke: () => unknown, providers = ['ev-plug']) {
|
||||
providersOf: vi.fn(() => providers),
|
||||
route: vi.fn(async () => invoke()),
|
||||
} as unknown as PluginHooks;
|
||||
return { c: new PluginRoutesController(runtime, new DatabaseService(dbConn)), runtime };
|
||||
// Plan 3j Task 3: `declaredProfiles` now takes `PluginsRepository`, not the raw
|
||||
// connection — `findCapabilities` reads the same `capabilitiesRow` fixture the
|
||||
// old `connection.prepare(...).get()` stub above read.
|
||||
const plugins = {
|
||||
findCapabilities: vi.fn(async () => (capabilitiesRow.value === undefined ? null : capabilitiesRow.value)),
|
||||
} as unknown as PluginsRepository;
|
||||
return { c: new PluginRoutesController(runtime, { findAccessible: canAccessTrip } as unknown as TripsRepository, plugins), runtime };
|
||||
}
|
||||
const wp = (n = 3) => Array.from({ length: n }, (_, i) => ({ lat: 48 + i * 0.1, lng: 2 + i * 0.1 }));
|
||||
const goodRoute = (n = 3, over: Record<string, unknown> = {}) => ({
|
||||
@@ -45,7 +51,7 @@ const body = (over: Record<string, unknown> = {}) => ({ tripId: 1, dayId: 7, way
|
||||
describe('PluginRoutesController', () => {
|
||||
beforeEach(() => {
|
||||
pluginsEnabled.mockReturnValue(true);
|
||||
canAccessTrip.mockReturnValue({ id: 1 } as never);
|
||||
canAccessTrip.mockResolvedValue({ id: 1 } as never);
|
||||
capabilitiesRow.value = JSON.stringify({ routeProfiles: [{ id: 'ev', label: 'EV' }] });
|
||||
});
|
||||
|
||||
@@ -57,9 +63,9 @@ describe('PluginRoutesController', () => {
|
||||
pluginsEnabled.mockReturnValue(true);
|
||||
|
||||
expect((await controller(() => goodRoute()).c.route('ev-plug', 'ev', body(), req(undefined))).route).toBeNull();
|
||||
canAccessTrip.mockReturnValue(undefined as never);
|
||||
canAccessTrip.mockResolvedValue(undefined as never);
|
||||
expect((await controller(() => goodRoute()).c.route('ev-plug', 'ev', body(), req(5))).route).toBeNull();
|
||||
canAccessTrip.mockReturnValue({ id: 1 } as never);
|
||||
canAccessTrip.mockResolvedValue({ id: 1 } as never);
|
||||
expect((await controller(() => goodRoute()).c.route('ev-plug', '../etc', body(), req(5))).route).toBeNull();
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
/**
|
||||
* task-6-rereview2.md I-A: `PluginRuntimeService.onApplicationBootstrap`'s
|
||||
* absent-ORM branch (`plugin-runtime.service.ts:~296-300`) was dead
|
||||
* suite-wide — every existing construction of the service that reaches
|
||||
* `onApplicationBootstrap` (boot-registry-order.test.ts, plugin-host.ts) hands
|
||||
* it a real MikroORM. That branch is the half of the boot RULING
|
||||
* (task-6-rereview.md §2) that makes "skip loudly, never abort app.init()"
|
||||
* defensible: dropping the `logError` call, or falling through to `activate`
|
||||
* anyway, would ship green with no test failing. This file pins it directly.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeAll, afterAll, beforeEach } from 'vitest';
|
||||
|
||||
const logMock = vi.hoisted(() => ({ LOG_LEVEL: 'error', logInfo: vi.fn(), logError: vi.fn(), logWarn: vi.fn(), logDebug: vi.fn() }));
|
||||
vi.mock('../../../src/nest/audit/audit-log.logger', () => logMock);
|
||||
|
||||
import { PluginRuntimeService } from '../../../src/nest/plugins/plugin-runtime.service';
|
||||
import { UnitOfWork } from '../../../src/nest/database/unit-of-work';
|
||||
import { AuditService } from '../../../src/nest/audit/audit.service';
|
||||
import { PluginUserSettingsService } from '../../../src/nest/plugins/plugin-user-settings.service';
|
||||
import { createTestAddonsService } from '../../helpers/test-addons';
|
||||
import { createSnapshotTestDb } from '../../helpers/db-mock';
|
||||
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
|
||||
import { AuditLog } from '../../../src/db/entities/AuditLog.entity';
|
||||
import { Users } from '../../../src/db/entities/Users.entity';
|
||||
import { Plugins } from '../../../src/db/entities/Plugins.entity';
|
||||
import { PluginErrorLog } from '../../../src/db/entities/PluginErrorLog.entity';
|
||||
import { PluginScheduledTasks } from '../../../src/db/entities/PluginScheduledTasks.entity';
|
||||
import { PluginUserErasureQueue } from '../../../src/db/entities/PluginUserErasureQueue.entity';
|
||||
import { PluginEgressHosts } from '../../../src/db/entities/PluginEgressHosts.entity';
|
||||
import { PluginSettingsFields } from '../../../src/db/entities/PluginSettingsFields.entity';
|
||||
import { PluginActions } from '../../../src/db/entities/PluginActions.entity';
|
||||
import { PluginUserConfig } from '../../../src/db/entities/PluginUserConfig.entity';
|
||||
import { PluginEntityMetadata } from '../../../src/db/entities/PluginEntityMetadata.entity';
|
||||
import { PluginOauthTokens } from '../../../src/db/entities/PluginOauthTokens.entity';
|
||||
import { PluginOauthState } from '../../../src/db/entities/PluginOauthState.entity';
|
||||
import { PluginMetaMigrations } from '../../../src/db/entities/PluginMetaMigrations.entity';
|
||||
import { PluginCapabilityAudit } from '../../../src/db/entities/PluginCapabilityAudit.entity';
|
||||
import { Settings } from '../../../src/db/entities/Settings.entity';
|
||||
import { NotificationChannelPreferences } from '../../../src/db/entities/NotificationChannelPreferences.entity';
|
||||
|
||||
const testDb = createSnapshotTestDb();
|
||||
let t: TestOrm;
|
||||
|
||||
beforeAll(async () => {
|
||||
// Global context disallowed — the production setting — so the WITH-orm
|
||||
// sibling case genuinely proves activation runs through a request context,
|
||||
// the same reasoning airports.service.test.ts and BOOT-REG-002 use.
|
||||
t = await createTestOrm(testDb, { allowGlobalContext: false });
|
||||
});
|
||||
afterAll(async () => { await t.close(); testDb.close(); });
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
/** installedDepRows() reads the `plugins` table directly — no discovery needed. */
|
||||
function installEnabledPlugin(id: string): void {
|
||||
testDb
|
||||
.prepare(
|
||||
`INSERT INTO plugins (id, name, status, enabled, version, api_version, permissions, granted_permissions, capabilities, config, dependencies)
|
||||
VALUES (?, ?, 'inactive', 1, '1.0.0', 1, '[]', '[]', '{}', '{}', '{}')`,
|
||||
)
|
||||
.run(id, id);
|
||||
}
|
||||
|
||||
async function buildRuntime(withOrm: boolean): Promise<PluginRuntimeService> {
|
||||
const audit = new AuditService(t.repo(AuditLog), t.repo(Users));
|
||||
const addons = await createTestAddonsService(testDb);
|
||||
const userSettings = new PluginUserSettingsService(t.repo(PluginSettingsFields), t.repo(PluginUserConfig));
|
||||
return new PluginRuntimeService(
|
||||
audit,
|
||||
addons,
|
||||
userSettings,
|
||||
t.repo(Plugins),
|
||||
t.repo(PluginErrorLog),
|
||||
t.repo(PluginScheduledTasks),
|
||||
t.repo(PluginUserErasureQueue),
|
||||
t.repo(PluginEgressHosts),
|
||||
t.repo(PluginSettingsFields),
|
||||
t.repo(PluginActions),
|
||||
t.repo(PluginUserConfig),
|
||||
t.repo(PluginEntityMetadata),
|
||||
t.repo(PluginOauthTokens),
|
||||
t.repo(PluginOauthState),
|
||||
t.repo(PluginMetaMigrations),
|
||||
t.repo(PluginCapabilityAudit),
|
||||
t.repo(Settings),
|
||||
t.repo(NotificationChannelPreferences),
|
||||
// Plan 4 Task 4: `uow` is no longer `@Optional()` — ordered ahead of
|
||||
// `registry?`/`hostFactory?`, matching the real constructor's own order.
|
||||
new UnitOfWork(t.em),
|
||||
undefined,
|
||||
undefined,
|
||||
withOrm ? t.orm : undefined,
|
||||
);
|
||||
}
|
||||
|
||||
describe('PluginRuntimeService.onApplicationBootstrap — absent-ORM boot branch (task-6-rereview2.md I-A)', () => {
|
||||
it('RT-BOOT-NOORM-001: without an ORM, boot logs the skip line and never calls activate', async () => {
|
||||
installEnabledPlugin('rtboot-noorm');
|
||||
const rt = await buildRuntime(false);
|
||||
const activateSpy = vi.spyOn(rt, 'activate');
|
||||
|
||||
await rt.onApplicationBootstrap();
|
||||
|
||||
// Plan 3j Task 2 (deviation, task-2-report.md): `installedDepRows` is now a
|
||||
// repository read that needs a request context this branch cannot provide, so
|
||||
// it is skipped rather than attempted unwrapped — the log line can no longer
|
||||
// name which plugin(s) it skipped, only that it skipped activation entirely.
|
||||
// Still fail-closed (never throws out of onApplicationBootstrap, never abandons
|
||||
// app.init()), still logged exactly once, still never calls activate.
|
||||
expect(logMock.logError).toHaveBeenCalledTimes(1);
|
||||
const [message] = logMock.logError.mock.calls[0] as [string];
|
||||
expect(message).toMatch(/PluginRuntimeService\.onApplicationBootstrap: no MikroORM available/);
|
||||
expect(activateSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('RT-BOOT-NOORM-002: WITH an ORM, the same arrangement activates the plugin — proves case 001 is not vacuous', async () => {
|
||||
installEnabledPlugin('rtboot-withorm');
|
||||
const rt = await buildRuntime(true);
|
||||
const activateSpy = vi.spyOn(rt, 'activate').mockResolvedValue(undefined);
|
||||
|
||||
await rt.onApplicationBootstrap();
|
||||
|
||||
expect(activateSpy).toHaveBeenCalledWith('rtboot-withorm');
|
||||
expect(logMock.logError).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -10,55 +10,55 @@ const { pluginsEnabled, getMock } = vi.hoisted(() => ({
|
||||
getMock: vi.fn(() => ({ 1: 1 })), // active by default
|
||||
}));
|
||||
vi.mock('../../../src/nest/plugins/kill-switch', () => ({ pluginsEnabled }));
|
||||
vi.mock('../../../src/db/database', () => ({ db: { prepare: () => ({ get: getMock }) } }));
|
||||
import { db as dbConn } from '../../../src/db/database';
|
||||
import { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
|
||||
import { PluginUserSettingsController } from '../../../src/nest/plugins/plugin-user-settings.controller';
|
||||
import type { PluginRuntimeService } from '../../../src/nest/plugins/plugin-runtime.service';
|
||||
import type { PluginsService } from '../../../src/nest/plugins/plugins.service';
|
||||
import type { PluginsRepository } from '../../../src/db/repositories/Plugins.repository';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const req = (id?: number) => ({ user: id === undefined ? undefined : { id } }) as any;
|
||||
function ctrl() {
|
||||
const svc = {
|
||||
userSettingsFields: vi.fn(() => [{ key: 'apiKey', secret: true }]),
|
||||
getUserConfig: vi.fn(() => ({ apiKey: '••••••••' })),
|
||||
updateUserConfig: vi.fn((_id: string, _uid: number, patch: Record<string, unknown>) => ({ ...patch, apiKey: '••••••••' })),
|
||||
userSettingsFields: vi.fn(async () => [{ key: 'apiKey', secret: true }]),
|
||||
getUserConfig: vi.fn(async () => ({ apiKey: '••••••••' })),
|
||||
updateUserConfig: vi.fn(async (_id: string, _uid: number, patch: Record<string, unknown>) => ({ ...patch, apiKey: '••••••••' })),
|
||||
} as unknown as PluginsService;
|
||||
// The controller now also takes the runtime (for settings-page actions).
|
||||
const runtime = { actionsOf: vi.fn(() => []), invokeAction: vi.fn(async () => ({ ok: true })) } as unknown as PluginRuntimeService;
|
||||
return { c: new PluginUserSettingsController(svc, runtime, new DatabaseService(dbConn)), svc, runtime };
|
||||
const runtime = { actionsOf: vi.fn(async () => []), invokeAction: vi.fn(async () => ({ ok: true })) } as unknown as PluginRuntimeService;
|
||||
// PUC1 (Plan 3j Task 5) — the active-plugin guard is now Plugins.repository.ts#existsActive.
|
||||
const plugins = { existsActive: vi.fn(async () => !!getMock()) } as unknown as PluginsRepository;
|
||||
return { c: new PluginUserSettingsController(svc, runtime, plugins), svc, runtime };
|
||||
}
|
||||
|
||||
describe('PluginUserSettingsController', () => {
|
||||
beforeEach(() => { pluginsEnabled.mockReturnValue(true); getMock.mockReturnValue({ 1: 1 }); });
|
||||
|
||||
it('GET returns fields + masked config for a bound user; empty when gated', () => {
|
||||
it('GET returns fields + masked config for a bound user; empty when gated', async () => {
|
||||
const { c } = ctrl();
|
||||
expect(c.get('p', req(5))).toEqual({ fields: [{ key: 'apiKey', secret: true }], config: { apiKey: '••••••••' }, actions: [] });
|
||||
expect(await c.get('p', req(5))).toEqual({ fields: [{ key: 'apiKey', secret: true }], config: { apiKey: '••••••••' }, actions: [] });
|
||||
pluginsEnabled.mockReturnValue(false);
|
||||
expect(c.get('p', req(5))).toEqual({ fields: [], config: {}, actions: [] });
|
||||
expect(await c.get('p', req(5))).toEqual({ fields: [], config: {}, actions: [] });
|
||||
pluginsEnabled.mockReturnValue(true);
|
||||
expect(c.get('p', req(undefined))).toEqual({ fields: [], config: {}, actions: [] });
|
||||
expect(await c.get('p', req(undefined))).toEqual({ fields: [], config: {}, actions: [] });
|
||||
getMock.mockReturnValue(undefined as never);
|
||||
expect(c.get('p', req(5))).toEqual({ fields: [], config: {}, actions: [] });
|
||||
expect(await c.get('p', req(5))).toEqual({ fields: [], config: {}, actions: [] });
|
||||
});
|
||||
|
||||
it('POST delegates the patch for a bound user; empty when gated', () => {
|
||||
it('POST delegates the patch for a bound user; empty when gated', async () => {
|
||||
const { c, svc } = ctrl();
|
||||
expect(c.update('p', { config: { units: 'metric' } }, req(5))).toEqual({ config: { units: 'metric', apiKey: '••••••••' } });
|
||||
expect(await c.update('p', { config: { units: 'metric' } }, req(5))).toEqual({ config: { units: 'metric', apiKey: '••••••••' } });
|
||||
expect(svc.updateUserConfig).toHaveBeenCalledWith('p', 5, { units: 'metric' });
|
||||
// a non-object body → empty patch (no throw)
|
||||
c.update('p', {}, req(5));
|
||||
await c.update('p', {}, req(5));
|
||||
expect(svc.updateUserConfig).toHaveBeenCalledWith('p', 5, {});
|
||||
getMock.mockReturnValue(undefined as never);
|
||||
expect(c.update('p', { config: { units: 'metric' } }, req(5))).toEqual({ config: {} });
|
||||
expect(await c.update('p', { config: { units: 'metric' } }, req(5))).toEqual({ config: {} });
|
||||
});
|
||||
|
||||
it('GET lists USER-scope actions only, and POST runs one as the caller in the user scope', async () => {
|
||||
const { c, runtime } = ctrl();
|
||||
c.get('p', req(5));
|
||||
await c.get('p', req(5));
|
||||
expect(runtime.actionsOf).toHaveBeenCalledWith('p', 'user');
|
||||
expect(await c.runAction('p', 'sync', req(5))).toEqual({ ok: true });
|
||||
expect(runtime.invokeAction).toHaveBeenCalledWith('p', 'sync', 5, 'user');
|
||||
|
||||
@@ -15,22 +15,47 @@ vi.mock('../../../src/nest/common/crypto/apiKeyCrypto', () => ({
|
||||
|
||||
const { getDb } = vi.hoisted(() => ({ getDb: { current: null as unknown } }));
|
||||
vi.mock('../../../src/db/database', () => ({ get db() { return getDb.current; } }));
|
||||
import { db as dbConn } from '../../../src/db/database';
|
||||
import { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
import { AddonsService } from '../../../src/nest/addons/addons.service';
|
||||
import { createTestAddonsService } from '../../helpers/test-addons';
|
||||
import { createSnapshotTestDb } from '../../helpers/db-mock';
|
||||
|
||||
import Database from 'better-sqlite3';
|
||||
import { PluginsService } from '../../../src/nest/plugins/plugins.service';
|
||||
import { PluginUserSettingsService } from '../../../src/nest/plugins/plugin-user-settings.service';
|
||||
/** The host-side settings reads, over the same connection the test seeded. */
|
||||
const userSettings = () => new PluginUserSettingsService(new DatabaseService(dbConn));
|
||||
import { sharedTestOrm } from '../../helpers/test-uow';
|
||||
import { Plugins } from '../../../src/db/entities/Plugins.entity';
|
||||
import { PluginErrorLog } from '../../../src/db/entities/PluginErrorLog.entity';
|
||||
import { PluginEgressHosts } from '../../../src/db/entities/PluginEgressHosts.entity';
|
||||
import { PluginSettingsFields } from '../../../src/db/entities/PluginSettingsFields.entity';
|
||||
import { PluginActions } from '../../../src/db/entities/PluginActions.entity';
|
||||
import { PluginUserConfig } from '../../../src/db/entities/PluginUserConfig.entity';
|
||||
import { PluginCapabilityAudit } from '../../../src/db/entities/PluginCapabilityAudit.entity';
|
||||
|
||||
/** Plan 3j Task 2 — PluginsService's own six repositories, over whichever fresh `getDb.current` the caller just set. */
|
||||
async function makePluginsService(): Promise<PluginsService> {
|
||||
const orm = await sharedTestOrm(getDb.current as Database.Database);
|
||||
return new PluginsService(
|
||||
await createTestAddonsService(getDb.current as Database.Database),
|
||||
orm.repo(Plugins),
|
||||
orm.repo(PluginEgressHosts),
|
||||
orm.repo(PluginSettingsFields),
|
||||
orm.repo(PluginActions),
|
||||
orm.repo(PluginUserConfig),
|
||||
orm.repo(PluginErrorLog),
|
||||
orm.repo(PluginCapabilityAudit),
|
||||
);
|
||||
}
|
||||
/**
|
||||
* The host-side settings reads, over the same connection the test seeded — a fresh
|
||||
* `orm` per test (`sharedTestOrm` is memoized per db HANDLE, and `beforeEach` swaps
|
||||
* `getDb.current` to a brand-new `:memory:` db every time, same as `makePluginsService`).
|
||||
*/
|
||||
async function userSettings(): Promise<PluginUserSettingsService> {
|
||||
const orm = await sharedTestOrm(getDb.current as Database.Database);
|
||||
return new PluginUserSettingsService(orm.repo(PluginSettingsFields), orm.repo(PluginUserConfig));
|
||||
}
|
||||
|
||||
function freshDb() {
|
||||
const d = new Database(':memory:');
|
||||
d.exec(`
|
||||
CREATE TABLE plugin_settings_fields (id INTEGER PRIMARY KEY AUTOINCREMENT, plugin_id TEXT, field_key TEXT, label TEXT, input_type TEXT, placeholder TEXT, hint TEXT, required INTEGER, secret INTEGER, scope TEXT, options TEXT, default_value TEXT, sort_order INTEGER);
|
||||
CREATE TABLE plugin_user_config (plugin_id TEXT, user_id INTEGER, config TEXT, updated_at TEXT, PRIMARY KEY (plugin_id, user_id));
|
||||
`);
|
||||
const d = createSnapshotTestDb();
|
||||
// p: a user-scope api key (secret) + a user-scope pref (not secret) + an INSTANCE field.
|
||||
const ins = d.prepare('INSERT INTO plugin_settings_fields (plugin_id, field_key, input_type, required, secret, scope, sort_order) VALUES (?,?,?,?,?,?,?)');
|
||||
ins.run('p', 'apiKey', 'text', 1, 1, 'user', 0);
|
||||
@@ -43,50 +68,49 @@ describe('per-user plugin settings', () => {
|
||||
let svc: PluginsService;
|
||||
// AddonsService only feeds PluginsService.list(), which no case here calls, but it is a
|
||||
// real collaborator on the same connection rather than a stand-in.
|
||||
beforeEach(() => {
|
||||
beforeEach(async () => {
|
||||
getDb.current = freshDb();
|
||||
const dbs = new DatabaseService(dbConn);
|
||||
svc = new PluginsService(dbs, new AddonsService(dbs));
|
||||
svc = await makePluginsService();
|
||||
});
|
||||
|
||||
it('lists only the user-scope fields, in order', () => {
|
||||
const fields = svc.userSettingsFields('p');
|
||||
it('lists only the user-scope fields, in order', async () => {
|
||||
const fields = await svc.userSettingsFields('p');
|
||||
expect(fields.map(f => f.key)).toEqual(['apiKey', 'units']); // not the instance field
|
||||
expect(fields[0]).toMatchObject({ secret: true, required: true });
|
||||
});
|
||||
|
||||
it('encrypts a secret at rest, masks it to the client, stores a plain field verbatim', () => {
|
||||
const masked = svc.updateUserConfig('p', 42, { apiKey: 'sk-123', units: 'metric' });
|
||||
it('encrypts a secret at rest, masks it to the client, stores a plain field verbatim', async () => {
|
||||
const masked = await svc.updateUserConfig('p', 42, { apiKey: 'sk-123', units: 'metric' });
|
||||
expect(masked.apiKey).toBe('••••••••'); // never echoed
|
||||
expect(masked.units).toBe('metric');
|
||||
// decrypted runtime read returns the real value; the stored form is ciphertext
|
||||
expect(userSettings().readOne('p', 42, 'apiKey')).toBe('sk-123');
|
||||
expect(svc.getUserConfig('p', 42).apiKey).toBe('••••••••');
|
||||
expect(await (await userSettings()).readOne('p', 42, 'apiKey')).toBe('sk-123');
|
||||
expect((await svc.getUserConfig('p', 42)).apiKey).toBe('••••••••');
|
||||
});
|
||||
|
||||
it('an unchanged secret (the mask) keeps the stored ciphertext', () => {
|
||||
svc.updateUserConfig('p', 42, { apiKey: 'sk-123' });
|
||||
svc.updateUserConfig('p', 42, { apiKey: '••••••••', units: 'imperial' }); // mask = untouched
|
||||
expect(userSettings().readOne('p', 42, 'apiKey')).toBe('sk-123'); // still the original
|
||||
expect(svc.getUserConfig('p', 42).units).toBe('imperial');
|
||||
it('an unchanged secret (the mask) keeps the stored ciphertext', async () => {
|
||||
await svc.updateUserConfig('p', 42, { apiKey: 'sk-123' });
|
||||
await svc.updateUserConfig('p', 42, { apiKey: '••••••••', units: 'imperial' }); // mask = untouched
|
||||
expect(await (await userSettings()).readOne('p', 42, 'apiKey')).toBe('sk-123'); // still the original
|
||||
expect((await svc.getUserConfig('p', 42)).units).toBe('imperial');
|
||||
});
|
||||
|
||||
it('ignores keys that are not declared user-scope fields', () => {
|
||||
it('ignores keys that are not declared user-scope fields', async () => {
|
||||
// apiKey is required — filled here so the save isn't refused; the assertion is
|
||||
// about adminOnly/bogus being dropped, not about required enforcement.
|
||||
svc.updateUserConfig('p', 42, { apiKey: 'sk-123', adminOnly: 'nope', bogus: 'x', units: 'metric' } as Record<string, unknown>);
|
||||
const cfg = svc.getUserConfig('p', 42);
|
||||
await svc.updateUserConfig('p', 42, { apiKey: 'sk-123', adminOnly: 'nope', bogus: 'x', units: 'metric' } as Record<string, unknown>);
|
||||
const cfg = await svc.getUserConfig('p', 42);
|
||||
expect(cfg.adminOnly).toBeUndefined(); // instance field — not accepted here
|
||||
expect(cfg.bogus).toBeUndefined();
|
||||
expect(cfg.units).toBe('metric');
|
||||
});
|
||||
|
||||
it('is per-user — one user cannot see another\'s value', () => {
|
||||
it('is per-user — one user cannot see another\'s value', async () => {
|
||||
// apiKey is required — filled here so the save isn't refused; the point of this
|
||||
// test is that user 99 sees none of user 42's values.
|
||||
svc.updateUserConfig('p', 42, { apiKey: 'sk-123', units: 'metric' });
|
||||
expect(svc.getUserConfig('p', 99).units).toBeUndefined();
|
||||
expect(userSettings().readOne('p', 99, 'apiKey')).toBeUndefined();
|
||||
await svc.updateUserConfig('p', 42, { apiKey: 'sk-123', units: 'metric' });
|
||||
expect((await svc.getUserConfig('p', 99)).units).toBeUndefined();
|
||||
expect(await (await userSettings()).readOne('p', 99, 'apiKey')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -95,10 +119,9 @@ describe('manifest defaults reach the runtime reads', () => {
|
||||
// through ctx.settings.get() / the channel dispatch's readAll — otherwise a plugin
|
||||
// that ships a sensible default serves nobody until every user opens the form.
|
||||
let svc: PluginsService;
|
||||
beforeEach(() => {
|
||||
beforeEach(async () => {
|
||||
getDb.current = freshDb();
|
||||
const dbs = new DatabaseService(dbConn);
|
||||
svc = new PluginsService(dbs, new AddonsService(dbs));
|
||||
svc = await makePluginsService();
|
||||
const ins = (getDb.current as import('better-sqlite3').Database).prepare(
|
||||
'INSERT INTO plugin_settings_fields (plugin_id, field_key, input_type, required, secret, scope, sort_order, default_value) VALUES (?,?,?,?,?,?,?,?)',
|
||||
);
|
||||
@@ -107,29 +130,29 @@ describe('manifest defaults reach the runtime reads', () => {
|
||||
ins.run('p', 'endpoint', 'text', 1, 0, 'user', 5, JSON.stringify('https://api.example'));
|
||||
});
|
||||
|
||||
it('readOne falls back to the declared default when nothing is stored', () => {
|
||||
expect(userSettings().readOne('p', 42, 'region')).toBe('eu');
|
||||
expect(userSettings().readOne('p', 42, 'retries')).toBe(3); // JSON round-trip keeps the type
|
||||
expect(userSettings().readOne('p', 42, 'apiKey')).toBeUndefined(); // no default declared
|
||||
it('readOne falls back to the declared default when nothing is stored', async () => {
|
||||
expect(await (await userSettings()).readOne('p', 42, 'region')).toBe('eu');
|
||||
expect(await (await userSettings()).readOne('p', 42, 'retries')).toBe(3); // JSON round-trip keeps the type
|
||||
expect(await (await userSettings()).readOne('p', 42, 'apiKey')).toBeUndefined(); // no default declared
|
||||
});
|
||||
|
||||
it('a stored value wins over the default', () => {
|
||||
svc.updateUserConfig('p', 42, { apiKey: 'sk-123', region: 'us' });
|
||||
expect(userSettings().readOne('p', 42, 'region')).toBe('us');
|
||||
expect(userSettings().readOne('p', 99, 'region')).toBe('eu'); // another user still gets the default
|
||||
it('a stored value wins over the default', async () => {
|
||||
await svc.updateUserConfig('p', 42, { apiKey: 'sk-123', region: 'us' });
|
||||
expect(await (await userSettings()).readOne('p', 42, 'region')).toBe('us');
|
||||
expect(await (await userSettings()).readOne('p', 99, 'region')).toBe('eu'); // another user still gets the default
|
||||
});
|
||||
|
||||
it('readAll folds defaults in for the fields the user left unset', () => {
|
||||
svc.updateUserConfig('p', 42, { apiKey: 'sk-123', region: 'us' });
|
||||
expect(userSettings().readAll('p', 42)).toMatchObject({ apiKey: 'sk-123', region: 'us', retries: 3, endpoint: 'https://api.example' });
|
||||
it('readAll folds defaults in for the fields the user left unset', async () => {
|
||||
await svc.updateUserConfig('p', 42, { apiKey: 'sk-123', region: 'us' });
|
||||
expect(await (await userSettings()).readAll('p', 42)).toMatchObject({ apiKey: 'sk-123', region: 'us', retries: 3, endpoint: 'https://api.example' });
|
||||
});
|
||||
|
||||
it('hasRequired treats a required field with a default as filled', () => {
|
||||
it('hasRequired treats a required field with a default as filled', async () => {
|
||||
// apiKey is required with no default → not configured until stored.
|
||||
expect(userSettings().hasRequired('p', 42)).toBe(false);
|
||||
svc.updateUserConfig('p', 42, { apiKey: 'sk-123' });
|
||||
expect(await (await userSettings()).hasRequired('p', 42)).toBe(false);
|
||||
await svc.updateUserConfig('p', 42, { apiKey: 'sk-123' });
|
||||
// endpoint is required too, but its default satisfies it.
|
||||
expect(userSettings().hasRequired('p', 42)).toBe(true);
|
||||
expect(await (await userSettings()).hasRequired('p', 42)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -138,24 +161,23 @@ describe('hasRequired applies the same "filled" rule as the save gate', () => {
|
||||
// it disagreed with assertRequiredFilled() a save the form accepted could still leave
|
||||
// the user "not configured" (or the reverse).
|
||||
let svc: PluginsService;
|
||||
beforeEach(() => {
|
||||
beforeEach(async () => {
|
||||
getDb.current = freshDb();
|
||||
const dbs = new DatabaseService(dbConn);
|
||||
svc = new PluginsService(dbs, new AddonsService(dbs));
|
||||
svc = await makePluginsService();
|
||||
(getDb.current as import('better-sqlite3').Database)
|
||||
.prepare('INSERT INTO plugin_settings_fields (plugin_id, field_key, input_type, required, secret, scope, sort_order) VALUES (?,?,?,?,?,?,?)')
|
||||
.run('p', 'consent', 'checkbox', 1, 0, 'user', 9);
|
||||
});
|
||||
|
||||
it('exempts a required checkbox (consent, not a settings field)', () => {
|
||||
svc.updateUserConfig('p', 42, { apiKey: 'sk-123' }); // consent never set
|
||||
expect(userSettings().hasRequired('p', 42)).toBe(true);
|
||||
it('exempts a required checkbox (consent, not a settings field)', async () => {
|
||||
await svc.updateUserConfig('p', 42, { apiKey: 'sk-123' }); // consent never set
|
||||
expect(await (await userSettings()).hasRequired('p', 42)).toBe(true);
|
||||
});
|
||||
|
||||
it('treats a whitespace-only value as empty', () => {
|
||||
it('treats a whitespace-only value as empty', async () => {
|
||||
(getDb.current as import('better-sqlite3').Database)
|
||||
.prepare("INSERT INTO plugin_user_config (plugin_id, user_id, config, updated_at) VALUES ('p', 42, ?, '')")
|
||||
.run(JSON.stringify({ apiKey: ' ', consent: true }));
|
||||
expect(userSettings().hasRequired('p', 42)).toBe(false);
|
||||
expect(await (await userSettings()).hasRequired('p', 42)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -12,12 +12,10 @@ const { rows, pluginsEnabled } = vi.hoisted(() => ({
|
||||
rows: { value: [] as Array<Record<string, unknown>> },
|
||||
pluginsEnabled: vi.fn(() => true),
|
||||
}));
|
||||
vi.mock('../../../src/db/database', () => ({ db: { prepare: () => ({ all: () => rows.value }) } }));
|
||||
import { db as dbConn } from '../../../src/db/database';
|
||||
import { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
vi.mock('../../../src/nest/plugins/kill-switch', () => ({ pluginsEnabled }));
|
||||
|
||||
import { PluginsFeedController } from '../../../src/nest/plugins/plugins-feed.controller';
|
||||
import type { PluginsRepository } from '../../../src/db/repositories/Plugins.repository';
|
||||
|
||||
const row = (over: Record<string, unknown> = {}) => ({
|
||||
id: 'p1', name: 'P', type: 'integration', icon: null,
|
||||
@@ -26,38 +24,40 @@ const row = (over: Record<string, unknown> = {}) => ({
|
||||
});
|
||||
|
||||
describe('PluginsFeedController', () => {
|
||||
const c = new PluginsFeedController(new DatabaseService(dbConn));
|
||||
// PFC1 (Plan 3j Task 5) — the feed read is now Plugins.repository.ts#findActiveFeedRows.
|
||||
const plugins = { findActiveFeedRows: vi.fn(async () => rows.value) } as unknown as PluginsRepository;
|
||||
const c = new PluginsFeedController(plugins);
|
||||
beforeEach(() => { pluginsEnabled.mockReturnValue(true); rows.value = []; });
|
||||
|
||||
it('marks a plugin as a search provider only alongside the recorded hook:search-provider grant (#2221)', () => {
|
||||
it('marks a plugin as a search provider only alongside the recorded hook:search-provider grant (#2221)', async () => {
|
||||
rows.value = [
|
||||
row({ id: 'index', granted_permissions: JSON.stringify(['hook:search-provider']) }),
|
||||
row({ id: 'asked-only', permissions: JSON.stringify(['hook:search-provider']) }),
|
||||
row({ id: 'poi-only', granted_permissions: JSON.stringify(['hook:poi-category-provider']) }),
|
||||
];
|
||||
const { plugins } = c.list();
|
||||
const { plugins } = await c.list();
|
||||
expect(plugins.find(p => p.id === 'index')?.searchProvider).toBe(true);
|
||||
expect(plugins.find(p => p.id === 'asked-only')).not.toHaveProperty('searchProvider');
|
||||
expect(plugins.find(p => p.id === 'poi-only')).not.toHaveProperty('searchProvider');
|
||||
});
|
||||
|
||||
it('returns an empty feed when the runtime is disabled', () => {
|
||||
it('returns an empty feed when the runtime is disabled', async () => {
|
||||
pluginsEnabled.mockReturnValue(false);
|
||||
rows.value = [row()];
|
||||
expect(c.list()).toEqual({ plugins: [] });
|
||||
expect(await c.list()).toEqual({ plugins: [] });
|
||||
});
|
||||
|
||||
it('serves routeProfiles only alongside the recorded hook:route-provider grant', () => {
|
||||
it('serves routeProfiles only alongside the recorded hook:route-provider grant', async () => {
|
||||
rows.value = [
|
||||
row({ id: 'granted', capabilities: JSON.stringify({ routeProfiles: [{ id: 'ev', label: 'EV' }] }), granted_permissions: JSON.stringify(['hook:route-provider']) }),
|
||||
row({ id: 'ungranted', capabilities: JSON.stringify({ routeProfiles: [{ id: 'ev', label: 'EV' }] }) }),
|
||||
];
|
||||
const { plugins } = c.list();
|
||||
const { plugins } = await c.list();
|
||||
expect(plugins.find(p => p.id === 'granted')?.routeProfiles).toEqual([{ id: 'ev', label: 'EV' }]);
|
||||
expect(plugins.find(p => p.id === 'ungranted')?.routeProfiles).toBeUndefined();
|
||||
});
|
||||
|
||||
it('re-validates hand-edited routeProfiles rows (bad ids dropped, labels capped, max 3)', () => {
|
||||
it('re-validates hand-edited routeProfiles rows (bad ids dropped, labels capped, max 3)', async () => {
|
||||
rows.value = [row({
|
||||
id: 'edited',
|
||||
capabilities: JSON.stringify({
|
||||
@@ -69,7 +69,7 @@ describe('PluginsFeedController', () => {
|
||||
}),
|
||||
granted_permissions: JSON.stringify(['hook:route-provider']),
|
||||
})];
|
||||
const profiles = c.list().plugins[0].routeProfiles!;
|
||||
const profiles = (await c.list()).plugins[0].routeProfiles!;
|
||||
expect(profiles.every(p => /^[a-z][a-z0-9-]{0,23}$/.test(p.id))).toBe(true);
|
||||
expect(profiles.length).toBeLessThanOrEqual(3);
|
||||
expect(profiles.every(p => p.label.length <= 40)).toBe(true);
|
||||
@@ -79,19 +79,19 @@ describe('PluginsFeedController', () => {
|
||||
const cat = { id: 'trailheads', label: 'Trailheads', labels: { de: 'Wanderparkplätze' }, icon: 'Signpost', color: '#2f855a' };
|
||||
const granted = JSON.stringify(['hook:poi-category-provider']);
|
||||
|
||||
it('serves them only alongside the recorded hook:poi-category-provider grant', () => {
|
||||
it('serves them only alongside the recorded hook:poi-category-provider grant', async () => {
|
||||
rows.value = [
|
||||
row({ id: 'granted', capabilities: JSON.stringify({ poiCategories: [cat] }), granted_permissions: granted }),
|
||||
row({ id: 'ungranted', capabilities: JSON.stringify({ poiCategories: [cat] }) }),
|
||||
row({ id: 'searchOnly', capabilities: JSON.stringify({ poiCategories: [cat] }), granted_permissions: JSON.stringify(['hook:search-provider']) }),
|
||||
];
|
||||
const { plugins } = c.list();
|
||||
const { plugins } = await c.list();
|
||||
expect(plugins.find(p => p.id === 'granted')?.poiCategories).toEqual([cat]);
|
||||
expect(plugins.find(p => p.id === 'ungranted')?.poiCategories).toBeUndefined();
|
||||
expect(plugins.find(p => p.id === 'searchOnly')?.poiCategories).toBeUndefined();
|
||||
});
|
||||
|
||||
it('re-validates a hand-edited row: bad colour, icon or id dropped, duplicates and the fifth one gone', () => {
|
||||
it('re-validates a hand-edited row: bad colour, icon or id dropped, duplicates and the fifth one gone', async () => {
|
||||
rows.value = [row({
|
||||
capabilities: JSON.stringify({
|
||||
poiCategories: [
|
||||
@@ -106,28 +106,28 @@ describe('PluginsFeedController', () => {
|
||||
granted_permissions: granted,
|
||||
})];
|
||||
// The first four entries are the ones read (the cap), and only one of them survives.
|
||||
expect(c.list().plugins[0].poiCategories).toEqual([{ ...cat, id: 'ok', label: 'Water' }]);
|
||||
expect((await c.list()).plugins[0].poiCategories).toEqual([{ ...cat, id: 'ok', label: 'Water' }]);
|
||||
});
|
||||
|
||||
it('omits the field when nothing survives', () => {
|
||||
it('omits the field when nothing survives', async () => {
|
||||
rows.value = [row({ capabilities: JSON.stringify({ poiCategories: [{ ...cat, color: 'red' }] }), granted_permissions: granted })];
|
||||
expect(c.list().plugins[0]).not.toHaveProperty('poiCategories');
|
||||
expect((await c.list()).plugins[0]).not.toHaveProperty('poiCategories');
|
||||
});
|
||||
});
|
||||
|
||||
it('flags geolocation only when the grant is recorded', () => {
|
||||
it('flags geolocation only when the grant is recorded', async () => {
|
||||
rows.value = [
|
||||
row({ id: 'granted', granted_permissions: JSON.stringify(['geolocation:read']) }),
|
||||
row({ id: 'ungranted' }),
|
||||
];
|
||||
const { plugins } = c.list();
|
||||
const { plugins } = await c.list();
|
||||
expect(plugins.find(p => p.id === 'granted')?.geolocation).toBe(true);
|
||||
expect(plugins.find(p => p.id === 'ungranted')?.geolocation).toBeUndefined();
|
||||
});
|
||||
|
||||
it('survives malformed JSON blobs without dropping the plugin', () => {
|
||||
it('survives malformed JSON blobs without dropping the plugin', async () => {
|
||||
rows.value = [row({ capabilities: '{not json', granted_permissions: 'also not' })];
|
||||
const { plugins } = c.list();
|
||||
const { plugins } = await c.list();
|
||||
expect(plugins).toHaveLength(1);
|
||||
expect(plugins[0].routeProfiles).toBeUndefined();
|
||||
expect(plugins[0].slot).toBe('sidebar');
|
||||
|
||||
@@ -13,9 +13,18 @@ const { pluginsEnabledMock, extractTokenMock, verifyMock } = vi.hoisted(() => ({
|
||||
vi.mock('../../../src/nest/plugins/kill-switch', () => ({ pluginsEnabled: pluginsEnabledMock }));
|
||||
vi.mock('../../../src/nest/auth/jwt-verify', () => ({ extractToken: extractTokenMock, verifyJwtAndLoadUser: verifyMock }));
|
||||
|
||||
import type { EntityManager } from '@mikro-orm/core';
|
||||
import { PluginsProxyController } from '../../../src/nest/plugins/plugins-proxy.controller';
|
||||
import type { PluginRuntimeService } from '../../../src/nest/plugins/plugin-runtime.service';
|
||||
|
||||
// EntityManager injection (Plan 3b Task 1 RULING) — verifyJwtAndLoadUser is
|
||||
// fully mocked above, so `em.getRepository` never needs to return anything
|
||||
// meaningful; it just has to not throw when the controller calls it.
|
||||
const emStub = { getRepository: () => ({}) } as unknown as EntityManager;
|
||||
function ctrl(runtime: PluginRuntimeService): PluginsProxyController {
|
||||
return new PluginsProxyController(runtime, emStub);
|
||||
}
|
||||
|
||||
function fakeRes() {
|
||||
const res = {
|
||||
statusCode: 0,
|
||||
@@ -52,33 +61,33 @@ describe('PluginsProxyController', () => {
|
||||
it('404 when the runtime is disabled', async () => {
|
||||
pluginsEnabledMock.mockReturnValue(false);
|
||||
const res = fakeRes();
|
||||
await new PluginsProxyController(makeRuntime()).proxy('p', fakeReq('GET', '/status'), res as never);
|
||||
await ctrl(makeRuntime()).proxy('p', fakeReq('GET', '/status'), res as never);
|
||||
expect(res.statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it('404 when the plugin is not active', async () => {
|
||||
const res = fakeRes();
|
||||
await new PluginsProxyController(makeRuntime({ isActive: vi.fn(() => false) } as never)).proxy('p', fakeReq('GET', '/status'), res as never);
|
||||
await ctrl(makeRuntime({ isActive: vi.fn(() => false) } as never)).proxy('p', fakeReq('GET', '/status'), res as never);
|
||||
expect(res.statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it('404 when no declared route matches', async () => {
|
||||
const res = fakeRes();
|
||||
await new PluginsProxyController(makeRuntime()).proxy('p', fakeReq('GET', '/nope'), res as never);
|
||||
await ctrl(makeRuntime()).proxy('p', fakeReq('GET', '/nope'), res as never);
|
||||
expect(res.statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it('401 on an auth route without a valid session', async () => {
|
||||
verifyMock.mockReturnValue(null as never);
|
||||
const res = fakeRes();
|
||||
await new PluginsProxyController(makeRuntime()).proxy('p', fakeReq('GET', '/status'), res as never);
|
||||
await ctrl(makeRuntime()).proxy('p', fakeReq('GET', '/status'), res as never);
|
||||
expect(res.statusCode).toBe(401);
|
||||
});
|
||||
|
||||
it('forwards an authenticated request and returns the child response', async () => {
|
||||
const runtime = makeRuntime();
|
||||
const res = fakeRes();
|
||||
await new PluginsProxyController(runtime).proxy('p', fakeReq('GET', '/status'), res as never);
|
||||
await ctrl(runtime).proxy('p', fakeReq('GET', '/status'), res as never);
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.headers['content-type']).toBe('application/json');
|
||||
expect(res.body).toBe('{"ok":true}');
|
||||
@@ -96,7 +105,7 @@ describe('PluginsProxyController', () => {
|
||||
verifyMock.mockReturnValue({ id: 7, username: 'root', role: 'admin' } as never);
|
||||
const runtime = makeRuntime();
|
||||
const res = fakeRes();
|
||||
await new PluginsProxyController(runtime).proxy('p', fakeReq('GET', '/status'), res as never);
|
||||
await ctrl(runtime).proxy('p', fakeReq('GET', '/status'), res as never);
|
||||
expect(runtime.invoke).toHaveBeenCalledWith('p', 'invoke.route', expect.objectContaining({
|
||||
req: expect.objectContaining({ user: { id: 7, username: 'root', isAdmin: true } }),
|
||||
}), 7);
|
||||
@@ -105,7 +114,7 @@ describe('PluginsProxyController', () => {
|
||||
it('a public (auth:false) route skips the session check', async () => {
|
||||
const runtime = makeRuntime({ routesOf: vi.fn(() => [{ i: 1, method: 'POST', path: '/webhook', auth: false }]) } as never);
|
||||
const res = fakeRes();
|
||||
await new PluginsProxyController(runtime).proxy('p', fakeReq('POST', '/webhook'), res as never);
|
||||
await ctrl(runtime).proxy('p', fakeReq('POST', '/webhook'), res as never);
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(extractTokenMock).not.toHaveBeenCalled();
|
||||
// a public route has no session user → no bound acting user (undefined)
|
||||
@@ -117,7 +126,7 @@ describe('PluginsProxyController', () => {
|
||||
it('forwards the raw request bytes to a webhook (auth:false) route, but withholds them from an authenticated route', async () => {
|
||||
// Webhook route → the plugin gets the raw payload so it can verify an HMAC.
|
||||
const wh = makeRuntime({ routesOf: vi.fn(() => [{ i: 1, method: 'POST', path: '/webhook', auth: false }]) } as never);
|
||||
await new PluginsProxyController(wh).proxy('p', fakeReq('POST', '/webhook', { rawBody: Buffer.from('{"a":1}') }), fakeRes() as never);
|
||||
await ctrl(wh).proxy('p', fakeReq('POST', '/webhook', { rawBody: Buffer.from('{"a":1}') }), fakeRes() as never);
|
||||
// forwarded as base64 so a non-UTF-8 signed body survives
|
||||
expect(wh.invoke).toHaveBeenCalledWith('p', 'invoke.route', expect.objectContaining({
|
||||
req: expect.objectContaining({ rawBodyBase64: Buffer.from('{"a":1}').toString('base64') }),
|
||||
@@ -125,7 +134,7 @@ describe('PluginsProxyController', () => {
|
||||
|
||||
// Authenticated route → raw bytes are never handed to the plugin.
|
||||
const auth = makeRuntime();
|
||||
await new PluginsProxyController(auth).proxy('p', fakeReq('GET', '/status', { rawBody: Buffer.from('secret') }), fakeRes() as never);
|
||||
await ctrl(auth).proxy('p', fakeReq('GET', '/status', { rawBody: Buffer.from('secret') }), fakeRes() as never);
|
||||
const fwd = (auth.invoke as unknown as { mock: { calls: unknown[][] } }).mock.calls[0][2] as { req: { rawBodyBase64?: unknown } };
|
||||
expect(fwd.req.rawBodyBase64).toBeUndefined();
|
||||
});
|
||||
@@ -141,7 +150,7 @@ describe('PluginsProxyController', () => {
|
||||
authorization: 'Bearer leak', // must be dropped
|
||||
'x-socket-id': 'sock-1', // must be dropped
|
||||
};
|
||||
await new PluginsProxyController(runtime).proxy('p', fakeReq('POST', '/webhook', { headers }), res as never);
|
||||
await ctrl(runtime).proxy('p', fakeReq('POST', '/webhook', { headers }), res as never);
|
||||
const forwarded = (runtime.invoke as unknown as { mock: { calls: unknown[][] } }).mock.calls[0][2] as { req: { headers: Record<string, string> } };
|
||||
expect(forwarded.req.headers).toEqual({ 'content-type': 'application/json', 'stripe-signature': 't=1,v1=abc', 'x-hub-signature-256': 'sha256=deadbeef' });
|
||||
expect(forwarded.req.headers.cookie).toBeUndefined();
|
||||
@@ -152,7 +161,7 @@ describe('PluginsProxyController', () => {
|
||||
it('an authenticated route gets NO inbound headers (even safe ones)', async () => {
|
||||
const runtime = makeRuntime(); // /status, auth:true
|
||||
const res = fakeRes();
|
||||
await new PluginsProxyController(runtime).proxy('p', fakeReq('GET', '/status', { headers: { 'content-type': 'application/json', 'stripe-signature': 'x' } }), res as never);
|
||||
await ctrl(runtime).proxy('p', fakeReq('GET', '/status', { headers: { 'content-type': 'application/json', 'stripe-signature': 'x' } }), res as never);
|
||||
const forwarded = (runtime.invoke as unknown as { mock: { calls: unknown[][] } }).mock.calls[0][2] as { req: { headers: Record<string, string> } };
|
||||
expect(forwarded.req.headers).toEqual({});
|
||||
});
|
||||
@@ -162,7 +171,7 @@ describe('PluginsProxyController', () => {
|
||||
invoke: vi.fn(async () => ({ status: 200, headers: { 'content-type': 'text/plain', 'set-cookie': 'evil=1' }, body: 'ok' })),
|
||||
} as never);
|
||||
const res = fakeRes();
|
||||
await new PluginsProxyController(runtime).proxy('p', fakeReq('GET', '/status'), res as never);
|
||||
await ctrl(runtime).proxy('p', fakeReq('GET', '/status'), res as never);
|
||||
expect(res.headers['content-type']).toBe('text/plain');
|
||||
expect(res.headers['set-cookie']).toBeUndefined(); // a plugin cannot set cookies
|
||||
});
|
||||
@@ -170,7 +179,7 @@ describe('PluginsProxyController', () => {
|
||||
it('502 when the plugin invoke throws', async () => {
|
||||
const runtime = makeRuntime({ invoke: vi.fn(async () => { throw new Error('down'); }) } as never);
|
||||
const res = fakeRes();
|
||||
await new PluginsProxyController(runtime).proxy('p', fakeReq('GET', '/status'), res as never);
|
||||
await ctrl(runtime).proxy('p', fakeReq('GET', '/status'), res as never);
|
||||
expect(res.statusCode).toBe(502);
|
||||
});
|
||||
|
||||
@@ -179,7 +188,7 @@ describe('PluginsProxyController', () => {
|
||||
invoke: vi.fn(async () => ({ status: 302, headers: { location: '/trips/5?tab=plan' } })),
|
||||
} as never);
|
||||
const res = fakeRes();
|
||||
await new PluginsProxyController(runtime).proxy('p', fakeReq('GET', '/status'), res as never);
|
||||
await ctrl(runtime).proxy('p', fakeReq('GET', '/status'), res as never);
|
||||
expect(res.statusCode).toBe(302);
|
||||
// normalised to path+query, still same-origin
|
||||
expect(res.headers['Location']).toBe('/trips/5?tab=plan');
|
||||
@@ -200,7 +209,7 @@ describe('PluginsProxyController', () => {
|
||||
invoke: vi.fn(async () => ({ status: 302, headers: { location: loc } })),
|
||||
} as never);
|
||||
const res = fakeRes();
|
||||
await new PluginsProxyController(runtime).proxy('p', fakeReq('GET', '/status'), res as never);
|
||||
await ctrl(runtime).proxy('p', fakeReq('GET', '/status'), res as never);
|
||||
expect(res.statusCode).toBe(502);
|
||||
expect(res.body).toMatchObject({ detail: 'unsafe redirect target' });
|
||||
expect(res.headers['Location']).toBeUndefined();
|
||||
@@ -211,7 +220,7 @@ describe('PluginsProxyController', () => {
|
||||
invoke: vi.fn(async () => ({ status: 301, headers: {} })),
|
||||
} as never);
|
||||
const res = fakeRes();
|
||||
await new PluginsProxyController(runtime).proxy('p', fakeReq('GET', '/status'), res as never);
|
||||
await ctrl(runtime).proxy('p', fakeReq('GET', '/status'), res as never);
|
||||
expect(res.statusCode).toBe(502);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,30 +2,69 @@
|
||||
* The read-side plugin service + controller (#plugins, M0). Lists installed
|
||||
* plugins and reports whether the runtime is enabled (TREK_PLUGINS_ENABLED).
|
||||
*/
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { describe, it, expect, beforeAll, beforeEach, afterEach, vi } from 'vitest';
|
||||
|
||||
const { testDb } = vi.hoisted(() => {
|
||||
const Database = require('better-sqlite3');
|
||||
const db = new Database(':memory:');
|
||||
db.exec(`CREATE TABLE plugins (
|
||||
id TEXT PRIMARY KEY, name TEXT, description TEXT, type TEXT, icon TEXT, version TEXT,
|
||||
status TEXT, enabled INTEGER DEFAULT 0, last_error TEXT, reviewed_at TEXT, source_repo TEXT, config TEXT DEFAULT '{}', permissions TEXT DEFAULT '[]', granted_permissions TEXT DEFAULT '[]', capabilities TEXT DEFAULT '{}', dependencies TEXT DEFAULT '{}', operator_egress INTEGER DEFAULT 0, updated_at TEXT,
|
||||
author_pubkey TEXT, update_block_code TEXT, update_block_detail TEXT, update_block_version TEXT,
|
||||
trek_range TEXT, sort_order INTEGER DEFAULT 0, update_hold INTEGER NOT NULL DEFAULT 0);
|
||||
CREATE TABLE plugin_settings_fields (plugin_id TEXT, field_key TEXT, scope TEXT, secret INTEGER, required INTEGER DEFAULT 0, input_type TEXT DEFAULT 'text', default_value TEXT);
|
||||
CREATE TABLE plugin_error_log (id INTEGER PRIMARY KEY AUTOINCREMENT, plugin_id TEXT, level TEXT, message TEXT, ts TEXT DEFAULT '2026-01-01');`);
|
||||
return { testDb: db };
|
||||
vi.mock('../../../src/db/database', async () => {
|
||||
const { createSnapshotTestDb } = await import('../../helpers/db-mock');
|
||||
const db = createSnapshotTestDb();
|
||||
return { db };
|
||||
});
|
||||
vi.mock('../../../src/db/database', () => ({ db: testDb }));
|
||||
import { db as dbConn } from '../../../src/db/database';
|
||||
import { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
import { db as testDb } from '../../../src/db/database';
|
||||
|
||||
import { AddonsService } from '../../../src/nest/addons/addons.service';
|
||||
import type { AddonsService } from '../../../src/nest/addons/addons.service';
|
||||
import { createTestAddonsService } from '../../helpers/test-addons';
|
||||
import { sharedTestOrm } from '../../helpers/test-uow';
|
||||
import { Plugins } from '../../../src/db/entities/Plugins.entity';
|
||||
import { PluginErrorLog } from '../../../src/db/entities/PluginErrorLog.entity';
|
||||
import { PluginEgressHosts } from '../../../src/db/entities/PluginEgressHosts.entity';
|
||||
import { PluginSettingsFields } from '../../../src/db/entities/PluginSettingsFields.entity';
|
||||
import { PluginActions } from '../../../src/db/entities/PluginActions.entity';
|
||||
import { PluginUserConfig } from '../../../src/db/entities/PluginUserConfig.entity';
|
||||
import { PluginCapabilityAudit } from '../../../src/db/entities/PluginCapabilityAudit.entity';
|
||||
import { PluginsService } from '../../../src/nest/plugins/plugins.service';
|
||||
import { PluginsController } from '../../../src/nest/plugins/plugins.controller';
|
||||
import { PluginsFeedController } from '../../../src/nest/plugins/plugins-feed.controller';
|
||||
import type { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service';
|
||||
|
||||
// AddonsService only feeds PluginsService.list()'s required-addon-dependency
|
||||
// resolution; none of the fixtures below declare any, so it is built once
|
||||
// (over the same connection) rather than reconstructed at every call site.
|
||||
let addonsService: AddonsService;
|
||||
beforeAll(async () => {
|
||||
addonsService = await createTestAddonsService(testDb);
|
||||
});
|
||||
|
||||
/**
|
||||
* Plan 3j Task 2 — PluginsService's own repository-backed constructor. One
|
||||
* factory, reused by every call site below (`sharedTestOrm` memoises the ORM
|
||||
* per connection, so this is cheap): the six PS1-PS13 repositories, resolved
|
||||
* over the SAME `testDb` handle every raw-SQL fixture line above writes to.
|
||||
*/
|
||||
async function makeService(): Promise<PluginsService> {
|
||||
const orm = await sharedTestOrm(testDb);
|
||||
return new PluginsService(
|
||||
addonsService,
|
||||
orm.repo(Plugins),
|
||||
orm.repo(PluginEgressHosts),
|
||||
orm.repo(PluginSettingsFields),
|
||||
orm.repo(PluginActions),
|
||||
orm.repo(PluginUserConfig),
|
||||
orm.repo(PluginErrorLog),
|
||||
orm.repo(PluginCapabilityAudit),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* PFC1 (Plan 3j Task 5) — PluginsFeedController's own feed read, now
|
||||
* Plugins.repository.ts#findActiveFeedRows, resolved over the SAME `testDb`
|
||||
* handle every raw-SQL fixture line above writes to (same `sharedTestOrm`
|
||||
* reasoning as `makeService` above).
|
||||
*/
|
||||
async function makeFeedController(): Promise<PluginsFeedController> {
|
||||
const orm = await sharedTestOrm(testDb);
|
||||
return new PluginsFeedController(orm.repo(Plugins));
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
testDb.exec('DELETE FROM plugins');
|
||||
testDb.exec('DELETE FROM plugin_settings_fields');
|
||||
@@ -36,13 +75,13 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe('PluginsService.list', () => {
|
||||
it('returns the installed plugins and the runtime-enabled flag', () => {
|
||||
it('returns the installed plugins and the runtime-enabled flag', async () => {
|
||||
testDb
|
||||
.prepare('INSERT INTO plugins (id, name, description, type, status, version) VALUES (?,?,?,?,?,?)')
|
||||
.run('flight', 'Flight', 'desc', 'widget', 'inactive', '1.0.0');
|
||||
process.env.TREK_PLUGINS_ENABLED = 'true';
|
||||
|
||||
const out = new PluginsService(new DatabaseService(dbConn), new AddonsService(new DatabaseService(dbConn))).list();
|
||||
const out = await (await makeService()).list();
|
||||
expect(out.enabled).toBe(true);
|
||||
expect(out.plugins).toHaveLength(1);
|
||||
expect(out.plugins[0]).toMatchObject({ id: 'flight', name: 'Flight', status: 'inactive' });
|
||||
@@ -60,19 +99,19 @@ describe('PluginsService.list', () => {
|
||||
.prepare("INSERT INTO plugins (id, name, type, status, version, trek_range) VALUES ('old','Old','widget','inactive','1.0.0','>=3.0.0 <4.0.0')")
|
||||
.run();
|
||||
|
||||
it('reports the switch off and an outgrown plugin as hostIncompatible by default', () => {
|
||||
it('reports the switch off and an outgrown plugin as hostIncompatible by default', async () => {
|
||||
process.env.APP_VERSION = '4.1.0';
|
||||
seed();
|
||||
const out = new PluginsService(new DatabaseService(dbConn), new AddonsService(new DatabaseService(dbConn))).list();
|
||||
const out = await (await makeService()).list();
|
||||
expect(out.ignoreTrekRange).toBe(false);
|
||||
expect(out.plugins[0]).toMatchObject({ dependencyStatus: 'hostIncompatible', trekRangeBypassed: null });
|
||||
});
|
||||
|
||||
it('with the switch on, the plugin may activate but the row still says it is outside its range', () => {
|
||||
it('with the switch on, the plugin may activate but the row still says it is outside its range', async () => {
|
||||
process.env.APP_VERSION = '4.1.0';
|
||||
process.env.TREK_PLUGINS_IGNORE_TREK_RANGE = '1';
|
||||
seed();
|
||||
const out = new PluginsService(new DatabaseService(dbConn), new AddonsService(new DatabaseService(dbConn))).list();
|
||||
const out = await (await makeService()).list();
|
||||
expect(out.ignoreTrekRange).toBe(true);
|
||||
expect(out.plugins[0]).toMatchObject({
|
||||
dependencyStatus: 'ok',
|
||||
@@ -80,16 +119,16 @@ describe('PluginsService.list', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('a plugin inside its range carries no marker even with the switch on', () => {
|
||||
it('a plugin inside its range carries no marker even with the switch on', async () => {
|
||||
process.env.APP_VERSION = '3.5.0';
|
||||
process.env.TREK_PLUGINS_IGNORE_TREK_RANGE = '1';
|
||||
seed();
|
||||
const out = new PluginsService(new DatabaseService(dbConn), new AddonsService(new DatabaseService(dbConn))).list();
|
||||
const out = await (await makeService()).list();
|
||||
expect(out.plugins[0]).toMatchObject({ dependencyStatus: 'ok', trekRangeBypassed: null });
|
||||
});
|
||||
});
|
||||
|
||||
it('surfaces updateHold as a boolean (held plugins leave the update banner)', () => {
|
||||
it('surfaces updateHold as a boolean (held plugins leave the update banner)', async () => {
|
||||
testDb
|
||||
.prepare("INSERT INTO plugins (id, name, type, status, version, update_hold) VALUES ('held','Held','widget','inactive','1.0.0',1)")
|
||||
.run();
|
||||
@@ -97,35 +136,35 @@ describe('PluginsService.list', () => {
|
||||
.prepare("INSERT INTO plugins (id, name, type, status, version) VALUES ('free','Free','widget','inactive','1.0.0')")
|
||||
.run();
|
||||
|
||||
const out = new PluginsService(new DatabaseService(dbConn), new AddonsService(new DatabaseService(dbConn))).list();
|
||||
const out = await (await makeService()).list();
|
||||
expect(out.plugins.find((p) => p.id === 'held')).toMatchObject({ updateHold: true });
|
||||
expect(out.plugins.find((p) => p.id === 'free')).toMatchObject({ updateHold: false });
|
||||
});
|
||||
|
||||
it('resumeUpdates clears the hold and reports whether the plugin existed', () => {
|
||||
it('resumeUpdates clears the hold and reports whether the plugin existed', async () => {
|
||||
testDb
|
||||
.prepare("INSERT INTO plugins (id, name, type, status, version, update_hold) VALUES ('held','Held','widget','inactive','1.0.0',1)")
|
||||
.run();
|
||||
const svc = new PluginsService(new DatabaseService(dbConn), new AddonsService(new DatabaseService(dbConn)));
|
||||
const svc = await makeService();
|
||||
|
||||
expect(svc.resumeUpdates('held')).toBe(true);
|
||||
expect(await svc.resumeUpdates('held')).toBe(true);
|
||||
expect(testDb.prepare("SELECT update_hold FROM plugins WHERE id='held'").get()).toMatchObject({ update_hold: 0 });
|
||||
expect(svc.resumeUpdates('ghost')).toBe(false);
|
||||
expect(await svc.resumeUpdates('ghost')).toBe(false);
|
||||
});
|
||||
|
||||
it('reports enabled by default (no kill switch set)', () => {
|
||||
it('reports enabled by default (no kill switch set)', async () => {
|
||||
testDb
|
||||
.prepare('INSERT INTO plugins (id, name, description, type, status, version) VALUES (?,?,?,?,?,?)')
|
||||
.run('flight', 'Flight', 'desc', 'widget', 'inactive', '1.0.0');
|
||||
|
||||
const out = new PluginsService(new DatabaseService(dbConn), new AddonsService(new DatabaseService(dbConn))).list();
|
||||
const out = await (await makeService()).list();
|
||||
expect(out.enabled).toBe(true);
|
||||
expect(out.plugins).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('reports disabled when the kill switch is off (TREK_PLUGINS_ENABLED=false)', () => {
|
||||
it('reports disabled when the kill switch is off (TREK_PLUGINS_ENABLED=false)', async () => {
|
||||
process.env.TREK_PLUGINS_ENABLED = 'false';
|
||||
const out = new PluginsService(new DatabaseService(dbConn), new AddonsService(new DatabaseService(dbConn))).list();
|
||||
const out = await (await makeService()).list();
|
||||
expect(out.enabled).toBe(false);
|
||||
expect(out.plugins).toEqual([]);
|
||||
});
|
||||
@@ -141,11 +180,11 @@ describe('PluginsService.list', () => {
|
||||
.prepare('INSERT INTO plugins (id, name, type, status, version, source_repo, author_pubkey) VALUES (?,?,?,?,?,?,?)')
|
||||
.run(id, id, 'widget', 'inactive', '1.0.0', sourceRepo, pubkey);
|
||||
|
||||
it('reports signed + a display fingerprint for a registry plugin with a pinned key', () => {
|
||||
it('reports signed + a display fingerprint for a registry plugin with a pinned key', async () => {
|
||||
const key = 'RWTvBn0aBcDeFgHiJkLmNoPqRsTuVwXyZ0123456789abcd';
|
||||
insert('signed-one', 'acme/signed-one', key);
|
||||
|
||||
const p = new PluginsService(new DatabaseService(dbConn), new AddonsService(new DatabaseService(dbConn))).list().plugins[0];
|
||||
const p = (await (await makeService()).list()).plugins[0];
|
||||
expect(p.signed).toBe(true);
|
||||
// Short head…tail, for eyeballing against what the author reads out over the
|
||||
// phone. NOT a confidentiality measure — the key is public, and the re-trust
|
||||
@@ -153,107 +192,107 @@ describe('PluginsService.list', () => {
|
||||
expect(p.keyFingerprint).toBe(`${key.slice(0, 8)}…${key.slice(-8)}`);
|
||||
});
|
||||
|
||||
it('reports unsigned for a registry plugin with no pinned key', () => {
|
||||
it('reports unsigned for a registry plugin with no pinned key', async () => {
|
||||
insert('plain', 'acme/plain', null);
|
||||
const p = new PluginsService(new DatabaseService(dbConn), new AddonsService(new DatabaseService(dbConn))).list().plugins[0];
|
||||
const p = (await (await makeService()).list()).plugins[0];
|
||||
expect(p.signed).toBe(false);
|
||||
expect(p.keyFingerprint).toBeNull();
|
||||
});
|
||||
|
||||
it('reports unsigned for a sideloaded and a dev-linked plugin (they carry no key)', () => {
|
||||
it('reports unsigned for a sideloaded and a dev-linked plugin (they carry no key)', async () => {
|
||||
insert('uploaded', 'local:upload', null);
|
||||
insert('linked', 'local:link', null);
|
||||
const plugins = new PluginsService(new DatabaseService(dbConn), new AddonsService(new DatabaseService(dbConn))).list().plugins;
|
||||
const plugins = (await (await makeService()).list()).plugins;
|
||||
expect(plugins.map((p) => [p.id, p.signed, p.source_repo])).toEqual([
|
||||
['linked', false, 'local:link'],
|
||||
['uploaded', false, 'local:upload'],
|
||||
]);
|
||||
});
|
||||
|
||||
it('surfaces a recorded update block, and reports none when there is none', () => {
|
||||
it('surfaces a recorded update block, and reports none when there is none', async () => {
|
||||
insert('blocked', 'acme/blocked', 'RWTvBn0aBcDeFgHiJkLmNoPqRsTuVwXyZ0123456789abcd');
|
||||
insert('fine', 'acme/fine', null);
|
||||
testDb
|
||||
.prepare('UPDATE plugins SET update_block_code = ?, update_block_detail = ?, update_block_version = ? WHERE id = ?')
|
||||
.run('SIGNATURE_KEY_CHANGED', 'the key changed', '2.0.0', 'blocked');
|
||||
|
||||
const byId = Object.fromEntries(new PluginsService(new DatabaseService(dbConn), new AddonsService(new DatabaseService(dbConn))).list().plugins.map((p) => [p.id, p]));
|
||||
const byId = Object.fromEntries((await (await makeService()).list()).plugins.map((p) => [p.id, p]));
|
||||
expect(byId.blocked.updateBlock).toEqual({ code: 'SIGNATURE_KEY_CHANGED', detail: 'the key changed', version: '2.0.0' });
|
||||
expect(byId.fine.updateBlock).toBeNull();
|
||||
});
|
||||
|
||||
it('never leaks the raw pinned key into the list response (only the fingerprint)', () => {
|
||||
it('never leaks the raw pinned key into the list response (only the fingerprint)', async () => {
|
||||
insert('signed-one', 'acme/signed-one', 'RWTvBn0aBcDeFgHiJkLmNoPqRsTuVwXyZ0123456789abcd');
|
||||
// PluginListItem is an interface, so it has no implicit index signature and cannot
|
||||
// be narrowed to a record directly. Widening through unknown is what lets this case
|
||||
// probe for a key the contract deliberately does not declare.
|
||||
const p = new PluginsService(new DatabaseService(dbConn), new AddonsService(new DatabaseService(dbConn))).list()
|
||||
const p = (await (await makeService()).list())
|
||||
.plugins[0] as unknown as Record<string, unknown>;
|
||||
expect(p.author_pubkey).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
it('controller delegates to the service', () => {
|
||||
const svc = { list: vi.fn(() => ({ enabled: false, plugins: [] })) } as unknown as PluginsService;
|
||||
it('controller delegates to the service', async () => {
|
||||
const svc = { list: vi.fn(async () => ({ enabled: false, plugins: [] })) } as unknown as PluginsService;
|
||||
const runtime = {} as unknown as import('../../../src/nest/plugins/plugin-runtime.service').PluginRuntimeService;
|
||||
const res = new PluginsController(svc, runtime, {} as never, { isManaged: () => false } as unknown as RuntimeEnvService).list();
|
||||
const res = await new PluginsController(svc, runtime, {} as never, { isManaged: () => false } as unknown as RuntimeEnvService).list();
|
||||
expect(svc.list).toHaveBeenCalled();
|
||||
expect(res).toEqual({ enabled: false, plugins: [] });
|
||||
});
|
||||
});
|
||||
|
||||
describe('PluginsFeedController (client feed)', () => {
|
||||
it('returns active plugins when enabled, nothing when disabled', () => {
|
||||
it('returns active plugins when enabled, nothing when disabled', async () => {
|
||||
testDb.prepare("INSERT INTO plugins (id, name, type, icon, status) VALUES ('w','W','widget','Box','active')").run();
|
||||
testDb.prepare("INSERT INTO plugins (id, name, type, icon, status) VALUES ('i','I','integration','Plug','inactive')").run();
|
||||
const feed = new PluginsFeedController(new DatabaseService(dbConn));
|
||||
const feed = await makeFeedController();
|
||||
|
||||
process.env.TREK_PLUGINS_ENABLED = 'true';
|
||||
const active = feed.list();
|
||||
const active = await feed.list();
|
||||
expect(active.plugins).toEqual([{ id: 'w', name: 'W', type: 'widget', icon: 'Box', slot: 'sidebar' }]);
|
||||
|
||||
process.env.TREK_PLUGINS_ENABLED = 'false';
|
||||
expect(feed.list().plugins).toEqual([]);
|
||||
expect((await feed.list()).plugins).toEqual([]);
|
||||
});
|
||||
|
||||
it('exposes the widget slot from capabilities (hero) and defaults on bad JSON', () => {
|
||||
it('exposes the widget slot from capabilities (hero) and defaults on bad JSON', async () => {
|
||||
testDb.prepare("INSERT INTO plugins (id, name, type, icon, status, capabilities) VALUES ('h','H','widget','Box','active','{\"widget\":{\"slot\":\"hero\"}}')").run();
|
||||
testDb.prepare("INSERT INTO plugins (id, name, type, icon, status, capabilities) VALUES ('b','B','widget','Box','active','not-json')").run();
|
||||
process.env.TREK_PLUGINS_ENABLED = 'true';
|
||||
const out = new PluginsFeedController(new DatabaseService(dbConn)).list();
|
||||
const out = await (await makeFeedController()).list();
|
||||
expect(out.plugins.find((p) => p.id === 'h')?.slot).toBe('hero');
|
||||
expect(out.plugins.find((p) => p.id === 'b')?.slot).toBe('sidebar');
|
||||
});
|
||||
|
||||
it('exposes the day-detail slot (a day-panel widget must not fall back to the dashboard)', () => {
|
||||
it('exposes the day-detail slot (a day-panel widget must not fall back to the dashboard)', async () => {
|
||||
testDb.prepare("INSERT INTO plugins (id, name, type, icon, status, capabilities) VALUES ('d','D','widget','Box','active','{\"widget\":{\"slot\":\"day-detail\"}}')").run();
|
||||
process.env.TREK_PLUGINS_ENABLED = 'true';
|
||||
expect(new PluginsFeedController(new DatabaseService(dbConn)).list().plugins.find((p) => p.id === 'd')?.slot).toBe('day-detail');
|
||||
expect((await (await makeFeedController()).list()).plugins.find((p) => p.id === 'd')?.slot).toBe('day-detail');
|
||||
});
|
||||
|
||||
it('exposes settingsUi only when the capability is exactly true', () => {
|
||||
it('exposes settingsUi only when the capability is exactly true', async () => {
|
||||
testDb.prepare("INSERT INTO plugins (id, name, type, icon, status, capabilities) VALUES ('su','S','widget','Box','active','{\"settingsUi\":true}')").run();
|
||||
testDb.prepare("INSERT INTO plugins (id, name, type, icon, status, capabilities) VALUES ('no','N','widget','Box','active','{\"settingsUi\":\"yes\"}')").run();
|
||||
process.env.TREK_PLUGINS_ENABLED = 'true';
|
||||
const out = new PluginsFeedController(new DatabaseService(dbConn)).list();
|
||||
const out = await (await makeFeedController()).list();
|
||||
expect(out.plugins.find((p) => p.id === 'su')?.settingsUi).toBe(true);
|
||||
expect(out.plugins.find((p) => p.id === 'no')?.settingsUi).toBeUndefined();
|
||||
});
|
||||
|
||||
it('exposes the reservation-detail slot (a booking-card widget must not fall back to the dashboard)', () => {
|
||||
it('exposes the reservation-detail slot (a booking-card widget must not fall back to the dashboard)', async () => {
|
||||
testDb.prepare("INSERT INTO plugins (id, name, type, icon, status, capabilities) VALUES ('r','R','widget','Box','active','{\"widget\":{\"slot\":\"reservation-detail\"}}')").run();
|
||||
process.env.TREK_PLUGINS_ENABLED = 'true';
|
||||
expect(new PluginsFeedController(new DatabaseService(dbConn)).list().plugins.find((p) => p.id === 'r')?.slot).toBe('reservation-detail');
|
||||
expect((await (await makeFeedController()).list()).plugins.find((p) => p.id === 'r')?.slot).toBe('reservation-detail');
|
||||
});
|
||||
|
||||
it('exposes tripPage for trip-page plugins, re-validated against the replaceable-tab whitelist', () => {
|
||||
it('exposes tripPage for trip-page plugins, re-validated against the replaceable-tab whitelist', async () => {
|
||||
testDb.prepare("INSERT INTO plugins (id, name, type, icon, status, capabilities) VALUES ('t','T','trip-page','Box','active','{\"tripPage\":{\"replaces\":[\"transports\",\"buchungen\"],\"position\":1}}')").run();
|
||||
// a hand-edited row trying to hide 'plan' (or junk) is filtered here, not just at install
|
||||
testDb.prepare("INSERT INTO plugins (id, name, type, icon, status, capabilities) VALUES ('evil','E','trip-page','Box','active','{\"tripPage\":{\"replaces\":[\"plan\",\"nope\"],\"position\":-3}}')").run();
|
||||
// the capability is meaningless off a trip-page and must not leak onto widgets
|
||||
testDb.prepare("INSERT INTO plugins (id, name, type, icon, status, capabilities) VALUES ('w2','W2','widget','Box','active','{\"tripPage\":{\"replaces\":[\"transports\"]}}')").run();
|
||||
process.env.TREK_PLUGINS_ENABLED = 'true';
|
||||
const out = new PluginsFeedController(new DatabaseService(dbConn)).list();
|
||||
const out = await (await makeFeedController()).list();
|
||||
expect(out.plugins.find((p) => p.id === 't')?.tripPage).toEqual({ replaces: ['transports', 'buchungen'], position: 1 });
|
||||
expect(out.plugins.find((p) => p.id === 'evil')?.tripPage).toBeUndefined();
|
||||
expect(out.plugins.find((p) => p.id === 'w2')?.tripPage).toBeUndefined();
|
||||
@@ -262,9 +301,9 @@ describe('PluginsFeedController (client feed)', () => {
|
||||
|
||||
describe('PluginsController M2 endpoints', () => {
|
||||
const svc = {
|
||||
getInstanceConfig: vi.fn(() => ({ a: 1 })),
|
||||
instanceSettingsFields: vi.fn(() => [{ key: 'a' }]),
|
||||
updateInstanceConfig: vi.fn(() => ({ a: 2 })),
|
||||
getInstanceConfig: vi.fn(async () => ({ a: 1 })),
|
||||
instanceSettingsFields: vi.fn(async () => [{ key: 'a' }]),
|
||||
updateInstanceConfig: vi.fn(async () => ({ a: 2 })),
|
||||
} as unknown as PluginsService;
|
||||
// None of the endpoints below carry the marker, so the ordinary install is the
|
||||
// whole story here; the refusals have their own tests.
|
||||
@@ -277,9 +316,9 @@ describe('PluginsController M2 endpoints', () => {
|
||||
});
|
||||
|
||||
it('get/update config delegate to the service (get carries the form fields, update the restart)', async () => {
|
||||
const rt = { activate: vi.fn(), deactivate: vi.fn(), isActive: vi.fn(), respawnIfActive: vi.fn(async () => false), actionsOf: vi.fn(() => []) } as never;
|
||||
const rt = { activate: vi.fn(), deactivate: vi.fn(), isActive: vi.fn(), respawnIfActive: vi.fn(async () => false), actionsOf: vi.fn(async () => []) } as never;
|
||||
const c = new PluginsController(svc, rt, {} as never, envStub);
|
||||
expect(c.getConfig('x')).toEqual({ fields: [{ key: 'a' }], config: { a: 1 }, actions: [] });
|
||||
expect(await c.getConfig('x')).toEqual({ fields: [{ key: 'a' }], config: { a: 1 }, actions: [] });
|
||||
expect(await c.updateConfig('x', { a: 2 })).toEqual({ config: { a: 2 }, restarted: false });
|
||||
});
|
||||
|
||||
@@ -309,13 +348,13 @@ describe('PluginsController M2 endpoints', () => {
|
||||
});
|
||||
|
||||
describe('PluginsService instance config', () => {
|
||||
it('encrypts secret fields on write and masks them on read; keeps plaintext for non-secrets', () => {
|
||||
it('encrypts secret fields on write and masks them on read; keeps plaintext for non-secrets', async () => {
|
||||
testDb.prepare("INSERT INTO plugins (id, name, status, config) VALUES ('x','X','inactive','{}')").run();
|
||||
testDb.prepare("INSERT INTO plugin_settings_fields (plugin_id, field_key, scope, secret) VALUES ('x','api_key','instance',1)").run();
|
||||
testDb.prepare("INSERT INTO plugin_settings_fields (plugin_id, field_key, scope, secret) VALUES ('x','server','instance',0)").run();
|
||||
|
||||
const svc = new PluginsService(new DatabaseService(dbConn), new AddonsService(new DatabaseService(dbConn)));
|
||||
const masked = svc.updateInstanceConfig('x', { api_key: 'super-secret', server: 'https://h' });
|
||||
const svc = await makeService();
|
||||
const masked = await svc.updateInstanceConfig('x', { api_key: 'super-secret', server: 'https://h' });
|
||||
// client gets the masked view
|
||||
expect(masked.api_key).toBe('••••••••');
|
||||
expect(masked.server).toBe('https://h');
|
||||
@@ -327,19 +366,19 @@ describe('PluginsService instance config', () => {
|
||||
expect(stored.server).toBe('https://h');
|
||||
|
||||
// an unchanged mask does not overwrite the stored secret
|
||||
svc.updateInstanceConfig('x', { api_key: '••••••••' });
|
||||
await svc.updateInstanceConfig('x', { api_key: '••••••••' });
|
||||
const still = JSON.parse((testDb.prepare("SELECT config FROM plugins WHERE id='x'").get() as { config: string }).config);
|
||||
expect(still.api_key).toBe(stored.api_key);
|
||||
|
||||
expect(svc.getInstanceConfig('x').api_key).toBe('••••••••');
|
||||
expect((await svc.getInstanceConfig('x')).api_key).toBe('••••••••');
|
||||
});
|
||||
|
||||
it('drops a key the plugin never declared, like the user-scope sibling does', () => {
|
||||
it('drops a key the plugin never declared, like the user-scope sibling does', async () => {
|
||||
testDb.prepare("INSERT INTO plugins (id, name, status, config) VALUES ('y','Y','inactive','{}')").run();
|
||||
testDb.prepare("INSERT INTO plugin_settings_fields (plugin_id, field_key, scope, secret) VALUES ('y','server','instance',0)").run();
|
||||
|
||||
const svc = new PluginsService(new DatabaseService(dbConn), new AddonsService(new DatabaseService(dbConn)));
|
||||
const masked = svc.updateInstanceConfig('y', { server: 'https://h', smuggled: 'nope' });
|
||||
const svc = await makeService();
|
||||
const masked = await svc.updateInstanceConfig('y', { server: 'https://h', smuggled: 'nope' });
|
||||
|
||||
expect(masked.server).toBe('https://h');
|
||||
expect(masked.smuggled).toBeUndefined();
|
||||
@@ -347,19 +386,19 @@ describe('PluginsService instance config', () => {
|
||||
expect(stored).toEqual({ server: 'https://h' });
|
||||
});
|
||||
|
||||
it('throws for an unknown plugin', () => {
|
||||
expect(() => new PluginsService(new DatabaseService(dbConn), new AddonsService(new DatabaseService(dbConn))).updateInstanceConfig('nope', {})).toThrow(/not found/);
|
||||
expect(() => new PluginsService(new DatabaseService(dbConn), new AddonsService(new DatabaseService(dbConn))).getInstanceConfig('nope')).toThrow(/not found/);
|
||||
it('throws for an unknown plugin', async () => {
|
||||
await expect((await makeService()).updateInstanceConfig('nope', {})).rejects.toThrow(/not found/);
|
||||
await expect((await makeService()).getInstanceConfig('nope')).rejects.toThrow(/not found/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('PluginsService error log', () => {
|
||||
beforeEach(() => testDb.exec('DELETE FROM plugin_error_log'));
|
||||
it('lists and clears a plugin error log', () => {
|
||||
testDb.prepare("INSERT INTO plugin_error_log (plugin_id, level, message) VALUES ('p','error','boom')").run();
|
||||
const svc = new PluginsService(new DatabaseService(dbConn), new AddonsService(new DatabaseService(dbConn)));
|
||||
expect(svc.errors('p')).toEqual([{ ts: '2026-01-01', level: 'error', message: 'boom' }]);
|
||||
svc.clearErrors('p');
|
||||
expect(svc.errors('p')).toEqual([]);
|
||||
it('lists and clears a plugin error log', async () => {
|
||||
testDb.prepare("INSERT INTO plugin_error_log (plugin_id, level, message, ts) VALUES ('p','error','boom','2026-01-01')").run();
|
||||
const svc = await makeService();
|
||||
expect(await svc.errors('p')).toEqual([{ ts: '2026-01-01', level: 'error', message: 'boom' }]);
|
||||
await svc.clearErrors('p');
|
||||
expect(await svc.errors('p')).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -11,7 +11,6 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { PluginSupervisor } from '../../../src/nest/plugins/supervisor/plugin-supervisor';
|
||||
import { createPluginRuntime } from '../../helpers/plugin-host';
|
||||
import { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
import { db } from '../../../src/db/database';
|
||||
|
||||
function makeSupervisor(): PluginSupervisor {
|
||||
@@ -154,7 +153,7 @@ describe('providersOf narrowed to one optional function (#2221)', () => {
|
||||
|
||||
describe('runtime.invokeHook defense-in-depth', () => {
|
||||
it('refuses a plugin id that is not a granted provider of the hook, even if passed directly', async () => {
|
||||
const rt = createPluginRuntime(new DatabaseService(db));
|
||||
const rt = await createPluginRuntime(db);
|
||||
// one legitimate granted provider exists, so providersOf('placeDetailProvider') = ['ok']
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(rt as any).supervisor.running.set('ok', { id: 'ok', status: 'active', hooks: ['placeDetailProvider'], events: [], granted: new Set(['hook:place-detail-provider']) });
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
/**
|
||||
* D6 regression (task-2-review.md C3): a plugin's `ctx.*` call arrives over a
|
||||
* child-process `message` event, not an HTTP request, so nothing has forked an
|
||||
* EntityManager for it. `PluginSupervisor.onMessage` (plugin-supervisor.ts:~553)
|
||||
* is the single choke point every plugin RPC dispatch passes through, and it now
|
||||
* wraps `sup.rpcHost.dispatch(...)` in `withRequestContext` there.
|
||||
*
|
||||
* The reviewer's probe, reproduced here through the REAL call chain
|
||||
* (PluginSupervisor.onMessage → PluginGuards.canCreateAs →
|
||||
* PermissionsService.checkPermission → AppSettingsRepository.findByKeyPrefix),
|
||||
* not just `checkPermission` in isolation: with `perm_trip_create` tightened
|
||||
* from its 'everybody' default to 'admin', a role-'user' actor's check must
|
||||
* come back `false`. Before the fix (dispatch outside any context, and
|
||||
* loadPermissions serving defaults on any error) it came back `true` — a
|
||||
* fail-open security regression. Task 2's round fixed it two switches away
|
||||
* from the choke point — the wrapper here, and `loadPermissions` rethrowing a
|
||||
* MikroORM `ValidationError` instead of degrading (permissions.service.ts) —
|
||||
* so an unwrapped dispatch failed CLOSED (a HOST_ERROR envelope) but only
|
||||
* because BOTH switches held. task-6-fix-brief.md item 1 (task-6-review-
|
||||
* template.md's Important 1 / M-B) moves the fail-closed decision TO the
|
||||
* choke point itself: an absent `resolveOrm` now makes the dispatch THROW
|
||||
* before it ever reaches `rpcHost.dispatch`, so the child gets no response at
|
||||
* all — not even the old HOST_ERROR envelope — and the security property no
|
||||
* longer depends on `loadPermissions`' rethrow holding too.
|
||||
*
|
||||
* Global context is disallowed on purpose (`{ allowGlobalContext: false }`),
|
||||
* like `tests/unit/nest/database/request-context.test.ts` — the production
|
||||
* setting — NOT the `createTestOrm` default (`true`) that `test-uow.ts`'s
|
||||
* shared helpers use to let ordinary unit tests call a repository with no
|
||||
* request wrapper at all: that default would hide this exact bug.
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
|
||||
import { createSnapshotTestDb } from '../../helpers/db-mock';
|
||||
import { createUser } from '../../helpers/factories';
|
||||
import { createTestAddonsService } from '../../helpers/test-addons';
|
||||
import { PermissionsService } from '../../../src/nest/permissions/permissions.service';
|
||||
import { PluginGuards } from '../../../src/nest/plugins/host/plugin-guards.service';
|
||||
import { PluginSupervisor } from '../../../src/nest/plugins/supervisor/plugin-supervisor';
|
||||
import { UnitOfWork } from '../../../src/nest/database/unit-of-work';
|
||||
import { RpcRateLimiter, DEFAULT_RPC_LIMIT } from '../../../src/nest/plugins/host/rate-limit';
|
||||
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
|
||||
import { AppSettings } from '../../../src/db/entities/AppSettings.entity';
|
||||
import { Users } from '../../../src/db/entities/Users.entity';
|
||||
import { Trips } from '../../../src/db/entities/Trips.entity';
|
||||
import type { PluginRpcHost } from '../../../src/nest/plugins/host/rpc-host';
|
||||
import type { RpcRequest, RpcResponse, RpcError } from '../../../src/nest/plugins/protocol/envelope';
|
||||
import type { EntityManager } from '@mikro-orm/core';
|
||||
|
||||
/** The slice of Supervisor's private `Supervised` shape a 'req' dispatch touches. */
|
||||
interface DispatchEntry {
|
||||
rpcHost: Pick<PluginRpcHost, 'dispatch'>;
|
||||
child: { send: (msg: unknown) => void } | null;
|
||||
rpcLimiter: RpcRateLimiter;
|
||||
invocations: Map<string, number | undefined>;
|
||||
}
|
||||
/** `onMessage` is private; this is the narrowest structural view that reaches it
|
||||
* without an `any` cast. */
|
||||
interface SupervisorPrivate {
|
||||
onMessage(sup: DispatchEntry, msg: RpcRequest): Promise<void>;
|
||||
}
|
||||
|
||||
const testDb = createSnapshotTestDb();
|
||||
|
||||
let t: TestOrm;
|
||||
let permissions: PermissionsService;
|
||||
let guards: PluginGuards;
|
||||
let userId: number;
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestOrm(testDb, { allowGlobalContext: false });
|
||||
permissions = new PermissionsService(t.repo(AppSettings), new UnitOfWork(t.em));
|
||||
// Plan 3j Task 1: PluginGuards' own role lookup (canCreateAs, PG4) now goes
|
||||
// through UsersRepository.getRole — a REAL repository bound to `t.em`
|
||||
// (allowGlobalContext: false, same as `permissions`' AppSettingsRepository
|
||||
// above), not a stub, because this suite's whole point is proving that
|
||||
// read fails outside withRequestContext and succeeds inside it (D6/C3).
|
||||
// A mocked UsersRepository would defeat that regression coverage.
|
||||
// Plan 4 Task 2 — PluginGuards' own canAccessTrip delegate is now
|
||||
// TripsRepository.findAccessible; same REAL-repository reasoning applies.
|
||||
guards = new PluginGuards(t.repo(Trips), permissions, await createTestAddonsService(testDb), t.repo(Users));
|
||||
userId = createUser(testDb, { role: 'user' }).user.id;
|
||||
// An admin has tightened trip_create from its 'everybody' default.
|
||||
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('perm_trip_create', 'admin')").run();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await t.close();
|
||||
testDb.close();
|
||||
});
|
||||
|
||||
/**
|
||||
* Wires one supervisor whose fake rpcHost.dispatch calls straight into
|
||||
* PluginGuards.canCreateAs — the same chain the review traced
|
||||
* (plugin-guards.service.ts:74,84 → PermissionsService.checkPermission) — and
|
||||
* envelope-shapes the result exactly like the real PluginRpcHost.handle()
|
||||
* catch (rpc-host.ts): a thrown error becomes a HOST_ERROR response, never an
|
||||
* unhandled rejection. `resolveOrm` is the exact 4th constructor arg
|
||||
* PluginRuntimeService passes in production (plugin-runtime.service.ts).
|
||||
*/
|
||||
function makeSupervisor(resolveOrm?: () => { em: EntityManager } | undefined) {
|
||||
const sent: Array<RpcResponse | RpcError> = [];
|
||||
const dispatch: PluginRpcHost['dispatch'] = async (req, actingUserId) => {
|
||||
try {
|
||||
const result = await guards.canCreateAs('trip_create', actingUserId as number);
|
||||
return { k: 'res', id: req.id, ok: true, result };
|
||||
} catch (e) {
|
||||
return { k: 'res', id: req.id, ok: false, error: { code: 'HOST_ERROR', message: e instanceof Error ? e.message : String(e) } };
|
||||
}
|
||||
};
|
||||
const createRpcHost = () => ({ dispatch }) as unknown as PluginRpcHost;
|
||||
const supervisor = new PluginSupervisor(createRpcHost, {}, {}, resolveOrm) as unknown as SupervisorPrivate;
|
||||
const sup: DispatchEntry = {
|
||||
rpcHost: { dispatch },
|
||||
child: { send: (msg) => sent.push(msg as RpcResponse | RpcError) },
|
||||
rpcLimiter: new RpcRateLimiter(DEFAULT_RPC_LIMIT, Date.now()),
|
||||
invocations: new Map([['inv-1', userId]]),
|
||||
};
|
||||
return { supervisor, sup, sent };
|
||||
}
|
||||
|
||||
describe('PluginSupervisor request context (D6, C3)', () => {
|
||||
it('CTX-PLUGIN-001: without a resolveOrm thunk, the dispatch THROWS (host-side visibility) but the child still gets answered first (task-6-rereview.md §5 RULING: an unanswered \'req\' hangs the plugin forever — plugin-host-entry.ts\'s pending map has no timeout)', async () => {
|
||||
permissions.invalidatePermissionsCache();
|
||||
const { supervisor, sup, sent } = makeSupervisor(); // no resolveOrm — the bug's exact reproduction
|
||||
const canCreateAsSpy = vi.spyOn(guards, 'canCreateAs');
|
||||
try {
|
||||
await expect(
|
||||
supervisor.onMessage(sup, { k: 'req', id: 'r1', method: 'trips.create', params: { _inv: 'inv-1' } }),
|
||||
).rejects.toThrow(/no ORM available/i);
|
||||
// The dispatch itself never ran — same fail-closed guarantee as before.
|
||||
expect(canCreateAsSpy).not.toHaveBeenCalled();
|
||||
// But unlike the previous wave, the child DOES get a response: a HOST_ERROR
|
||||
// envelope, matching the rate-limiter refusal's shape, so its ctx.* promise
|
||||
// settles instead of hanging forever.
|
||||
expect(sent).toHaveLength(1);
|
||||
const res = sent[0];
|
||||
expect(res.ok).toBe(false);
|
||||
if (res.ok === false) {
|
||||
expect(res.error.code).toBe('HOST_ERROR');
|
||||
expect(res.error.message).toMatch(/no ORM available/i);
|
||||
}
|
||||
} finally {
|
||||
// task-6-rereview2.md M5: never restored before — a leak waiting for the
|
||||
// first mockImplementation another test in this file adds to `guards`.
|
||||
canCreateAsSpy.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('CTX-PLUGIN-002: wrapped in withRequestContext, the same dispatch enforces the stored override — a "user" role is refused', async () => {
|
||||
permissions.invalidatePermissionsCache();
|
||||
const { supervisor, sup, sent } = makeSupervisor(() => t.orm);
|
||||
|
||||
await supervisor.onMessage(sup, { k: 'req', id: 'r2', method: 'trips.create', params: { _inv: 'inv-1' } });
|
||||
|
||||
expect(sent).toHaveLength(1);
|
||||
const res = sent[0];
|
||||
expect(res.ok).toBe(true);
|
||||
if (res.ok) expect(res.result).toBe(false); // role 'user' against a stored 'admin' override
|
||||
});
|
||||
});
|
||||
@@ -23,9 +23,11 @@ import { ReservationsRpc } from '../../../src/nest/reservations/reservations.rpc
|
||||
import { DaysRpc } from '../../../src/nest/days/days.rpc';
|
||||
import { VacayRpc } from '../../../src/nest/vacay/vacay.rpc';
|
||||
import { NotFoundError, ValidationError } from '../../../src/nest/trips/trips.service';
|
||||
import type { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
import type { EntityManager } from '@mikro-orm/core';
|
||||
import type { TripsRepository } from '../../../src/db/repositories/Trips.repository';
|
||||
import type { PermissionsService } from '../../../src/nest/permissions/permissions.service';
|
||||
import type { AddonsService } from '../../../src/nest/addons/addons.service';
|
||||
import type { UsersRepository } from '../../../src/db/repositories/Users.repository';
|
||||
import type { RpcRequest, RpcError } from '../../../src/nest/plugins/protocol/envelope';
|
||||
import { makeDeps } from '../../helpers/rpc-host-deps';
|
||||
import { schemaMessage } from '../../../src/nest/plugins/host/rpc-params';
|
||||
@@ -40,15 +42,31 @@ const ALL = new Set([
|
||||
|
||||
function guardsFor() {
|
||||
const db = {
|
||||
canAccessTrip: vi.fn(() => ({ id: 1, user_id: 42 })),
|
||||
findAccessible: vi.fn(async () => ({ id: 1, user_id: 42 })),
|
||||
prepare: vi.fn(() => ({ get: () => ({ role: 'user' }), all: () => [] })),
|
||||
} as unknown as DatabaseService;
|
||||
} as unknown as TripsRepository;
|
||||
// Plan 3c Task 7: TripsRpc's RP1-RP6 resolve `EntityManager.getRepository(...)`
|
||||
// now, not `db.prepare(...)` — a generic fake repository (same shape regardless
|
||||
// of which entity class was requested) covers every RP method these fallback
|
||||
// cases exercise, none of which assert on the repository's specific return value.
|
||||
const em = {
|
||||
getRepository: () => ({
|
||||
getRole: vi.fn(async () => 'user'),
|
||||
findIdAndEmail: vi.fn(async () => ({ id: 2, email: 'x@example.test' })),
|
||||
getOwnerId: vi.fn(async () => 1),
|
||||
findRaw: vi.fn(async () => ({ id: 1, title: 'Japan', feed_token: null })),
|
||||
listForTripOrdered: vi.fn(async () => []),
|
||||
listRawUsernameAndDisplayName: vi.fn(async () => []),
|
||||
}),
|
||||
} as unknown as EntityManager;
|
||||
return {
|
||||
db,
|
||||
em,
|
||||
guards: new PluginGuards(
|
||||
db,
|
||||
{ checkPermission: vi.fn(() => true) } as unknown as PermissionsService,
|
||||
{ isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService,
|
||||
{ getRole: vi.fn(async () => 'user') } as unknown as UsersRepository,
|
||||
),
|
||||
};
|
||||
}
|
||||
@@ -77,19 +95,19 @@ describe('optional fields fall back rather than reaching the service as undefine
|
||||
});
|
||||
|
||||
it('FALLBACK-003 a file link with no targets stores three nulls', async () => {
|
||||
const { guards, db } = guardsFor();
|
||||
const { guards } = guardsFor();
|
||||
const createFileLink = vi.fn(() => []);
|
||||
const files = { getFileById: vi.fn(() => ({})), findForeignLinkTarget: vi.fn(() => null), createFileLink } as never;
|
||||
const host = new PluginRpcHost('p', ALL, makeDeps(), createTestPluginRegistry([new FilesRpc(files, realtime(), db, guards, {} as never)]));
|
||||
const host = new PluginRpcHost('p', ALL, makeDeps(), createTestPluginRegistry([new FilesRpc(files, realtime(), {} as never, guards, {} as never)]));
|
||||
await host.dispatch(req('files.createLink', { tripId: 1, fileId: 2, opts: {} }), 42);
|
||||
expect(createFileLink).toHaveBeenCalledWith(2, { reservation_id: null, assignment_id: null, place_id: null });
|
||||
});
|
||||
|
||||
it('FALLBACK-004 a file update tells an omitted link from one cleared with null', async () => {
|
||||
const { guards, db } = guardsFor();
|
||||
const { guards } = guardsFor();
|
||||
const updateFile = vi.fn((id: number) => ({ id }));
|
||||
const files = { getFileById: vi.fn(() => ({})), findForeignLinkTarget: vi.fn(() => null), updateFile } as never;
|
||||
const host = new PluginRpcHost('p', ALL, makeDeps(), createTestPluginRegistry([new FilesRpc(files, realtime(), db, guards, {} as never)]));
|
||||
const host = new PluginRpcHost('p', ALL, makeDeps(), createTestPluginRegistry([new FilesRpc(files, realtime(), {} as never, guards, {} as never)]));
|
||||
await host.dispatch(req('files.update', { tripId: 1, fileId: 2, input: { reservation_id: null, place_id: 7 } }), 42);
|
||||
expect(updateFile).toHaveBeenLastCalledWith(2, expect.anything(), expect.objectContaining({ reservation_id: null, place_id: '7' }));
|
||||
});
|
||||
@@ -141,14 +159,14 @@ describe('a service that says no becomes a refusal, not a crash', () => {
|
||||
|
||||
describe('service errors are translated into the RPC taxonomy', () => {
|
||||
function tripsHost(updateThrows?: Error, createThrows?: Error) {
|
||||
const { guards, db } = guardsFor();
|
||||
const { guards, em } = guardsFor();
|
||||
const trips = {
|
||||
list: vi.fn(() => []),
|
||||
updateTrip: vi.fn(() => { if (updateThrows) throw updateThrows; return { updatedTrip: { id: 1 } }; }),
|
||||
create: vi.fn(() => { if (createThrows) throw createThrows; return { trip: { id: 99 } }; }),
|
||||
removeMember: vi.fn(),
|
||||
} as never;
|
||||
const rpc = new TripsRpc(trips, {} as never, {} as never, {} as never, db, realtime(), guards, {} as never, {} as never);
|
||||
const rpc = new TripsRpc(trips, {} as never, {} as never, {} as never, realtime(), guards, {} as never, {} as never, em);
|
||||
return new PluginRpcHost('p', ALL, makeDeps(), createTestPluginRegistry([rpc]));
|
||||
}
|
||||
|
||||
@@ -245,13 +263,13 @@ const SCHEMA_REJECTS: Array<[string, Record<string, unknown>]> = [
|
||||
|
||||
describe('every schema-validated method rejects a payload its schema refuses', () => {
|
||||
function everything() {
|
||||
const { guards, db } = guardsFor();
|
||||
const { guards, em } = guardsFor();
|
||||
const anything = new Proxy({}, { get: () => vi.fn(() => ({ id: 1, trip: { id: 1 }, updatedTrip: { id: 1 }, reservation: { id: 1 } })) }) as never;
|
||||
const registry = createTestPluginRegistry([
|
||||
new PlacesRpc(anything, anything, realtime(), guards),
|
||||
new DaysRpc(anything, realtime(), guards, anything),
|
||||
new PackingRpc(anything, realtime(), guards),
|
||||
new TripsRpc(anything, anything, anything, anything, db, realtime(), guards, anything, anything),
|
||||
new TripsRpc(anything, anything, anything, anything, realtime(), guards, anything, anything, em),
|
||||
new AccommodationsRpc(anything, realtime(), guards),
|
||||
new ReservationsRpc(anything, realtime(), guards),
|
||||
]);
|
||||
|
||||
@@ -17,7 +17,8 @@ import type { RealtimeService } from '../../../src/nest/realtime/realtime.servic
|
||||
import { TripsRpc } from '../../../src/nest/trips/trips.rpc';
|
||||
import { DbRpc } from '../../../src/nest/plugins/host/rpc/db.rpc';
|
||||
import { PluginGuards } from '../../../src/nest/plugins/host/plugin-guards.service';
|
||||
import type { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
import type { EntityManager } from '@mikro-orm/core';
|
||||
import type { TripsRepository } from '../../../src/db/repositories/Trips.repository';
|
||||
import type { PluginUserSettingsService } from '../../../src/nest/plugins/plugin-user-settings.service';
|
||||
|
||||
const req = (method: string, params: Record<string, unknown>): RpcRequest => ({ k: 'req', id: 'x', method, params });
|
||||
@@ -35,12 +36,17 @@ const dbRegistry = () => {
|
||||
/** trips.getById lives on the decorators now, so the audit cases bind it through them. */
|
||||
const tripsRegistry = () => {
|
||||
const db = {
|
||||
canAccessTrip: (tripId: number, userId: number) => (tripId === 1 && userId === 42 ? { id: 1, user_id: 42 } : undefined),
|
||||
findAccessible: async (tripId: number, userId: number) => (tripId === 1 && userId === 42 ? { id: 1, user_id: 42 } : undefined),
|
||||
prepare: () => ({ get: () => ({ id: 1, title: 'Japan' }), all: () => [] }),
|
||||
} as unknown as DatabaseService;
|
||||
const guards = new PluginGuards(db, {} as never, {} as never);
|
||||
} as unknown as TripsRepository;
|
||||
const guards = new PluginGuards(db, {} as never, {} as never, {} as never);
|
||||
// Plan 3c Task 7: trips.getById (RP1) now reads through
|
||||
// `EntityManager.getRepository(Trips).findRaw(...)`, not `db.prepare(...)`.
|
||||
const em = {
|
||||
getRepository: () => ({ findRaw: async () => ({ id: 1, title: 'Japan', feed_token: null }) }),
|
||||
} as unknown as EntityManager;
|
||||
return createTestPluginRegistry([
|
||||
new TripsRpc({} as never, {} as never, {} as never, {} as never, db, {} as never, guards, {} as never, {} as never),
|
||||
new TripsRpc({} as never, {} as never, {} as never, {} as never, {} as never, guards, {} as never, {} as never, em),
|
||||
]);
|
||||
};
|
||||
|
||||
@@ -108,7 +114,7 @@ describe('dispatch strips the supervisor _inv marker', () => {
|
||||
createTestPluginRegistry([new PackingRpc(packing, realtime, guards)]),
|
||||
);
|
||||
await host.dispatch(req('packing.setBagMembers', { tripId: 1, bagId: 80, userIds: [3], _inv: 'req-7' }), 42);
|
||||
expect(setBagMembers).toHaveBeenCalledWith('1', '80', [3]);
|
||||
expect(setBagMembers).toHaveBeenCalledWith('1', 80, [3]);
|
||||
});
|
||||
|
||||
/**
|
||||
|
||||
@@ -121,7 +121,7 @@ describe('PluginRpcHost — capability enforcement', () => {
|
||||
expect(seen?.data).toBe(deps.data);
|
||||
await seen?.plugins.call('other', 'sum', [1], 42);
|
||||
expect(deps.callPlugin).toHaveBeenCalledWith('other', 'sum', [1], 42);
|
||||
seen?.plugins.emit('ping', { a: 1 });
|
||||
await seen?.plugins.emit('ping', { a: 1 });
|
||||
expect(deps.emitPluginEvent).toHaveBeenCalledWith('ping', { a: 1 });
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* `toCamelCase` (Plan 3j Task 6, design spec D8) — the DORMANT plugin-RPC facade
|
||||
* utility. This is its entire test surface: it is wired into no `*.rpc.ts` handler, so
|
||||
* no RPC-handler test changes alongside it. See `row-shape.ts`'s own docstring for why
|
||||
* it exists unwired and what it must never be applied to.
|
||||
*/
|
||||
import { describe, it, expect, expectTypeOf } from 'vitest';
|
||||
import { toCamelCase } from '../../../../src/nest/plugins/host/rpc-kit/row-shape';
|
||||
|
||||
describe('toCamelCase', () => {
|
||||
it('ROWSHAPE-001 a flat row with several snake_case keys gets both cases, originals unchanged', () => {
|
||||
const row = { id: 1, display_name: 'Ada', avatar_url: null as string | null };
|
||||
const mapped = toCamelCase(row);
|
||||
expect(mapped).toEqual({
|
||||
id: 1,
|
||||
display_name: 'Ada',
|
||||
avatar_url: null,
|
||||
displayName: 'Ada',
|
||||
avatarUrl: null,
|
||||
});
|
||||
// Originals present and unchanged, not moved.
|
||||
expect(mapped.display_name).toBe('Ada');
|
||||
expect(mapped.avatar_url).toBeNull();
|
||||
});
|
||||
|
||||
it('ROWSHAPE-002 a key with no underscore passes through untouched — no identity-transform copy', () => {
|
||||
const row = { id: 1, username: 'ada' };
|
||||
const mapped = toCamelCase(row);
|
||||
expect(mapped).toEqual({ id: 1, username: 'ada' });
|
||||
expect(Object.keys(mapped).sort()).toEqual(['id', 'username']);
|
||||
});
|
||||
|
||||
it('ROWSHAPE-003 an array of rows maps element-wise', () => {
|
||||
const rows = [
|
||||
{ id: 1, display_name: 'Ada' },
|
||||
{ id: 2, display_name: 'Bea' },
|
||||
];
|
||||
const mapped = toCamelCase(rows);
|
||||
expect(mapped).toEqual([
|
||||
{ id: 1, display_name: 'Ada', displayName: 'Ada' },
|
||||
{ id: 2, display_name: 'Bea', displayName: 'Bea' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('ROWSHAPE-004 a nested object stays untouched — proves the shallow, one-level scope', () => {
|
||||
const profile = { first_name: 'Ada', last_name: 'Lovelace' };
|
||||
const row = { id: 1, user_profile: profile };
|
||||
const mapped = toCamelCase(row);
|
||||
// The camel sibling points at the exact SAME object — never a recursively-mapped copy.
|
||||
expect(mapped.userProfile).toBe(profile);
|
||||
expect(mapped.user_profile).toBe(profile);
|
||||
// The nested object itself gained no camelCase siblings.
|
||||
expect(Object.keys(profile).sort()).toEqual(['first_name', 'last_name']);
|
||||
expect((profile as Record<string, unknown>).firstName).toBeUndefined();
|
||||
});
|
||||
|
||||
it('ROWSHAPE-005 null, undefined and a primitive pass through safely, unchanged', () => {
|
||||
expect(toCamelCase(null)).toBeNull();
|
||||
expect(toCamelCase(undefined)).toBeUndefined();
|
||||
expect(toCamelCase('a string')).toBe('a string');
|
||||
expect(toCamelCase(42)).toBe(42);
|
||||
expect(toCamelCase(true)).toBe(true);
|
||||
});
|
||||
|
||||
it('ROWSHAPE-006 a Date or Buffer value — at the top level or nested under a key — passes through unchanged', () => {
|
||||
const when = new Date('2026-09-24T00:00:00.000Z');
|
||||
const bytes = Buffer.from('hello');
|
||||
|
||||
// Top-level argument.
|
||||
expect(toCamelCase(when)).toBe(when);
|
||||
expect(toCamelCase(bytes)).toBe(bytes);
|
||||
|
||||
// Nested under a row key — never spread, never recursed into.
|
||||
const row = { id: 1, created_at: when, blob_data: bytes };
|
||||
const mapped = toCamelCase(row);
|
||||
expect(mapped.createdAt).toBe(when);
|
||||
expect(mapped.created_at).toBe(when);
|
||||
expect(mapped.blobData).toBe(bytes);
|
||||
expect(mapped.blob_data).toBe(bytes);
|
||||
});
|
||||
|
||||
it('ROWSHAPE-007 a digit immediately after an underscore follows the same rule (no special case)', () => {
|
||||
const row = { place_2_id: 7 };
|
||||
const mapped = toCamelCase(row);
|
||||
expect(mapped).toEqual({ place_2_id: 7, place2Id: 7 });
|
||||
});
|
||||
|
||||
it('ROWSHAPE-008 an empty object round-trips to an equal empty object', () => {
|
||||
expect(toCamelCase({})).toEqual({});
|
||||
});
|
||||
|
||||
it('ROWSHAPE-009 an empty array round-trips to an empty array', () => {
|
||||
expect(toCamelCase([])).toEqual([]);
|
||||
});
|
||||
|
||||
it('ROWSHAPE-010 type-level: the SDK-shaped User row keeps its snake_case members AND exposes the camel siblings', () => {
|
||||
// Mirrors plugin-sdk/src/index.ts's published `User` shape exactly (id, username,
|
||||
// display_name, avatar, plus its index signature) — the one row HostSurfaceRpc#getUser
|
||||
// (HR1) would wrap if the facade were ever wired in.
|
||||
interface SdkUserRow {
|
||||
id: number;
|
||||
username?: string;
|
||||
display_name?: string | null;
|
||||
avatar?: string | null;
|
||||
[k: string]: unknown;
|
||||
}
|
||||
const row: SdkUserRow = { id: 1, username: 'ada', display_name: 'Ada Lovelace', avatar: null };
|
||||
const mapped = toCamelCase(row);
|
||||
|
||||
// The mapped type is `SdkUserRow & Record<string, unknown>`: every original member
|
||||
// stays typed, and any camelCase sibling (`displayName`, unlisted on `SdkUserRow`
|
||||
// itself) resolves through the added index signature rather than failing to compile —
|
||||
// exactly the shape a plugin-sdk follow-up release's row types would need.
|
||||
expectTypeOf(mapped).toEqualTypeOf<SdkUserRow & Record<string, unknown>>();
|
||||
expectTypeOf(mapped.display_name).toEqualTypeOf<SdkUserRow['display_name']>();
|
||||
expectTypeOf(mapped.displayName).toEqualTypeOf<unknown>();
|
||||
|
||||
expect(mapped.display_name).toBe('Ada Lovelace');
|
||||
expect(mapped.displayName).toBe('Ada Lovelace');
|
||||
});
|
||||
});
|
||||
@@ -9,29 +9,56 @@
|
||||
* field with such a name reported as configured for a user who had configured nothing —
|
||||
* which for a notification channel meant being dispatched to everyone with no credentials.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest';
|
||||
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
|
||||
|
||||
const { testDb, dbMock } = vi.hoisted(() => {
|
||||
const Database = require('better-sqlite3');
|
||||
const db = new Database(':memory:');
|
||||
return { testDb: db, dbMock: { db, closeDb: () => {}, reinitialize: () => {}, canAccessTrip: () => null } };
|
||||
vi.mock('../../../src/db/database', async () => {
|
||||
const { createSnapshotTestDb } = await import('../../helpers/db-mock');
|
||||
const db = createSnapshotTestDb();
|
||||
return { db, closeDb: () => {}, reinitialize: () => {}, canAccessTrip: async () => null };
|
||||
});
|
||||
vi.mock('../../../src/db/database', () => dbMock);
|
||||
import { db as dbConn } from '../../../src/db/database';
|
||||
import { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
import { db as testDb } from '../../../src/db/database';
|
||||
import { UnitOfWork } from '../../../src/nest/database/unit-of-work';
|
||||
import { AuditService } from '../../../src/nest/audit/audit.service';
|
||||
import { AddonsService } from '../../../src/nest/addons/addons.service';
|
||||
import { createTestAddonsService } from '../../helpers/test-addons';
|
||||
vi.mock('../../../src/config', () => ({ JWT_SECRET: 'x'.repeat(40), ENCRYPTION_KEY: 'a'.repeat(64), updateJwtSecret: () => {} }));
|
||||
|
||||
import { createTables } from '../../../src/db/schema';
|
||||
import { runMigrations } from '../../../src/db/migrations';
|
||||
import { createUser } from '../../helpers/factories';
|
||||
import { PluginUserSettingsService } from '../../../src/nest/plugins/plugin-user-settings.service';
|
||||
import { parseManifest, ManifestError } from '../../../src/nest/plugins/install/manifest';
|
||||
/** The host-side settings reads, over the same connection the test seeded. */
|
||||
const userSettings = () => new PluginUserSettingsService(new DatabaseService(dbConn));
|
||||
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
|
||||
import { AuditLog } from '../../../src/db/entities/AuditLog.entity';
|
||||
import { Users } from '../../../src/db/entities/Users.entity';
|
||||
import { Plugins } from '../../../src/db/entities/Plugins.entity';
|
||||
import { PluginErrorLog } from '../../../src/db/entities/PluginErrorLog.entity';
|
||||
import { PluginScheduledTasks } from '../../../src/db/entities/PluginScheduledTasks.entity';
|
||||
import { PluginUserErasureQueue } from '../../../src/db/entities/PluginUserErasureQueue.entity';
|
||||
import { PluginEgressHosts } from '../../../src/db/entities/PluginEgressHosts.entity';
|
||||
import { PluginSettingsFields } from '../../../src/db/entities/PluginSettingsFields.entity';
|
||||
import { PluginActions } from '../../../src/db/entities/PluginActions.entity';
|
||||
import { PluginUserConfig } from '../../../src/db/entities/PluginUserConfig.entity';
|
||||
import { PluginEntityMetadata } from '../../../src/db/entities/PluginEntityMetadata.entity';
|
||||
import { PluginOauthTokens } from '../../../src/db/entities/PluginOauthTokens.entity';
|
||||
import { PluginOauthState } from '../../../src/db/entities/PluginOauthState.entity';
|
||||
import { PluginMetaMigrations } from '../../../src/db/entities/PluginMetaMigrations.entity';
|
||||
import { PluginCapabilityAudit } from '../../../src/db/entities/PluginCapabilityAudit.entity';
|
||||
import { Settings } from '../../../src/db/entities/Settings.entity';
|
||||
import { NotificationChannelPreferences } from '../../../src/db/entities/NotificationChannelPreferences.entity';
|
||||
/**
|
||||
* The host-side settings reads, over the same connection the test seeded. `t` is
|
||||
* initialized in `beforeAll` (below) before any test runs — this reaches for
|
||||
* `PluginSettingsFieldsRepository`/`PluginUserConfigRepository` through it, matching
|
||||
* PSET-007's own `PluginRuntimeService` construction further down, which reuses the
|
||||
* SAME `t` rather than a second ORM over the same connection.
|
||||
*/
|
||||
const userSettings = () =>
|
||||
new PluginUserSettingsService((t as TestOrm).repo(PluginSettingsFields), (t as TestOrm).repo(PluginUserConfig));
|
||||
|
||||
let uid: number;
|
||||
let t: TestOrm | undefined;
|
||||
|
||||
afterAll(async () => {
|
||||
await t?.close();
|
||||
});
|
||||
|
||||
function declareField(pluginId: string, key: string, opts: { required?: boolean; secret?: boolean } = {}) {
|
||||
testDb.prepare(
|
||||
@@ -43,7 +70,12 @@ function setUserConfig(pluginId: string, config: Record<string, unknown>) {
|
||||
testDb.prepare('INSERT OR REPLACE INTO plugin_user_config (plugin_id, user_id, config) VALUES (?, ?, ?)').run(pluginId, uid, JSON.stringify(config));
|
||||
}
|
||||
|
||||
beforeAll(() => { createTables(testDb); runMigrations(testDb); });
|
||||
beforeAll(async () => {
|
||||
// Plan 3j Task 4 — `userSettings()` above now needs repositories, so the ORM this
|
||||
// file eventually built only inside PSET-007 is built here instead, before any
|
||||
// test runs (PSET-001..006 call `userSettings()` with no ORM of their own).
|
||||
t = await createTestOrm(testDb);
|
||||
});
|
||||
beforeEach(() => {
|
||||
testDb.prepare('DELETE FROM plugin_settings_fields').run();
|
||||
testDb.prepare('DELETE FROM plugin_user_config').run();
|
||||
@@ -53,7 +85,7 @@ beforeEach(() => {
|
||||
});
|
||||
|
||||
describe('plugin settings are isolated from core and from each other', () => {
|
||||
it('PSET-001 — a plugin declaring "webhook_url" cannot touch the CORE settings row', () => {
|
||||
it('PSET-001 — a plugin declaring "webhook_url" cannot touch the CORE settings row', async () => {
|
||||
testDb.prepare("INSERT INTO settings (user_id, key, value) VALUES (?, 'webhook_url', 'https://core.example.com/real')").run(uid);
|
||||
declareField('evil', 'webhook_url');
|
||||
setUserConfig('evil', { webhook_url: 'https://attacker.example.com' });
|
||||
@@ -62,43 +94,43 @@ describe('plugin settings are isolated from core and from each other', () => {
|
||||
// its own blob, in its own table. The namespacing is structural, not by key naming.
|
||||
const core = testDb.prepare("SELECT value FROM settings WHERE user_id = ? AND key = 'webhook_url'").get(uid) as { value: string };
|
||||
expect(core.value).toBe('https://core.example.com/real');
|
||||
expect(userSettings().readAll('evil', uid)).toEqual({ webhook_url: 'https://attacker.example.com' });
|
||||
expect(await userSettings().readAll('evil', uid)).toEqual({ webhook_url: 'https://attacker.example.com' });
|
||||
});
|
||||
|
||||
it('PSET-002 — plugin A cannot read plugin B’s config, even with the same key name', () => {
|
||||
it('PSET-002 — plugin A cannot read plugin B’s config, even with the same key name', async () => {
|
||||
declareField('a', 'token', { secret: true });
|
||||
declareField('b', 'token', { secret: true });
|
||||
setUserConfig('b', { token: 'B-SECRET' });
|
||||
|
||||
expect(userSettings().readAll('a', uid)).toEqual({});
|
||||
expect(userSettings().readOne('a', uid, 'token')).toBeUndefined();
|
||||
expect(userSettings().readOne('b', uid, 'token')).toBe('B-SECRET');
|
||||
expect(await userSettings().readAll('a', uid)).toEqual({});
|
||||
expect(await userSettings().readOne('a', uid, 'token')).toBeUndefined();
|
||||
expect(await userSettings().readOne('b', uid, 'token')).toBe('B-SECRET');
|
||||
});
|
||||
|
||||
it('PSET-003 — a plugin only ever sees its own DECLARED keys', () => {
|
||||
it('PSET-003 — a plugin only ever sees its own DECLARED keys', async () => {
|
||||
declareField('p', 'declared');
|
||||
// An undeclared key that somehow reached the blob is not handed to the plugin.
|
||||
setUserConfig('p', { declared: 'yes', sneaked: 'no' });
|
||||
expect(userSettings().readAll('p', uid)).toEqual({ declared: 'yes' });
|
||||
expect(await userSettings().readAll('p', uid)).toEqual({ declared: 'yes' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('settings keys cannot resolve off the prototype chain', () => {
|
||||
it.each(['__proto__', 'constructor', 'prototype'])(
|
||||
'PSET-004 — a REQUIRED field named "%s" is NOT reported as configured',
|
||||
(key) => {
|
||||
async (key) => {
|
||||
declareField('evil', key, { required: true });
|
||||
// The user has configured nothing at all.
|
||||
expect(userSettings().hasRequired('evil', uid)).toBe(false);
|
||||
expect(userSettings().readAll('evil', uid)).toEqual({});
|
||||
expect(await userSettings().hasRequired('evil', uid)).toBe(false);
|
||||
expect(await userSettings().readAll('evil', uid)).toEqual({});
|
||||
},
|
||||
);
|
||||
|
||||
it('PSET-005 — a genuinely configured required field still reports configured', () => {
|
||||
it('PSET-005 — a genuinely configured required field still reports configured', async () => {
|
||||
declareField('good', 'appToken', { required: true, secret: true });
|
||||
expect(userSettings().hasRequired('good', uid)).toBe(false);
|
||||
expect(await userSettings().hasRequired('good', uid)).toBe(false);
|
||||
setUserConfig('good', { appToken: 'T' });
|
||||
expect(userSettings().hasRequired('good', uid)).toBe(true);
|
||||
expect(await userSettings().hasRequired('good', uid)).toBe(true);
|
||||
});
|
||||
|
||||
it('PSET-006 — the manifest rejects such a key at install', () => {
|
||||
@@ -126,13 +158,34 @@ describe('a plugin channel label is bounded by the host', () => {
|
||||
VALUES ('loud', 'Loud', 'active', 1, '1.0.0', '[]', '[]', ?, '{}')`,
|
||||
).run(JSON.stringify({ notificationChannel: { title: '🎉'.repeat(5) + 'A'.repeat(500) } }));
|
||||
|
||||
const rt = new PluginRuntimeService(new DatabaseService(dbConn), new AuditService(new DatabaseService(dbConn)), new AddonsService(new DatabaseService(dbConn)), userSettings());
|
||||
const rt = new PluginRuntimeService(
|
||||
new AuditService(t.repo(AuditLog), t.repo(Users)),
|
||||
await createTestAddonsService(testDb),
|
||||
userSettings(),
|
||||
t.repo(Plugins),
|
||||
t.repo(PluginErrorLog),
|
||||
t.repo(PluginScheduledTasks),
|
||||
t.repo(PluginUserErasureQueue),
|
||||
t.repo(PluginEgressHosts),
|
||||
t.repo(PluginSettingsFields),
|
||||
t.repo(PluginActions),
|
||||
t.repo(PluginUserConfig),
|
||||
t.repo(PluginEntityMetadata),
|
||||
t.repo(PluginOauthTokens),
|
||||
t.repo(PluginOauthState),
|
||||
t.repo(PluginMetaMigrations),
|
||||
t.repo(PluginCapabilityAudit),
|
||||
t.repo(Settings),
|
||||
t.repo(NotificationChannelPreferences),
|
||||
// Plan 4 Task 4: `uow` is no longer `@Optional()`.
|
||||
new UnitOfWork(t.em),
|
||||
);
|
||||
// Stand the plugin up as a granted, active notificationChannel provider.
|
||||
(rt as unknown as { supervisor: { running: Map<string, unknown> } }).supervisor.running.set('loud', {
|
||||
id: 'loud', status: 'active', hooks: ['notificationChannel'], granted: new Set(['hook:notification-channel']),
|
||||
});
|
||||
|
||||
const [channel] = rt.notificationChannels();
|
||||
const [channel] = await rt.notificationChannels();
|
||||
expect(channel.id).toBe('plugin:loud');
|
||||
expect(channel.label!.length).toBeLessThanOrEqual(40);
|
||||
expect(channel.label).not.toMatch(/\p{Extended_Pictographic}/u);
|
||||
|
||||
@@ -4,14 +4,25 @@
|
||||
* an admin depends on: re-activating a plugin that died stays possible, and a
|
||||
* crash-restart cycle doesn't leak the dead child's cron tasks.
|
||||
*/
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest';
|
||||
import { describe, it, expect, vi, beforeAll, afterAll, afterEach } from 'vitest';
|
||||
import Database from 'better-sqlite3';
|
||||
import { PluginSupervisor } from '../../../src/nest/plugins/supervisor/plugin-supervisor';
|
||||
import { RpcRateLimiter, TokenBucket } from '../../../src/nest/plugins/host/rate-limit';
|
||||
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
|
||||
|
||||
// task-6-fix-brief.md item 1: onMessage's 'req' branch now THROWS without a
|
||||
// resolveOrm thunk (no more silent unwrapped dispatch), so the one case below
|
||||
// that dispatches a real 'req' message ("refuses a throttled call...") needs a
|
||||
// real ORM even though nothing it exercises reaches a repository.
|
||||
const ormDb = new Database(':memory:');
|
||||
let ormHandle: TestOrm;
|
||||
beforeAll(async () => { ormHandle = await createTestOrm(ormDb); });
|
||||
afterAll(async () => { await ormHandle.close(); ormDb.close(); });
|
||||
|
||||
function makeSupervisor() {
|
||||
const dispose = vi.fn();
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const s = new PluginSupervisor((() => ({ dispose })) as any, {}, {});
|
||||
const s = new PluginSupervisor((() => ({ dispose })) as any, {}, {}, () => ormHandle.orm);
|
||||
const spawn = vi.fn();
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(s as any).spawn = spawn;
|
||||
|
||||
@@ -9,7 +9,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
const { canAccessTrip, pluginsEnabled } = vi.hoisted(() => ({
|
||||
// trips 1 and 2 are accessible to user 5; everything else is not.
|
||||
canAccessTrip: vi.fn((tripId: number, userId: number) => (userId === 5 && (tripId === 1 || tripId === 2) ? { id: tripId } : undefined)),
|
||||
canAccessTrip: vi.fn(async (tripId: number, userId: number) => (userId === 5 && (tripId === 1 || tripId === 2) ? { id: tripId } : undefined)),
|
||||
pluginsEnabled: vi.fn(() => true),
|
||||
}));
|
||||
vi.mock('../../../src/db/database', () => ({ db: { prepare: () => ({ get: () => undefined }) }, canAccessTrip }));
|
||||
@@ -17,7 +17,7 @@ vi.mock('../../../src/nest/plugins/kill-switch', () => ({ pluginsEnabled }));
|
||||
|
||||
import { TripCardContributionsController } from '../../../src/nest/plugins/contributions/trip-card-contributions.controller';
|
||||
import type { PluginHooks } from '../../../src/nest/plugins/plugin-hooks.service';
|
||||
import type { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
import type { TripsRepository } from '../../../src/db/repositories/Trips.repository';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const req = (id?: number) => ({ user: id === undefined ? undefined : { id } }) as any;
|
||||
@@ -26,7 +26,7 @@ function controller(invoke: (id: string, args: unknown[]) => unknown, providers
|
||||
providersOf: vi.fn(() => providers),
|
||||
tripCards: vi.fn(async (id: string, _h: string, _fn: string, args: unknown[]) => invoke(id, args)),
|
||||
} as unknown as PluginHooks;
|
||||
return { c: new TripCardContributionsController(runtime, { canAccessTrip } as unknown as DatabaseService), runtime };
|
||||
return { c: new TripCardContributionsController(runtime, { findAccessible: canAccessTrip } as unknown as TripsRepository), runtime };
|
||||
}
|
||||
const badge = (over: Record<string, unknown> = {}) => ({ tripId: 1, id: 'b1', label: 'Visa', ...over });
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
const { canAccessTrip, pluginsEnabled } = vi.hoisted(() => ({
|
||||
canAccessTrip: vi.fn((tripId: number, userId: number) => (tripId === 1 && userId === 5 ? { id: 1 } : undefined)),
|
||||
canAccessTrip: vi.fn(async (tripId: number, userId: number) => (tripId === 1 && userId === 5 ? { id: 1 } : undefined)),
|
||||
pluginsEnabled: vi.fn(() => true),
|
||||
}));
|
||||
vi.mock('../../../src/db/database', () => ({ db: {}, canAccessTrip }));
|
||||
@@ -9,7 +9,7 @@ vi.mock('../../../src/nest/plugins/kill-switch', () => ({ pluginsEnabled }));
|
||||
|
||||
import { TripWarningsController } from '../../../src/nest/plugins/contributions/trip-warnings.controller';
|
||||
import type { PluginHooks } from '../../../src/nest/plugins/plugin-hooks.service';
|
||||
import type { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
import type { TripsRepository } from '../../../src/db/repositories/Trips.repository';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const req = (id?: number) => ({ user: id === undefined ? undefined : { id } }) as any;
|
||||
@@ -20,18 +20,18 @@ function controller(over: Partial<PluginHooks> = {}) {
|
||||
id === 'p2' ? [{ level: 'error', message: 'Day 3 is overpacked', dayId: 3 }] : [{ level: 'warning', message: 'Museum closed Mon', placeId: 7 }]),
|
||||
...over,
|
||||
} as unknown as PluginHooks;
|
||||
return { c: new TripWarningsController(runtime, { canAccessTrip } as unknown as DatabaseService), runtime };
|
||||
return { c: new TripWarningsController(runtime, { findAccessible: canAccessTrip } as unknown as TripsRepository), runtime };
|
||||
}
|
||||
|
||||
describe('TripWarningsController', () => {
|
||||
beforeEach(() => { pluginsEnabled.mockReturnValue(true); canAccessTrip.mockReturnValue({ id: 1 } as never); });
|
||||
beforeEach(() => { pluginsEnabled.mockReturnValue(true); canAccessTrip.mockResolvedValue({ id: 1 } as never); });
|
||||
|
||||
it('returns [] when disabled / no user / no access', async () => {
|
||||
pluginsEnabled.mockReturnValue(false);
|
||||
expect(await controller().c.get('1', req(5))).toEqual({ warnings: [] });
|
||||
pluginsEnabled.mockReturnValue(true);
|
||||
expect(await controller().c.get('1', req(undefined))).toEqual({ warnings: [] });
|
||||
canAccessTrip.mockReturnValue(undefined as never);
|
||||
canAccessTrip.mockResolvedValue(undefined as never);
|
||||
expect(await controller().c.get('1', req(5))).toEqual({ warnings: [] });
|
||||
});
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
const { canAccessTrip, pluginsEnabled } = vi.hoisted(() => ({
|
||||
canAccessTrip: vi.fn((tripId: number, userId: number) => (tripId === 1 && userId === 5 ? { id: 1 } : undefined)),
|
||||
canAccessTrip: vi.fn(async (tripId: number, userId: number) => (tripId === 1 && userId === 5 ? { id: 1 } : undefined)),
|
||||
pluginsEnabled: vi.fn(() => true),
|
||||
}));
|
||||
vi.mock('../../../src/db/database', () => ({ db: { prepare: () => ({ get: () => undefined }) }, canAccessTrip }));
|
||||
@@ -16,7 +16,7 @@ vi.mock('../../../src/nest/plugins/kill-switch', () => ({ pluginsEnabled }));
|
||||
|
||||
import { ViewContributionsController } from '../../../src/nest/plugins/contributions/view-contributions.controller';
|
||||
import type { PluginHooks } from '../../../src/nest/plugins/plugin-hooks.service';
|
||||
import type { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
import type { TripsRepository } from '../../../src/db/repositories/Trips.repository';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const req = (id?: number) => ({ user: id === undefined ? undefined : { id } }) as any;
|
||||
@@ -25,13 +25,13 @@ function controller(invoke: (id: string) => unknown, providers = ['p1']) {
|
||||
providersOf: vi.fn(() => providers),
|
||||
tableContributions: vi.fn(async (id: string) => invoke(id)),
|
||||
} as unknown as PluginHooks;
|
||||
return { c: new ViewContributionsController(runtime, { canAccessTrip } as unknown as DatabaseService), runtime };
|
||||
return { c: new ViewContributionsController(runtime, { findAccessible: canAccessTrip } as unknown as TripsRepository), runtime };
|
||||
}
|
||||
const col = (over: Record<string, unknown> = {}) => ({ kind: 'column', entityId: 1, id: 'c1', label: 'X', ...over });
|
||||
const act = (over: Record<string, unknown> = {}) => ({ kind: 'action', entityId: 1, id: 'a1', label: 'Go', target: { kind: 'frame', sub: '/ui' }, ...over });
|
||||
|
||||
describe('ViewContributionsController', () => {
|
||||
beforeEach(() => { pluginsEnabled.mockReturnValue(true); canAccessTrip.mockReturnValue({ id: 1 } as never); });
|
||||
beforeEach(() => { pluginsEnabled.mockReturnValue(true); canAccessTrip.mockResolvedValue({ id: 1 } as never); });
|
||||
|
||||
it('gates: disabled / unknown view / no user / non-member all return [] (no plugin calls on the first two)', async () => {
|
||||
pluginsEnabled.mockReturnValue(false);
|
||||
@@ -52,7 +52,7 @@ describe('ViewContributionsController', () => {
|
||||
}
|
||||
|
||||
expect((await controller(() => [col()]).c.get('places', '1', req(undefined))).contributions).toEqual([]);
|
||||
canAccessTrip.mockReturnValue(undefined as never);
|
||||
canAccessTrip.mockResolvedValue(undefined as never);
|
||||
expect((await controller(() => [col()]).c.get('day', '1', req(5))).contributions).toEqual([]);
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user