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:
Maurice
2026-11-21 13:23:02 +01:00
parent 2f7b8357ce
commit 3f38621024
203 changed files with 3710 additions and 498 deletions
+44 -2
View File
@@ -37,7 +37,15 @@ const req = (method: string, params: Record<string, unknown> = {}): RpcRequest =
* `linkedTo` the booking cost 5 is linked to before the write.
*/
function build(
opts: { addonOn?: boolean; canEdit?: boolean; missing?: boolean; refusal?: string; linkedTo?: number | null } = {},
opts: {
addonOn?: boolean;
canEdit?: boolean;
missing?: boolean;
refusal?: string;
linkedTo?: number | null;
/** What a trip's owner chose for Costs, by trip id; a trip left out follows the instance (`addonOn`). */
tripAddon?: Record<number, boolean>;
} = {},
) {
const budget = {
listBudgetItems: vi.fn((tripId: number) => [{ id: 5, trip_id: tripId }]),
@@ -63,7 +71,10 @@ function build(
const guards = new PluginGuards(
db,
{ checkPermission: vi.fn(() => opts.canEdit ?? true) } as unknown as PermissionsService,
{ isAddonEnabled: vi.fn(() => opts.addonOn ?? true) } as unknown as AddonsService,
{
isAddonEnabled: vi.fn(() => opts.addonOn ?? true),
isEnabledForTrip: vi.fn(async (tripId: number) => opts.tripAddon?.[tripId] ?? opts.addonOn ?? true),
} as unknown as AddonsService,
{ getRole: vi.fn(async () => 'user') } as unknown as UsersRepository,
);
// The leaf membership read replaced the deleted trips.bridge for listMine.
@@ -122,6 +133,37 @@ describe('CostsRpc reads', () => {
});
});
describe('CostsRpc per trip', () => {
it('COSTS-RPC-TRIP-001 a trip that switched Costs on answers although the instance has it off', async () => {
const f = build({ addonOn: false, tripAddon: { 1: true } });
expect((await f.host().dispatch(req('costs.getByTrip', { tripId: 1 }), 42)).ok).toBe(true);
const created = await f.host().dispatch(req('costs.create', { tripId: 1, input: { name: 'Hotel', price: 1 } }), 42);
expect(created.ok).toBe(true);
});
it('COSTS-RPC-TRIP-002 a trip that switched Costs off is refused although the instance has it on', async () => {
const f = build({ tripAddon: { 1: false } });
const read = (await f.host().dispatch(req('costs.getByTrip', { tripId: 1 }), 42)) as RpcError;
expect(read.error.message).toBe('the costs addon is disabled');
const write = (await f.host().dispatch(req('costs.delete', { tripId: 1, itemId: 5 }), 42)) as RpcError;
expect(write.error.message).toBe('the costs addon is disabled');
expect(f.budget.listBudgetItems).not.toHaveBeenCalled();
expect(f.budget.remove).not.toHaveBeenCalled();
});
it('COSTS-RPC-TRIP-003 listMine leaves out the trips that have Costs off, and reads the ones that switched it on', async () => {
const off = build({ tripAddon: { 2: false } });
expect((await off.host().dispatch(req('costs.listMine'), 42)).ok).toBe(true);
expect(off.budget.listBudgetItems).toHaveBeenCalledTimes(1);
expect(off.budget.listBudgetItems).toHaveBeenCalledWith(1);
const on = build({ addonOn: false, tripAddon: { 2: true } });
expect((await on.host().dispatch(req('costs.listMine'), 42)).ok).toBe(true);
expect(on.budget.listBudgetItems).toHaveBeenCalledTimes(1);
expect(on.budget.listBudgetItems).toHaveBeenCalledWith(2);
});
});
describe('CostsRpc writes', () => {
it('COSTS-RPC-006 every write needs the addon, trip access and budget_edit', async () => {
const f = build();
+1
View File
@@ -160,6 +160,7 @@ async function deleteTripAndWatchTempFiles(db: Database.Database): Promise<{
new UnitOfWork(t.em, new SqliteEngine()),
t.em,
none,
none,
);
await trips.remove(trip.id, user.id, 'user');
return {
+4 -3
View File
@@ -59,14 +59,15 @@ describe('ALL_ENTITIES', () => {
* + trip_member_removals, who another member took off a trip, so its invite link refuses them
* + assistant_attachments, the files attached in the trip chat, kept with their conversation
* + mail_ingest_addresses, _prefs, _cursor, _messages and _candidates, the forwarded
* booking mails, the bookings read from them and the switches and addresses behind them)
* booking mails, the bookings read from them and the switches and addresses behind them
* + trip_addon_overrides, the owner's per-trip on or off for a trip addon)
* is registered, and no two share a class name (a silent duplicate would
* shadow one of them in `orm.getMetadata()`, exactly the kind of drift
* `entity-schema-parity.test.ts` can't see — it iterates the metadata map,
* which de-duplicates by class name).
*/
it('ENT-003: exactly 173 entities, every class name unique', () => {
expect(ALL_ENTITIES.length).toBe(173);
it('ENT-003: exactly 174 entities, every class name unique', () => {
expect(ALL_ENTITIES.length).toBe(174);
const names = ALL_ENTITIES.map((s) => s.meta.className);
expect(new Set(names).size).toBe(names.length);
});
@@ -66,7 +66,8 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
// + mail_ingest_addresses: id, token_hash, token_enc, user_id; mail_ingest_prefs: id, user_id; mail_ingest_cursor:
// id, transport, mailbox; mail_ingest_messages: id, transport, dedupe_hash, user_id, size; mail_ingest_candidates:
// id, message_id, user_id (each row is written whole by the mail import, which always knows all of them).
const KNOWN_UNINITIALISED_NOT_NULL_SCALARS = 632;
// + trip_addon_overrides: trip_id, addon_id, enabled (an override is only ever written whole, by the trip owner).
const KNOWN_UNINITIALISED_NOT_NULL_SCALARS = 635;
describe('entity class fields never carry a NaN initialiser (task-4-review-shape.md, Important 1)', () => {
it('CLASSFIELD-001: new X() has no own property whose value is NaN, across all 133 entities', () => {
@@ -115,6 +115,7 @@ const UNNUMBERED = [
'Migration20200101046450_a_carried_over_half_day_stays_half',
'Migration20200101046460_an_upgraded_install_gets_the_columns_its_history_skipped',
'Migration20200101046480_an_address_changed_after_an_admin_made_the_account',
'Migration20200101046490_a_trip_can_switch_its_own_addons',
];
// The last step the positional runner ever had; planLegacyBaseline refuses a
// schema_version past it.
@@ -0,0 +1,133 @@
/**
* `TripAddonOverridesRepository`: a trip's own on or off for a trip addon.
* Seeded and read through the ORM factories on the migrated snapshot, whose
* seeded addon rows (packing, budget, tours, ...) the foreign key points at.
*/
import { TripAddonOverrides } from '../../../../src/db/entities/TripAddonOverrides.entity';
import { Trips } from '../../../../src/db/entities/Trips.entity';
import type { TripAddonOverridesRepository } from '../../../../src/db/repositories/TripAddonOverrides.repository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { countRows, deleteRows, findRow } from '../../../helpers/factories/rows';
import { addTripMember, makeTrip } from '../../../helpers/factories/trips';
import { makeUser } from '../../../helpers/factories/users';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let repo: TripAddonOverridesRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
repo = t.repo(TripAddonOverrides);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
async function ownerAndTrip() {
const { user } = await makeUser(t);
const trip = await makeTrip(t, user.id);
return { user, trip };
}
describe('TripAddonOverridesRepository', () => {
it('TAOREPO-001: a trip without choices lists nothing and follows the instance for every addon', async () => {
const { trip } = await ownerAndTrip();
expect(await repo.listForTrip(trip.id)).toEqual([]);
expect(await repo.findForTrip(trip.id, 'budget')).toBeNull();
});
it('TAOREPO-002: upsertOverride writes on and off as booleans and replaces an earlier choice in place', async () => {
const { trip } = await ownerAndTrip();
await repo.upsertOverride(trip.id, 'budget', false);
await repo.upsertOverride(trip.id, 'packing', true);
expect(await repo.findForTrip(trip.id, 'budget')).toBe(false);
expect(await repo.findForTrip(trip.id, 'packing')).toBe(true);
await repo.upsertOverride(trip.id, 'budget', true);
expect(await repo.listForTrip(trip.id)).toEqual([
{ addon_id: 'budget', enabled: true },
{ addon_id: 'packing', enabled: true },
]);
expect(await countRows(t, TripAddonOverrides, { trip: trip.id })).toBe(2);
const row = await findRow(t, TripAddonOverrides, { trip: trip.id, addon: 'budget' });
expect(row?.updated_at).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/);
});
it('TAOREPO-003: deleteOverride drops one choice and leaves the others', async () => {
const { trip } = await ownerAndTrip();
await repo.upsertOverride(trip.id, 'budget', false);
await repo.upsertOverride(trip.id, 'tours', true);
await repo.deleteOverride(trip.id, 'budget');
expect(await repo.listForTrip(trip.id)).toEqual([{ addon_id: 'tours', enabled: true }]);
await repo.deleteOverride(trip.id, 'budget');
expect(await repo.listForTrip(trip.id)).toEqual([{ addon_id: 'tours', enabled: true }]);
});
it('TAOREPO-004: the choices of one trip never show on another', async () => {
const { user, trip } = await ownerAndTrip();
const other = await makeTrip(t, user.id);
await repo.upsertOverride(trip.id, 'budget', false);
expect(await repo.listForTrip(other.id)).toEqual([]);
expect(await repo.findForTrip(other.id, 'budget')).toBeNull();
});
it('TAOREPO-005: copyForTrip gives the new trip the same choices and leaves the source alone', async () => {
const { user, trip } = await ownerAndTrip();
const copy = await makeTrip(t, user.id);
await repo.upsertOverride(trip.id, 'budget', false);
await repo.upsertOverride(trip.id, 'roadtrip', true);
await repo.copyForTrip(trip.id, copy.id);
await repo.copyForTrip(trip.id, copy.id);
const expected = [
{ addon_id: 'budget', enabled: false },
{ addon_id: 'roadtrip', enabled: true },
];
expect(await repo.listForTrip(copy.id)).toEqual(expected);
expect(await repo.listForTrip(trip.id)).toEqual(expected);
});
it('TAOREPO-006: copyForTrip of a trip without choices copies nothing', async () => {
const { user, trip } = await ownerAndTrip();
const copy = await makeTrip(t, user.id);
await repo.copyForTrip(trip.id, copy.id);
expect(await repo.listForTrip(copy.id)).toEqual([]);
});
it('TAOREPO-007: anyEnabledForUser sees a trip the user owns or belongs to that switched the addon on', async () => {
const { user: owner, trip } = await ownerAndTrip();
const { user: member } = await makeUser(t);
const { user: stranger } = await makeUser(t);
await addTripMember(t, trip.id, member.id, owner.id);
expect(await repo.anyEnabledForUser(owner.id, 'roadtrip')).toBe(false);
await repo.upsertOverride(trip.id, 'roadtrip', true);
expect(await repo.anyEnabledForUser(owner.id, 'roadtrip')).toBe(true);
expect(await repo.anyEnabledForUser(member.id, 'roadtrip')).toBe(true);
expect(await repo.anyEnabledForUser(stranger.id, 'roadtrip')).toBe(false);
expect(await repo.anyEnabledForUser(owner.id, 'tours')).toBe(false);
});
it('TAOREPO-008: a trip that switched the addon off counts for nobody', async () => {
const { user, trip } = await ownerAndTrip();
await repo.upsertOverride(trip.id, 'roadtrip', false);
expect(await repo.anyEnabledForUser(user.id, 'roadtrip')).toBe(false);
});
it('TAOREPO-009: the choices go with their trip', async () => {
const { trip } = await ownerAndTrip();
await repo.upsertOverride(trip.id, 'budget', false);
await deleteRows(t, Trips, { id: trip.id });
expect(await countRows(t, TripAddonOverrides, { trip: trip.id })).toBe(0);
});
});
+2 -2
View File
@@ -80,7 +80,7 @@ function build(
const guards = new PluginGuards(
db,
permissions,
{ isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService,
{ isAddonEnabled: vi.fn(() => true), isEnabledForTrip: vi.fn(async () => true) } as unknown as AddonsService,
usersRepo,
);
const storage = {
@@ -417,7 +417,7 @@ describe('FilesRpc writes', () => {
const guards = new PluginGuards(
db,
{ checkPermission: vi.fn(() => true) } as unknown as PermissionsService,
{ isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService,
{ isAddonEnabled: vi.fn(() => true), isEnabledForTrip: vi.fn(async () => true) } as unknown as AddonsService,
// PluginGuards' own role lookup — unrelated to FL28's `usersRepo` below,
// which is used for the demo-uploader email check.
{ getRole: vi.fn(async () => 'user') } as unknown as UsersRepository,
@@ -81,6 +81,9 @@ const { isAddonEnabledMock } = vi.hoisted(() => {
// of behind an import path.
const addonsStub = {
isAddonEnabled: isAddonEnabledMock,
// The trip addons answer per user and per trip; this suite has no overrides, so both follow the switch.
isEnabledForUserAnywhere: isAddonEnabledMock,
isEnabledForTrip: isAddonEnabledMock,
getCollabFeatures: () => ({ chat: true, notes: true, links: true, polls: true, whatsnext: true }),
} as unknown as AddonsService;
@@ -420,6 +423,22 @@ describe('Prompt: trip-summary', () => {
expect(text).toContain('?'); // start/end date fallback
expect(text).toContain('EUR'); // currency fallback
});
it('leaves out the sections whose addon is off for the trip, the rest as before', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Lisbon' });
isAddonEnabledMock.mockImplementation((tripOrId: unknown, id?: string) =>
typeof tripOrId === 'number' && id !== undefined ? id === 'collab' : true,
);
const client = await buildServer(user.id);
const text = await invokePromptText(client, 'trip-summary', { tripId: trip.id });
expect(text).toContain('Lisbon');
expect(text).toContain('Reservations:');
expect(text).toContain('Collab Notes:');
expect(text).not.toContain('Packing:');
expect(text).not.toContain('Budget:');
});
});
// ─────────────────────────────────────────────────────────────────────────────
@@ -59,6 +59,7 @@ describe('tool gate', () => {
expect(gate).toHaveBeenCalledWith(
expect.objectContaining({ name: 'write_it', annotations: { readOnlyHint: false } }),
asCtx({ userId: 3 }),
{ n: 1 },
);
});
@@ -48,7 +48,9 @@ const ctx = (actingUserId: number | undefined): PluginRpcContext => ({
* 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 } = {}) {
function build(
overrides: { role?: string | null; allow?: boolean; addonOn?: boolean; tripAddon?: Record<number, boolean> } = {},
) {
const db = {
findAccessible: vi.fn(async (tripId: number, userId: number) =>
tripId === 1 && userId === 42 ? { id: 1, user_id: 42 } : undefined,
@@ -60,8 +62,10 @@ function build(overrides: { role?: string | null; allow?: boolean; addonOn?: boo
const permissions = {
checkPermission: vi.fn(() => overrides.allow ?? true),
} as unknown as PermissionsService;
// `tripAddon` is what a trip's owner chose, by trip id; a trip left out follows the instance (`addonOn`).
const addons = {
isAddonEnabled: vi.fn(() => overrides.addonOn ?? true),
isEnabledForTrip: vi.fn(async (tripId: number) => overrides.tripAddon?.[tripId] ?? overrides.addonOn ?? true),
} as unknown as AddonsService;
return { guards: new PluginGuards(db, permissions, addons, users), db, users, permissions, addons };
}
@@ -255,6 +259,56 @@ describe('PluginGuards — requireAddon', () => {
});
});
describe('PluginGuards: requireAddon for one trip', () => {
it('PGUARD-030 a trip the user sees answers with its own choice, in either direction', async () => {
const on = build({ addonOn: false, tripAddon: { 1: true } });
await expect(on.guards.requireAddon('budget', 'costs', { tripId: 1, userId: 42 })).resolves.toBeUndefined();
expect(on.addons.isEnabledForTrip).toHaveBeenCalledWith(1, 'budget');
const off = build({ addonOn: true, tripAddon: { 1: false } });
await expect(off.guards.requireAddon('budget', 'costs', { tripId: 1, userId: 42 })).rejects.toThrow(
new ForbiddenResource('the costs addon is disabled'),
);
});
it('PGUARD-031 a trip the user cannot see is answered with the instance switch, never its own choice', async () => {
const f = build({ addonOn: true, tripAddon: { 1: false } });
await expect(f.guards.requireAddon('budget', 'costs', { tripId: 1, userId: 7 })).resolves.toBeUndefined();
expect(f.addons.isEnabledForTrip).not.toHaveBeenCalled();
});
it('PGUARD-032 tripRead and requireTripEdit ask the addon of the trip after the access check', async () => {
const f = build({ tripAddon: { 1: false } });
const read = vi.fn(() => 'rows');
await expect(
f.guards.tripRead({ tripId: 1 }, ctx(42), read, { addonId: 'packing', noun: 'packing' }),
).rejects.toThrow(new ForbiddenResource('the packing addon is disabled'));
expect(read).not.toHaveBeenCalled();
await expect(
f.guards.requireTripEdit(1, 42, 'packing_edit', { addonId: 'packing', noun: 'packing' }),
).rejects.toThrow(new ForbiddenResource('the packing addon is disabled'));
// Without an addon named, the two stay what they were.
await expect(f.guards.tripRead({ tripId: 1 }, ctx(42), read)).resolves.toBe('rows');
await expect(f.guards.requireTripEdit(1, 42, 'packing_edit')).resolves.toBeUndefined();
});
it('PGUARD-033 tripsWithAddon keeps the trips the addon applies to, in the order given', async () => {
const f = build({ addonOn: true, tripAddon: { 2: false } });
expect(await f.guards.tripsWithAddon('budget', 'costs', [3, 2, 1])).toEqual([3, 1]);
// The instance off: only the trips that switched it on, and a refusal when none did.
expect(
await build({ addonOn: false, tripAddon: { 2: true } }).guards.tripsWithAddon('budget', 'costs', [1, 2]),
).toEqual([2]);
await expect(build({ addonOn: false }).guards.tripsWithAddon('budget', 'costs', [1, 2])).rejects.toThrow(
new ForbiddenResource('the costs addon is disabled'),
);
// The instance on with every trip switched off is an empty answer, not a refusal.
expect(
await build({ addonOn: true, tripAddon: { 1: false } }).guards.tripsWithAddon('budget', 'costs', [1]),
).toEqual([]);
});
});
describe('PluginGuards — capStrings', () => {
it('PGUARD-017 a field within the cap passes', () => {
expect(() => build().guards.capStrings({ name: 'ok' }, { name: 200 })).not.toThrow();
+41 -4
View File
@@ -24,16 +24,20 @@ import { Reflector } from '@nestjs/core';
import { describe, it, expect, vi } from 'vitest';
/** A context whose handler/class carry the decorator under test. */
function ctxFor(handler: object, cls: object = class {}): ExecutionContext {
/** A context whose handler/class carry the decorator under test, for a request with or without a user. */
function ctxFor(handler: object, cls: object = class {}, user?: { id: number }): ExecutionContext {
return {
getHandler: () => handler,
getClass: () => cls,
switchToHttp: () => ({ getRequest: () => ({ user }) }),
} as unknown as ExecutionContext;
}
function addons(enabled: boolean): AddonsService {
return { isAddonEnabled: vi.fn(() => enabled) } as unknown as AddonsService;
function addons(enabled: boolean, anywhere = false): AddonsService {
return {
isAddonEnabled: vi.fn(() => enabled),
isEnabledForUserAnywhere: vi.fn(() => enabled || anywhere),
} as unknown as AddonsService;
}
async function thrown(fn: () => unknown) {
@@ -107,6 +111,39 @@ describe('AddonGuard', () => {
});
});
describe('AddonGuard once the user is known', () => {
it('ADDON-GUARD-008: opens for a user one of whose trips switched the addon on, although the instance has it off', async () => {
const cls = decorated(ADDON_IDS.TOURS, 'Tours');
const svc = addons(false, true);
const guard = new AddonGuard(svc, new Reflector());
expect(await guard.canActivate(ctxFor(() => {}, cls, { id: 7 }))).toBe(true);
expect(svc.isEnabledForUserAnywhere).toHaveBeenCalledWith(7, ADDON_IDS.TOURS);
expect(svc.isAddonEnabled).not.toHaveBeenCalled();
});
it('ADDON-GUARD-009: stays shut for a user none of whose trips switched it on', async () => {
const cls = decorated(ADDON_IDS.ROADTRIP, 'Road trip');
const guard = new AddonGuard(addons(false, false), new Reflector());
expect(await thrown(() => guard.canActivate(ctxFor(() => {}, cls, { id: 7 })))).toEqual({
status: 404,
body: { error: 'Road trip addon is not enabled' },
});
});
it('ADDON-GUARD-010: without a user it reads the instance switch alone', async () => {
const cls = decorated(ADDON_IDS.TOURS, 'Tours');
const svc = addons(false, true);
expect(await thrown(() => new AddonGuard(svc, new Reflector()).canActivate(ctxFor(() => {}, cls)))).toEqual({
status: 404,
body: { error: 'Tours addon is not enabled' },
});
expect(svc.isEnabledForUserAnywhere).not.toHaveBeenCalled();
});
});
describe('the gated route groups still declare their addon', () => {
const metaOf = (cls: object): RequireAddonMeta | undefined => Reflect.getMetadata(REQUIRE_ADDON, cls);
const guardsOf = (cls: object): unknown[] => Reflect.getMetadata('__guards__', cls) ?? [];
@@ -27,6 +27,7 @@ import { AppSettings } from '../../../src/db/entities/AppSettings.entity';
import { PhotoProviderFields } from '../../../src/db/entities/PhotoProviderFields.entity';
import { PhotoProviders } from '../../../src/db/entities/PhotoProviders.entity';
import { PlaceShadowPicks } from '../../../src/db/entities/PlaceShadowPicks.entity';
import { TripAddonOverrides } from '../../../src/db/entities/TripAddonOverrides.entity';
import { Users } from '../../../src/db/entities/Users.entity';
import type { AddonsRepository } from '../../../src/db/repositories/Addons.repository';
import type { AppSettingsRepository } from '../../../src/db/repositories/AppSettings.repository';
@@ -197,6 +198,7 @@ beforeEach(() => {
appSettingsRepo,
usersRepo,
new UnitOfWork(t.em, new SqliteEngine()),
t.repo(TripAddonOverrides),
);
});
@@ -435,6 +437,22 @@ describe('AddonsService addon/feature flags', () => {
expect((await svc.list()).toursWanderer).toBe(false);
});
it('the wanderer sub-option alone ignores the Tours switch, which a trip may decide for itself', async () => {
expect(await svc.isWandererAllowed()).toBe(false); // absent row: OFF
await svc.updateToursWanderer(true);
// Tours is off for the instance, yet the option holds wherever a trip switched Tours on.
expect(await svc.isWandererAllowed()).toBe(true);
expect(await svc.isWandererAvailable()).toBe(false);
const saved = process.env.TREK_MANAGED;
try {
process.env.TREK_MANAGED = '1';
expect(await svc.isWandererAllowed()).toBe(false);
} finally {
if (saved === undefined) delete process.env.TREK_MANAGED;
else process.env.TREK_MANAGED = saved;
}
});
it('wanderer is never available on a managed install, whatever the stored switch says', async () => {
const saved = process.env.TREK_MANAGED;
try {
@@ -481,6 +499,16 @@ describe('AddonsService addon/feature flags', () => {
expect((await svc.list()).toursHikingMap).toBe(true);
});
it('lists the Tours options apart from the instance Tours switch, for a trip that switched Tours on itself', async () => {
// Tours is off for the instance: the combined flags say no, the options say what the admin chose.
expect((await svc.list()).toursOptions).toEqual({ wanderer: false, hikingMap: true, cycleMap: true });
expect((await svc.list()).toursHikingMap).toBe(false);
await svc.updateToursWanderer(true);
await svc.updateToursCycleMap(false);
expect((await svc.list()).toursOptions).toEqual({ wanderer: true, hikingMap: true, cycleMap: false });
expect((await svc.list()).toursWanderer).toBe(false);
});
it('the piste router under Tours is on until an admin switches it off', async () => {
expect(await svc.getToursSkiRouting()).toEqual({ enabled: true }); // absent row → ON
expect(await svc.updateToursSkiRouting(false)).toEqual({ enabled: false });
@@ -55,17 +55,18 @@ describe('attachedPort', () => {
it('ASTATL-001: offers keep_attached_file where the thread holds a file, read_attached_file where one has text', () => {
const port = base();
expect(attachedPort(port, null)).toBe(port);
expect(attachedPort(port, { attached: [], sentTo: 'm', read: vi.fn() })).toBe(port);
expect(attachedPort(port, { attached: [], sentTo: 'm', keeps: true, read: vi.fn() })).toBe(port);
const scanOnly = attachedPort(port, {
attached: [row(SCAN, { text_status: 'scanned' })],
sentTo: 'm',
keeps: true,
read: vi.fn(),
});
expect(scanOnly.specs().map((spec) => spec.name)).toEqual(['get_trip_summary', KEEP_ATTACHED_FILE_SPEC.name]);
expect(scanOnly.pinArgs('read_attached_file', { attachmentId: SCAN })).toEqual({
args: { attachmentId: SCAN },
});
const offered = attachedPort(port, { attached: ATTACHED, sentTo: 'm', read: vi.fn() });
const offered = attachedPort(port, { attached: ATTACHED, sentTo: 'm', keeps: true, read: vi.fn() });
expect(offered.specs().map((spec) => spec.name)).toEqual([
'get_trip_summary',
READ_ATTACHED_FILE_SPEC.name,
@@ -74,7 +75,7 @@ describe('attachedPort', () => {
});
it('ASTATL-002: the first read of a file is held for the user, a shared one runs at once', () => {
const port = attachedPort(base(), { attached: ATTACHED, sentTo: 'm', read: vi.fn() });
const port = attachedPort(base(), { attached: ATTACHED, sentTo: 'm', keeps: true, read: vi.fn() });
expect(port.kindOf('read_attached_file', { attachmentId: OWN })).toBe('write');
expect(port.kindOf('read_attached_file', { attachmentId: SHARED })).toBe('read');
expect(port.kindOf('read_attached_file', { attachmentId: ELSEWHERE })).toBe('write');
@@ -82,7 +83,12 @@ describe('attachedPort', () => {
});
it('ASTATL-003: the held call names the file and where its text goes, never more; anything else is refused alike', () => {
const port = attachedPort(base(), { attached: ATTACHED, sentTo: 'gpt-5 (api.openai.com)', read: vi.fn() });
const port = attachedPort(base(), {
attached: ATTACHED,
sentTo: 'gpt-5 (api.openai.com)',
keeps: true,
read: vi.fn(),
});
expect(port.pinArgs('read_attached_file', { attachmentId: OWN, sentTo: 'nowhere' })).toEqual({
args: { attachmentId: OWN, name: '0b7c.pdf', sentTo: 'gpt-5 (api.openai.com)' },
});
@@ -96,7 +102,7 @@ describe('attachedPort', () => {
it('ASTATL-004: a read runs through the turn, and only for a file of the thread', async () => {
const read = vi.fn(async () => ({ ok: true, value: { name: 'x', read: true }, modelText: 'text' }));
const inner = base();
const port = attachedPort(inner, { attached: ATTACHED, sentTo: 'm', read });
const port = attachedPort(inner, { attached: ATTACHED, sentTo: 'm', keeps: true, read });
expect(await port.call('read_attached_file', { attachmentId: SHARED })).toMatchObject({ modelText: 'text' });
expect(read).toHaveBeenCalledWith(SHARED);
expect(await port.call('read_attached_file', { attachmentId: ELSEWHERE })).toEqual({
@@ -114,7 +120,7 @@ describe('attachedPort', () => {
});
it('ASTATL-006: a keep is always held, checked, and names the file; an attachment of no one here is refused alike', () => {
const port = attachedPort(base(), { attached: ATTACHED, sentTo: 'm', read: vi.fn() });
const port = attachedPort(base(), { attached: ATTACHED, sentTo: 'm', keeps: true, read: vi.fn() });
expect(port.kindOf('keep_attached_file', { attachmentId: SCAN })).toBe('write');
expect(port.pinArgs('keep_attached_file', { attachmentId: SCAN, reservation_id: 5, name: 'forged.exe' })).toEqual({
args: { attachmentId: SCAN, reservation_id: 5, name: '2d9e.pdf' },
@@ -124,4 +130,14 @@ describe('attachedPort', () => {
const bad = port.pinArgs('keep_attached_file', { attachmentId: OWN, budget_item_id: 'seven' });
expect(bad).toEqual({ error: expect.stringContaining('Invalid arguments') });
});
it('ASTATL-007: no keep is offered or held while the trip has Documents off; the call goes to the port', () => {
const inner = base();
const port = attachedPort(inner, { attached: ATTACHED, sentTo: 'm', keeps: false, read: vi.fn() });
expect(port.specs().map((spec) => spec.name)).toEqual(['get_trip_summary', READ_ATTACHED_FILE_SPEC.name]);
expect(port.kindOf('keep_attached_file', { attachmentId: SCAN })).toBe('read');
expect(inner.kindOf).toHaveBeenCalledWith('keep_attached_file', { attachmentId: SCAN });
port.pinArgs('keep_attached_file', { attachmentId: SCAN });
expect(inner.pinArgs).toHaveBeenCalledWith('keep_attached_file', { attachmentId: SCAN });
});
});
@@ -53,10 +53,19 @@ interface Listed {
mtimeMs: number;
}
async function make(opts: { text?: string | Error; listed?: Listed[]; failDelete?: string; failPut?: boolean } = {}) {
interface MakeOpts {
text?: string | Error;
listed?: Listed[];
failDelete?: string;
failPut?: boolean;
attached?: Array<{ id: string; trip_id: number }>;
documents?: boolean;
}
async function make(opts: MakeOpts = {}) {
const rows = {
insertAttachment: vi.fn(async () => undefined),
listForThread: vi.fn(async () => []),
listForThread: vi.fn(async () => opts.attached ?? []),
listObjectsOfThread: vi.fn(async () => [{ id: 'a1', storage_key: 'assistant/a1.pdf' }]),
listCreatedBefore: vi.fn(async () => [
{ id: 'old1', storage_key: 'assistant/old1.pdf' },
@@ -90,6 +99,10 @@ async function make(opts: { text?: string | Error; listed?: Listed[]; failDelete
}),
fitText: vi.fn((text: string, compact: boolean) => (compact ? text.slice(0, 4) : text)),
};
const keeper = {
keep: vi.fn(async () => ({ ok: true, value: { file: { id: 3 } } })),
keepsOn: vi.fn(async (_tripId: number) => opts.documents !== false),
};
const moduleRef = await Test.createTestingModule({
providers: [
AssistantAttachmentsService,
@@ -99,11 +112,11 @@ async function make(opts: { text?: string | Error; listed?: Listed[]; failDelete
{ provide: MikroORM, useValue: {} },
{
provide: AssistantKeepFileService,
useValue: { keep: vi.fn(async () => ({ ok: true, value: { file: { id: 3 } } })) },
useValue: keeper,
},
],
}).compile();
return { service: moduleRef.get(AssistantAttachmentsService), rows, storage, llmParse };
return { service: moduleRef.get(AssistantAttachmentsService), rows, storage, llmParse, keeper };
}
describe('AssistantAttachmentsService', () => {
@@ -258,5 +271,18 @@ describe('AssistantAttachmentsService', () => {
const cloud = await t.service.turnFor(7, 4, { kind: 'openai', model: 'gpt-5', host: 'api.openai.com' });
expect(cloud.texts).toEqual(new Map([[SHARED, 'Casa Lisboa, HM4X2']]));
expect(t.rows.listSharedTexts).toHaveBeenCalledWith(4, 7);
// A thread without files has nothing to keep and asks no addon.
expect(cloud.turn.keeps).toBe(false);
expect(t.keeper.keepsOn).not.toHaveBeenCalled();
});
it('ASTATT-012: a turn may keep its files only while their trip has Documents on', async () => {
const connection = { kind: 'openai', model: 'gpt-5', host: 'api.openai.com' } as const;
const attached = [{ id: SHARED, trip_id: 9 }];
const on = await make({ attached });
expect((await on.service.turnFor(7, 4, connection)).turn.keeps).toBe(true);
expect(on.keeper.keepsOn).toHaveBeenCalledWith(9);
const off = await make({ attached, documents: false });
expect((await off.service.turnFor(7, 4, connection)).turn.keeps).toBe(false);
});
});
@@ -80,7 +80,7 @@ async function codeOf(promise: Promise<unknown>): Promise<string | null> {
describe('AssistantBookingImportService', () => {
it('ASTBKI-001: refuses a file nothing here reads, and a photo the model cannot see', async () => {
const readable = async (opts: Opts, name: string) =>
codeOf((await make(opts)).service.ensureReadable(7, file(name)));
codeOf((await make(opts)).service.ensureReadable(7, 1, file(name)));
expect(await readable({ extractor: false }, 'a.pdf')).toBe('import_unavailable');
expect(await readable({ extractor: false, ai: true }, 'a.pdf')).toBeNull();
expect(await readable({}, 'a.pdf')).toBeNull();
@@ -1,10 +1,11 @@
/**
* keep_attached_file applied: the checks a Files upload runs (demo, trip,
* rights, types, same-trip links), the bytes copied to a trip file of their
* the trip's Documents addon, rights, types, same-trip links), the bytes copied to a trip file of their
* own, the rows written in one transaction, the broadcast after it, and a
* second keep that answers the first file.
*/
import { AssistantAttachments } from '../../../../src/db/entities/AssistantAttachments.entity';
import { AddonsService } from '../../../../src/nest/addons/addons.service';
import { AssistantKeepFileService } from '../../../../src/nest/assistant/assistant-keep-file.service';
import { DemoService } from '../../../../src/nest/common/demo.service';
import { UnitOfWork } from '../../../../src/nest/database/unit-of-work';
@@ -28,6 +29,7 @@ const AT = { userId: 7, threadId: 4, tripId: 9 };
interface Opts {
demo?: boolean;
trip?: boolean;
documents?: boolean;
upload?: boolean;
edit?: boolean;
allowed?: string;
@@ -75,6 +77,8 @@ async function make(opts: Opts = {}) {
),
};
const uow = { transactional: vi.fn(async (fn: () => Promise<unknown>) => fn()) };
// The trip's Documents addon: what its owner chose, else the instance switch.
const addons = { isEnabledForTrip: vi.fn(async () => opts.documents !== false) };
const moduleRef = await Test.createTestingModule({
providers: [
AssistantKeepFileService,
@@ -89,9 +93,10 @@ async function make(opts: Opts = {}) {
useValue: { findAccessible: vi.fn(async () => (opts.trip === false ? undefined : { id: 9 })) },
},
{ provide: UnitOfWork, useValue: uow },
{ provide: AddonsService, useValue: addons },
],
}).compile();
return { service: moduleRef.get(AssistantKeepFileService), rows, files, guards, uow, storage };
return { service: moduleRef.get(AssistantKeepFileService), rows, files, guards, uow, storage, addons };
}
describe('AssistantKeepFileService', () => {
@@ -155,6 +160,19 @@ describe('AssistantKeepFileService', () => {
});
});
it('ASTKEP-007: refused while the trip has Documents off, with the words the Files routes use', async () => {
const t = await make({ documents: false });
expect(await t.service.keep(AT, { attachmentId: ID })).toEqual({
ok: false,
value: 'Documents addon is not enabled',
});
expect(t.addons.isEnabledForTrip).toHaveBeenCalledWith(9, 'documents');
expect(t.rows.findInThread).not.toHaveBeenCalled();
expect(t.files.storeBytes).not.toHaveBeenCalled();
expect(await t.service.keepsOn(9)).toBe(false);
expect(await (await make()).service.keepsOn(9)).toBe(true);
});
it('ASTKEP-004: an attachment of no one here, a type Files refuses and a link off the trip are refused', async () => {
const run = async (opts: Opts, args: Record<string, unknown> = { attachmentId: ID }) =>
(await make(opts)).service.keep(AT, args);
@@ -30,7 +30,7 @@ const db = createSnapshotTestDb();
let t: TestModule;
const addons = {
isAddonEnabled: vi.fn(async () => true),
isEnabledForTrip: vi.fn(async () => true),
getCollabFeatures: vi.fn(async () => ({ chat: true, notes: true, polls: true })),
};
const collab = {
@@ -108,7 +108,7 @@ describe('AssistantShareService', () => {
it('ASTSHR-003: refused while the collab addon or its chat is off', async () => {
const c = await conversation();
const share = () => shareAs(c.user, c.tripId, c.threadId, `msg-${c.answer.id}`);
addons.isAddonEnabled.mockResolvedValueOnce(false);
addons.isEnabledForTrip.mockResolvedValueOnce(false);
await expect(share()).rejects.toMatchObject({ status: 403, message: 'Collab chat is off' });
addons.getCollabFeatures.mockResolvedValueOnce({ chat: false, notes: true, polls: true });
await expect(share()).rejects.toMatchObject({ status: 403, code: 'forbidden' });
@@ -37,15 +37,15 @@ function file(name: string): Express.Multer.File {
async function make(tracks: TourFileTrack[], opts: { tours?: boolean; whole?: boolean } = {}) {
const read = vi.fn(async () => ({ tracks, whole: opts.whole === true }));
const isAddonEnabled = vi.fn(async () => opts.tours !== false);
const isEnabledForTrip = vi.fn(async () => opts.tours !== false);
const moduleRef = await Test.createTestingModule({
providers: [
AssistantTourFileService,
{ provide: TourFileReadService, useValue: { read } },
{ provide: AddonsService, useValue: { isAddonEnabled } },
{ provide: AddonsService, useValue: { isEnabledForTrip } },
],
}).compile();
return { service: moduleRef.get(AssistantTourFileService), read, isAddonEnabled };
return { service: moduleRef.get(AssistantTourFileService), read, isEnabledForTrip };
}
describe('AssistantTourFileService', () => {
@@ -56,10 +56,10 @@ describe('AssistantTourFileService', () => {
});
it('AST-TOUR-FILE-002: refuses a route file where tours are off', async () => {
const { service, isAddonEnabled } = await make([], { tours: false });
await expect(service.ensureReadable(7, file('a.gpx'))).rejects.toBeInstanceOf(DomainError);
expect(isAddonEnabled).toHaveBeenCalledWith('tours');
await expect((await make([])).service.ensureReadable(7, file('a.gpx'))).resolves.toBeUndefined();
const { service, isEnabledForTrip } = await make([], { tours: false });
await expect(service.ensureReadable(7, 3, file('a.gpx'))).rejects.toBeInstanceOf(DomainError);
expect(isEnabledForTrip).toHaveBeenCalledWith(3, 'tours');
await expect((await make([])).service.ensureReadable(7, 3, file('a.gpx'))).resolves.toBeUndefined();
});
it('AST-TOUR-FILE-003: proposes one hike per track, the GPX text kept on the held call only', async () => {
@@ -294,7 +294,7 @@ describe('BookingImportService.confirm venue website (#2483)', () => {
reservationsRepo: reservationsRepoStub,
reservations,
guards: guardsStub,
addons: { isAddonEnabled: () => false },
addons: { isAddonEnabled: () => false, isEnabledForTrip: async () => false },
realtime: { broadcast: vi.fn() },
maps: { geocodeQuery: vi.fn() },
places,
@@ -389,7 +389,7 @@ describe('BookingImportService.confirm writes the booking with its cost', () =>
reservations,
guards: guardsStub,
budget,
addons: { isAddonEnabled: async () => opts.budget ?? true },
addons: { isAddonEnabled: async () => opts.budget ?? true, isEnabledForTrip: async () => opts.budget ?? true },
realtime,
maps: { geocodeQuery: vi.fn() },
places,
@@ -563,7 +563,7 @@ describe('BookingImportService.confirm reports every item it did not create', ()
reservationsRepo: reservationsRepoStub,
reservations,
guards: guardsStub,
addons: { isAddonEnabled: async () => false },
addons: { isAddonEnabled: async () => false, isEnabledForTrip: async () => false },
realtime: { broadcast: vi.fn() },
maps: { geocodeQuery: vi.fn() },
places: { create: vi.fn() },
@@ -125,9 +125,10 @@ describe('BudgetItemsMcp surface', () => {
expect(options.name).toBe(name);
expect(options.access).toEqual({ group: 'budget', mode: 'read' });
expect(options.annotations).toMatchObject({ readOnlyHint: true, destructiveHint: false });
const enabled = vi.spyOn(t.get(AddonsService), 'isAddonEnabled').mockResolvedValue(false);
// Costs is a trip addon: the read is offered while the instance or any trip of the caller has it on.
const enabled = vi.spyOn(t.get(AddonsService), 'isEnabledForUserAnywhere').mockResolvedValue(false);
expect(await options.when?.(ctx(1), mcp)).toBe(false);
expect(enabled).toHaveBeenCalledWith(ADDON_IDS.BUDGET);
expect(enabled).toHaveBeenCalledWith(1, ADDON_IDS.BUDGET);
enabled.mockResolvedValue(true);
expect(await options.when?.(ctx(1), mcp)).toBe(true);
},
@@ -34,6 +34,7 @@ import { CalendarService, calendarOptionsFromQuery, foldICS } from '../../../src
import { CalendarModule } from '../../../src/nest/calendar/calendar.module';
import { expectRegisteredProvider } from '../../helpers/module-providers';
import { notificationsStub } from '../../helpers/notifications';
import { createTestAddonsService } from '../../helpers/test-addons';
import { accommodationsOver } from '../../helpers/accommodations-service';
import { createTestUnitOfWork, createTestAppSettingsRepo, createTestReservationsRepo, createTestReservationEndpointsRepo, createTestReservationTravelersRepo, createTestReservationDayPositionsRepo, createTestDayAccommodationsRepo, createTestDaysRepo, createTestDayNotesRepo, createTestPlacesRepo, createTestDayAssignmentsRepo, createTestTripMembersRepo, createTestUsersRepo, createTestTripsRepo } from '../../helpers/test-uow';
import { createTestBudgetItemsRepo } from '../../helpers/files-repos';
@@ -58,7 +59,7 @@ let orm: TestOrm;
beforeAll(async () => {
budgetSvc = new BudgetService(new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)), new ExchangeRatesService(), realtime, await createTestUnitOfWork(testDb), ...(await budgetRepoArgs(testDb)));
svc = new CalendarService(
new ReservationsService(new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)), budgetSvc, realtime, notificationsStub(), new ReservationsReadService(await createTestReservationsRepo(testDb), await createTestReservationEndpointsRepo(testDb), await createTestReservationTravelersRepo(testDb), await createTestReservationDayPositionsRepo(testDb)), await accommodationsOver(testDb, realtime), await createTestUnitOfWork(testDb), await createTestReservationsRepo(testDb), await createTestReservationEndpointsRepo(testDb), await createTestReservationTravelersRepo(testDb), await createTestReservationDayPositionsRepo(testDb), await createTestDayAccommodationsRepo(testDb), await createTestDaysRepo(testDb), await createTestPlacesRepo(testDb), await createTestDayAssignmentsRepo(testDb), await createTestTripMembersRepo(testDb), await createTestUsersRepo(testDb), await createTestTripsRepo(testDb), await createTestBudgetItemsRepo(testDb)),
new ReservationsService(new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)), budgetSvc, realtime, notificationsStub(), new ReservationsReadService(await createTestReservationsRepo(testDb), await createTestReservationEndpointsRepo(testDb), await createTestReservationTravelersRepo(testDb), await createTestReservationDayPositionsRepo(testDb)), await accommodationsOver(testDb, realtime), await createTestUnitOfWork(testDb), await createTestReservationsRepo(testDb), await createTestReservationEndpointsRepo(testDb), await createTestReservationTravelersRepo(testDb), await createTestReservationDayPositionsRepo(testDb), await createTestDayAccommodationsRepo(testDb), await createTestDaysRepo(testDb), await createTestPlacesRepo(testDb), await createTestDayAssignmentsRepo(testDb), await createTestTripMembersRepo(testDb), await createTestUsersRepo(testDb), await createTestTripsRepo(testDb), await createTestBudgetItemsRepo(testDb), await createTestAddonsService(testDb)),
await createTestTripsRepo(testDb), await createTestDaysRepo(testDb), await createTestDayNotesRepo(testDb), await createTestReservationsRepo(testDb),
);
});
+3 -3
View File
@@ -545,11 +545,11 @@ describe('CityWalkMcp (CW-11)', () => {
]);
expect(propose.description).toContain('stations_for_create');
expect(create.description).toContain('route_pending');
const isAddonEnabled = vi.fn(async (id: string) => id === 'tours');
const isEnabledForUserAnywhere = vi.fn(async (_userId: number, id: string) => id === 'tours');
const gated = await Promise.all(
[propose, create].map((tool) => tool.when?.(ctx(1), { addons: { isAddonEnabled } })),
[propose, create].map((tool) => tool.when?.(ctx(1), { addons: { isEnabledForUserAnywhere } })),
);
expect(gated).toEqual([true, true]);
expect(isAddonEnabled).toHaveBeenCalledWith('tours');
expect(isEnabledForUserAnywhere).toHaveBeenCalledWith(1, 'tours');
});
});
@@ -1,3 +1,6 @@
import type { AddonsService } from '../../../src/nest/addons/addons.service';
import { REQUIRE_ADDON } from '../../../src/nest/addons/require-addon.decorator';
import { TripAddonGuard } from '../../../src/nest/addons/trip-addon.guard';
import { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service';
import { JwtAuthGuard } from '../../../src/nest/auth-core/jwt-auth.guard';
import {
@@ -54,8 +57,12 @@ const storageStub = {
* Build the controller over its stubs. The env is the live one, so a case about
* demo mode stubs DEMO_MODE and every other case runs outside it.
*/
function ctl(service: CollabService, storage: StorageService = storageStub): CollabController {
return new CollabController(service, storage, new RuntimeEnvService());
/** Whether Collab applies to the trip: on, unless a test switches it off for its trip. */
const addonsOn = { isEnabledForTrip: vi.fn(async () => true) } as unknown as AddonsService;
const addonsOff = { isEnabledForTrip: vi.fn(async () => false) } as unknown as AddonsService;
function ctl(service: CollabService, storage: StorageService = storageStub, addons = addonsOn): CollabController {
return new CollabController(service, storage, new RuntimeEnvService(), addons);
}
async function thrownAsync(fn: () => Promise<unknown>): Promise<{ status: number; body: unknown }> {
@@ -346,6 +353,18 @@ describe('CollabController (parity with the legacy /api/trips/:tripId/collab rou
).toEqual({ status: 403, body: { error: 'No permission' } });
});
it('refuses a trip that has Collab off for itself, after the trip check, with the addon text', async () => {
const s = svc({ verifyTripAccess: vi.fn().mockResolvedValue({ id: 5, user_id: 1 }) } as Partial<CollabService>);
expect(
await thrownAsync(() => ctl(s, storageStub, addonsOff).createMessage(user, '5', { text: 'hi' }, undefined)),
).toEqual({
status: 404,
body: { error: 'Collab addon is not enabled' },
});
expect(addonsOff.isEnabledForTrip).toHaveBeenCalledWith(5, 'collab');
expect(s.postMessage).not.toHaveBeenCalled();
});
it('react 404 unknown, else broadcasts reactions (empty emoji now 400s in the Zod pipe)', async () => {
expect(
await thrownAsync(() =>
@@ -667,8 +686,24 @@ describe('CollabController (parity with the legacy /api/trips/:tripId/collab rou
for (const handler of [CollabController.prototype.createMessage, CollabController.prototype.addNoteFile]) {
expect(Reflect.getMetadata(TRIP_PERMISSION_KEY, handler)).toBeUndefined();
expect(guardsOn(handler)).not.toContain(TripAccessGuard);
expect(guardsOn(handler)).not.toContain(TripAddonGuard);
}
});
it('every other route asks the trip and then the Collab addon of that trip', async () => {
expect(Reflect.getMetadata(REQUIRE_ADDON, CollabController)).toEqual({ addonId: 'collab', label: 'Collab' });
const multipart = new Set<unknown>([
CollabController.prototype.createMessage,
CollabController.prototype.addNoteFile,
]);
const proto = CollabController.prototype as unknown as Record<string, unknown>;
const routes = Object.getOwnPropertyNames(CollabController.prototype)
.map((name) => proto[name])
.filter((fn) => typeof fn === 'function' && Reflect.getMetadata('method', fn as object) !== undefined)
.filter((fn) => !multipart.has(fn));
expect(routes.length).toBeGreaterThan(15);
for (const handler of routes) expect(guardsOn(handler as object)).toEqual([TripAccessGuard, TripAddonGuard]);
});
});
describe('link preview', () => {
@@ -8,6 +8,7 @@ import 'reflect-metadata';
import { AddonGuard } from '../../../src/nest/addons/addon.guard';
import { REQUIRE_ADDON } from '../../../src/nest/addons/require-addon.decorator';
import { TripAddonGuard } from '../../../src/nest/addons/trip-addon.guard';
import { JwtAuthGuard } from '../../../src/nest/auth-core/jwt-auth.guard';
import { DomainError } from '../../../src/nest/common/domain-error';
import { TRIP_PERMISSION_KEY, TripAccessGuard } from '../../../src/nest/permissions/trip-access.guard';
@@ -59,7 +60,7 @@ describe('CollectionToursController', () => {
expect(Reflect.getMetadata(PATH_METADATA, CollectionToursController)).toBe(
'api/addons/collections/:collectionId/tours',
);
expect(Reflect.getMetadata(GUARDS_METADATA, CollectionToursController)).toEqual([AddonGuard, JwtAuthGuard]);
expect(Reflect.getMetadata(GUARDS_METADATA, CollectionToursController)).toEqual([JwtAuthGuard, AddonGuard]);
expect(Reflect.getMetadata(REQUIRE_ADDON, CollectionToursController)).toEqual({ addonId: 'tours', label: 'Tours' });
const proto = CollectionToursController.prototype;
expect(route(proto, 'list')).toMatchObject({ path: '/', verb: RequestMethod.GET });
@@ -98,9 +99,9 @@ describe('CollectionTourTakeOverController', () => {
it('LIB3-CTRL-004: is trip-scoped, needs place_edit and hands the body on', async () => {
expect(Reflect.getMetadata(PATH_METADATA, CollectionTourTakeOverController)).toBe('api/trips/:tripId/tours');
expect(Reflect.getMetadata(GUARDS_METADATA, CollectionTourTakeOverController)).toEqual([
AddonGuard,
JwtAuthGuard,
TripAccessGuard,
TripAddonGuard,
]);
expect(route(CollectionTourTakeOverController.prototype, 'takeOver')).toEqual({
path: 'from-collection',
@@ -215,12 +215,16 @@ describe('CollectionToursMcp', () => {
if (entry?.kind !== 'tool') throw new Error(`${name} is no tool`);
return entry.options;
};
const enabled = vi.spyOn(t.get(AddonsService), 'isAddonEnabled').mockResolvedValue(true);
// Collections is an instance addon, Tours a trip addon that is on for the caller while the instance
// or any trip of theirs has it on.
const collections = vi.spyOn(t.get(AddonsService), 'isAddonEnabled').mockResolvedValue(true);
const tours = vi.spyOn(t.get(AddonsService), 'isEnabledForUserAnywhere').mockResolvedValue(true);
const gate = options('listCollectionTours').when;
expect(await gate?.(ctx(1), mcp)).toBe(true);
enabled.mockImplementation(async (id: string) => id !== 'collections');
collections.mockImplementation(async (id: string) => id !== 'collections');
expect(await gate?.(ctx(1), mcp)).toBe(false);
enabled.mockImplementation(async (id: string) => id !== 'tours');
collections.mockResolvedValue(true);
tours.mockImplementation(async (_userId: number, id: string) => id !== 'tours');
expect(await gate?.(ctx(1), mcp)).toBe(false);
const allowed = (name: string, scopes: string[]) => {
@@ -19,7 +19,7 @@ import { createSnapshotTestDb } from '../../helpers/db-mock';
import { addCollectionMember, makeCollection } from '../../helpers/factories/collections';
import { makePlace } from '../../helpers/factories/places';
import { countRows, deleteRows, findRow, findRows, updateRows } from '../../helpers/factories/rows';
import { setAddonEnabled } from '../../helpers/factories/settings';
import { setAddonEnabled, setTripAddon } from '../../helpers/factories/settings';
import { addTourWaypoints, makeTour } from '../../helpers/factories/tours';
import { addTripMember, makeTrip } from '../../helpers/factories/trips';
import { makeUser } from '../../helpers/factories/users';
@@ -399,4 +399,17 @@ describe('CollectionToursService', () => {
),
).toEqual(off);
});
it('LIB3-SVC-013: a trip with Tours off has no tour to keep and is no target, the instance on', async () => {
const f = await fixture();
const tour = await keep(f);
vi.spyOn(t.get(PermissionsService), 'checkPermission').mockResolvedValue(true);
await setTripAddon(orm, f.alps.id, 'tours', false);
expect(
await refusal(service.save(f.owner.id, f.list.id, { source_trip_id: f.alps.id, source_place_id: f.ridge.id })),
).toEqual({ status: 404, error: 'Tour not found' });
expect(await countRows(orm, CollectionTours)).toBe(1);
const detail = await service.detail({ id: f.owner.id, role: 'user' }, f.list.id, tour.id);
expect(detail.trips.map((trip) => trip.title).sort()).toEqual(['Away', 'Next']);
});
});
@@ -283,11 +283,8 @@ const sqlTime = (modifier: string): string =>
// test-sql-allow: the timestamp has to come from SQLite's own clock, the one CURRENT_TIMESTAMP compares against.
(testDb.prepare("SELECT datetime('now', ?) AS t").get(modifier) as { t: string }).t;
/**
* The Documents addon. Every binding asks it before it runs, so a double that
* always says yes would hide the one case worth a test.
*/
const addons = { isAddonEnabled: vi.fn(() => true) };
/** The Documents addon (instance, then trip). An always-yes double would hide the one case worth a test. */
const addons = { isAddonEnabled: vi.fn(() => true), isEnabledForTrip: vi.fn(async (_t: number, _a: string) => true) };
/** The admin's per-provider switch, which is a real row rather than a double. */
const switchProvider = (id: string, on: boolean) =>
@@ -1070,14 +1067,16 @@ describe('DocSyncService', () => {
expect(await itemRow(itemId)).toEqual(itemBefore);
});
it('stands down the same way while the Documents addon is off', async () => {
it.each(['instance', 'trip'] as const)('stands down the same way with Documents off for the %s', async (where) => {
const link = await makeLink();
const before = await linkRow(link.id);
addons.isAddonEnabled.mockReturnValue(false);
if (where === 'instance') addons.isAddonEnabled.mockReturnValue(false);
else addons.isEnabledForTrip.mockResolvedValue(false);
const res = await service.syncLink(link);
expect(res.state).toBe('disabled');
if (where === 'trip') expect(addons.isEnabledForTrip).toHaveBeenCalledWith(link.trip_id, 'documents');
expect(provider.list).not.toHaveBeenCalled();
expect(await linkRow(link.id)).toEqual(before);
});
+73 -29
View File
@@ -1,9 +1,13 @@
import type { AddonsService } from '../../../src/nest/addons/addons.service';
import { REQUIRE_ADDON } from '../../../src/nest/addons/require-addon.decorator';
import { TripAddonGuard } from '../../../src/nest/addons/trip-addon.guard';
import { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service';
import { isDemoEmail } from '../../../src/nest/common/demo';
import { DomainError } from '../../../src/nest/common/domain-error';
import { FilesDownloadController } from '../../../src/nest/files/files-download.controller';
import { FilesController } from '../../../src/nest/files/files.controller';
import type { FilesService } from '../../../src/nest/files/files.service';
import { TripAccessGuard } from '../../../src/nest/permissions/trip-access.guard';
import { PhotosController } from '../../../src/nest/photos/photos.controller';
import type { PhotosService } from '../../../src/nest/photos/photos.service';
import type { StorageService } from '../../../src/nest/storage/storage.service';
@@ -29,9 +33,13 @@ function fsvc(o: Partial<FilesService> = {}): FilesService {
const storageStub = { put: vi.fn().mockResolvedValue(undefined) } as unknown as StorageService;
/** Whether Documents applies to the trip: on, unless a test switches it off for its trip. */
const addonsOn = { isEnabledForTrip: vi.fn(async () => true) } as unknown as AddonsService;
const addonsOff = { isEnabledForTrip: vi.fn(async () => false) } as unknown as AddonsService;
/** Construct the controller with the standard env + storage stubs. */
function fc(svc: FilesService): FilesController {
return new FilesController(svc, new RuntimeEnvService(), storageStub);
function fc(svc: FilesService, addons: AddonsService = addonsOn): FilesController {
return new FilesController(svc, new RuntimeEnvService(), storageStub, addons);
}
function thrown(fn: () => unknown): { status: number; body: unknown } {
@@ -66,6 +74,21 @@ const trip = { id: 5, user_id: 42 } as never;
// The 404 "Trip not found" cases moved to trip-access.guard.test.ts with the check.
describe('FilesController (parity with the legacy /api/trips/:tripId/files route)', () => {
it('every route but the multipart upload asks the trip and then the Documents addon of that trip', () => {
expect(Reflect.getMetadata(REQUIRE_ADDON, FilesController)).toEqual({ addonId: 'documents', label: 'Documents' });
const proto = FilesController.prototype as unknown as Record<string, unknown>;
const routes = Object.getOwnPropertyNames(FilesController.prototype)
.map((name) => proto[name])
.filter((fn) => typeof fn === 'function' && Reflect.getMetadata('method', fn as object) !== undefined);
const guarded = routes.filter((fn) => fn !== FilesController.prototype.upload);
expect(guarded.length).toBeGreaterThan(8);
for (const handler of guarded) {
expect(Reflect.getMetadata('__guards__', handler as object)).toEqual([TripAccessGuard, TripAddonGuard]);
}
// A guard on the multipart route would answer before multer read the body (ECONNRESET), so it checks inside.
expect(Reflect.getMetadata('__guards__', FilesController.prototype.upload)).toBeUndefined();
});
it('GET / lists with the trash flag', async () => {
const listFiles = vi.fn().mockReturnValue([{ id: 1 }]);
expect(await fc(fsvc({ listFiles } as Partial<FilesService>)).list(user, trip, '5', 'true')).toEqual({
@@ -86,6 +109,16 @@ describe('FilesController (parity with the legacy /api/trips/:tripId/files route
});
const file = { filename: 'a.pdf' } as Express.Multer.File;
it('404 while Documents is off for the trip, after the trip check and before anything is stored', async () => {
const svc = fsvc({ verifyTripAccess: vi.fn().mockReturnValue({ id: 5, user_id: 1 }) });
expect(await rejected(fc(svc, addonsOff).upload(user, '5', file, {}))).toEqual({
status: 404,
body: { error: 'Documents addon is not enabled' },
});
expect(addonsOff.isEnabledForTrip).toHaveBeenCalledWith(5, 'documents');
expect(storageStub.put).not.toHaveBeenCalled();
});
it('403 in demo mode for a demo email', async () => {
process.env.DEMO_MODE = 'true';
vi.mocked(isDemoEmail).mockReturnValue(true);
@@ -439,7 +472,7 @@ describe('FilesDownloadController', () => {
const s = dsvc({
authenticateDownload: vi.fn().mockRejectedValue(new DomainError(401, 'Authentication required')),
});
expect(await rejected(new FilesDownloadController(s, dstor()).download(req, res, '5', '9'))).toEqual({
expect(await rejected(new FilesDownloadController(s, dstor(), addonsOn).download(req, res, '5', '9'))).toEqual({
status: 401,
body: { error: 'Authentication required' },
});
@@ -448,45 +481,56 @@ describe('FilesDownloadController', () => {
it('404 without trip access and 404 for an unknown file', async () => {
expect(
await rejected(
new FilesDownloadController(dsvc({ verifyTripAccess: vi.fn().mockReturnValue(undefined) }), dstor()).download(
req,
res,
'5',
'9',
),
new FilesDownloadController(
dsvc({ verifyTripAccess: vi.fn().mockReturnValue(undefined) }),
dstor(),
addonsOn,
).download(req, res, '5', '9'),
),
).toEqual({ status: 404, body: { error: 'Trip not found' } });
expect(
await rejected(
new FilesDownloadController(dsvc({ getFileById: vi.fn().mockReturnValue(undefined) }), dstor()).download(
req,
res,
'5',
'9',
),
new FilesDownloadController(
dsvc({ getFileById: vi.fn().mockReturnValue(undefined) }),
dstor(),
addonsOn,
).download(req, res, '5', '9'),
),
).toEqual({ status: 404, body: { error: 'File not found' } });
});
it('404 while Documents is off for the trip, before the file is looked up', async () => {
const s = dsvc({ verifyTripAccess: vi.fn().mockReturnValue({ id: 5, user_id: 1 }) });
expect(await rejected(new FilesDownloadController(s, dstor(), addonsOff).download(req, res, '5', '9'))).toEqual({
status: 404,
body: { error: 'Documents addon is not enabled' },
});
expect(s.getFileById).not.toHaveBeenCalled();
});
it('404 when the object is gone from storage', async () => {
const storage = dstor({ exists: vi.fn().mockResolvedValue(false) });
expect(await rejected(new FilesDownloadController(dsvc(), storage).download(req, res, '5', '9'))).toEqual({
status: 404,
body: { error: 'File not found' },
});
expect(await rejected(new FilesDownloadController(dsvc(), storage, addonsOn).download(req, res, '5', '9'))).toEqual(
{
status: 404,
body: { error: 'File not found' },
},
);
});
it('404 when the stored name is an invalid key (exists rejects)', async () => {
const storage = dstor({ exists: vi.fn().mockRejectedValue(new Error('invalid storage key')) });
expect(await rejected(new FilesDownloadController(dsvc(), storage).download(req, res, '5', '9'))).toEqual({
status: 404,
body: { error: 'File not found' },
});
expect(await rejected(new FilesDownloadController(dsvc(), storage, addonsOn).download(req, res, '5', '9'))).toEqual(
{
status: 404,
body: { error: 'File not found' },
},
);
});
it('streams a regular file through storage with no wallet headers', async () => {
const storage = dstor();
await new FilesDownloadController(dsvc(), storage).download(req, res, '5', '9');
await new FilesDownloadController(dsvc(), storage, addonsOn).download(req, res, '5', '9');
expect(storage.exists).toHaveBeenCalledWith('files', 'x.pdf');
expect(storage.sendToResponse).toHaveBeenCalledWith('files', 'x.pdf', res, undefined);
});
@@ -494,7 +538,7 @@ describe('FilesDownloadController', () => {
it('tolerates a stray prefixed row via basename(), same as the download controller', async () => {
const storage = dstor();
const s = dsvc({ getFileById: vi.fn().mockReturnValue({ filename: 'files/x.pdf', original_name: 'x.pdf' }) });
await new FilesDownloadController(s, storage).download(req, res, '5', '9');
await new FilesDownloadController(s, storage, addonsOn).download(req, res, '5', '9');
expect(storage.sendToResponse).toHaveBeenCalledWith('files', 'x.pdf', res, undefined);
});
@@ -503,7 +547,7 @@ describe('FilesDownloadController', () => {
const s = dsvc({
getFileById: vi.fn().mockReturnValue({ filename: 'pass.pkpass', original_name: 'BoardingPass.pkpass' }),
});
await new FilesDownloadController(s, storage).download(req, res, '5', '9');
await new FilesDownloadController(s, storage, addonsOn).download(req, res, '5', '9');
expect(storage.sendToResponse).toHaveBeenCalledWith('files', 'pass.pkpass', res, {
contentType: 'application/vnd.apple.pkpass',
disposition: 'inline; filename="BoardingPass.pkpass"',
@@ -515,7 +559,7 @@ describe('FilesDownloadController', () => {
const s = dsvc({
getFileById: vi.fn().mockReturnValue({ filename: 'passes.pkpasses', original_name: 'BoardingPasses.pkpasses' }),
});
await new FilesDownloadController(s, storage).download(req, res, '5', '9');
await new FilesDownloadController(s, storage, addonsOn).download(req, res, '5', '9');
expect(storage.sendToResponse).toHaveBeenCalledWith('files', 'passes.pkpasses', res, {
contentType: 'application/vnd.apple.pkpasses',
disposition: 'inline; filename="BoardingPasses.pkpasses"',
@@ -525,7 +569,7 @@ describe('FilesDownloadController', () => {
it('falls back to the stored basename when a .pkpass has no original name', async () => {
const storage = dstor();
const s = dsvc({ getFileById: vi.fn().mockReturnValue({ filename: 'pass.pkpass', original_name: null }) });
await new FilesDownloadController(s, storage).download(req, res, '5', '9');
await new FilesDownloadController(s, storage, addonsOn).download(req, res, '5', '9');
expect(storage.sendToResponse).toHaveBeenCalledWith('files', 'pass.pkpass', res, {
contentType: 'application/vnd.apple.pkpass',
disposition: 'inline; filename="pass.pkpass"',
@@ -540,7 +584,7 @@ describe('FilesDownloadController', () => {
const s = dsvc({
getFileById: vi.fn().mockReturnValue({ filename: 'pass.pkpass', original_name: '搭乗券.pkpass' }),
});
await new FilesDownloadController(s, storage).download(req, res, '5', '9');
await new FilesDownloadController(s, storage, addonsOn).download(req, res, '5', '9');
expect(storage.sendToResponse).toHaveBeenCalledWith('files', 'pass.pkpass', res, {
contentType: 'application/vnd.apple.pkpass',
disposition: 'inline; filename="download.pkpass"; filename*=UTF-8\'\'%E6%90%AD%E4%B9%97%E5%88%B8.pkpass',
+3 -3
View File
@@ -264,10 +264,10 @@ describe('HikePlanMcp: the tools and their gates', () => {
expect(tools[1].description).toContain('route_pending');
expect(tools[2].description).toContain('expected_revision');
expect(tools[3].description).toContain('skipped');
const isAddonEnabled = vi.fn(async (id: string) => id === 'tours');
const gated = await Promise.all(tools.map((tool) => tool.when?.(ctx(1), { addons: { isAddonEnabled } })));
const isEnabledForUserAnywhere = vi.fn(async (_userId: number, id: string) => id === 'tours');
const gated = await Promise.all(tools.map((tool) => tool.when?.(ctx(1), { addons: { isEnabledForUserAnywhere } })));
expect(gated).toEqual([true, true, true, true]);
expect(isAddonEnabled).toHaveBeenCalledWith('tours');
expect(isEnabledForUserAnywhere).toHaveBeenCalledWith(1, 'tours');
});
it('HIKE-MCP-002: an outsider is refused every tool, and the writes are refused without place_edit, as REST refuses them', async () => {
@@ -25,6 +25,7 @@ import { createUser, createTrip } from '../../../helpers/factories';
import { findRow, findRows } from '../../../helpers/factories/rows';
import { createTestBudgetItemsRepo } from '../../../helpers/files-repos';
import { notificationsStub } from '../../../helpers/notifications';
import { createTestAddonsService } from '../../../helpers/test-addons';
import {
createTestUnitOfWork,
createTestAppSettingsRepo,
@@ -89,6 +90,7 @@ async function makeImportService(): Promise<AirtrailImportService> {
await createTestUsersRepo(db),
await createTestTripsRepo(db),
await createTestBudgetItemsRepo(db),
await createTestAddonsService(db),
),
{ listFlights } as unknown as AirtrailClient,
{
@@ -483,6 +483,25 @@ describe('listed events follow the features that are on', () => {
}
});
it('NPREF-LIST-003: a trip addon a trip of the user switched on lists its rows for that user, not in the defaults', async () => {
const { user: chatty } = createUser(testDb);
const { user: quiet } = createUser(testDb);
const { user: admin } = createAdmin(testDb);
const all = { ...features };
Object.assign(features, {
isAddonEnabled: async (id: string) => id !== 'collab',
isEnabledForUserAnywhere: async (userId: number, id: string) => id === 'collab' && userId === chatty.id,
});
try {
expect((await svc.getPreferencesMatrix(chatty.id, 'user')).event_types).toContain('collab_message');
expect((await svc.getPreferencesMatrix(quiet.id, 'user')).event_types).not.toContain('collab_message');
expect((await svc.getPreferencesMatrix(quiet.id, 'user')).event_types).not.toContain('packing_tagged');
expect((await svc.getInstanceDefaults(admin.id)).event_types).not.toContain('collab_message');
} finally {
Object.assign(features, all);
}
});
it('NPREF-LIST-002: the flight events are listed only while live flight status is on', async () => {
const flights = ['flight_departed', 'flight_delayed', 'flight_landed'];
const { user } = createUser(testDb);
@@ -50,7 +50,7 @@ const region: PaddleRegion = {
describe('PaddleObstaclesController', () => {
it('PADCTL-001: GET api/paddle/obstacles sits behind the Tours addon ahead of the session check', () => {
expect(Reflect.getMetadata(PATH_METADATA, PaddleObstaclesController)).toBe('api/paddle');
expect(Reflect.getMetadata(GUARDS_METADATA, PaddleObstaclesController)).toEqual([AddonGuard, JwtAuthGuard]);
expect(Reflect.getMetadata(GUARDS_METADATA, PaddleObstaclesController)).toEqual([JwtAuthGuard, AddonGuard]);
expect(Reflect.getMetadata(REQUIRE_ADDON, PaddleObstaclesController)).toEqual({ addonId: 'tours', label: 'Tours' });
const handler = PaddleObstaclesController.prototype.inBox;
expect(Reflect.getMetadata(METHOD_METADATA, handler)).toBe(RequestMethod.GET);
@@ -7,9 +7,9 @@
import { ADDON_IDS } from '../../../../src/addons';
import type { McpContext, McpTextResult, ToolOptions } from '../../../../src/nest-mcp';
import { getEntry, type ClassRef } from '../../../../src/nest-mcp/metadata';
import { AddonGuard } from '../../../../src/nest/addons/addon.guard';
import type { AddonsService } from '../../../../src/nest/addons/addons.service';
import { REQUIRE_ADDON } from '../../../../src/nest/addons/require-addon.decorator';
import { TripAddonGuard } from '../../../../src/nest/addons/trip-addon.guard';
import { JwtAuthGuard } from '../../../../src/nest/auth-core/jwt-auth.guard';
import { RESPONSE_CONTRACT_KEY } from '../../../../src/nest/common/response-contract';
import { PaddleRoutingController } from '../../../../src/nest/paddle-routing/paddle-routing.controller';
@@ -56,9 +56,9 @@ describe('PaddleRoutingController', () => {
it('PADROUTE-CTL-001: POST api/trips/:tripId/paddle/route sits behind Tours, the session and the trip, answers 200 on the contract', () => {
expect(Reflect.getMetadata(PATH_METADATA, PaddleRoutingController)).toBe('api/trips/:tripId/paddle');
expect(Reflect.getMetadata(GUARDS_METADATA, PaddleRoutingController)).toEqual([
AddonGuard,
JwtAuthGuard,
TripAccessGuard,
TripAddonGuard,
]);
expect(Reflect.getMetadata(REQUIRE_ADDON, PaddleRoutingController)).toEqual({ addonId: 'tours', label: 'Tours' });
const handler = PaddleRoutingController.prototype.route;
@@ -97,15 +97,16 @@ function makeMcp(accessible: boolean) {
}
describe('PaddleRoutingMcp', () => {
it('PADROUTE-MCP-001: plan_paddle_route is read only, gated on Tours and scoped to reading trips', () => {
it('PADROUTE-MCP-001: plan_paddle_route is read only, gated on Tours and scoped to reading trips', async () => {
const options = toolOptions();
expect(options.name).toBe('plan_paddle_route');
expect(options.annotations?.readOnlyHint).toBe(true);
expect(options.access).toEqual({ group: 'trips', mode: 'read' });
const isAddonEnabled = vi.fn((id: string) => id === ADDON_IDS.TOURS);
const self = { addons: { isAddonEnabled } } as unknown as PaddleRoutingMcp;
expect(options.when?.(ctx, self)).toBe(true);
expect(isAddonEnabled).toHaveBeenCalledWith(ADDON_IDS.TOURS);
// Tours is a trip addon: the tool is offered while it is on for the instance or any trip of the caller.
const isEnabledForUserAnywhere = vi.fn(async (_userId: number, id: string) => id === ADDON_IDS.TOURS);
const self = { addons: { isEnabledForUserAnywhere } } as unknown as PaddleRoutingMcp;
expect(await options.when?.(ctx, self)).toBe(true);
expect(isEnabledForUserAnywhere).toHaveBeenCalledWith(7, ADDON_IDS.TOURS);
});
it('PADROUTE-MCP-002: takes the REST contract plus the trip, with the same defaults and limits', () => {
@@ -23,7 +23,7 @@ function make(over: { readsImages?: boolean; trip?: unknown; addon?: boolean; al
findAccessible: vi.fn(async () => ('trip' in over ? over.trip : { user_id: 5 })),
} as unknown as TripsRepository),
{ checkPermission } as unknown as PermissionsService,
{ isAddonEnabled: vi.fn(async () => over.addon ?? true) } as unknown as AddonsService,
{ isEnabledForTrip: vi.fn(async () => over.addon ?? true) } as unknown as AddonsService,
);
return { c, startReceipt, checkPermission };
}
@@ -12,6 +12,7 @@ import { Trips } from '../../../src/db/entities/Trips.entity';
import type { AppSettingsRepository } from '../../../src/db/repositories/AppSettings.repository';
import type { TodoItemsRepository } from '../../../src/db/repositories/TodoItems.repository';
import type { TripsRepository } from '../../../src/db/repositories/Trips.repository';
import type { AddonsService } from '../../../src/nest/addons/addons.service';
import type { NotificationsService } from '../../../src/nest/notifications/notifications.service';
import { ReminderJobsService } from '../../../src/nest/notifications/reminder-jobs.service';
import type { CronRegistrarService } from '../../../src/nest/scheduling/cron-registrar.service';
@@ -23,7 +24,9 @@ import {
setNotificationChannels,
} from '../../helpers/factories';
import { findRow, updateRows } from '../../helpers/factories/rows';
import { setTripAddon } from '../../helpers/factories/settings';
import { notificationsStub } from '../../helpers/notifications';
import { createTestAddonsService } from '../../helpers/test-addons';
import { createTestAppSettingsRepo, createTestTripsRepo } from '../../helpers/test-uow';
import { sharedTestOrm } from '../../helpers/test-uow';
import { createTestTodoItemsRepo } from '../../helpers/todo-repos';
@@ -69,6 +72,7 @@ interface Registered {
let appSettingsRepo: AppSettingsRepository;
let tripsRepo: TripsRepository;
let todoItemsRepo: TodoItemsRepository;
let addonsSvc: AddonsService;
function makeJobs(overrides: { notifications?: NotificationsService } = {}) {
const registered: Registered[] = [];
@@ -94,6 +98,7 @@ function makeJobs(overrides: { notifications?: NotificationsService } = {}) {
todoItemsRepo,
overrides.notifications ?? notificationsStub(send),
registrar as unknown as CronRegistrarService,
addonsSvc,
);
return { svc, registered, registrar, send };
}
@@ -122,6 +127,7 @@ beforeAll(async () => {
appSettingsRepo = await createTestAppSettingsRepo(testDb);
tripsRepo = await createTestTripsRepo(testDb);
todoItemsRepo = await createTestTodoItemsRepo(testDb);
addonsSvc = await createTestAddonsService(testDb);
});
beforeEach(() => {
@@ -347,6 +353,19 @@ describe('todo reminder tick', () => {
expect(send).not.toHaveBeenCalled();
});
it('RJOB-018: a trip that has Lists off is reminded of no todo, and the todo stays unclaimed', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Porto' });
const todo = createTodoItem(testDb, trip.id, { name: 'Book ferry' });
await setTodo(todo.id, { due_date: dayFromToday(1) });
await setTripAddon(await orm(), trip.id, 'packing', false);
const { svc, send } = makeJobs();
await svc.todoTick();
expect(send).not.toHaveBeenCalled();
expect(await remindedAtOf(todo.id)).toBeNull();
});
it('RJOB-009 — an assigned todo notifies the assignee (user scope)', async () => {
const { user } = createUser(testDb);
const { user: assignee } = createUser(testDb, { email: 'b@example.test', username: 'assignee' });
@@ -67,6 +67,8 @@ import { countRows, deleteRows, findRow, findRows, insertRow, updateRows } from
import { makeReservation } from '../../helpers/factories/reservations';
import { makeTrip, readTripDays } from '../../helpers/factories/trips';
import { makeUser } from '../../helpers/factories/users';
import { setTripAddon } from '../../helpers/factories/settings';
import { createTestAddonsService } from '../../helpers/test-addons';
import { BudgetItems } from '../../../src/db/entities/BudgetItems.entity';
import { DayAccommodations } from '../../../src/db/entities/DayAccommodations.entity';
import { DayAssignments } from '../../../src/db/entities/DayAssignments.entity';
@@ -84,7 +86,7 @@ const broadcast = realtime.broadcastMock;
let svc: ReservationsService;
let orm: TestOrm;
beforeAll(async () => {
svc = new ReservationsService(permissionsStub, budget as unknown as BudgetService, realtime, notificationsStub(notif.send), new ReservationsReadService(await createTestReservationsRepo(testDb), await createTestReservationEndpointsRepo(testDb), await createTestReservationTravelersRepo(testDb), await createTestReservationDayPositionsRepo(testDb)), await makeAccommodationsService(testDb, realtime), await createTestUnitOfWork(testDb), await createTestReservationsRepo(testDb), await createTestReservationEndpointsRepo(testDb), await createTestReservationTravelersRepo(testDb), await createTestReservationDayPositionsRepo(testDb), await createTestDayAccommodationsRepo(testDb), await createTestDaysRepo(testDb), await createTestPlacesRepo(testDb), await createTestDayAssignmentsRepo(testDb), await createTestTripMembersRepo(testDb), await createTestUsersRepo(testDb), await createTestTripsRepo(testDb), await createTestBudgetItemsRepo(testDb));
svc = new ReservationsService(permissionsStub, budget as unknown as BudgetService, realtime, notificationsStub(notif.send), new ReservationsReadService(await createTestReservationsRepo(testDb), await createTestReservationEndpointsRepo(testDb), await createTestReservationTravelersRepo(testDb), await createTestReservationDayPositionsRepo(testDb)), await makeAccommodationsService(testDb, realtime), await createTestUnitOfWork(testDb), await createTestReservationsRepo(testDb), await createTestReservationEndpointsRepo(testDb), await createTestReservationTravelersRepo(testDb), await createTestReservationDayPositionsRepo(testDb), await createTestDayAccommodationsRepo(testDb), await createTestDaysRepo(testDb), await createTestPlacesRepo(testDb), await createTestDayAssignmentsRepo(testDb), await createTestTripMembersRepo(testDb), await createTestUsersRepo(testDb), await createTestTripsRepo(testDb), await createTestBudgetItemsRepo(testDb), await createTestAddonsService(testDb));
});
beforeEach(async () => {
@@ -843,6 +845,22 @@ describe('ReservationsService (DI-native, real SQL)', () => {
svc.announceCost(String(trip.id), out.costEvents, 'sock');
expect(broadcast).toHaveBeenCalledWith(String(trip.id), 'budget:updated', { item: { id: item.id } }, 'sock');
});
it('RESV-TX-008: with Costs off for the trip an edit leaves the linked cost as it is, cleared price and new type alike', async () => {
const { trip, res, item } = await linkedItem({ total_price: 100, category: 'other' });
await updateRows(orm, Reservations, { id: res.id }, { title: 'Old', type: 'other' });
await setTripAddon(orm, trip.id, 'budget', false);
const current = await svc.getReservation(String(res.id), String(trip.id));
if (!current) throw new Error('the booking was not written');
const out = await svc.updateWithCost(String(res.id), String(trip.id), { title: 'New', type: 'flight' } as never, current, { total_price: 0 });
expect(out.costEvents).toEqual([]);
expect(budget.deleteBudgetItem).not.toHaveBeenCalled();
expect(budget.updateBudgetItem).not.toHaveBeenCalled();
expect(await findRow(orm, BudgetItems, { id: item.id })).toMatchObject({ total_price: 100, category: 'other' });
expect(await findRow(orm, Reservations, { id: res.id })).toMatchObject({ title: 'New', type: 'flight' });
});
});
describe('createWithCost', () => {
@@ -868,6 +886,17 @@ describe('ReservationsService (DI-native, real SQL)', () => {
expect(broadcast).not.toHaveBeenCalled();
});
it('RESV-TX-009: with Costs off for the trip the booking is written without its cost', async () => {
const { trip } = ownerTrip();
await setTripAddon(orm, trip.id, 'budget', false);
const out = await svc.createWithCost(String(trip.id), { title: 'Hotel', type: 'other' } as never, { total_price: 200 });
expect(out.reservation.id).toBeGreaterThan(0);
expect(out.costEvents).toEqual([]);
expect(budget.linkBudgetItemToReservation).not.toHaveBeenCalled();
});
it('RESV-TX-005: without a price there is no cost and no event', async () => {
const { trip } = ownerTrip();
const out = await svc.createWithCost(String(trip.id), { title: 'Dinner' } as never, undefined);
@@ -337,7 +337,7 @@ describe('browser-independent roadtrip calculation', () => {
expect(body.undatedRides).toEqual([]);
expect(body.days.length).toBeGreaterThan(0);
// And the tool says what the field is, or an assistant has no reason to read it.
const addons = { isAddonEnabled: vi.fn(() => true) };
const addons = { isEnabledForUserAnywhere: vi.fn(async () => true) };
const registry = createTestRegistry([new RoadtripPlanningMcp(s.plans, {} as never, addons as never)], {
accessPolicy: trekMcpAccessPolicy,
validateAccess: trekMcpValidateAccess,
@@ -397,7 +397,7 @@ describe('Roadtrip MCP registration and search', () => {
});
it('hides addon tools when disabled and separates settings reads from writes', async () => {
const s = setup();
const addons = { isAddonEnabled: vi.fn(() => true) };
const addons = { isEnabledForUserAnywhere: vi.fn(async () => true) };
const registry = createTestRegistry(
[
new RoadtripPreferencesMcp(s.preferences, addons as never, s.tripsRepo as never, {} as never),
@@ -415,7 +415,7 @@ describe('Roadtrip MCP registration and search', () => {
expect(names).toContain('get_roadtrip_settings');
expect(names).not.toContain('update_roadtrip_settings');
names.length = 0;
addons.isAddonEnabled.mockReturnValue(false);
addons.isEnabledForUserAnywhere.mockResolvedValue(false);
await registry.attach(registrar as never, { ...ctx, scopes: null });
expect(names).toEqual([]);
});
@@ -425,11 +425,11 @@ describe('Roadtrip MCP registration and search', () => {
[
new RoadtripPreferencesMcp(
s.preferences,
{ isAddonEnabled: () => true } as never,
{ isEnabledForUserAnywhere: async () => true } as never,
s.tripsRepo as never,
{} as never,
),
new RoadtripPlanningMcp(s.plans, {} as never, { isAddonEnabled: () => true } as never),
new RoadtripPlanningMcp(s.plans, {} as never, { isEnabledForUserAnywhere: async () => true } as never),
],
{ accessPolicy: trekMcpAccessPolicy, validateAccess: trekMcpValidateAccess },
);
@@ -102,7 +102,7 @@ describe('roadtrip read tools', () => {
{} as never,
{} as never,
{} as never,
{ isAddonEnabled: () => true } as never,
{ isEnabledForUserAnywhere: async () => true } as never,
);
const registry = createTestRegistry([tool], {
accessPolicy: trekMcpAccessPolicy,
@@ -10,7 +10,7 @@
* The guard chain is asserted through the decorator metadata rather than by
* booting Nest: the controller's own comment calls the ORDER load-bearing, and
* a class-level assertion is the only thing that fails when somebody removes
* AddonGuard again. `@RequireAddon` is metadata and does nothing on its own, so
* TripAddonGuard again. `@RequireAddon` is metadata and does nothing on its own, so
* dropping the guard from the list is a silent regression that opens all seven
* routes on an instance that switched the addon off.
*
@@ -18,7 +18,7 @@
* siblings, pinned in roadtrip.service.test.ts); here only that every write
* hands it the REST writer of this trip, user and socket.
*/
import { AddonGuard } from '../../../src/nest/addons/addon.guard';
import { TripAddonGuard } from '../../../src/nest/addons/trip-addon.guard';
import { JwtAuthGuard } from '../../../src/nest/auth-core/jwt-auth.guard';
import type { TripWriter } from '../../../src/nest/common/trip-writer';
import { TripAccessGuard } from '../../../src/nest/permissions/trip-access.guard';
@@ -64,17 +64,17 @@ async function thrown(fn: () => unknown): Promise<{ status: number; body: unknow
}
describe('RoadtripController — the guard chain', () => {
it('ROADTRIP-CTL-001: the addon gate leads, and the auth and trip guards follow', () => {
it('ROADTRIP-CTL-001: auth and the trip lead, and the addon gate of the trip follows', () => {
const guards = Reflect.getMetadata(GUARDS_METADATA, RoadtripController) as unknown[];
// AddonGuard first, and present at all: @RequireAddon is metadata and inert
// TripAddonGuard present at all: @RequireAddon is metadata and inert
// without it, and the guard is not registered globally either. Without this
// line all seven routes answered on an instance that had the addon off,
// which is the bug this branch fixed once already.
expect(guards).toEqual([AddonGuard, JwtAuthGuard, TripAccessGuard]);
// It leads because a disabled addon owes an anonymous caller a 404 rather
// than a 401 that tells them the route exists.
expect(guards[0]).toBe(AddonGuard);
expect(guards).toEqual([JwtAuthGuard, TripAccessGuard, TripAddonGuard]);
// It follows TripAccessGuard because what applies is the trip's own choice,
// which only somebody who may see the trip gets to learn.
expect(guards[guards.length - 1]).toBe(TripAddonGuard);
});
});
@@ -42,6 +42,7 @@ import {
import { deleteRows, findRow, insertRow, updateRows } from '../../helpers/factories/rows';
import { setAppSetting, setUserSetting } from '../../helpers/factories/settings';
import { shareServiceRepoArgs } from '../../helpers/share-repos';
import { createTestAddonsService } from '../../helpers/test-addons';
import { resetTestDb } from '../../helpers/test-db';
import { createTestModule, type TestModule } from '../../helpers/test-module';
import type { TestOrm } from '../../helpers/test-orm';
@@ -102,6 +103,7 @@ beforeAll(async () => {
photoCacheStub,
await createTestUnitOfWork(testDb),
...(await shareServiceRepoArgs(testDb)),
await createTestAddonsService(testDb),
);
});
@@ -7,9 +7,9 @@
import { ADDON_IDS } from '../../../../src/addons';
import type { McpContext, McpTextResult, ToolOptions } from '../../../../src/nest-mcp';
import { getEntry, type ClassRef } from '../../../../src/nest-mcp/metadata';
import { AddonGuard } from '../../../../src/nest/addons/addon.guard';
import type { AddonsService } from '../../../../src/nest/addons/addons.service';
import { REQUIRE_ADDON } from '../../../../src/nest/addons/require-addon.decorator';
import { TripAddonGuard } from '../../../../src/nest/addons/trip-addon.guard';
import { JwtAuthGuard } from '../../../../src/nest/auth-core/jwt-auth.guard';
import { RESPONSE_CONTRACT_KEY } from '../../../../src/nest/common/response-contract';
import { TripAccessGuard } from '../../../../src/nest/permissions/trip-access.guard';
@@ -96,9 +96,9 @@ describe('SkiRoutingController', () => {
it('SKICTL-001: the routes sit behind Tours, the session and the trip, each on its contract', () => {
expect(Reflect.getMetadata(PATH_METADATA, SkiRoutingController)).toBe('api/trips/:tripId/ski');
expect(Reflect.getMetadata(GUARDS_METADATA, SkiRoutingController)).toEqual([
AddonGuard,
JwtAuthGuard,
TripAccessGuard,
TripAddonGuard,
]);
expect(Reflect.getMetadata(REQUIRE_ADDON, SkiRoutingController)).toEqual({ addonId: 'tours', label: 'Tours' });
const { route, areaNear, network } = SkiRoutingController.prototype;
@@ -160,15 +160,16 @@ function makeMcp(accessible: boolean) {
}
describe('SkiRoutingMcp', () => {
it('SKIMCP-001: plan_ski_route is read only, gated on Tours and scoped to reading trips', () => {
it('SKIMCP-001: plan_ski_route is read only, gated on Tours and scoped to reading trips', async () => {
const options = toolOptions();
expect(options.name).toBe('plan_ski_route');
expect(options.annotations?.readOnlyHint).toBe(true);
expect(options.access).toEqual({ group: 'trips', mode: 'read' });
const isAddonEnabled = vi.fn((id: string) => id === ADDON_IDS.TOURS);
const self = { addons: { isAddonEnabled } } as unknown as SkiRoutingMcp;
expect(options.when?.(ctx, self)).toBe(true);
expect(isAddonEnabled).toHaveBeenCalledWith(ADDON_IDS.TOURS);
// Tours is a trip addon: the tool is offered while it is on for the instance or any trip of the caller.
const isEnabledForUserAnywhere = vi.fn(async (_userId: number, id: string) => id === ADDON_IDS.TOURS);
const self = { addons: { isEnabledForUserAnywhere } } as unknown as SkiRoutingMcp;
expect(await options.when?.(ctx, self)).toBe(true);
expect(isEnabledForUserAnywhere).toHaveBeenCalledWith(7, ADDON_IDS.TOURS);
});
it('SKIMCP-002: takes the REST contract plus the trip, with the same defaults and limits', () => {
@@ -6,8 +6,8 @@
*/
import 'reflect-metadata';
import { AddonGuard } from '../../../src/nest/addons/addon.guard';
import { REQUIRE_ADDON } from '../../../src/nest/addons/require-addon.decorator';
import { TripAddonGuard } from '../../../src/nest/addons/trip-addon.guard';
import { JwtAuthGuard } from '../../../src/nest/auth-core/jwt-auth.guard';
import { TRIP_PERMISSION_KEY, TripAccessGuard } from '../../../src/nest/permissions/trip-access.guard';
import { TourActivitiesController } from '../../../src/nest/tours/tour-activities.controller';
@@ -32,9 +32,9 @@ describe('TourActivitiesController', () => {
'api/trips/:tripId/tours/:placeId/activities',
);
expect(Reflect.getMetadata(GUARDS_METADATA, TourActivitiesController)).toEqual([
AddonGuard,
JwtAuthGuard,
TripAccessGuard,
TripAddonGuard,
]);
expect(Reflect.getMetadata(REQUIRE_ADDON, TourActivitiesController)).toEqual({ addonId: 'tours', label: 'Tours' });
});
@@ -28,7 +28,7 @@ const answer = { entries: [], uncounted: { unassigned: 0, undated: 0 } };
describe('TourActivityStatsController', () => {
it('STA2-CTL-001: sits behind the addon and auth guards, not under a trip', () => {
expect(Reflect.getMetadata(PATH_METADATA, TourActivityStatsController)).toBe('api/tours/activity-stats');
expect(Reflect.getMetadata(GUARDS_METADATA, TourActivityStatsController)).toEqual([AddonGuard, JwtAuthGuard]);
expect(Reflect.getMetadata(GUARDS_METADATA, TourActivityStatsController)).toEqual([JwtAuthGuard, AddonGuard]);
expect(Reflect.getMetadata(REQUIRE_ADDON, TourActivityStatsController)).toEqual({
addonId: 'tours',
label: 'Tours',
@@ -419,9 +419,9 @@ describe('TourChangeMcp.saveTourChange (MCP-T03)', () => {
const confirmed = z.object(options.inputSchema as ZodRawShape).pick({ confirmed: true });
const yes = [true, false, undefined].map((value) => confirmed.safeParse({ confirmed: value }).success);
expect(yes).toEqual([true, false, false]);
const isAddonEnabled = vi.fn(async (id: string) => id === 'tours');
expect(await options.when?.(ctx(1), { addons: { isAddonEnabled } })).toBe(true);
expect(isAddonEnabled).toHaveBeenCalledWith('tours');
const isEnabledForUserAnywhere = vi.fn(async (_userId: number, id: string) => id === 'tours');
expect(await options.when?.(ctx(1), { addons: { isEnabledForUserAnywhere } })).toBe(true);
expect(isEnabledForUserAnywhere).toHaveBeenCalledWith(1, 'tours');
});
it('TCHG-SAVE-010: a save sent again once saved writes nothing and answers the step it was saved as', async () => {
@@ -500,11 +500,11 @@ describe('TourChangeUndoMcp (MCP-T04)', () => {
]);
expect(Object.keys(options.inputSchema as object)).toEqual([...fields]);
expect(options.description).toContain('planner');
const isAddonEnabled = vi.fn(async (id: string) => id === 'tours');
return { isAddonEnabled, open: options.when?.(ctx(1), { addons: { isAddonEnabled } }) };
const isEnabledForUserAnywhere = vi.fn(async (_userId: number, id: string) => id === 'tours');
return { isEnabledForUserAnywhere, open: options.when?.(ctx(1), { addons: { isEnabledForUserAnywhere } }) };
});
expect(await Promise.all(gates.map((gate) => gate.open))).toEqual([true, true, true]);
for (const { isAddonEnabled } of gates) expect(isAddonEnabled).toHaveBeenCalledWith('tours');
for (const { isEnabledForUserAnywhere } of gates) expect(isEnabledForUserAnywhere).toHaveBeenCalledWith(1, 'tours');
const entry = getEntry(TourChangeUndoMcp as unknown as ClassRef, 'undoTourChange');
if (!entry || entry.kind !== 'tool') throw new Error('undoTourChange is no MCP tool');
// The fields are zod schemas from @trek/shared, read here by what they answer.
@@ -292,8 +292,8 @@ describe('TourChangeMcp (MCP-T02)', () => {
]);
const terms = ['revision', 'spontaneous stop', 'protected', 'visited or skipped', 'data_gaps', 'create_place'];
for (const term of terms) expect(options.description).toContain(term);
const isAddonEnabled = vi.fn(async (id: string) => id === 'tours');
expect(await options.when?.(ctx(1), { addons: { isAddonEnabled } })).toBe(true);
expect(isAddonEnabled).toHaveBeenCalledWith('tours');
const isEnabledForUserAnywhere = vi.fn(async (_userId: number, id: string) => id === 'tours');
expect(await options.when?.(ctx(1), { addons: { isEnabledForUserAnywhere } })).toBe(true);
expect(isEnabledForUserAnywhere).toHaveBeenCalledWith(1, 'tours');
});
});
@@ -4,8 +4,8 @@
*/
import 'reflect-metadata';
import { AddonGuard } from '../../../src/nest/addons/addon.guard';
import { REQUIRE_ADDON } from '../../../src/nest/addons/require-addon.decorator';
import { TripAddonGuard } from '../../../src/nest/addons/trip-addon.guard';
import { JwtAuthGuard } from '../../../src/nest/auth-core/jwt-auth.guard';
import { TRIP_PERMISSION_KEY, TripAccessGuard } from '../../../src/nest/permissions/trip-access.guard';
import { TourDraftsController } from '../../../src/nest/tours/tour-drafts.controller';
@@ -33,9 +33,9 @@ describe('TourDraftsController', () => {
it('TDRAFT-CTL-001: sits behind the addon guard before auth and trip access; only keeping a draft needs place_edit', () => {
expect(Reflect.getMetadata(PATH_METADATA, TourDraftsController)).toBe('api/trips/:tripId/tour-draft');
expect(Reflect.getMetadata(GUARDS_METADATA, TourDraftsController)).toEqual([
AddonGuard,
JwtAuthGuard,
TripAccessGuard,
TripAddonGuard,
]);
expect(Reflect.getMetadata(REQUIRE_ADDON, TourDraftsController)).toEqual({ addonId: 'tours', label: 'Tours' });
const routes = [
@@ -1,6 +1,6 @@
import { ADDON_IDS } from '../../../src/addons';
import { AddonGuard } from '../../../src/nest/addons/addon.guard';
import { REQUIRE_ADDON } from '../../../src/nest/addons/require-addon.decorator';
import { TripAddonGuard } from '../../../src/nest/addons/trip-addon.guard';
import { JwtAuthGuard } from '../../../src/nest/auth-core/jwt-auth.guard';
import { RESPONSE_CONTRACT_KEY } from '../../../src/nest/common/response-contract';
import { TripAccessGuard } from '../../../src/nest/permissions/trip-access.guard';
@@ -70,9 +70,9 @@ describe('TourHorseRoutesController (HOR-01)', () => {
it('HORSE-CTRL-004: sits behind the Tours addon, the session and the trip access, and declares its contract', () => {
expect(Reflect.getMetadata(GUARDS_METADATA, TourHorseRoutesController)).toEqual([
AddonGuard,
JwtAuthGuard,
TripAccessGuard,
TripAddonGuard,
]);
expect(Reflect.getMetadata(REQUIRE_ADDON, TourHorseRoutesController)).toEqual({
addonId: ADDON_IDS.TOURS,
@@ -6,8 +6,8 @@
*/
import 'reflect-metadata';
import { AddonGuard } from '../../../src/nest/addons/addon.guard';
import { REQUIRE_ADDON } from '../../../src/nest/addons/require-addon.decorator';
import { TripAddonGuard } from '../../../src/nest/addons/trip-addon.guard';
import { JwtAuthGuard } from '../../../src/nest/auth-core/jwt-auth.guard';
import { TRIP_PERMISSION_KEY, TripAccessGuard } from '../../../src/nest/permissions/trip-access.guard';
import { TourPackingLinkController } from '../../../src/nest/tours/tour-packing-link.controller';
@@ -34,9 +34,9 @@ describe('TourPackingLinkController', () => {
it('TPL-CTL-001: sits behind the addon guard before auth and trip access; only the writes need place_edit', () => {
expect(Reflect.getMetadata(PATH_METADATA, TourPackingLinkController)).toBe('api/trips/:tripId/tours');
expect(Reflect.getMetadata(GUARDS_METADATA, TourPackingLinkController)).toEqual([
AddonGuard,
JwtAuthGuard,
TripAccessGuard,
TripAddonGuard,
]);
expect(Reflect.getMetadata(REQUIRE_ADDON, TourPackingLinkController)).toEqual({ addonId: 'tours', label: 'Tours' });
const routes = [
@@ -133,14 +133,14 @@ describe('TourPackingMcp', () => {
if (entry?.kind !== 'tool') throw new Error(`${name} is no tool`);
return entry.options;
};
const enabled = vi.spyOn(t.get(AddonsService), 'isAddonEnabled').mockResolvedValue(true);
const enabled = vi.spyOn(t.get(AddonsService), 'isEnabledForUserAnywhere').mockResolvedValue(true);
const gates = ['getTourPacking', 'linkTourPacking', 'unlinkTourPacking'].map((name) => options(name).when);
const open = () => Promise.all(gates.map((gate) => gate?.(ctx(1), mcp)));
enabled.mockResolvedValue(true);
expect(await open()).toEqual([true, true, true]);
enabled.mockImplementation(async (id: string) => id !== 'packing');
enabled.mockImplementation(async (_userId: number, id: string) => id !== 'packing');
expect(await open()).toEqual([false, false, false]);
enabled.mockImplementation(async (id: string) => id !== 'tours');
enabled.mockImplementation(async (_userId: number, id: string) => id !== 'tours');
expect(await open()).toEqual([false, false, false]);
const allowed = (name: string, scopes: string[]) => {
+2 -2
View File
@@ -246,8 +246,8 @@ describe('TourPlanMcp: the tools and their gates', () => {
expect(tools[1].description).toContain('run_pace_seconds_per_km');
expect(tools[2].description).toContain('water_context');
expect(tools[3].description).toContain('discipline');
const isAddonEnabled = vi.fn(async (id: string) => id === 'tours');
const gated = await Promise.all(tools.map((tool) => tool.when?.(ctx(1), { addons: { isAddonEnabled } })));
const isEnabledForUserAnywhere = vi.fn(async (_userId: number, id: string) => id === 'tours');
const gated = await Promise.all(tools.map((tool) => tool.when?.(ctx(1), { addons: { isEnabledForUserAnywhere } })));
expect(gated).toEqual([true, true, true, true]);
});
@@ -5,8 +5,8 @@
*/
import 'reflect-metadata';
import { AddonGuard } from '../../../src/nest/addons/addon.guard';
import { REQUIRE_ADDON } from '../../../src/nest/addons/require-addon.decorator';
import { TripAddonGuard } from '../../../src/nest/addons/trip-addon.guard';
import { JwtAuthGuard } from '../../../src/nest/auth-core/jwt-auth.guard';
import { RESPONSE_CONTRACT_KEY } from '../../../src/nest/common/response-contract';
import { TRIP_PERMISSION_KEY, TripAccessGuard } from '../../../src/nest/permissions/trip-access.guard';
@@ -22,9 +22,9 @@ describe('TourSkiController', () => {
it('TOUR-SKI-CTL-001: sits behind the addon guard before auth and trip access, and needs place_edit', () => {
expect(Reflect.getMetadata(PATH_METADATA, TourSkiController)).toBe('api/trips/:tripId/tours/:placeId/ski');
expect(Reflect.getMetadata(GUARDS_METADATA, TourSkiController)).toEqual([
AddonGuard,
JwtAuthGuard,
TripAccessGuard,
TripAddonGuard,
]);
expect(Reflect.getMetadata(REQUIRE_ADDON, TourSkiController)).toEqual({ addonId: 'tours', label: 'Tours' });
const handler = TourSkiController.prototype.classify;
@@ -133,8 +133,8 @@ describe('TourStopsMcp', () => {
['remove_tour_stop', false, { group: 'trips', mode: 'write' }],
]);
expect(tools[0].description).toContain('after_key');
const isAddonEnabled = vi.fn(async (id: string) => id === 'tours');
const gated = await Promise.all(tools.map((tool) => tool.when?.(ctx(1), { addons: { isAddonEnabled } })));
const isEnabledForUserAnywhere = vi.fn(async (_userId: number, id: string) => id === 'tours');
const gated = await Promise.all(tools.map((tool) => tool.when?.(ctx(1), { addons: { isEnabledForUserAnywhere } })));
expect(gated).toEqual([true, true]);
});
@@ -5,8 +5,8 @@
*/
import 'reflect-metadata';
import { AddonGuard } from '../../../src/nest/addons/addon.guard';
import { REQUIRE_ADDON } from '../../../src/nest/addons/require-addon.decorator';
import { TripAddonGuard } from '../../../src/nest/addons/trip-addon.guard';
import { JwtAuthGuard } from '../../../src/nest/auth-core/jwt-auth.guard';
import { TRIP_PERMISSION_KEY, TripAccessGuard } from '../../../src/nest/permissions/trip-access.guard';
import { TourVisitsController } from '../../../src/nest/tours/tour-visits.controller';
@@ -30,9 +30,9 @@ describe('TourVisitsController', () => {
it('TOUR-VISITS-CTL-001: sits behind the addon guard before auth and trip access; only a write needs day_edit', () => {
expect(Reflect.getMetadata(PATH_METADATA, TourVisitsController)).toBe('api/trips/:tripId/tour-visits');
expect(Reflect.getMetadata(GUARDS_METADATA, TourVisitsController)).toEqual([
AddonGuard,
JwtAuthGuard,
TripAccessGuard,
TripAddonGuard,
]);
expect(Reflect.getMetadata(REQUIRE_ADDON, TourVisitsController)).toEqual({ addonId: 'tours', label: 'Tours' });
const routes = [
@@ -4,8 +4,8 @@
*/
import 'reflect-metadata';
import { AddonGuard } from '../../../src/nest/addons/addon.guard';
import { REQUIRE_ADDON } from '../../../src/nest/addons/require-addon.decorator';
import { TripAddonGuard } from '../../../src/nest/addons/trip-addon.guard';
import { JwtAuthGuard } from '../../../src/nest/auth-core/jwt-auth.guard';
import { TRIP_PERMISSION_KEY, TripAccessGuard } from '../../../src/nest/permissions/trip-access.guard';
import { TourWalkImportController } from '../../../src/nest/tours/tour-walk-import.controller';
@@ -28,9 +28,9 @@ describe('TourWalkImportController', () => {
it('WALK-IMPORT-CTL-001: sits behind the addon guard before auth and trip access, and needs place_edit', () => {
expect(Reflect.getMetadata(PATH_METADATA, TourWalkImportController)).toBe('api/trips/:tripId/tours');
expect(Reflect.getMetadata(GUARDS_METADATA, TourWalkImportController)).toEqual([
AddonGuard,
JwtAuthGuard,
TripAccessGuard,
TripAddonGuard,
]);
expect(Reflect.getMetadata(REQUIRE_ADDON, TourWalkImportController)).toEqual({ addonId: 'tours', label: 'Tours' });
const handler = TourWalkImportController.prototype.preview;
@@ -31,7 +31,7 @@ const preview = vi.fn<ToursWandererService['preview']>();
const importTrail = vi.fn<ToursWandererService['import']>();
const checkSource = vi.fn<ToursWandererService['checkSource']>();
const hasTripPermission = vi.fn<McpToolGuardsService['hasTripPermission']>();
const isWandererAvailable = vi.fn<AddonsService['isWandererAvailable']>();
const isWandererAllowed = vi.fn<AddonsService['isWandererAllowed']>();
let t: TestModule;
let mcp: ToursWandererMcp;
const orm = () => t.get(MikroORM);
@@ -66,12 +66,12 @@ beforeAll(async () => {
],
});
mcp = t.get(ToursWandererMcp);
vi.spyOn(t.get(AddonsService), 'isWandererAvailable').mockImplementation(isWandererAvailable);
vi.spyOn(t.get(AddonsService), 'isWandererAllowed').mockImplementation(isWandererAllowed);
});
beforeEach(() => {
resetTestDb(db);
hasTripPermission.mockReset().mockResolvedValue(true);
isWandererAvailable.mockReset().mockResolvedValue(true);
isWandererAllowed.mockReset().mockResolvedValue(true);
search.mockReset().mockResolvedValue({ trails: [TRAIL], total: 1, page: 1, pageSize: 20 });
preview.mockReset().mockResolvedValue({
trail: TRAIL,
@@ -190,7 +190,7 @@ describe('wanderer over MCP', () => {
]);
const gate = options[0]?.when;
expect(await gate?.(ctx(1), mcp)).toBe(true);
isWandererAvailable.mockResolvedValue(false);
isWandererAllowed.mockResolvedValue(false);
expect(await gate?.(ctx(1), mcp)).toBe(false);
});
});
@@ -8,9 +8,9 @@
*/
import 'reflect-metadata';
import { AddonGuard } from '../../../src/nest/addons/addon.guard';
import type { AddonsService } from '../../../src/nest/addons/addons.service';
import { REQUIRE_ADDON } from '../../../src/nest/addons/require-addon.decorator';
import { TripAddonGuard } from '../../../src/nest/addons/trip-addon.guard';
import { JwtAuthGuard } from '../../../src/nest/auth-core/jwt-auth.guard';
import { TRIP_PERMISSION_KEY, TripAccessGuard } from '../../../src/nest/permissions/trip-access.guard';
import type { PlacesService } from '../../../src/nest/places/places.service';
@@ -86,7 +86,7 @@ async function thrownAsync(fn: () => Promise<unknown>): Promise<{ status: number
function importFixture(
o: { addon?: boolean; trip?: typeof trip | undefined; canEdit?: boolean; result?: unknown } = {},
) {
const addons = { isAddonEnabled: vi.fn(async () => o.addon ?? true) };
const addons = { isEnabledForTrip: vi.fn(async () => o.addon ?? true) };
const places = {
verifyTripAccess: vi.fn(async () => ('trip' in o ? o.trip : trip)),
canEdit: vi.fn(async () => o.canEdit ?? true),
@@ -110,9 +110,13 @@ describe('ToursController planner routes', () => {
expect(legacyDatabaseAccess).not.toHaveBeenCalled();
});
it('TOURS-CTL-001: hides every Tours route behind the addon guard before auth', () => {
it('TOURS-CTL-001: hides every Tours route behind the trip addon guard, after trip access', () => {
expect(Reflect.getMetadata(PATH_METADATA, ToursController)).toBe('api/trips/:tripId/tours');
expect(Reflect.getMetadata(GUARDS_METADATA, ToursController)).toEqual([AddonGuard, JwtAuthGuard, TripAccessGuard]);
expect(Reflect.getMetadata(GUARDS_METADATA, ToursController)).toEqual([
JwtAuthGuard,
TripAccessGuard,
TripAddonGuard,
]);
expect(Reflect.getMetadata(REQUIRE_ADDON, ToursController)).toEqual({ addonId: 'tours', label: 'Tours' });
});
@@ -226,15 +230,15 @@ describe('ToursImportController (POST /api/trips/:tripId/tours/import/gpx)', ()
expect(await controller.importGpx(user, '7', file)).toBe(allSkipped);
});
it('TOURS-IMP-004: addon off is the AddonGuard 404 before any trip lookup', async () => {
it('TOURS-IMP-004: Tours off for the trip is the TripAddonGuard 404, after the trip lookup', async () => {
const { controller, places, tours, addons } = importFixture({ addon: false });
expect(await thrownAsync(() => controller.importGpx(user, '7', file))).toEqual({
status: 404,
body: { error: 'Tours addon is not enabled' },
});
expect(addons.isAddonEnabled).toHaveBeenCalledWith('tours');
expect(places.verifyTripAccess).not.toHaveBeenCalled();
expect(places.verifyTripAccess).toHaveBeenCalledWith('7', user.id);
expect(addons.isEnabledForTrip).toHaveBeenCalledWith(trip.id, 'tours');
expect(tours.importGpxAsTour).not.toHaveBeenCalled();
});
@@ -7,8 +7,8 @@
*/
import 'reflect-metadata';
import { AddonGuard } from '../../../src/nest/addons/addon.guard';
import type { AddonsService } from '../../../src/nest/addons/addons.service';
import { TripAddonGuard } from '../../../src/nest/addons/trip-addon.guard';
import { JwtAuthGuard } from '../../../src/nest/auth-core/jwt-auth.guard';
import { extractToken, verifyJwtAndLoadUser } from '../../../src/nest/auth-core/jwt-verify';
import type { PermissionsService } from '../../../src/nest/permissions/permissions.service';
@@ -95,7 +95,7 @@ function importFixture(canEdit: boolean, canAssign: boolean) {
const controller = new ToursImportController(
{ importGpxAsTour } as unknown as ToursService,
places as unknown as PlacesService,
{ isAddonEnabled: vi.fn(async () => true) } as unknown as AddonsService,
{ isEnabledForTrip: vi.fn(async () => true) } as unknown as AddonsService,
);
return { controller, access, permission, importGpxAsTour };
}
@@ -117,8 +117,12 @@ describe('Tours permission contract (mock-only, no DB)', () => {
expect(legacyDatabaseAccess).not.toHaveBeenCalled();
});
it('retains addon/JWT/trip guard order and exact write metadata', () => {
expect(Reflect.getMetadata(GUARDS_METADATA, ToursController)).toEqual([AddonGuard, JwtAuthGuard, TripAccessGuard]);
it('retains JWT/trip/addon guard order and exact write metadata', () => {
expect(Reflect.getMetadata(GUARDS_METADATA, ToursController)).toEqual([
JwtAuthGuard,
TripAccessGuard,
TripAddonGuard,
]);
expect(Reflect.getMetadata(GUARDS_METADATA, ToursImportController)).toEqual([JwtAuthGuard]);
for (const handler of ['create', 'update'] as const) {
expect(Reflect.getMetadata(TRIP_PERMISSION_KEY, ToursController.prototype[handler])).toBe('place_edit');
@@ -173,13 +177,8 @@ describe('Tours permission contract (mock-only, no DB)', () => {
expect(test.importGpxAsTour).not.toHaveBeenCalled();
});
it('preserves addon and JWT refusal without reaching trip resolution', async () => {
it('refuses without a session before trip resolution, and Tours off for the trip only after it', async () => {
const test = fixture('create', true, true);
const addon = new AddonGuard(
{ isAddonEnabled: vi.fn(async () => false) } as unknown as AddonsService,
new Reflector(),
);
await expectStatus(() => addon.canActivate(test.context), 404);
const jwt = new JwtAuthGuard({ getRepository: vi.fn() } as unknown as EntityManager);
vi.mocked(extractToken).mockReturnValue(null);
await expectStatus(() => jwt.canActivate(test.context), 401);
@@ -187,5 +186,11 @@ describe('Tours permission contract (mock-only, no DB)', () => {
vi.mocked(verifyJwtAndLoadUser).mockResolvedValue(null);
await expectStatus(() => jwt.canActivate(test.context), 401);
expect(test.access).not.toHaveBeenCalled();
expect(await test.guard.canActivate(test.context)).toBe(true);
const isEnabledForTrip = vi.fn(async () => false);
const addon = new TripAddonGuard({ isEnabledForTrip } as unknown as AddonsService, new Reflector());
await expectStatus(() => addon.canActivate(test.context), 404);
expect(isEnabledForTrip).toHaveBeenCalledWith(trip.id, 'tours');
});
});
@@ -0,0 +1,185 @@
/**
* TRIPADDON-MCP-001..012: the MCP side of the per-trip addons.
*
* Two halves. A tool's `when:` gate (addonGate and its siblings) runs once, at
* attach: it registers a trip addon's tools while the instance or any trip of
* the user has the addon on, or, for a session pinned to one trip, while that
* trip has it on. The host's tool gate (trekTripAddonToolGate) runs on every
* call and asks the trip the call names, so a trip that has the addon off
* refuses with the REST text and one that switched it on lets the call through.
*/
import type { McpContext, ToolOptions } from '../../../src/nest-mcp';
import { combineToolGates, errorResult } from '../../../src/nest-mcp';
import {
addonGate,
addonOffResource,
addonsOfGate,
allAddonsGate,
collabFeatureGate,
gateOnAddons,
instanceAddonGate,
type HasAddons,
} from '../../../src/nest/addons/addon-gate';
import type { AddonsService } from '../../../src/nest/addons/addons.service';
import { trekTripAddonToolGate } from '../../../src/nest/addons/trip-addon-tool-gate';
import type { TripAccessService } from '../../../src/nest/trip-membership/trip-access.service';
import { describe, it, expect, vi } from 'vitest';
const ctx = (extra: Partial<McpContext> = {}): McpContext => ({
userId: 7,
scopes: null,
isStaticToken: false,
...extra,
});
/**
* The instance has `instance` on; trip 5 chose `trip5`; the user's trips have
* `anywhere` on somewhere. Trip 5 is the user's, trip 9 is not.
*/
function addonsStub(o: { instance?: string[]; trip5?: Record<string, boolean>; anywhere?: string[] } = {}) {
const instance = new Set(o.instance ?? []);
const anywhere = new Set([...(o.anywhere ?? []), ...instance]);
return {
isAddonEnabled: vi.fn(async (id: string) => instance.has(id)),
isEnabledForTrip: vi.fn(async (tripId: number, id: string) =>
tripId === 5 ? (o.trip5?.[id] ?? instance.has(id)) : instance.has(id),
),
isEnabledForUserAnywhere: vi.fn(async (_userId: number, id: string) => anywhere.has(id)),
getCollabFeatures: vi.fn(async () => ({ chat: true, notes: false, links: true, polls: true, whatsnext: true })),
};
}
const self = (addons: ReturnType<typeof addonsStub>): HasAddons => ({ addons: addons as unknown as AddonsService });
const trips = {
findAccessible: vi.fn(async (tripId: number, userId: number) =>
tripId === 5 && userId === 7 ? { id: 5 } : undefined,
),
} as unknown as TripAccessService;
const tool = (when?: unknown): ToolOptions => ({ name: 'some_tool', when }) as unknown as ToolOptions;
describe('the attach-time gates', () => {
it('TRIPADDON-MCP-001: a trip addon is offered while it is on anywhere for the user, any other addon on the instance', async () => {
const off = addonsStub({ anywhere: ['packing'] });
expect(await addonGate('packing')(ctx(), self(off))).toBe(true);
expect(off.isEnabledForUserAnywhere).toHaveBeenCalledWith(7, 'packing');
expect(await addonGate('budget')(ctx(), self(off))).toBe(false);
// Vacay has no trip side: only the instance switch counts.
expect(await addonGate('vacay')(ctx(), self(addonsStub({ anywhere: ['vacay'] })))).toBe(false);
expect(await addonGate('vacay')(ctx(), self(addonsStub({ instance: ['vacay'] })))).toBe(true);
});
it('TRIPADDON-MCP-002: a session pinned to one trip asks that trip alone', async () => {
const addons = addonsStub({ instance: ['budget'], trip5: { budget: false, roadtrip: true } });
expect(await addonGate('budget')(ctx({ tripId: 5 }), self(addons))).toBe(false);
expect(await addonGate('roadtrip')(ctx({ tripId: 5 }), self(addons))).toBe(true);
expect(addons.isEnabledForUserAnywhere).not.toHaveBeenCalled();
});
it('TRIPADDON-MCP-003: allAddonsGate needs every addon, collabFeatureGate the addon and its instance-wide flag', async () => {
const addons = addonsStub({ anywhere: ['tours'], instance: ['collab'] });
expect(await allAddonsGate('tours', 'packing')(ctx(), self(addons))).toBe(false);
expect(await allAddonsGate('tours', 'collab')(ctx(), self(addons))).toBe(true);
expect(await collabFeatureGate('chat')(ctx(), self(addons))).toBe(true);
expect(await collabFeatureGate('notes')(ctx(), self(addons))).toBe(false);
expect(await collabFeatureGate('chat')(ctx({ tripId: 5 }), self(addonsStub({ trip5: { collab: false } })))).toBe(
false,
);
});
it('TRIPADDON-MCP-004: instanceAddonGate reads the instance switch alone, a trip that switched it on aside', async () => {
expect(await instanceAddonGate('documents')(ctx(), self(addonsStub({ anywhere: ['documents'] })))).toBe(false);
expect(await instanceAddonGate('documents')(ctx(), self(addonsStub({ instance: ['documents'] })))).toBe(true);
});
it('TRIPADDON-MCP-005: every gate names the addons it stands for; anything else names none', () => {
expect(addonsOfGate(addonGate('packing'))).toEqual(['packing']);
expect(addonsOfGate(allAddonsGate('tours', 'packing'))).toEqual(['tours', 'packing']);
expect(addonsOfGate(collabFeatureGate('polls'))).toEqual(['collab']);
expect(addonsOfGate(instanceAddonGate('documents'))).toEqual(['documents']);
expect(addonsOfGate(gateOnAddons(['tours'], async () => true))).toEqual(['tours']);
expect(addonsOfGate(async () => true)).toEqual([]);
expect(addonsOfGate(undefined)).toEqual([]);
expect(addonsOfGate(Object.assign(async () => true, { addonIds: 'tours' }))).toEqual([]);
});
it('TRIPADDON-MCP-006: a trip resource whose addon is off answers with the REST text', () => {
const uri = new URL('trek://trips/5/budget');
expect(addonOffResource(uri, 'budget')).toEqual({
contents: [
{ uri: uri.href, mimeType: 'application/json', text: JSON.stringify({ error: 'Costs addon is not enabled' }) },
],
});
});
});
describe('trekTripAddonToolGate, on every call', () => {
it('TRIPADDON-MCP-007: a trip that has the addon off refuses the call; one that switched it on lets it through', async () => {
const addons = addonsStub({ instance: ['budget'], trip5: { budget: false, roadtrip: true } });
const gate = trekTripAddonToolGate(addons as unknown as AddonsService, trips);
expect(await gate(tool(addonGate('budget')), ctx(), { tripId: 5 })).toEqual(
errorResult('Costs addon is not enabled'),
);
expect(await gate(tool(addonGate('roadtrip')), ctx(), { tripId: '5' })).toBeUndefined();
expect(addons.isEnabledForTrip).toHaveBeenCalledWith(5, 'roadtrip');
});
it('TRIPADDON-MCP-008: of several addons the first one off answers', async () => {
const addons = addonsStub({ instance: ['tours', 'packing'], trip5: { packing: false } });
const gate = trekTripAddonToolGate(addons as unknown as AddonsService, trips);
expect(await gate(tool(allAddonsGate('tours', 'packing')), ctx(), { tripId: 5 })).toEqual(
errorResult('Packing addon is not enabled'),
);
});
it('TRIPADDON-MCP-009: a tool of no trip addon, or one gated some other way, is left alone', async () => {
const addons = addonsStub();
const gate = trekTripAddonToolGate(addons as unknown as AddonsService, trips);
expect(await gate(tool(undefined), ctx(), { tripId: 5 })).toBeUndefined();
expect(await gate(tool(addonGate('vacay')), ctx(), { tripId: 5 })).toBeUndefined();
expect(
await gate(
tool(async () => true),
ctx(),
{ tripId: 5 },
),
).toBeUndefined();
expect(addons.isEnabledForTrip).not.toHaveBeenCalled();
});
it('TRIPADDON-MCP-010: a trip the caller cannot see is left to the tool, which answers not found', async () => {
const addons = addonsStub({ trip5: { budget: false } });
const gate = trekTripAddonToolGate(addons as unknown as AddonsService, trips);
expect(await gate(tool(addonGate('budget')), ctx(), { tripId: 9 })).toBeUndefined();
expect(addons.isEnabledForTrip).not.toHaveBeenCalled();
});
it('TRIPADDON-MCP-011: a call that names no trip asks the pinned trip, else the user anywhere', async () => {
const addons = addonsStub({ trip5: { packing: false }, anywhere: ['packing'] });
const gate = trekTripAddonToolGate(addons as unknown as AddonsService, trips);
expect(await gate(tool(addonGate('packing')), ctx(), {})).toBeUndefined();
expect(await gate(tool(addonGate('packing')), ctx(), undefined)).toBeUndefined();
expect(addons.isEnabledForUserAnywhere).toHaveBeenCalledWith(7, 'packing');
expect(await gate(tool(addonGate('packing')), ctx({ tripId: 5 }), {})).toEqual(
errorResult('Packing addon is not enabled'),
);
expect(await gate(tool(addonGate('budget')), ctx(), {})).toEqual(errorResult('Costs addon is not enabled'));
});
});
describe('combineToolGates', () => {
it('TRIPADDON-MCP-012: asks the gates in order, answers with the first refusal and stops there', async () => {
const first = vi.fn(async () => undefined);
const second = vi.fn(() => errorResult('no'));
const third = vi.fn(async () => errorResult('never asked'));
const gate = combineToolGates(first, second, third);
const options = tool();
expect(await gate(options, ctx(), { tripId: 5 })).toEqual(errorResult('no'));
expect(first).toHaveBeenCalledWith(options, ctx(), { tripId: 5 });
expect(third).not.toHaveBeenCalled();
expect(await combineToolGates(first)(options, ctx())).toBeUndefined();
expect(await combineToolGates()(options, ctx())).toBeUndefined();
});
});
@@ -0,0 +1,108 @@
/**
* TRIPADDON-GUARD-001..006: TripAddonGuard, the trip-scoped twin of AddonGuard.
*
* It answers @RequireAddon with what applies to the one trip TripAccessGuard
* parked on the request: the owner's choice for the trip, else the instance
* switch. Both directions are pinned, the trip on although the instance is
* off and the trip off although the instance is on, with the 404 body
* AddonGuard has always sent.
*/
import type { AddonsService } from '../../../src/nest/addons/addons.service';
import { RequireAddon } from '../../../src/nest/addons/require-addon.decorator';
import { TripAddonGuard } from '../../../src/nest/addons/trip-addon.guard';
import { TRIP_REQUEST_KEY } from '../../../src/nest/permissions/trip-access.guard';
import { type ExecutionContext, HttpException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { describe, it, expect, vi } from 'vitest';
/** A route group carrying @RequireAddon, as the controllers declare it. */
function decorated(addonId: string | readonly string[], label: string): object {
@RequireAddon(addonId, label)
class Gated {}
return Gated;
}
function ctxFor(cls: object, trip?: { id: number; user_id: number }): ExecutionContext {
return {
getHandler: () => () => {},
getClass: () => cls,
switchToHttp: () => ({ getRequest: () => (trip ? { [TRIP_REQUEST_KEY]: trip } : {}) }),
} as unknown as ExecutionContext;
}
/** `chosen` is what applies to each addon on trip 5. */
function addons(chosen: Record<string, boolean>) {
return {
isEnabledForTrip: vi.fn(async (_tripId: number, id: string) => chosen[id] ?? false),
} as unknown as AddonsService & { isEnabledForTrip: ReturnType<typeof vi.fn> };
}
async function refusal(run: () => Promise<unknown>): Promise<{ status: number; body: unknown }> {
try {
await run();
} catch (err) {
const e = err as HttpException;
return { status: e.getStatus(), body: e.getResponse() };
}
throw new Error('expected a refusal');
}
const TRIP = { id: 5, user_id: 1 };
describe('TripAddonGuard', () => {
it('TRIPADDON-GUARD-001: a route that did not ask for an addon is never gated, and nothing is read', async () => {
const svc = addons({});
expect(await new TripAddonGuard(svc, new Reflector()).canActivate(ctxFor(class {}))).toBe(true);
expect(svc.isEnabledForTrip).not.toHaveBeenCalled();
});
it('TRIPADDON-GUARD-002: a trip that switched the addon on answers, whatever the instance says', async () => {
const svc = addons({ roadtrip: true });
const guard = new TripAddonGuard(svc, new Reflector());
expect(await guard.canActivate(ctxFor(decorated('roadtrip', 'Road trip'), TRIP))).toBe(true);
expect(svc.isEnabledForTrip).toHaveBeenCalledWith(5, 'roadtrip');
});
it('TRIPADDON-GUARD-003: a trip that has the addon off gets the AddonGuard 404 body', async () => {
const guard = new TripAddonGuard(addons({ budget: false }), new Reflector());
expect(await refusal(() => guard.canActivate(ctxFor(decorated('budget', 'Costs'), TRIP)))).toEqual({
status: 404,
body: { error: 'Costs addon is not enabled' },
});
});
it('TRIPADDON-GUARD-004: of several addons one is enough, as with AddonGuard', async () => {
const guard = new TripAddonGuard(addons({ tours: false, roadtrip: true }), new Reflector());
expect(await guard.canActivate(ctxFor(decorated(['tours', 'roadtrip'], 'Tours'), TRIP))).toBe(true);
const none = new TripAddonGuard(addons({}), new Reflector());
expect(
(await refusal(() => none.canActivate(ctxFor(decorated(['tours', 'roadtrip'], 'Tours'), TRIP)))).status,
).toBe(404);
});
it('TRIPADDON-GUARD-005: without a trip parked by TripAccessGuard it fails closed instead of opening', async () => {
const svc = addons({ packing: true });
const guard = new TripAddonGuard(svc, new Reflector());
await expect(guard.canActivate(ctxFor(decorated('packing', 'Packing')))).rejects.toThrow(/TripAccessGuard/);
expect(svc.isEnabledForTrip).not.toHaveBeenCalled();
});
it('TRIPADDON-GUARD-006: a handler-level requirement overrides the class one', async () => {
@RequireAddon('tours', 'Tours')
class Routes {
@RequireAddon('packing', 'Packing')
handler() {}
}
const svc = addons({ tours: true, packing: false });
const context = {
getHandler: () => Routes.prototype.handler,
getClass: () => Routes,
switchToHttp: () => ({ getRequest: () => ({ [TRIP_REQUEST_KEY]: TRIP }) }),
} as unknown as ExecutionContext;
expect(await refusal(() => new TripAddonGuard(svc, new Reflector()).canActivate(context))).toEqual({
status: 404,
body: { error: 'Packing addon is not enabled' },
});
});
});
@@ -0,0 +1,71 @@
/**
* TripAddonsController: the route shapes, the guard chain and the owner
* refusal it declares, and that each handler hands the guard-resolved trip and
* the caller straight to TripAddonsService. The behaviour behind it is pinned
* in trip-addons.service.test.ts and over HTTP in trip-addons.e2e.test.ts.
*/
import type { TripAccess } from '../../../src/db/repositories/Trips.repository';
import { TripAddonsController, TripAddonUpdateDto } from '../../../src/nest/addons/trip-addons.controller';
import { TRIP_ADDON_OWNER_ONLY, type TripAddonsService } from '../../../src/nest/addons/trip-addons.service';
import { JwtAuthGuard } from '../../../src/nest/auth-core/jwt-auth.guard';
import { RESPONSE_CONTRACT_KEY } from '../../../src/nest/common/response-contract';
import { TripAccessGuard } from '../../../src/nest/permissions/trip-access.guard';
import { TRIP_OWNER_KEY, TripOwnerGuard } from '../../../src/nest/permissions/trip-owner.guard';
import type { User } from '../../../src/types';
import { RequestMethod } from '@nestjs/common';
import { GUARDS_METADATA, METHOD_METADATA, PATH_METADATA } from '@nestjs/common/constants';
import { tripAddonsResponseSchema, tripAddonUpdateRequestSchema, type TripAddon } from '@trek/shared';
import { describe, expect, it, vi } from 'vitest';
const trip: TripAccess = { id: 7, user_id: 3, currency: 'EUR' };
const user = { id: 3 } as User;
const addons: TripAddon[] = [
{ id: 'budget', name: 'Costs', icon: 'Wallet', enabled: false, instanceEnabled: true, overridden: true },
];
function makeController() {
const service = {
effectiveTripAddons: vi.fn().mockResolvedValue(addons),
setTripOverride: vi.fn().mockResolvedValue(addons),
};
return { service, controller: new TripAddonsController(service as unknown as TripAddonsService) };
}
const proto = TripAddonsController.prototype;
describe('TripAddonsController', () => {
it('TRIPADDON-CTRL-001: lives under the trip, behind auth and trip access, with no addon gate', () => {
expect(Reflect.getMetadata(PATH_METADATA, TripAddonsController)).toBe('api/trips/:tripId/addons');
expect(Reflect.getMetadata(GUARDS_METADATA, TripAddonsController)).toEqual([JwtAuthGuard, TripAccessGuard]);
});
it('TRIPADDON-CTRL-002: GET / answers the trip list, declared by the shared response schema', async () => {
expect(Reflect.getMetadata(METHOD_METADATA, proto.list)).toBe(RequestMethod.GET);
expect(Reflect.getMetadata(PATH_METADATA, proto.list)).toBe('/');
expect(Reflect.getMetadata(RESPONSE_CONTRACT_KEY, proto.list)).toBe(tripAddonsResponseSchema);
expect(Reflect.getMetadata(GUARDS_METADATA, proto.list)).toBeUndefined();
const { service, controller } = makeController();
expect(await controller.list(trip)).toEqual({ tripId: 7, addons });
expect(service.effectiveTripAddons).toHaveBeenCalledWith(7);
});
it('TRIPADDON-CTRL-003: PUT /:addonId is owner-only with the REST refusal text and the shared body', () => {
expect(Reflect.getMetadata(METHOD_METADATA, proto.update)).toBe(RequestMethod.PUT);
expect(Reflect.getMetadata(PATH_METADATA, proto.update)).toBe(':addonId');
expect(Reflect.getMetadata(GUARDS_METADATA, proto.update)).toEqual([TripOwnerGuard]);
expect(Reflect.getMetadata(TRIP_OWNER_KEY, proto.update)).toEqual({ message: TRIP_ADDON_OWNER_ONLY });
expect(Reflect.getMetadata(RESPONSE_CONTRACT_KEY, proto.update)).toBe(tripAddonsResponseSchema);
expect(TripAddonUpdateDto.schema).toBe(tripAddonUpdateRequestSchema);
});
it('TRIPADDON-CTRL-004: PUT hands trip, caller, addon, choice and socket id to the service', async () => {
const { service, controller } = makeController();
expect(await controller.update(user, trip, 'budget', { enabled: false }, 'sock-9')).toEqual({ tripId: 7, addons });
expect(service.setTripOverride).toHaveBeenCalledWith(7, 3, 'budget', false, 'sock-9');
await controller.update(user, trip, 'budget', { enabled: null });
expect(service.setTripOverride).toHaveBeenLastCalledWith(7, 3, 'budget', null, undefined);
});
});
@@ -0,0 +1,263 @@
/**
* TripAddonsService: whether a trip addon applies to one trip, and the owner's
* switch for it. Real in-memory SQLite over the container (the service comes
* out of AddonsModule), the broadcasts recorded by the FakeRealtimeService.
*/
import { TripAddonOverrides } from '../../../src/db/entities/TripAddonOverrides.entity';
import { sessions, type McpSession } from '../../../src/mcp/sessionManager';
import { AddonsModule } from '../../../src/nest/addons/addons.module';
import { AddonsService } from '../../../src/nest/addons/addons.service';
import {
TRIP_ADDON_NOT_FOUND,
TRIP_ADDON_OWNER_ONLY,
TripAddonsService,
} from '../../../src/nest/addons/trip-addons.service';
import { DomainError } from '../../../src/nest/common/domain-error';
import { createSnapshotTestDb } from '../../helpers/db-mock';
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 { oneByOne } from '../../helpers/one-by-one';
import { resetTestDb } from '../../helpers/test-db';
import { createTestModule, type TestModule } from '../../helpers/test-module';
import { MikroORM } from '@mikro-orm/core';
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const db = createSnapshotTestDb();
let t: TestModule;
let svc: TripAddonsService;
let addons: AddonsService;
const orm = () => t.get(MikroORM);
beforeAll(async () => {
t = await createTestModule({ db, imports: [AddonsModule] });
svc = t.get(TripAddonsService);
addons = t.get(AddonsService);
});
beforeEach(() => {
resetTestDb(db);
t.realtime.reset();
});
afterAll(async () => {
await t.close();
db.close();
});
async function ownedTrip() {
const { user: owner } = await makeUser(orm());
const trip = await makeTrip(orm(), owner.id);
return { owner, trip };
}
async function refusal(work: Promise<unknown>): Promise<DomainError> {
const error = await work.then(
() => null,
(e: unknown) => e,
);
expect(error).toBeInstanceOf(DomainError);
return error as DomainError;
}
describe('TripAddonsService: what applies to a trip', () => {
it('TRIPADDON-SVC-001: without a choice the trip follows the instance switch', async () => {
const { trip } = await ownedTrip();
await setAddonEnabled(orm(), 'roadtrip', false);
await setAddonEnabled(orm(), 'budget', true);
expect(await addons.isEnabledForTrip(trip.id, 'roadtrip')).toBe(false);
expect(await addons.isEnabledForTrip(trip.id, 'budget')).toBe(true);
});
it('TRIPADDON-SVC-002: the owner may switch an addon on although the instance has it off, and off although on', async () => {
const { owner, trip } = await ownedTrip();
await setAddonEnabled(orm(), 'roadtrip', false);
await setAddonEnabled(orm(), 'budget', true);
await svc.setTripOverride(trip.id, owner.id, 'roadtrip', true);
await svc.setTripOverride(trip.id, owner.id, 'budget', false);
expect(await addons.isEnabledForTrip(trip.id, 'roadtrip')).toBe(true);
expect(await addons.isEnabledForTrip(trip.id, 'budget')).toBe(false);
});
it('TRIPADDON-SVC-003: a global addon and an unknown id answer with the instance switch alone', async () => {
const { trip } = await ownedTrip();
await setAddonEnabled(orm(), 'vacay', true);
expect(await addons.isEnabledForTrip(trip.id, 'vacay')).toBe(true);
expect(await addons.isEnabledForTrip(trip.id, 'no_such_addon')).toBe(false);
});
it('TRIPADDON-SVC-004: the list holds every trip addon in order, the legacy photo row and other types left out', async () => {
const { owner, trip } = await ownedTrip();
await svc.setTripOverride(trip.id, owner.id, 'budget', false);
const list = await svc.effectiveTripAddons(trip.id);
const ids = list.map((a) => a.id);
expect(ids).toEqual(expect.arrayContaining(['packing', 'budget', 'documents', 'collab', 'roadtrip', 'tours']));
expect(ids).not.toContain('memories');
expect(ids).not.toContain('vacay');
expect(ids).not.toContain('mcp');
const budget = list.find((a) => a.id === 'budget');
expect(budget).toMatchObject({ enabled: false, instanceEnabled: true, overridden: true });
expect(typeof budget?.name).toBe('string');
const packing = list.find((a) => a.id === 'packing');
expect(packing).toMatchObject({ overridden: false });
expect(packing?.enabled).toBe(packing?.instanceEnabled);
});
});
describe('TripAddonsService: routes without a trip', () => {
it('TRIPADDON-SVC-010: open while the instance has the addon on', async () => {
const { owner } = await ownedTrip();
await setAddonEnabled(orm(), 'tours', true);
expect(await addons.isEnabledForUserAnywhere(owner.id, 'tours')).toBe(true);
});
it('TRIPADDON-SVC-011: off for the instance, open once a trip the user owns or belongs to switched it on', async () => {
const { owner, trip } = await ownedTrip();
const { user: member } = await makeUser(orm());
const { user: stranger } = await makeUser(orm());
await addTripMember(orm(), trip.id, member.id, owner.id);
await setAddonEnabled(orm(), 'tours', false);
expect(await addons.isEnabledForUserAnywhere(owner.id, 'tours')).toBe(false);
await svc.setTripOverride(trip.id, owner.id, 'tours', true);
expect(await addons.isEnabledForUserAnywhere(owner.id, 'tours')).toBe(true);
expect(await addons.isEnabledForUserAnywhere(member.id, 'tours')).toBe(true);
expect(await addons.isEnabledForUserAnywhere(stranger.id, 'tours')).toBe(false);
});
it('TRIPADDON-SVC-012: a global addon that is off and an unknown id stay closed', async () => {
const { owner } = await ownedTrip();
await setAddonEnabled(orm(), 'vacay', false);
expect(await addons.isEnabledForUserAnywhere(owner.id, 'vacay')).toBe(false);
expect(await addons.isEnabledForUserAnywhere(owner.id, 'no_such_addon')).toBe(false);
});
it('TRIPADDON-SVC-013: tripsWithAddon keeps the trips the addon applies to, in their order, each as isEnabledForTrip says', async () => {
const { owner, trip: off } = await ownedTrip();
const on = await makeTrip(orm(), owner.id);
const follows = await makeTrip(orm(), owner.id);
const ids = [on.id, off.id, follows.id];
await setAddonEnabled(orm(), 'tours', true);
await svc.setTripOverride(off.id, owner.id, 'tours', false);
expect(await addons.tripsWithAddon(ids, 'tours')).toEqual([on.id, follows.id]);
await setAddonEnabled(orm(), 'tours', false);
await svc.setTripOverride(on.id, owner.id, 'tours', true);
expect(await addons.tripsWithAddon(ids, 'tours')).toEqual([on.id]);
expect(await addons.tripsWithAddon([], 'tours')).toEqual([]);
});
it('TRIPADDON-SVC-014: tripsWithAddon answers a global addon with its instance switch and an unknown id with none', async () => {
const { trip } = await ownedTrip();
await setAddonEnabled(orm(), 'vacay', true);
expect(await addons.tripsWithAddon([trip.id], 'vacay')).toEqual([trip.id]);
await setAddonEnabled(orm(), 'vacay', false);
expect(await addons.tripsWithAddon([trip.id], 'vacay')).toEqual([]);
expect(await addons.tripsWithAddon([trip.id], 'no_such_addon')).toEqual([]);
});
});
describe('TripAddonsService: the owner switch', () => {
it('TRIPADDON-SVC-020: answers the whole list and broadcasts it to the trip, the saving tab left out', async () => {
const { owner, trip } = await ownedTrip();
const addons = await svc.setTripOverride(trip.id, owner.id, 'budget', false, 'sock-1');
expect(addons.find((a) => a.id === 'budget')).toMatchObject({ enabled: false, overridden: true });
expect(t.realtime.broadcastMock).toHaveBeenCalledTimes(1);
expect(t.realtime.broadcastMock).toHaveBeenCalledWith(String(trip.id), 'tripAddons:changed', { addons }, 'sock-1');
});
it('TRIPADDON-SVC-021: null drops the choice, so the instance setting applies again', async () => {
const { owner, trip } = await ownedTrip();
await svc.setTripOverride(trip.id, owner.id, 'budget', false);
const addons = await svc.setTripOverride(trip.id, owner.id, 'budget', null);
expect(addons.find((a) => a.id === 'budget')).toMatchObject({ enabled: true, overridden: false });
expect(await countRows(orm(), TripAddonOverrides, { trip: trip.id })).toBe(0);
});
it('TRIPADDON-SVC-022: a member and an admin who does not own the trip are refused, and nothing is written', async () => {
const { owner, trip } = await ownedTrip();
const { user: member } = await makeUser(orm());
const { user: admin } = await makeAdmin(orm());
await addTripMember(orm(), trip.id, member.id, owner.id);
await addTripMember(orm(), trip.id, admin.id, owner.id);
const refused = await oneByOne([member.id, admin.id], (userId) =>
refusal(svc.setTripOverride(trip.id, userId, 'budget', false)),
);
for (const e of refused) {
expect(e.getStatus()).toBe(403);
expect(e.publicMessage).toBe(TRIP_ADDON_OWNER_ONLY);
}
expect(await countRows(orm(), TripAddonOverrides, { trip: trip.id })).toBe(0);
expect(t.realtime.broadcastMock).not.toHaveBeenCalled();
});
it('TRIPADDON-SVC-023: somebody who cannot see the trip gets a 404', async () => {
const { trip } = await ownedTrip();
const { user: stranger } = await makeUser(orm());
const e = await refusal(svc.setTripOverride(trip.id, stranger.id, 'budget', false));
expect(e.getStatus()).toBe(404);
expect(e.publicMessage).toBe('Trip not found');
});
it('TRIPADDON-SVC-024: an id that names no trip addon is a 404 and writes nothing', async () => {
const { owner, trip } = await ownedTrip();
const unknown = await oneByOne(['vacay', 'memories', 'no_such_addon'], (addonId) =>
refusal(svc.setTripOverride(trip.id, owner.id, addonId, true)),
);
for (const e of unknown) {
expect(e.getStatus()).toBe(404);
expect(e.publicMessage).toBe(TRIP_ADDON_NOT_FOUND);
}
expect(await countRows(orm(), TripAddonOverrides, { trip: trip.id })).toBe(0);
expect(t.realtime.broadcastMock).not.toHaveBeenCalled();
});
it('TRIPADDON-SVC-025: copyOverrides gives a copied trip the choices of its source', async () => {
const { owner, trip } = await ownedTrip();
const copy = await makeTrip(orm(), owner.id);
await svc.setTripOverride(trip.id, owner.id, 'budget', false);
await svc.copyOverrides(trip.id, copy.id);
expect(await addons.isEnabledForTrip(copy.id, 'budget')).toBe(false);
});
});
describe('TripAddonsService: open MCP sessions', () => {
/** A live MCP session of `userId`, as the transport keeps it; `closed` says whether it was ended. */
function liveSession(sid: string, userId: number) {
const state = { closed: false };
sessions.set(sid, {
userId,
server: { close: () => undefined },
transport: { close: () => (state.closed = true) },
} as unknown as McpSession);
return state;
}
afterEach(() => sessions.clear());
it('TRIPADDON-SVC-030: switching on an addon the instance has off ends the sessions of everyone on the trip', async () => {
const { owner, trip } = await ownedTrip();
const { user: member } = await makeUser(orm());
const { user: stranger } = await makeUser(orm());
await addTripMember(orm(), trip.id, member.id, owner.id);
await setAddonEnabled(orm(), 'roadtrip', false);
const own = liveSession('own', owner.id);
const asMember = liveSession('member', member.id);
const other = liveSession('other', stranger.id);
await svc.setTripOverride(trip.id, owner.id, 'roadtrip', true);
// Their tools were attached while Road trip was off everywhere for them; a new session offers them.
expect([own.closed, asMember.closed, other.closed]).toEqual([true, true, false]);
expect(sessions.has('other')).toBe(true);
});
it('TRIPADDON-SVC-031: switching off, or on while the instance has it on, leaves every session alone', async () => {
const { owner, trip } = await ownedTrip();
await setAddonEnabled(orm(), 'budget', true);
const own = liveSession('own', owner.id);
await svc.setTripOverride(trip.id, owner.id, 'budget', false);
await svc.setTripOverride(trip.id, owner.id, 'budget', true);
await setAddonEnabled(orm(), 'roadtrip', false);
await svc.setTripOverride(trip.id, owner.id, 'roadtrip', false);
expect(own.closed).toBe(false);
});
});
@@ -84,6 +84,7 @@ import {
createTestPluginUserErasureQueueRepo,
} from '../../helpers/share-repos';
import { makeStorageFixture } from '../../helpers/storage-fixture';
import { createTestAddonsService } from '../../helpers/test-addons';
import { resetTestDb } from '../../helpers/test-db';
import {
createTestUnitOfWork,
@@ -314,6 +315,7 @@ const buildReadModel = async (tripsRepo: TripsRepository, roster: TripMembersSer
await createTestUsersRepo(testDb),
await createTestTripsRepo(testDb),
await createTestBudgetItemsRepo(testDb),
await createTestAddonsService(testDb),
),
new CollabService(
// Plan 4 Task 2 — CollabService's own DatabaseService param is gone:
@@ -364,6 +366,7 @@ const buildReadModel = async (tripsRepo: TripsRepository, roster: TripMembersSer
await createTestBudgetItemsRepo(testDb),
{ releaseValues: async () => [] } as never, // StorageReleaseService
),
await createTestAddonsService(testDb),
);
let svc: Awaited<ReturnType<typeof buildReadModel>>;
@@ -542,7 +545,7 @@ describe('bundle shaping', () => {
members: undefined,
} as never);
try {
const result = (await svc.bundle(String(trip.id), { user_id: owner.id }, owner.id)) as any;
const result = (await svc.bundle(String(trip.id), { id: trip.id, user_id: owner.id }, owner.id)) as any;
expect(result.members).toEqual([{ id: owner.id, username: 'solo' }]);
} finally {
roster.mockRestore();
@@ -561,7 +564,7 @@ describe('bundle shaping', () => {
members: [{ id: 42, username: 'left-behind' }],
} as never);
try {
const result = (await svc.bundle(String(trip.id), { user_id: owner.id }, owner.id)) as any;
const result = (await svc.bundle(String(trip.id), { id: trip.id, user_id: owner.id }, owner.id)) as any;
expect(result.members).toEqual([{ id: 42, username: 'left-behind' }]);
} finally {
roster.mockRestore();
@@ -586,7 +589,7 @@ describe('private packing items stay viewer-scoped (#858)', () => {
expect(asViewer.packing.items.map((i: any) => i.name)).toEqual(['Tent']);
expect(asViewer.packing.total).toBe(1);
const bundled = (await svc.bundle(String(trip.id), { user_id: owner.id }, viewer.id)) as any;
const bundled = (await svc.bundle(String(trip.id), { id: trip.id, user_id: owner.id }, viewer.id)) as any;
expect(bundled.packingItems.map((i: any) => i.name)).toEqual(['Tent']);
// The owner still sees their own private item through both paths, so the
@@ -596,7 +599,7 @@ describe('private packing items stay viewer-scoped (#858)', () => {
'Tent',
]);
expect(
((await svc.bundle(String(trip.id), { user_id: owner.id }, owner.id)) as any).packingItems.map(
((await svc.bundle(String(trip.id), { id: trip.id, user_id: owner.id }, owner.id)) as any).packingItems.map(
(i: any) => i.name,
),
).toEqual(['Ring', 'Tent']);
+10 -13
View File
@@ -54,6 +54,7 @@ import { buildPlaceImportService } from '../../helpers/place-import';
import { UserCleanupService } from '../../../src/nest/auth/user-cleanup.service';
import { TripMembersService } from '../../../src/nest/trip-members/trip-members.service';
import { TripReadModelService } from '../../../src/nest/trip-read-model/trip-read-model.service';
import { createTestAddonsService } from '../../helpers/test-addons';
import { AccommodationsService } from '../../../src/nest/accommodations/accommodations.service';
import { accommodationsOver, makeAccommodationsService } from '../../helpers/accommodations-service';
import { buildMapsService } from '../../helpers/maps-service';
@@ -284,7 +285,7 @@ beforeAll(async () => {
// which comes out of its own module instead of a constructor call here.
membership = await createTestModule({ db: testDb, imports: [TripMembershipModule] });
svc = new TripsService(
new ReservationsService(new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)), budgetSvc, realtime, notificationsStub(), new ReservationsReadService(await createTestReservationsRepo(testDb), await createTestReservationEndpointsRepo(testDb), await createTestReservationTravelersRepo(testDb), await createTestReservationDayPositionsRepo(testDb)), accommodationsSvc, await createTestUnitOfWork(testDb), await createTestReservationsRepo(testDb), await createTestReservationEndpointsRepo(testDb), await createTestReservationTravelersRepo(testDb), await createTestReservationDayPositionsRepo(testDb), await createTestDayAccommodationsRepo(testDb), await createTestDaysRepo(testDb), await createTestPlacesRepo(testDb), await createTestDayAssignmentsRepo(testDb), await createTestTripMembersRepo(testDb), await createTestUsersRepo(testDb), await createTestTripsRepo(testDb), await createTestBudgetItemsRepo(testDb)),
new ReservationsService(new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)), budgetSvc, realtime, notificationsStub(), new ReservationsReadService(await createTestReservationsRepo(testDb), await createTestReservationEndpointsRepo(testDb), await createTestReservationTravelersRepo(testDb), await createTestReservationDayPositionsRepo(testDb)), accommodationsSvc, await createTestUnitOfWork(testDb), await createTestReservationsRepo(testDb), await createTestReservationEndpointsRepo(testDb), await createTestReservationTravelersRepo(testDb), await createTestReservationDayPositionsRepo(testDb), await createTestDayAccommodationsRepo(testDb), await createTestDaysRepo(testDb), await createTestPlacesRepo(testDb), await createTestDayAssignmentsRepo(testDb), await createTestTripMembersRepo(testDb), await createTestUsersRepo(testDb), await createTestTripsRepo(testDb), await createTestBudgetItemsRepo(testDb), await createTestAddonsService(testDb)),
daysSvc,
new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)),
budgetSvc,
@@ -302,7 +303,7 @@ beforeAll(async () => {
{ releaseValues: async () => [] } as never, // StorageReleaseService: the cover release has its own suite
await createTestUnitOfWork(testDb),
(await sharedTestOrm(testDb)).em,
new SettingsService(await createTestUnitOfWork(testDb), await createTestAppSettingsRepo(testDb), await createTestSettingsRepo(testDb), membership.get(TripMembershipService)),
new SettingsService(await createTestUnitOfWork(testDb), await createTestAppSettingsRepo(testDb), await createTestSettingsRepo(testDb), membership.get(TripMembershipService)), { copyOverrides: async () => {} } as never,
);
membersSvc = new TripMembersService(budgetSvc, new UserCleanupService(new MaintenanceRepository(dbsEm!), budgetSvc, await createTestUnitOfWork(testDb), await createTestUsersRepo(testDb), await createTestTripMembersRepo(testDb), await createTestBudgetItemsRepo(testDb), await createTestBudgetSettlementsRepo(testDb), await createTestJourneyShareTokensRepo(testDb), await createTestJourneysRepo(testDb), await createTestJourneyEntriesRepo(testDb), await createTestJourneyContributorsRepo(testDb), await createTestShareTokensRepo(testDb), await createTestPluginsRepo(testDb), await createTestPluginUserErasureQueueRepo(testDb), { releaseValues: async () => [] } as never), new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)), realtime, notificationsStub(), await createTestUnitOfWork(testDb), await createTestTripsRepo(testDb), await createTestTripMembersRepo(testDb), await createTestUsersRepo(testDb));
readModelSvc = new TripReadModelService(
@@ -313,7 +314,7 @@ beforeAll(async () => {
await createTestPackingCategoryAssigneesRepo(testDb), await createTestPackingTemplatesRepo(testDb), await createTestPackingTemplateCategoriesRepo(testDb),
await createTestPackingTemplateItemsRepo(testDb), await createTestTripsRepo(testDb), await createTestTripMembersRepo(testDb),
),
new ReservationsService(new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)), budgetSvc, realtime, notificationsStub(), new ReservationsReadService(await createTestReservationsRepo(testDb), await createTestReservationEndpointsRepo(testDb), await createTestReservationTravelersRepo(testDb), await createTestReservationDayPositionsRepo(testDb)), accommodationsSvc, await createTestUnitOfWork(testDb), await createTestReservationsRepo(testDb), await createTestReservationEndpointsRepo(testDb), await createTestReservationTravelersRepo(testDb), await createTestReservationDayPositionsRepo(testDb), await createTestDayAccommodationsRepo(testDb), await createTestDaysRepo(testDb), await createTestPlacesRepo(testDb), await createTestDayAssignmentsRepo(testDb), await createTestTripMembersRepo(testDb), await createTestUsersRepo(testDb), await createTestTripsRepo(testDb), await createTestBudgetItemsRepo(testDb)),
new ReservationsService(new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)), budgetSvc, realtime, notificationsStub(), new ReservationsReadService(await createTestReservationsRepo(testDb), await createTestReservationEndpointsRepo(testDb), await createTestReservationTravelersRepo(testDb), await createTestReservationDayPositionsRepo(testDb)), accommodationsSvc, await createTestUnitOfWork(testDb), await createTestReservationsRepo(testDb), await createTestReservationEndpointsRepo(testDb), await createTestReservationTravelersRepo(testDb), await createTestReservationDayPositionsRepo(testDb), await createTestDayAccommodationsRepo(testDb), await createTestDaysRepo(testDb), await createTestPlacesRepo(testDb), await createTestDayAssignmentsRepo(testDb), await createTestTripMembersRepo(testDb), await createTestUsersRepo(testDb), await createTestTripsRepo(testDb), await createTestBudgetItemsRepo(testDb), await createTestAddonsService(testDb)),
new CollabService(
// Plan 4 Task 2 — CollabService's own DatabaseService param is gone:
// canAccessTrip now reads through the TripsRepository at the end.
@@ -333,19 +334,15 @@ beforeAll(async () => {
// Plan 4 Task 2 — canAccessTrip is TripsRepository.findAccessible, in the same constructor slot.
new TripAccessService(await createTestTripsRepo(testDb)),
new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)),
realtime,
new EphemeralTokenService(),
coversFx.storage,
realtime, new EphemeralTokenService(), coversFx.storage,
(await sharedTestOrm(testDb)).em,
await createTestUnitOfWork(testDb),
await createTestTripFilesRepo(testDb),
await createTestFileLinksRepo(testDb),
await createTestReservationsRepo(testDb),
await createTestPlacesRepo(testDb),
await createTestDayAssignmentsRepo(testDb),
await createTestBudgetItemsRepo(testDb),
await createTestTripFilesRepo(testDb), await createTestFileLinksRepo(testDb),
await createTestReservationsRepo(testDb), await createTestPlacesRepo(testDb),
await createTestDayAssignmentsRepo(testDb), await createTestBudgetItemsRepo(testDb),
{ releaseValues: async () => [] } as never, // StorageReleaseService
),
await createTestAddonsService(testDb), // what the bundle sends follows the trip's addons
);
});
@@ -1505,7 +1502,7 @@ describe('TripsService wrapper helpers', () => {
await insertRow(await orm(), PackingItems, { trip: trip.id, name: 'Secret', is_private: 1, owner: owner.id });
await insertRow(await orm(), PackingItems, { trip: trip.id, name: 'Shared' });
const result = (await readModelSvc.bundle(String(trip.id), { user_id: owner.id }, viewer.id)) as any;
const result = (await readModelSvc.bundle(String(trip.id), { id: trip.id, user_id: owner.id }, viewer.id)) as any;
expect(result.days).toHaveLength(2);
expect(result.members.map((m: any) => m.id).sort()).toEqual([owner.id, viewer.id].sort());
expect(result.packingItems.map((p: any) => p.name)).toEqual(['Shared']);
@@ -35,11 +35,12 @@ function watchService() {
}
describe('WandererWatchController', () => {
it('WWCTL-001: sits beside the connection, behind Tours, auth and the wanderer switch', () => {
it('WWCTL-001: sits beside the connection, behind auth, Tours for the caller and the wanderer switch', () => {
expect(Reflect.getMetadata(PATH_METADATA, WandererWatchController)).toBe('api/integrations/wanderer/watch');
// Auth first: the watch belongs to no one trip, so Tours opens once the caller is known (any trip of theirs).
expect(Reflect.getMetadata(GUARDS_METADATA, WandererWatchController)).toEqual([
AddonGuard,
JwtAuthGuard,
AddonGuard,
WandererEnabledGuard,
]);
expect(Reflect.getMetadata(REQUIRE_ADDON, WandererWatchController)).toEqual({ addonId: 'tours', label: 'Tours' });
@@ -85,7 +85,7 @@ function build(opts: { canEdit?: boolean; before?: Item | undefined; updated?: I
),
} as unknown as TripsRepository,
{ checkPermission: vi.fn(() => opts.canEdit ?? true) } as unknown as PermissionsService,
{ isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService,
{ isAddonEnabled: vi.fn(() => true), isEnabledForTrip: vi.fn(async () => true) } as unknown as AddonsService,
{ getRole: vi.fn(async () => 'user') } as unknown as UsersRepository,
);
const rpc = new PackingRpc(packing, realtime, guards);
@@ -53,7 +53,7 @@ function build(
const guards = new PluginGuards(
db,
{ checkPermission: vi.fn(() => true) } as unknown as PermissionsService,
{ isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService,
{ isAddonEnabled: vi.fn(() => true), isEnabledForTrip: vi.fn(async () => true) } as unknown as AddonsService,
{ getRole: vi.fn(async () => 'user') } as unknown as UsersRepository,
);
const realtime = { broadcast: vi.fn() } as never;
@@ -74,7 +74,7 @@ function build(addonOn: boolean) {
const guards = new PluginGuards(
db,
{ checkPermission: vi.fn(() => true) } as unknown as PermissionsService,
{ isAddonEnabled: vi.fn(() => addonOn) } as unknown as AddonsService,
{ isAddonEnabled: vi.fn(() => addonOn), isEnabledForTrip: vi.fn(async () => addonOn) } as unknown as AddonsService,
{ getRole: vi.fn(async () => 'user') } as unknown as UsersRepository,
);
const registry = createTestPluginRegistry([
@@ -168,8 +168,10 @@ describe('every addon-gated plugin method refuses when its addon is off', () =>
expect(res.ok).toBe(false);
expect(res.error.code).toBe('RESOURCE_FORBIDDEN');
expect(res.error.message).toBe(`the ${addon} addon is disabled`);
// The gate has to come before the service, not after it.
expect(f.calls).toEqual([]);
// The gate has to come before the service, not after it. listMine first reads which trips the
// user has, since a trip of theirs may have switched Costs on while the instance has it off.
const reads = method === 'costs.listMine' ? ['membership.listAccessibleTripIds'] : [];
expect(f.calls).toEqual(reads);
});
}
@@ -0,0 +1,61 @@
/**
* PEVADDON-001..004: the plugin event sink with the trip's addons in front.
*
* A trip that has an addon off shows none of its rows, so a subscribed plugin
* gets none of that family's events either; every other event goes out at once.
*/
import type { AddonsService } from '../../../src/nest/addons/addons.service';
import { tripAddonOfEvent, tripEventSink } from '../../../src/nest/plugins/plugin-event-addons';
import { describe, it, expect, vi } from 'vitest';
/** Lets the sink's pending addon read settle. */
const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
describe('the plugin event sink per trip', () => {
it('PEVADDON-001: an event names its trip addon by family; a trip event names none', () => {
expect(tripAddonOfEvent('budget:created')).toBe('budget');
expect(tripAddonOfEvent('packing:updated')).toBe('packing');
expect(tripAddonOfEvent('todo:deleted')).toBe('packing');
expect(tripAddonOfEvent('file:created')).toBe('documents');
expect(tripAddonOfEvent('collab:message:created')).toBe('collab');
expect(tripAddonOfEvent('roadtripVia:created')).toBe('roadtrip');
expect(tripAddonOfEvent('tours:updated')).toBe('tours');
expect(tripAddonOfEvent('place:created')).toBeNull();
expect(tripAddonOfEvent('toString:x')).toBeNull();
});
it('PEVADDON-002: an event of no addon goes out at once, without asking', () => {
const deliver = vi.fn();
const addons = { isEnabledForTrip: vi.fn() } as unknown as AddonsService;
tripEventSink(addons, undefined, deliver)(5, 'place:created', undefined);
expect(deliver).toHaveBeenCalledWith(5, 'place:created', undefined);
expect(addons.isEnabledForTrip).not.toHaveBeenCalled();
});
it('PEVADDON-003: an addon event goes out only for a trip that has the addon on', async () => {
const deliver = vi.fn();
const addons = {
isEnabledForTrip: vi.fn(async (tripId: number, id: string) => !(tripId === 5 && id === 'budget')),
} as unknown as AddonsService;
const sink = tripEventSink(addons, undefined, deliver);
sink(5, 'budget:created', undefined);
sink(6, 'budget:created', undefined);
sink(5, 'packing:created', undefined);
await settle();
expect(deliver.mock.calls.map(([tripId, event]) => `${tripId} ${event}`)).toEqual([
'6 budget:created',
'5 packing:created',
]);
});
it('PEVADDON-004: an addon that cannot be read sends nothing', async () => {
const deliver = vi.fn();
const addons = {
isEnabledForTrip: vi.fn(async () => Promise.reject(new Error('db gone'))),
} as unknown as AddonsService;
tripEventSink(addons, undefined, deliver)(5, 'file:created', undefined);
await settle();
expect(deliver).not.toHaveBeenCalled();
});
});
@@ -83,7 +83,7 @@ function guardsFor() {
guards: new PluginGuards(
db,
{ checkPermission: vi.fn(() => true) } as unknown as PermissionsService,
{ isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService,
{ isAddonEnabled: vi.fn(() => true), isEnabledForTrip: vi.fn(async () => true) } as unknown as AddonsService,
{ getRole: vi.fn(async () => 'user') } as unknown as UsersRepository,
),
};
@@ -6,6 +6,7 @@
* 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';
@@ -23,7 +24,7 @@ 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']) {
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)),
@@ -32,6 +33,9 @@ function controller(invoke: (id: string) => unknown, providers = ['p1']) {
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,
};
@@ -152,4 +156,13 @@ describe('ViewContributionsController', () => {
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);
});
});
+1 -1
View File
@@ -44,7 +44,7 @@ function build(canEdit = true) {
),
} as unknown as TripsRepository,
permissions,
{ isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService,
{ isAddonEnabled: vi.fn(() => true), isEnabledForTrip: vi.fn(async () => true) } as unknown as AddonsService,
{ getRole: vi.fn(async () => 'user') } as unknown as UsersRepository,
);
const rpc = new TodoRpc(todos, realtime, guards);