mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 01:28:55 +00:00
refactor(mcp): the demo-mode write block runs once, in the registry's tool gate
Every write tool used to open with its own demo check, 196 copies across 30 tool files, most of them injecting AuthService for nothing else. The registry now takes a toolGate (built from the container) that runs before each registered tool handler, and TREK's gate refuses a demo account on every tool not annotated read-only with the same canned result. The per-tool checks, the AuthService injections, AuthService.isDemoUser and the AuthModule imports that only fed them are gone; ESLint refuses a demo check in a tool file, and a registry-wide test calls every write tool as the demo account.
This commit is contained in:
@@ -243,3 +243,32 @@ describe('app setting selectors', () => {
|
||||
expect(messages(service, `${PROBE}void repo.getValue(\`pref_\${key}\`);`)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('MCP demo gate selectors', () => {
|
||||
const DEMO = 'MCP tools do not check demo mode themselves';
|
||||
const demoHits = (options: unknown[], code: string) => messages(options, code).filter((m) => m.startsWith(DEMO));
|
||||
const CODE = `
|
||||
declare const auth: { isDemoUser(id: number): Promise<boolean> };
|
||||
declare const demo: { isDemoUserId(id: number): Promise<boolean> };
|
||||
declare function demoDenied(): unknown;
|
||||
`;
|
||||
|
||||
it('refuses a demo check of its own in a *.mcp.ts file, and keeps the env and fetch guards there', async () => {
|
||||
const options = await selectorsFor('src/nest/memories/probe.mcp.ts');
|
||||
expect(demoHits(options, `${CODE}
|
||||
void auth.isDemoUser(1);`)).toHaveLength(1);
|
||||
expect(demoHits(options, `${CODE}
|
||||
void demo.isDemoUserId(1);`)).toHaveLength(1);
|
||||
expect(demoHits(options, `${CODE}
|
||||
void demoDenied();`)).toHaveLength(1);
|
||||
expect(messages(options, 'void process.env.X;')).not.toEqual([]);
|
||||
expect(messages(options, `${PRELUDE}
|
||||
void fetch(url);`)).not.toEqual([]);
|
||||
});
|
||||
|
||||
it('leaves the same call alone outside the tool files', async () => {
|
||||
const options = await selectorsFor('src/nest/memories/probe.service.ts');
|
||||
expect(demoHits(options, `${CODE}
|
||||
void demo.isDemoUserId(1);`)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
/**
|
||||
* The demo-mode write block, held for every registered MCP tool at once.
|
||||
*
|
||||
* The block used to be the first line of each write tool; it now runs in the
|
||||
* registry (trekDemoToolGate, wired into McpModule.forRoot and into the MCP test
|
||||
* registry). This suite attaches the real registry to a capturing server and
|
||||
* calls every write tool as the demo account: each one has to answer with the
|
||||
* canned refusal before its handler runs. Every read-only tool has to pass the
|
||||
* gate. Besides that it pins the two markers the gate relies on to each other,
|
||||
* so a tool declared `mode: 'write'` but annotated read-only (or the reverse)
|
||||
* fails here instead of slipping past the gate.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeAll, beforeEach, afterEach, afterAll } from 'vitest';
|
||||
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
|
||||
import { db as testDb } from '../../../src/db/database';
|
||||
|
||||
vi.mock('../../../src/db/database', async () => {
|
||||
const { createSnapshotTestDb, buildDbMock } = await import('../../helpers/db-mock');
|
||||
return buildDbMock(createSnapshotTestDb());
|
||||
});
|
||||
vi.mock('../../../src/config', () => ({
|
||||
JWT_SECRET: 'test-jwt-secret-for-trek-testing-only',
|
||||
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
|
||||
updateJwtSecret: () => {},
|
||||
}));
|
||||
vi.mock('../../../src/websocket', () => ({ broadcast: vi.fn() }));
|
||||
|
||||
import { resetTestDb, setAddonEnabled } from '../../helpers/test-db';
|
||||
import { createUser } from '../../helpers/factories';
|
||||
import { createMcpTestRegistry } from '../../helpers/mcp-test-controllers';
|
||||
import { ADDON_IDS } from '../../../src/addons';
|
||||
import { isDemoGatedTool, trekDemoToolGate } from '../../../src/mcp/nest-mcp-policy';
|
||||
import type { McpContext, McpRegistry, McpRegistryListing } from '../../../src/nest-mcp';
|
||||
|
||||
const DEMO_REFUSAL = { content: [{ type: 'text', text: 'Write operations are disabled in demo mode.' }], isError: true };
|
||||
|
||||
interface CapturedTool {
|
||||
annotations?: Record<string, unknown>;
|
||||
call: (args?: Record<string, unknown>) => Promise<unknown>;
|
||||
}
|
||||
|
||||
/** Attaches the registry to a stand-in server that keeps every tool callback instead of serving it. */
|
||||
async function captureTools(registry: McpRegistry, ctx: McpContext): Promise<Map<string, CapturedTool>> {
|
||||
const tools = new Map<string, CapturedTool>();
|
||||
const server = {
|
||||
registerTool: (name: string, config: { annotations?: Record<string, unknown> }, cb: (...a: unknown[]) => unknown) => {
|
||||
// Arguments as a client would send nothing: the gate answers before
|
||||
// the handler ever reads them.
|
||||
tools.set(name, { annotations: config.annotations, call: async (args = {}) => cb(args, {}) });
|
||||
},
|
||||
registerResource: () => undefined,
|
||||
registerPrompt: () => undefined,
|
||||
} as unknown as McpServer;
|
||||
await registry.attach(server, ctx);
|
||||
return tools;
|
||||
}
|
||||
|
||||
let registry: McpRegistry;
|
||||
let toolListings: McpRegistryListing[];
|
||||
|
||||
beforeAll(async () => {
|
||||
registry = await createMcpTestRegistry();
|
||||
toolListings = registry.list().filter((entry) => entry.kind === 'tool');
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
resetTestDb(testDb);
|
||||
for (const id of Object.values(ADDON_IDS)) setAddonEnabled(testDb, id, true);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
delete process.env.DEMO_MODE;
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
testDb.close();
|
||||
});
|
||||
|
||||
describe('demo tool gate over the whole registry', () => {
|
||||
it('DEMOGATE-001: every write tool refuses the demo account with the canned body, before its handler', async () => {
|
||||
process.env.DEMO_MODE = 'true';
|
||||
const { user: demo } = createUser(testDb, { email: 'demo@trek.app' });
|
||||
const tools = await captureTools(registry, { userId: demo.id, scopes: null, isStaticToken: false });
|
||||
|
||||
const writes = [...tools].filter(([, t]) => t.annotations?.readOnlyHint !== true);
|
||||
expect(writes.length).toBeGreaterThan(150);
|
||||
for (const [name, tool] of writes) {
|
||||
expect({ name, result: await tool.call() }).toEqual({ name, result: DEMO_REFUSAL });
|
||||
}
|
||||
});
|
||||
|
||||
it('DEMOGATE-002: no read-only tool is held back for the demo account', async () => {
|
||||
process.env.DEMO_MODE = 'true';
|
||||
const { user: demo } = createUser(testDb, { email: 'demo@trek.app' });
|
||||
const ctx: McpContext = { userId: demo.id, scopes: null, isStaticToken: false };
|
||||
const gate = trekDemoToolGate(async () => true);
|
||||
const tools = await captureTools(registry, ctx);
|
||||
|
||||
const reads = [...tools].filter(([, t]) => t.annotations?.readOnlyHint === true);
|
||||
expect(reads.length).toBeGreaterThan(80);
|
||||
for (const [name, tool] of reads) {
|
||||
expect({ name, refusal: await gate({ name, annotations: tool.annotations }, ctx) }).toEqual({ name, refusal: undefined });
|
||||
}
|
||||
});
|
||||
|
||||
it('DEMOGATE-003: an ordinary account reaches the write handlers in demo mode', async () => {
|
||||
process.env.DEMO_MODE = 'true';
|
||||
const { user } = createUser(testDb, { email: 'alice@example.com' });
|
||||
const tools = await captureTools(registry, { userId: user.id, scopes: null, isStaticToken: false });
|
||||
// create_tag has no trip to check and no addon gate: it writes and answers.
|
||||
const result = (await tools.get('create_tag')!.call({ name: 'Mine' })) as { isError?: boolean; content: { text: string }[] };
|
||||
expect(result.isError).toBeUndefined();
|
||||
expect(result.content[0].text).toContain('Mine');
|
||||
});
|
||||
|
||||
it('DEMOGATE-004: outside demo mode the demo account is an ordinary account', async () => {
|
||||
const { user: demo } = createUser(testDb, { email: 'demo@trek.app' });
|
||||
const tools = await captureTools(registry, { userId: demo.id, scopes: null, isStaticToken: false });
|
||||
const result = (await tools.get('create_tag')!.call({ name: 'Mine' })) as { isError?: boolean };
|
||||
expect(result.isError).toBeUndefined();
|
||||
});
|
||||
|
||||
it('DEMOGATE-005: with every addon on, only the photo-library tools stay detached, so the sweep above covers the rest', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const tools = await captureTools(registry, { userId: user.id, scopes: null, isStaticToken: false });
|
||||
const missing = toolListings.map((t) => t.name).filter((name) => !tools.has(name));
|
||||
// These three wait for a connected Immich or Synology provider
|
||||
// (anyPhotoProviderEnabled), and all three are reads.
|
||||
expect(missing.sort()).toEqual(['list_provider_album_photos', 'list_provider_albums', 'search_provider_photos']);
|
||||
});
|
||||
|
||||
it('DEMOGATE-006: the scope mode and the read-only annotation agree on every declarative tool', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const tools = await captureTools(registry, { userId: user.id, scopes: null, isStaticToken: false });
|
||||
const mismatched: string[] = [];
|
||||
for (const listing of toolListings) {
|
||||
const access = listing.access;
|
||||
if (access === undefined || typeof access === 'function') continue;
|
||||
const tool = tools.get(listing.name);
|
||||
if (!tool) continue; // the detached photo-library reads of DEMOGATE-005
|
||||
const readOnly = tool.annotations?.readOnlyHint === true;
|
||||
if (access.mode === 'read' && !readOnly) mismatched.push(`${listing.name}: mode read, not annotated read-only`);
|
||||
if ((access.mode === 'write' || access.mode === 'delete') && readOnly) {
|
||||
mismatched.push(`${listing.name}: mode ${access.mode}, annotated read-only`);
|
||||
}
|
||||
}
|
||||
expect(mismatched).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('trekDemoToolGate', () => {
|
||||
const ctx: McpContext = { userId: 7, scopes: null, isStaticToken: false };
|
||||
|
||||
it('DEMOGATE-010: refuses a write tool for a demo account and asks with the caller id', async () => {
|
||||
const isDemo = vi.fn(async () => true);
|
||||
expect(await trekDemoToolGate(isDemo)({ name: 'w', annotations: { readOnlyHint: false } }, ctx)).toEqual(DEMO_REFUSAL);
|
||||
expect(isDemo).toHaveBeenCalledWith(7);
|
||||
});
|
||||
|
||||
it('DEMOGATE-011: lets a write tool through for any other account', async () => {
|
||||
expect(await trekDemoToolGate(async () => false)({ name: 'w' }, ctx)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('DEMOGATE-012: never asks about the caller for a read-only tool', async () => {
|
||||
const isDemo = vi.fn(async () => true);
|
||||
expect(await trekDemoToolGate(isDemo)({ name: 'r', annotations: { readOnlyHint: true } }, ctx)).toBeUndefined();
|
||||
expect(isDemo).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('DEMOGATE-013: a tool without annotations counts as a write', () => {
|
||||
expect(isDemoGatedTool({ name: 'x' })).toBe(true);
|
||||
expect(isDemoGatedTool({ name: 'x', annotations: { readOnlyHint: true } })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -28,7 +28,7 @@ import { resetTestDb } from '../../helpers/test-db';
|
||||
import { createUser, createAdmin } from '../../helpers/factories';
|
||||
import { createMcpHarness, parseToolResult, parseResourceResult, type McpHarness } from '../../helpers/mcp-harness';
|
||||
import { createTestRegistry } from '../../../src/nest-mcp';
|
||||
import { trekMcpAccessPolicy, trekMcpValidateAccess } from '../../../src/mcp/nest-mcp-policy';
|
||||
import { trekDemoToolGate, trekMcpAccessPolicy, trekMcpValidateAccess } from '../../../src/mcp/nest-mcp-policy';
|
||||
import { CategoriesMcp } from '../../../src/nest/categories/categories.mcp';
|
||||
import { CategoriesService } from '../../../src/nest/categories/categories.service';
|
||||
import { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service';
|
||||
@@ -78,19 +78,20 @@ async function withHarness(
|
||||
// file's DB, which is what lets the admin gate and the demo gate be driven from
|
||||
// the users table instead of from a stub.
|
||||
let categoriesMcp: CategoriesMcp;
|
||||
let categoriesDemo: DemoService;
|
||||
beforeAll(async () => {
|
||||
const categoriesEm = (await sharedTestOrm(testDb)).em;
|
||||
categoriesMcp = new CategoriesMcp(
|
||||
new CategoriesService(await createTestCategoriesRepo(testDb)),
|
||||
new RuntimeEnvService(),
|
||||
new McpToolGuardsService(await createTestTripsRepo(testDb), await createTestUsersRepo(testDb), new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)), new RealtimeService()),
|
||||
new DemoService(new RuntimeEnvService(), categoriesEm),
|
||||
);
|
||||
categoriesDemo = new DemoService(new RuntimeEnvService(), categoriesEm);
|
||||
});
|
||||
|
||||
async function withWriteHarness(userId: number, fn: (client: Client) => Promise<void>) {
|
||||
const server = new McpServer({ name: 'trek-test', version: '1.0.0' });
|
||||
await createTestRegistry([categoriesMcp], { accessPolicy: trekMcpAccessPolicy, validateAccess: trekMcpValidateAccess })
|
||||
await createTestRegistry([categoriesMcp], { accessPolicy: trekMcpAccessPolicy, validateAccess: trekMcpValidateAccess, toolGate: trekDemoToolGate((id) => categoriesDemo.isDemoUserId(id)) })
|
||||
.attach(server, { userId, scopes: null, isStaticToken: false });
|
||||
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
||||
const client = new Client({ name: 'test-client', version: '1.0.0' });
|
||||
|
||||
@@ -69,17 +69,15 @@ import { BudgetService } from '../../../src/nest/budget/budget.service';
|
||||
import { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service';
|
||||
import { ExchangeRatesService } from '../../../src/nest/budget/exchange-rates.service';
|
||||
import { AuthMcp } from '../../../src/nest/auth/auth.mcp';
|
||||
import { DemoService } from '../../../src/nest/common/demo.service';
|
||||
import { PermissionsService } from '../../../src/nest/permissions/permissions.service';
|
||||
import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
|
||||
import { McpToolGuardsService } from '../../../src/nest/mcp-shared/mcp-tool-guards.service';
|
||||
import type { AuthService } from '../../../src/nest/auth/auth.service';
|
||||
import type { TripsService } from '../../../src/nest/trips/trips.service';
|
||||
import type { TodoService } from '../../../src/nest/todo/todo.service';
|
||||
import type { CollabService } from '../../../src/nest/collab/collab.service';
|
||||
import { AddonsService } from '../../../src/nest/addons/addons.service';
|
||||
import { notificationsStub } from '../../helpers/notifications';
|
||||
import { createTestUnitOfWork, createTestAppSettingsRepo, createTestTripsRepo, createTestTripMembersRepo, createTestUsersRepo, sharedTestOrm, createTestPlacesRepo } from '../../helpers/test-uow';
|
||||
import { createTestUnitOfWork, createTestAppSettingsRepo, createTestTripsRepo, createTestTripMembersRepo, createTestUsersRepo, createTestPlacesRepo } from '../../helpers/test-uow';
|
||||
import { budgetRepoArgs } from '../../helpers/budget-repos';
|
||||
import {
|
||||
createTestPackingItemsRepo,
|
||||
@@ -90,7 +88,6 @@ import {
|
||||
createTestPackingTemplateCategoriesRepo,
|
||||
createTestPackingTemplateItemsRepo,
|
||||
} from '../../helpers/packing-repos';
|
||||
import type { EntityManager } from '@mikro-orm/core';
|
||||
|
||||
// The trip-summary prompt moved to the DI-discovered TripsMcp — its cases below
|
||||
// exercise it through a hand-built registry over a stub TripsService whose
|
||||
@@ -112,16 +109,6 @@ const readModelStub = {
|
||||
// The three remaining prompts moved to their domains' @McpController classes:
|
||||
// packing-list, budget-overview and the static-token notice. Built over the same
|
||||
// in-memory DB so the cases below keep asserting real rows.
|
||||
//
|
||||
// Plan 3c Task 0b: `promptEm` is resolved once in the first `beforeAll` below —
|
||||
// `canAccessTrip`/`isOwner`/`rosterUserIds`/
|
||||
// `getPlaceWithTags` resolve `TripsRepository`/`TripMembersRepository`/
|
||||
// `PlacesRepository` through it now, not through `db/database.ts`'s deleted
|
||||
// free functions this file's `dbMock` used to stand in for.
|
||||
let promptEm: EntityManager | undefined;
|
||||
const authStub = { isDemoUser: () => false } as unknown as AuthService;
|
||||
|
||||
|
||||
|
||||
// The packing-list / budget-overview prompts live here since the trips.bridge
|
||||
// fold; the summary rides the same readModelStub the trip-summary prompt uses.
|
||||
@@ -134,7 +121,6 @@ let budgetMcp: BudgetMcp;
|
||||
let tripPromptsMcp: TripPromptsMcp;
|
||||
beforeAll(async () => {
|
||||
orm = await createTestOrm(testDb);
|
||||
promptEm = (await sharedTestOrm(testDb)).em;
|
||||
promptGuards = new McpToolGuardsService(await createTestTripsRepo(testDb), await createTestUsersRepo(testDb), new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)), new RealtimeService());
|
||||
tripsMcp = new TripsMcp(
|
||||
tripsStub,
|
||||
@@ -142,7 +128,6 @@ beforeAll(async () => {
|
||||
{ listPolls: () => [], countMessages: () => 0 } as unknown as CollabService,
|
||||
undefined as never,
|
||||
undefined as never,
|
||||
undefined as never,
|
||||
readModelStub,
|
||||
addonsStub,
|
||||
promptGuards,
|
||||
@@ -162,7 +147,7 @@ beforeAll(async () => {
|
||||
await createTestTripsRepo(testDb),
|
||||
await createTestTripMembersRepo(testDb),
|
||||
);
|
||||
packingMcp = new PackingMcp(promptPackingService, authStub, addonsStub, promptGuards);
|
||||
packingMcp = new PackingMcp(promptPackingService, addonsStub, promptGuards);
|
||||
promptBudget = new BudgetService(new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)), new ExchangeRatesService(), new RealtimeService(), await createTestUnitOfWork(testDb), ...(await budgetRepoArgs(testDb)));
|
||||
budgetMcp = new BudgetMcp(
|
||||
promptBudget,
|
||||
@@ -174,7 +159,6 @@ beforeAll(async () => {
|
||||
await createTestUnitOfWork(testDb),
|
||||
await createTestPlacesRepo(testDb),
|
||||
await createTestTripsRepo(testDb),
|
||||
new DemoService(new RuntimeEnvService(), promptEm),
|
||||
await createTestTripMembersRepo(testDb),
|
||||
);
|
||||
tripPromptsMcp = new TripPromptsMcp(tripsStub, readModelStub, promptPackingService, addonsStub);
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
import {
|
||||
createTestRegistry,
|
||||
McpController,
|
||||
McpModule,
|
||||
McpRegistryService,
|
||||
Resource,
|
||||
Tool,
|
||||
type McpDynamicTool,
|
||||
type McpToolGate,
|
||||
} from '../../../src/nest-mcp';
|
||||
import { asCtx, createAttachHarness, type AttachHarness, type TestCtx } from './harness';
|
||||
import { Injectable, Module } from '@nestjs/common';
|
||||
import { Test } from '@nestjs/testing';
|
||||
|
||||
import 'reflect-metadata';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { z } from 'zod';
|
||||
|
||||
const REFUSAL = { content: [{ type: 'text', text: 'refused' }], isError: true };
|
||||
|
||||
@McpController()
|
||||
class GatedMcp {
|
||||
calls = 0;
|
||||
|
||||
@Tool({ name: 'write_it', inputSchema: { n: z.number() }, annotations: { readOnlyHint: false } })
|
||||
async writeIt({ n }: { n: number }, ctx: TestCtx) {
|
||||
this.calls++;
|
||||
return { content: [{ type: 'text', text: JSON.stringify({ n, userId: ctx.userId }) }] };
|
||||
}
|
||||
|
||||
@Tool({ name: 'no_schema', annotations: { readOnlyHint: true } })
|
||||
async noSchema(args: Record<string, never>) {
|
||||
return { content: [{ type: 'text', text: JSON.stringify(args) }] };
|
||||
}
|
||||
|
||||
@Resource({ name: 'res', uri: 'gate://res' })
|
||||
async res(uri: URL) {
|
||||
return { contents: [{ uri: uri.href, text: 'resource' }] };
|
||||
}
|
||||
}
|
||||
|
||||
const textOf = (result: unknown): string => (result as { content: { text: string }[] }).content[0].text;
|
||||
|
||||
describe('tool gate', () => {
|
||||
let harness: AttachHarness | undefined;
|
||||
afterEach(async () => {
|
||||
await harness?.cleanup();
|
||||
harness = undefined;
|
||||
});
|
||||
|
||||
it('answers with the gate result and never runs the handler', async () => {
|
||||
const mcp = new GatedMcp();
|
||||
const gate = vi.fn<McpToolGate>(() => REFUSAL);
|
||||
harness = await createAttachHarness(createTestRegistry([mcp], { toolGate: gate }), { userId: 3 });
|
||||
const result = await harness.client.callTool({ name: 'write_it', arguments: { n: 1 } });
|
||||
expect(result).toEqual(REFUSAL);
|
||||
expect(mcp.calls).toBe(0);
|
||||
expect(gate).toHaveBeenCalledWith(expect.objectContaining({ name: 'write_it', annotations: { readOnlyHint: false } }), asCtx({ userId: 3 }));
|
||||
});
|
||||
|
||||
it('runs the handler with its arguments when the gate returns undefined', async () => {
|
||||
const mcp = new GatedMcp();
|
||||
harness = await createAttachHarness(createTestRegistry([mcp], { toolGate: async () => undefined }), { userId: 4 });
|
||||
const result = await harness.client.callTool({ name: 'write_it', arguments: { n: 2 } });
|
||||
expect(JSON.parse(textOf(result))).toEqual({ n: 2, userId: 4 });
|
||||
expect(mcp.calls).toBe(1);
|
||||
});
|
||||
|
||||
it('gates a tool without an input schema too', async () => {
|
||||
harness = await createAttachHarness(createTestRegistry([new GatedMcp()], { toolGate: () => REFUSAL }), {});
|
||||
expect(await harness.client.callTool({ name: 'no_schema', arguments: {} })).toEqual(REFUSAL);
|
||||
});
|
||||
|
||||
it('leaves resources alone', async () => {
|
||||
const gate = vi.fn<McpToolGate>(() => REFUSAL);
|
||||
harness = await createAttachHarness(createTestRegistry([new GatedMcp()], { toolGate: gate }), {});
|
||||
const read = await harness.client.readResource({ uri: 'gate://res' });
|
||||
expect(read.contents[0]).toMatchObject({ text: 'resource' });
|
||||
expect(gate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('leaves dynamic tools to their own source', async () => {
|
||||
const gate = vi.fn<McpToolGate>(() => REFUSAL);
|
||||
const dynamic: McpDynamicTool = {
|
||||
options: { name: 'dyn', inputSchema: {}, access: () => true },
|
||||
handler: () => ({ content: [{ type: 'text', text: 'dynamic ran' }] }),
|
||||
};
|
||||
harness = await createAttachHarness(createTestRegistry([], { toolGate: gate }), {}, { dynamicTools: () => [dynamic] });
|
||||
expect(textOf(await harness.client.callTool({ name: 'dyn', arguments: {} }))).toBe('dynamic ran');
|
||||
expect(gate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('runs after onInvoke and inside around, so the audit and the trace still see a refused call', async () => {
|
||||
const order: string[] = [];
|
||||
const registry = createTestRegistry([new GatedMcp()], {
|
||||
toolGate: () => {
|
||||
order.push('gate');
|
||||
return REFUSAL;
|
||||
},
|
||||
});
|
||||
harness = await createAttachHarness(registry, {}, {
|
||||
onInvoke: () => order.push('onInvoke'),
|
||||
around: async (_info, call) => {
|
||||
order.push('around:in');
|
||||
const out = await call();
|
||||
order.push('around:out');
|
||||
return out;
|
||||
},
|
||||
});
|
||||
await harness.client.callTool({ name: 'write_it', arguments: { n: 1 } });
|
||||
expect(order).toEqual(['onInvoke', 'around:in', 'gate', 'around:out']);
|
||||
});
|
||||
|
||||
it('is skipped entirely without a configured gate', async () => {
|
||||
const mcp = new GatedMcp();
|
||||
harness = await createAttachHarness(createTestRegistry([mcp]), { userId: 1 });
|
||||
await harness.client.callTool({ name: 'write_it', arguments: { n: 5 } });
|
||||
expect(mcp.calls).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
@Injectable()
|
||||
class Verdicts {
|
||||
refuse = true;
|
||||
}
|
||||
|
||||
@Module({ providers: [Verdicts, GatedMcp], exports: [Verdicts] })
|
||||
class GatedModule {}
|
||||
|
||||
describe('McpModule.forRoot toolGate', () => {
|
||||
let harness: AttachHarness | undefined;
|
||||
afterEach(async () => {
|
||||
await harness?.cleanup();
|
||||
harness = undefined;
|
||||
});
|
||||
|
||||
it('builds the gate from the container with its injected providers', async () => {
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
imports: [
|
||||
GatedModule,
|
||||
McpModule.forRoot({
|
||||
toolGate: {
|
||||
imports: [GatedModule],
|
||||
inject: [Verdicts],
|
||||
useFactory: (verdicts: Verdicts) => () => (verdicts.refuse ? REFUSAL : undefined),
|
||||
},
|
||||
}),
|
||||
],
|
||||
}).compile();
|
||||
await moduleRef.init();
|
||||
harness = await createAttachHarness(moduleRef.get(McpRegistryService), { userId: 1 });
|
||||
expect(await harness.client.callTool({ name: 'write_it', arguments: { n: 1 } })).toEqual(REFUSAL);
|
||||
moduleRef.get(Verdicts).refuse = false;
|
||||
expect(JSON.parse(textOf(await harness.client.callTool({ name: 'write_it', arguments: { n: 1 } })))).toEqual({ n: 1, userId: 1 });
|
||||
await moduleRef.close();
|
||||
});
|
||||
|
||||
it('boots without a gate and runs every handler', async () => {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [GatedModule, McpModule.forRoot()] }).compile();
|
||||
await moduleRef.init();
|
||||
harness = await createAttachHarness(moduleRef.get(McpRegistryService), { userId: 2 });
|
||||
expect(JSON.parse(textOf(await harness.client.callTool({ name: 'write_it', arguments: { n: 3 } })))).toEqual({ n: 3, userId: 2 });
|
||||
await moduleRef.close();
|
||||
});
|
||||
});
|
||||
@@ -1189,17 +1189,6 @@ describe('resetPassword', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('ephemeral + demo helpers', () => {
|
||||
it('AUTH-DB-088: isDemoUser is true only for the demo email in demo mode', async () => {
|
||||
const { user } = createUser(testDb, { email: 'demo@nomad.app' });
|
||||
const { user: other } = createUser(testDb);
|
||||
expect(await svc.isDemoUser(user.id)).toBe(false); // demo mode off
|
||||
vi.stubEnv('DEMO_MODE', 'true');
|
||||
expect(await svc.isDemoUser(user.id)).toBe(true);
|
||||
expect(await svc.isDemoUser(other.id)).toBe(false);
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Quirk fixes after the DI fold (trailing fix(server) commit): AUTH-DB-089+.
|
||||
|
||||
@@ -43,7 +43,7 @@ import { DawarichMcp } from '../../../src/nest/integrations/dawarich.mcp';
|
||||
import { AcceptError } from '../../../src/nest/integrations/dawarich-suggestions.service';
|
||||
import type { DawarichSuggestionsService } from '../../../src/nest/integrations/dawarich-suggestions.service';
|
||||
import type { DawarichTracksService } from '../../../src/nest/integrations/dawarich-tracks.service';
|
||||
import type { AuthService } from '../../../src/nest/auth/auth.service';
|
||||
import { callGatedTool } from '../../helpers/mcp-gate';
|
||||
import type { AddonsService } from '../../../src/nest/addons/addons.service';
|
||||
import { getEntry, type ClassRef } from '../../../src/nest-mcp/metadata';
|
||||
import type { McpContext, McpTextResult, ToolOptions } from '../../../src/nest-mcp';
|
||||
@@ -54,17 +54,14 @@ const ctx = { userId: 7, scopes: null, isStaticToken: false } as McpContext;
|
||||
interface Mocks {
|
||||
suggestions?: Partial<DawarichSuggestionsService>;
|
||||
tracks?: Partial<DawarichTracksService>;
|
||||
auth?: Partial<AuthService>;
|
||||
addons?: Partial<AddonsService>;
|
||||
}
|
||||
|
||||
/** The demo gate is off unless a case turns it on; every write tool asks it. */
|
||||
/** The demo gate runs in the registry; the cases about it go through callGatedTool. */
|
||||
function makeMcp(m: Mocks = {}) {
|
||||
const auth: Partial<AuthService> = m.auth ?? { isDemoUser: async () => false };
|
||||
return new DawarichMcp(
|
||||
(m.suggestions ?? {}) as DawarichSuggestionsService,
|
||||
(m.tracks ?? {}) as DawarichTracksService,
|
||||
auth as AuthService,
|
||||
(m.addons ?? {}) as AddonsService,
|
||||
);
|
||||
}
|
||||
@@ -226,10 +223,10 @@ describe('DawarichMcp surface', () => {
|
||||
const forTrip = vi.fn().mockResolvedValue({
|
||||
days: [], source: 'tracks', fetchedAt: '2026-05-02T09:00:00.000Z', pointCount: 0, truncated: false,
|
||||
});
|
||||
const mcp = makeMcp({ suggestions: { list: listFn }, tracks: { forTrip }, auth: { isDemoUser } });
|
||||
const mcp = makeMcp({ suggestions: { list: listFn }, tracks: { forTrip } });
|
||||
|
||||
payload(await mcp.listSuggestions({}, ctx));
|
||||
payload(await mcp.tripTrack({ tripId: 5 }, ctx));
|
||||
payload((await callGatedTool(mcp, 'listSuggestions', {}, ctx, isDemoUser)) as McpTextResult);
|
||||
payload((await callGatedTool(mcp, 'tripTrack', { tripId: 5 }, ctx, isDemoUser)) as McpTextResult);
|
||||
expect(isDemoUser).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -439,10 +436,9 @@ describe('DawarichMcp accept tools', () => {
|
||||
const accept = vi.fn();
|
||||
const setState = vi.fn();
|
||||
const isDemoUser = vi.fn().mockResolvedValue(true);
|
||||
const mcp = makeMcp({ suggestions: { accept, setState }, auth: { isDemoUser } });
|
||||
const mcp = makeMcp({ suggestions: { accept, setState } });
|
||||
|
||||
const call = (mcp as unknown as Record<string, (a: unknown, c: McpContext) => Promise<McpTextResult>>)[method];
|
||||
expect(refusal(await call.call(mcp, args, ctx))).toBe('Write operations are disabled in demo mode.');
|
||||
expect(refusal((await callGatedTool(mcp, method, args, ctx, isDemoUser)) as McpTextResult)).toBe('Write operations are disabled in demo mode.');
|
||||
expect(isDemoUser).toHaveBeenCalledWith(7);
|
||||
expect(accept).not.toHaveBeenCalled();
|
||||
expect(setState).not.toHaveBeenCalled();
|
||||
|
||||
@@ -18,6 +18,7 @@ import { DayAssignments } from '../../../src/db/entities/DayAssignments.entity';
|
||||
import { RoadtripDayBoundaries } from '../../../src/db/entities/RoadtripDayBoundaries.entity';
|
||||
import { deleteRows } from '../../helpers/factories/rows';
|
||||
import type { McpContext } from '../../../src/nest-mcp';
|
||||
import { callGatedTool } from '../../helpers/mcp-gate';
|
||||
|
||||
const testDb = createSnapshotTestDb();
|
||||
let t: TestOrm;
|
||||
@@ -41,16 +42,16 @@ function setup() {
|
||||
const boundariesRepo = t.repo(RoadtripDayBoundaries);
|
||||
const service = new DayBoundariesService(dayAssignmentsRepo, boundariesRepo);
|
||||
const realtime = { broadcast: vi.fn() };
|
||||
const auth = { isDemoUser: vi.fn(() => false) };
|
||||
const demo = { isDemoUser: vi.fn(async () => false) };
|
||||
const guards = { hasTripPermission: vi.fn(() => true) };
|
||||
const tripsRepo = { findAccessible: vi.fn(async () => ({ id: tripA.id, user_id: user.id })) };
|
||||
const mcp = new DayBoundariesMcp(service, tripsRepo as never, auth as never, guards as never, realtime as never, {} as never);
|
||||
const mcp = new DayBoundariesMcp(service, tripsRepo as never, guards as never, realtime as never, {} as never);
|
||||
return {
|
||||
service,
|
||||
controller: new DayBoundariesController(service, realtime as never),
|
||||
mcp,
|
||||
tripsRepo,
|
||||
auth,
|
||||
demo,
|
||||
guards,
|
||||
realtime,
|
||||
tripA,
|
||||
@@ -134,9 +135,10 @@ it('MCP checks demo, trip access and edit permission before saving', async () =>
|
||||
const ctx = { userId: 1 } as McpContext;
|
||||
const boundary = { day_number: 1, from_assignment_id: s.fromId, to_assignment_id: s.toId, fraction: 0.4 };
|
||||
const request = { tripId: s.tripA.id, dayNumber: 1, boundary };
|
||||
s.auth.isDemoUser.mockReturnValue(true);
|
||||
await s.mcp.save(request, ctx);
|
||||
s.auth.isDemoUser.mockReturnValue(false);
|
||||
const save = (req: typeof request) => callGatedTool(s.mcp, 'save', req, ctx, s.demo.isDemoUser);
|
||||
s.demo.isDemoUser.mockResolvedValue(true);
|
||||
await save(request);
|
||||
s.demo.isDemoUser.mockResolvedValue(false);
|
||||
s.tripsRepo.findAccessible.mockResolvedValue(undefined);
|
||||
await s.mcp.save(request, ctx);
|
||||
s.tripsRepo.findAccessible.mockResolvedValue({ id: s.tripA.id, user_id: 1 });
|
||||
|
||||
@@ -1,21 +1,15 @@
|
||||
/**
|
||||
* Plan 3i Task 3 — named regression tests for 4 of the 5 `isDemoUserId`
|
||||
* survivor sites (the 5th, `PluginMcpToolsService`, is MCPTOOLS-014 in
|
||||
* `tests/unit/plugins/plugin-mcp-tools.test.ts`, strengthened in this same
|
||||
* task to assert the exact refusal body too).
|
||||
*
|
||||
* Each of `TripInviteMcp`/`FeedsMcp`/`CategoriesMcp`/`BudgetMcp` checks
|
||||
* `this.isDemoUser(ctx.userId)` — now `this.demo.isDemoUserId(userId)`,
|
||||
* the injected `DemoService` (`common/demo.service.ts`) — as the FIRST
|
||||
* statement of the write tool exercised below, before touching any other
|
||||
* collaborator, so every other constructor dependency can stay an untyped
|
||||
* stub: the mutation this proves (Task 3's report: "mutation proofs for the
|
||||
* demo gates — loosen isDemoUserId → red") is that a `DemoService` whose
|
||||
* `isDemoUserId` resolves `true` reaches the exact canned `demoDenied()`
|
||||
* body byte-for-byte, not a domain-specific string.
|
||||
* The demo refusal for the four write tools that used to ask DemoService
|
||||
* themselves (trip invites, calendar feeds, categories, budget). The check now
|
||||
* sits in the registry's tool gate (trekDemoToolGate), so each tool is called
|
||||
* the way a session reaches it, through tests/helpers/mcp-gate.ts, with every
|
||||
* other collaborator a bare stub: a refusal that reached any of them would
|
||||
* throw instead. The fifth site, PluginMcpToolsService, keeps its own gate and
|
||||
* is MCPTOOLS-014 in tests/unit/plugins/plugin-mcp-tools.test.ts.
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type { McpContext } from '../../../src/nest-mcp';
|
||||
import { callGatedTool } from '../../helpers/mcp-gate';
|
||||
import { TripInviteMcp } from '../../../src/nest/trip-invite/trip-invite.mcp';
|
||||
import { FeedsMcp } from '../../../src/nest/feeds/feeds.mcp';
|
||||
import { CategoriesMcp } from '../../../src/nest/categories/categories.mcp';
|
||||
@@ -25,32 +19,32 @@ const DEMO_REFUSAL = { content: [{ type: 'text', text: 'Write operations are dis
|
||||
|
||||
const ctx = { userId: 5, scopes: null, isStaticToken: false } as McpContext;
|
||||
|
||||
/** A DemoService stub whose isDemoUserId always resolves `true`. */
|
||||
const demoBlocked = { isDemoUserId: () => Promise.resolve(true) } as never;
|
||||
/** The demo check, answering yes for everyone. */
|
||||
const demoBlocked = () => Promise.resolve(true);
|
||||
const stub = {} as never;
|
||||
|
||||
describe('Plan 3i Task 3 — isDemoUserId survivor sites: exact refusal body per domain', () => {
|
||||
describe('demo refusal at the former survivor sites: exact refusal body per domain', () => {
|
||||
it('DEMO-SURVIVOR-001 (trip-invite.mcp.ts): create_trip_invite_link refuses byte-for-byte in demo mode', async () => {
|
||||
const mcp = new TripInviteMcp(stub, stub, stub, stub, demoBlocked);
|
||||
const res = await mcp.createTripInviteLink({ tripId: 1, expires_in_days: null }, ctx);
|
||||
const mcp = new TripInviteMcp(stub, stub, stub, stub);
|
||||
const res = await callGatedTool(mcp, 'createTripInviteLink', { tripId: 1, expires_in_days: null }, ctx, demoBlocked);
|
||||
expect(res).toEqual(DEMO_REFUSAL);
|
||||
});
|
||||
|
||||
it('DEMO-SURVIVOR-002 (feeds.mcp.ts): enable_trip_calendar_feed refuses byte-for-byte in demo mode', async () => {
|
||||
const mcp = new FeedsMcp(stub, stub, stub, stub, demoBlocked);
|
||||
const res = await mcp.enableTripCalendarFeed({ tripId: 1 }, ctx);
|
||||
const mcp = new FeedsMcp(stub, stub, stub, stub);
|
||||
const res = await callGatedTool(mcp, 'enableTripCalendarFeed', { tripId: 1 }, ctx, demoBlocked);
|
||||
expect(res).toEqual(DEMO_REFUSAL);
|
||||
});
|
||||
|
||||
it('DEMO-SURVIVOR-003 (categories.mcp.ts): create_category refuses byte-for-byte in demo mode', async () => {
|
||||
const mcp = new CategoriesMcp(stub, stub, stub, demoBlocked);
|
||||
const res = await mcp.createCategory({ name: 'Test' }, ctx);
|
||||
const mcp = new CategoriesMcp(stub, stub, stub);
|
||||
const res = await callGatedTool(mcp, 'createCategory', { name: 'Test' }, ctx, demoBlocked);
|
||||
expect(res).toEqual(DEMO_REFUSAL);
|
||||
});
|
||||
|
||||
it('DEMO-SURVIVOR-004 (budget.mcp.ts): create_budget_item refuses byte-for-byte in demo mode', async () => {
|
||||
const mcp = new BudgetMcp(stub, stub, stub, stub, stub, stub, stub, stub, stub, demoBlocked, stub);
|
||||
const res = await mcp.createBudgetItem({ tripId: 1, name: 'Test', total_price: 10 }, ctx);
|
||||
const mcp = new BudgetMcp(stub, stub, stub, stub, stub, stub, stub, stub, stub, stub);
|
||||
const res = await callGatedTool(mcp, 'createBudgetItem', { tripId: 1, name: 'Test', total_price: 10 }, ctx, demoBlocked);
|
||||
expect(res).toEqual(DEMO_REFUSAL);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { trekMcpAccessPolicy, trekMcpValidateAccess } from '../../../src/mcp/nest-mcp-policy';
|
||||
import type { McpContext } from '../../../src/nest-mcp';
|
||||
import { createTestRegistry } from '../../../src/nest-mcp';
|
||||
import { callGatedTool } from '../../helpers/mcp-gate';
|
||||
import { PlacesMcp } from '../../../src/nest/places/places.mcp';
|
||||
import { RoadtripPlanService } from '../../../src/nest/roadtrip/roadtrip-plan.service';
|
||||
import { RoadtripPlanningMcp } from '../../../src/nest/roadtrip/roadtrip-planning.mcp';
|
||||
@@ -160,13 +161,12 @@ describe('roadtrip preferences', () => {
|
||||
expect((await s.preferences.read(10)).roadtrip_day_start).toBe('');
|
||||
const mcp = new RoadtripPreferencesMcp(
|
||||
s.preferences,
|
||||
{ isDemoUser: () => true } as never,
|
||||
{} as never,
|
||||
s.tripsRepo as never,
|
||||
{} as never,
|
||||
);
|
||||
s.preferenceDb.upsertValue.mockClear();
|
||||
await mcp.update({ tripId: 10, settings: { roadtrip_range_km: 300 } }, ctx);
|
||||
await callGatedTool(mcp, 'update', { tripId: 10, settings: { roadtrip_range_km: 300 } }, ctx, async () => true);
|
||||
expect(s.preferenceDb.upsertValue).not.toHaveBeenCalled();
|
||||
});
|
||||
it('saves the switch that starts and ends each day at the stay, through the tool too, and reads it back', async () => {
|
||||
@@ -174,7 +174,6 @@ describe('roadtrip preferences', () => {
|
||||
expect((await s.preferences.read(10)).roadtrip_hotel_bookends).toBeUndefined();
|
||||
const mcp = new RoadtripPreferencesMcp(
|
||||
s.preferences,
|
||||
{ isDemoUser: () => false } as never,
|
||||
{} as never,
|
||||
s.tripsRepo as never,
|
||||
{ hasTripPermission: () => true } as never,
|
||||
@@ -192,7 +191,6 @@ describe('roadtrip preferences', () => {
|
||||
const s = setup();
|
||||
const mcp = new RoadtripPreferencesMcp(
|
||||
s.preferences,
|
||||
{ isDemoUser: () => false } as never,
|
||||
{} as never,
|
||||
s.tripsRepo as never,
|
||||
{ hasTripPermission: () => true } as never,
|
||||
@@ -355,13 +353,11 @@ describe('browser-independent roadtrip calculation', () => {
|
||||
describe('Roadtrip MCP registration and search', () => {
|
||||
it('imports GPX through the existing service and broadcasts the imported places', async () => {
|
||||
const places = { importGpx: vi.fn(() => ({ places: [{ id: 12 }], count: 1, skipped: 0 })) };
|
||||
const auth = { isDemoUser: vi.fn(() => false) };
|
||||
const guards = { hasTripPermission: () => true, safeBroadcast: vi.fn() };
|
||||
const mcp = new PlacesMcp(
|
||||
places as never,
|
||||
{} as never,
|
||||
{ findAccessible: () => ({ id: 1, user_id: 1, currency: null }) } as never,
|
||||
auth as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
guards as never,
|
||||
@@ -384,8 +380,7 @@ describe('Roadtrip MCP registration and search', () => {
|
||||
});
|
||||
expect(guards.safeBroadcast).toHaveBeenCalledWith(1, 'place:created', { place: { id: 12 } });
|
||||
places.importGpx.mockClear();
|
||||
auth.isDemoUser.mockReturnValue(true);
|
||||
await mcp.importGpx(input, ctx);
|
||||
await callGatedTool(mcp, 'importGpx', input, ctx, async () => true);
|
||||
expect(places.importGpx).not.toHaveBeenCalled();
|
||||
});
|
||||
it('hides addon tools when disabled and separates settings reads from writes', async () => {
|
||||
@@ -393,7 +388,7 @@ describe('Roadtrip MCP registration and search', () => {
|
||||
const addons = { isAddonEnabled: vi.fn(() => true) };
|
||||
const registry = createTestRegistry(
|
||||
[
|
||||
new RoadtripPreferencesMcp(s.preferences, {} as never, addons as never, s.tripsRepo as never, {} as never),
|
||||
new RoadtripPreferencesMcp(s.preferences, addons as never, s.tripsRepo as never, {} as never),
|
||||
new RoadtripPlanningMcp(s.plans, {} as never, addons as never),
|
||||
],
|
||||
{ accessPolicy: trekMcpAccessPolicy, validateAccess: trekMcpValidateAccess },
|
||||
@@ -416,7 +411,7 @@ describe('Roadtrip MCP registration and search', () => {
|
||||
const s = setup();
|
||||
const registry = createTestRegistry(
|
||||
[
|
||||
new RoadtripPreferencesMcp(s.preferences, {} as never, { isAddonEnabled: () => true } as never, s.tripsRepo as never, {} as never),
|
||||
new RoadtripPreferencesMcp(s.preferences, { isAddonEnabled: () => true } as never, s.tripsRepo as never, {} as never),
|
||||
new RoadtripPlanningMcp(s.plans, {} as never, { isAddonEnabled: () => true } as never),
|
||||
],
|
||||
{ accessPolicy: trekMcpAccessPolicy, validateAccess: trekMcpValidateAccess },
|
||||
@@ -492,7 +487,6 @@ describe('Roadtrip MCP registration and search', () => {
|
||||
service as never,
|
||||
{ findAccessible: () => true } as never,
|
||||
guards as never,
|
||||
{ isDemoUser: () => false } as never,
|
||||
{} as never,
|
||||
);
|
||||
const input = { tripId: 1, dayId: 2, viaId: 4, lat: 48, lng: 10 };
|
||||
@@ -531,8 +525,7 @@ describe('RoadtripMcp — non-member refusal, one case per tool (Plan 3d Task 7
|
||||
};
|
||||
const tripsRepo = { findAccessible: vi.fn(async () => findAccessible) };
|
||||
const guards = { hasTripPermission: vi.fn(async () => true) };
|
||||
const auth = { isDemoUser: vi.fn(async () => false) };
|
||||
const mcp = new RoadtripMcp(service as never, tripsRepo as never, guards as never, auth as never, {} as never);
|
||||
const mcp = new RoadtripMcp(service as never, tripsRepo as never, guards as never, {} as never);
|
||||
return { mcp, service, tripsRepo };
|
||||
}
|
||||
|
||||
@@ -576,7 +569,7 @@ describe('RoadtripMcp — non-member refusal, one case per tool (Plan 3d Task 7
|
||||
describe('MCP trip preferences authorization', () => {
|
||||
it('reads shared preferences and refuses inaccessible trips', async () => {
|
||||
const s = setup();
|
||||
const tool = new RoadtripPreferencesMcp(s.preferences, { isDemoUser: () => false } as never, {} as never, s.tripsRepo as never, { hasTripPermission: () => true } as never);
|
||||
const tool = new RoadtripPreferencesMcp(s.preferences, {} as never, s.tripsRepo as never, { hasTripPermission: () => true } as never);
|
||||
expect(JSON.stringify(await tool.read({ tripId: 10 }, ctx))).toContain('100');
|
||||
s.tripsRepo.findAccessible.mockResolvedValue(false);
|
||||
expect((await tool.read({ tripId: 10 }, ctx)).isError).toBe(true);
|
||||
@@ -589,18 +582,16 @@ describe('MCP trip preferences authorization', () => {
|
||||
it('update_roadtrip_settings refuses a non-member trip on its own, without a prior read call', async () => {
|
||||
const s = setup();
|
||||
s.tripsRepo.findAccessible.mockResolvedValue(false);
|
||||
const tool = new RoadtripPreferencesMcp(s.preferences, { isDemoUser: () => false } as never, {} as never, s.tripsRepo as never, { hasTripPermission: () => true } as never);
|
||||
const tool = new RoadtripPreferencesMcp(s.preferences, {} as never, s.tripsRepo as never, { hasTripPermission: () => true } as never);
|
||||
const res = await tool.update({ tripId: 10, settings: { roadtrip_range_km: 50 } }, ctx);
|
||||
expect(res.isError).toBe(true);
|
||||
expect(JSON.stringify(res)).toContain('access denied');
|
||||
});
|
||||
it('rejects demos and readers, but permits a trip editor', async () => {
|
||||
const s = setup();
|
||||
const auth = { isDemoUser: vi.fn(() => true) };
|
||||
const guards = { hasTripPermission: vi.fn(() => false) };
|
||||
const tool = new RoadtripPreferencesMcp(s.preferences, auth as never, {} as never, s.tripsRepo as never, guards as never);
|
||||
expect((await tool.update({ tripId: 10, settings: {} }, ctx)).isError).toBe(true);
|
||||
auth.isDemoUser.mockReturnValue(false);
|
||||
const tool = new RoadtripPreferencesMcp(s.preferences, {} as never, s.tripsRepo as never, guards as never);
|
||||
expect(await callGatedTool(tool, 'update', { tripId: 10, settings: {} }, ctx, async () => true)).toMatchObject({ isError: true });
|
||||
expect((await tool.update({ tripId: 10, settings: {} }, ctx)).isError).toBe(true);
|
||||
guards.hasTripPermission.mockReturnValue(true);
|
||||
expect(JSON.stringify(await tool.update({ tripId: 10, settings: { roadtrip_range_km: 120 } }, ctx))).toContain('120');
|
||||
|
||||
@@ -6,6 +6,7 @@ import { RoadtripHazardsMcp } from '../../../src/nest/roadtrip/roadtrip-hazards.
|
||||
import { GoogleRouteMcp } from '../../../src/nest/roadtrip/google-route.mcp';
|
||||
import { DayBoundariesMcp } from '../../../src/nest/roadtrip/day-boundaries.mcp';
|
||||
import { createTestRegistry } from '../../../src/nest-mcp';
|
||||
import { callGatedTool } from '../../helpers/mcp-gate';
|
||||
import { trekMcpAccessPolicy, trekMcpValidateAccess } from '../../../src/mcp/nest-mcp-policy';
|
||||
|
||||
const ctx = { userId: 5 } as McpContext;
|
||||
@@ -25,8 +26,7 @@ describe('roadtrip read tools', () => {
|
||||
});
|
||||
it('passes reviewed Google stops and the authenticated user to the importer', async () => {
|
||||
const routes = { preview: vi.fn(async () => ({ stops: [] })), import: vi.fn(() => ({ imported: 2 })) };
|
||||
const auth = { isDemoUser: vi.fn(async () => false) };
|
||||
const tool = new GoogleRouteMcp(routes as never, auth as never, {} as never);
|
||||
const tool = new GoogleRouteMcp(routes as never, {} as never);
|
||||
await tool.preview({ url: 'https://www.google.com/maps/dir/A/B' });
|
||||
expect(routes.preview).toHaveBeenCalledWith('https://www.google.com/maps/dir/A/B');
|
||||
const input = { tripId: 10, dayId: 1, stops: [{ name: 'A', lat: 1, lng: 2 }] };
|
||||
@@ -38,12 +38,11 @@ describe('roadtrip read tools', () => {
|
||||
// The one non-admin write tool that had no gate: a demo session could write
|
||||
// thirty places and their assignments onto the shared demo trip.
|
||||
const routes = { preview: vi.fn(), import: vi.fn() };
|
||||
const auth = { isDemoUser: vi.fn(async () => true) };
|
||||
const tool = new GoogleRouteMcp(routes as never, auth as never, {} as never);
|
||||
const tool = new GoogleRouteMcp(routes as never, {} as never);
|
||||
|
||||
const res = await tool.import({ tripId: 10, dayId: 1, stops: [{ name: 'A', lat: 1, lng: 2 }] } as never, ctx);
|
||||
const res = await callGatedTool(tool, 'import', { tripId: 10, dayId: 1, stops: [{ name: 'A', lat: 1, lng: 2 }] }, ctx, async () => true);
|
||||
|
||||
expect(res.isError).toBe(true);
|
||||
expect(res).toMatchObject({ isError: true });
|
||||
expect(routes.import).not.toHaveBeenCalled();
|
||||
});
|
||||
it('answers a refusal from the service with its reason, not with the exception class name', async () => {
|
||||
@@ -57,22 +56,21 @@ describe('roadtrip read tools', () => {
|
||||
const charging = new ChargingMcp({ read: refuse('Place not found', 404) } as never, tripsRepo as never, {} as never);
|
||||
expect(text(await charging.read({ tripId: 10, placeId: 2 }, ctx))).toEqual([true, 'Place not found']);
|
||||
|
||||
const auth = { isDemoUser: vi.fn(async () => false) };
|
||||
const routes = { preview: refuse('Use a Google Maps directions link.', 400), import: refuse('Permission denied', 403) };
|
||||
const google = new GoogleRouteMcp(routes as never, auth as never, {} as never);
|
||||
const google = new GoogleRouteMcp(routes as never, {} as never);
|
||||
expect(text(await google.preview({ url: 'https://www.google.com/maps/place/A' }))).toEqual([true, 'Use a Google Maps directions link.']);
|
||||
expect(text(await google.import({ tripId: 10, dayId: 1, stops: [{ name: 'A', lat: 1, lng: 2 }] } as never, ctx))).toEqual([true, 'Permission denied']);
|
||||
|
||||
const realtime = { broadcast: vi.fn() };
|
||||
const guards = { hasTripPermission: vi.fn(() => true) };
|
||||
const boundaries = new DayBoundariesMcp({ save: refuse('Stop not found', 404) } as never, tripsRepo as never, auth as never, guards as never, realtime as never, {} as never);
|
||||
const boundaries = new DayBoundariesMcp({ save: refuse('Stop not found', 404) } as never, tripsRepo as never, guards as never, realtime as never, {} as never);
|
||||
const boundary = { day_number: 1, from_assignment_id: 11, to_assignment_id: 12, fraction: 0.4 };
|
||||
expect(text(await boundaries.save({ tripId: 10, dayNumber: 1, boundary }, ctx))).toEqual([true, 'Stop not found']);
|
||||
expect(realtime.broadcast).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('tells the assistant that a boundary over a booked night is ignored while the stay switch is on', async () => {
|
||||
const tool = new DayBoundariesMcp({} as never, {} as never, {} as never, {} as never, {} as never, { isAddonEnabled: () => true } as never);
|
||||
const tool = new DayBoundariesMcp({} as never, {} as never, {} as never, {} as never, { isAddonEnabled: () => true } as never);
|
||||
const registry = createTestRegistry([tool], { accessPolicy: trekMcpAccessPolicy, validateAccess: trekMcpValidateAccess });
|
||||
const descriptions: Record<string, string> = {};
|
||||
await registry.attach(
|
||||
@@ -86,7 +84,7 @@ describe('roadtrip read tools', () => {
|
||||
it('does not expose manual boundaries to nonmembers', async () => {
|
||||
const boundaries = { list: vi.fn(() => [{ day_number: 1 }]) };
|
||||
const tripsRepo = { findAccessible: vi.fn(async () => false) };
|
||||
const tool = new DayBoundariesMcp(boundaries as never, tripsRepo as never, {} as never, {} as never, {} as never, {} as never);
|
||||
const tool = new DayBoundariesMcp(boundaries as never, tripsRepo as never, {} as never, {} as never, {} as never);
|
||||
expect((await tool.list({ tripId: 10 }, ctx)).isError).toBe(true);
|
||||
expect(boundaries.list).not.toHaveBeenCalled();
|
||||
tripsRepo.findAccessible.mockResolvedValue(true);
|
||||
|
||||
Reference in New Issue
Block a user