Files
TREK/server/tests/unit/plugins/view-contributions.controller.test.ts
T
Maurice 3f38621024 feat(server): let a trip owner switch trip addons for one trip
A trip can now turn a trip addon (lists, costs, documents, collab, road
trip, tours) on or off for itself, whatever the instance switch says. No
row in the new trip_addon_overrides table means the trip follows the
instance; a row is the owner's choice. Going back to the instance setting
deletes the row, and no addon data is touched either way.

- GET/PUT /api/trips/:tripId/addons[/:addonId] (every member reads, the
  owner writes) and the MCP tools get_trip_addons and set_trip_addon, on
  the shared tripAddons contract; tripAddons:changed tells the members.
- Every trip-scoped addon surface asks the trip: REST through
  TripAddonGuard, MCP through a per-call gate on the named or pinned trip,
  plugin RPC and events, the share link, the offline bundle, reminders,
  doc sync, the assistant (tools, keep_attached_file), booking costs, the
  trip summary prompt, and the cross-trip tour reads (library, Atlas
  stats, collection save).
- Routes without a trip open while the addon is on in any of the user's
  trips. Switching an addon on that the instance has off ends the members'
  MCP sessions so they reconnect with its tools.
- A copied trip takes its owner's choices along.

Behaviour changes: an anonymous call to an addon route that is off now
gets 401 instead of 404, and with an instance switch off the packing,
todo and files plugin RPC methods, the files MCP tools, todo reminder
mails, core plugin events, plugin view contributions, the share link's
lists, costs and chat sections and the offline bundle's lists follow it.
2026-11-21 13:23:09 +01:00

169 lines
7.6 KiB
TypeScript

