mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-28 07:30:04 +00:00
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.
This commit is contained in:
@@ -138,6 +138,8 @@ describe('GET /api/addons e2e (real auth guard + temp SQLite)', () => {
|
||||
toursWanderer: false,
|
||||
toursHikingMap: false,
|
||||
toursCycleMap: false,
|
||||
// The options themselves, which apply wherever a trip switched Tours on.
|
||||
toursOptions: { wanderer: false, hikingMap: true, cycleMap: true },
|
||||
addons: [
|
||||
{ id: 'packing', name: 'Packing', type: 'trip', icon: 'Backpack', enabled: true },
|
||||
{ id: 'journey', name: 'Journey', type: 'global', icon: 'Compass', enabled: true },
|
||||
|
||||
@@ -62,7 +62,11 @@ vi.mock('../../src/db/database', async () => {
|
||||
};
|
||||
});
|
||||
|
||||
const { isAddonEnabled } = vi.hoisted(() => ({ isAddonEnabled: vi.fn(() => true) }));
|
||||
const { isAddonEnabled, isEnabledForTrip } = vi.hoisted(() => ({
|
||||
isAddonEnabled: vi.fn(() => true),
|
||||
// What the owner chose for Documents on the trip; the instance switch above still has to be on.
|
||||
isEnabledForTrip: vi.fn(async () => true),
|
||||
}));
|
||||
|
||||
/**
|
||||
* The SSRF guard resolves DNS, and `paperless.example.com` does not exist. In
|
||||
@@ -147,7 +151,7 @@ describe('Document sync e2e (real guards + real services + temp SQLite)', () =>
|
||||
imports: [await TestUnitOfWorkModule.forRoot(db), await createTestMikroOrmModule(db), DocSyncModule],
|
||||
})
|
||||
.overrideProvider(AddonsService)
|
||||
.useValue({ isAddonEnabled });
|
||||
.useValue({ isAddonEnabled, isEnabledForTrip });
|
||||
const fakes = providers.map(([, id]) => fakeProvider(id));
|
||||
providers.forEach(([token], i) => {
|
||||
builder = builder.overrideProvider(token).useValue(fakes[i]);
|
||||
@@ -185,6 +189,16 @@ describe('Document sync e2e (real guards + real services + temp SQLite)', () =>
|
||||
|
||||
beforeEach(() => {
|
||||
isAddonEnabled.mockReturnValue(true);
|
||||
isEnabledForTrip.mockResolvedValue(true);
|
||||
});
|
||||
|
||||
it('answers 404 to a member of a trip that has Documents off for itself, the instance on', async () => {
|
||||
isEnabledForTrip.mockResolvedValue(false);
|
||||
const res = await request(server)
|
||||
.get(`/api/trips/${tripId}/docsync/status`)
|
||||
.set('Cookie', sessionCookie(ownerId))
|
||||
.expect(404);
|
||||
expect(res.body).toEqual({ error: 'Documents addon is not enabled' });
|
||||
});
|
||||
|
||||
it('answers 404 rather than 401 when the addon is off, to everyone alike', async () => {
|
||||
|
||||
@@ -61,6 +61,13 @@ const { db } = vi.hoisted(() => {
|
||||
// StorageRegistryService (behind StorageModule, now in this module chain) reads
|
||||
// this at onModuleInit.
|
||||
tmp.exec('CREATE TABLE app_settings (key TEXT PRIMARY KEY, value TEXT);');
|
||||
// Documents is a trip addon: every files route asks whether it applies to its trip
|
||||
// (the trip's own choice, else the instance switch), so both tables are here, Documents on.
|
||||
tmp.exec(`CREATE TABLE addons (id TEXT PRIMARY KEY, name TEXT NOT NULL, description TEXT, type TEXT DEFAULT 'global',
|
||||
icon TEXT, enabled INTEGER DEFAULT 0, config TEXT DEFAULT '{}', sort_order INTEGER DEFAULT 0);`);
|
||||
tmp.exec("INSERT INTO addons (id, name, type, enabled) VALUES ('documents', 'Documents', 'trip', 1);");
|
||||
tmp.exec(`CREATE TABLE trip_addon_overrides (trip_id INTEGER NOT NULL, addon_id TEXT NOT NULL, enabled INTEGER NOT NULL,
|
||||
updated_at TEXT, PRIMARY KEY (trip_id, addon_id));`);
|
||||
return { db: tmp };
|
||||
});
|
||||
|
||||
|
||||
@@ -176,12 +176,14 @@ afterAll(async () => {
|
||||
});
|
||||
|
||||
describe('GET /api/paddle/obstacles', () => {
|
||||
it('PADE2E-001: 404 while Tours is off, ahead of the session check; 401 without a cookie once on', async () => {
|
||||
it('PADE2E-001: 404 while Tours is off for the caller; 401 without a cookie, whatever Tours says', async () => {
|
||||
// The obstacles belong to no one trip: Tours opens them for a caller one of whose trips has it on,
|
||||
// so the addon is asked once the session says who is asking.
|
||||
await setAddonEnabled(orm, 'tours', false);
|
||||
for (const res of [await obstacles(BOX), await obstacles(BOX, USER)]) {
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body).toEqual({ error: 'Tours addon is not enabled' });
|
||||
}
|
||||
const off = await obstacles(BOX, USER);
|
||||
expect(off.status).toBe(404);
|
||||
expect(off.body).toEqual({ error: 'Tours addon is not enabled' });
|
||||
expect((await obstacles(BOX)).status).toBe(401);
|
||||
await setAddonEnabled(orm, 'tours', true);
|
||||
const anonymous = await obstacles(BOX);
|
||||
expect(anonymous.status).toBe(401);
|
||||
|
||||
@@ -387,12 +387,13 @@ describe('Roadtrip e2e (real guard chain + temp SQLite)', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('ROADTRIP-E2E-002: a disabled addon owes an anonymous caller a 404, not a 401', async () => {
|
||||
// The gate leads the chain for this reason: a 401 tells a stranger the
|
||||
// route exists. Both answers refuse; only one of them says nothing.
|
||||
it('ROADTRIP-E2E-002: with the addon off an anonymous caller gets the 401 every trip route answers', async () => {
|
||||
// Whether Road trip applies is the trip's own choice now (a trip may switch it on while the
|
||||
// instance has it off), and only somebody who may see the trip learns it, so the addon gate
|
||||
// follows the auth and trip guards and an anonymous caller hears what it hears on any trip route.
|
||||
await setAddon(false);
|
||||
const res = await request(server).get('/api/trips/5/roadtrip/vias');
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it('ROADTRIP-E2E-003: with the addon on, an anonymous caller gets 401', async () => {
|
||||
|
||||
@@ -79,6 +79,7 @@ const NOT_ROW_IDS: Record<string, string> = {
|
||||
'* /api/plugin-settings/ :id': 'a plugin id is its manifest slug',
|
||||
'* /api/oauth/clients/ :id': 'an OAuth client row id is a generated text key',
|
||||
'PUT /api/admin/addons/:id :id': 'an addon id is its key',
|
||||
'PUT /api/trips/:tripId/addons/:addonId :addonId': 'an addon id is its key',
|
||||
'GET /api/maps/place-photo/:placeId :placeId': 'a maps provider place id is a provider string',
|
||||
'* /api/ :toolCallId': "an assistant tool call id is the model's string",
|
||||
};
|
||||
|
||||
@@ -12,6 +12,7 @@ import { AssignmentParticipants } from '../../src/db/entities/AssignmentParticip
|
||||
import { Days } from '../../src/db/entities/Days.entity';
|
||||
import { Places } from '../../src/db/entities/Places.entity';
|
||||
import { TourActivityExclusions } from '../../src/db/entities/TourActivityExclusions.entity';
|
||||
import { TripAddonOverrides } from '../../src/db/entities/TripAddonOverrides.entity';
|
||||
import { Trips } from '../../src/db/entities/Trips.entity';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
|
||||
@@ -22,7 +23,7 @@ import { ToursModule } from '../../src/nest/tours/tours.module';
|
||||
import { createSnapshotTestDb } from '../helpers/db-mock';
|
||||
import { makeDayAssignment } from '../helpers/factories/itinerary';
|
||||
import { countRows, deleteRows, insertRow, insertRows } from '../helpers/factories/rows';
|
||||
import { setAddonEnabled } from '../helpers/factories/settings';
|
||||
import { setAddonEnabled, setTripAddon } from '../helpers/factories/settings';
|
||||
import { addTripMember } from '../helpers/factories/trips';
|
||||
import { makeUser } from '../helpers/factories/users';
|
||||
import { FakeRealtimeService } from '../helpers/fake-realtime';
|
||||
@@ -218,6 +219,24 @@ describe('Tour activity stats e2e (STA-02)', () => {
|
||||
expect(off.body).toEqual({ error: 'Tours addon is not enabled' });
|
||||
});
|
||||
|
||||
it('STA2-E2E-006: a trip with Tours off adds nothing to the sums and its tours cannot be left out, data kept', async () => {
|
||||
const ridge = await tourOnDay('Ridge', 3);
|
||||
await setTripAddon(orm, TRIP, 'tours', false);
|
||||
try {
|
||||
const off = await request(server).get(STATS).set(as(OWNER));
|
||||
expect(off.status).toBe(200);
|
||||
expect(off.body).toEqual({ entries: [], uncounted: { unassigned: 0, undated: 0 } });
|
||||
const left = await exclude({ place_id: ridge.placeId, excluded: true });
|
||||
expect(left.status).toBe(404);
|
||||
expect(left.body).toEqual({ error: 'Tour not found' });
|
||||
expect(await countRows(orm, TourActivityExclusions)).toBe(0);
|
||||
} finally {
|
||||
await deleteRows(orm, TripAddonOverrides);
|
||||
}
|
||||
const back = await request(server).get(STATS).set(as(OWNER));
|
||||
expect(back.body.entries.map((entry: { place_id: number }) => entry.place_id)).toEqual([ridge.placeId]);
|
||||
});
|
||||
|
||||
it('STA2-E2E-005: a tour on two days counts once, dated on the last of them', async () => {
|
||||
const ridge = await tourOnDay('Ridge', 3);
|
||||
await makeDayAssignment(orm, 4, ridge.placeId);
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
import { DayAssignments } from '../../src/db/entities/DayAssignments.entity';
|
||||
import { Places } from '../../src/db/entities/Places.entity';
|
||||
import { Tours } from '../../src/db/entities/Tours.entity';
|
||||
import { TripAddonOverrides } from '../../src/db/entities/TripAddonOverrides.entity';
|
||||
import { Trips } from '../../src/db/entities/Trips.entity';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
|
||||
@@ -23,7 +24,7 @@ import { ToursModule } from '../../src/nest/tours/tours.module';
|
||||
import { createSnapshotTestDb } from '../helpers/db-mock';
|
||||
import { makePlace } from '../helpers/factories/places';
|
||||
import { countRows, deleteRows, findRow, insertRows } from '../helpers/factories/rows';
|
||||
import { setAddonEnabled } from '../helpers/factories/settings';
|
||||
import { setAddonEnabled, setTripAddon } from '../helpers/factories/settings';
|
||||
import { makeTour } from '../helpers/factories/tours';
|
||||
import { addTripMember } from '../helpers/factories/trips';
|
||||
import { makeUser } from '../helpers/factories/users';
|
||||
@@ -660,6 +661,30 @@ describe('Tours planned e2e (real guards + temp SQLite)', () => {
|
||||
expect(await countRows(orm, Places, { trip: 7 })).toBe(before);
|
||||
});
|
||||
|
||||
it('a trip with Tours off is out of the library: not listed, previewed or taken over, its tours kept', async () => {
|
||||
const ridge = await createViaApi(5);
|
||||
await createViaApi(6, tourBody({ name: 'Valley walk' }));
|
||||
await setTripAddon(orm, 5, 'tours', false);
|
||||
try {
|
||||
const all = await request(server).get('/api/tours/library').set('Cookie', sessionCookie(OWNER));
|
||||
expect(all.body.tours.map((tour: { name: string }) => tour.name)).toEqual(['Valley walk']);
|
||||
expect(all.body.trips).toEqual([{ id: 6, title: 'Other', tour_count: 1 }]);
|
||||
const named = await request(server).get('/api/tours/library?trip_id=5').set('Cookie', sessionCookie(OWNER));
|
||||
expect(named.body.tours).toEqual([]);
|
||||
const preview = await request(server).get(`/api/tours/library/${ridge}`).set('Cookie', sessionCookie(OWNER));
|
||||
expect(preview.status).toBe(404);
|
||||
const taken = await request(server)
|
||||
.post('/api/trips/6/tours/take-over')
|
||||
.set('Cookie', sessionCookie(OWNER))
|
||||
.send({ source_trip_id: 5, source_place_id: ridge });
|
||||
expect(taken.status).toBe(404);
|
||||
expect(taken.body).toEqual({ error: 'Tour not found' });
|
||||
} finally {
|
||||
await deleteRows(orm, TripAddonOverrides);
|
||||
}
|
||||
expect(await findRow(orm, Places, { id: ridge })).toMatchObject({ trip_id: 5 });
|
||||
});
|
||||
|
||||
it('needs place_edit on the trip it writes into, the addon on, a session and a well-formed body', async () => {
|
||||
const source = await createViaApi(6);
|
||||
const viewer = await request(server)
|
||||
|
||||
@@ -0,0 +1,329 @@
|
||||
/**
|
||||
* Per-trip addons, enforced: what a trip's own choice does to the surfaces of
|
||||
* its addons, end to end on the whole app (buildApp, the real guards, the
|
||||
* response contract check, the MCP registry with the host's tool gate).
|
||||
*
|
||||
* Every surface is held both ways: the instance has the addon off and the
|
||||
* trip switched it on (allowed), and the instance has it on and the trip
|
||||
* switched it off (refused with `<Label> addon is not enabled`, data kept).
|
||||
* A trip without a choice follows the instance, so the instance switch now
|
||||
* closes the lists, costs, collab and files routes too.
|
||||
*/
|
||||
import { buildApp } from '../../src/bootstrap';
|
||||
import { BudgetItems } from '../../src/db/entities/BudgetItems.entity';
|
||||
import { Reservations } from '../../src/db/entities/Reservations.entity';
|
||||
import { createLocalMcpServer, McpRegistryService } from '../../src/nest-mcp';
|
||||
import { withRequestContext } from '../../src/nest/database/request-context';
|
||||
import { makeBudgetItem } from '../helpers/factories/budget';
|
||||
import { makeCollabNote } from '../helpers/factories/collab';
|
||||
import { makeTripFile } from '../helpers/factories/files';
|
||||
import { makePackingItem } from '../helpers/factories/packing';
|
||||
import { countRows } from '../helpers/factories/rows';
|
||||
import { setAddonEnabled, setTripAddon } from '../helpers/factories/settings';
|
||||
import { makeTodoItem } from '../helpers/factories/todos';
|
||||
import { addTripMember, makeShareToken, makeTrip } from '../helpers/factories/trips';
|
||||
import { makeUser } from '../helpers/factories/users';
|
||||
import { oneByOne } from '../helpers/one-by-one';
|
||||
import { resetDatabase } from '../helpers/reset-database';
|
||||
import { sessionCookie } from './harness';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import { Client } from '@modelcontextprotocol/sdk/client/index';
|
||||
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory';
|
||||
import type { INestApplication } from '@nestjs/common';
|
||||
|
||||
import request from 'supertest';
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
let app: INestApplication;
|
||||
let orm: MikroORM;
|
||||
|
||||
beforeAll(async () => {
|
||||
app = await buildApp();
|
||||
orm = app.get(MikroORM);
|
||||
}, 60_000);
|
||||
beforeEach(async () => {
|
||||
await resetDatabase(orm);
|
||||
});
|
||||
afterAll(async () => {
|
||||
await app?.close();
|
||||
});
|
||||
|
||||
const TRIP_ADDONS = ['packing', 'budget', 'documents', 'collab', 'roadtrip', 'tours'];
|
||||
|
||||
/**
|
||||
* Every trip addon on for the instance, an owner with two trips, a member on
|
||||
* the first, and a stranger; each trip holds a row of every addon.
|
||||
*/
|
||||
async function world() {
|
||||
await Promise.all(TRIP_ADDONS.map((addonId) => setAddonEnabled(orm, addonId, true)));
|
||||
const { user: owner } = await makeUser(orm);
|
||||
const { user: member } = await makeUser(orm);
|
||||
const { user: stranger } = await makeUser(orm);
|
||||
const chosen = await makeTrip(orm, owner.id, { title: 'Chosen' });
|
||||
const plain = await makeTrip(orm, owner.id, { title: 'Plain' });
|
||||
await addTripMember(orm, chosen.id, member.id, owner.id);
|
||||
await Promise.all(
|
||||
[chosen.id, plain.id].map(async (tripId) => {
|
||||
await makePackingItem(orm, tripId, { name: 'Tent' });
|
||||
await makeTodoItem(orm, tripId, { name: 'Book ferry' });
|
||||
await makeBudgetItem(orm, tripId, { name: 'Hotel' });
|
||||
await makeCollabNote(orm, tripId, owner.id, { title: 'Ideas' });
|
||||
await makeTripFile(orm, tripId, { original_name: 'ticket.pdf' });
|
||||
}),
|
||||
);
|
||||
return { owner, member, stranger, chosen, plain };
|
||||
}
|
||||
|
||||
const get = (userId: number | null, path: string) => {
|
||||
const req = request(app.getHttpServer()).get(path);
|
||||
return userId === null ? req : req.set('Cookie', sessionCookie(userId));
|
||||
};
|
||||
|
||||
/** One read route per trip addon whose REST surface had no addon check before. */
|
||||
const ROUTES: ReadonlyArray<[string, string, (tripId: number) => string]> = [
|
||||
['packing', 'Packing', (id) => `/api/trips/${id}/packing`],
|
||||
['packing', 'Packing', (id) => `/api/trips/${id}/todo`],
|
||||
['budget', 'Costs', (id) => `/api/trips/${id}/budget`],
|
||||
['collab', 'Collab', (id) => `/api/trips/${id}/collab/notes`],
|
||||
['documents', 'Documents', (id) => `/api/trips/${id}/files`],
|
||||
['roadtrip', 'Road trip', (id) => `/api/trips/${id}/roadtrip/vias`],
|
||||
['tours', 'Tours', (id) => `/api/trips/${id}/tours`],
|
||||
];
|
||||
|
||||
describe('trip-scoped REST', () => {
|
||||
it.each(ROUTES)(
|
||||
'TRIPADDON-ENF-001: %s at %s: a trip that switched it off answers 404 while the instance has it on',
|
||||
async (addonId, label, path) => {
|
||||
const { owner, member, chosen, plain } = await world();
|
||||
await setAddonEnabled(orm, addonId, true);
|
||||
await setTripAddon(orm, chosen.id, addonId, false);
|
||||
const [own, asMember, other] = await oneByOne(
|
||||
[
|
||||
() => get(owner.id, path(chosen.id)),
|
||||
() => get(member.id, path(chosen.id)),
|
||||
() => get(owner.id, path(plain.id)),
|
||||
],
|
||||
(send) => send(),
|
||||
);
|
||||
expect(own.status).toBe(404);
|
||||
expect(own.body).toEqual({ error: `${label} addon is not enabled` });
|
||||
expect(asMember.status).toBe(404);
|
||||
expect(other.status).toBe(200);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(ROUTES)(
|
||||
'TRIPADDON-ENF-002: %s at %s: a trip that switched it on answers while the instance has it off, the others 404',
|
||||
async (addonId, label, path) => {
|
||||
const { owner, member, chosen, plain } = await world();
|
||||
await setAddonEnabled(orm, addonId, false);
|
||||
await setTripAddon(orm, chosen.id, addonId, true);
|
||||
const [own, asMember, other] = await oneByOne(
|
||||
[
|
||||
() => get(owner.id, path(chosen.id)),
|
||||
() => get(member.id, path(chosen.id)),
|
||||
() => get(owner.id, path(plain.id)),
|
||||
],
|
||||
(send) => send(),
|
||||
);
|
||||
expect(own.status).toBe(200);
|
||||
expect(asMember.status).toBe(200);
|
||||
expect(other.status).toBe(404);
|
||||
expect(other.body).toEqual({ error: `${label} addon is not enabled` });
|
||||
},
|
||||
);
|
||||
|
||||
it('TRIPADDON-ENF-003: a stranger hears "Trip not found" and nobody signed in a 401, whatever the trip chose', async () => {
|
||||
const { stranger, chosen } = await world();
|
||||
await setTripAddon(orm, chosen.id, 'budget', false);
|
||||
const [unseen, anonymous] = await oneByOne(
|
||||
[() => get(stranger.id, `/api/trips/${chosen.id}/budget`), () => get(null, `/api/trips/${chosen.id}/budget`)],
|
||||
(send) => send(),
|
||||
);
|
||||
expect(unseen.status).toBe(404);
|
||||
expect(unseen.body).toEqual({ error: 'Trip not found' });
|
||||
expect(anonymous.status).toBe(401);
|
||||
});
|
||||
|
||||
it('TRIPADDON-ENF-004: the multipart upload refuses in its handler, so the caller reads the 404 body', async () => {
|
||||
const { owner, chosen } = await world();
|
||||
await setTripAddon(orm, chosen.id, 'documents', false);
|
||||
const res = await request(app.getHttpServer())
|
||||
.post(`/api/trips/${chosen.id}/files`)
|
||||
.set('Cookie', sessionCookie(owner.id))
|
||||
.attach('file', Buffer.from('%PDF-1.4 test'), 'ticket.pdf');
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body).toEqual({ error: 'Documents addon is not enabled' });
|
||||
});
|
||||
|
||||
it('TRIPADDON-ENF-005: switching back on brings every row back where it was', async () => {
|
||||
const { owner, chosen } = await world();
|
||||
await setTripAddon(orm, chosen.id, 'packing', false);
|
||||
expect((await get(owner.id, `/api/trips/${chosen.id}/packing`)).status).toBe(404);
|
||||
await setTripAddon(orm, chosen.id, 'packing', true);
|
||||
const res = await get(owner.id, `/api/trips/${chosen.id}/packing`);
|
||||
expect(res.status).toBe(200);
|
||||
expect((res.body.items as Array<{ name: string }>).map((item) => item.name)).toEqual(['Tent']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('routes about no one trip', () => {
|
||||
it('TRIPADDON-ENF-010: the tour library opens for a user one of whose trips switched Tours on', async () => {
|
||||
const { owner, member, stranger, chosen } = await world();
|
||||
await setAddonEnabled(orm, 'tours', false);
|
||||
expect((await get(owner.id, '/api/tours/library')).status).toBe(404);
|
||||
await setTripAddon(orm, chosen.id, 'tours', true);
|
||||
const [own, asMember, other] = await oneByOne(
|
||||
[
|
||||
() => get(owner.id, '/api/tours/library'),
|
||||
() => get(member.id, '/api/tours/library'),
|
||||
() => get(stranger.id, '/api/tours/library'),
|
||||
],
|
||||
(send) => send(),
|
||||
);
|
||||
expect(own.status).toBe(200);
|
||||
expect(asMember.status).toBe(200);
|
||||
expect(other.status).toBe(404);
|
||||
expect(other.body).toEqual({ error: 'Tours addon is not enabled' });
|
||||
});
|
||||
|
||||
it('TRIPADDON-ENF-011: a trip that switched Tours off closes the library for nobody while the instance has it on', async () => {
|
||||
const { owner, chosen } = await world();
|
||||
await setTripAddon(orm, chosen.id, 'tours', false);
|
||||
expect((await get(owner.id, '/api/tours/library')).status).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
describe('what leaves the trip in bulk', () => {
|
||||
it('TRIPADDON-ENF-020: the offline bundle sends empty lists for the addons the trip has off', async () => {
|
||||
const { owner, chosen } = await world();
|
||||
await setTripAddon(orm, chosen.id, 'packing', false);
|
||||
await setTripAddon(orm, chosen.id, 'documents', false);
|
||||
const res = await get(owner.id, `/api/trips/${chosen.id}/bundle`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.packingItems).toEqual([]);
|
||||
expect(res.body.todoItems).toEqual([]);
|
||||
expect(res.body.files).toEqual([]);
|
||||
expect((res.body.budgetItems as Array<{ name: string }>).map((item) => item.name)).toEqual(['Hotel']);
|
||||
});
|
||||
|
||||
it('TRIPADDON-ENF-021: the offline bundle carries an addon a trip switched on while the instance has it off', async () => {
|
||||
const { owner, chosen, plain } = await world();
|
||||
await setAddonEnabled(orm, 'budget', false);
|
||||
await setTripAddon(orm, chosen.id, 'budget', true);
|
||||
const [on, off] = await oneByOne(
|
||||
[() => get(owner.id, `/api/trips/${chosen.id}/bundle`), () => get(owner.id, `/api/trips/${plain.id}/bundle`)],
|
||||
(send) => send(),
|
||||
);
|
||||
expect((on.body.budgetItems as unknown[]).length).toBe(1);
|
||||
expect(off.body.budgetItems).toEqual([]);
|
||||
});
|
||||
|
||||
it('TRIPADDON-ENF-022: a share link leaves out what the trip has off, whatever the link allows', async () => {
|
||||
const { owner, chosen } = await world();
|
||||
const share = await makeShareToken(orm, chosen.id, owner.id, {
|
||||
token: 'trip-addon-share',
|
||||
share_packing: 1,
|
||||
share_budget: 1,
|
||||
share_collab: 1,
|
||||
});
|
||||
await setTripAddon(orm, chosen.id, 'budget', false);
|
||||
const res = await get(null, `/api/shared/${share.token}`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.permissions).toMatchObject({ share_packing: true, share_budget: false, share_collab: true });
|
||||
expect((res.body.packing as unknown[]).length).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
/** One MCP tool call as `userId` through a real session: its JSON, or its error text. */
|
||||
async function callTool(userId: number, name: string, args: Record<string, unknown>) {
|
||||
const server = createLocalMcpServer('TREK trip addon enforcement e2e');
|
||||
const around = (_info: unknown, call: () => unknown): unknown => withRequestContext(orm, call);
|
||||
await withRequestContext(orm, () =>
|
||||
app
|
||||
.get(McpRegistryService)
|
||||
.attach(server, { userId, scopes: null, isStaticToken: false }, { include: (kind) => kind === 'tool', around }),
|
||||
);
|
||||
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
||||
const client = new Client({ name: 'trip-addon-enforcement-e2e', version: '1.0.0' });
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
try {
|
||||
const listed = (await client.listTools()).tools.map((tool) => tool.name);
|
||||
if (!listed.includes(name)) return { listed: false, answer: null, error: null };
|
||||
const result = await client.callTool({ name, arguments: args });
|
||||
const content = Array.isArray(result.content) ? (result.content as Array<{ text?: string }>) : [];
|
||||
const text = content[0]?.text ?? '';
|
||||
return result.isError === true
|
||||
? { listed: true, answer: null, error: text }
|
||||
: { listed: true, answer: JSON.parse(text) as Record<string, unknown>, error: null };
|
||||
} finally {
|
||||
await client.close();
|
||||
await server.close();
|
||||
}
|
||||
}
|
||||
|
||||
describe('MCP', () => {
|
||||
it('TRIPADDON-ENF-030: a trip that switched Lists off refuses the tool for that trip and keeps it for the others', async () => {
|
||||
const { owner, chosen, plain } = await world();
|
||||
await setTripAddon(orm, chosen.id, 'packing', false);
|
||||
const refused = await callTool(owner.id, 'list_packing_items', { tripId: chosen.id });
|
||||
expect(refused.error).toBe('Packing addon is not enabled');
|
||||
const other = await callTool(owner.id, 'list_packing_items', { tripId: plain.id });
|
||||
expect(other.error).toBeNull();
|
||||
expect(other.answer).not.toBeNull();
|
||||
});
|
||||
|
||||
it('TRIPADDON-ENF-031: with the instance off a tool is offered to whoever has a trip that switched it on, for that trip', async () => {
|
||||
const { owner, stranger, chosen, plain } = await world();
|
||||
await setAddonEnabled(orm, 'packing', false);
|
||||
expect((await callTool(owner.id, 'list_packing_items', { tripId: chosen.id })).listed).toBe(false);
|
||||
await setTripAddon(orm, chosen.id, 'packing', true);
|
||||
const allowed = await callTool(owner.id, 'list_packing_items', { tripId: chosen.id });
|
||||
expect(allowed.error).toBeNull();
|
||||
const elsewhere = await callTool(owner.id, 'list_packing_items', { tripId: plain.id });
|
||||
expect(elsewhere.error).toBe('Packing addon is not enabled');
|
||||
expect((await callTool(stranger.id, 'list_packing_items', { tripId: chosen.id })).listed).toBe(false);
|
||||
});
|
||||
|
||||
it('TRIPADDON-ENF-032: a trip the caller cannot see gets the tool\'s own "not found", never the addon answer', async () => {
|
||||
const { stranger, chosen } = await world();
|
||||
await setTripAddon(orm, chosen.id, 'budget', false);
|
||||
await setTripAddon(orm, (await makeTrip(orm, stranger.id)).id, 'budget', true);
|
||||
const res = await callTool(stranger.id, 'list_settlements', { tripId: chosen.id });
|
||||
expect(res.listed).toBe(true);
|
||||
expect(res.error).not.toBe('Costs addon is not enabled');
|
||||
});
|
||||
|
||||
it('TRIPADDON-ENF-033: the trip summary leaves out the sections of the addons the trip has off', async () => {
|
||||
const { owner, chosen } = await world();
|
||||
await setTripAddon(orm, chosen.id, 'packing', false);
|
||||
await setTripAddon(orm, chosen.id, 'budget', false);
|
||||
const res = await callTool(owner.id, 'get_trip_summary', { tripId: chosen.id });
|
||||
expect(res.error).toBeNull();
|
||||
expect(res.answer).not.toHaveProperty('packing');
|
||||
expect(res.answer).not.toHaveProperty('budget');
|
||||
});
|
||||
});
|
||||
|
||||
describe('what a booking writes into Costs', () => {
|
||||
it('TRIPADDON-ENF-040: a booking with a price on a trip with Costs off is written without its cost, REST and MCP alike', async () => {
|
||||
const { owner, chosen } = await world();
|
||||
await setTripAddon(orm, chosen.id, 'budget', false);
|
||||
const rest = await request(app.getHttpServer())
|
||||
.post(`/api/trips/${chosen.id}/reservations`)
|
||||
.set('Cookie', sessionCookie(owner.id))
|
||||
.send({ title: 'Hut night', type: 'other', create_budget_entry: { total_price: 80 } });
|
||||
expect(rest.status).toBe(201);
|
||||
const tool = await callTool(owner.id, 'create_reservation', {
|
||||
tripId: chosen.id,
|
||||
title: 'Museum',
|
||||
type: 'event',
|
||||
price: 20,
|
||||
});
|
||||
expect(tool.error).toBeNull();
|
||||
expect(await countRows(orm, Reservations, { trip: chosen.id })).toBe(2);
|
||||
// Only the cost world() made before; the trip keeps it while Costs is off.
|
||||
expect(await countRows(orm, BudgetItems, { trip: chosen.id })).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,250 @@
|
||||
/**
|
||||
* Per-trip addons end to end: GET and PUT /api/trips/:tripId/addons and the
|
||||
* MCP tools get_trip_addons and set_trip_addon on the whole app (buildApp, the
|
||||
* real guards, the response contract check, the registry with its scopes and
|
||||
* error mapper), seeded through the ORM factories.
|
||||
*
|
||||
* Who may do what: every member reads the list, only the owner changes it. A
|
||||
* member and an admin who does not own the trip get a 403, somebody who
|
||||
* cannot see the trip a 404, and nothing is written for either.
|
||||
*/
|
||||
import { buildApp } from '../../src/bootstrap';
|
||||
import { TripAddonOverrides } from '../../src/db/entities/TripAddonOverrides.entity';
|
||||
import { createLocalMcpServer, McpRegistryService } from '../../src/nest-mcp';
|
||||
import { TRIP_ADDON_NOT_FOUND, TRIP_ADDON_OWNER_ONLY } from '../../src/nest/addons/trip-addons.service';
|
||||
import { withRequestContext } from '../../src/nest/database/request-context';
|
||||
import { countRows } from '../helpers/factories/rows';
|
||||
import { setAddonEnabled } from '../helpers/factories/settings';
|
||||
import { addTripMember, makeTrip } from '../helpers/factories/trips';
|
||||
import { makeAdmin, makeUser } from '../helpers/factories/users';
|
||||
import { spyOnRealtime, type RealtimeSpies } from '../helpers/fake-realtime';
|
||||
import { oneByOne } from '../helpers/one-by-one';
|
||||
import { resetDatabase } from '../helpers/reset-database';
|
||||
import { sessionCookie } from './harness';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import { Client } from '@modelcontextprotocol/sdk/client/index';
|
||||
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory';
|
||||
import type { INestApplication } from '@nestjs/common';
|
||||
import type { TripAddon } from '@trek/shared';
|
||||
|
||||
import request from 'supertest';
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
let app: INestApplication;
|
||||
let orm: MikroORM;
|
||||
let spies: RealtimeSpies;
|
||||
|
||||
beforeAll(async () => {
|
||||
app = await buildApp();
|
||||
orm = app.get(MikroORM);
|
||||
spies = spyOnRealtime(app);
|
||||
}, 60_000);
|
||||
beforeEach(async () => {
|
||||
await resetDatabase(orm);
|
||||
spies.broadcast.mockClear();
|
||||
});
|
||||
afterAll(async () => {
|
||||
await app?.close();
|
||||
});
|
||||
|
||||
/** An owner with a trip, a member on it, an admin on it, an admin off it and a stranger. */
|
||||
async function world() {
|
||||
const { user: owner } = await makeUser(orm);
|
||||
const { user: member } = await makeUser(orm);
|
||||
const { user: adminMember } = await makeAdmin(orm);
|
||||
const { user: admin } = await makeAdmin(orm);
|
||||
const { user: stranger } = await makeUser(orm);
|
||||
const trip = await makeTrip(orm, owner.id, { title: 'Porto' });
|
||||
await addTripMember(orm, trip.id, member.id, owner.id);
|
||||
await addTripMember(orm, trip.id, adminMember.id, owner.id);
|
||||
return { owner, member, adminMember, admin, stranger, trip };
|
||||
}
|
||||
|
||||
const get = (userId: number, tripId: number | string) =>
|
||||
request(app.getHttpServer()).get(`/api/trips/${tripId}/addons`).set('Cookie', sessionCookie(userId));
|
||||
|
||||
const put = (userId: number, tripId: number, addonId: string, body: unknown, socketId?: string) => {
|
||||
const req = request(app.getHttpServer())
|
||||
.put(`/api/trips/${tripId}/addons/${addonId}`)
|
||||
.set('Cookie', sessionCookie(userId));
|
||||
if (socketId) req.set('X-Socket-Id', socketId);
|
||||
return req.send(body as object);
|
||||
};
|
||||
|
||||
const entry = (addons: TripAddon[], id: string) => addons.find((a) => a.id === id);
|
||||
|
||||
/** One MCP tool call as `userId` through a real session: its JSON or its error text. */
|
||||
async function callTool(userId: number, name: string, args: Record<string, unknown>) {
|
||||
const server = createLocalMcpServer('TREK trip addons e2e');
|
||||
const around = (_info: unknown, call: () => unknown): unknown => withRequestContext(orm, call);
|
||||
await withRequestContext(orm, () =>
|
||||
app
|
||||
.get(McpRegistryService)
|
||||
.attach(server, { userId, scopes: null, isStaticToken: false }, { include: (kind) => kind === 'tool', around }),
|
||||
);
|
||||
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
||||
const client = new Client({ name: 'trip-addons-e2e', version: '1.0.0' });
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
try {
|
||||
const result = await client.callTool({ name, arguments: args });
|
||||
const content = Array.isArray(result.content) ? (result.content as Array<{ text?: string }>) : [];
|
||||
const text = content[0]?.text ?? '';
|
||||
if (result.isError === true) return { answer: null, error: text };
|
||||
return { answer: JSON.parse(text) as { tripId: number; addons: TripAddon[] }, error: null };
|
||||
} finally {
|
||||
await client.close();
|
||||
await server.close();
|
||||
}
|
||||
}
|
||||
|
||||
describe('GET /api/trips/:tripId/addons', () => {
|
||||
it('TRIPADDON-E2E-001: every member reads the trip addons with their instance state', async () => {
|
||||
const { owner, member, trip } = await world();
|
||||
for (const res of await oneByOne([owner.id, member.id], (userId) => get(userId, trip.id))) {
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.tripId).toBe(trip.id);
|
||||
const ids = (res.body.addons as TripAddon[]).map((a) => a.id);
|
||||
expect(ids).toEqual(expect.arrayContaining(['packing', 'budget', 'documents', 'collab', 'roadtrip', 'tours']));
|
||||
expect(ids).not.toContain('memories');
|
||||
for (const addon of res.body.addons as TripAddon[]) {
|
||||
expect(addon.overridden).toBe(false);
|
||||
expect(addon.enabled).toBe(addon.instanceEnabled);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('TRIPADDON-E2E-002: somebody who cannot see the trip, an admin included, gets a 404; nobody signed in a 401', async () => {
|
||||
const { admin, stranger, trip } = await world();
|
||||
for (const res of await oneByOne([admin.id, stranger.id], (userId) => get(userId, trip.id))) {
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body).toEqual({ error: 'Trip not found' });
|
||||
}
|
||||
expect((await request(app.getHttpServer()).get(`/api/trips/${trip.id}/addons`)).status).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
describe('PUT /api/trips/:tripId/addons/:addonId', () => {
|
||||
it('TRIPADDON-E2E-010: the owner switches costs off for the trip; every other tab gets the list', async () => {
|
||||
const { owner, member, trip } = await world();
|
||||
const res = await put(owner.id, trip.id, 'budget', { enabled: false }, 'sock-owner');
|
||||
expect(res.status).toBe(200);
|
||||
expect(entry(res.body.addons, 'budget')).toMatchObject({ enabled: false, instanceEnabled: true, overridden: true });
|
||||
expect(spies.broadcast).toHaveBeenCalledWith(
|
||||
String(trip.id),
|
||||
'tripAddons:changed',
|
||||
{ addons: res.body.addons },
|
||||
'sock-owner',
|
||||
);
|
||||
const seen = await get(member.id, trip.id);
|
||||
expect(entry(seen.body.addons, 'budget')).toMatchObject({ enabled: false, overridden: true });
|
||||
});
|
||||
|
||||
it('TRIPADDON-E2E-011: a trip may switch an addon on that the instance has off', async () => {
|
||||
const { owner, trip } = await world();
|
||||
await setAddonEnabled(orm, 'roadtrip', false);
|
||||
const res = await put(owner.id, trip.id, 'roadtrip', { enabled: true });
|
||||
expect(res.status).toBe(200);
|
||||
expect(entry(res.body.addons, 'roadtrip')).toMatchObject({
|
||||
enabled: true,
|
||||
instanceEnabled: false,
|
||||
overridden: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('TRIPADDON-E2E-012: null goes back to the instance setting and drops the row', async () => {
|
||||
const { owner, trip } = await world();
|
||||
await put(owner.id, trip.id, 'budget', { enabled: false });
|
||||
const res = await put(owner.id, trip.id, 'budget', { enabled: null });
|
||||
expect(res.status).toBe(200);
|
||||
expect(entry(res.body.addons, 'budget')).toMatchObject({ enabled: true, overridden: false });
|
||||
expect(await countRows(orm, TripAddonOverrides, { trip: trip.id })).toBe(0);
|
||||
});
|
||||
|
||||
it('TRIPADDON-E2E-013: a member and an admin on the trip are refused with 403; nothing is written or sent', async () => {
|
||||
const { member, adminMember, trip } = await world();
|
||||
const refused = await oneByOne([member.id, adminMember.id], (userId) =>
|
||||
put(userId, trip.id, 'budget', { enabled: false }),
|
||||
);
|
||||
for (const res of refused) {
|
||||
expect(res.status).toBe(403);
|
||||
expect(res.body).toEqual({ error: TRIP_ADDON_OWNER_ONLY });
|
||||
}
|
||||
expect(await countRows(orm, TripAddonOverrides, { trip: trip.id })).toBe(0);
|
||||
expect(spies.broadcast).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('TRIPADDON-E2E-014: an admin off the trip and a stranger get a 404', async () => {
|
||||
const { admin, stranger, trip } = await world();
|
||||
const unseen = await oneByOne([admin.id, stranger.id], (userId) =>
|
||||
put(userId, trip.id, 'budget', { enabled: false }),
|
||||
);
|
||||
for (const res of unseen) {
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body).toEqual({ error: 'Trip not found' });
|
||||
}
|
||||
expect(await countRows(orm, TripAddonOverrides, { trip: trip.id })).toBe(0);
|
||||
});
|
||||
|
||||
it('TRIPADDON-E2E-015: an id that names no trip addon is a 404, a body that is no choice a 400', async () => {
|
||||
const { owner, trip } = await world();
|
||||
const unknown = await oneByOne(['vacay', 'memories', 'no_such_addon'], (addonId) =>
|
||||
put(owner.id, trip.id, addonId, { enabled: true }),
|
||||
);
|
||||
for (const res of unknown) {
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body).toEqual({ error: TRIP_ADDON_NOT_FOUND });
|
||||
}
|
||||
const malformed = await oneByOne([{}, { enabled: 'yes' }, { enabled: true, extra: 1 }], (body) =>
|
||||
put(owner.id, trip.id, 'budget', body),
|
||||
);
|
||||
expect(malformed.map((res) => res.status)).toEqual([400, 400, 400]);
|
||||
expect(await countRows(orm, TripAddonOverrides, { trip: trip.id })).toBe(0);
|
||||
});
|
||||
|
||||
it('TRIPADDON-E2E-016: a copied trip keeps the switches of its source', async () => {
|
||||
const { owner, trip } = await world();
|
||||
await put(owner.id, trip.id, 'budget', { enabled: false });
|
||||
const copy = await request(app.getHttpServer())
|
||||
.post(`/api/trips/${trip.id}/copy`)
|
||||
.set('Cookie', sessionCookie(owner.id))
|
||||
.send({ title: 'Porto again' });
|
||||
expect(copy.status).toBe(201);
|
||||
const res = await get(owner.id, copy.body.trip.id as number);
|
||||
expect(entry(res.body.addons, 'budget')).toMatchObject({ enabled: false, overridden: true });
|
||||
});
|
||||
});
|
||||
|
||||
describe('MCP get_trip_addons and set_trip_addon', () => {
|
||||
it('TRIPADDON-E2E-020: a member reads the list; somebody who cannot see the trip is told so', async () => {
|
||||
const { member, stranger, trip } = await world();
|
||||
const read = await callTool(member.id, 'get_trip_addons', { tripId: trip.id });
|
||||
expect(read.answer?.tripId).toBe(trip.id);
|
||||
expect(entry(read.answer?.addons ?? [], 'budget')).toMatchObject({ overridden: false });
|
||||
expect((await callTool(stranger.id, 'get_trip_addons', { tripId: trip.id })).error).toBe(
|
||||
'Trip not found or access denied.',
|
||||
);
|
||||
});
|
||||
|
||||
it('TRIPADDON-E2E-021: only the owner switches, with the REST refusal for anybody else', async () => {
|
||||
const { owner, member, adminMember, stranger, trip } = await world();
|
||||
const refused = await oneByOne([member.id, adminMember.id], (userId) =>
|
||||
callTool(userId, 'set_trip_addon', { tripId: trip.id, addonId: 'budget', enabled: false }),
|
||||
);
|
||||
expect(refused.map((res) => res.error)).toEqual([TRIP_ADDON_OWNER_ONLY, TRIP_ADDON_OWNER_ONLY]);
|
||||
const unseen = await callTool(stranger.id, 'set_trip_addon', {
|
||||
tripId: trip.id,
|
||||
addonId: 'budget',
|
||||
enabled: false,
|
||||
});
|
||||
expect(unseen.error).toBe('Trip not found or access denied.');
|
||||
expect(await countRows(orm, TripAddonOverrides, { trip: trip.id })).toBe(0);
|
||||
|
||||
const done = await callTool(owner.id, 'set_trip_addon', { tripId: trip.id, addonId: 'budget', enabled: false });
|
||||
expect(entry(done.answer?.addons ?? [], 'budget')).toMatchObject({ enabled: false, overridden: true });
|
||||
const unknown = await callTool(owner.id, 'set_trip_addon', { tripId: trip.id, addonId: 'vacay', enabled: true });
|
||||
expect(unknown.error).toBe(TRIP_ADDON_NOT_FOUND);
|
||||
const reset = await callTool(owner.id, 'set_trip_addon', { tripId: trip.id, addonId: 'budget', enabled: null });
|
||||
expect(entry(reset.answer?.addons ?? [], 'budget')).toMatchObject({ overridden: false });
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user