/**
* ViewContributionsController (#plugins, UI-contribution registry): host-rendered
* columns/actions plugins add into a native planner view. Mirrors
* place-details.controller (gate + fail-safe) and additionally proves the mandatory
* hardening: server-side normalization, a URL-scheme allowlist (no click-XSS), and
* length/count caps.
*/
import type { TripsRepository } from '../../../src/db/repositories/Trips.repository';
import type { AddonsService } from '../../../src/nest/addons/addons.service';
import { ViewContributionsController } from '../../../src/nest/plugins/contributions/view-contributions.controller';
import type { PluginHooks } from '../../../src/nest/plugins/plugin-hooks.service';
import { TripAccessService } from '../../../src/nest/trip-membership/trip-access.service';
import { describe, it, expect, vi, beforeEach } from 'vitest';
const { canAccessTrip, pluginsEnabled } = vi.hoisted(() => ({
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 }));
vi.mock('../../../src/nest/plugins/kill-switch', () => ({ pluginsEnabled }));
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const req = (id?: number) => ({ user: id === undefined ? undefined : { id } }) as any;
function controller(invoke: (id: string) => unknown, providers = ['p1'], offForTrip: readonly string[] = []) {
const runtime = {
providersOf: vi.fn(() => providers),
tableContributions: vi.fn(async (id: string) => invoke(id)),
} as unknown as PluginHooks;
return {
c: new ViewContributionsController(
runtime,
new TripAccessService({ findAccessible: canAccessTrip } as unknown as TripsRepository),
{
isEnabledForTrip: vi.fn(async (_tripId: number, id: string) => !offForTrip.includes(id)),
} as unknown as AddonsService,
),
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.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);
let x = controller(() => [col()]);
expect(await x.c.get('reservations', '1', req(5))).toEqual({ contributions: [] });
expect(x.runtime.providersOf).not.toHaveBeenCalled();
pluginsEnabled.mockReturnValue(true);
x = controller(() => [col()]);
expect(await x.c.get('bogus', '1', req(5))).toEqual({ contributions: [] }); // view not whitelisted
expect(x.runtime.providersOf).not.toHaveBeenCalled();
// costs/packing/files were added to the whitelist — they must be accepted (providers consulted).
for (const view of ['costs', 'packing', 'files']) {
const y = controller(() => [col()]);
expect((await y.c.get(view, '1', req(5))).contributions.length).toBe(1);
expect(y.runtime.providersOf).toHaveBeenCalledWith('tableContributor');
}
expect((await controller(() => [col()]).c.get('places', '1', req(undefined))).contributions).toEqual([]);
canAccessTrip.mockResolvedValue(undefined as never);
expect((await controller(() => [col()]).c.get('day', '1', req(5))).contributions).toEqual([]);
});
it('column: keeps http/https/mailto urls, DROPS javascript:/data:, caps lengths, defaults a bad tone', async () => {
const { c } = controller(() => [
col({ id: 'ok', label: 'Crowd', value: 'Quiet', url: 'https://x.test', tone: 'success', icon: 'Users' }),
col({ id: 'js', label: 'Evil', url: 'javascript:alert(1)' }),
col({ id: 'data', label: 'Evil2', url: 'data:text/html,x' }),
col({ id: 'mail', label: 'Mail', url: 'mailto:a@b.c' }),
col({ id: 'long', label: 'L'.repeat(200), value: 'V'.repeat(500), tone: 'nope' }),
]);
const out = (await c.get('reservations', '1', req(5))).contributions;
expect(out[0]).toEqual({
kind: 'column',
pluginId: 'p1',
entityId: 1,
id: 'ok',
label: 'Crowd',
value: 'Quiet',
url: 'https://x.test',
icon: 'Users',
tone: 'success',
});
expect((out[1] as { url?: string }).url).toBeUndefined(); // javascript: rejected
expect((out[2] as { url?: string }).url).toBeUndefined(); // data: rejected
expect((out[3] as { url?: string }).url).toBe('mailto:a@b.c');
expect((out[4] as { label: string }).label).toHaveLength(64);
expect((out[4] as { value: string }).value).toHaveLength(256);
expect((out[4] as { tone: string }).tone).toBe('default');
});
it('action: keeps valid frame/route targets, drops malformed ones', async () => {
const { c } = controller(() => [
act({ id: 'frame', target: { kind: 'frame', sub: '/ui' } }),
act({ id: 'route', target: { kind: 'route', method: 'POST', sub: '/do' } }),
act({ id: 'badmethod', target: { kind: 'route', method: 'DELETE', sub: '/x' } }),
act({ id: 'nosub', target: { kind: 'frame' } }),
act({ id: 'badkind', target: { kind: 'nope', sub: '/x' } }),
]);
const out = (await c.get('reservations', '1', req(5))).contributions;
expect(out.map((o) => o.id)).toEqual(['frame', 'route']);
});
it('drops entries missing entityId/id/label, non-objects, and unknown kinds', async () => {
const { c } = controller(() => [
col({ entityId: undefined }),
col({ id: '' }),
col({ label: '' }),
{ kind: 'mystery', entityId: 1, id: 'x', label: 'y' },
'not-an-object',
null,
col({ id: 'good' }),
]);
const out = (await c.get('places', '1', req(5))).contributions;
expect(out.map((o) => o.id)).toEqual(['good']);
});
it('caps per-provider counts: <=20 columns and <=10 actions', async () => {
const many = [
...Array.from({ length: 30 }, (_, i) => col({ id: `c${i}` })),
...Array.from({ length: 15 }, (_, i) => act({ id: `a${i}` })),
];
const { c } = controller(() => many);
const out = (await c.get('day', '1', req(5))).contributions;
expect(out.filter((o) => o.kind === 'column')).toHaveLength(20);
expect(out.filter((o) => o.kind === 'action')).toHaveLength(10);
});
it('merges providers, skips one that throws, and passes (view, tripId) + user to the hook', async () => {
const { c, runtime } = controller(
(id) => {
if (id === 'p2') throw new Error('slow');
return [col({ id: 'from-p1' })];
},
['p1', 'p2'],
);
const out = (await c.get('reservations', '1', req(5))).contributions;
expect(out.map((o) => o.id)).toEqual(['from-p1']);
expect(runtime.tableContributions).toHaveBeenCalledWith('p1', 'reservations', 1, 5);
});
it('VIEWCONTRIB-ADDON: a view whose addon is off for the trip gets nothing, the other views still do', async () => {
const { c, runtime } = controller(() => [col()], ['p1'], ['budget', 'packing']);
const off = await Promise.all(['costs', 'packing', 'todos'].map((view) => c.get(view, '1', req(5))));
expect(off.map((answer) => answer.contributions)).toEqual([[], [], []]);
expect(runtime.tableContributions).not.toHaveBeenCalled();
expect((await c.get('files', '1', req(5))).contributions).toHaveLength(1);
expect((await c.get('reservations', '1', req(5))).contributions).toHaveLength(1);
});
});